题解【洛谷P3662】[USACO17FEB]Why Did the Cow Cross the Road II S

本题是练习前缀和的好题!
我们可以枚举前端点,确定一个长度为k的区间,然后利用前缀和统计区间内损坏的灯的数量,最后取最小值即可。
AC代码:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 inline int read()//快速读入 
 6 {
 7     int f=1,x=0;
 8     char c=getchar();
 9 
10     while(c<'0' || c>'9')
11     {
12         if(c=='-')f=-1;
13         c=getchar();
14     }
15 
16     while(c>='0' && c<='9')
17     {
18         x=x*10+c-'0';
19         c=getchar();
20     }
21 
22     return f*x;
23 }
24 
25 int n,k,b,v[100005],s[100005],sum=2000000007;
26 
27 int main()
28 {
29     n=read(),k=read(),b=read();//输入 
30 
31     for(register int i=1; i<=b; i++)
32     {
33         int x=read();
34 
35         v[x]=1;//记录损坏的灯的编号 
36     }
37 
38     for(register int i=1; i<=n; i++)
39     {
40         s[i]=s[i]+s[i-1]+v[i];//计算从1~i损坏的灯的个数 
41     }
42 
43     for(register int i=1; i<=n-k+1; i++)//枚举区间 
44     {
45         if((s[i+k-1]-s[i-1])<sum)//如果这个区间损坏的灯数比当前最小值小 
46         {
47             sum=s[i+k-1]-s[i-1];//就更新最小值 
48         }
49     }
50 
51     printf("%d",sum);//输出最小值 
52 
53     return 0;//结束 
54 }

 P.S. 这是本人在洛谷上AC的第400题。

原文地址:https://www.cnblogs.com/xsl19/p/10450769.html