图的应用

从键盘或文件读入有向图的顶点信息和弧信息(输入格式自拟);
建立有向图的十字链表存储结构;

利用拓扑排序方法判断该图是否为有向无环图。


#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <bitset>
#include <list>
#include <sstream>
#include <set>
#include <functional>
using namespace std;

#define maxn 200
typedef char vtype;
typedef struct Anode
{
    int tail,head;
    struct Anode*hlink,*tlink;
}arcnode;
typedef struct Vnode
{
    vtype data;
    arcnode *fin,*fout;
}vexnode;
vexnode G[maxn];
int m;

void createorlist(vexnode G[maxn])
{
    int i,j;
    arcnode *p;
    vtype ch,u,v;
    i = m = 0;
    printf("Please input nodes:");
    ch = getchar();
    while(ch!='#')
    {
        m++;
        G[i].data = ch;
        G[i].fin = G[i].fout = NULL;
        i++;
        ch = getchar();
    }
    getchar();
    printf("Please input roads:");
    scanf("%c %c",&u,&v);
    getchar();
    while(u!='#')
    {
        for(int k = 0; k < m; k++){
            if(G[k].data==u){i = k;break;}
        }
        for(int k = 0; k < m; k++){
            if(G[k].data==v){j = k;break;}
        }
        p = (arcnode*)malloc(sizeof(arcnode));
        p->tail = i;
        p->head = j;
        p->hlink = G[j].fin;
        G[j].fin = p;
        p->tlink = G[i].fout;
        G[i].fout = p;
        scanf("%c %c",&u,&v);
        getchar();
    }
}

void Creatid(vexnode G2[maxn],int n,int id[maxn])
{
    int count,i;
    arcnode *p;
    for(i = 0; i < n; i++)
    {
        count = 0;
        p = G2[i].fin;
        while(p)
        {
            count ++;
            p = p->hlink;
        }
        id[i] = count;
    }
}

void Topsort(vexnode G1[maxn],int n)
{
    stack <int> s;
    int i,j,k,count,id[maxn];
    arcnode *p;
    Creatid(G1,n,id);
    while(!s.empty()) s.pop();
    for(i = 0; i < n; i++)
        if(id[i]==0)
            s.push(i);
    count = 0;
    while(!s.empty())
    {
        j = s.top();
        s.pop();
        printf("%d %c\n",j,G1[j].data);
        count++;
        p = G1[j].fout;
        while(p)
        {
            k = p->head;
            id[k]--;
            if(id[k]==0)
                s.push(k);
            p = p->tlink;
        }
    }
    if(count == n)
        printf("This graph has not cycle\n");
    else
        printf("This graph has cycle\n");
}

int main()
{
    createorlist(G);
    Topsort(G,m);
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值