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.
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.
For each the case, your program will output maximum number of friend pair.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
#define N 505
typedef long long LL;
LL qpow(LL a,LL b,LL r)//快速幂
{
LL ans=1,buff=a;
while(b)
{
if(b&1)ans=(ans*buff)%r;
buff=(buff*buff)%r;
b>>=1;
}
return ans;
}
bool Miller_Rabbin(LL n,LL a)//米勒拉宾素数测试
{
LL r=0,s=n-1,j;
if(!(n%a))
return false;
while(!(s&1)){
s>>=1;
r++;
}
LL k=qpow(a,s,n);
if(k==1)
return true;
for(j=0;j<r;j++,k=k*k%n)
if(k==n-1)
return true;
return false;
}
bool IsPrime(LL n)//判断是否是素数
{
LL tab[]={2,3,5,7};
for(int i=0;i<4;i++)
{
if(n==tab[i])
return true;
if(!Miller_Rabbin(n,tab[i]))
return false;
}
return true;
}
int n;
int graph[N][N];
int linker[N];
bool vis[N];
LL a[N];
bool dfs(int u){
for(int i=1;i<=n;i++){
if(graph[u][i]&&!vis[i]){
vis[i] = true;
if(linker[i]==-1||dfs(linker[i])){
linker[i] = u;
return true;
}
}
}
return false;
}
int main()
{
while(scanf("%d",&n)!=EOF){
for(int i=1;i<=n;i++){
scanf("%lld",&a[i]);
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++) graph[i][j] = 0;
}
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(IsPrime(a[i]+a[j])){
graph[i][j] = graph[j][i] = 1;
}
}
}
int ans = 0;
memset(linker,-1,sizeof(linker));
for(int i=1;i<=n;i++){
memset(vis,false,sizeof(vis));
if(dfs(i)) ans++;
}
printf("%d\n",ans/2);
}
return 0;
}