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.