Description
输入一个简单无向图,求出图中连通块的数目。
Input
输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。
以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。
Output
单独一行输出连通块的数目。
题目解释:就是对于无向图,求出连通块数
解题思路:使用容器 map<int, vector<int> >,其实map的key是节点标号,vector<int> 是以key节点标号为一边的另一边节点标号。最后通过遍历标记节点,同一个连通块的标记是一样的。
#include <iostream>
#include <map>
#include <vector>
#include <stack>
#include <string.h>
using namespace std;
int class_map[1005];
int main(int argc, const char * argv[]) {
// insert code here...
int nodeNum, edgeNum;
cin >> nodeNum >> edgeNum;
map<int, vector<int> > graph;
memset(class_map, -1, sizeof(class_map));
for (int i = 0; i < edgeNum; i++) {
int v,y;
cin >> v >> y;
graph[v].push_back(y);
graph[y].push_back(v);
}
int result = 0;
stack<int> st;
map<int, vector<int> >::iterator it ;
for (it = graph.begin(); it != graph.end(); it++) {
if (class_map[it->first] == -1) {
result++;
st.push(it->first);
// class_map[it->first] = result;
while (!st.empty()) {
int topnum = st.top();
st.pop();
class_map[topnum] = result;
for (int i = 0; i < graph[topnum].size(); i++) {
if (class_map[graph[topnum][i]] == -1) {
class_map[graph[topnum][i]] = result;
}
}
}
}
else continue;
}
cout << result << endl;
return 0;
}