mission details
Given an undirected graph, add a new vertex to this undirected graph.
programming requirements
Input
multiple sets of data, each set of m+2 lines. The first line has two numbers n and m, representing n vertices and m edges. The vertices are numbered 1 to n. There are two numbers h and k in each line from the second line to the m+1th line, representing the two vertices to which the edge is attached. Line m+2 has a number f representing the newly inserted vertex number. When both n and m are equal to 0, the input ends.
Output
Each set of data outputs n+1 lines. It is the adjacency list after adding vertices. Separate each two numbers with a space.
Test instructions
The platform will test the code you write:
Test input:
3 2
1 2
2 3
4
2 1
1 2
4
0 0
Expected output:
1 2
2 3 1
3 2
4
1 2
2 1
4
C code
h file
#include<iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MVNum 100
using namespace std;
typedef struct VNode{
int data;
struct VNode *next;
}VNode,*NodeList;
typedef struct{
NodeList V[MVNum];
int vexnum,arcnum;
}ALGragh ;
int CreateUDG(ALGragh &G,int vexnum,int arcnum){
G.vexnum = vexnum;
G.arcnum = arcnum;
for(int i=1;i<=vexnum; i ++){
G.V[i] = new VNode;
G.V[i]->next = NULL;
G.V[i]->data = i;
}
for(int i=0;i<arcnum;i++){
int v1,v2;
cin>>v1>>v2;
NodeList p1 =new VNode;
p1->data =v2;
p1->next =G.V[v1]->next;
G.V[v1]->next = p1;
NodeList p2 =new VNode;
p2->data = v1;
p2->next = G.V[v2]->next;
G.V[v2]->next = p2;
}
return OK;
}
int InsertVex(ALGragh &G){
int data;
cin>>data;
G.vexnum++;
G.V[G.vexnum] = new VNode;
G.V[G.vexnum]->data = data;
G.V[G.vexnum]->next = NULL;
return OK;
}
int PrintGraph(ALGragh G){
for(int i=1;i<=G.vexnum;i++){
NodeList p =G.V[i];
while(p->next){
cout<<p->data<<" ";
p = p->next;
}
cout<<p->data<<endl;
}
return OK;
}
The main function file is not editable
#include<iostream>
#include "275.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MVNum 100 //最大顶点数
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m)
{
if(n==0&&m==0) break; //输入结束标志
ALGragh G;
CreateUDG(G,n,m); //采用邻接表表示法,创建无向图G
InsertVex(G); //在图G中增添新顶点
PrintGraph(G); //输出图G
}
return 0;
}