hdu 3908 Triple

Triple

Time Limit: 5000/3000 MS (Java/Others)    Memory Limit: 125536/65536 K (Java/Others)
Total Submission(s): 205    Accepted Submission(s): 84


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 < 105) 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
 

Source
 
題解:這題比賽時卡了很久,後然才發現要用逆向思維,總數減去不滿足的情況。
 
#include <iostream>
using namespace std;
int a[805];
int n,ans;
int gcd(int x,int y)
{
	if(y==0)
		return x;
	return gcd(y,x%y);
}
int main()
{
	int i,j,T,x,y,s;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		for(i=1;i<=n;i++)
			scanf("%d",&a[i]);
		ans=n*(n-1)*(n-2)/6;
		s=0;
		for(i=1;i<=n;i++)
		{
			x=y=0;
			for(j=1;j<=n;j++)
			{
				if(i==j)
					continue;
				if(gcd(a[i],a[j])==1)
					x++;
				else
					y++;
			}
			s+=x*y;
		}
		printf("%d\n",ans-s/2);
	}
	return 0;
}



發佈了28 篇原創文章 · 獲贊 8 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章