码迷,mamicode.com
首页 > 其他好文 > 详细

Light Oj 1003

时间:2015-10-25 22:23:03      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

题意 : 给你m个二元关系, 问是否可以确定各个节点的先后关系;

思路: 拓扑排序, 判断是否有环;

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 131;
struct Node{
    int nxt, to;
}edge[maxn];
int Head[maxn], tot;

void AddEdge(int From, int To)
{
    edge[tot].to = To;
    edge[tot].nxt = Head[From];
    Head[From] = tot++;
}

map<string, int> StoI;
string a, b;
int Vis[maxn];/// 记录节点的访问次数

void TopSort(int n)
{
    queue<int> qu;
    int lest = n;
    for(int i = 1; i <= n; ++i)
    {
        if(!Vis[i]) qu.push(i);
    }
    while(!qu.empty())
    {
        int u = qu.front();
        qu.pop();
        --lest;
        for(int i = Head[u]; i != -1; i = edge[i].nxt)
        {
            int v = edge[i].to;
            --Vis[v];
            if(!Vis[v]) qu.push(v);
        }
    }
    if(lest) puts("No");
    else puts("Yes");
}

int main()
{
    int t;
    scanf("%d",&t);
    for(int kase = 1; kase <= t; ++kase)
    {
        int m;
        scanf("%d",&m);
        StoI.clear();
        memset(Head,-1,sizeof(Head));
        tot = 0;
        int n = 0;
        memset(Vis, 0, sizeof(Vis));
        for(int i = 1; i <= m; ++i)
        {
            cin >> a >> b;
            if(StoI.find(a) == StoI.end())
                StoI[a] = ++n;
            if(StoI.find(b) == StoI.end())
                StoI[b] = ++n;
            ++Vis[StoI[b]];
            AddEdge(StoI[a], StoI[b]);
        }
        printf("Case %d: ",kase);
        TopSort(n);
    }
    return 0;
}

 

Light Oj 1003

标签:

原文地址:http://www.cnblogs.com/aoxuets/p/4909613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!