您的位置:首页 > 其它

hdu 5072 容斥

2015-06-06 12:35 435 查看

Coprime

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)

Total Submission(s): 1123    Accepted Submission(s): 453


[align=left]Problem Description[/align]
There are n people standing in a line. Each of them has a unique id number.

Now the Ragnarok is coming. We should choose 3 people to defend the evil. As a group, the 3 people should be able to communicate. They are able to communicate if and only if their id numbers are pairwise coprime or pairwise not coprime. In other words, if their
id numbers are a, b, c, then they can communicate if and only if [(a, b) = (b, c) = (a, c) = 1] or [(a, b) ≠ 1 and (a, c) ≠ 1 and (b, c) ≠ 1], where (x, y) denotes the greatest common divisor of x and y.

We want to know how many 3-people-groups can be chosen from the n people.
 

[align=left]Input[/align]
The first line contains an integer T (T ≤ 5), denoting the number of the test cases.

For each test case, the first line contains an integer n(3 ≤ n ≤ 105), denoting the number of people. The next line contains n distinct integers a1, a2, . . . , an(1 ≤ ai ≤ 105) separated by
a single space, where ai stands for the id number of the i-th person.
 

[align=left]Output[/align]
For each test case, output the answer in a line.
 

[align=left]Sample Input[/align]

1
5
1 3 9 10 2

 

[align=left]Sample Output[/align]

4

 

2014鞍山赛区C题

给了n个不同的数,要求有多少个三元组,两两互质 或者 两两不互质

模型请参考 《算法竞赛入门经典 训练指南》  p105 问题6

 直接对每个数,求有多少个和它互质的,多少个和它不互质的, 相乘累加。。  就是反面的2倍了。

至于如何求有多少个互质的,直接质因数分解,然后容斥就可以了。

#include <bits/stdc++.h>
#define For(i,a,b) for(int (i)=(a);(i) < (b);(i)++)
#define rof(i,a,b) for(int (i)=(a);(i) > (b);(i)--)
#define IOS ios::sync_with_stdio(false)
#define lson l,m,rt <<1
#define rson m+1,r,rt<<1|1
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int maxn = 1e5+10;
const int INF =0x3f3f3f3f;
vector<int>p[maxn];
int a[maxn*3];
int num[maxn];
int mul[maxn];
void update(int x)
{
for(int mask=0;mask<(1<<p[x].size());mask++){
if(!mask) mul[mask]=1;
else{
mul[mask]=mul[mask&(mask-1)]*p[x][__builtin_ctz(mask)];
}
num[mul[mask]]++;
}
}
int getpair(int x)
{
int ret=0;
for(int mask=0;mask<(1<<p[x].size());mask++){
if(!mask) mul[mask]=1;
else{
mul[mask]=mul[mask&(mask-1)]*p[x][__builtin_ctz(mask)];
}
if(__builtin_popcount(mask)&1)
ret-=num[mul[mask]];
else ret+=num[mul[mask]];
}
if(x==1) ret--;
return ret;
}
int main()
{
For(i,2,maxn)
if(p[i].empty())
for(int j=i;j<maxn;j+=i)
p[j].push_back(i);
int T,n;
cin>>T;
while(T--){
cin>>n;
mem(num,0);
For(i,0,n)
{
cin>>a[i];
update(a[i]);
}
ll ans=0;
For(i,0,n){
int t=getpair(a[i]);
ans+=(ll)t*(n-t-1);
}
ll tot=(ll)n*(n-1)*(n-2)/6;
cout<<tot-ans/2<<endl;
}
return 0;
}


[align=left][/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: