HDU 6188 - Duizi and Shunzi ( 贪心 )

题意

给出n张牌, 每张牌编号为ai, 有两种组成方式, 一种叫”对子”, 也就是两张牌牌面相同, 另一种叫”顺子”, 也就是三张牌牌面连续, 每张牌最多只能用一次, 求最多能组成多少组

思路

贪心
贪心方法 : 枚举每张牌面的数量, 先尽可能多的组成对子, 那么至多只能剩下一张, 若该牌面只剩一张, 就要想办法将其与后面的牌组成顺子, 首先要保证s[i+1] 和 s[i+2] 至少有牌, 其次要保证 s[i+1] 个数必须是奇数, 关于 s[i+2] 的奇偶性不予讨论, ( 因为要保证s[i+1]也要尽可能多组成对子, 可是 s[i+2] 拿与不拿是等效的 )

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
int s[maxn];

int main(){
    int n, a;
    while( ~scanf("%d",&n) ){
        memset(s, 0, sizeof(s));
        int mmax = -1;
        for( int i = 0; i < n; i++ ){
            scanf("%d",&a);
            mmax = max(mmax, a);
            s[a]++;
        }
        int ans = 0;
        for( int i = 1; i <= mmax; i++ ){
            if( s[i] >= 2 ){
                ans += s[i] / 2;
                s[i] %= 2;
            }
            if( s[i] == 1 && s[i+1] % 2 != 0 && s[i+2] ){
                ans++;
                s[i]--, s[i+1]--, s[i+2]--;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}
posted @ 2018-04-15 18:59  JinxiSui  阅读(147)  评论(0编辑  收藏  举报