dp[x][y][z] 表示s[0......x] ,t[0.......y] 之间0,1的个数之差为z-1(z=0,1,2)
记忆化搜索就行了
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<queue>
#include<map>
using namespace std;
#define FOR(i,a,b) for(int (i)=(a);(i)<=(b);(i)++)
#define DOR(i,a,b) for(int (i)=(a);(i)>=(b);(i)--)
#define nMax 1010
#define bug puts("Fuck");
#define LL long long
#define pb push_back
int n;
char s[2][nMax];
int dp[nMax][nMax][3],fa[nMax][nMax][3];
int dfs(int x,int y,int z){
//printf("%d %d %d\n",x,y,z);
if(dp[x][y][z]!=-1) return dp[x][y][z];
dp[x][y][z] = fa[x][y][z] = 0;
if(x-1>=0) {
int sum = 0;
if(s[0][x]=='0') sum = -1;
else sum = 1;
if(z-sum>=0 && z-sum<=2) dp[x][y][z] |= dfs(x-1,y,z-sum);
if(dp[x][y][z]) {
fa[x][y][z] = -1;
return dp[x][y][z];
}
}
if(y-1>=0) {
int sum ;
if(s[1][y]=='0')sum=-1;
else sum = 1;
if(z-sum>=0 && z-sum<=2) dp[x][y][z] |= dfs(x,y-1,z-sum);
if(dp[x][y][z]) fa[x][y][z] = 1;
}
return dp[x][y][z];
}
void out(int x,int y,int z){
//printf("%d %d %d\n",x,y,z);
if(x==0 && y==0) return ;
if(fa[x][y][z] < 0) {
z -= (s[0][x]=='1'?1:-1);
x-=1;
out(x,y,z);
printf("%d",1);
}else if(fa[x][y][z]>0){
z -= (s[1][y]=='1'?1:-1);
y-=1;
out(x,y,z);
printf("%d",2);
}
return ;
}
void sovle(){
memset(dp,-1,sizeof(dp));
dp[0][0][1]=1;
int ok = 0;
FOR(z,0,2) {
if(ok|=dfs(n,n,z)){
// printf("%d\n",z);
out(n,n,z);printf("\n");
break;
}
}
if(!ok) printf("Impossible\n");
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
#endif
while(~scanf("%d",&n)){
FOR(i,0,1) scanf("%s",s[i]+1);
sovle();
}
return 0;
}
![](https://img-my.csdn.net/uploads/201304/23/1366731983_4935.png)