洛谷 P1564 膜拜
题目传送门
解题思路:
把甲的崇拜者设为-1,乙的崇拜者设为1,求前缀和,f[i]表示到第i个人所需的最少机房数.
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 6 using namespace std; 7 8 int n,m,a[2501],j,y,f[2501],sum[2501]; 9 10 int main() { 11 memset(f,0x3f3f3f,sizeof(f)); 12 scanf("%d%d",&n,&m); 13 for(int i = 1;i <= n; i++) { 14 scanf("%d",&a[i]); 15 if(a[i] == 2) sum[i] = sum[i-1] - 1; 16 else sum[i] = sum[i-1] + 1; 17 } 18 f[0] = 0; 19 for(int i = 1;i <= n; i++) 20 for(int j = 1;j <= i; j++) 21 if(abs(sum[i] - sum[j-1]) == i - j + 1 || abs(sum[i] - sum[j-1]) <= m) 22 //这一段全相同或两种人数相差不超过m 23 f[i] = min(f[i],f[j-1] + 1); 24 printf("%d",f[n]); 25 return 0; 26 }