Pagini recente » Cod sursa (job #3180368) | Cod sursa (job #946023) | Cod sursa (job #603127) | Cod sursa (job #2505820) | Cod sursa (job #1136228)
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iterator>
#include <random>
#include <assert.h>
using namespace std;
const string file = "ctc";
const string infile = file + ".in";
const string outfile = file + ".out";
const int INF = 0x3f3f3f3f;
//#define ONLINE_JUDGE
vector<vector<int> > G;
vector<int> idx;
vector<int> lowlink;
vector<bool> viz;
vector<bool> uz;
stack<int> st;
int current;
vector<vector<int> > ctc;
void tarjan(int x)
{
viz[x] = true;
idx[x] = lowlink[x] = ++current;
st.push(x);
for(vector<int>::iterator itr = G[x].begin();
itr != G[x].end();
itr++)
{
if(viz[*itr] == false)
{
tarjan(*itr);
lowlink[x] = min(lowlink[x], lowlink[*itr]);
}
else if(uz[*itr] == false)
{
lowlink[x] = min(lowlink[x], lowlink[*itr]);
}
}
if(lowlink[x] == idx[x])
{
int n = -1;
vector<int> newCtc;
while( n != x)
{
n = st.top();
uz[n] = true;
st.pop();
newCtc.push_back(n);
}
ctc.push_back(newCtc);
}
}
int main()
{
#ifdef ONLINE_JUDGE
ostream &fout = cout;
istream &fin = cin;
#else
fstream fin(infile.c_str(), ios::in);
fstream fout(outfile.c_str(), ios::out);
#endif
int N, M;
fin >> N >> M;
G.resize(N + 1);
idx.resize(N + 1);
lowlink.resize(N + 1);
viz.resize(N + 1);
uz.resize(N + 1);
for(int i = 0 ; i < M; i++)
{
int x, y;
fin >> x >> y;
G[x].push_back(y);
}
for(int i = 1; i <= N; i++)
{
if(viz[i] == false)
{
tarjan(i);
}
}
fout << ctc.size() << "\n";
for(vector<vector<int> >::reverse_iterator itr = ctc.rbegin();
itr != ctc.rend();
itr++)
{
for(vector<int>::reverse_iterator jtr = itr->rbegin();
jtr != itr->rend();
jtr++)
{
fout << *jtr << " ";
}
fout << "\n";
}
#ifdef ONLINE_JUDGE
#else
fout.close();
fin.close();
#endif
}