您的位置:首页 > 其它

uva10305 拓扑排序

2016-07-26 16:56 399 查看
John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task isonly possible if other tasks have already been executed.

题干很短,意思很简单,拓扑排序。

我的方法是用队列做,将入度为零的点进队,每次出队更新入度,继续将入度为零的点进队。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
vector<int> mp[105];
vector<int> ans;
int ru[105];
int n,m;
void init()
{
for(int i=0; i<=n; ++i)
{
mp[i].clear();
}
memset(ru, 0, sizeof(ru));
}
int main()
{
int x,y;
while(scanf("%d %d",&n,&m)&&(n||m))
{
init();
ans.clear();
queue<int> q;
for(int i=0;i<m;i++)
{

scanf("%d %d",&x,&y);
mp[x].push_back(y);
++ru[y];
}
for(int i=1; i<=n; i++)
if(!ru[i]) q.push(i);
while(!q.empty())
{
int t=q.front();
q.pop();
ans.push_back(t);
for(int i=0;i<mp[t].size();i++)
{
--ru[mp[t][i]];
if(ru[mp[t][i]]==0)
q.push(mp[t][i]);
}
}
printf("%d",ans[0]);
for(int i=1;i<ans.size();i++)
{
printf(" %d",ans[i]);
}
printf("\n");
}

}
貌似还有一种用dfs做的方法,思路也蛮清晰的

就不贴出来了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm 拓扑排序