拓扑排序纯板子求调,纯度100%
查看原帖
拓扑排序纯板子求调,纯度100%
370648
柠檬布丁吖楼主2023/3/26 20:45
//int n,m;
//vector<int> g[maxn];
//int in[maxn];
//
//bool topu(){
//	vector<int> L;
//	queue<int> S;
//	for(int i=1;i<=n;i++){
//		if(in[i]==0) S.push(i);
//	}
//	
//	while(!S.empty()){
//		int u=S.front();
//		S.pop();
//		L.push_back(u);
//		for(auto v : G[u]){
//			if(--in[v]==0){
//				S.push(v);
//			}
//		}
//	}
//	
//	if(L.size()==n){
//		for(outo i:L) cout<<i<<endl" ";
//		return true;
//	} else {
//		return false;
//	}
//}

//P1347 排序luogu
#include<bits/stdc++.h>

using namespace std;

inline int read(){
	int ret=0,f=1;
	char c=getchar();
	for(;c<'0'||c>'9';c=getchar()) if(c=='-') c=getchar();
	for(;c>='0'&&c<='9';c=getchar()) ret=ret*10+c-'0';
	return ret*f;
}

int n,m,s;

const int maxn=1e2+55;

struct _edge{
	int ne,to;
}edge[maxn];
int tot;

int head[maxn],in[maxn];
void add(int x,int y){
	tot++;
	edge[tot].to=y;
	edge[tot].ne=head[x];
	head[x]=tot;
}

int _in[maxn];

bool vis[maxn];
bool unpd,v;
int sum;

queue<int> q;
int p[maxn];
int topu(){
	unpd=false;v=false;sum=0;
	for(int i=1;i<=26;i++){
		_in[i]=in[i];
		if(!_in[i]&&vis[i]){
			if(!v) v=true;
			else unpd=true;
			q.push(i);
			p[++sum]=i;
		}
	}
	
	if(q.empty()) return 1;
	
	while(!q.empty()){
		int x=q.front();v=false;q.pop();
		for(int i=head[x];i;i=edge[i].ne){
			_in[edge[i].to]--;
			if(!_in[edge[i].to]){
				q.push(edge[i].to);
				if(!v) v=true;
				else unpd=true;
				p[++sum]=edge[i].to;
			}
		}
	}
	
	if(sum!=s) return 1;
	if(unpd) return 2;
	return 0;
}

signed main(void){
	
	n=read();m=read();
	
	char ch;
	int a,b;
	
	for(int i=1;i<=m;i++){
		cin>>ch;
		cout<<ch<<endl;
		a=ch-64;
		if(!vis[a]) vis[a]=true;
		s++;
		cin>>ch;
		cout<<ch<<endl;
		cin>>ch;
		cout<<ch<<endl;
		b=ch-64;
		if(!vis[b]) vis[b]=true;
		s++;
		
		add(a,b);
		in[b]++;
		if(topu()==1){
			printf("Inconsistency found after %d relations.\n",i);
			return 0;
		}
		
		if(sum==n&&!topu()){
			printf("Sorted sequence determined after %d relations: ",i);
			for(int j=1;j<=n;j++){
				printf("%c",p[j]+64);
			}
			printf(".\n");
			return 0;
		}
	}
	
	printf("Sorted sequence cannot be determined.");
	
	return 0;
}
2023/3/26 20:45
加载中...