Cod sursa(job #890195)

Utilizator daniel.florinPitis Daniel-Florin daniel.florin Data 24 februarie 2013 21:50:09
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.69 kb
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;

bool vis[100005];
vector <int> G[100005];

int main()
{
	int n,m,i,x,y,rez = 0;
	queue<int> q;
	freopen("dfs.in","r",stdin);
	freopen("dfs.out","w",stdout);
	scanf("%d %d",&n, &m);

	for(i=1; i<=m; i++)
	{
		scanf("%d %d",&x, &y);
		G[x].push_back(y);
		G[y].push_back(x);
	}
	for (i=1;i<=n;i++) if (!vis[i])
	{
		rez++;
		vis[i] = true;
		q.push(i);
		while(!q.empty())
		{
			int fr=q.front();
			for(int i=0; i<G[fr].size(); i++)
				{
					if(vis[G[fr][i]]==false)
					{
						q.push(G[fr][i]);
						vis[G[fr][i]]=true;
					}
				}
			q.pop();
		}
	}
	printf("%d",rez);
	return 0;
}