Duizi and Shunzi HDU - 6188 (思维+贪心)

本文介绍了一个基于贪心算法解决的卡片组合问题。该问题要求玩家使用整数卡片尽可能多地形成顺子和对子,每张卡片只能使用一次。文章详细解释了贪心策略,并提供了实现代码。

Duizi and Shunzi

HDU - 6188

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)



        
 

贪心思路:优先组成对子,如果当前i只要一个,i+1是奇数,i+2也存在,就组成顺子

从小跑到大。例如1,1,2,3。跑到1的时候有对子,这时候优先要对子。不然你牺牲对子去换顺子,也就是一比一,根本不会赚。例如1,2,2,3。这个思路和前面一样,如果2,2拆开当顺子不会赚。例如1,2,3,3这时候跑1。发现1还有一张,2的个数是奇数,这时候就可以选择顺子1,2,3,因为3是最后面的。拆开它,一比一,不亏。它可能会和后面的5,6形成顺子,这时候就赚了。所以贪心的大体思路是这样,详细的看代码。

code:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 1e6+10;
int num;
int vis[maxn];
int main(){
    int n;
    while(scanf("%d",&n) != EOF){
        memset(vis,0,sizeof(vis));
        for(int i = 0; i < n; i++){
            scanf("%d",&num);
            vis[num]++;
        }
        int ans = 0;
        for(int i = 1; i < maxn; i++){
            if(vis[i] >= 2){//第一个数如果有对子,那么优先对子
                ans += vis[i] / 2;
                vis[i] %= 2;
            }
            if(i <= 999998){
                if(vis[i+2] && vis[i] == 1 && vis[i+1] % 2){//如果第一个数是1,第二个数是奇数个,那么组成顺子
                    ans++;
                    vis[i]--;
                    vis[i+1]--;
                    vis[i+2]--;
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值