60分求助
  • 板块P1347 排序
  • 楼主_Aurore_
  • 当前回复0
  • 已保存回复0
  • 发布时间2022/7/25 15:39
  • 上次更新2023/10/27 18:29:50
查看原帖
60分求助
593595
_Aurore_楼主2022/7/25 15:39
#include<bits/stdc++.h>
#define MAXM 610
#define ll long long
#define MAXN 30
using namespace std;
inline ll read(){ll x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}return x*f;}
inline void write(ll x){if(x==0){putchar('0');return;}if(x<0){putchar('-');x=-x;}char s[22];ll tmp=x,cnt=0;while(tmp>0){s[cnt++]=tmp%10+'0';tmp/=10;}while(cnt>0) putchar(s[--cnt]);} 
ll n,m,in[MAXN],dad[MAXN],sum; 
ll IN[MAXN],ans[MAXN];
ll INPUT[MAXN];
vector<int> edge[MAXN];
queue<int> q;
bool topo(){
//	for(int i=1;i<=n;i++){
//		for(int j=0;j<edge[i].size();j++){
//			cout<<i<<" "<<edge[i][j]<<"     ";
//		}
//		cout<<endl;
//	}
	bool flag1,flag2;//用来判断无法判断关系的情况(在任意时刻出现多个入度为0的点)
	flag1=false,flag2=false; 
	sum=0;
	while(!q.empty()) q.pop();
	memset(ans,0,sizeof(ans));
	for(int i=1;i<=n;i++){
		IN[i]=in[i];
		if(!IN[i]&&INPUT[i]){
			if(!flag1) flag1=true;
			else flag2=true;
			q.push(i);
			sum++;
			ans[sum]=i;
		}
	}
	while(!q.empty()){
		ll x=q.front();
		q.pop();
		flag1=false;
		for(int i=0;i<edge[x].size();i++){
			IN[edge[x][i]]--;
			if(!IN[edge[x][i]]){
				if(!flag1) flag1=true;
				else flag2=true;
				q.push(edge[x][i]);
				sum++;
			    ans[sum]=edge[x][i];
			}
		}
	}
//	for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
//	cout<<endl;
	if(flag2) return false;
	if(sum==n&&!flag2) return true;
}
ll find(ll x){
	if(dad[x]==x) return x;
	return dad[x]=find(dad[x]); 
}
int main(){
	n=read(),m=read();
	for(int i=1;i<=n;i++) dad[i]=i;
	for(int i=1;i<=m;i++){
		string input;
		cin>>input;
		ll f=(ll)input[0]-'A'+1,e=(ll)input[2]-'A'+1;
	    edge[f].push_back(e);
	    in[e]++;
	    INPUT[f]=1,INPUT[e]=1;
	    if(find(e)==f){
	    	cout<<"Inconsistency found after "<<i<<" relations.";
	    	return 0;
		}
		dad[f]=e;
		if(topo()&&sum==n){
			cout<<"Sorted sequence determined after "<<i<<" relations: ";
			for(int i=1;i<=sum;i++) cout<<char(ans[i]+'A'-1);
			cout<<".";
			return 0;
		}
	}
	cout<<"Sorted sequence cannot be determined."; 
	return 0;
}
2022/7/25 15:39
加载中...