D
被样例的构造误导到了奇怪的地方,以为“无限走”就要不断经过起始格子,实际上可以走到某个“核心”处然后在核心处绕圈圈。
int n; int x[1005][1005]; int y[1005][1005]; int vis[1005][1005]; int deg[1005][1005]; char ans[1005][1005]; int dx[4] = {0, 0, 1, -1}; int dy[4] = {-1, 1, 0, 0}; char dans[4] = {'R', 'L', 'U', 'D'}; char adans[4] = {'L', 'R', 'D', 'U'}; queue<pii> Q; void bfs1(int ux, int uy) { vis[ux][uy] = 1; ans[ux][uy] = 'X'; Q.push({ux, uy}); while(!Q.empty()) { int vx = Q.front().first; int vy = Q.front().second; Q.pop(); for(int i = 0; i < 4; ++i) { int tx = vx + dx[i]; int ty = vy + dy[i]; if(1 <= tx && tx <= n && 1 <= ty && ty <= n) { if(x[tx][ty] == ux && y[tx][ty] == uy && vis[tx][ty] == 0) { vis[tx][ty] = 1; ans[tx][ty] = dans[i]; Q.push({tx, ty}); } } } } } void bfs2(int ux, int uy) { vis[ux][uy] = 1; Q.push({ux, uy}); for(int i = 0; i < 4; ++i) { int tx = ux + dx[i]; int ty = uy + dy[i]; if(1 <= tx && tx <= n && 1 <= ty && ty <= n) { if(x[tx][ty] == -1 && y[tx][ty] == -1 && vis[tx][ty] == 0) { vis[tx][ty] = 1; ans[ux][uy] = adans[i]; ans[tx][ty] = dans[i]; Q.push({tx, ty}); break; } } } if(Q.size() == 1) { puts("INVALID"); exit(0); } while(!Q.empty()) { int vx = Q.front().first; int vy = Q.front().second; Q.pop(); for(int i = 0; i < 4; ++i) { int tx = vx + dx[i]; int ty = vy + dy[i]; if(1 <= tx && tx <= n && 1 <= ty && ty <= n) { if(x[tx][ty] == -1 && y[tx][ty] == -1 && vis[tx][ty] == 0) { vis[tx][ty] = 1; ans[tx][ty] = dans[i]; Q.push({tx, ty}); } } } } } void test_case() { scanf("%d", &n); for(int i = 1; i <= n; ++i) { for(int j = 1; j <= n; ++j) { scanf("%d%d", &x[i][j], &y[i][j]); ans[i][j] = '.'; } } for(int i = 1; i <= n; ++i) { for(int j = 1; j <= n; ++j) { if(vis[i][j] == 0 && x[i][j] == i && y[i][j] == j) bfs1(i, j); } } for(int i = 1; i <= n; ++i) { for(int j = 1; j <= n; ++j) { if(vis[i][j] == 0 && x[i][j] == -1 && y[i][j] == -1) bfs2(i, j); } } for(int i = 1; i <= n; ++i) { for(int j = 1; j <= n; ++j) { if(vis[i][j] == 0) { puts("INVALID"); exit(0); } } } puts("VALID"); for(int i = 1; i <= n; ++i) { for(int j = 1; j <= n; ++j) putchar(ans[i][j]); putchar('\n'); } }
来源:https://www.cnblogs.com/KisekiPurin2019/p/12418168.html