Connected Components
Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.
Input
In the first line, two integer nn and mm are given. nn is the number of users in the SNS and mm is the number of relations in the SNS. The users in the SNS are identified by IDs 0,1,...,n−10,1,...,n−1.
In the following mm lines, the relations are given. Each relation is given by two integers ss and tt that represents ss and tt are friends (and reachable each other).
In the next line, the number of queries qq is given. In the following qq lines, qq queries are given respectively. Each query consists of two integers ss and tt separated by a space character.
Output
For each query, print "yes" if tt is reachable from ss through the social network, "no" otherwise.
Constraints
- 2≤n≤100,0002≤n≤100,000
- 0≤m≤100,0000≤m≤100,000
- 1≤q≤10,0001≤q≤10,000
Sample Input
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
Sample Output
yes yes no
用vector做邻接表处理,通过的代码:
#include<iostream>
#include<vector>
#include<stack>
#include<cstdio>
using namespace std;
const int N=1e5+10;
int ne[N],h[N],e[N];
int idx;
int n,m,flag;
int color[N];
vector<int> g[N];
//void addedge(int a,int b){
// e[idx]=b;
// ne[idx]=h[a];
// h[a]=idx++;
//}
void dfs(int k,int u){
color[k]=u;
stack<int> s;
s.push(k);
while(!s.empty()){
int v=s.top(); s.pop();
for(int i=0;i<g[v].size();i++){
int j=g[v][i];
if(color[j]==0) {
color[j]=u;
s.push(j);
}
}
}
// for(int i=h[k];i!=-1;i=ne[i]){
// int j=e[i];
// if(color[j]==0) dfs(j,u);
// }
}
int main(){
scanf("%d%d",&n,&m);;
for(int i=0;i<n;i++) h[i]=-1;
for(int i=0;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
g[a].push_back(b);
g[b].push_back(a);
// addedge(a,b);
// addedge(b,a);
}
for(int i=0;i<n;i++){
if(color[i]==0) dfs(i,++flag);
}
int q;
scanf("%d",&q);
while(q--){
int a,b;
scanf("%d%d",&a,&b);;
if(color[a]==color[b]) printf("yes\n");
else printf("no\n");
}
return 0;
}
用数组的邻接表不能通过大数点:
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int N=1e5+10;
int ne[N],h[N],e[N];
int idx;
int n,m,flag;
int color[N];
void addedge(int a,int b){
e[idx]=b;
ne[idx]=h[a];
h[a]=idx++;
}
void dfs(int k,int u){
color[k]=u;
stack<int> s;
s.push(k);
while(!s.empty()){
int v=s.top(); s.pop();
for(int i=h[v];i!=-1;i=ne[i]){
int j=e[i];
if(color[j]==0){
color[j]=u;
s.push(j);
}
}
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) h[i]=-1;
for(int i=0;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
addedge(a,b);
addedge(b,a);
}
for(int i=0;i<n;i++){
if(color[i]==0) dfs(i,++flag);
}
int q;
scanf("%d",&q);
while(q--){
int a,b;
scanf("%d%d",&a,&b);
if(color[a]==color[b]) printf("yes\n");
else printf("no\n");
}
return 0;
}
猜想:vector的速度比普通数组要快(但是在网络上查询得到的测试结果却是反的???)