【CODEVS 1553】互斥的数 哈希表

来源:互联网 发布:海报自动设计软件 编辑:程序博客网 时间:2024/06/06 03:37

题目描述 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 21 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;}
1 0