1501. Sense of Beauty
Time limit: 0.5 second
Memory limit: 64 MB
Memory limit: 64 MB
The owner of a casino for New Russians has a very refined sense of beauty. For example, after a game there remain two piles with the same number of cards on the table, and the owner likes the cards to be arranged into two piles according to the color: one pile with red cards and the other with black cards. Of course, this is done not by the owner himself, but by a croupier. The owner just likes to watch the process. The croupier takes a card from the top of one of the initial piles and puts it into one of the new piles; this is repeated until all the cards from the initial piles are transferred. The owner doesn't like it if one of the resulting piles grows faster than the other. At each moment the resulting piles must not differ in size by more than one card; a bigger difference would contradict the owner's sense of beauty. Help the croupier to arrange the cards according to the tastes of his owner.
Input
The first line of the input contains the number
N of cards in each of the piles (4 ≤
N ≤ 1000). Each of the next two lines contains
N digits 0 or 1 describing the piles: 1 denotes a red-suit card and 0 denotes a black-suit card. The cards in a pile are described from the top to the bottom. There are in total
N red and
N black cards in the two piles.
Output
Output a line containing 2
N digits 1 or 2, which describes the process of transferring the cards. Each number shows the number of the pile from which a card is taken. If it is impossible to perform this task according to the given rules, output "Impossible".
Samples
input | output |
---|---|
4 0011 0110 | 22121112 |
4 1100 1100 | Impossible |
题目大意:
一开始有两堆牌,各n张。
0表示红色,1表示黑色。
现在需要把这两堆牌重新分,使得红黑各一堆。
但分牌的时候只能从原先两堆牌从前到后依次取,并且在分牌的过程中,红黑两堆牌的差的绝对值一定要<=1。
如果无法完成输出Impossible
题解:
一开始没有读懂意思,最后在neko13大牛的帮助下才理解,,,,
题目不难,但是neko13提供了一种好方法,从后往前记忆化搜索,从末态搜初态,这样可以输出的时候少写个回溯,,,
因为拿走黑白牌数差不超过1,所以这次拿了黑, 下次就要拿白,这次拿了白, 下次就要拿黑,所以每次拿两张,两张看做一个整体
dp[i][j]对应a[1..i]被拿光,b[1..j]被拿光的真假
代码如下:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
using namespace std;
int n;
bool dp[1002][1002];
char a[1002], b[1002];
bool dfs(int i,int j)
{
if(!i&&!j)
return true;
if(dp[i][j]==false)
{
dp[i][j]=true;
}
else
{
return false;
}
if(i>=2&&a[i]!=a[i-1]&&dfs(i-2,j))
{
printf("11");
return true;
}
if(j>=2&&b[j]!=b[j-1]&&dfs(i,j-2))
{
printf("22");
return true;
}
if(i&&j&&a[i]!=b[j]&&dfs(i-1,j-1))
{
printf("12");
return true;
}
return false;
}
int main()
{
scanf("%d%s%s", &n,a+1,b+1);
if(!dfs(n,n))
printf("Impossible\n");
return 0;
}