POSSPEW - Editorial

PROBLEM LINK:

Contest Division 1
Contest Division 2
Contest Division 3
Practice

Setter: Soumyadeep Pal
Tester: Samarth Gupta
Editorialist: Taranpreet Singh

DIFFICULTY

Easy

PREREQUISITES

None

PROBLEM

Given a circular array A of length N with non-negative integers and an integer K, the following process is repeated every second

  • For each i such that A_i \gt 0, elements adjacent to i-th element get incremented by 1.

Find the sum of the array A after K seconds.

QUICK EXPLANATION

  • Once an element becomes non-zero, it stays non-zero.
  • Each non-zero element contributes 2 to the sum every second. If A_p becomes non-zero at time T, then it contributes 2*max(0, K-T) to the overall sum.
  • For each element, we can calculate the first time it becomes non-zero by finding the nearest non-zero values in the given circular array.
  • Only edge case is when all elements are 0. The sum remains 0 in this case.

EXPLANATION

Instead of trying to maintain the actual array, let’s only keep relevant information. We only care about the sum of the array after K seconds, so let’s try computing that directly. The sum of the final array would be the sum of the initial array plus the increments from operations.

In each operation, for each non-zero A_i, one is added to adjacent elements on both sides, which increases the sum of the array by 2. This happens for each non-zero value in the array.

So, if before an operation, there are x non-zero values in an array, the sum is increased by 2*x by that operation.

Also, we can see that once an element becomes non-zero, it only increases, and thus, keeps contributing to the overall sum.

Minimum time an element becomes non-zero

Now, the problem reduces to computing T_i, where T_i is the minimum time when A_i becomes non-zero. For non-zero elements in initial array, T_i = 0.

Let’s assume A_p is the nearest non-zero value for A_i. Then it takes |p-i| seconds, as, after each second, the element adjacent to the nearest non-zero element becomes positive, reducing |p-i| by 1.

Hence, for each element, find the position of the nearest non-zero element in both directions, and take the minimum distance to both elements.

It can be easily done via ordered sets in O(N*log(N)).

But we can use DP as well, using recurrence T_{i+1} = min(T_{i+1}, T_i +1) (looping i from 1 to N twice to handle circular array) and T_{i-1} = min(T_{i-1}, T_i +1) (looping i from N to 1 twice to handle circular array).

Hence, this way we are able to compute T_i, so we can compute sum of final array as \displaystyle \sum_{i = 1}^N A_i + 2*max(0, K - T_i)

Bonus

Solve this problem for non-circular array A.

TIME COMPLEXITY

The time complexity is O(N) or O(N*log(N)) depending upon implementation.

SOLUTIONS

Setter's Solution
#include<bits/stdc++.h>
using namespace std;
#define int long long

void solve() {
    int n; cin >> n;
    assert(n >= 3);
    int k; cin >> k;
    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];
    int sum = accumulate(a.begin(), a.end(), 0LL);
    if (sum == 0) {
	    cout << 0 << '\n';
	    return;
    }
    vector<int> time(n);
    int L = -n;
    for (int i = n - 1; i >= 0; i--) {
	    if (a[i] > 0) {
		    L = -(n - i);
		    break;
	    }
    }
    for (int i = 0; i < n; i++) {
	    if (a[i] > 0) {
		    L = i;
	    }
	    time[i] = i - L;
    }
    int R = 2 * n;
    for (int i = 0; i < n; i++) {
	    if (a[i] > 0) {
		    R = n + i;
		    break;
	    }
    }
    for (int i = n - 1; i >= 0; i--) {
	    if (a[i] > 0) {
		    R = i;
	    }
	    time[i] = min(time[i], R - i);
    }
    int ans = sum;
    for (int i = 0; i < n; i++) ans += 2 * max(0LL, k - time[i]);
    cout << ans << '\n';
}

signed main() {
    ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int t; cin >> t;
    while (t--) {
	    solve();
    }
    return 0;
}
Tester's Solution
#include <bits/stdc++.h>
using namespace std;

long long readInt(long long l, long long r, char endd) {
    long long x=0;
    int cnt=0;
    int fi=-1;
    bool is_neg=false;
    while(true) {
        char g=getchar();
        if(g=='-') {
            assert(fi==-1);
            is_neg=true;
            continue;
        }
        if('0'<=g&&g<='9') {
            x*=10;
            x+=g-'0';
            if(cnt==0) {
                fi=g-'0';
            }
            cnt++;
            assert(fi!=0 || cnt==1);
            assert(fi!=0 || is_neg==false);
 
            assert(!(cnt>19 || ( cnt==19 && fi>1) ));
        } else if(g==endd) {
            if(is_neg) {
                x=-x;
            }
            assert(l<=x&&x<=r);
            return x;
        } else {
            assert(false);
        }
    }
}
string readString(int l, int r, char endd) {
    string ret="";
    int cnt=0;
    while(true) {
        char g=getchar();
        assert(g!=-1);
        if(g==endd) {
            break;
        }
        cnt++;
        ret+=g;
    }
    assert(l<=cnt&&cnt<=r);
    return ret;
}
long long readIntSp(long long l, long long r) {
    return readInt(l,r,' ');
}
long long readIntLn(long long l, long long r) {
    return readInt(l,r,'\n');
}
string readStringLn(int l, int r) {
    return readString(l,r,'\n');
}
string readStringSp(int l, int r) {
    return readString(l,r,' ');
}
 
void readEOF(){
    assert(getchar()==EOF);
}

int main() {
    // your code goes here
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int t;
    t = readIntLn(1, 10000);
    int sum = 0;
    while(t--){
        int n, k;
        n = readIntSp(3, 100000);
        //cerr << "done" << endl;
        sum += n;
        assert(sum <= 1e6);
        k = readIntLn(0, 1000000000);
        vector<int> vec(n);
        queue<int> q;
        vector<int> vis_time(n, 1e9);
        for(int i = 0; i < n ; i++){
            if(i == n - 1)
                vec[i] = readIntLn(0, 1000000);
            else
                vec[i] = readIntSp(0, 1000000);
            if(vec[i] > 0)
                q.push(i), vis_time[i] = 0;
        }
        while(!q.empty()){
            int idx = q.front();
            q.pop();
            if(vis_time[(idx+1)%n] == 1e9)
                q.push((idx+1)%n), vis_time[(idx+1)%n] = vis_time[idx] + 1;
            if(vis_time[(idx-1+n)%n] == 1e9)
                q.push((idx-1+n)%n), vis_time[(idx-1+n)%n] = vis_time[idx] + 1;
        }
        long long ans = 0;
        for(int i = 0; i < n ; i++){
            ans += (vec[i] + max(k - vis_time[(i+1)%n], 0) + max(k - vis_time[(i-1+n)%n], 0));
        }
        cout << ans << '\n';
    }
    readEOF();
    return 0;
}
Editorialist's Solution
import java.util.*;
import java.io.*;
class POSSPEW{
    //SOLUTION BEGIN
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int N = ni(), K = ni();
        int[] A = new int[N];
        for(int i = 0; i< N; i++)A[i] = ni();
        int[] minTime = new int[N];
        int INF = 3*N;
        Arrays.fill(minTime, INF);
        boolean allzero = true;
        for(int i = 0; i< N; i++)if(A[i] > 0){
            minTime[i] = 0;
            allzero = false;
        }
        for(int i = 0; i< 2*N; i++)
            minTime[(i+1)%N] = Math.min(minTime[(i+1)%N], minTime[i%N]+1);
        for(int i = 2*N-1; i>= 0; i--)
            minTime[(i+N-1)%N] = Math.min(minTime[(i+N-1)%N], minTime[i%N]+1);
        
        if(allzero){
            pn(0);
            return;
        }
        long sum = 0;
        for(int x:A)sum += x;
        for(int i = 0; i< N; i++)sum += 2*Math.max(0, K-minTime[i]);
        pn(sum);
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    static boolean multipleTC = true;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        new POSSPEW().run();
    }
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{   
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }  
            return str;
        }
    }
}

Feel free to share your approach. Suggestions are welcomed as always. :slight_smile:

11 Likes

what’s wrong with my solution https://www.codechef.com/viewsolution/51174003

1 Like

https://www.codechef.com/viewsolution/51174003

My Approach :
First make all elements Non - Zero (if at least one element is zero) . Then, if the sum of array elements is s and each element of array is non-zero. Answer will become s + 2nk where k is number of operations and n is number of elements.
P.S. This approach should have given TLE on the basis of the contraints given in the question. Maybe Test Cases were not proper.

#include<bits/stdc++.h> 
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define ll long long 
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
const unsigned int M = 1000000007;
using namespace std;
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> tree;
bool checkzeroes(vector<ll> data){
    for(auto elem : data){
        if(elem == 0)
        return true;
    }
    return false;
}
void solve()
{
    int t;
    ll n, k;
    cin>>t;
    while(t--){
        cin>>n>>k;
        bool check_non_zero = false;
        vector<ll> data(n);
        for(auto &elem : data)
        cin>>elem;

        for(auto elem : data){
            if(elem != 0)
            {
                check_non_zero = true;
                break;
            }
        }
        if(!check_non_zero){
            cout<<"0\n";
            continue;
        }

        while(checkzeroes(data) and k > 0){
            vector<bool> pts(n,false);
            for(int i = 0; i < n; i ++)
            if(data[i] != 0)
            pts[i] = true;
            
            for(int i = 0; i < n ; i++ ){
                if(pts[i]){
                    if(i == 0)
                    data[n-1] ++ , data[i+1] ++ ;
                    else if(i == n-1)
                    data[0] ++, data[i-1] ++ ;
                    else
                     data[i-1] ++ , data[i+1] ++ ;
                }
            }
            k--;
        }
        ll sum = accumulate(data.begin(),data.end(),0);
        sum += (n*k*2);
        
        cout<<sum<<"\n";

    }

}
int main()
{
ios_base::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
solve();
return 0;
}
6 Likes

the simple and easy-to-understand solution,
solved using multisource BFS concept, queue with visited arrays.

https://www.codechef.com/viewsolution/51125036

10 Likes

I have solved it using prefix and suffix concept in O(n) . I calculated total zeroes before and after the element , from this we can simple know the time when it will become positive .
https://www.codechef.com/viewsolution/51126119

9 Likes

Isn’t this solution https://www.codechef.com/viewsolution/51122029 have time complexity O(n^2)?

Assume a case of n=10^5, k=10^9 and only one element in the array is non-zero, in this case, shouldn’t the above solution result in TLE??

@taran_1407 @samarth2017 @soumyadeep_21

7 Likes

Exactly that’s what I have thought this method is O(n^2)? Otherwise question will be just implementation. This should result in TLE

2 Likes

No this wont give TLE. It will take very few iterations to make all elements of array to non zero

1 Like

Test it locally, when N=1e4, the code is running for 5e7 iterations, so it should definitely TLE for full constraints.

1 Like

I think only 2 numbers (according to my test case) which are zero get converted into non-zeros in each iteration. It approximately takes n/2 iterations (according to my test case) to make all elements of the array non-zero.

2 Likes

the sum you have to use long long I guess, int will cause overflow

1 Like

Yes atmost n/2 operations is possible. This should give TLE.

2 Likes

I also did this but I am getting wrong answer. Could you tell what is difference between my and your code .
My submission : CodeChef: Practical coding for everyone

1 Like

Hi!
https://www.codechef.com/viewsolution/51164974
I have done the same approach. Can you please tell me why it is showing TLE in Task 1?

1 Like

Great Editorial ! Thanks

1 Like

Can anyone please explain why this solution got SIGSEGV and where it is going wrong.

https://www.codechef.com/viewsolution/51174797

1 Like

Testcase
1
3 2
0 0 0

1 Like

Your solution may overflow. arr[i] <= 10e6. Use Long Long array

1 Like

Sorry Bro ! I found that my solution should also have given TLE. Maybe the test cases were not proper. Here is a Sample Code. For 10e3, it takes 500 iterations. It means complexity goes to O(n^2) and it should give TLE.

n = 10**3
a = [0 for i in range(n)]
a[n//2] = 1

counter = 0 
while 0 in a : 
    check = [False for i in range(len(a))]
    for i in range(len(a)):
        if a[i] != 0:
            check[i] = True
    for i in range(len(a)):
        if check[i]:
            if i == 0:
                a[len(a)-1] += 1
                a[i + 1] += 1
            elif i == len(a)-1: 
                a[len(a)-1] += 1
                a[i-1] += 1
            else:
                a[i-1]+= 1
                a[i+1] += 1

    counter += 1

print(counter)
1 Like