拓扑排序
啥是拓扑排序?
直观理解就是在AOE/AOV网络里面,把图的一种先后顺序,对图进行遍历
进行的算法也不难
直接每次选取入度为0的点,进行入队
然后每次出队一个,并对其邻接的顶点进行度的减一操作。
如果出队的顶点数小于总的顶点数,那么,表明存在圈
所以,该算法也能用于有向图的圈的判定问题。
咱们利用一道例题说明:
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
题目的大致意思,就是:每项工作,用图G里面的边进行表示,节点表示任务结束(AOE/activity on edge网络),求最小完成时间
我们需要做的,实现之前的拓扑排序算法
对于最短时间,我们只需要弄一个数组earlist,每次入度减一时,进行最大的更新操作
PS:一开始,没看清楚权重为0的边,表明我们在对图的初始化时,要当心。调试程序真的是让人头秃啊。。。。。
代码见下:
#include <iostream>
#include <queue>
#define inf 9999999
int n, m;
int graph[200][200];
int ru_du[200];
using namespace std;
void ini()
{
cin>>n>>m;
int i, j, k, x, y;
for(i=0;i<200;i++)
{
for(j=0;j<200;j++)
{
graph[i][j]=-100;
}
}
for (i=0; i<m; i++)
{
cin>>x>>y;
cin>>k;
graph[x][y]=k;
ru_du[y]++;
}
}
int maxx(int a,int b)
{
if(a>b)
{
return a;
}
else
{
return b;
}
}
void slove()
{
queue <int> qq;
int i,j,k;
for(i=0;i<n;i++)
{
if(ru_du[i]==0)
{
qq.push(i);
}
}
int counnt=0;
int earlist[2000]={0};
while (!qq.empty())
{
int t=qq.front();
qq.pop();
counnt++;
for(i=0;i<n;i++)
{
if(graph[t][i]!=-100)
{
ru_du[i]--;
earlist[i]=maxx(earlist[i],earlist[t]+graph[t][i]);
if(ru_du[i]==0)
{
qq.push(i);
}
}
}
}
if(counnt!=n)
{
cout<<"Impossible";
return;
}
else
{
int t=0;
for(i=0;i<n;i++)
{
t=maxx(earlist[i],t);
}
cout<<t;
return;
}
}
int main()
{
ini();
slove();
}