CodeForces-1131D (gourmet choice)(并查集+拓扑排序)

题目:http://codeforces.com/contest/1131/problem/D

分析:对于‘=’ 我们进行缩点,利用并查集。

对于‘<’ , 我们建立a[i] 到b[j] 的边,

相反,对于‘>’ ,我们建立b[j] 到 a[i] 的边。

对于每一个点进行编号,最后进行拓扑排序,同一个集合的点标号相同。

有环无解,无环有解。

 

#include <bits/stdc++.h>

using namespace std;

const int maxn = 2005;
int f[maxn],de[maxn],ans[maxn],vis[maxn];
char s[maxn][maxn];
vector<int>V[maxn];
queue<int>Q;

int Find(int x)
{
    return x == f[x] ? x : f[x] = Find(f[x]);
}

int main()
{
    int n,m;
    while(cin >> n >> m)
    {
        for(int i = 1;i <= n + m;i ++)f[i] = i;
        for(int i = 1;i <= n;i ++)
        {
            cin >> (s[i] + 1);
            for(int j = 1;j <= m;j ++)
            {
                if(s[i][j] == '=')
                    f[Find(n + j)] = Find(i);
            }
        }
        for(int i = 1;i <= n;i++)
            for(int j = 1;j <= m;j ++)
        {
            if(s[i][j] == '>') ++ de[Find(i)],V[Find(n + j)].push_back(Find(i));
            if(s[i][j] == '<') ++ de[Find(n + j)],V[Find(i)].push_back(Find(n + j));
        }
        for(int i = 1;i <= n + m;i ++)
        {
            if(!de[Find(i)] && !vis[Find(i)])
            {
                vis[Find(i)] = 1;
                Q.push(Find(i));
                ans[Find(i)] = 1;
            }
        }
        while(!Q.empty())
        {
            int u = Find(Q.front());
            Q.pop();
            for(int i = 0;i < V[u].size();i ++)
            {
                int v = V[u][i];
                if(-- de[Find(v)] == 0 && ! vis[Find(v)])
                {
                    vis[Find(v)] = 1;
                    ans[Find(v)] = ans[u] + 1;
                    Q.push(Find(v));
                }
            }
        }
        for(int i = 1;i <= n + m;i ++)
        {
            if(de[i])
            {
                return !printf("No\n");
            }
        }
        printf("Yes\n");
        for(int i = 1;i <= n + m;i ++)
        {
            if(i == n)
                printf("%d\n",ans[Find(i)]);
            else printf("%d ",ans[Find(i)]);
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值