Problem Description
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 1Sample Output
2
题意:给出 n 条指令的系统,有 m 个 x y z 形式的依赖关系,表示 y 指令必须在 x 指令后 z 秒执行,每条指令执行需要 1 秒,问该系统的指令执行完至少要多久
思路:可以看成一个 AOE 网,求整个工程的最少完成时间,求关键路径即可
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 2000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
struct Node{
int to,dis;
Node(){}
Node(int to,int dis):to(to),dis(dis){}
};
int n,m;
int in[N];
vector<Node>G[N];
int dis[N];
void getPath() {
queue<int> Q;
int u,v,w;
for(int i=0;i<n;i++){
if(in[i]==0){
Q.push(i);
dis[i]++;
}
}
while(!Q.empty()){
int x=Q.front();
Q.pop();
for(int i=0;i<G[x].size();i++){
int y=G[x][i].to;
int diss=G[x][i].dis;
dis[y]=max(dis[y],dis[x]+diss);
if (--in[y]==0)
Q.push(y);
}
}
}
int main() {
while(scanf("%d%d",&n,&m)!=EOF){
memset(in,0,sizeof(in));
memset(dis,0,sizeof(dis));
for(int i=0;i<n;i++)
G[i].clear();
for(int i=1;i<=m;i++){
int x,y,dis;
scanf("%d%d%d",&x,&y,&dis);
G[x].push_back(Node(y,dis));
in[y]++;
}
getPath();
int res=-INF;
for(int i=0;i<n;i++)
res=max(res,dis[i]);
printf("%d\n",res);
}
return 0;
}