1.g Duizi and Shunzi

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/han_hhh/article/details/81048445

Nike likes playing cards and makes a problem of it. 

Now give you n integers,  ai(1in)ai(1≤i≤n) 

We define two identical numbers (eg:  2,22,2) a Duizi, 
and three consecutive positive integers (eg:  2,3,42,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)max(s)

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

For each test case, the first line contains one integer n( 1n1061≤n≤106). 
Then the next line contains n space-separated integers  aiai ( 1ain1≤ai≤n
OutputFor 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)


思路:要找出来顺子和对子,先找顺子或先找对子的方法都不合适,用贪心法,先找顺子,再看顺子的前两个数能不能构成对子,

//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int book[1000000];

int main(void){
    int n,i,a,maxn;
    while(~scanf("%d",&n)){
         memset(book,0,sizeof(book));//注意要在循环内
         int maxn=-1;//节省贪心模拟的时间
        for(i=1;i<=n;i++){
            scanf("%d",&a);
            book[a]++;  //统计出来每个数出现的次数,方便找对子
            maxn=max(maxn,a);
        }
        int res=0;  //注意要在循环内
        for(i=3;i<=maxn+3;i++){
            if(book[i-1]>=2){   //看顺子的第二个数有没有对子
                if(book[i-1]%2==0){
                    res+=book[i-1]/2;
                    book[i-1]=0;
                }
                else if(book[i-1]%2){
                    res+=book[i-1]/2;
                    book[i-1]=1;
                }
            }
            if(book[i-2]>=2){   //看顺子的第一个数有没有对子
                if(book[i-2]%2==0){
                    res+=book[i-2]/2;
                    book[i-2]=0;
                }
                else if(book[i-2]%2){
                    res+=book[i-2]/2;
                    book[i-2]=1;
                }
            }
            if(book[i]&&book[i-1]&&book[i-2]){   //顺子
                book[i]--;
                book[i-1]--;
                book[i-2]--;
                res++;
            }

        }
        printf("%d\n",res);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/han_hhh/article/details/81048445
G 1
G1