拼题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;
}

 

 

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