
2289B Problem from Chebarkul
题目描述
You are given an array of integers and an integer .
Find the number of integers such that in all subsequences of the array of length , the same number is located at the -th position.
A sequence is a subsequence of a sequence if can be obtained from by the deletion of several (possibly, zero or all) elements from arbitrary positions.
输入格式
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The first line of each test case contains two integers and ().
The second line of each test case contains integers ().
It is guaranteed that the sum of over all test cases does not exceed .
输出格式
For each test case, output one integer — the number of positions at which the same number is located in all subsequences of length of the array .
说明/提示
题面里的样例没有拿到,此处从略。
思路
先把「子序列的第 个元素」翻译成「原数组的哪个位置」。
长度为 的子序列,是从 个数里删掉 个。要让第 个元素落在原数组的 位:
- 它前面必须留下 个,所以 ;
- 它后面必须留下 个,所以 ,即 。
合起来,第 个位置能对应到的原下标恰好是整段
而且这段里的每个下标都能取到(删掉 前面若干个、后面若干个即可)。
于是问题变成:这段区间 里的数全部相同,第 个位置才被固定;只要有一个不同,就能通过不同的删法让第 位取到不同的值。
区间长度是 。 从 到 ,这 个区间正好是「一个长度 的窗口从左往右滑 次」——起点 的右端点是 ,不越界。
所以:滑窗,数每个窗口里有多少种不同的数,等于 1 就记一次。
怎么维护「不同数的个数」
用值桶 ct[v] 记窗口里 出现了几次,dis 记桶里非零的个数。窗口右移一格:
- 删掉左端那个数,它的计数减到 0 就让
dis--; - 加进右端那个数,它原本计数是 0 就让
dis++。
只有计数跨过 0 的时候 dis 才变,这样每次滑动是 。
复杂度 每组。
正确代码
#include<bits/stdc++.h>using namespace std;#define int long longint T,n,k;int a[200060];int ct[200060];int ans;signed main(){ cin>>T; while(T--){ ans=0; cin>>n>>k; for(int i=1;i<=n;i++) ct[i]=0; for(int i=1;i<=n;i++) cin>>a[i]; int len=n-k+1; int dis=0; for(int i=1;i<=len;i++){ if(ct[a[i]]==0) dis++; ct[a[i]]++; } if(dis==1) ans++; for(int i=2;i<=k;i++){//i->i+len-1; ct[a[i-1]]--; if(ct[a[i-1]]==0) dis--; if(ct[a[i+len-1]]==0) dis++; ct[a[i+len-1]]++; if(dis==1) ans++; } cout<<ans<<endl; } return 0;}我想了什么
这题最容易走偏的一步是「子序列第 位能取到哪些下标」。 想清楚是「一个连续的区间 」之后,题目就变成了滑窗;如果一直想着枚举子序列或者用组合数,就出不来了。
为什么窗口长度是 而不是 ? 因为窗口是「这一位可能来自的原下标范围」,长度由「能删多少」决定( 个可删,加上自己就是 ),跟 不是一回事。我一开始也差点按 去算。
清桶用的是 for(int i=1;i<=n;i++) ct[i]=0; 而不是 memset。 每组只清 个位置,比清满 便宜——多组数据、 又都小的时候差别明显。
但这里藏着一条没写下来的假设:桶是按数值 ct[a[i]] 索引的,却按下标范围 去清。这要求 ,题面里正好保证了(),代码本身却没把这条表达出来。
i+len-1 的上界正好卡在 。 循环 i<=k 而 ,一个不多一个不少,所以不用额外判越界。
ans 是全局的,每组开头 ans=0。 跟清桶是同一个习惯:全局数组省内存,代价是每次自己重置。
#define int long long 之后 ct 每个元素 8 字节。 计数最大也就是 ,用 int 就够,这里多花了一倍内存。
复杂度
每组时间 :建第一个窗口 ,滑动 ,相加就是 。空间 。
小结
核心只有一句话:第 个位置能来自的下标是连续区间 ,所以「固定」等价于「这段全相同」。
剩下的就是定长滑窗 + 值桶维护不同数个数,标准写法。
分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
最后更新于 ,距今已过 8 天
部分内容可能已过时