一个项目由若干个任务组成,任务之间有先后依赖顺序。项目经理需要设置一系列里程碑,在每个里程碑节点处检查任务的完成情况,并启动后续的任务。现给定一个项目中各个任务之间的关系,请你计算出这个项目的最早完工时间。
输入格式:
首先第一行给出两个正整数:项目里程碑的数量 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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <bits/stdc++.h>
using namespace std;
#define PII pair<int,int>
const int N = 110;
const int inf = 0x3f3f3f3f;
int n,m;
int in[N];
int res[N];
int dis[N];
int tot=0;
vector<PII>g[N];
void topo(){ // 拓扑求关键路径
queue<int>q;
for(int i=0;i<n;i++){
if(!in[i]) q.push(i);
}
while(q.size()){
auto u=q.front();
q.pop();
res[tot++]=u;
for(auto i:g[u]){
auto v=i.first,w=i.second;
in[v]--;
if(!in[v]) q.push(v);
if(dis[v]<dis[u]+w) dis[v]=dis[u]+w;
}
}
}
int main(){
cin>>n>>m;
while(m--){
int u,v,w;
cin>>u>>v>>w;
g[u].push_back(PII{v,w}); // 存图
in[v]++; // 入度++
}
topo();
if(tot==n){
int maxx=0;
for(int i=0;i<n;i++) maxx=max(maxx,dis[i]);
cout<<maxx<<endl;
}else cout<<"Impossible"<<endl;
return 0;
}