• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

  • 联系
  • 订阅
  • 管理

View Post

zoj 1060 Sorting It All Out 拓扑排序

//这题之前一直卡着没过,今晚蛋疼了一晚才过
//这题是拓扑排序,有几个易错点
//拓扑排序的时候,m每次要保证入度为0的点只有1个,因为题目要求的是完全排序
//当满足条件(确定排序或检测到矛盾)后,后面的输入就可以不管了
#include <iostream>
#include <queue>
#include <string>
#include <cstring>
using namespace std;

const int N = 30;

int maze[N][N];
bool isAppear[N];
int n, cases;
bool isDetermine, isInconsistance;
string path;

void toposort()
{
	queue<int> Q;
	int delete_num = 0;
	int cnt = 0;
	path = "";
	bool flag = false;
	int size[N];
	
	memset(size, 0, sizeof(size));
	for (int i = 0; i < n; i++)
	{		
		cnt = 0;
		for (int j = 0; j < n; j++)
			if (maze[j][i])
				size[i]++;
		if (!size[i])
			Q.push(i);
	}

	if (Q.empty())
	{
		isInconsistance = true;
		return;
	}

	if (Q.size() > 1)
		flag = true;
	
	while (!Q.empty())
	{
		int qhead = Q.front();
		Q.pop();
		path += char(qhead + 'A');
		delete_num++;
		for (int i = 0; i < n; i++)
			if (maze[qhead][i])
			{
				size[i]--;
				if (size[i] == 0)
					Q.push(i);
			}
		if (Q.size() > 1)
			flag = true;
	}
	
	cnt = 0;
	for (int i = 0; i < n; i++)
		if (isAppear[i])
			cnt++;

	if (cnt == delete_num && cnt == n && !flag)
		isDetermine = true;
	else if (cnt > delete_num)
		isInconsistance = true;
}

int main()
{
	char c1, c2;
	int num, ans;

	while (cin >> n >> cases && (n || cases))
	{
		memset(isAppear, false, sizeof(isAppear));
		isDetermine = false;
		isInconsistance = false;
		num = 0;
		memset(maze, 0, sizeof(maze));

		while (cases--)
		{
			num++;
			cin >> c1;
			cin >> c2;
			cin >> c2;
			if (isInconsistance || isDetermine)
				continue;

			isAppear[c1-'A'] = true;
			isAppear[c2-'A'] = true;
			maze[c1-'A'][c2-'A'] = 1;
			
			toposort();

			if (isDetermine)
				ans = num;
			if (isInconsistance)
				ans = num;
		}
		
		if (isDetermine || isInconsistance)
			if (isDetermine)
				cout << "Sorted sequence determined after " << ans << " relations: " << path << "." << endl;
			else
				cout << "Inconsistency found after " << ans << " relations." << endl;
		else
			cout << "Sorted sequence cannot be determined." << endl;
	}
	return 0;
}

posted on 2011-03-19 22:40  sysuwhj  阅读(611)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3