我有下面的代码,但我不能实现它,因为我不知道如何使用它的顶点来表示DAG。拓扑排序
#include<iostream>
#include "queue.h"
#include "graph.h"
#include "bool.h"
using namespace std;
void init(Queue *q)
{
q->first=0;
q->last=queuesize-1;
q->count=0;
}
void enqueue(Queue *q,int x)
{
if(q->count>=queuesize)
{
cout<<"queue overflow "<<endl;
}
else
{
q->last=(q->last+1)%queuesize;
q->q[q->last]=x;
q->count=q->count+1;
}
}
int dequeue(Queue *q)
int x;
if(q->count<=0)
{
cout<<" empthy "<<endl;
}
else
{
x=q->q[q->first];
q->first=(q->first+1)%queuesize;
q->count=q->count-1;
}
return x;
}
int empthy_queue (Queue *q)
{
if(q->count<=0)
{
return TRUE;
}
return FALSE;
}
void initialize (graph *g)
{
int i;
g->nvertices=0;
g->nedges=0;
for(i=1; i<=maxv; i++)
{
g->degree[i]=0;
}
}
void insert(graph *g,int x,int y,boolean directed)
{
if(g->degree[x]>maxdegree)
{
cout<<"degree overflow";
}
g->edges[x][g->degree[x]]=y;
g->degree[x]++;
if(directed==FALSE)
{
insert(g,y,x,TRUE);
}
else
{
g->nedges++;
}
}
void read_graph(graph *g,boolean directed)
{
int i;
int m;
int x,y;
initialize(g);
cin>>g->nvertices>>m;
for(i=1; i<=m; i++)
{
cin>>x>>y;
insert(g,x,y,directed);
}
}
void cpmpute_degree(graph *g,int in[])
{
int i,j;
for(i=1; i<=g->nvertices; i++)
{
in[i]=0;
}
for(i=1; i<=g->nvertices; i++)
for(j=0; j<g->degree[i]; j++)
{
in[g->edges[i][j]]++;
}
}
void topsort(graph *g,int sorted[])
{
int indegree[maxv];
int x,y;
Queue zeroin;
int i,j;
cpmpute_degree(g,indegree);
init(&zeroin);
for(i=1; i<=g->nvertices; i++)
if(indegree[i]==0)
{
enqueue(&zeroin,i);
}
j=0;
while(empthy_queue(&zeroin)==FALSE)
{
j=j+1;
x=dequeue(&zeroin);
sorted[j]=x;
for(i=0; i<g->degree[x]; i++)
{
y=g->edges[x][i];
indegree[y]--;
if(indegree[y]==0)
{
enqueue(&zeroin,y);
}
}
}
if(j!=g->nvertices)
{
printf("Not a DAG -- only %d vertices found\n",j);
}
}
int main()
{
graph g;
int out[maxv];
int i;
read_graph(&g,false);
topsort(&g,out);
for(i=1; i<=g.nvertices; i++)
{
cout<<out[i]<<" ";
}
return 0;
}
请告诉我如何从键盘读取图形,使给定的图形应该是DAG?我的意思是这一个
1 2
2 3
3 4
4 5
等等。 假设顶点是6个边8 请帮助我,当我进入图形几次,它写了这个输出
printf("Not a DAG -- only %d vertices found\n",j);
请给我正确的输入图形(顶点6,边8)
啊,所以你有一个含糊不清的代码模糊的问题:让我来帮你!如果你展示了产生该输出的实际特定输入,解释了为什么你认为这是错误的,以及到目前为止已经做了什么来解释它,这可能会有所帮助。 – Useless
假设输入像这样1-2 2-3 3-4 4-5 5-6 6-7 7-1(7个顶点,7个边) –
真的没有理由将'Graph'实例作为指针。改用引用(在适当的地方使用'const')。 –