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");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值