dfs+记忆化 对于当前状态虽然满足和差 但如果搜下去没有满足的情况也是不可以的 所以需要记忆化下
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 using namespace std; 7 char s1[1010],s2[1010]; 8 int dp[1010][1010]; 9 int sum1,sum2; 10 int p[2010],n,flag; 11 int ss1[1010],ss2[1010]; 12 int st1[1010],st2[1010]; 13 int dfs(int x,int y,int v,int o) 14 { 15 if(flag) 16 return 1; 17 if(dp[x][y]==2) 18 return 2; 19 if(o==1) 20 p[v] = 1; 21 else 22 p[v] = 2; 23 int i; 24 if(v==2*n) 25 { 26 for(i = 1; i <= 2*n ; i++) 27 printf("%d",p[i]); 28 puts(""); 29 flag = 1; 30 return 1; 31 } 32 if(y<n&&abs((ss1[x]+ss2[y+1])-(st1[x]+st2[y+1]))<=1) 33 { 34 35 if(dfs(x,y+1,v+1,2)==1) 36 return dp[x][y+1] = 1; 37 else 38 dp[x][y+1] = 2; 39 } 40 if(x<n&&abs((ss1[x+1]+ss2[y])-(st1[x+1]+st2[y]))<=1) 41 { 42 if(dfs(x+1,y,v+1,1)==1) 43 return dp[x+1][y] = 1; 44 else 45 dp[x+1][y] = 2; 46 } 47 } 48 int main() 49 { 50 int i,j,k; 51 scanf("%d",&n); 52 scanf("%s%s",s1,s2); 53 ss1[0]=0,ss2[0]=0;st1[0] = 0;st2[0]=0; 54 for(i = 0 ; i < n ; i++) 55 if(s1[i]=='1') 56 { 57 ss1[i+1] = ss1[i]+1; 58 st1[i+1] = st1[i]; 59 } 60 else 61 { 62 st1[i+1] = st1[i]+1; 63 ss1[i+1] = ss1[i]; 64 } 65 for(i =0 ; i < n ; i++) 66 if(s2[i]=='1') 67 { 68 ss2[i+1] = ss2[i]+1; 69 st2[i+1] = st2[i]; 70 } 71 else 72 { 73 st2[i+1] = st2[i]+1; 74 ss2[i+1] = ss2[i]; 75 } 76 dfs(1,0,1,1); 77 if(!flag) 78 dfs(0,1,1,2); 79 if(!flag) 80 printf("Impossible\n"); 81 return 0; 82 }