Is Topological Order pta 6-29

先讲思路,答案是第一段代码,题目在最后;

插个图方便理解:

这道题属于拓扑排序的运用,可以用拓扑排序的思路做,but,我的代码用了更简洁的思路:遍历Seq的每一个元素 Seq[ i ] 并确定其在 图Graph 中对应的下标 v ,collected[v]=1(收集v);  p=Graph->G[v].FirstEdge,遍历(p=p->Next)同时判断p包括p之后的每一个Next是否有collected[p->AdjV]==1,若有则说明v指向的点中有已收集的,比如:5 2 1 3 6;i=2时v对应图中1(此时5和2都已经被收集),1指向2和3,而2已被收集,说明不是拓扑排序,return false;

答案代码如下:

//直接把seq带进去   seq[i]标记收集,
//i对应的每一个点走到,如果遍历i指向的点时遇到已经收集的点就return false 
bool IsTopSeq( LGraph Graph, Vertex Seq[] ){
	PtrToAdjVNode p;
	int collected[MaxVertexNum],i,v;
//标记已收集的边,注意这道题的不能定义在函数外面,因为题目一个main里调了好几次 
	for(i=0;i<MaxVertexNum;i++){
		collected[i]=0;
	}
	for(int i=0;i<Graph->Nv;i++){
		int v=Seq[i]-1;
		collected[v]=1;
		p=Graph->G[v].FirstEdge;//注意v-1 
		while(p){
			if(collected[p->AdjV]) return false;
			p=p->Next;
		}
	} 
	return true;
}

题目:

Write a program to test if a give sequence Seq is a topological order of a given graph Graph.

Format of functions:

 

bool IsTopSeq( LGraph Graph, Vertex Seq[] );

where LGraph is defined as the following:

 

typedef struct AdjVNode *PtrToAdjVNode; struct AdjVNode{ Vertex AdjV; PtrToAdjVNode Next; }; typedef struct Vnode{ PtrToAdjVNode FirstEdge; } AdjList[MaxVertexNum]; typedef struct GNode *PtrToGNode; struct GNode{ int Nv; int Ne; AdjList G; }; typedef PtrToGNode LGraph;

The function IsTopSeq must return true if Seq does correspond to a topological order; otherwise return false.

Note: Although the vertices are numbered from 1 to MaxVertexNum, they are indexed from 0 in the LGraph structure.

Sample program of judge:

 
#include <stdio.h>
#include <stdlib.h>

typedef enum {false, true} bool;
#define MaxVertexNum 10  /* maximum number of vertices */
typedef int Vertex;      /* vertices are numbered from 1 to MaxVertexNum */

typedef struct AdjVNode *PtrToAdjVNode; 
struct AdjVNode{
    Vertex AdjV;
    PtrToAdjVNode Next;
};

typedef struct Vnode{
    PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];

typedef struct GNode *PtrToGNode;
struct GNode{  
    int Nv;
    int Ne;
    AdjList G;
};
typedef PtrToGNode LGraph;

LGraph ReadG(); /* details omitted */

bool IsTopSeq( LGraph Graph, Vertex Seq[] );

int main()
{
    int i, j, N;
    Vertex Seq[MaxVertexNum];
    LGraph G = ReadG();
    scanf("%d", &N);
    for (i=0; i<N; i++) {
        for (j=0; j<G->Nv; j++)
            scanf("%d", &Seq[j]);
        if ( IsTopSeq(G, Seq)==true ) printf("yes\n");
        else printf("no\n");
    }

    return 0;
}

/* Your function will be put here */

Sample Input (for the graph shown in the figure):

topord.JPG

6 8
1 2
1 3
5 2
5 4
2 3
2 6
3 4
6 4
5
1 5 2 3 6 4
5 1 2 6 3 4
5 1 2 3 6 4
5 2 1 6 3 4
1 2 3 4 5 6

Sample Output:

yes
yes
yes
no
no

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值