Reputation: 1795
i correctly coded this question and get accepted in 0.39 sec using bfs algorithm
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. Some body please explain.
i simply understand that he did not used bfs or dfs algorithm. 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;
}
Upvotes: 0
Views: 828
Reputation: 71019
This code uses disjoint 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:
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.
Upvotes: 2