Ali has taken the Computer Organization and Architecture course this term. He learned that there may be dependence between instructions, like WAR (write after read), WAW, RAW.
If the distance between two instructions is less than the Safe Distance, it will result in hazard, which may cause wrong result. So we need to design special circuit to eliminate hazard. However the most simple way to solve this problem is to add bubbles (useless operation), which means wasting time to ensure that the distance between two instructions is not smaller than the Safe Distance.
The definition of the distance between two instructions is the difference between their beginning times.
Now we have many instructions, and we know the dependent relations and Safe Distances between instructions. We also have a very strong CPU with infinite number of cores, so you can run as many instructions as you want simultaneity, and the CPU is so fast that it just cost 1ns to finish any instruction.
Your job is to rearrange the instructions so that the CPU can finish all the instructions using minimum time.
Input
The input consists several testcases.
The first line has two integers N, M (N <= 1000, M <= 10000), means that there are N instructions and M dependent relations.
The following M lines, each contains three integers X, Y , Z, means the Safe Distance between X and Y is Z, and Y should run after X. The instructions are numbered from 0 to N - 1.
Output
Print one integer, the minimum time the CPU needs to run.
Sample Input
5 2
1 2 1
3 4 1
Sample Output
2
题意
给出N道工序和M个关系,每个工序启动需要1秒,M行关系三个参数x y z分别代表x执行z秒后方能执行y。
思路
求拓扑排序的同时更新最长路,其实和最短路差不多,只不过是反过来。具体细节见代码。
代码
#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>
#include <algorithm>
#define MAX_N 1000
using namespace std;
int N, M, degree[MAX_N], finish[MAX_N];
typedef pair<int, int> Edge;
int solve(vector<Edge> G[]){
queue<int> q;
// 将初始任务加入, 它们的结束时间是1秒(题目条件,启动需要1秒)
for(int i = 0; i < N; i++){
if(degree[i] == 0){
q.push(i);
finish[i] = 1;
}
}
// 遍历
while (!q.empty()) {
int u = q.front();
q.pop();
for(Edge e : G[u]){
// 更新以u为前驱的任务的最晚结束时间
if(e.second + finish[u] > finish[e.first]){
finish[e.first] = e.second + finish[u];
}
// 如果它的入度减少到0,则加入队列
if(--degree[e.first] == 0){
q.push(e.first);
}
}
}
// 寻找最大值
int res = finish[0];
for(int i = 1; i < N; i++){
res = max(finish[i], res);
}
return res;
}
int main() {
while (scanf("%d %d", &N, &M) != EOF) {
// 初始化
fill(degree, degree + N, 0);
fill(finish, finish + N, 0);
// 读入
vector<Edge> G[MAX_N];
int from, to, dist;
while (M-- > 0) {
scanf("%d %d %d", &from, &to, &dist);
G[from].push_back(Edge(to, dist));
degree[to]++;
}
// 输出
printf("%d\n", solve(G));
}
return 0;
}