Cod sursa(job #359172)

Utilizator cristiprgPrigoana Cristian cristiprg Data 25 octombrie 2009 23:07:47
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <cstdio>
#include <vector>
#define DIM 100005
#define pb push_back
using namespace std;

vector <int> A[DIM], v;
int n, m, count;

void DFS(int start)
{
    v[start] = 1;


    for (int i = 1; i <= A[start][0]; i++)
        if (!v[A[start][i]])
        {

            DFS(A[start][i]);
        }
}

int main()
{
    FILE *f = fopen("dfs.in", "r");
    fscanf(f, "%d%d", &n, &m);

    int i, x, y;
    for (i = 1; i <= n; i++)
        A[i].pb(0), v.pb(0);

    for (i = 1; i <= m; i++)
    {
        fscanf(f, "%d%d", &x, &y);
        A[x].pb(y);
        A[x][0]++;

        A[y].pb(x);
        A[y][0]++;

    }

    fclose(f);

    for (i = 1; i <= n; i++)
        if (!v[i])
            count++, DFS(i);

    f = fopen("dfs.out", "w");
    fprintf(f, "%d\n", count);
    fclose(f);

    return 0;
}

/*
#include <stdio.h>

int a[1005][1005], n, m, viz[1005], cnt;

void citire()
{
	freopen("dfs.in","r",stdin);
	freopen("dfs.out","w",stdout);
	scanf("%d %d",&n,&m);
	int i, x, y;
	for (i = 1; i <= m; i++)
	{
		scanf("%d %d",&x,&y);
		a[x][y] = a[y][x] = 1;
	}
}

void DFS(int nod)
{
	int i;
	viz[nod] = 1;
	for (i = 1; i <= n; i++) if (!viz[i] && a[nod][i]) DFS(i);
}

int main()
{
	citire();
	int i;
	for (i = 1; i <= n; i++) if (!viz[i]) { cnt++; DFS(i);}
	printf("%d\n",cnt);
	return 0;
}
*/