Codeforces Round #245 (Div. 2) B. Balls Game
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?
There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.
For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.
Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.
The first line of input contains three integers: n (1 ≤ n ≤ 100), k (1 ≤ k ≤ 100) and x (1 ≤ x ≤ k). The next line contains n space-separated integers c1, c2, ..., cn (1 ≤ ci ≤ k). Number ci means that the i-th ball in the row has color ci.
It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color.
Print a single integer — the maximum number of balls Iahub can destroy.
6 2 2
1 1 2 2 1 1
6
首先拜大神 http://www.cnblogs.com/qscqesze/p/4428295.html
看懂了大神的解法后,写一点方便自己理解的东西 记录一下
分析:题目中的数据范围并不大,可以采用暴力枚举所有可能的情况。
#include <bits/stdc++.h> using namespace std; #define sspeed ios_base::sync_with_stdio(0);cin.tie(0) #define maxn 200001 #define mod 10007 #define eps 1e-9 const int inf=0x3f3f3f3f; int a[maxn]; int dp[maxn]; int flag[maxn]; int pre[maxn]; int Find(int x) { if(x!=pre[x]) pre[x]=Find(pre[x]); // 递归的并查集写法 return pre[x]; } int n,m,q; int dfs(int x) { int ans=0; int l=x+1; int r=Find(x)-1; ans=l-r-1; while(1) { int t=2; //能够消掉的话,两端每次l和r的一定要相同,所以初始的连续相同的数量默认为2 for(int i=l;i<=n;i++) { if(a[i]==a[i+1]) t++; else { l=i; break; } } for(int i=r;i;i--) { if(a[i]==a[i-1]) t++; else { r=i; break; } } if(a[l]!=a[r]) break; if(t<=2) //大于等于3个才能消去 break; ans=l-r+1; l++; r--; } return ans; } int main() { cin>>n>>m>>q; for(int i=1;i<=n;i++) { pre[i]=i; cin>>a[i]; if(a[i]==a[i-1]) { dp[i]=dp[i-1]+1;//后面保存数量 pre[i]=Find(i-1);//保存并查集的根 } else dp[i]=1; } int ans=0; for(int i=n;i;i--) { if(dp[i]>=2&&a[i]==q) // 保证插入点插入之后能消去,且是能插入的颜色 { ans=max(dfs(i),ans); i=Find(i); } } cout<<ans<<endl; }