解题思路:利用vectior存储输入的拓扑关系,定义数组记录每一个点状态。对状态显示还未被遍历的点进行DFS(),遍历该点以及与该点有直接拓扑关系的点。在DFS过程中将元素压入存放拓扑结果的vector结构ans。具体分析下面给出的程序。
大体题意:
John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.
Input The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1 ≤ n ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m is the number of direct precedence relations between tasks. After this, there will be m lines with two integers i and j, representing the fact that task i must be executed before task j. An instance with n = m = 0 will finish the input.
Output For each instance, print a line with n integers representing the tasks in a possible order of execution.
Sample Input 5 4 1 2 2 3 1 3 1 5 0 0
Sample Output 1 4 2 5 3
题意:就是给你几组任务,给出了任务的先后顺序,求出他们的执行顺序
拓扑排序就是用来解决这类排序问题的... 先构造出一个图,用dfs递归实现来遍历
#include<cstdio>
#include<string>
#include<vector>
#include<string.h>
#include<iostream>
using namespace std;
vector<int> a[100];
int mark[100]; //mark为1表示已经遍历该节点及其子节点
//为0表示还未遍历,为-1表示正在遍历
vector<int> topo;
bool DFS(int u)
{
mark[u]=-1;
for(int i=0;i<a[u].size();i++)
{
if(mark[a[u][i]]==-1) //再次遇到正在遍历中的,返回false
{
return false;
}
else if(mark[a[u][i]]==0&&DFS(a[u][i])==false) //未遍历则开始遍历并对返回值做出判断
return false;
}
mark[u]=1; //该值遍历完成
topo.push_back(u); //放入topo序列中
return true;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
if(n==0&&m==0)
break;
memset(mark,0,sizeof(mark));
for(int i=1;i<=n;i++)
{
a[i].clear(); //清空一定不能忘
}
topo.clear(); //清空
for(int i=1;i<=m;i++)
{
int u,v;
cin>>u>>v;
a[u].push_back(v);
}
bool flag=true;
for(int i=1;i<=n;i++)
{
if(mark[i]==1) continue; //已经遍历过,直接跳
if(DFS(i)==false) //有一个false即不存在
{
flag=false;
}
}
if(flag==true)
{
for(int i=topo.size()-1;i>=0;i--) //拓扑排序从后往前打印
{
cout<<topo[i]<<" ";
}
cout<<endl;
}
else
cout<<"not exist."<<endl;
}
return 0;
}