Instrction Arrangement(HDU 4109)

题目链接

题目描述

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.

输入格式

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.

输出格式

Print one integer, the minimum time the CPU needs to run.

输入样例

5 2
1 2 1
3 4 1

输出样例

2

分析

题目大意给定n个指令,m条规则,每个指令执行时间为1秒,每条规则表明两指令之间的安全距离(安全时间差),求完成所有指令所需要的最短时间。
拓扑排序关键路径模板题,将AOV图转换成AOE图之后求最长路径,用t数组存储指令i完成的时间。注意输入的安全距离如果≤0的话应当赋值成1,但可能题目太水没卡这个。

源程序

#include <bits/stdc++.h>
#define MAXN 10005
using namespace std;
struct Edge{
	int v,w,next;
	Edge(){};
	Edge(int _v,int _w,int _next){
		v=_v,w=_w,next=_next;
	};
}edge[MAXN];
int EdgeCount,head[MAXN];
int n,m,in[MAXN],t[MAXN];
void addEdge(int u,int v,int w)
{
	edge[++EdgeCount]=Edge(v,w,head[u]);
	head[u]=EdgeCount;
}
void TopSort()
{
	queue<int> q;
	for(int i=0;i<n;i++)
		if(!in[i]){
			t[i]=1;
			q.push(i);
		}
	while(!q.empty()){
		int u=q.front();
		q.pop();
		for(int i=head[u];i;i=edge[i].next){
			int v=edge[i].v,w=edge[i].w;
			in[v]--;
			t[v]=max(t[v],t[u]+w);
			if(!in[v])q.push(v);
		}
	}
}
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF){
		EdgeCount=0;
		for(int i=0;i<MAXN;i++)in[i]=head[i]=t[i]=0;
		for(int i=1;i<=m;i++){
			int u,v,w;
			scanf("%d%d%d",&u,&v,&w);
			if(w<=0)w=1;
			addEdge(u,v,w);
			in[v]++;
		}
		TopSort();
		int ans=-9999999;
		for(int i=0;i<n;i++)
			ans=max(ans,t[i]);
		printf("%d\n",ans);
	}
} 
发布了19 篇原创文章 · 获赞 0 · 访问量 127

猜你喜欢

转载自blog.csdn.net/weixin_43960284/article/details/105253488