Skip to content

Instantly share code, notes, and snippets.

@sparfenyuk
Created October 27, 2014 18:41
Show Gist options
  • Select an option

  • Save sparfenyuk/3b469f6be6f941d697a9 to your computer and use it in GitHub Desktop.

Select an option

Save sparfenyuk/3b469f6be6f941d697a9 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <iterator>
#include <set>
#include <vector>
#include <algorithm>
#include <cassert>
#include <cmath>
using namespace std;
typedef unsigned long long input_type;
typedef vector<vector<input_type> > InputContainer;
void prepare_graph(InputContainer& container, input_type n)
{
container.resize(n);
}
void add_edge(InputContainer& container, input_type from_point, input_type to_point)
{
container[from_point - 1].push_back(to_point - 1);
}
void explore_path(const InputContainer& container, const input_type index, vector<bool>& v, vector<input_type>& path)
{
v[index] = true;
const vector<input_type>& a = container[index];
for (input_type i = 0; i < a.size(); ++i) {
const input_type& next_index = a[i];
if (!v[next_index]) {
explore_path(container, next_index, v, path);
}
}
path.push_back(index);
}
void explore(const InputContainer& container, vector<input_type>& whole_path)
{
vector<bool> v(container.size(), false);
for (input_type i = 0; i < v.size(); ++i) {
if (!v[i]) {
explore_path(container, i, v, whole_path);
}
}
}
int main()
{
input_type n = 0, m = 0;
cin >> n >> m;
InputContainer input, inversed_input;
prepare_graph(input, n);
prepare_graph(inversed_input, n);
for (input_type i = 0; i < m; ++i) {
input_type first, second;
cin >> first >> second;
add_edge(input, first, second);
add_edge(inversed_input, second, first);
}
vector<input_type> path;
explore(inversed_input, path);
assert(path.size() == n);
vector<bool> v(input.size(), false);
input_type count = 0;
while (path.size()) {
input_type i = path.back();
path.pop_back();
vector<input_type> p;
if (!v[i]) {
explore_path(input, i, v, p);
assert(p.size() != 0);
++count;
}
}
cout << count;
return 0;
}
@sparfenyuk
Copy link
Author

Sample Input:
4 4
1 2
4 1
2 3
3 1
Sample Output:
2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment