tip:
first from left to right, then from right to left, keep the smaller of the spending when during that, and save every position's possible way
code:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 1e6+5;
const int inf = 0x3f3f3f3f;
int r, l, c[maxn], g[maxn];
int n, arr[maxn], pos[maxn], vis[maxn];
void input() {
scanf("%d", &n);
memset(vis, -1, sizeof(vis));
int cnt=0, mv=0;
for(int i=0; i<n; i++) {
scanf("%d", &arr[i]);
if(arr[i] == 0) {
pos[cnt++] = i;//for cal the distance between the start and final
c[mv]++;//for save every position's possible way
mv++;//lenghth
}
else {
mv += arr[i];
int k = min(cnt, arr[i]);//possible removing length
for(int j=1; j<=k; j++) {// removing length
int u = mv - j;//current position
vis[u] = i-pos[cnt-j]-j+1;//i-pos[cur-j] is the distance between the start and final and cult the length of remove
g[u] += vis[u];
c[u] ++;
}
}
}
cnt = 0;
reverse(arr, arr+n);
for(int i=0; i<n; i++) {
if(arr[i] == 0) {//done before
pos[cnt++] = i;
mv--;
}
else {
mv -= arr[i];
int k = min(cnt, arr[i]);
for(int j=0; j<k; j++) {
int u = mv + j;//current position
if(vis[u]==-1) {
vis[u] = i-pos[cnt-j-1] - j;
g[u] += vis[u];
c[u]++;
}
else {
int tmp = i-pos[cnt-j-1]-j;
g[u] += min(0, tmp-vis[u]);
}
}
}
}
}
void deal() {
int ans = inf, cnt = 0;
for(int i=0; i<l; i++) {
if(c[i] == r) {
if(g[i] < ans) {
ans = g[i];
cnt = 0;
}
if(g[i] == ans) vis[cnt++] = i;
}
}
printf("%d\n", ans);
for(int i=0; i<cnt; i++) printf("%d ", vis[i]);
printf("\n");
}
int main() {
int kase;
scanf("%d", &kase);
while(kase--) {
scanf("%d%d", &r, &l);
memset(c, 0, sizeof(c));
memset(g, 0, sizeof(g));
for(int i=0; i<r; i++) {
input();
}
deal();
}
return 0;
}