10305 - Ordering Tasks (UVA)

题目链接如下:

Online Judge

有一个非常刁钻的卡点,第16行要是在&& n后面加上 && m的话,就会WA...因为m可以为0.

我的代码如下:

#include 
#include 
#include 
#include 
const int maxx = 101;
// #define debug

int n, m, u, v;
int prev[maxx];

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    while (scanf("%d %d", &n, &m) == 2 && n){
        std::fill(prev, prev + n + 1, 0);
        std::vector> vec(n + 1);
        std::vector ans;
        for (int i = 0; i < m; ++i){
            scanf("%d %d", &u, &v);
            if (!vec[u].count(v)){
                vec[u].insert(v);
                prev[v]++;
            }
        }
        do {
            for (int i = 1; i <= n; ++i){
                if (!prev[i]){
                    ans.push_back(i);
                    prev[i]--;
                    for (auto it = vec[i].begin(); it != vec[i].end(); ++it){
                        prev[*it]--;
                    }
                }
            }
        } while (ans.size() < n);
        for (int i = 0; i < n; ++i){
            printf("%d%s", ans[i], i == n - 1 ? "\n" : " ");
        }
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}

又写了一个dfs的版本,这里没有判断有没有环,因为根据题意,应该没有环的情况出现:

#include 
#include 
#include 
const int maxx = 101;
// #define debug

int n, m, u, v;
int arc[maxx][maxx];
bool visited[maxx];
std::vector vec;

void dfs(int k){
    visited[k] = true;
    for (int i = 1; i <= n; ++i){
        if (i != k && !visited[i] && arc[k][i]){
            dfs(i);
        }
    }
    vec.push_back(k);
}

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    while (scanf("%d %d", &n, &m) == 2 && n){
        vec.clear();
        std::fill(arc[0], arc[0] + maxx * maxx, 0);
        std::fill(visited, visited + maxx, false);
        for (int i = 0; i < m; ++i){
            scanf("%d %d", &u, &v);
            arc[u][v] = 1;
        }
        for (int i = 1; i <= n; ++i){
            if (!visited[i]){
                dfs(i);
            }
        }
        reverse(vec.begin(), vec.end());
        for (int i = 0; i < vec.size(); ++i){
            printf("%d%s", vec[i], i == vec.size() - 1 ? "\n" : " ");
        }
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}

你可能感兴趣的:(UVA,图论,算法)