Instrction Arrangement
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3168 Accepted Submission(s): 1248
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 1
Sample Output
2
Hint
In the 1st ns, instruction 0, 1 and 3 are executed; In the 2nd ns, instruction 2 and 4 are executed. So the answer should be 2.
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
int cnt,head[maxn],n,m,a,b,c,d[maxn],minn[maxn],minnn;
queue<int>q;
struct node
{
int u,v,w,next;
}e[maxn];
void add(int a,int b,int c)
{
cnt++;
e[cnt].u=a;
e[cnt].v=b;
e[cnt].w=c;
e[cnt].next=head[a];
head[a]=cnt;
}
void top_sort()
{
for(int i=0;i<n;i++)
{
if(d[i]==0) q.push(i),minn[i]=1;//minn 所有入度为0的点都是在第一时间开始运行
}
while(!q.empty())
{
int t=q.front();
q.pop();
for(int i=head[t];i;i=e[i].next)
{
int j=e[i].v;
d[j]--;
minn[j]=max(minn[j],minn[e[i].u]+e[i].w);//比较出最大的一个时间
if(d[j]==0) q.push(j);
}
}
}
int main()
{
while(cin>>n>>m)
{
cnt=0;
memset(minn,0,sizeof(minn));
memset(d,0,sizeof(d));
memset(head,0,sizeof(head));
memset(e,0,sizeof(e));
for(int i=1;i<=m;i++)
{
cin>>a>>b>>c;
add(a,b,c);
d[b]++;
}
top_sort();
minnn=0;
for(int i=0;i<n;i++) minnn=max(minnn,minn[i]);//比较出最大的一个时间
cout<<minnn<<endl;
}
return 0;
}