顺子(51Nod-2510)

题目

小b有n张牌。 

现在她想把牌分组,使得每组都是长度为W的顺子,即由连续W个数组成。

请问小b能做到吗?

输入

第一行输入一个数n,表示手牌张数;
第二行输入n个非负整数,表示每张牌的数字,以空格隔开;
第三行输入一个数,表示每组大小W;
其中1≤W≤n≤10000,任意牌的数字hand[i]满足0≤hand[i]≤10^9

输出

可以分组,输出“true”;
不能分组,输出“false”。

输入样例

9
1 2 3 6 2 3 4 7 8
3

输出样例

true

思路:桶排的基本应用,需要注意的是,由于 a[i] 最大可能到 1E9,数组开不了那么大,因此需要使用 map 来进行桶排

源程序

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 4000000+5;
const int dx[] = {0,0,-1,1,-1,-1,1,1};
const int dy[] = {-1,1,0,0,-1,1,-1,1};
using namespace std;

LL a[N];
//int bucket[N];
map<LL,int> bucket;
int main() {
    int n,w;
    scanf("%d",&n);
    for(int i=1; i<=n; i++) {
        scanf("%lld",&a[i]);
        bucket[a[i]]++;
    }
    scanf("%d",&w);

    if(w==1)
        printf("true\n");
    else if(n%w!=0)
        printf("false\n");
    else{
        sort(a+1,a+n+1);

        int num=w;
        bool flag=false;
        for(int i=1; i<=n; i++) {
            if(bucket[a[i]]==0)
                continue;
            for(int j=0; j<w; j++) {
                if(bucket[a[i]+j]!=0)
                    bucket[a[i]+j]--;
                else {
                    flag=true;
                    break;
                }
            }
            if(flag)
                break;
        }
        if(flag)
            printf("false\n");
        else
            printf("true\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值