Dwarves(拓撲排序+字串使用map量化表示)
題目描述
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
題意: 給定 字串代表的名字 ,例如 s1,s2 如果輸入為s1 > s2 代表s1比s2高,給定n個這樣的大小關係比較式,
如果都滿足邏輯關係,就輸出possible,否則就輸出impossible
分析:對於所給定的關係中,可以構成有向圖,對這個有向圖進行拓撲排序,如果成環就代表又不符合邏輯的關係式
如果完成了拓撲排序,就是代表無邏輯衝突,然後就是名字的量化表示
分析:
#include<iostream>
#include<stdio.h>
#include<vector>
#include<string.h>
#include<map>
using namespace std;
#define maxn 100010
int n,c[maxn],h[maxn];
vector<int> e[maxn];
char bb[2];
string aa,cc;
map<string,int> flag;
int countt=1;
int findd(string x)
{
if(flag[x]!=0)
return flag[x];
flag[x]=countt++;
return flag[x];
}
bool dfs(int u){
c[u]=-1;
for(int i=0;i<e[u].size();i++){
int v=e[u][i];
if(c[v]<0)
return false;
else if(!c[v]&&!dfs(v))
return false;
}
c[u]=1;
return true;
}
bool toposort(){
for(int u=1;u<=countt;u++)
if(!c[u])
if(!dfs(u))
return false;
return true;
}
int main(){
int u,v;
scanf("%d",&n);
flag.clear();
memset(h,-1,sizeof(h));
for(int i=0;i<n;i++){
cin >> aa >> bb >>cc;
u=findd(aa);
v=findd(cc);
if(bb[0]=='<')
e[u].push_back(v);
else
e[v].push_back(u);
}
if(toposort())
printf("possible\n");
else
printf("impossible\n");
}