//输入样例 /* 5 0 AB AD AC CD BE DE */ //输出 /* Please Input the edge x-->y:AB AD AC CD BE DE A 1 2 3 B 0 4 C 0 3 D 0 2 4 E 1 3 */ #include<iostream> #include<cstdio> using namespace std; #define MAXVER 10 typedef char Elemtype; //接下来要连的结点 typedef struct node{ int num; struct node *next; }slink; //首结点数组 typedef struct{ struct{ Elemtype vertex; slink *first; }ve[MAXVER]; int vex,edge,tag; }adjlist; //使用简单结构建立图的邻接表 void cregraph(adjlist *G,int n,int m) { G->vex=n; G->tag=m; int e=0; slink *s,*p,*q; for(int i=0;i<n;i++){ G->ve[i].vertex='A'+i; G->ve[i].first=NULL; } Elemtype x,y; printf("Please Input the edge x-->y:"); scanf("%c%c",&x,&y); while(x!=' '&&y!=' ') { e++; s=(slink *)malloc(sizeof(slink)); s->num=y-'A'; if(G->ve[x-'A'].first==NULL){ G->ve[x-'A'].first=s; s->next=NULL; } else{ p=G->ve[x-'A'].first; if(p->num>s->num){ s->next=p; G->ve[x-'A'].first=s; } else{ q=p->next; while(q!=NULL&&q->num<s->num) { p=q; q=q->next; } p->next=s; s->next=q; } } if(!G->tag) { s=(slink *)malloc(sizeof(slink)); s->num=x-'A'; if(G->ve[y-'A'].first==NULL) {G->ve[y-'A'].first=s;s->next=NULL;} else{ p=G->ve[y-'A'].first; if(p->num>s->num) {s->next=p;G->ve[y-'A'].first=s;} else{ q=p->next; while(q!=NULL&&q->num<s->num) {p=q;q=q->next;} p->next=s; s->next=q; } } } getchar(); scanf("%c%c",&x,&y); } G->edge=e; } //输出用邻接表表示的图的算法 void list(adjlist *G) { slink *p; for(int i=0;i<G->vex;i++) { p=G->ve[i].first; printf("%c",G->ve[i].vertex); while(p) { printf("%3d",p->num); p=p->next; } printf("\n"); } } int main() { adjlist *G; G=(adjlist *)malloc(sizeof(adjlist)); int n,m; scanf("%d%d",&n,&m); getchar(); cregraph(G,n,m); list(G); return 0; }
时间: 2024-10-31 22:41:49