--正文
搜索即可
PS:开始时候,把数组定成了5*5,莫名奇妙的错误,我果然是SB
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; int n,k; int gcd(int a,int b){ if (a < b) return gcd(b,a); if (b == 0) return a; else return gcd(b,a % b); } bool buhuzhi[10][10]; int arr[10]; int table[10][10] = {0}; bool used[10] = {0}; int total = 0; bool canPlace(int i,int x,int y){ if (y == 1){ if (x == 1){ return true; } else { if (buhuzhi[table[x-1][y]][i]) return false; else return true; } } else { if (x == 1){ if (buhuzhi[table[x][y-1]][i]) return false; else return true; } else { if (buhuzhi[table[x][y-1]][i] || buhuzhi[table[x-1][y]][i] ) return false; else return true; } } } void search(int x,int y){ int i; for (i=1;i<=9;i++){ if (x==1 && y==1){ // printf("NOW "); } if (!used[i] && canPlace(i,x,y)){ used[i] = true; if (x == 3){ if (y == 3){ table[x][y] = i; total ++; used[i] = false; return; } else { table[x][y] = i; search(1,y+1); } } else { table[x][y] = i; search(x+1,y); } used[i] = false; } } return; } int main(){ while (scanf("%d %d %d %d %d %d %d %d %d",&arr[1],&arr[2],&arr[3],&arr[4],&arr[5],&arr[6],&arr[7],& arr[8],&arr[9]) != EOF) { memset(buhuzhi,true,sizeof(buhuzhi)); memset(table,0,sizeof(table)); memset(used,false,sizeof(used)); int i,j; for (i=1;i<=9;i++){ for (j=1;j<=9;j++){ if (gcd(arr[i],arr[j]) == 1){ buhuzhi[i][j] = false; buhuzhi[j][i] = false; } } } search(1,1); printf("%d ",total); total = 0; } return 0; }