题目链接:http://codeforces.com/contest/1316/problem/D
题目意思太长了我就不多说了
想法:
走到自己位置上的一定是'X',然后同一路径上的目的地一定一样,可以从每个‘X’开始把同一目的地的都搜过去,处理出来,然后-1的情况就是所有联通的-1构成一个死循环就好了,如果最后发现有没有被处理到的,说明无法构造出来。
#include <algorithm> #include <string> #include <string.h> #include <vector> #include <map> #include <stack> #include <set> #include <queue> #include <math.h> #include <cstdio> #include <iomanip> #include <time.h> #include <bitset> #include <cmath> #include <sstream> #include <iostream> #define LL long long #define ls nod<<1 #define rs (nod<<1)+1 #define pii pair<int,int> #define mp make_pair #define pb push_back const double eps = 1e-10; const int maxn = 1e3 + 10; const LL mod = 1e9 + 7; const LL INF = 1e18; int sgn(double a){return a < -eps ? -1 : a < eps ? 0 : 1;} using namespace std; pii p[maxn][maxn]; char m[maxn][maxn]; int n; inline void dfs1(int x,int y,int xx,int yy) { if (x > 1 && p[x-1][y].first == xx && p[x-1][y].second == yy && m[x-1][y] == '#') { m[x - 1][y] = 'D'; dfs1(x-1,y,xx,yy); } if (x < n && p[x+1][y].first == xx && p[x+1][y].second == yy && m[x+1][y] == '#') { m[x + 1][y] = 'U'; dfs1(x+1,y,xx,yy); } if (y > 1 && p[x][y-1].first == xx && p[x][y-1].second == yy && m[x][y-1] == '#') { m[x][y-1] = 'R'; dfs1(x,y-1,xx,yy); } if (y < n && p[x][y+1].first == xx && p[x][y+1].second == yy && m[x][y+1] == '#') { m[x][y+1] = 'L'; dfs1(x,y+1,xx,yy); } } inline void dfs2(int x,int y) { if (x > 1 && m[x-1][y] == '?') { m[x-1][y] = 'D'; dfs2(x-1,y); } if (x < n && m[x+1][y] == '?') { m[x+1][y] = 'U'; dfs2(x+1,y); } if (y > 1 && m[x][y-1] == '?') { m[x][y-1] = 'R'; dfs2(x,y-1); } if (y < n && m[x][y+1] == '?') { m[x][y+1] = 'L'; dfs2(x,y+1); } } int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1;i <= n;i++) { for (int j = 1;j <= n;j++) m[i][j] = '#'; } for (int i = 1;i <= n;i++) { for (int j = 1;j <= n;j++) { cin >> p[i][j].first >> p[i][j].second; if (i == p[i][j].first && j == p[i][j].second) m[i][j] = 'X'; if (-1 == p[i][j].first && -1 == p[i][j].second) m[i][j] = '?'; } } for (int i = 1;i <= n;i++) { for (int j = 1;j <= n;j++) { if (m[i][j] == 'X') { dfs1(i,j,i,j); } } } for (int i = 1;i <= n;i++) { for (int j = 1;j <= n;j++) { if (m[i][j] == '?') { if (m[i+1][j] == '?' && i < n) { m[i][j] = 'D'; m[i+1][j] = 'U'; dfs2(i,j); dfs2(i+1,j); } if (m[i][j+1] == '?' && j < n) { m[i][j] = 'R'; m[i][j+1] = 'L'; dfs2(i,j); dfs2(i,j+1); } } } } for(int i = 1;i <= n;i++) for(int j = 1;j <= n;j++) { if(m[i][j]=='#'||m[i][j]=='?'){cout<<"INVALID";return 0;} } cout<<"VALID"<<endl; for(int i = 1;i <= n;i++) { for(int j = 1;j <= n;j++) cout << m[i][j]; cout<<endl; } return 0; }