本实验项目是实验项目6-06的深化。任务调度问题中,如果还给出了完成每个子任务需要的时间,则我们可以算出完成整个工程需要的最短时间。在这些子任务中,有些任务即使推迟几天完成,也不会影响全局的工期;但是有些任务必须准时完成,否则整个项目的工期就要因此延误,这种任务就叫“关键活动”。
请编写程序判定一个给定的工程项目的任务调度是否可行;如果该调度方案可行,则计算完成整个工程项目需要的最短时间,并输出所有的关键活动。
输入格式说明:
输入第1行给出两个正整数N(<=100)和M,其中N是任务交接点(即衔接相互依赖的两个子任务的节点,例如:若任务2要在任务1完成后才开始,则两任务之间必有一个交接点)的数量,交接点按1~N编号,M是子任务的数量,依次编号为1~M。随后M行,每行给出了3个正整数,分别是该任务开始和完成涉及的交接点编号以及该任务所需的时间,整数间用空格分隔。
输出格式说明:
如果任务调度不可行,则输出0;否则第1行输出完成整个工程项目需要的时间,第2行开始输出所有关键活动,每个关键活动占一行,按格式“V->W”输出,其中V和W为该任务开始和完成涉及的交接点编号。关键活动输出的顺序规则是:任务开始的交接点编号小者优先,起点编号相同时,与输入时任务的顺序相反。如下面测试用例2中,任务<5,7>先于任务<5,8>输入,而作为关键活动输出时则次序相反。
样例输入与输出:
序号 | 输入 | 输出 |
1 | 7 8 1 2 4 1 3 3 2 4 5 3 4 3 4 5 1 4 6 6 5 7 5 6 7 2 | 17 1->2 2->4 4->6 6->7 |
2 | 9 11 1 2 6 1 3 4 1 4 5 2 5 1 3 5 1 4 6 2 5 7 9 5 8 7 6 8 4 7 9 2 8 9 4 | 18 1->2 2->5 5->8 5->7 7->9 8->9 |
3 | 11 14 1 2 4 1 3 3 2 4 5 3 4 3 4 5 1 4 6 6 5 7 5 6 7 2 8 3 7 9 3 7 9 10 6 4 10 2 10 6 5 6 11 4 | 21 3->4 4->10 6->11 8->3 9->3 10->6 |
4 | 4 5 1 2 4 2 3 5 3 4 6 4 2 3 4 1 2 | 0 |
#include<iostream>
#include<climits>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
#define N 101
#define MAX 100000
int earliest[N];
int latest[N];
int indeg[N];
int outdeg[N];
int act[N][N];
queue<int> aux;
int main()
{
int n, m;
cin>> n >>m;
int i,j;
vector<int> aa;
for(i = 1; i<=n; i++)
for(j = 0; j<=n; j++)
act[i][j] = -1;
for(i = 1; i<= n; i++)
{
earliest[i] = -1;
latest[i] = MAX;
}
for(i = 0; i< m; i++)
{
int s, e, w;
cin>>s>>e>>w;
act[s][e] = w;
indeg[e] ++;
outdeg[s] ++;
aa.push_back(i);
}
vector<int> start;
vector<int> last;
for(i =1; i<= n; i++)
{
if(indeg[i] == 0)
{
aux.push(i);
earliest[i] = 0;
start.push_back(i);
}
if(outdeg[i] == 0)
{
last.push_back(i);
}
}
int cnt = 0, dates = -1;
//计算每个节点的最早完成时间
while(!aux.empty())
{
int v = aux.front();
aux.pop();
cnt++;
for(i=1; i<=n; i++)
{
if(act[v][i] != -1)
{
if(--indeg[i] == 0)
aux.push(i);
earliest[i] = max(earliest[i], earliest[v]+ act[v][i]);
dates = max(dates,earliest[i]);
}
}
}
if(cnt != n)
{
cout<<"0"<< endl;
return 0;
}
cout<< dates<< endl;
for(i=0; i<last.size(); i++)
{
latest[last[i]] = dates;
aux.push(last[i]);
}
//计算每个节点的最晚完成时间
while(!aux.empty())
{
int v = aux.front();
aux.pop();
for(i = 1; i <=n ; i++)
{
if(act[i][v] != -1)
{
if(--outdeg[i] == 0 )
aux.push(i);
latest[i] = min(latest[i], latest[v] - act[i][v]);
}
}
}
//计算每个路径多出的时间,D=0则是关键路劲
for(i = 1; i<=n; i++)
{
if(latest[i] != earliest[i])
continue;
for(j=n; j>=0; j--)
{
if(act[i][j] != -1 && (latest[j] == earliest[j]))
{
if((latest[j]-earliest[i]-act[i][j])==0)
cout<<i<<"->"<< j<< endl;
}
}
}
return 0;
}