题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1274
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 505
int N, num[MAX], tmp[MAX];
vector<int> relativePrime[MAX];
vector<int> relativeCompo[MAX];
int gcd(int x, int y)
{
if(!x) return y;
if(!y) return x;
if(x & 1){
if(y & 1) return gcd(abs(x - y), min(x, y));
else return gcd(x, y >> 1);
}
else{
if(y & 1) return gcd(x >> 1, y);
else return gcd(x >> 1, y >> 1) << 1;
}
}
int main()
{
while(~scanf("%d", &N)){
for(int i = 0; i < N; ++i){
scanf("%d", num + i);
relativePrime[i].clear();
relativeCompo[i].clear();
}
sort(num, num + N);
for(int i = 0; i < N; ++i){
for(int j = i+1; j < N; ++j){
if(gcd(num[i], num[j]) == 1) relativePrime[i].push_back(j);
else relativeCompo[i].push_back(j);
}
}
int tot = 0;
for(int i = 0; i < N; ++i){
for(int j = i+1; j < N; ++j){
if(binary_search(relativePrime[i].begin(), relativePrime[i].end(), j))
tot += set_intersection(relativePrime[i].begin(), relativePrime[i].end(),
relativePrime[j].begin(), relativePrime[j].end(),
tmp) - tmp;
else
tot += set_intersection(relativeCompo[i].begin(), relativeCompo[i].end(),
relativeCompo[j].begin(), relativeCompo[j].end(),
tmp) - tmp;
}
}
printf("%d\n", tot);
}
return 0;
}