# 【2020年天梯赛校选赛】7-14 战争地图!(邻接矩阵版本)

## 【2020年天梯赛校选赛】7-14 战争地图!(邻接矩阵版本)

8 8
1 2
1 4
2 3
4 3
3 5
5 7
5 6
5 8
3
3
5
7

2
4
1

#include <iostream>					//7-9 战争地图！（邻接矩阵版本）
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
const int MaxV = 1002;	//最大顶点数

int N, M;			//输入顶点数与边数
bool Vis[MaxV];		//标记是否访问

/*邻接表需要的结构定义*/
typedef struct ENode{
int v1, v2;
} * Edge;
};
typedef struct VNode{
typedef struct GNode{
int Nv, Ne;
} * LGraph;

void InsertEdge(LGraph G, Edge E)		//插入无向边
{
A->Next = G->L[E->v2].FirstEdge;
G->L[E->v2].FirstEdge = A;

A->Next = G->L[E->v1].FirstEdge;
G->L[E->v1].FirstEdge = A;
}

void DestroyGraph(LGraph G)				//释放内存
{
for (int i = 1; i <= G->Nv; i++)
while (G->L[i].FirstEdge)
{
A = G->L[i].FirstEdge;
G->L[i].FirstEdge = A->Next;
delete A;
}
delete G;
}

int BFS(int k, LGraph G)		//用BFS统计连通分量个数
{
int ans = 0;
Vis[k] = true;
queue<int> q;

for (int i = 1; i <= G->Nv; i++)
{
if(Vis[i])
continue;
q.push(i);
while (!q.empty())		//应用BFS搜索
{
int k = q.front();
q.pop();
A = G->L[k].FirstEdge;
while (A)
{
A = A->Next;
}
}
ans++;
}
return ans;
}

int main()
{
int x, y;
cin >> N >> M;
LGraph G = new GNode();
G->Nv = N, G->Ne = M;

Edge E = new ENode;
for (int i = 0; i < M; i++)
{
cin >> E->v1 >> E->v2;
InsertEdge(G, E);
}
delete E;		//记得释放内存

/*输入并测试*/
int T, k;
cin >> T;
while (T--)
{
cin >> k;
memset(Vis, false, sizeof(Vis));
cout << BFS(k, G) << endl;
}
DestroyGraph(G);	//释放图的内存

system("pause");
return 0;
}


08-20 8950

04-19 4866
08-16 2万+
10-21 6577
04-30 2167
05-29 1万+
07-01 1万+
04-30 5万+