您的位置:首页 > 其它

【CODEVS 1553】互斥的数 哈希表

2016-05-06 13:09 351 查看
题目描述 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: