1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int vertice; 6 int edge; 7 char i,j; 8 int s; 9 int a=0; 10 cout<<"请输入无向图的顶点数"<<endl; 11 cin>>vertice; 12 cout<<"请输入无向图的边数"<<endl; 13 cin>>edge; 14 char *ver1=new char[vertice]; 15 char *ver2=new char[vertice]; 16 int *degree=new int[vertice]; 17 int **array; 18 array=new int*[vertice]; 19 cout<<"请输入每个顶点元素"<<endl; 20 for(int p=0;p<vertice;p++) 21 { 22 cin>>ver1[p]; 23 ver2[p]=ver1[p]; 24 } 25 cout<<"请输入无向图的边,以0结束"<<endl; 26 for(int K=0;K<edge;K++) 27 { 28 array[K]=new int[edge]; 29 } 30 for(p=0;p<vertice;p++) 31 { 32 for(int q=0;q<vertice;q++) 33 array[p][q]=0;//先给邻接矩阵中的每个元素赋值为0 34 } 35 while(true) 36 { 37 cin>>i; 38 if(i==‘0‘)//注意一定要加单引号!! 39 break; 40 else 41 { 42 for(int p=0;p<vertice;p++)//构造邻接矩阵 43 { 44 if(ver1[p]==i) 45 { 46 cin>>j; 47 s=p; 48 p=vertice; 49 } 50 } 51 for(int q=0;q<vertice;q++) 52 { 53 if(ver2[q]==j) 54 { 55 array[s][q]=array[s][q]+1; 56 array[q][s]=array[q][s]+1; 57 q=vertice; 58 }//记录两点之间的边数 59 } 60 } 61 } 62 cout<<"该邻接矩阵为:"<<endl;//输出邻接矩阵 63 64 for(p=0;p<vertice;p++) 65 { 66 for(int q=0;q<vertice;q++) 67 68 cout<<array[p][q]<<" "; 69 70 cout<<endl; 71 72 } 73 74 for(i=0;i<vertice;i++) 75 degree[i]=0; 76 for(i=0;i<vertice;i++) 77 { 78 for(int j=0;j<vertice;j++) 79 degree[i]+=array[i][j]; 80 } 81 for( i=0;i<vertice;i++) 82 cout<<degree[i]<<endl; 83 84 85 86 system("pause"); 87 }
时间: 2024-10-24 13:53:27