您的位置:首页 > 其它

HDU 1285 确定比赛名次

2017-08-17 21:37 225 查看

拓扑排序。

结果很多种按字典序小的输出,所以用优先队列来存储。

代码:

#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;

const int maxn = 505;
int n, m;
int indegree[maxn] = {0}, gragh[maxn][maxn], res[maxn];
vector<int>g[505];
void toposort()
{
priority_queue<int,vector<int>,greater<int> >q;
int cnt = 0;
for (int i = 0; i < n; i++)
if (indegree[i] == 0)
q.push(i);
while (!q.empty())
{
int tmp = q.top();
q.pop();
res[cnt++] = tmp;
for (int i = 0; i < g[tmp].size(); i++)
{
int b = g[tmp][i];
if (--indegree[b] == 0)
q.push(b);
}
}
printf("%d", res[0] + 1);
for (int i = 1; i < cnt; i++)
printf(" %d", res[i] + 1);
printf("\n");
}

int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
for(int i = 0; i <= n; i++)
{
g[i].clear();
}
//memset(gragh, 0, sizeof(gragh));
memset(indegree, 0, sizeof(indegree));
int a, b;
for (int i = 0; i < m; i++)
{
scanf("%d%d", &a, &b);
g[a-1].push_back(b-1);
indegree[b-1]++;
}
toposort();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: