今天拿起来了小白书,开始仔细的过一过。
连通分量问题:
编写一个程序,输入QQ的好友关系,判断从指定任务出发是否能通过盆友链抵达目标任务。
(题目实在懒得写,拍了张照片)
关于这个问题,其实不难,是一个简单的无向图**(不一定连通哦)**,查找两个点之间是否连通,书本上给了一种解法,然后我把它打出来,发现觉得些许有些麻烦。
测试用例:
10 9
0 1
0 2
3 4
5 7
5 6
6 7
6 8
7 8
8 9
3
0 1
5 9
1 3
书上代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
static const int MAX = 100000;
static const int NIL = -1;
int n;
vector<int> G[MAX];
int color[MAX];
void dfs(int r,int c) {
stack<int> S;
S.push(r);
color[r] = c;
while(!S.empty()) {
int u = S.top();
S.pop();
for(int i = 0; i<G[u].size(); i++) {
if(color[G[u][i]] == NIL) {
color[G[u][i]] = c;
S.push(G[u][i]);
}
}
}
}
void assignColor() {
int id = 1;
for(int i=0; i<n; i++) color[i] = NIL;
//这里其实就是一个深度搜索,搜索所有连通着的点。
for(int u = 0; u<n; u++) {
if(color[u] == NIL) dfs(u,id++);
}
}
int main() {
int s,t,m,q;
cin>>n>>m;
int num = n;
for(int i = 0; i<m; i++) {
cin>>s>>t;
G[s].push_back(t);
G[t].push_back(s);
}
assignColor();
cin>>q;
for(int i = 0; i<q; i++) {
cin>>s>>t;
if(color[s] == color[t])
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
写完之后,发现自己以前写过相关问题,于是就把另一种写了些试一试。
代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
static const int MAX = 100000;
static const int NIL = -1;
int n;
//方法2
int Gro[100];
int findGroup(int x)
{
if(x==Gro[x])
return x;
return findGroup(Gro[x]);
}
int main() {
int s,t,m,q;
cin>>n>>m;
int num = n;
for(int i=1;i<=n;i++)
Gro[i] = i;
for(int i = 0; i<m; i++) {
cin>>s>>t;
int x = findGroup(s);
int y = findGroup(t);
if(x != y)
{
num--;
Gro[x] = Gro[y];
}
}
cin>>q;
for(int i = 0; i<q; i++) {
cin>>s>>t;
if(color[s] == color[t])
int x = findGroup(s);
int y = findGroup(t);
if(x != y)
cout<<"no"<<endl;
else
cout<<"yes"<<endl;
}
}
只写了一个函数,自认为比上面dfs简单一点。