UVA - 10305 【拓扑排序】

这里写图片描述

题意
给出一些任务的优先级别 将这些任务进行的时间 进行先后排序

思路
拓扑排序

将所以有先后关系的任务都连一条边

然后每次 输出 度为0 的任务
每次把 以这个任务为弧的边 都取消 相对应任务的度也-1

再循环

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

#define CLR(a) memset(a, 0, sizeof(a))
#define pb push_back

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;

const double PI = acos(-1.0);
const double E = exp(1);
const double eps = 1e-30;

const int INF = 0x3f3f3f3f;
const int maxn = 1e2 + 5;
const int MOD = 1e9 + 7;

int G[maxn][maxn];
int degree[maxn];
int v[maxn];

int n, m;

vector <int> ans;

int Count;

void dfs()
{
    for (int i = 1; i <= n; i++)
    {
        if (degree[i] == 0 && v[i] == 0)
        {
            Count++;
            ans.pb(i);
            v[i] = 1;
            for (int j = 1; j <= n; j++)
            {
                if (G[i][j])
                {
                    G[i][j] = 1;
                    degree[j]--;
                }
            }
        }
    }
    if (Count != n)
        dfs();
}

int main()
{
    while (scanf("%d%d", &n, &m) && (n || m))
    {
        CLR(G);
        CLR(degree);
        CLR(v);
        int x, y;
        for (int i = 0; i < m; i++)
        {
            scanf("%d%d", &x, &y);
            G[x][y] = G[y][x] = 1;
            degree[y]++;
        }
        ans.clear();
        Count = 0;
        dfs();
        vector <int>::iterator it;
        for (it = ans.begin(); it != ans.end(); it++)
        {
            if (it != ans.begin())
                printf(" ");
            printf("%d", (*it));
        }
        cout << endl;
    }
}
posted @ 2018-04-09 21:46  Dup4  阅读(92)  评论(0编辑  收藏  举报