Cod sursa(job #169968)

Utilizator znakeuJurba Andrei znakeu Data 2 aprilie 2008 11:51:04
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <stdio.h>
#include <algorithm> 
#define MAXN 100500
#define MAXM 500000

using namespace std; 

struct muchie 
{
	int x,y;	
};

bool cmp(muchie a, muchie b)  
{  
    if (a.x==b.x)  
        return a.y<b.y;  
    return a.x<b.x;    
}  

muchie a[MAXM],p[MAXN];
int v[MAXN],n,m,wtf[MAXN],wtfN,R=1,r[MAXN];


void citire()
{
	char s[20];
	int x,y,i,j;
	fgets(s,20,stdin);
	
	x=0; y=0; i=0;
	while (s[i]>='0' && s[i]<='9')
		x=x*10+s[i++]-'0';
	i++;
	while (s[i]>='0' && s[i]<='9')
		y=y*10+s[i++]-'0';
	n=x; m=y;
	
	for (i=0; i<m; i++)
	{
		fgets(s,20,stdin);
		x=0; y=0; j=0;
		while (s[j]>='0' && s[j]<='9')
			x=x*10+s[j++]-'0';
		j++;
		while (s[j]>='0' && s[j]<='9')
			y=y*10+s[j++]-'0';
		a[2*i].x=x; a[2*i].y=y;
		a[2*i+1].x=y; a[2*i+1].y=x;		
	}
	m*=2;
	
	sort(a,a+m,cmp);
	
	p[1].x=0;
	for (i=0,j=1; i<m;)
	{
		
		while (a[i].x==j && i<m)
			i++;
		p[j].y=i; j++;
		while (a[i].x!=j && j<n)
		{
			p[j].x=p[j].y=i;
			j++;			
		}
		p[j].x=i;
	}
	p[j].y=i;
}

void rez()
{
	for (int i=0; i<wtfN; i++)
		for (int j=p[wtf[i]].x; j<p[wtf[i]].y; j++)
			if (r[a[j].y]==0)
			{
				r[a[j].y]=R;
				wtf[wtfN++]=a[j].y;
			}
}

void rezolvare()
{
	for (int i=1; i<=n; i++)
		if (r[i]==0)
		{
			r[i]=R;
			wtfN=1;
			wtf[0]=i;
			rez();
			R++;
		}
}

void afisare()
{
	printf("%d\n",R-1);	
}

int main()
{
	freopen("dfs.in","r",stdin);
	freopen("dfs.out","w",stdout);
	
	citire();
	rezolvare();
	afisare();	
	
	fclose(stdin);
	fclose(stdout);
	return 0;
}