Cod sursa(job #3146205)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 19 august 2023 09:41:57
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>
using namespace std;

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};

InParser in("dfs.in");
ofstream out("dfs.out");

pair <int, int> much[400001];
int last[100001];

bool viz[100001];

void dfs(int nod)
{
    viz[nod] = 1;
    for(int y = last[nod]; y > 0; y = much[y].second)
        if(!viz[much[y].first])
            dfs(much[y].first);
}

int main()
{
    int n, m, x, y;
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        in >> x >> y;
        much[2 * i - 1] = {y, last[x]};
        last[x] = 2 * i - 1;
        much[2 * i] = {x, last[y]};
        last[y] = 2 * i;
    }
    int cnt = 0;
    for(int i = 1; i <= n; i++)
        if(!viz[i])
        {
            dfs(i);
            cnt++;
        }
    out << cnt;
    return 0;
}