拼題A 最短工期

題目描述:

一個項目由若干個任務組成,任務之間有先後依賴順序。項目經理需要設置一系列里程碑,在每個里程碑節點處檢查任務的完成情況,並啓動後續的任務。現給定一個項目中各個任務之間的關係,請你計算出這個項目的最早完工時間。

輸入格式:

首先第一行給出兩個正整數:項目里程碑的數量 N(≤100)和任務總數 M。這裏的里程碑從 0 到 N−1 編號。隨後 M 行,每行給出一項任務的描述,格式爲“任務起始里程碑 任務結束里程碑 工作時長”,三個數字均爲非負整數,以空格分隔。

輸出格式:

如果整個項目的安排是合理可行的,在一行中輸出最早完工時間;否則輸出"Impossible"。

輸入樣例 1:

9 12
0 1 6
0 2 4
0 3 5
1 4 1
2 4 1
3 5 2
5 4 0
4 6 9
4 7 7
5 7 4
6 8 2
7 8 4

輸出樣例 1:

 

18

輸入樣例 2:

4 5
0 1 1
0 2 2
2 1 3
1 3 4
3 2 5

輸出樣例 2: 

Impossible

 拓撲排序加上一點關鍵路徑

代碼:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int MAX = 109;
const int INF = 1 << 30;


int task[MAX][MAX];
int in_degree[MAX], ans[MAX];
int N, M, u, v, cost;

int main()
{
    scanf("%d%d", &N, &M);

    for( int i = 0; i < N; i++ ) // 初始化
        for( int j = 0; j < N; j++ )
            task[i][j] = -1;

    for( int i = 0; i < M; i++ )
    {
        scanf("%d%d%d", &u, &v, &cost);
        task[u][v] = cost;
        in_degree[v]++; // 入度
    }

    queue<int> que;
    for( int i = 0; i < N; i++ ) // 入度爲零的入隊
    {
        if( in_degree[i] == 0 )
        {
            que.push(i);
        }
    }

    int res, cnt;
    cnt = res = 0;

    while(!que.empty())
    {
        int temp = que.front();
        que.pop();
        cnt++; // 如果符合條件的話cnt 一定爲N

        for( int i = 0; i < N; i++ )
        {
            if( task[temp][i] != -1 )
            {
                ans[i] = max(ans[i], ans[temp] + task[temp][i]); // 每個里程碑要取最大值
                in_degree[i] --; // 入度減一
                res = max(res, ans[i]);  // 結果也要取最大值

                if(in_degree[i] == 0) // 入度爲零則入隊
                    que.push(i);
            }
        }
    }

    if( cnt == N )
        printf("%d\n", res);
    else
        printf("Impossible\n");
    return 0;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章