Pagini recente » Cod sursa (job #2842082) | Clasament tema_vacanta_sambata_14.30 | Cod sursa (job #772363) | Cod sursa (job #1827905) | Cod sursa (job #2475121)
#include <bits/stdc++.h>
#include <fstream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
ofstream fout("ctc.out");
const int NMAX = 100010;
vector<pair<int,bool>> graf[NMAX];
bool viz[NMAX];
bool vizPlus[NMAX],vizMinus[NMAX];
vector<vector<int>> comps;
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;
}
};
void dfsPlus(int node)
{
for(int i = 0; i<graf[node].size(); i++)
{
if(!vizPlus[graf[node][i].first]&&graf[node][i].second&&!viz[graf[node][i].first])
{
vizPlus[graf[node][i].first] = true;
dfsPlus(graf[node][i].first);
}
}
}
void dfsMinus(int node)
{
for(int i = 0; i<graf[node].size(); i++)
{
if(!vizMinus[graf[node][i].first]&&!graf[node][i].second&&!viz[graf[node][i].first])
{
if(vizPlus[graf[node][i].first])
{
comps[comps.size()-1].push_back(graf[node][i].first);
viz[graf[node][i].first] = true;
}
vizMinus[graf[node][i].first]=true;
dfsMinus(graf[node][i].first);
}
}
}
void getComp(int node)
{
fill(vizPlus,vizPlus+NMAX,false);
fill(vizMinus,vizMinus+NMAX,false);
viz[node]=true;
vector<int> v;
v.push_back(node);
comps.push_back(v);
vizPlus[node]=true;
dfsPlus(node);
vizMinus[node]=true;
dfsMinus(node);
}
int main()
{
ios::sync_with_stdio(0);
InParser fin("ctc.in");
int n,m;
fin>>n>>m;
for(int i = 0; i<m; i++)
{
int x,y;
fin>>x>>y;
graf[x].push_back({y,true});
graf[y].push_back({x,false});
}
for(int i = 1; i<=n; i++)
{
if(!viz[i])
{
getComp(i);
}
}
printf("%d\n",comps.size());
for(int j = 0;j<comps.size();j++)
{
for(int i = 0;i<comps[j].size();i++)
printf("%d ",comps[j][i]);
printf("\n");
}
return 0;
}