# include<iostream>
# include<queue>
# include<vector>
# include<cstring>
using namespace std;
const int maxn=100+5;
//定义弧的数据结构
typedef struct arcnode{
int adjnode; //该弧指向的节点索引
arcnode *nextarc; //指向下一条弧
}arcnode;
typedef struct node{
int data;
arcnode *firstarc;
}node;
typedef struct graph{
node vertex[maxn];//顶点集
int vertexnum; //顶点数
int edgenum; //边数
}graph;
graph g;
bool vis[maxn];
vector<int> ss;
int find(graph g,int i) //寻找对应顶点的索引
{
for(int j=0;j<g.vertexnum;j++)
if(g.vertex[j].data==i)
return j;
return -1;
}
void init(graph &g)
{
cin>>g.vertexnum>>g.edgenum;
for(int i=0;i<g.vertexnum;i++)
{
cin>>g.vertex[i].data;
g.vertex[i].firstarc=NULL;
}
for(int i=0;i<g.edgenum;i++)
{
int u,v;
arcnode *s=new arcnode(); //分配节点空间
cin>>u>>v; //输入u->v的边的顶点
int index_u=find(g,u); //查找顶点 u,v的索引
int index_v=find(g,v);
s->adjnode=index_v;
s->nextarc=g.vertex[index_u].firstarc;
g.vertex[index_u].firstarc=s;
}
}
bool dfs(graph g,int u)
{
vis[u]=-1;
arcnode *s=g.vertex[u].firstarc;
while(s)
{
if(vis[s->adjnode]<0)
return false;
else if(!vis[s->adjnode]&&!dfs(g,s->adjnode))
return false;
s=s->nextarc;
}
vis[u]=1;
ss.insert(ss.begin(),g.vertex[u].data);
return true;
}
int main()
{
init(g);
memset(vis,0,sizeof(vis));
for(int i=0;i<g.vertexnum;i++)
if(!vis[i]&&!dfs(g,i))
{
cout<<"存在回路"<<endl;
return 0;
}
for(vector<int>::iterator in=ss.begin();in!=ss.end();in++)
cout<<*in<<" ";
return 0;
}
拓扑排序(dfs)邻接表建图
最新推荐文章于 2021-12-03 18:06:32 发布