[DFS]《奧賽一本通》 素數環
阿新 • • 發佈:2019-02-13
原題:在書上,大致就是:將從1到20這20個整數圍成一個圓環,若其中任意2個相鄰的數字相加,結果均為素數,那麼這個環就成為素數環。
時間:2014.1.27
型別:回溯,dfs
原始碼:
#include<iostream> using namespace std; int a[20]; bool b[20]; bool is_prime(int n) { if(n==2||n==3||n==5||n==7||n==11||n==13||n==17||n==19||n==23||n==29||n==31||n==37||n==41) { return true; } else return false; } void print() { for(int i=1;i<=20;i++) { cout<<a[i]<<" "; } cout<<"\n"; } void search(int n) { if(n==21&&is_prime(a[1]+a[20])) { print(); return; } for(int i=1;i<=20;i++) { if(b[i]) continue; if(n==1||is_prime(i+a[n-1])) { b[i]=true; a[n]=i; search(n+1); b[i]=false; } } } int main() { search(1); system("pause"); return 0; }
最終狀態:AC
總結:打的第一道回溯題目,關鍵就是回溯這個思想