【CODEVS 1553】互斥的数 哈希表

题目描述 Description
有这样的一个集合,集合中的元素个数由给定的N决定,集合的元素为N个不同的正整数,一旦集合中的两个数x,y满足y = P*x,那么就认为x,y这两个数是互斥的,现在想知道给定的一个集合的最大子集满足两两之间不互斥。

输入描述 Input Description
输入有多组数据,每组第一行给定两个数N和P(1<=N<=10^5, 1<=P<=10^9)。接下来一行包含N个不同正整数ai(1<=ai<=10^9)。

输出描述 Output Description
输出一行表示最大的满足要求的子集的元素个数。

样例输入 Sample Input

4 2
1 2 3 4

样例输出 Sample Output

3

题解
先把ai排序然后我们可以直接把那个数乘于P的数标记就可以了。
没有什么好说的,其实直接把每个元素塞到两个亿的bool数组。这里写图片描述

/*
作者:WZH
题目:p1553 互斥的数
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;

long long n,p,ans,a[1000005];
bool d[200000005];

inline unsigned long long read(){
    long long x = 0, f = 1;char ch = getchar();
    while(ch < '0' || '9' < ch) { ch = getchar(); }
    while('0' <=ch &&  ch<='9') { x = x * 10 + ch - '0';ch = getchar(); }
    return x * f; 
}

inline unsigned long long hash(unsigned long long x){
    return x % 198347770;
}

inline void init(){
    n = read();p = read();
    for(int i = 1;i <= n;i++)
     a[i] = read();
    sort(a+1,a+n+1);
    for(int i = 1;i <= n;i++)
    {
        unsigned long long b = hash( a[i] );
        if(d[b]) continue;
        b = hash( p * a[i] );
        if(!d[b]) ans++,d[b] = true;
        else continue;
    }
}

int main()
{
    init();
    printf("%d",ans);
    return 0;
}

正常的哈希

/*
作者:WZH
题目:p1553 互斥的数
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;

const int MOD = 350899;

int head[400000],a[1000000],ans;
unsigned long long e = 1,n,p;

struct node{
    int v,next;
}D[1000000];

inline void add(int u,int v){
    D[e].v = v;D[e].next = head[u];head[u] = e++;
}

inline unsigned long long read(){
    long long x = 0, f = 1;char ch = getchar();
    while(ch < '0' || '9' < ch) { ch = getchar(); }
    while('0' <=ch &&  ch<='9') { x = x * 10 + ch - '0';ch = getchar(); }
    return x * f; 
}

inline bool check(unsigned long long x){
    unsigned long long h = x % MOD;

    for(int i = head[h];i;i = D[i].next)
     if(D[i].v == x) return false;
    return true;
}   

inline void hash(unsigned long long x)
{
    //bool ans = true;
    if(!check(x)) return ;
    x *= p;
    unsigned long long h = x % MOD;
    add(h,x);ans++;
}

inline void init(){
    n = read();p = read();
    for(int i = 1;i <= n;i++) a[i] = read();
    sort(a+1,a+n+1);
    for(int i = 1;i <= n;i++) hash(a[i]);
}

int main(){
    init();
    printf("%d",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值