【Luogu_P1347】排序

题目链接

思路:

直接附代码

#include
#include
#include
#include
#include
#include
#include
using namespace std;

int n, m, tot, head[100], d[100], du[100], f[100100], v[1001], ans[100];
int len=0;
struct node
{
	int to, next;
}b[1000100];

void VL_ljb(int x, int y)
{
	b[++tot]=(node){y, head[x]};
	head[x]=tot;
}
void VL_topu()
{
	int hd=0, tl=0;
	len=0;
	for(int i=1; i<=n; i++)
	{
		ans[i]=0;
		f[i]=0;
		du[i]=d[i];
		v[i]=0;
		if(du[i]==0)
		{
			tl++;
			v[i]=1;
			f[tl]=i;
			ans[i]=1;
		}
	}
	while(hd<tl)
	{
		hd++;
		int x=f[hd];
		for(int i=head[x]; i; i=b[i].next)
		{
			int y=b[i].to;
			if(v[y]==1)continue;
			du[y]--;
			ans[y]=max(ans[y], ans[x]+1);
			len=max(len, ans[y]);
			if(du[y]==0)
			{
				v[y]=1;
				f[++tl]=y;
			}
		}
	}
}
int main(){
	cin>>n>>m;
	for(int i=1; i<=m; i++)
	{
		char a;
		int x, y;
		cin>>a;
		x=a-64;
		cin>>a>>a;
		y=a-64;
		if(x==y)
		{
			printf("Inconsistency found after %d relations.", i);
			return 0;
		}
		VL_ljb(x, y);
		d[y]++;
		VL_topu();
		for(int j=1; j<=n; j++)
			if(du[j]>0)
			{
				printf("Inconsistency found after %d relations.", i);
				return 0;
			}
		if(len==n)
		{
			printf("Sorted sequence determined after %d relations: ", i);
			for(int j=1; j<=n; j++)
				printf("%c", f[j]+64);
			printf(".");
			return 0;
		}
	}
	printf("Sorted sequence cannot be determined.");
	return 0;
}

你可能感兴趣的:(题解,拓扑排序)