之前一直觉得拓扑算法听起来很高大上觉得是很复杂的算法,但是今天做过才算知道原来拓扑就是英文top的中国读音,哈哈哈。。。。。算法本身也不是很难。
题目:
08-图8 How Long Does It Take (25 分)
Given the relations of all the activities of a project, you are supposed to find the earliest completion time of the project.
Input Specification:
Each input file contains one test case. Each case starts with a line containing two positive integers N (≤100), the number of activity check points (hence it is assumed that the check points are numbered from 0 to N−1), and M, the number of activities. Then M lines follow, each gives the description of an activity. For the i-th activity, three non-negative numbers are given: S[i], E[i], and L[i], where S[i] is the index of the starting check point, E[i] of the ending check point, and L[i] the lasting time of the activity. The numbers in a line are separated by a space.
Output Specification:
For each test case, if the scheduling is possible, print in a line its earliest completion time; or simply output “Impossible”.
Sample Input 1:
9 12
0 1 6
0 2 4
0 3 5
1 4 1
2 4 1
3 5 2
5 4 0
4 6 9
4 7 7
5 7 4
6 8 2
7 8 4
Sample Output 1:
18
Sample Input 2:
4 5
0 1 1
0 2 2
2 1 3
1 3 4
3 2 5
Sample Output 2:
Impossible
解题思路:
解题思路:
实际的例子就是计算多个工程的最短工期有多大,其实思路感觉和广度优先搜索类似,先用一个二维数轴将两个有关联的工期表示出来(注意和之前的floyd算法不同,这个是有向的也就是两个点之间的日期只能被表示一次),然后计算每个点的入度,将计算结果保存在InDegree的数轴里,然后遍历所有点,将入度为0的点放进一个队列中,再从队列中取点,注意每次从队列中取出点时,计算所有从这个点出发的工程中,达到这个点所用的时间加上这个点到下一个点所用时间之和与之前存储的时间大小,如果大就替换掉,这里再用一个minDate来存储达到每个工程所需要的时间。
遇到困难:
没有什么特别的困难,就是要注意变量名取用时要注意规范。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
#define Max 1000
#define Infinity 666
int Indegree[Max]={0}; //indegree of every project is 0
int minDate[Max]={0}; //every project's mininal finished date is 0
int A[Max][Max]={0};
int cnt=0;
void Top(int N,int side);
int Find(int N);
void printf(int day,int N);
void Top(int N,int side){
int v;
queue<int> q;
//make sure the indegree of every project
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(A[i][j]!=Infinity) Indegree[j]++; //if i point j then project j++
}
}
for(int i=0;i<N;i++){
if(Indegree[i]==0){
q.push(i);
}
}
while(!q.empty()){
v=q.front();
q.pop();
cnt++;
for(int j=0;j<N;j++){
if(A[v][j]!=Infinity){
if(A[v][j]+minDate[v]>minDate[j]) minDate[j]=A[v][j]+minDate[v]; //if the day is bigger than replace the day
Indegree[j]--; //delete the side
if(Indegree[j]==0) q.push(j); //if j is 0 than push j into the queue
}
}
}
}
int Find(int N){
int Maxday=0;
for(int i=0;i<N;i++){
if(minDate[i]>Maxday) Maxday=minDate[i];
}
return Maxday;
}
void Printf(int fDay,int N){
if(cnt!=N) printf("Impossible");
else printf("%d",fDay);
}
int main(){
int N,side;
int fDay=Infinity;
scanf("%d %d",&N,&side);
//initial A[][]
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
A[i][j]=Infinity;
}
}
//get the days between two projects
for(int i=0;i<side;i++){
int x,y;
int day;
scanf("%d %d %d",&x,&y,&day);
A[x][y]=day;
}
Top(N,side); //call for Top arithmetic
fDay=Find(N);
Printf(fDay,N);
}