(拓扑排序)E - Paint the Grid Again

https://vjudge.net/problem/49919/origin

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
#define lb long double
#define INF 0x3f3f3f3f
const int maxn = 505;
const ll mod = 1e9 + 7;
int n, m, t, cnt, k;
char s[maxn][maxn];
int head[maxn*2], vis[maxn*2], du[maxn*2], ans[maxn*2];
struct node{
    int to;
    int next;
}edge[maxn * maxn];
void add(int u, int v){
    edge[cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt ++;
}
void work(){
    priority_queue<int, vector<int>, greater<int> > que;
    for(int i = 1 ; i <= n + n ; ++ i){
        if(du[i] == 0){
            que.push(i);
            du[i] = -1;
        }
    }
    while(!que.empty()){
        int cur = que.top();
        que.pop();
        ans[++ k] = cur;
        for(int i = head[cur] ; i != -1 ; i = edge[i].next){
            int tt = edge[i].to;
            du[tt] --;
            if(du[tt] == 0){
                que.push(tt);
                du[tt] = -1;
            }
        }
    }
}
void init(){
    scanf("%d", &n);
    memset(head, -1, sizeof(head));
    memset(edge, 0, sizeof(edge));
    memset(du, 0, sizeof(du));
    memset(vis, 0, sizeof(vis));
    cnt = 0;
    k = 0;
    for(int i = 1 ; i <= n ; ++ i){
        scanf("%s", s[i] + 1);
    }
}
int main()
{
	scanf("%d", &t);
	while(t--){
        init();
        for(int i = 1 ; i <= n ; ++ i){
            for(int j = 1 ; j <= n ; ++ j){
                if(s[i][j] == 'X'){
                    add(j, i + n);
                    vis[i + n] = 1;
                    du[i + n] ++;
                }
                if(s[i][j] == 'O'){
                    add(i + n, j);
                    vis[j] = 1;
                    du[j] ++;
                }
            }
        }
        work();
        if(k != n + n){
            cout << "No solution" << endl;
            continue;
        }
        else{
            for(int i = 1 ; i <= k ; ++ i){
                if(!vis[ans[i]]) continue;
                if(ans[i] > n) printf("R%d%c", ans[i] - n, i == k ? '\n' : ' ');
                else printf("C%d%c", ans[i], i == k ? '\n' : ' ');
            }
        }
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zufesatoshi/article/details/89245797
今日推荐