URAL 1501. Sense of Beauty(记忆化搜索)

时间:2021-09-17 06:58:57

题目链接

本来暴力写个TLE了,加上记忆化就A了。

 #include <cstring>
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int pre[][];
int flag[][];
char s1[],s2[];
int sum1[],sum2[];
int n;
int que[];
int dfs(int x,int y)
{
if(x == n&&y == n)
return ;
if(flag[x][y] == )
return ;
else if(flag[x][y] == )
return ;
if(x+ <= n)
{
if(abs(sum1[x+] + sum2[y]-(x++y-sum1[x+]-sum2[y])) <= )
{
pre[x+][y] = ;
if(dfs(x+,y))
return flag[x+][y] = ;
else
{
flag[x+][y] = ;
pre[x+][y] = ;
}
}
}
if(y+ <= n)
{
if(abs(sum1[x] + sum2[y+]-(x+y+-sum1[x]-sum2[y+])) <= )
{
pre[x][y+] = ;
if(dfs(x,y+))
return flag[x][y+] = ;
else
{
flag[x][y+] = ;
pre[x][y+] = ;
}
}
}
return ;
}
int main()
{
int i,x,y;
scanf("%d%s%s",&n,s1,s2);
if(s1[] == '')
sum1[] = ;
if(s2[] == '')
sum2[] = ;
for(i = ;i <= n;i ++)
{
if(s1[i-] == '')
sum1[i] = sum1[i-] + ;
else
sum1[i] = sum1[i-];
if(s2[i-] == '')
sum2[i] = sum2[i-] + ;
else
sum2[i] = sum2[i-];
}
if(dfs(,))
{
x = n;
y = n;
int m = ;
while(x != ||y != )
{
que[m++] = pre[x][y];
if(pre[x][y] == )
x --;
else
y --;
}
for(i = m-;i >= ;i --)
printf("%d",que[i]);
printf("\n");
}
else
printf("Impossible\n");
return ;
}