拓扑排序\有向无环图判断 及经典问题 - 选课

本文介绍了一种使用有向无环图(DAG)解决xmuOJ在线选课系统的课程依赖问题的方法。通过邻接矩阵记录课程间的依赖关系,并采用拓扑排序算法来确定合理的选课顺序。

比较好的一个算法

clipboard.png

DAG : 有向无环图。

xmuOJ 选课

一个点的入点(指向它的点怎么表示)怎么表示? 数组 or vector?
我最后选择了邻接矩阵。

#include <iostream>
#include<stdlib.h>
#include <vector>
#include<stdio.h>
#include<string>
#include<queue>
#include<string.h>

using namespace std;

typedef queue<int> Q;

int main()
{
    int N;
    string name[501];
    int a[501][501]; //a[i][j] = 1 则 i指向j
    int rudu[501];
    Q topQ;//top dui lie
    Q zeroQ;
    int i,j,k;

    //initialize
    memset(a, 0, sizeof(a));
    scanf("%d", &N);
    for (i = 1; i <= N; i++)
        cin >> name[i];
    for (i = 1; i <= N; i++)
    {
        scanf("%d", rudu + i);
        if (rudu[i] == 0)
            zeroQ.push(i);
        for ( j = 1; j <= rudu[i]; j++)
        {
            int b ;
            scanf("%d", &b);
            a[b][i] = 1;
        }
    }

    int top[501], cnt = 0;
    while (!zeroQ.empty())
    {
        top[++cnt] = zeroQ.front(), zeroQ.pop();//
        for ( i = 1; i <= N; i++)
        {
            if (a[top[cnt]][i] == 1)
            {
                if (--rudu[i] == 0)
                { 
                    zeroQ.push(i);
                }
            }
                
        }
    }

    if (cnt!= N)
    {
        printf("Impossible!");
        return 0;
    }

    for (i = 1; i < N; i++)
    {
        cout << name[top[i]];
        printf(" ");
    }
    cout << name[top[N]];

    return 0;
}

/*
9
Introduction_to_Computer_Science C_Programming_Language Data_Structure Design_and_Analysis_of_Algorithms Mathematical_Analysis Advanced_Algebra Probability_and_Statistics Numerical_Analysis Operating_System
0
1 1
2 1 2
3 1 2 3
0
0
1 5
2 5 6
2 1 2
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值