拼图——dfs
题目链接:https://www.luogu.com.cn/problem/P3969
分析等会再补,先贴代码。
代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<queue> 6 using namespace std; 7 #define int long long 8 #define debug printf("zjyvegetable\n") 9 inline int read(){ 10 int a=0,b=1;char c=getchar(); 11 while(!isdigit(c)){if(c=='-')b=-1;c=getchar();} 12 while(isdigit(c)){a=a*10+c-'0';c=getchar();} 13 return a*b; 14 } 15 const int N=20; 16 int n,r[N],c[N],s[N][5][5],t[5][5],ans,a[5][5],pre[N],rem; 17 char cc[N]; 18 bool check(int p,int x,int y){ 19 if(x+r[p]-1>4||y+c[p]-1>4)return false; 20 for(int i=x;i<=x+r[p]-1;i++){ 21 for(int j=y;j<=y+c[p]-1;j++) 22 if(s[p][i-x+1][j-y+1]&&t[i][j])return false; 23 } 24 return true; 25 } 26 void putin(int p,int x,int y){ 27 for(int i=x;i<=x+r[p]-1;i++){ 28 for(int j=y;j<=y+c[p]-1;j++){ 29 if(s[p][i-x+1][j-y+1])t[i][j]=s[p][i-x+1][j-y+1]; 30 } 31 } 32 } 33 void takeout(int p,int x,int y){ 34 for(int i=x;i<=x+r[p]-1;i++){ 35 for(int j=y;j<=y+c[p]-1;j++) 36 if(s[p][i-x+1][j-y+1])t[i][j]=0; 37 } 38 } 39 bool jud(){ 40 for(int i=1;i<=4;i++){ 41 for(int j=1;j<=4;j++){ 42 if(!t[i][j])return false; 43 } 44 } 45 return true; 46 } 47 void dfs(int p){ 48 //printf("%lld\n",p); 49 if(pre[p]){ 50 dfs(p+1);return; 51 } 52 if(jud()){ 53 ans++; 54 if(ans==2)rem=1; 55 if(ans==1){ 56 for(int i=1;i<=4;i++){ 57 for(int j=1;j<=4;j++){ 58 a[i][j]=t[i][j]; 59 } 60 } 61 } 62 return; 63 } 64 if(p==n+1)return; 65 for(int i=1;i<=4;i++){ 66 for(int j=1;j<=4;j++){ 67 if(!check(p,i,j))continue; 68 putin(p,i,j); 69 dfs(p+1); 70 if(rem)return; 71 takeout(p,i,j); 72 } 73 } 74 dfs(p+1); 75 } 76 signed main(){ 77 while(scanf("%lld",&n)!=EOF){ 78 memset(t,0,sizeof(t)); 79 memset(pre,0,sizeof(pre)); 80 for(int i=1;i<=n;i++){ 81 r[i]=read();c[i]=read(); 82 if(r[i]>4||c[i]>4)pre[i]=1; 83 for(int j=1;j<=r[i];j++){ 84 scanf("%s",cc); 85 for(int k=1;k<=c[i];k++){ 86 s[i][j][k]=(cc[k-1]-'0'==1?i:0); 87 } 88 } 89 } 90 ans=0;rem=0; 91 dfs(1); 92 if(!ans){ 93 printf("No solution\n"); 94 } 95 else if(ans>1){ 96 printf("Yes, many!\n"); 97 } 98 else{ 99 printf("Yes, only one!\n"); 100 for(int i=1;i<=4;i++){ 101 for(int j=1;j<=4;j++) 102 printf("%lld",a[i][j]); 103 printf("\n"); 104 } 105 } 106 } 107 return 0; 108 }