B. Drazil and Tiles
题目连接:
http://codeforces.com/contest/516/problem/B
Description
Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:
"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."
But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".
Drazil found that the constraints for this task may be much larger than for the original task!
Can you solve this new problem?
Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2000).
The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.
Output
If there is no solution or the solution is not unique, you should print the string "Not unique".
Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example.
Sample Input
3 3
...
.*.
...
Sample Output
Not unique
Hint
题意
给你一个nm的矩阵,你们的.位置是可以放1/*2的骨牌的,现在问你是否存在唯一解,如果有的话,输出。
否则输出Not unique
题解
有点拓扑排序的味道
找到唯一能够覆盖的,然后盖上去,找找到下一个度数为1的。
然后搞一搞就好了。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2005;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int n,m,d[maxn][maxn];
char s[maxn][maxn],ans[maxn][maxn];
queue<int>Qx,Qy;
bool in(int x,int y){
if(x>=1&&x<=n&&y>=1&&y<=m)return true;
return false;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%s",s[i]+1);
for(int j=1;j<=m;j++)
ans[i][j]=s[i][j];
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(s[i][j]=='.'){
for(int k=0;k<4;k++){
int nx=i+dx[k];
int ny=j+dy[k];
if(in(nx,ny)&&s[nx][ny]=='.')
d[i][j]++;
}
}
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(d[i][j]==1)
Qx.push(i),Qy.push(j);
while(!Qx.empty()){
int x=Qx.front();
int y=Qy.front();
Qx.pop(),Qy.pop();
for(int k=0;k<4;k++){
int nx=x+dx[k];
int ny=y+dy[k];
if(in(nx,ny)&&ans[nx][ny]=='.'){
if(k==0)ans[x][y]='^',ans[nx][ny]='v';
if(k==1)ans[x][y]='v',ans[nx][ny]='^';
if(k==2)ans[x][y]='<',ans[nx][ny]='>';
if(k==3)ans[x][y]='>',ans[nx][ny]='<';
d[x][y]=d[nx][ny]=0;
for(int p=0;p<4;p++){
int nnx=nx+dx[p];
int nny=ny+dy[p];
if(in(nnx,nny)&&ans[nnx][nny]=='.')
d[nnx][nny]--;
if(d[nnx][nny]==1)
Qx.push(nnx),Qy.push(nny);
}
d[x][y]=d[nx][ny]=0;
}
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(ans[i][j]=='.'){
cout<<"Not unique"<<endl;
return 0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
printf("%c",ans[i][j]);
printf("
");
}
}