Problem Description
设有向图G,现给出其邻接矩阵,要求将其转化为邻接表(采用头插法存边)进行存储。
Input
输入数据有多组
每组数据第一行为一个正整数n(0<n<=50),代表G的顶点数目
接下来有n行,为有向图G的邻接矩阵
Output
对于每组数据,输出有若干行,为该有向图中所有顶点的出边信息(空表不输出任何信息),每行最后均无空格,每两组数据之间有一空行,具体格式见样例。
Sample Input
3 0 0 1 0 0 0 1 0 0 4 0 1 0 1 1 0 1 0 1 0 0 1 0 0 0 0
Sample Output
0->2 2->0 0->3->1 1->2->0 2->3->0
#include <iostream>
#include <stdlib.h>
#define maxvex 20
#include<stdio.h>
using namespace std;
typedef struct {
int adjvex;
} ArcCell[maxvex][maxvex];
typedef struct {
ArcCell arc;
int vertexnum,arcnum;
char vex[maxvex];
} MatrixGraph;
struct ArcNode {
int adjvex;
ArcNode* next;
};
typedef struct Edge {
char vertex;
ArcNode *firstedge;
} EdgeList[maxvex];
typedef struct {
EdgeList adjlist;
int vertexnum,arcnum;
} GraphList;
void CreatList(GraphList &G,int n,int e) {
G.arcnum=e;
G.vertexnum=n;
for(int i=0; i<G.vertexnum; i++) {
cin>>G.adjlist[i].vertex;
G.adjlist[i].firstedge=NULL;
}
for(int i=0; i<G.arcnum; i++) {
int a,b;
cin>>a>>b;
ArcNode* p=new ArcNode;
p->adjvex=b;
p->next=G.adjlist[a].firstedge;
G.adjlist[a].firstedge=p;
}
}
int Locate(GraphList G,char v) {
int inedx=-1;
for(int i=0; i<G.vertexnum; i++) {
if(G.adjlist[i].vertex==v) {
inedx=i;
break;
}
}
return inedx;
}
void CreatMat(MatrixGraph& G,int n) {
int e=0;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
cin>>G.arc[i][j].adjvex;
if(G.arc[i][j].adjvex) e++;
}
}
G.arcnum=e;
G.vertexnum=n;
}
void MatToList(GraphList& g2,MatrixGraph &g1) {
g2.arcnum=g1.arcnum;
g2.vertexnum=g1.vertexnum;
for(int i=0; i<g1.vertexnum; i++) {
g2.adjlist[i].firstedge=NULL;
for(int j=0; j<g1.vertexnum; j++) {
if(g1.arc[i][j].adjvex) {
ArcNode* p=new ArcNode;
p->adjvex=j;
p->next= g2.adjlist[i].firstedge;
g2.adjlist[i].firstedge=p;
}
}
}
}
void print(GraphList g) {
for(int i=0; i<g.vertexnum; i++) {
if(g.adjlist[i].firstedge)
cout<<i;
for(ArcNode* p=g.adjlist[i].firstedge; p; p=p->next) {
cout<<"->"<<p->adjvex;
}
if(g.adjlist[i].firstedge)
cout<<endl;
}
}
int main() {
int n,e;
int count=0;
while(cin>>n) {
if(count)cout<<endl;
MatrixGraph g;
CreatMat(g,n);
GraphList g2;
MatToList(g2,g);
print(g2);
count++;
}
return 0;
}