http://acm.hdu.edu.cn/showproblem.php?pid=1016
题意:输入一个数,给出符合要求的素数环。
经典的dfs遍历。
1 #include<iostream> 2 #include<cstring> 3 #include<cmath> 4 using namespace std; 5 6 int visited[25]; 7 int pos[25]; 8 int n, kase = 0; 9 10 int judge(int x) //判断是否为素数 11 { 12 for (int i = 2; i <= sqrt(x); i++) 13 { 14 if (x%i == 0) return 0; 15 } 16 return 1; 17 } 18 19 void dfs(int x,int count) 20 { 21 pos[count] = x; 22 visited[x] = 1; 23 if (count == n && judge(x + pos[1])) 24 { 25 for (int i = 1; i < n; i++) 26 cout << pos[i] << " "; 27 cout << pos[n]; 28 cout << endl; 29 } 30 for (int k = 2; k <= n; k++) 31 { 32 if (!visited[k] && judge(k+pos[count])) 33 { 34 dfs(k, count+1); 35 visited[k] = 0; 36 } 37 } 38 } 39 40 int main() 41 { 42 while (cin >> n && n) 43 { 44 memset(visited, 0, sizeof(visited)); 45 memset(pos, 0, sizeof(pos)); 46 kase++; 47 cout << "Case " << kase << ":" << endl; 48 dfs(1,1); 49 cout << endl; 50 } 51 return 0; 52 }