题目
题目链接
题解及代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e5+7;
int f[2*N][55],a[2*N],sum[2*N],ans[2*N],pb[2*N];
int T,n,k;
#define pr(x) cout<<#x<<":"<<x<<endl
/** 题解* 由于最多跳一个环就结束,因此倍长数组就足够了。* 预处理出f[i][j]表示从i点出发,每次跳j步,最远能跳到哪里。* 预处理出sum[i]表示数组[1,i]位置中有多少个'#'。* 预处理出pb[i],表示i位置前面距离最近的'#'的位置。* ans数组为存储最终答案的数组。* 枚举出发点i,再从大到小枚举跳跃长度m,很容易得到f[i][m]得到下一个点nxt,* 如果nxt不为0,则表示可以走,为了避免多跳,我们把nxt和pb[i]+1取一个最小值,* 然后ans[i] += ceil((nxt-now)/m);* 并更新now = nxt;* 这样的话,总的时间复杂度就是O(nk)*/
int main(){freopen("jumps.in","r",stdin);cin>>T;while(T--){cin>>n>>k;memset(f,0,sizeof(f));memset(sum,0,sizeof(sum));memset(a,0,sizeof(a));memset(ans,0,sizeof(ans));for(int i = 1;i <= n;++i){char c;scanf(" %c",&c);if(c == '#') a[i] = 1;sum[i] = sum[i-1] + a[i];}for(int i = n+1;i <= 2*n;++i){a[i] = a[i-n];sum[i] = sum[i-1] + a[i];}sum[2*n+1] = sum[2*n];int pre = 0;for(int i = 1;i <= 2*n;++i){if(a[i]) pre = i;else pb[i] = pre;}for(int i = 2*n;i;--i) for(int m = k;m;--m){if(a[i]) continue;int t = m + i;if(t > 2*n){if(!a[t-2*n] && sum[2*n]-sum[i]+sum[t-2*n] <= 1)f[i][m] = 2*n+1;}else{if(!a[t] && sum[t]-sum[i] <= 1)f[i][m] = max(f[t][m],t);}}for(int i = 1;i <= n;++i){if(a[i]) continue;int it = i;for(int m = k;m;--m){int nxt = f[it][m];if(nxt) {if(nxt > pb[i+n]) nxt = pb[i+n]+1;ans[i] += (nxt-it) / m;if((nxt-it)%m) ans[i]++;it = nxt;}if(it > pb[i+n]) break;}if(it < pb[i+n]) ans[i] = -1;}for(int i = 1;i <= n;++i){if(i != 1) cout<<' ';cout<<ans[i];}cout<<endl;}return 0;
}