Description
On an alien planet, every extraterrestrial is born with a number. If the sum of two numbers is a prime number, then two extraterrestrials can be friends. But every extraterrestrial can only has at most one friend. You are given all number of the extraterrestrials,
please determining the maximum number of friend pair.
Input
There are several test cases.
Each test start with positive integers N(1 ≤ N ≤ 100), which means there are N extraterrestrials on the alien planet.
The following N lines, each line contains a positive integer pi ( 2 ≤ pi ≤10^18),indicate the i-th extraterrestrial is born with pi number.
The input will finish with the end of file.
Output
For each the case, your program will output maximum number of friend pair.
Sample Input
3 2 2 3 4 2 5 3 8
Sample Output
1 2
思路:题目是朋友有多少对,是配对问题,联想到二分图,求最大匹配。条件是加起来是素数(质数),于是要求素数,数可能是10^18的,太大,直接求会超时,就要用到拉宾米勒数素数
来求,就是利用数论里面的概率来求,随机产生数。如果它(n)为质素就满足a^n-1%n==1(费马小定理、数论) a为随机产生(2=<a<=n-2) ,a^n-1%n==1直接去模可能会超时,就要用快速幂取模来写,用快速幂取模的时候s=(s*a)%n;可能会超出long
long,所以又要经行处理,优化。
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<cmath> #include<time.h> using namespace std; typedef unsigned long long LL; LL sum[101]; int a[101][101]; int n,vis[101],cn[101]; LL multi(LL a,LL b,LL n) //加法代替乘法,防止溢出 long long { LL s=0; while(b) { if(b%2==1) s=(s+a)%n; b/=2; a=(a+a)%n; } return s; } LL mod(LL a,LL b,LL n) { LL s=1; while(b) { if(b%2==1) s=multi(s,a,n);//<span style="color:#ff0000;">s=(s*a)%n;</span> b/=2; a=multi(a,a,n); } return s; } //拉宾米勒数素数 bool test(LL n) { LL a,x; int k=0,i,j; if(n<2) return 0; if(n==2) return 1;//2是唯一的偶素数,直接返回 if(n%2==0) return 0; srand((LL)time(0)); for(i=0;i<10;i++) //测试最大次数 { a=rand()%(n-2)+2; //生成一个2到n-2的数字 x=mod(a,n-1,n); //快速幂(a^n-1)%n==1 费马小定理(a为整数,a,n互质) if(x!=1)//结果不是1,不是素数 return 0; } return 1;//是素数 } int funxx(int u) { int i; for(i=1;i<=n;i++) { if(a[u][i]&&!vis[i]) { vis[i]=1; if(cn[i]==-1||funxx(cn[i])) { cn[i]=u; return 1; } } } return 0; } int hun() { int i,count=0; memset(cn,-1,sizeof(cn)); for(i=1;i<=n;i++) { memset(vis,0,sizeof(vis)); if(funxx(i)) count++; } return count; } int main() { int i,j; while(scanf("%d",&n)==1) { memset(a,0,sizeof(a)); for(i=1;i<=n;i++) scanf("%lld",&sum[i]); for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { if(test(sum[i]+sum[j])) {a[i][j]=1;a[j][i]=1;} } } printf("%d\n",hun()/2);//二分图 } return 0; }