简体   繁体   English

无向图中的连接组件

[英]Connected Components in an undirected graph

i correctly coded this question and get accepted in 0.39 sec using bfs algorithm 我正确编码了这个问题,并使用bfs算法在0.39秒内被接受

here's my code 这是我的代码

#include<iostream>
#include<vector>
#include<string.h>
#include<cstdio>
#include<queue>
using namespace std;

int main()
{
queue<int>q;
bool visited[100000];
int t,i,j,x,y;
int n,e;
cin>>t;
while(t--)
{
scanf("%d%d",&n,&e);
vector< vector<int> >G(n);
memset(visited,0,sizeof(visited));

for(i=0;i<e;i++)
{
scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}

int ans=0;
for(i=0;i<n;i++)
{
if(!visited[i])
{
q.push(i);
visited[i]=1;

while(!q.empty())
{
int p=q.front();
q.pop();
for(j=0;j<G[p].size();j++)
{
if(!visited[G[p][j]])
{
visited[G[p][j]]=1;
q.push(G[p][j]);
}
}
}
ans++;
}
}
printf("%d\n",ans);
}
}

but then i checked another accepted code in 0.15 sec i don't understand what he has done. 但是后来我在0.15秒内检查了另一个可接受的代码,我不知道他做了什么。 Some body please explain. 有些身体请解释。

i simply understand that he did not used bfs or dfs algorithm. 我只是了解他没有使用bfs或dfs算法。 and why his method got accepted in lesser time. 以及为什么他的方法在较短的时间内被接受。

here's is his code 这是他的代码

#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;

int p[100001];


int find( int a)
{
int root = a;
while ( p[a] != a) {
    a = p[a];
}
while ( root != a) {

  int root2 = p[root];
  p[root] = a;
  root = root2;
}   

return a;

} }

int main()
  {
int t;

scanf("%d",&t);
while ( t-- ) {
    int n,m,a,b,q;

    scanf("%d%d",&n,&m);
    for ( int i = 0; i < n; i++) 
        p[i] = i;

    //int count = n;

    for ( int i = 0; i < m;i++) {

        scanf("%d%d",&a,&b);
        int root = find(a);
        int root2 = find(b);
        p[root2] = root;

    }
    int count = 0;
    for ( int i = 0; i < n;i++) {
        if ( p[i] == i)
          count++;

    }
    printf("%d\n",count);
}
return 0;

} }

This code uses disjoint set forest . 这段代码使用了不相交的set forest A very efficient data structure that is able to perform union-find. 一种非常有效的数据结构,能够执行联合查找。 In essence the user has a set of sets and can perform two operations: 本质上,用户具有一组集合,并且可以执行两个操作:

  • join two sets 合二套
  • check which set the element belongs to 检查元素属于哪个集合

The algorithm above also uses one important heuristics - path compression. 上面的算法还使用一种重要的启发式方法-路径压缩。 Usually disjoint set is implement using one more heuristics - union by rank but the author decided not to use it. 通常,不相交集是使用一种或多种启发式实现的工具-按等级联合,但作者决定不使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM