描述 Description | |||
给你一个长度为n的数字串,数字串里会包含1-m这些数字。如果连续的一段数字子串包含了1-m这些数字,则称这个数字字串为NUM串。你的任务是求出长度最短的NUM串是什么,只需要输出这个长度即可。 1<=n,m<=200000 | |||
输入格式 Input Format | |||
第一行给定n和m。 第二行n个数,表示数字串,数字间用空格隔开。 | |||
输出格式 Output Format | |||
如果存在NUM串则输出最短NUM串长度,否则输出“NO”。 | |||
样例输入 Sample Input [复制数据] | |||
样例输出 Sample Output [复制数据] | |||
时间限制 Time Limitation | |||
各个测试点1s |
好像是高一的时候考过的题。
贪心策略一般不太好想,因为要保证没有漏洞不太容易,另外很容易被引导向其他的错误的方法。
这道题很容易。遇到一个数字就把它的最近位置标记为现在的位置,当所有的数字都出现了之后,就一直更新答案。
#include <cstdio>
bool used[200010];
long near[200010];
int main()
{
long n,m;
scanf("%ld%ld",&n,&m);
long c = 0;
long ans = 0x7f7f7f7f;
for (long i=1;i<n+1;i++)
{
long num;
scanf("%ld",&num);
if (!used[num])
{
used[num] = true;
c ++;
}
near[num] = i;
if (c == m)
{
long farest = i;
for(long j=1;j<m+1;j++)
if (near[j] < farest)
farest = near[j];
ans = ans > i-farest+1 ? i-farest+1:ans;
}
}
if (ans < 0x7f7f7f7f)
printf("%ld",ans);
else
printf("NO");
return 0;
}