week8 B - 猫猫向前冲

题目

样例输入

4 3
1 2
2 3
4 3

样例输出

1 2 4 3

 

思路

可以使用拓扑排序解决。

如果P1赢了P2,则存在一条P1到P2的 单向边,并且计算每个点的入度。

如果某个点入度为0,说明当前没有能赢它的猫猫。

题目要求输出最小序列,那么可以用优先队列代替队列,存储入度为0的点,这样每次出队列的就是当前赢了的编号最小的猫猫。

 

代码

#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
#include<vector>
#define MAXN 2520
#define MAXE 520
#define inf 100000000
using namespace std;

queue<int> q;
priority_queue<int> p;
int degree[MAXE];

struct Edge
{
	int u, v, w, next;

}Edge[2 * MAXN];

bool cmp(struct Edge &a, struct Edge &b)
{
	return a.w < b.w;
}


int head[MAXN];
int total = 1;


void init()
{
	total = 1;
	memset(degree, 0, sizeof degree);
	for (int i = 0; i < MAXN; i++)
		head[i] = -1;
}


void addEdge(int uu, int vv, int ww)
{
	Edge[total].u = uu;
	Edge[total].v = vv;
	Edge[total].w = ww;
	Edge[total].next = head[uu];
	head[uu] = total;
	degree[vv]++;
	total++;
}

bool toposort(int n)
{
	int num = 0;
	vector<int> ans;
	for (int i = 1; i <= n; i++)
		if (degree[i] == 0) p.push(-i);
	while (!p.empty())
	{
		int x = -p.top();
		ans.push_back(x);
		p.pop();
		for (int i = head[x]; i != -1; i = Edge[i].next)
		{
			int y = Edge[i].v;
			if (degree[y] > 0)
			{
				degree[y]--;
				if (degree[y] == 0)
					p.push(-y);
					
			}
		}
	}
	if (ans.size() == n)
	{
		for (int i = 0; i < n; i++)
			if (i == 0) cout << ans[i];
			else cout << " " << ans[i] ;
		cout << endl;
		return true;
	}
	else return false;
}

int main()
{
	int m, n, a, b;
	while (cin >> n)
	{
		init();
		cin >> m;
		for (int i = 0; i < m; i++)
		{
			cin >> a >> b;
			addEdge(a, b, 1);
		}
		toposort(n);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值