我有以下代码,但我无法实现它,因为我不确定如何使用其顶点表示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)
答案 0 :(得分:1)
您可以通过调查read_graph
函数
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);
}
第一个cin
在nvertices
和m
中存储用户输入。 m
稍后用于迭代剩余的输入,因此它等于边数。
后面的每一行代表图中的单个边。据推测,这两个数字代表起始节点和结束节点。
因此,生成6顶点8边图的正确输入是:
6 8
[eight lines of edges here]
答案 1 :(得分:1)
我不确定你究竟是什么意思。
您是否想在尝试拓扑排序之前检查它确实是DAG?好吧,拓扑排序的技巧是,如果有一个循环,它会自动失败。因此拓扑排序本身就是对DAGness的测试(我认为没有更简单的测试)。因此,不要先测试图形是否为DAG,而只是尝试拓扑排序。如果你成功了,它就是一个DAG,如果你失败了,你就完成了,它不是DAG而且你可以告诉用户,即你也完成了。
或者您是否要求提供可能描述DAG的输入文件(以便您可以在其上测试代码)?
如果我正确理解您的输入格式,则以下内容应为:
6 8
1 2
1 3
2 3
2 5
3 6
4 5
4 6
5 6
它应描述以下图表:
1 ------> 2 -----
\ | \
\ | V
\ | 4 -> 5
\ | \ |
\ V V V
---> 3 ----> 6
(我希望你可以理解我的ASCII艺术)