EOJ-2912 放书
没什么营养的DFS,主要是为了好玩第一次尝试写文件离线打表(其实没意义)
输出的总文件长度大概20几k..
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<map> 2 #include<queue> 3 #include<cmath> 4 #include<cctype> 5 #include<cstdio> 6 #include<string> 7 #include<cstdlib> 8 #include<cstring> 9 #include<iostream> 10 #include<algorithm> 11 using namespace std; 12 int v[11],a[11]; 13 FILE* T=fopen("out.txt","w"); 14 void dfs(int depth,int n){ 15 if(depth==n+1){ 16 for(int j=1;j<=n;j++) 17 fprintf(T,"%d",a[j]); 18 fprintf(T,"\\n"); 19 return ; 20 } 21 for(int i=1;i<=n;i++) 22 if(v[i]==0){ 23 v[i]=1; 24 if(i!=depth){ 25 a[depth]=i; 26 dfs(depth+1,n); 27 } 28 v[i]=0; 29 } 30 } 31 int main(){ 32 for(int i=2;i<8;i++){ 33 memset(v,0,sizeof(v)); 34 fprintf(T,"if(n==%d)printf(\"",i); 35 dfs(1,i); 36 fprintf(T,"\");\n"); 37 } 38 return 0; 39 }
普通dfs,AC:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<map> 2 #include<queue> 3 #include<cmath> 4 #include<cctype> 5 #include<cstdio> 6 #include<string> 7 #include<cstdlib> 8 #include<cstring> 9 #include<iostream> 10 #include<algorithm> 11 using namespace std; 12 int n,cnt; 13 int v[11],a[11]; 14 void dfs(int depth){ 15 if(depth==n+1){ 16 if(n<8){ 17 for(int j=1;j<=n;j++) 18 printf("%d",a[j]); 19 printf("\n"); 20 }else cnt++; 21 return ; 22 } 23 for(int i=1;i<=n;i++) 24 if(v[i]==0){ 25 v[i]=1; 26 if(i!=depth){ 27 if(n<8)a[depth]=i; 28 dfs(depth+1); 29 } 30 v[i]=0; 31 } 32 } 33 int main(){ 34 int t; 35 cin>>t; 36 while(t--){ 37 cin>>n; 38 memset(v,0,sizeof(v)); 39 cnt=0; 40 dfs(1); 41 if(n>=8) cout<<cnt<<endl; 42 } 43 return 0; 44 }