编程实现:以邻接表的存储方式,创建一个有向网,顶点为字符型。

输入格式:

第一行输入顶点个数和边的个数,中间用空格分开。下一行开始依次输入顶点,空格或回车分开。接着依次输入边依附的两个顶点和权值,空格分开。

输出格式:

若数据合理,则输出对应的邻接表形式,见样例,邻接点下标与权值空格分开。若顶点个数为0,则输出”error”。若顶点个数为1,边个数不合理,则输出”error”

输入样例:

在这里给出一组输入。例如:

4 4
a b c d
a b 1
a c 1
c d 1
d a 1
 

输出样例:

在这里给出相应的输出。例如:

a->2 1->1 1
b
c->3 1
d->0 1

#include<iostream>
using namespace std;
#define MVNum 1000
typedef char VerTexType;
typedef int ArcType;
typedef struct ArcNode           //边节点
{
    int adjvex;                  //边所指顶点位置
    struct ArcNode * nextarc;    //下一条边
    int info;
}ArcNode;
 
typedef struct VNode              //顶点
{
    VerTexType data;
    ArcNode *firstarc;             //该点的第一条指针
}VNode,AdjList[MVNum];             //AdjList表示邻接表类型

typedef struct                     //邻接表
{
    AdjList vertices;
    int vexnum,arcnum;             // 顶点数和边数
}ALGraph;

int LocateVex(ALGraph &G , VerTexType v)
{
    for(int i = 0 ; i < G.vexnum ; i++)
        if(G.vertices[i].data == v)
            return i;
}

void CreateUDG(int vnum,int anum,ALGraph &G)
{
   G.vexnum = vnum;
   G.arcnum = anum;
    
    for(int i = 0 ; i < G.vexnum ; ++i)
    {
        cin>>G.vertices[i].data;           //顶点
        G.vertices[i].firstarc = NULL;     //初始化表头
    }

    for(int k = 0 ; k < G.arcnum ; k++)
    {
        VerTexType v1,v2;
        cin>>v1>>v2;
        int i = LocateVex(G,v1);
        int j = LocateVex(G,v2);
        
        ArcNode *p = new ArcNode;                   //生成新节点
        p->adjvex = j;                     //邻接点序号
        p->nextarc = G.vertices[i].firstarc;
        cin>>p->info;
        G.vertices[i].firstarc = p;
    }
}

void show(ALGraph &G)
{
     for(int i=0 ; i<G.vexnum; i++)
     {
        cout<<G.vertices[i].data;
        ArcNode* p = G.vertices[i].firstarc;
        
        while(p!=NULL){
            cout<<"->"<<p->adjvex<<' '<<p->info;
            p=p->nextarc;
        }
        if(i!=G.vexnum-1) cout<<endl;
    }
}
int main()
{
    int vnum,anum;
    cin>>vnum>>anum;
    if(vnum == 0)
    {
        cout<<"error";
        return 0;
    } 
    if(vnum == 1 && anum > 0)
    {
        cout<<"error";
        return 0;
    }
    ALGraph G;
    CreateUDG(vnum,anum,G);
    show(G);
    return 0;
}

 

原文地址:http://www.cnblogs.com/fan-wang/p/16888776.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性