Instrction 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 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.
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 should 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
Recommendlcy 差分約束系統加一個源點s指向所有點邊權為0,加一個匯點t,所有點指向t邊權為0,u和v安全距離為w,則加邊v->u,邊權為-w求s到t最短路即可。代碼:
#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]);}}