DS图—图的邻接矩阵存储及度计算

题目描述

 假设图用邻接矩阵存储。输入图的顶点信息和边信息,完成邻接矩阵的设置,并计算各顶点的入度、出度和度,并输出图中的孤立点(度为0的顶点)

--程序要求--

若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio

程序中若include多过一个头文件,不看代码,作0分处理

不允许使用第三方对象或函数实现本题的要求

输入

测试次数T,每组测试数据格式如下:

图类型  顶点数 (D—有向图,U—无向图)

顶点信息

边数

每行一条边(顶点1 顶点2)或弧(弧尾 弧头)信息

输出

每组测试数据输出如下信息(具体输出格式见样例):

图的邻接矩阵

按顶点信息输出各顶点的度(无向图)或各顶点的出度  入度  度(有向图)。孤立点的度信息不输出。

图的孤立点。若没有孤立点,不输出任何信息。

输入样例

2
D 5
V1 V2 V3 V4 V5
7
V1 V2
V1 V4
V2 V3
V3 V1
V3 V5
V4 V3
V4 V5
U 5
A B C D E
5
A B
A C
B D
D C
A D

输出样例

0 1 0 1 0
0 0 1 0 0
1 0 0 0 1
0 0 1 0 1
0 0 0 0 0
V1: 2 1 3
V2: 1 1 2
V3: 2 2 4
V4: 2 1 3
V5: 0 2 2
0 1 1 1 0
1 0 0 1 0
1 0 0 1 0
1 1 1 0 0
0 0 0 0 0
A: 3
B: 2
C: 2
D: 3
E

AC代码参考

#include<iostream>
using namespace std;
const int MaxLen=20;

class Graph{
	public:
		int VerNum;
		int Matrix[MaxLen][MaxLen];
		string Vertex[MaxLen];
		
		Graph(int v){
			VerNum=v;
			for(int i=0;i<VerNum;i++){
				cin>>Vertex[i];
			}
			
			for(int i=0;i<MaxLen;i++)
				for(int j=0;j<MaxLen;j++)
						Matrix[i][j]=0;
		}
		int find(string s){
			for(int i=0;i<VerNum;i++){
				if(s==Vertex[i])
					return i;
			}
		}
		void InsertMatrix(char type,string s1,string s2){
			int x,y;
			x=find(s1),y=find(s2);
			if(type=='D')
				Matrix[x][y]=1;
			else{
				Matrix[x][y]=1;
			  	Matrix[y][x]=1;
			}
		}
		void print(char type){
			int i,j,k,count;
			count=0;
			for(i=0;i<VerNum;i++){
				for(j=0;j<VerNum;j++){
					cout<<Matrix[i][j];
					count++;
					if(count%VerNum==0)
						cout<<endl;
					else
						cout<<" ";
				} 
			}
			if(type=='D'){
				int indegree,outdegree,sum;
				indegree=outdegree=sum=0;
				for(i=0;i<VerNum;i++){
					for(j=0;j<VerNum;j++)
					{
						if(Matrix[i][j]==1)
						outdegree++;
					}
				for(k=0;k<VerNum;k++){
					if(Matrix[k][i]==1)
						indegree++;
				}
				sum=outdegree+indegree;
				if(sum>0)
					cout<<Vertex[i]<<": "<<outdegree<<" "<<indegree<<" "<<sum<<endl;
				else
					cout<<Vertex[i]<<endl;
				indegree=outdegree=sum=0;
				} 
			}
			else{
				int degree;
				degree=0;
				for(i=0;i<VerNum;i++){
					for(j=0;j<VerNum;j++)
					{
						if(Matrix[i][j]==1)
						degree++;
					}
				if(degree>0)
					cout<<Vertex[i]<<": "<<degree<<endl;
				else
					cout<<Vertex[i]<<endl;
				degree=0;
				} 
			}
		}
};

int main(){
	int T,vnum,lnum;
	char type;
	string s1,s2;
	cin>>T;
	while(T--){
		cin>>type>>vnum;
		Graph g(vnum);
		cin>>lnum;
		while(lnum--){
			cin>>s1>>s2;
			g.InsertMatrix(type,s1,s2);
		}
			g.print(type);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值