Duizi and Shunzi (贪心)

Nike likes playing cards and makes a problem of it.

Now give you n integers, ai(1in)

We define two identical numbers (eg: 2,2) a Duizi,
and three consecutive positive integers (eg: 2,3,4) a Shunzi.

Now you want to use these integers to form Shunzi and Duizi as many as possible.

Let s be the total number of the Shunzi and the Duizi you formed.

Try to calculate max(s)
.

Each number can be used only once.
Input The input contains several test cases.

For each test case, the first line contains one integer n( 1n106).
Then the next line contains n space-separated integers ai ( 1ain)
Output For each test case, output the answer in a line.
Sample Input
7
1 2 3 4 5 6 7
9
1 1 1 2 2 2 3 3 3
6
2 2 3 3 3 3 
6
1 2 3 3 4 5
Sample Output
2
4
3
2


        
  
Hint
Case 1(1,2,3)(4,5,6)

Case 2(1,2,3)(1,1)(2,2)(3,3)

Case 3(2,2)(3,3)(3,3)

Case 4(1,2,3)(3,4,5)

题意:给出一个长度为n的序列,要求求出对子数与顺子数总数最大值,2个相同的数字称为对子,3个相邻的数字称为顺子(如:2,3,4)

思路:贪心,因为组成对子的扑克数量比组成顺子的扑克数量大,要想总数最大,就尽可能的组成对子

#include<cstdio>
#include<cstring>
using namespace std;
const int N = 1e6+5;
int vis[N];
int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		memset(vis,0,sizeof(vis));
		for(int i=1;i<=n;i++){
			int x;
			scanf("%d",&x);
			vis[x]++;
		}
		int ans=0;
		for(int i=1;i<=n;i++){
			if(vis[i]>=2){
				ans+=vis[i]/2;
				vis[i]%=2;
			}
			if(vis[i]&&vis[i+1]%2==1&&vis[i+2]){
				ans++;
				vis[i]--;
				vis[i+1]--;
				vis[i+2]--;
			}
			  
		}
		printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/islittlehappy/article/details/80590400