Triple
Time Limit: 5000/3000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others)
Problem Description
Given many different integers, find out the number of triples (a, b, c) which satisfy a, b, c are co-primed each other or are not co-primed each other. In a triple, (a, b, c) and (b, a, c) are considered as same triple.
Input
The first line contains a single integer T (T <= 15), indicating the number of test cases.
In each case, the first line contains one integer n (3 <= n <= 800), second line contains n different integers d (2 <= d < 10 5) separated with space.
In each case, the first line contains one integer n (3 <= n <= 800), second line contains n different integers d (2 <= d < 10 5) separated with space.
Output
For each test case, output an integer in one line, indicating the number of triples.
Sample Input
1 6 2 3 5 7 11 13
Sample Output
20
这是昨天比赛的题,但是我没有做出来,今天就又做了一下。
题意:给出n个数,从这n个数中任选3个数,使得它们两两互素或者两两不互素。问一共有多少种选法。
分析:直接求解不是很好求,但是可以间接求解,即可以先求出不满足条件的有多少种选法,然后用总数减去不满足条件的,剩下的就是满足条件的。总数就是从n个数里面选三个,用组合公式可以算出;不满足条件的情况就是三个数中有一个数与其他两个数中的一个互素,和另外一个不互素。所以对于每一个数,可以从与它互素的数中选一个,再从与它不互素的数中选一个,再加上这个数本身,让这三个数组合在一起就是不满足条件的。设n个数中与第i个数互素的有s[i]个,则与第i个数不互素的有n-1-s[i]个,那么对于第i个数,不满足条件的选法就有s[i] * (n-1-s[i])中。对n个数都这样求一遍,最后求得的总和就是总的不满足条件的个数的2倍,因为对于每个每两个数,前一个数和后一个数互素,则后一个数也和前一个数互素,这就相当于每个数参与了两次计算,最后除以2即可。
#include<stdio.h>
#include<string.h>
const int N = 1000;
int gcd(int a, int b)
{
while(b != 0)
{
int r = a % b;
a = b;
b = r;
}
return a;
}
int main()
{
int t, n, i, j;
int s[N], a[N];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i = 0; i < n; i++)
scanf("%d",&a[i]);
memset(s, 0, sizeof(s));
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
{
if(gcd(a[i], a[j]) == 1)
s[i]++; //记录和a[i]互素的个数
}
int sum = 0;
for(i = 0; i < n; i++)
sum += s[i] * (n-1-s[i]); //不满足条件的2倍
int ans = n * (n-1) * (n-2) / 6;
printf("%d\n",ans - sum/2);
}
return 0;
}