标签:素数 input process put main graphic ane series --
1 #include<cstdio> 2 #include<string.h> 3 #include<cmath> 4 #include<algorithm> 5 using namespace std; 6 int n,cnt; 7 int prime(int x){//判断素数 8 if(n==1) 9 return 0; 10 if(n==2) 11 return 1; 12 for(int i=2;i<=floor(sqrt(x));i++){ 13 if(x%i==0) 14 return 0; 15 } 16 return 1; 17 } 18 19 int vis[30],a[30]; 20 void dfs(int x){ 21 if(x==n&&prime(a[n]+1)){//如果正好轮了n个数,且相邻之和都为素数,输出 22 for(int i=1;i<=n-1;i++){ 23 printf("%d ",a[i]); 24 } 25 printf("%d\n",a[n]); 26 } 27 for(int i=2;i<=n;i++){ //从2-n一个一个试下去 28 a[cnt]=i; 29 if(prime(a[cnt]+a[cnt-1])&&vis[i]==0){ //然后是素数且没有用过就继续 30 vis[i]=1;//标记用过 31 cnt++; 32 dfs(x+1); 33 vis[i]=0;//回溯 34 cnt--; 35 } 36 } 37 } 38 39 int main(){ 40 int q=1; 41 while(scanf("%d",&n)!=EOF){ 42 printf("Case %d:\n",q++); 43 memset(vis,0,sizeof(vis)); 44 memset(a,0,sizeof(0)); 45 vis[1]=1; 46 a[1]=1; 47 cnt=2; 48 dfs(1); 49 printf("\n"); 50 } 51 return 0; 52 }
HDU 1016 Prime Ring Problem(dfs)
标签:素数 input process put main graphic ane series --
原文地址:https://www.cnblogs.com/cake-lover-77/p/10197652.html