uva10305-给任务排序

此题为数据结构基础图的训练参考

 

题目链接 http://acm.hust.edu.cn/vjudge/problem/19494

 

解题思路

拓扑排序。

一开始在想如果排序不唯一oj能判断出来吗?结果oj能判断。。。

可以仿照白书里dfs的做法,也可以采用邻接表存储,入度判断的方法。

代码采用的是后一种。

 

注意 可能有任务为0的情况

 

代码

#include<iostream>
#include<cstdio>
//#define LOCAL
using namespace std; 
const int maxLen = 101;
struct ArcNode {
    int task;
    int adjvex;
    ArcNode *next;
};
struct VertexNode {
    int task;
    int in;
    ArcNode *firstEdge;
}v[maxLen];
int q[2*maxLen];
int n, m;
void TopSort()
{
    int top = -1;
    int count = 0;
    for(int i=0; i<n; i++)
        if(v[i].in == 0) q[++top] = i;
    while(top != -1) {
        int j=q[top--]; count++;
        if(count != n) cout << v[j].task << ' ';
        else cout << v[j].task;
        ArcNode *p = v[j].firstEdge;
        while(p != NULL) {
            int k = p->adjvex;
            v[k].in--;
            if(v[k].in == 0) q[++top] = k;
            p = p->next;
        }
    }
}
int main()
{
    #ifdef LOCAL
        freopen("data.txt", "r", stdin);
        freopen("ans.txt", "w", stdout);
    #endif
    cin >> n >> m;
    while(n!=0 && m!=0) {
        for(int i=0; i<n; i++) {
            v[i].in = 0;
            v[i].task = i+1;
            v[i].firstEdge = NULL;
        }
        for(int i=0; i<m; i++) {
            int x, y;
            cin >> x >> y;
            ArcNode *s = new ArcNode;
            s->task = y; s->adjvex = y-1;
            s->next = v[x-1].firstEdge;
            v[x-1].firstEdge = s;
            v[y-1].in++;
        }
        if(n!=0)TopSort();
        cout << endl;
        cin >> n >> m;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/ZengWangli/p/5760585.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值