描述
给定一个无向图,在此无向图中增加一条边。
输入
多组数据,每组m+2行。第一行有两个数字n和m,代表有n个顶点和m条边。顶点编号为1到n。第二行到第m+1行每行有两个数字h和k,代表边依附的两个顶点。第m+2行有两个数字f和g,代表增加的边所依附的两个顶点。当n和m都等于0时,输入结束。
输出
每组数据输出n行。为增加边后的邻接矩阵。每两个数字之间用空格隔开。
输入样例 1
3 2 1 2 2 3 3 1 3 1 1 2 1 3 0 0
输出样例 1
0 1 2 3 1 0 1 1 2 1 0 1 3 1 1 0 0 1 2 3 1 0 1 1 2 1 0 0 3 1 0 0
//基于邻接矩阵的新顶点的增加
#include <iostream>
#define MVNum 100//最大顶点数
using namespace std;
typedef struct{
int vexs[MVNum];//顶点表
int arcs[MVNum][MVNum];//邻接矩阵
int vexnum,arcnum;
}AMGraph;
void Create_V(AMGraph &G,int name){
int pos=++G.vexnum;
G.vexs[pos-1]=name;//存入点名
for(int i=1;i<=pos;i++){//点所在的行列清零
G.arcs[i-1][pos-1]=0;
G.arcs[pos-1][i-1]=0;
}
}
void Create_Arc(AMGraph &G,int h,int k){
G.arcs[h-1][k-1]=G.arcs[k-1][h-1]=1;//点与对称点都归1
}
void Out_Graph(AMGraph G){
cout<<"0 ";//开头输出0
for(int i=1;i<G.vexnum;i++) cout<<G.vexs[i-1]<<" ";//输出所有点名
cout<<G.vexs[G.vexnum-1]<<endl;
for(int i=1;i<=G.vexnum;i++){//输出所有弧
cout<<G.vexs[i-1]<<" ";
for(int j=1;j<G.vexnum;j++){
cout<<G.arcs[i-1][j-1]<<" ";
}
cout<<G.arcs[i-1][G.vexnum-1]<<endl;
}
}
void Calculate(int m,int n){
AMGraph G;
G.vexnum=G.arcnum=0;
for(int i=1;i<=m;i++) Create_V(G,i);//构造前n个顶点
for(int i=1;i<=n+1;i++){//构造n条边(再新增一条边 买n送1)
int h,k;
cin>>h>>k;//输入左右顶点
Create_Arc(G,h,k);//构造边
}
Out_Graph(G);//输出图
}
int main(){
int m,n;
while(cin>>m>>n&&m!=0&&n!=0){//每次处理一行数据
Calculate(m,n);
}
return 0;
}