Direction ction Arrangement
Time Limit: 2000/1000 MS (Java/others) memory limit: 32768/32768 K (Java/Others)
Total submission (s): 107 accepted submission (s): 48
Problem DescriptionAli 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 implements 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 your 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.
InputThe 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 shocould run after X. the instructions are numbered from 0 to N-1.
OutputPrint one integer, the minimum time the CPU needs to run.
Sample Input
5 21 2 13 4 1
Sample output
2HintIn 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.
Source2011 Alibaba-cup campus contest
The recommendlcy difference constraint system adds a Source Vertex s to point to 0 for all vertex edges, adds a sink vertex T, all vertices point to the T edge right to 0, and the safe distance between U and V is W, then add the edge V-> U, and the edge weight is-W to calculate s to T's shortest short circuit. Code:
#include<cstdio>#include<cstring>#define N 1005int n,m,num,adj[N],low[N],f[N],q[N];struct edge{int v,w,pre;}e[N*10];void insert(int u,int v,int w){e[num].v=v;e[num].w=w;e[num].pre=adj[u];adj[u]=num++;}void spfa(int x){int i,v,head=0,tail=0;memset(f,0,sizeof(f));memset(low,0x3f,sizeof(low));low[x]=0;q[++tail]=x;while(head!=tail){x=q[head=(head+1)%N];f[x]=0;for(i=adj[x];~i;i=e[i].pre)if(low[v=e[i].v]>low[x]+e[i].w){low[v]=low[x]+e[i].w;if(!f[v]){f[v]=1;q[tail=(tail+1)%N]=v;}}}}int main(){int u,v,w;while(~scanf("%d%d",&n,&m)){num=0;memset(adj,-1,sizeof(adj));while(m--){scanf("%d%d%d",&u,&v,&w);u++;v++;insert(v,u,-w);}for(u=1;u<=n;u++){insert(0,u,0);insert(u,n+1,0);}spfa(0);printf("%d\n",1-low[n+1]);}}