UVA12174

这里写图片描述
这里写图片描述
这里写图片描述
我有话说:
这道题运用了滑动窗口这一技巧。转载了刘汝佳大神的代码。做了一下翻译。

#include<iostream>
#include<vector>
using namespace std;

const int maxn = 100000 + 5;
int s, n, x[maxn*3], cnt[maxn], ok[maxn*2];

int main() {
  int T;
  cin >> T;
  while(T--) {
    cin >> s >> n;
    //可能上一段还有歌,但是没记录,我们初始为-1
    // so we don't have to worry about negative subscript or wrapping round
    //并且从s开始储存,我们就不用担心负数的下标或者还没有结束的一段
    fill(x, x+n+2*s, -1);
    for(int i = 0; i < n; i++) cin >> x[i+s];

    int tot = 0; // 统计在滑动窗口中的不一样的数字的个数
    fill(cnt+1, cnt+s+1, 0); // cnt[i]保存数字i在窗口中出现的次数
    fill(ok, ok+n+s+1, 0);   // ok[i] = 1 当如果窗口中没有相同的数,那么一定是一个排列

    //更新ok数组
    for(int i = 0; i < n+s+1; i++) {
      if (tot == s) ok[i] = 1;              //完整的窗口
      if (i < s && tot == i) ok[i] = 1;     //在左端不完整的窗口
      if (i > n && tot == n+s-i) ok[i] = 1; //在右端不完整的窗口

      //滑动窗口后更新cnt和tot
      if (i == n+s) break; //没有更多的窗口
      if (x[i] != -1 && --cnt[x[i]]==0) tot--; //左端数字滑出窗口
      if (x[i+s] != -1 && cnt[x[i+s]]++==0) tot++; //右端数字滑进窗口
    }

    //检验每种可能的答案
    int ans = 0;
    for(int i = 0; i < s; i++) {
      int valid = 1;
      for (int j = i; j < n+s+1; j += s)
        if(!ok[j]) valid = 0;;
      if(valid) ans++;
    }
    if(ans == n+1) ans = s; //特殊情况 
    cout << ans << "\n";
  }
  return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值