HDU1016(簡單dfs)
阿新 • • 發佈:2018-12-24
Problem DescriptionA ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.
Inputn (0 < n < 20).
OutputThe output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input6 8
Sample OutputCase 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2
Source
RecommendJGShining | We have carefully selected several similar problems for you: 1010 1072 1175 1253 1181
Note: the number of first circle should always be 1.
Inputn (0 < n < 20).
OutputThe output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input6 8
Sample OutputCase 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2
Source
RecommendJGShining | We have carefully selected several similar problems for you:
題意:給你一個小於20的數n,讓你用1-n的數去形成一個素數環,這個素數環定義第一個數為1,任意相鄰兩個數之和為素數。
思路:簡單dfs,標記每個數用還是不用,不滿足條件時候回溯去掉標記就是了。
程式碼:
#include<bits/stdc++.h> using namespace std; const int maxn=30; int a[maxn]; bool vis[maxn]; int n; bool check(int num) { for(int i=2;i*i<=num;i++) { if(num%i==0) return false; } return true; } void dfs(int num)//填到第i個數 { if(num==n&&check(a[0]+a[n-1])) { for(int i=0;i<n;i++) { if(i!=n-1) printf("%d ",a[i]); else printf("%d\n",a[i]); } } else { for(int i=2;i<=n;i++) { if(!vis[i]&&check(i+a[num-1])) { a[num]=i; vis[i]=true; dfs(num+1); vis[i]=false;//回溯去標記 } } } } int main() { while(~scanf("%d",&n)) { memset(vis,false,sizeof(false)); memset(a,0,sizeof(a)); static int t=1; printf("Case %d:\n",t++); a[0]=1; dfs(1); printf("\n"); } return 0; }