凜冬之翼---拓撲演算法
之前一直覺得拓撲演算法聽起來很高大上覺得是很複雜的演算法,但是今天做過才算知道原來拓撲就是英文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);
}