谁来救救我?!
  • 板块P1347 排序
  • 楼主DevilsFlame
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/7/31 19:22
  • 上次更新2024/7/31 20:34:58
查看原帖
谁来救救我?!
1050431
DevilsFlame楼主2024/7/31 19:22
#include<bits/stdc++.h>
using namespace std;
int f[30],n,m,a,b,v,top;
char x,y;
vector <int> q[30];
bool e,d[30][30];
string ans;
bool dfs(int x,int d)
{
	if(d > n)
	{
		return 1;
	}
	d ++;
	for(int i = 0;i < q[x].size();i ++)
	{
		int v = q[x][i];
		if(dfs(v,d)) return 1;
	}
	return 0;
}
int main()
{
	ios::sync_with_stdio(0);
	cin >> n >> m;
	for(int i = 1;i <= m;i ++)
	{
		cin >> x >> y >> y;
		a = x - 64,b = y - 64;
		if(d[a][b]) continue;
		d[a][b] = 1;
		q[a].push_back(b);
		f[b] ++;
	}
	for(int i = 1;i <= n;i ++)
		if(dfs(i,0))
		{
			cout << "Inconsistency found after " << m << " relations." << endl;
		    return 0;
		}
	int cnt = 0;
	for(int i = 1;i <= n;i ++) if(!f[i]) v = i,cnt++;
	if(cnt > 1)
	{
		printf("Sorted sequence cannot be determined.\n");
		return 0;
	}
	queue <int> t;
	t.push(v);
	int j = 0;
	while(!t.empty())
	{
		if(j > 1)
		{
			cout << "Sorted sequence cannot be determined.\n" << endl;
			return 0;
		}
		v = t.front();
		ans += char(v + 64);
		top ++;
		j = 0;
		t.pop();
		for(int i = 0;i < q[v].size();i ++)
		{
			int u = q[v][i];
			f[u] --;
			if(!f[u])
			{
				j ++;
				t.push(u);
			}
		}
	}
	if(top < n)
	{
		cout << "Sorted sequence cannot be determined.\n" << endl;
		return 0;
	}
	printf("Sorted sequence determined after %d relations: ");
	cout << ans << '.' << endl;
	return 0;
}
2024/7/31 19:22
加载中...