Dwarves (有向图判环)

时间:2023-07-27 21:39:26

Dwarves

时间限制: 1 Sec  内存限制: 64 MB
提交: 14  解决: 4
[提交][状态][讨论版]

题目描述

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
【分析】有向图判环问题。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <queue>
#include <vector>
#define inf 0x7fffffff
#define met(a,b) memset(a,b,sizeof a)
typedef long long ll;
using namespace std;
const int N = ;
const int M = ;
int n,m,cnt=;
int vis[N];
vector<int>vec[N];
bool flag=false;
map<string,int>p;
void dfs(int x) {
vis[x]=-;
if(flag)return;
for(int i=; i<vec[x].size(); i++) {
int v=vec[x][i];
if(vis[v]==-) {
flag=true;
return;
}
else if(!vis[v])dfs(v);
}
vis[x]=;
}
int main() {
string a,b,c;
scanf("%d\n",&n);
while(n--) {
cin>>a>>b>>c;
if(!p[a])p[a]=++cnt;
if(!p[c])p[c]=++cnt;
if(b[]=='>')vec[p[a]].push_back(p[c]);
else vec[p[c]].push_back(p[a]);
}
for(int i=; i<=cnt; i++) {
if(flag)break;
if(!vis[i])dfs(i);
}
if(flag)puts("impossible");
else puts("possible");
return ;
}