Problem Description
设有一有向图,其顶点值为字符型并假设各值互不相等,采用邻接表表示法存储表示。设计一个算法,求该图中所有顶点的入度值(要求按顶点的存储顺序输出)。
Input
有多组测试数据,每组数据的第一行表示图的顶点数n和图的边数e(0<n<30);第二行表示各顶点的值,按输入顺序进行存储;接下来有e行,每一行表示每条边所依附的顶点的存储下标i和j,两个下标之间用空格隔开。
Output
每组输出占一行,按顶点的存储顺序输出各顶点的入度值,要求每两个入度值之间有一空格。
Sample Input
4 4 ABCD 0 1 0 3 1 2 1 3
Sample Output
0 1 1 2
#include <iostream>
#include <stdlib.h>
#define maxvex 20
#include<stdio.h>
using namespace std;
typedef struct {
int adjvex;
} ArcCell,ArcCells[maxvex][maxvex];
typedef struct {
char vertex[maxvex];
ArcCells arcs;
int arcnum,vexnum;
} MatrixGraph;
struct ArcNode {
int adj;
ArcNode* next;
};
typedef struct {
ArcNode* firstedge;
char vex;
} Edge,Edges[maxvex];
typedef struct {
Edges edges;
int arcnum,vertexnum;
int deg[maxvex];
} Graph;
void CreatDG(Graph&G,int n,int e) {
G.arcnum=e;
G.vertexnum=n;
for(int i=0; i<n; i++) {
cin>>G.edges[i].vex;
G.edges[i].firstedge=NULL;
G.deg[i]=0;
}
for(int i=0; i<e; i++) {
int a,b;
cin>>a>>b;
ArcNode* p=new ArcNode;
p->adj=b;
p->next=G.edges[a].firstedge;
G.edges[a].firstedge=p;
}
}
void Deg(Graph& G) {
for(int i=0; i<G.vertexnum; i++) {
ArcNode* p=G.edges[i].firstedge;
while(p) {
G.deg[p->adj]++;
p=p->next;
}
}
}
void Print(Graph G) {
for(int i=0; i<G.vertexnum; i++) {
ArcNode* p=G.edges[i].firstedge;
while(p) {
cout<<p->adj<<" ";
p=p->next;
}
cout<<endl;
}
}
void CreatUDM(MatrixGraph &G,int n,int e) {
G.arcnum=e;
G.vexnum=n;
for(int i=0; i<G.vexnum; i++) {
cin>>G.vertex[i];
for(int j=0; j<G.vexnum; j++) {
G.arcs[i][j].adjvex=0;
}
}
for(int i=0; i<G.arcnum; i++) {
int a,b;
cin>>a>>b;
G.arcs[a][b].adjvex=1;
G.arcs[b][a].adjvex=1;
}
}
bool vistited[maxvex];
void InitVistied() {
for(int i=0; i<maxvex; i++) {
vistited[i]=false;
}
}
void MatrixDFSTraverse(MatrixGraph G,int v) {
vistited[v]=true;
cout<<G.vertex[v]<<":";
for(int j=0; j<G.vexnum; j++) {
if(G.arcs[v][j].adjvex!=0) {
cout<<G.vertex[j];
}
}
cout<<endl;
for(int i=0; i<G.vexnum; i++) {
if(!vistited[i]&&G.arcs[v][i].adjvex!=0) {
MatrixDFSTraverse(G,i);
}
}
}
int main() {
int n,e;
while(cin>>n>>e) {
Graph g;
CreatDG(g,n,e);
Deg(g);
for(int i=0; i<g.vertexnum-1; i++) {
cout<<g.deg[i]<<" ";
}
cout<<g.deg[g.vertexnum-1]<<endl;
}
return 0;
}