UPC 2780 拓扑排序

题目描述

Once upon a time, there arose a huge discussion among the dwarves in Dwarfland. The government wanted to introduce an identity card for all inhabitants.
Most dwarves accept to be small, but they do not like to be measured. Therefore, the government allowed them to substitute the field “height” in their personal identity card with a field “relative dwarf size”. For producing the ID cards, the dwarves were being interviewed about their relative
sizes. For some reason, the government suspects that at least one of the interviewed dwarves must have lied.
Can you help find out if the provided information proves the existence of at least one lying dwarf?

输入

The input consists of:
• one line with an integer n (1 ≤ n ≤ 105 ), where n is the number of statements;
• n lines describing the relations between the dwarves. Each relation is described by:
– one line with “s 1 < s 2 ” or “s 1 > s 2 ”, telling whether dwarf s 1 is smaller or taller than dwarf s 2 . s 1 and s 2 are two different dwarf names.
A dwarf name consists of at most 20 letters from “A” to “Z” and “a” to “z”. A dwarf name does not contain spaces. The number of dwarves does not exceed 104 .

输出

Output “impossible” if the statements are not consistent, otherwise output “possible”.

样例输入

3
Dori > Balin
Balin > Kili
Dori < Kili

样例输出

impossible

题目大意:给你n个相对大小关系,然后你需要进行判断是不是存在一些矛盾的大小关系,如果存在的话就输出impossible

否则就输出possible

分析:开始以为是什么传递闭包,后来怎么也没有想到是拓扑排序,,,,因为根本就没有了解过什么是拓扑排序问题,在这里需要一个传送门(这里面介绍了拓扑排序),为什么会是拓扑排序解决这道题目的呢,因为在拓扑排序中是将所有的偏序关系转化为全序关系,在这道题目中,每两个人之间是一种偏序关系,在代码中所体现的就是一种大于关系,然后将所有的偏序关系链接成为个无环有向图,然后就可以进行拓扑排序,进而能将所有的偏序关系对的相对关系找到

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define prep(i,a,b) for(int i=a;i>=b;i--)
const int N=1e5+19;
int id;
map<string,int> mp;
vector< int > e[N];
int du[N];
int n;
char str1[N],str2[N];
void TuoPu()
{
    int tot=0;
    queue<int> q;
    rep(i,1,id)
    if(du[i]==0) q.push(i),tot++;
    while(q.size())
    {
        int u=q.front();q.pop();
        for(int i=0;i<e[u].size();i++)
        {
            int t=e[u][i];
            du[t]--;
            if(du[t]==0) q.push(t),tot++;
        }
    }
    if(tot==id)//如果能将所有的偏序关系输出一遍,那就说明不存在环的情况,因此就不存在矛盾的
//相对偏序关系
        printf("possible\n");
        else printf("impossible\n");
}
int main()
{
//    freopen("in.txt","r",stdin);
    scanf("%d",&n);
    char ch;id=0;
    rep(i,1,n){
    scanf("%s %c %s",str1,&ch,str2);
    if(mp[str1]==0) mp[str1]=++id;
    if(mp[str2]==0) mp[str2]=++id;
    int t1=mp[str1];int t2=mp[str2];
    if(ch=='>')
    e[t2].push_back(t1),du[t1]++;
    else
    e[t1].push_back(t2),du[t2]++;
//    printf("%s %c %s\n",str1,ch,str2);
    }
    TuoPu();
}

猜你喜欢

转载自blog.csdn.net/c___c18/article/details/82971099
UPC
今日推荐