Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
stack<int> sk;
bool insk[100010], isok[100010];
int step, dfn[100010], low[100010], belong[100010], num[100010], tol;
struct Edge {
int to, next;
} edge[200010];
int head[100010], tail;
void add(int from, int to) {
edge[tail].to = to;
edge[tail].next = head[from];
head[from] = tail++;
}
void dfs(int from) {
dfn[from] = low[from] = ++step;
sk.push(from);
insk[from] = 1;
for (int i = head[from]; i != -1; i = edge[i].next) {
int to = edge[i].to;
if (dfn[to] == 0) {
dfs(to);
low[from] = min(low[from], low[to]);
} else if (insk[to])
low[from] = min(low[from], dfn[to]);
}
if (dfn[from] == low[from]) {
int v;
do {
v = sk.top();
sk.pop();
insk[v] = 0;
belong[v] = tol;
num[tol]++;
} while (v != from);
if (num[tol] > 1) isok[tol] = 1;
tol++;
}
}
int pr[100010];
int seek(int v) { return pr[v] = v == pr[v] ? v : seek(pr[v]); }
int main() {
int n, m;
cin >> n >> m;
memset(head, -1, sizeof(head));
while (m--) {
int a, b;
cin >> a >> b;
add(a, b);
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) dfs(i);
for (int i = 0; i < tol; i++) pr[i] = i;
int ans = 0;
for (int i = 1; i <= n; i++)
for (int j = head[i]; j != -1; j = edge[j].next) {
int a = belong[i], b = belong[edge[j].to];
a = seek(a);
b = seek(b);
if (a != b) {
isok[a] |= isok[b];
num[a] += num[b];
pr[b] = a;
}
}
for (int i = 0; i < tol; i++)
if (pr[i] == i) ans += num[i] + (isok[i] ? 0 : -1);
cout << ans;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
os << "[";
for (int i = 0; i < (((int)(v).size())); ++i) {
if (i) os << ", ";
os << v[i];
}
return os << "]";
}
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
return os << "(" << p.first << " " << p.second << ")";
}
template <class T>
bool chmax(T &a, const T &b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
bool chmin(T &a, const T &b) {
if (b < a) {
a = b;
return true;
}
return false;
}
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using P = pair<int, int>;
using vi = vector<int>;
using vll = vector<ll>;
using vvi = vector<vi>;
using vvll = vector<vll>;
const ll MOD = 1e9 + 7;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;
const ld eps = 1e-9;
struct StronglyConnectedComponents {
int n;
vector<vector<int>> g, rg, graph;
vector<int> ord, used, comp;
StronglyConnectedComponents(const vector<vector<int>> &g)
: n(g.size()), g(g), rg(n), used(n), comp(n, -1) {
for (int i = 0; i < n; ++i) {
for (int to : g[i]) {
rg[to].push_back(i);
}
}
}
void build() {
for (int i = 0; i < n; ++i) dfs(i);
reverse(ord.begin(), ord.end());
int ptr = 0;
for (int i : ord)
if (comp[i] == -1) rdfs(i, ptr), ptr++;
graph.resize(ptr);
for (int i = 0; i < n; ++i) {
for (int to : g[i]) {
int x = comp[i], y = comp[to];
if (x == y) continue;
graph[x].push_back(y);
}
}
for (auto &v : graph) {
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
}
}
private:
void dfs(int idx) {
if (used[idx]) return;
used[idx] = true;
for (int to : g[idx]) dfs(to);
ord.push_back(idx);
}
void rdfs(int idx, int cnt) {
if (comp[idx] != -1) return;
comp[idx] = cnt;
for (int to : rg[idx]) rdfs(to, cnt);
}
};
struct UnionFind {
vector<int> par, sz;
UnionFind(int n) : par(n), sz(n, 1) {
for (int i = 0; i < n; ++i) par[i] = i;
}
int root(int x) {
if (par[x] == x) return x;
return par[x] = root(par[x]);
}
void merge(int x, int y) {
x = root(x);
y = root(y);
if (x == y) return;
if (sz[x] < sz[y]) swap(x, y);
par[y] = x;
sz[x] += sz[y];
sz[y] = 0;
}
bool issame(int x, int y) { return root(x) == root(y); }
int size(int x) { return sz[root(x)]; }
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
int n, m;
cin >> n >> m;
vvi g(n);
for (int i = 0; i < (m); ++i) {
int u, v;
cin >> u >> v;
u--;
v--;
g[u].push_back(v);
}
StronglyConnectedComponents scc(g);
scc.build();
map<int, int> mp;
for (int i = 0; i < (n); ++i) {
mp[scc.comp[i]]++;
}
int sz = ((int)(scc.graph).size());
UnionFind uf(sz);
for (int i = 0; i < (sz); ++i) {
for (auto &to : scc.graph[i]) {
uf.merge(i, to);
}
}
int ans = 0;
map<int, int> cnt;
map<int, bool> isn;
for (int i = 0; i < (sz); ++i) {
cnt[uf.root(i)] += mp[i];
isn[uf.root(i)] |= mp[i] >= 2;
}
for (auto &e : cnt) {
if (isn[e.first]) {
ans += e.second;
} else {
ans += e.second - 1;
}
}
cout << min(n, ans) << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16000000")
using namespace std;
const int Maxn = 100005;
int n, m;
vector<int> rneigh[Maxn], neigh[Maxn];
int in[Maxn];
vector<int> seq;
bool tk[Maxn], tk2[Maxn];
int res;
void Traverse(int v) {
if (tk[v]) return;
tk[v] = true;
seq.push_back(v);
for (int i = 0; i < rneigh[v].size(); i++) Traverse(rneigh[v][i]);
}
int Solve() {
queue<int> Q;
for (int i = 0; i < seq.size(); i++)
if (in[seq[i]] == 0) {
Q.push(seq[i]);
tk2[seq[i]] = true;
}
while (!Q.empty()) {
int v = Q.front();
Q.pop();
for (int i = 0; i < neigh[v].size(); i++) {
int u = neigh[v][i];
if (--in[u] == 0) {
Q.push(u);
tk2[u] = true;
}
}
}
for (int i = 0; i < seq.size(); i++)
if (!tk2[seq[i]]) return seq.size();
return seq.size() - 1;
}
int main() {
scanf("%d %d", &n, &m);
while (m--) {
int a, b;
scanf("%d %d", &a, &b);
neigh[a].push_back(b);
in[b]++;
rneigh[a].push_back(b);
rneigh[b].push_back(a);
}
for (int i = 1; i <= n; i++)
if (!tk[i]) {
seq.clear();
Traverse(i);
res += Solve();
}
printf("%d\n", res);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
const double eps = 1e-9;
const int INF = inf;
const double EPS = eps;
struct __timestamper {};
vector<int> all1, all2;
vector<pair<int, int> > ces;
vector<bool> was1, was2;
vector<vector<int> > es, rves;
void dfs1(int v) {
if (was1[v]) return;
was1[v] = true;
all1.push_back(v);
for (int x : es[v]) dfs1(x), ces.push_back(make_pair(v, x));
for (int x : rves[v]) dfs1(x);
}
void dfs2(int v) {
if (was2[v]) return;
was2[v] = true;
for (int x : es[v]) dfs2(x);
all2.push_back(v);
}
int main() {
int n, m;
while (scanf("%d%d", &n, &m) == 2) {
es = vector<vector<int> >(n);
rves = vector<vector<int> >(n);
for (int i = 0; i < (m); i++) {
int a, b;
scanf("%d%d", &a, &b), a--, b--;
es[a].push_back(b);
rves[b].push_back(a);
}
was1 = vector<bool>(n, false);
was2 = vector<bool>(n, false);
int ans = 0;
int bigcyc = 0;
for (int i = 0; i < (n); i++)
if (!was1[i]) {
all1.clear();
all2.clear();
ces.clear();
dfs1(i);
if (ces.empty()) continue;
for (int x : all1)
if (!was2[x]) {
dfs2(x);
}
reverse(all2.begin(), all2.end());
map<int, int> ids;
for (int i2 = 0; i2 < (((int)(all2).size())); i2++) ids[all2[i2]] = i2;
bool ncyc = true;
for (pair<int, int> e : ces) {
int a = ids[e.first];
int b = ids[e.second];
ncyc = ncyc && a <= b;
}
if (ncyc) {
ans += ((int)(all2).size()) - 1;
} else {
bigcyc += ((int)(all2).size());
}
}
printf("%d\n", ans + bigcyc);
}
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
void fre() {
freopen("c://test//input.in", "r", stdin);
freopen("c://test//output.out", "w", stdout);
}
template <class T>
inline void gmax(T &a, T b) {
if (b > a) a = b;
}
template <class T>
inline void gmin(T &a, T b) {
if (b < a) a = b;
}
using namespace std;
const int N = 1e5 + 10, M = 0, Z = 1e9 + 7, maxint = 2147483647,
ms31 = 522133279, ms63 = 1061109567, ms127 = 2139062143;
const double eps = 1e-8, PI = acos(-1.0);
int n, m;
int ind[N];
int sta[N], top;
vector<int> a[N];
vector<int> b[N];
bool vis[N];
int num;
void dfs(int x) {
vis[x] = 1;
++num;
if (ind[x] == 0) sta[++top] = x;
for (auto y : a[x])
if (!vis[y]) dfs(y);
}
int main() {
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; i++)
a[i].clear(), b[i].clear(), ind[i] = vis[i] = 0;
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
++ind[y];
a[x].push_back(y);
a[y].push_back(x);
b[x].push_back(y);
}
int ans = 0;
for (int i = 1; i <= n; i++)
if (!vis[i]) {
num = top = 0;
dfs(i);
int sum = top;
while (top) {
int x = sta[top--];
for (auto y : b[x]) {
if (--ind[y] == 0) {
sta[++top] = y;
++sum;
}
}
}
if (sum == num)
ans += (num - 1);
else
ans += num;
}
printf("%d\n", ans);
}
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> g[100100];
vector<int> k[100100];
int used[100100];
vector<int> g2[100100];
bool check[100100];
bool use[100100];
int t = 1;
int N, M;
stack<int> s;
void dfs(int a) {
if (check[a]) return;
check[a] = true;
for (int i = 0; i < g[a].size(); i++) dfs(g[a][i]);
s.push(a);
}
void dfs2(int a, int b) {
if (used[a]) return;
used[a] = b;
g2[b].push_back(a);
for (int i = 0; i < g[a].size(); i++) dfs2(g[a][i], b);
for (int i = 0; i < k[a].size(); i++) dfs2(k[a][i], b);
return;
}
int main() {
cin >> N >> M;
for (int i = 0; i < M; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
g[x].push_back(y);
k[y].push_back(x);
}
for (int i = 0; i < N; i++)
if (!used[i]) dfs2(i, t++);
int sum = 0;
for (int i = 1; i < t; i++) {
sum += g2[i].size() - 1;
for (int j = 0; j < g2[i].size(); j++) dfs(g2[i][j]);
while (!s.empty()) {
int x = s.top();
s.pop();
use[x] = true;
for (int i = 0; i < k[x].size(); i++) {
if (!use[k[x][i]]) {
sum++;
goto q;
}
}
}
q:
while (!s.empty()) s.pop();
}
cout << sum;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> v[100010];
int p[100010], mark[100010], in[100010];
queue<int> que;
int Find(int x) { return p[x] == x ? x : (p[x] = Find(p[x])); }
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) p[i] = i;
while (m--) {
int x, y;
scanf("%d%d", &x, &y);
v[x].push_back(y);
in[y]++;
p[Find(x)] = Find(y);
}
for (int i = 1; i <= n; i++)
if (in[i] == 0) que.push(i);
while (!que.empty()) {
int i = que.front();
que.pop();
for (int k = 0; k < (v[i].size()); k++) {
int to = v[i][k];
if (--in[to] == 0) que.push(to);
}
}
for (int i = 1; i <= n; i++)
if (in[i]) mark[Find(i)] = 1;
int ans = n;
for (int i = 1; i <= n; i++)
if (Find(i) == i && mark[Find(i)] == 0) ans--;
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100 * 1000 + 10;
int n, m, comp[N], res, ans, sz[N], par[N];
vector<int> adj[N], _adj[N], topol;
vector<pair<int, int>> ed;
bool vis[N], cycle[N];
void dfs_topol(int v) {
vis[v] = true;
for (int u : adj[v])
if (!vis[u]) dfs_topol(u);
topol.push_back(v);
}
void topol_sort() {
for (int i = 0; i < n; i++)
if (!vis[i]) dfs_topol(i);
reverse(topol.begin(), topol.end());
}
void dfs_scc(int v) {
comp[v] = res;
for (int u : _adj[v])
if (!comp[u]) dfs_scc(u);
}
void scc() {
topol_sort();
for (int x : topol)
if (!comp[x]) res++, dfs_scc(x);
for (int i = 0; i < n; i++) sz[comp[i]]++;
for (int i = 1; i <= res; i++)
if (sz[i] > 1) cycle[i] = true;
}
int get_par(int u) { return par[u] ^ -1 ? par[u] = get_par(par[u]) : u; }
void merge(int u, int v) {
u = get_par(u), v = get_par(v);
if (u == v) return;
if (sz[u] > sz[v]) swap(u, v);
par[u] = v;
cycle[v] |= cycle[u];
sz[v] += sz[u];
}
int main() {
ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
memset(par, -1, sizeof par);
cin >> n >> m;
for (int i = 0, u, v; i < m; i++) {
cin >> u >> v, adj[--u].push_back(--v), _adj[v].push_back(u);
ed.push_back({u, v});
}
scc();
for (auto [u, v] : ed) merge(comp[u], comp[v]);
for (int i = 1; i <= res; i++)
if (get_par(i) == i) ans += sz[i] - 1 + cycle[i];
cout << ans << '\n';
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100007;
vector<int> order, G[N], RG[N], S[N];
int n, m, compCnt, cnt, comp[N], size[N];
vector<pair<int, int> > edges;
bool used[N];
void dfs(int u) {
used[u] = true;
for (int to : G[u]) {
if (!used[to]) dfs(to);
}
order.push_back(u);
}
void rdfs(int u) {
++cnt;
comp[u] = compCnt;
for (int to : RG[u]) {
if (comp[to] == 0) rdfs(to);
}
}
void dfsComp(int u, vector<int> &mas) {
mas.push_back(u);
used[u] = true;
for (int to : S[u]) {
if (!used[to]) dfsComp(to, mas);
}
}
void solve() {
scanf("%d%d", &n, &m);
for (int i = 0; i < (m); ++i) {
int u, v;
scanf("%d%d", &u, &v);
edges.push_back(make_pair(u, v));
G[u].push_back(v);
RG[v].push_back(u);
}
for (int i = 1; i <= n; ++i) {
if (!used[i]) dfs(i);
}
reverse((order).begin(), (order).end());
int ans = 0;
for (int u : order) {
if (comp[u] == 0) {
++compCnt;
cnt = 0;
rdfs(u);
size[compCnt] = cnt;
}
}
for (auto &e : edges) {
S[comp[e.first]].push_back(comp[e.second]);
S[comp[e.second]].push_back(comp[e.first]);
}
memset(used, 0, sizeof used);
for (int i = 1; i <= compCnt; ++i) {
if (!used[i]) {
vector<int> mas;
dfsComp(i, mas);
bool flag = true;
int sum = 0;
for (int u : mas) {
sum += size[u];
if (size[u] > 1) {
flag = false;
}
}
if (!flag)
ans += sum;
else
ans += sum - 1;
}
}
printf("%d\n", ans);
}
int rd() { return (((long long)rand() << 16) | rand()) % 1000000000; }
void testGen() {
FILE *f = fopen("input.txt", "w");
fclose(f);
}
int main() {
solve();
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> grafo[100001];
vector<int> grafo2[100001];
bool visitado[100001];
bool termino[100001];
bool hayciclo[100001];
bool ciclo;
int t;
void dfs(int u) {
visitado[u] = true;
for (int i = 0; i < grafo[u].size(); i++) {
int v = grafo[u][i];
if (!visitado[v])
dfs(v);
else if (!termino[v])
hayciclo[v] = true;
}
termino[u] = true;
}
void dfs2(int u) {
visitado[u] = true;
t++;
if (hayciclo[u]) ciclo = true;
for (int i = 0; i < grafo[u].size(); i++) {
int des = grafo[u][i];
if (!visitado[des]) dfs2(des);
}
for (int i = 0; i < grafo2[u].size(); i++) {
int des = grafo2[u][i];
if (!visitado[des]) dfs2(des);
}
}
int main() {
scanf("%d", &n);
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d", &a);
scanf("%d", &b);
a--;
b--;
grafo[a].push_back(b);
grafo2[b].push_back(a);
}
memset(visitado, false, sizeof(visitado));
memset(termino, false, sizeof(termino));
memset(hayciclo, false, sizeof(hayciclo));
int res = 0;
for (int i = 0; i < n; i++) {
if (!visitado[i]) {
dfs(i);
}
}
memset(visitado, false, sizeof(visitado));
for (int i = 0; i < n; i++) {
if (!visitado[i]) {
ciclo = false;
t = 0;
dfs2(i);
if (ciclo)
res += t;
else
res += t - 1;
}
}
printf("%d\n", res);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
void fre() {
freopen("c://test//input.in", "r", stdin);
freopen("c://test//output.out", "w", stdout);
}
template <class T>
inline void gmax(T &a, T b) {
if (b > a) a = b;
}
template <class T>
inline void gmin(T &a, T b) {
if (b < a) a = b;
}
using namespace std;
const int N = 1e5 + 10, M = 0, Z = 1e9 + 7, maxint = 2147483647,
ms31 = 522133279, ms63 = 1061109567, ms127 = 2139062143;
const double eps = 1e-8, PI = acos(-1.0);
int n, m;
int x, y;
int ind[N], s[N], num, top;
vector<int> a[N], b[N];
bool e[N];
void dfs(int x) {
e[x] = 1;
num++;
if (ind[x] == 0) s[++top] = x;
for (int i = a[x].size() - 1; i >= 0; i--) {
int y = a[x][i];
if (!e[y]) dfs(y);
}
}
int main() {
while (~scanf("%d%d", &n, &m)) {
memset(ind, 0, sizeof(ind));
for (int i = 1; i <= n; i++) a[i].clear(), b[i].clear();
for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
ind[y]++;
a[x].push_back(y);
a[y].push_back(x);
b[x].push_back(y);
}
int ans = 0;
memset(e, 0, sizeof(e));
for (int i = 1; i <= n; i++)
if (!e[i]) {
num = top = 0;
dfs(i);
int sum = top;
while (top) {
int x = s[top--];
for (int j = b[x].size() - 1; j >= 0; j--) {
int y = b[x][j];
ind[y]--;
if (ind[y] == 0) {
s[++top] = y;
sum++;
}
}
}
if (sum == num)
ans += (num - 1);
else
ans += num;
}
printf("%d\n", ans);
}
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 |
import java.util.*;
import java.io.*;
public class B
{
public static void main(String[] args)
{
PrintWriter out = new PrintWriter(System.out);
new B(new FastScanner(), out);
out.close();
}
public B(FastScanner in, PrintWriter out)
{
Graph orig = new Graph(in.nextInt());
int M = in.nextInt();
while (M-->0)
orig.add(in.nextInt()-1, in.nextInt()-1);
Tarjan scc = new Tarjan(orig);
Graph dag = new Graph(scc.count);
for (int i=0; i<orig.N; i++)
for (int j : orig.adj[i])
dag.add(scc.id[i], scc.id[j]);
dag = dag.doubleUp();
int res = 0;
boolean[] seen = new boolean[dag.N];
ArrayDeque<Integer> q = new ArrayDeque<>();
for (int i=0; i<dag.N; i++) if (!seen[i])
{
int size = 0;
seen[i] = true;
q.add(i);
boolean isSilly = false;
while (q.size() > 0)
{
int cur = q.poll();
size+=scc.sz[cur];
if (scc.sz[cur] > 1)
isSilly = true;
for (int j : dag.adj[cur]) if (!seen[j])
{
seen[j] = true;
q.add(j);
}
}
res += isSilly ? size : size-1;
}
out.println(res);
}
}
class Tarjan {
boolean[] marked;
int[] id, low, stk, sz;
int pre,count;
Graph g;
public Tarjan(Graph gg) {
g=gg;
marked = new boolean[g.N];
stk = new int[g.N+1];
id = new int[g.N];
sz = new int[g.N];
low = new int[g.N];
for(int i=0; i<g.N; i++)
if(!marked[i])
dfs(i);
}
void dfs(int i) {
marked[i] = true;
int min = low[stk[++stk[0]] = i] = pre++;
for(int j : g.adj[i]) {
if(!marked[j]) dfs(j);
if(low[j] < min) min = low[j];
}
if(min < low[i]) low[i] = min;
else {
for(int j=i+1; j != i; id[j] = count, sz[count]++, low[j] = g.N)
j = stk[stk[0]--];
count++;
}
}
}
class Graph
{
int N;
ArrayList<Integer>[] adj;
Graph(int NN)
{
adj = new ArrayList[N=NN];
for (int i=0; i<N; i++)
adj[i] = new ArrayList<>();
}
void add(int i, int j)
{
adj[i].add(j);
}
Graph doubleUp()
{
Graph g = new Graph(N);
for (int i=0; i<N; i++)
{
for (int j : adj[i])
{
g.add(i, j);
g.add(j, i);
}
}
return g;
}
}
class FastScanner{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner()
{
stream = System.in;
}
int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c)
{
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
boolean isEndline(int c)
{
return c=='\n'||c=='\r'||c==-1;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String next(){
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isSpaceChar(c));
return res.toString();
}
String nextLine(){
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isEndline(c));
return res.toString();
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
namespace FGF {
int n, m;
const int N = 1e5 + 5;
struct edg {
int to[N], nxt[N], cnt, head[N];
void add(int u, int v) {
cnt++;
to[cnt] = v;
nxt[cnt] = head[u];
head[u] = cnt;
}
} G1;
int read() {
int s = 0;
char ch = getchar();
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) s = s * 10 + ch - '0', ch = getchar();
return s;
}
int dfn[N], low[N], num, st[N], tp, scc, bel[N], siz[N], ru[N], ans;
int fa[N], vis[N], val[N], is[N];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void tarjan(int u) {
dfn[u] = low[u] = ++num, st[++tp] = u, vis[u] = 1;
for (int i = G1.head[u]; i; i = G1.nxt[i]) {
int v = G1.to[i];
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (vis[v])
low[u] = min(low[u], dfn[v]);
}
if (low[u] == dfn[u]) {
scc++;
int x = -1;
do {
x = st[tp--];
vis[x] = 0;
bel[x] = scc;
val[scc]++;
if (val[scc] != 1) is[scc] = 1;
} while (x != u);
}
}
queue<int> q;
void work() {
n = read(), m = read();
for (int i = 1; i <= m; i++) {
int u = read(), v = read();
G1.add(u, v);
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
for (int i = 1; i <= scc; i++) fa[i] = i;
for (int u = 1; u <= n; u++)
for (int i = G1.head[u]; i; i = G1.nxt[i]) {
int fu = find(bel[u]), fv = find(bel[G1.to[i]]);
if (fu != fv) {
fa[fu] = fv;
val[fv] += val[fu], is[fv] |= is[fu];
}
}
for (int i = 1; i <= scc; i++)
if (fa[i] == i) {
if (is[i])
ans += val[i];
else
ans += val[i] - 1;
}
printf("%d\n", ans);
}
} // namespace FGF
int main() {
FGF::work();
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int n, m, u, v;
vector<int> g[N];
namespace SCC {
int dfn[N], low[N], id[N], st[N], _st, _, cc;
void dfs(int c, vector<int> g[]) {
dfn[c] = low[c] = ++cc;
st[_st++] = c;
for (auto t : g[c])
if (!dfn[t])
dfs(t, g), low[c] = min(low[c], low[t]);
else if (!id[t])
low[c] = min(low[c], dfn[t]);
if (low[c] == dfn[c]) {
++_;
while (st[--_st] != c) id[st[_st]] = _;
id[c] = _;
}
}
vector<int> ng[N];
int sz[N], vis[N];
int bfs(int c) {
vector<int> v;
v.push_back(c);
vis[c] = true;
bool b2 = false;
int all = 0;
for (int i = 0; i < ((int)(v).size()); ++i) {
all += sz[v[i]];
b2 |= sz[v[i]] >= 2;
for (auto j : ng[v[i]])
if (!vis[j]) vis[j] = true, v.push_back(j);
}
return all - !b2;
}
int solve(int n, vector<int> g[]) {
fill_n(dfn, n, cc = 0);
fill_n(low, n, _st = 0);
fill_n(id, n, _ = 0);
for (int i = 0; i < (n); ++i)
if (!dfn[i]) dfs(i, g);
fill_n(ng, _, vector<int>());
fill_n(sz, _, 0);
fill_n(vis, _, 0);
int ans = 0;
for (int i = 0; i < (n); ++i) ++sz[--id[i]];
for (int i = 0; i < (n); ++i)
for (auto j : g[i])
if (id[i] != id[j])
ng[id[i]].push_back(id[j]), ng[id[j]].push_back(id[i]);
for (int i = 0; i < (_); ++i)
if (!vis[i]) ans += bfs(i);
printf("%d\n", ans);
return _;
}
} // namespace SCC
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < (m); ++i) {
scanf("%d%d", &u, &v);
--u;
--v;
g[u].push_back(v);
}
SCC::solve(n, g);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int inf = 2e9;
const int MOD = 1e9 + 7;
const int N = 1e5 + 10;
stack<int> s;
int n, m, ans, low[N], num[N], h[N] = {0}, t[N] = {0};
vector<int> a[N], b[N];
void DFSt(int x) {
static int c = 0;
s.push(x);
num[x] = low[x] = --c;
for (vector<int>::iterator i = a[x].begin(); i != a[x].end(); i++) {
int nx = *i;
if (num[nx] > 0) continue;
if (!num[nx]) DFSt(nx);
low[x] = max(low[x], low[nx]);
}
if (low[x] <= num[x]) {
num[x] = ++m;
t[m] = 1;
while (s.top() != x) {
num[s.top()] = m;
s.pop();
t[m]++;
}
s.pop();
}
}
int main() {
scanf("%d%d", &n, &m);
ans = 0;
while (m--) {
int x, y;
scanf("%d%d", &x, &y);
a[x].push_back(y);
}
m = 0;
for (int i = 1; i <= n; i++)
if (!num[i]) DFSt(i);
for (int x = 1; x <= n; x++)
for (auto y : a[x])
if (num[x] != num[y]) {
b[num[x]].push_back(num[y]);
b[num[y]].push_back(num[x]);
}
queue<int> q;
for (int x = 1; x <= m; x++)
if (!h[x]) {
int c = t[x], ok = (t[x] > 1);
q.push(x);
h[x] = 1;
while (!q.empty()) {
int cx = q.front();
q.pop();
for (auto i : b[cx])
if (!h[i]) {
h[i] = 1;
c += t[i];
q.push(i);
ok |= (t[i] > 1);
}
}
ans += c - 1 + ok;
}
cout << ans;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
public class DMain {
String returnValue = "NoResult";
PrintWriter out;
Parser in;
static class City{
final int index;
int color;
boolean checked;
boolean suspected;
Vector<City> toCities = new Vector<City>();
Vector<City> fromCities = new Vector<City>();
City(int index) {
this.index = index;
}
}
static class StackNode{
final City city;
Stack<City> stack;
StackNode(City city, List<City> to) {
this.city = city;
this.stack = new Stack<City>();
this.stack .addAll(to);
}
}
public void solve() {
int n = in.nextInteger();
int m = in.nextInteger();
City[] cities = new City[n];
for(int i = 0; i < n; ++i){
cities[i] = new City(i + 1);
}
for(int i = 0; i < m; ++i){
int a = in.nextInteger();
int b = in.nextInteger();
cities[a - 1].toCities.add(cities[b - 1]);
cities[b - 1].fromCities.add(cities[a - 1]);
}
Stack<City> cityStack = new Stack<City>();
int color = 0;
int areaCount = 0;
int emptyCount = 0;
for(City city : cities){
if(city.color != 0) continue;
if(city.fromCities.isEmpty() && city.toCities.isEmpty()){
++emptyCount;
continue;
}
++color;
++areaCount;
cityStack.push(city);
while(!cityStack.isEmpty()){
City c = cityStack.pop();
if(c.color == color)continue;
c.color = color;
for(City cc : c.toCities){
if(cc.color != color) cityStack.push(cc);
}
for(City cc : c.fromCities){
if(cc.color != color) cityStack.push(cc);
}
}
}
boolean[] areaHasLoop = new boolean[areaCount + 1];
int areaWithLoop = 0;
Stack<StackNode> stack = new Stack<StackNode>();
for(City city : cities) {
if (city.color == 0 || areaHasLoop[city.color] || city.checked) continue;
int area = city.color;
stack.push(new StackNode(city, city.toCities));
city.checked = true;
while (!stack.empty()) {
StackNode top = stack.peek();
if (top.city.suspected) {
areaHasLoop[area] = true;
++areaWithLoop;
stack.clear();
break;
}
if (top.stack.empty()) {
stack.pop();
continue;
}
City to = top.stack.pop();
if (to.checked) {
to.suspected = true;
} else {
to.checked = true;
stack.push(new StackNode(to, to.toCities));
}
}
}
out.println(n - emptyCount - areaCount + areaWithLoop);
}
static public class Parser{
Scanner scanner;
public Parser() {
scanner = new Scanner(System.in).useLocale(Locale.ENGLISH);
}
public Parser(String str) {
scanner = new Scanner(str).useLocale(Locale.ENGLISH);
}
long nextLong(){
return scanner.nextLong();
}
int nextInteger(){
return scanner.nextInt();
}
double nextDouble(){
return scanner.nextDouble();
}
String nextLine(){
return scanner.nextLine();
}
String next(){
return scanner.next();
}
int[] nextIntegers(int count){
int[] result = new int[count];
for(int i = 0; i < count; ++i){
result[i] = nextInteger();
}
return result;
}
long[] nextLongs(int count){
long[] result = new long[count];
for(int i = 0; i < count; ++i){
result[i] = nextLong();
}
return result;
}
int[][] nextIntegers(int fields, int count){
int[][] result = new int[fields][count];
for(int c = 0; c < count; ++c){
for(int i = 0; i < fields; ++i){
result[i][c] = nextInteger();
}
}
return result;
}
}
void doReturn(){
throw new RuntimeException();
}
void doReturn(String str){
returnValue = str;
doReturn();
}
void run(){
in = new Parser();
try{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
out = new PrintWriter(System.out);
solve();
out.close();
System.out.print(outStream.toString());
} catch (RuntimeException exc){
System.out.print(returnValue);
}
}
public static void main(String[] args) {
new DMain().run();
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
#pragma comment(linker, "/stack:32000000")
using namespace std;
const int INF = 2147483647;
const long long LLINF = 9223372036854775807LL;
const int maxn = 100010;
vector<int> g2[maxn];
bool ok;
int used[maxn];
void dfscycle(int x) {
used[x] = 2;
for (int i = 0; i < int((g2[x]).size()); ++i) {
int to = g2[x][i];
if (used[to] == 2) {
ok = true;
} else if (used[to] == 0)
dfscycle(to);
}
used[x] = 1;
}
vector<int> g1[maxn];
int color[maxn];
vector<int> comp;
void dfscomp(int x) {
color[x] = 1;
comp.push_back(x);
for (int i = 0; i < int((g1[x]).size()); ++i) {
int to = g1[x][i];
if (color[to] == 0) dfscomp(to);
}
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
int fr, to;
scanf("%d%d", &fr, &to);
--fr, --to;
g1[fr].push_back(to);
g1[to].push_back(fr);
g2[fr].push_back(to);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (color[i] == 0) {
comp.clear();
dfscomp(i);
ok = false;
for (int jj = 0; jj < int((comp).size()); ++jj) {
int cur = comp[jj];
if (!used[cur]) dfscycle(cur);
}
if (!ok)
ans += int((comp).size()) - 1;
else
ans += int((comp).size());
}
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
int n, m;
int usedWCC[((int)2e5 + 5)];
int mark[((int)2e5 + 5)];
int mark2[((int)2e5 + 5)];
vector<int> v[((int)2e5 + 5)];
vector<int> u[((int)2e5 + 5)];
vector<int> wcc[((int)2e5 + 5)];
int wccCount;
void dfs(int node) {
wcc[wccCount].push_back(node);
usedWCC[node] = wccCount;
for (int i = 0; i < u[node].size(); ++i)
if (usedWCC[u[node][i]] == -1) dfs(u[node][i]);
}
bool dfs2(int node) {
if (mark[node]) return true;
mark[node] = 1;
mark2[node] = 1;
for (int i = 0; i < v[node].size(); ++i)
if (mark[v[node][i]])
return true;
else if (mark2[v[node][i]] == 0 && dfs2(v[node][i]))
return true;
mark[node] = 0;
return false;
}
bool isCyclic(vector<int>& cc) {
for (int i = 0; i < cc.size(); ++i)
if (mark2[cc[i]] == 0)
if (dfs2(cc[i])) return true;
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
v[a].push_back(b);
u[a].push_back(b);
u[b].push_back(a);
}
for (int i = 1; i <= n; ++i) usedWCC[i] = -1;
for (int i = 1; i <= n; ++i)
if (usedWCC[i] == -1) {
dfs(i);
wccCount++;
}
int ans = n;
for (int i = 0; i < wccCount; ++i) {
int t = isCyclic(wcc[i]);
ans -= (!t);
}
cout << ans << "\n";
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m, dad[100010], x, y, gs[100010], head[200010], ne[1000010], v[1000010],
vis[200010], l, use[200010], i, ans, tot;
void add(int x, int y) {
v[++l] = y;
ne[l] = head[x];
head[x] = l;
}
int find(int x) { return dad[x] == x ? x : dad[x] = find(dad[x]); }
int dfs(int x) {
vis[x] = 1;
tot++;
for (int i = head[x]; i; i = ne[i]) {
if (!vis[v[i]])
if (!dfs(v[i])) return 0;
if (vis[v[i]] == 1) return 0;
}
vis[x] = -1;
return 1;
}
int main() {
scanf("%d%d", &n, &m);
for (i = 1; i <= n; i++) dad[i] = i;
for (i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
add(x, y);
gs[y]++;
if (find(x) != find(y)) dad[dad[x]] = dad[y];
}
for (i = 1; i <= n; i++) {
use[find(i)]++;
if (!gs[i]) add(dad[i] + n, i);
}
for (i = 1; i <= n; i++)
if (use[i]) {
ans += use[i];
tot = 0;
if (dfs(i + n) && tot > use[i] && head[i + n]) ans--;
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static ArrayList<Integer>[] adjList;
static int N, dfs_num[];
static UnionFind uf;
static void dfs(int u)
{
dfs_num[u] = -1;
for(int i = 0; i < adjList[u].size(); i++)
{
int v = adjList[u].get(i);
if(dfs_num[v] == 0)
{
uf.unionSet(u, v);
dfs(v);
}
else
{
if(dfs_num[v] == -1)
uf.needEdge[uf.findSet(v)] = true;
uf.unionSet(u, v);
}
}
dfs_num[u] = 1;
}
static int go()
{
uf = new UnionFind(N);
dfs_num = new int[N];
for(int i = 0; i < N; i++)
if(dfs_num[i]==0)
dfs(i);
int ans = 0;
boolean[] processed = new boolean[N];
for(int i = 0; i < N; i++)
{
int k = uf.findSet(i);
if(!processed[k])
{
ans += uf.setSize[k] - (uf.needEdge[k] ? 0 : 1);
processed[k] = true;
}
}
return ans;
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
int m = sc.nextInt();
adjList = new ArrayList[N];
for(int i = 0; i < N; i++)
adjList[i] = new ArrayList<Integer>();
while(m-->0)
{
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
adjList[u].add(v);
}
out.println(go());
out.flush();
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
boolean[] needEdge;
public UnionFind(int N)
{
p = new int[N];
rank = new int[N];
setSize = new int[N];
needEdge = new boolean[N];
numSets = N;
for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; }
}
public int findSet(int i)
{
if (p[i] == i) return i;
else return p[i] = findSet(p[i]);
}
public Boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public void unionSet(int i, int j)
{
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
// rank is used to keep the tree short
if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; needEdge[x] |= needEdge[y]; }
else
{ p[x] = y; setSize[y] += setSize[x];
needEdge[y] |= needEdge[x];
if(rank[x] == rank[y]) rank[y]++;
}
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
int countTokens() throws IOException
{
st = new StringTokenizer(br.readLine());
return st.countTokens();
}
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.util.*;
import java.io.*;
public class CF506B {
public static void main(String[] args) throws IOException {
in.init(System.in);
n = in.nextInt();
int m = in.nextInt();
adj = new ArrayList[n];
bid = new ArrayList[n];
for(int i = 0; i < n; i ++)
{
adj[i] = new ArrayList<Integer>();
bid[i] = new ArrayList<Integer>();
}
for(int i = 0; i < m; i ++)
{
int x = in.nextInt()-1;
int y = in.nextInt()-1;
adj[x].add(y);
bid[x].add(y);
bid[y].add(x);
}
deg = new int[n];
for(int i = 0; i < n; i ++)
for(int e: adj[i])
deg[e]++;
id = new int[n];
Arrays.fill(id, -1);
count = 0;
for(int i = 0; i < n; i ++)
{
if(id[i]!=-1)
continue;
BFS(i);
count++;
}
comps = new int[count];
for(int i = 0; i < n; i ++)
comps[id[i]]++;
cycle = new boolean[count];
ArrayDeque<Integer> dq = new ArrayDeque<Integer>();
for(int i = 0; i < n; i ++)
if(deg[i]==0)
dq.add(i);
while(!dq.isEmpty())
{
int at = dq.poll();
for(int e: adj[at])
{
deg[e]--;
if(deg[e]==0)
dq.add(e);
}
}
for(int i = 0; i < n; i ++)
if(deg[i]!=0)
cycle[id[i]] = true;
int ans = 0;
for(int i = 0; i < count; i ++)
ans += cycle[i]?comps[i]:comps[i]-1;
System.out.println(ans);
}
static boolean[] cycle;
static int[] comps;
static int[] deg;
static void BFS(int start)
{
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(start);
id[start] = count;
while(!q.isEmpty())
{
int at = q.poll();
for(int e: bid[at])
{
if(id[e]!=-1)
continue;
id[e] = id[at];
q.add(e);
}
}
}
static int count;
static int[] id;
static ArrayList<Integer>[] adj;
static ArrayList<Integer>[] bid;
static int n;
public static class in {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream in) {
reader = new BufferedReader(
new InputStreamReader(in));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
inline long long in() {
int32_t x;
scanf("%d", &x);
return x;
}
inline string getStr() {
char ch[200];
scanf("%s", ch);
return ch;
}
inline char getCh() {
char ch;
scanf(" %c", &ch);
return ch;
}
template <class P, class Q>
inline P smin(P &a, Q b) {
if (b < a) a = b;
return a;
}
template <class P, class Q>
inline P smax(P &a, Q b) {
if (a < b) a = b;
return a;
}
const long long MOD = 1e10;
const long long MAX_N = 1e6 + 10;
const long long MAX_LG = 21;
const long long base = 29;
vector<long long> g[MAX_N];
bool mark[MAX_N], st[MAX_N];
long long lvl[MAX_N], h[MAX_N], cmp;
long long component[MAX_N], cmpSize[MAX_N];
stack<long long> Stack;
inline void dfs(long long v, long long dep = 0) {
lvl[v] = h[v] = dep;
st[v] = mark[v] = true;
Stack.push(v);
for (long long i = 0; i < g[v].size(); i++) {
long long u = g[v][i];
if (!mark[u]) {
dfs(u, dep + 1);
smin(h[v], h[u]);
} else if (st[u])
smin(h[v], h[u]);
}
if (h[v] == lvl[v]) {
long long node;
do {
node = Stack.top(), Stack.pop();
component[node] = cmp;
cmpSize[cmp]++;
st[node] = false;
} while (node != v);
cmp++;
}
}
long long pr[MAX_N], sz[MAX_N], f[MAX_N];
inline long long root(long long p) {
return (p == pr[p] ? p : pr[p] = root(pr[p]));
}
inline void merge(long long p, long long q) {
p = root(p), q = root(q);
if (p == q) return;
if (sz[p] < sz[q]) swap(p, q);
pr[q] = p;
if (sz[p] == sz[q]) sz[p]++;
}
long long res;
int32_t main() {
long long n = in(), m = in();
res = n;
for (long long i = 0; i < m; i++) {
long long v = in(), u = in();
g[v].push_back(u);
}
for (long long i = 1; i <= n; i++) {
if (!mark[i]) dfs(i);
}
for (long long i = 0; i < cmp; i++) {
pr[i] = i, sz[i] = 1;
}
for (long long i = 1; i <= n; i++) {
long long v = component[i];
for (long long j = 0; j < g[i].size(); j++) {
long long u = component[g[i][j]];
merge(v, u);
}
}
for (long long i = 1; i <= n; i++) {
long long Root = root(component[i]);
f[Root] |= (cmpSize[component[i]] > 1);
}
for (long long i = 0; i < cmp; i++)
if (!f[i] && root(i) == i) res--;
cout << res << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> E[100005];
int P[100005], S[100005];
int find(int i) { return (P[i] == i ? i : P[i] = find(P[i])); }
bool join(int i, int j) {
i = find(i), j = find(j);
if (i == j) return false;
if (S[i] > S[j]) swap(i, j);
P[i] = j;
S[j] += S[i];
return true;
}
bool onstack[100005];
bool vis[100005];
bool add[100005];
bool has_cycle(int i) {
if (onstack[i]) return true;
if (vis[i]) return false;
vis[i] = true;
onstack[i] = true;
bool ans = false;
int numE = E[i].size();
for (int x = 0; x < (numE); ++x) {
int j = E[i][x];
if (has_cycle(j)) ans = true;
}
onstack[i] = false;
return ans;
}
int main() {
int N, M, a, b;
scanf("%d%d", &N, &M);
for (int q = 0; q < (M); ++q) {
scanf("%d%d", &a, &b);
a--;
b--;
E[a].push_back(b);
}
for (int i = 0; i < (N); ++i) P[i] = i, S[i] = 1;
for (int i = 0; i < (N); ++i) {
int numE = E[i].size();
for (int x = 0; x < (numE); ++x) join(i, E[i][x]);
}
for (int i = 0; i < (N); ++i)
if (!vis[i] && has_cycle(i)) add[find(i)] = true;
int ans = 0;
for (int i = 0; i < (N); ++i)
if (P[i] == i) ans += S[i] - 1 + add[i];
cout << ans << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int read() {
int x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
int n, m, scc, ind;
int dfn[100005], low[100005], instack[100005];
int belong[100005];
int sum[100005];
vector<int> v[100005];
stack<int> st;
void tarjan(int x) {
dfn[x] = low[x] = ++ind;
instack[x] = 1;
st.push(x);
for (int i = 0; i < v[x].size(); i++) {
int V = v[x][i];
if (!dfn[V]) {
tarjan(V);
low[x] = min(low[x], low[V]);
} else if (instack[V])
low[x] = min(low[x], dfn[V]);
}
if (dfn[x] == low[x]) {
static int now;
scc++;
while (now != x) {
now = st.top();
st.pop();
instack[now] = 0;
belong[now] = scc;
sum[scc]++;
}
}
}
int father[100005], flag[100005];
int findf(int x) { return father[x] == x ? x : father[x] = findf(father[x]); }
void mergef(int x, int y) {
father[x] = y;
sum[y] += sum[x];
flag[y] |= flag[x];
}
int main() {
n = read(), m = read();
for (int i = 1; i <= m; i++) {
static int x, y;
x = read(), y = read();
v[x].push_back(y);
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
int ans = 0;
for (int i = 1; i <= scc; i++)
if (sum[i] > 1) flag[i] = 1;
for (int i = 1; i <= scc; i++) father[i] = i;
for (int i = 1; i <= n; i++)
for (int j = 0; j < v[i].size(); j++) {
int V = v[i][j];
if (belong[i] != belong[V]) {
static int x, y, fx, fy;
x = belong[i], y = belong[V];
fx = findf(x), fy = findf(y);
if (fx != fy) mergef(fx, fy);
}
}
for (int i = 1; i <= scc; i++)
if (findf(i) == i) {
ans += sum[i] - 1;
if (flag[i]) ans++;
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
public class Task {
public static void main(String[] args) throws IOException {
new Task().solve();
}
PrintWriter out;
int cnt = 0;
int n;
boolean[] used;
ArrayList<Integer>[] g;
ArrayList<Integer>[] rg;
ArrayList<Integer> tsort = new ArrayList<Integer>();
int[] comp;
int[] compsize;
void solve() throws IOException{
Reader in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
//out = new PrintWriter(new FileWriter(new File("output.txt")));
int n = in.nextInt();
int m = in.nextInt();
g = new ArrayList[n];
rg = new ArrayList[n];
used = new boolean[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<Integer>();
rg[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
g[x].add(y);
rg[y].add(x);
}
for (int i = 0; i < n; i++)
if (!used[i])
dfs(i);
Arrays.fill(used, false);
Collections.reverse(tsort);
comp = new int[n];
compsize = new int[n];
int cnt = 0;
for (int v : tsort)
if (!used[v]) {
rdfs(v, cnt);
cnt++;
}
for (int i = 0; i < n; i++) {
compsize[comp[i]]++;
}
Arrays.fill(used, false);
int ans = n;
for (int i = 0; i < n; i++)
if (!used[i] && dfs2(i)) {
ans--;
}
out.print(ans);
out.flush();
out.close();
}
void dfs(int v) {
used[v] = true;
for (int k : g[v])
if (!used[k])
dfs(k);
tsort.add(v);
}
void rdfs(int v, int cnt) {
used[v] = true;
comp[v] = cnt;
for (int k : rg[v])
if (!used[k])
rdfs(k, cnt);
}
boolean dfs2(int v) {
used[v] = true;
boolean res = compsize[comp[v]] == 1;
for (int k : g[v])
if (!used[k])
res &= dfs2(k);
for (int k : rg[v])
if (!used[k])
res &= dfs2(k);
return res;
}
long pow(int x, int m) {
if (m == 0)
return 1;
return x*pow(x, m-1);
}
}
class Pair {
int v;
int z;
Pair (int v, int z) {
this.v = v;
this.z = z;
}
}
class Item implements Comparable<Item> {
int v;
int l;
int z;
Item(int v, int l, int z) {
this.v = v;
this.l = l;
this.z = z;
}
@Override
public int compareTo(Item item) {
if (l > item.l)
return 1;
else
if (l < item.l)
return -1;
else {
if (z > item.z)
return 1;
else
if (z < item.z)
return -1;
return 0;
}
}
}
class Reader {
StringTokenizer token;
BufferedReader in;
public Reader(String file) throws IOException {
//in = new BufferedReader( new FileReader( file ) );
in = new BufferedReader( new InputStreamReader( System.in ) );
}
public byte nextByte() throws IOException {
return Byte.parseByte(Next());
}
public int nextInt() throws IOException {
return Integer.parseInt(Next());
}
public long nextLong() throws IOException {
return Long.parseLong(Next());
}
public String nextString() throws IOException {
return in.readLine();
}
private String Next() throws IOException {
while (token == null || !token.hasMoreTokens()) {
token = new StringTokenizer(in.readLine());
}
return token.nextToken();
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5 + 10;
int n, m, parent[maxN], num_comp, res, num[maxN], low[maxN], num_node,
unavail[maxN], comp[maxN], sze[maxN];
vector<int> adj[maxN];
stack<int> st;
struct Edge {
int u, v;
} e[maxN];
int get_root(int u) {
return (u == parent[u] ? u : (parent[u] = get_root(parent[u])));
}
void visit(int u) {
low[u] = num[u] = ++num_node;
st.push(u);
for (int v : adj[u])
if (!unavail[v]) {
if (!num[v]) visit(v);
low[u] = min(low[u], low[v]);
}
if (low[u] == num[u]) {
int v = 0;
++num_comp;
while (v != u) {
v = st.top();
st.pop();
++sze[num_comp];
unavail[v] = 1;
comp[v] = num_comp;
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; ++i) {
scanf("%d %d", &e[i].u, &e[i].v);
adj[e[i].u].push_back(e[i].v);
}
for (int i = 1; i <= n; ++i)
if (num[i] == 0) visit(i);
res = n;
for (int i = 1; i <= num_comp; ++i) parent[i] = i;
for (int i = 0; i < m; ++i)
parent[get_root(comp[e[i].u])] = get_root(comp[e[i].v]);
for (int i = 1; i <= num_comp; ++i)
sze[get_root(i)] = max(sze[get_root(i)], sze[i]);
for (int i = 1; i <= num_comp; ++i)
if (i == get_root(i)) --res, res += (sze[i] > 1);
cout << res;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int m = readInt();
LinkedList<Edge>[] edges = new LinkedList[n];
for(int i = 0; i < n; i++) {
edges[i] = new LinkedList<Edge>();
}
while(m-- > 0) {
int a = readInt()-1;
int b = readInt()-1;
edges[a].add(new Edge(b, true));
edges[b].add(new Edge(a, false));
}
boolean[] seen = new boolean[n];
int ret = 0;
for(int i = 0; i < n; i++) {
if(seen[i] || edges[i].isEmpty()) continue;
LinkedList<Integer> q = new LinkedList<Integer>();
Map<Integer, Integer> p = new HashMap<Integer, Integer>();
q.add(i);
seen[i] = true;
p.put(i, 0);
while(!q.isEmpty()) {
int curr = q.removeFirst();
for(Edge out: edges[curr]) {
if(!p.containsKey(out.to)) {
p.put(out.to, 0);
}
if(out.real) {
p.put(out.to, p.get(out.to) + 1);
}
if(!seen[out.to]) {
seen[out.to] = true;
q.add(out.to);
}
}
}
int add = 0;
for(int out: p.keySet()) {
if(p.get(out) == 0) {
q.add(out);
}
}
while(!q.isEmpty()) {
int curr = q.removeFirst();
add++;
for(Edge out: edges[curr]) {
if(out.real) {
int next = p.get(out.to) - 1;
if(next == 0) {
q.add(out.to);
}
p.put(out.to, next);
}
}
}
if(add == p.size()) {
ret += p.size()-1;
}
else {
ret += p.size();
}
}
pw.println(ret);
}
exitImmediately();
}
static class Edge {
public int to;
public boolean real;
public Edge(int to, boolean real) {
super();
this.to = to;
this.real = real;
}
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
if(!br.ready()) {
exitImmediately();
}
st = null;
return br.readLine();
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, nxt;
} e[100005];
int head[100005], cnte, n, m;
void adde(int u, int v) {
e[++cnte] = (edge){v, head[u]};
head[u] = cnte;
}
int fa[100005];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void merge(int x, int y) {
if ((x = find(x)) ^ (y = find(y))) fa[x] = y;
}
queue<int> q;
int vis[100005], in[100005];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
while (m--) {
int u, v;
scanf("%d%d", &u, &v);
adde(u, v);
merge(u, v);
in[v]++;
}
int ans = n;
for (int i = 1; i <= n; i++)
fa[i] = find(i), ans -= vis[fa[i]] == 0, vis[fa[i]] = 1;
for (int i = 1; i <= n; i++)
if (!in[i]) q.push(i);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].to;
in[v]--;
if (!in[v]) q.push(v);
}
}
for (int i = 1; i <= n; i++)
if (in[i]) ans += vis[fa[i]], vis[fa[i]] = 0;
return printf("%d\n", ans), 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> adj[(100005)];
int N, M;
pair<int, int> edges[(100005)];
int num_comp;
int comp[(100005)];
int num_members[(100005)];
int visited[(100005)];
bool cycle[(100005)];
void dfs(int at) {
num_members[num_comp]++;
comp[at] = num_comp;
visited[at] = true;
for (int v : adj[at]) {
if (!visited[v]) {
dfs(v);
}
}
}
void dfs2(int at) {
visited[at] = 1;
for (int v : adj[at]) {
if (visited[v] == 0) {
dfs2(v);
} else if (visited[v] == 1) {
cycle[comp[at]] = true;
}
}
visited[at] = 2;
}
int main() {
int u, v;
scanf("%d %d", &N, &M);
for (int(i) = 0; (i) < (M); ++(i)) {
scanf("%d %d", &u, &v);
edges[i] = {u, v};
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 1; i <= N; i++) {
if (!visited[i]) {
num_comp++;
dfs(i);
}
}
for (int i = 1; i <= N; i++) adj[i].clear();
for (int(i) = 0; (i) < (M); ++(i)) {
adj[edges[i].first].push_back(edges[i].second);
}
memset(visited, 0, sizeof(visited));
for (int i = 1; i <= N; i++) {
if (!visited[i]) {
dfs2(i);
}
}
int ans = 0;
for (int i = 1; i <= num_comp; i++) {
if (cycle[i])
ans += num_members[i];
else
ans += num_members[i] - 1;
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
public class Equal {
static int mod = (int) (1e9 + 7);
static ArrayList<Integer>[] adjList;
static int V, counter, c, SCC, dfs_num[], dfs_low[];
static boolean[] inSCC;
static Stack<Integer> stack;
static int ans;
static void tarjanSCC() // O(V + E)
{
counter = 0;
SCC = 0;
dfs_low = new int[V];
dfs_num = new int[V];
inSCC = new boolean[V];
stack = new Stack<>();
for (int i = 0; i < V; ++i) {
counter = 0;
SCC = 0;
int sum = 0;
for (int x : arr[i]) {
if (dfs_num[x] == 0) {
sum += tarjanSCC(x);
}
}
if (sum != 0) {
if (sum == SCC)
ans += sum - 1;
else
ans += sum;
// System.out.println(sum + " " + SCC);
}
}
}
static int tarjanSCC(int u) {
dfs_num[u] = dfs_low[u] = ++counter;
stack.push(u);
int sum = 1;
for (int v : adjList[u]) {
if (dfs_num[v] == 0)
sum += tarjanSCC(v);
if (!inSCC[v])
dfs_low[u] = Math.min(dfs_low[u], dfs_low[v]);
}
if (dfs_num[u] == dfs_low[u]) {
// SCC found
SCC++;
while (true) {
int v = stack.pop();
inSCC[v] = true;
if (v == u)
break;
}
}
return sum;
}
static ArrayList<Integer>[] arr;
public static void main(String[] args) throws IOException {
// BufferedReader br = new BufferedReader(new FileReader("name.in"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter pw = new PrintWriter(System.out);
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
V = n;
UnionFind uf = new UnionFind(n);
adjList = new ArrayList[n];
arr = new ArrayList[n];
for (int i = 0; i < adjList.length; i++) {
adjList[i] = new ArrayList<>();
arr[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken()) - 1;
int v = Integer.parseInt(st.nextToken()) - 1;
adjList[u].add(v);
uf.unionSet(u, v);
}
for (int i = 0; i < n; i++) {
arr[uf.findSet(i)].add(i);
}
// for (int i = 0; i < n; i++) {
// System.out.println(arr[i]);
// }
ans = 0;
tarjanSCC();
pw.println(ans);
pw.flush();
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
public UnionFind(int N) {
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) {
p[i] = i;
setSize[i] = 1;
}
}
public int findSet(int i) {
return p[i] == i ? i : (p[i] = findSet(p[i]));
}
public boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
public void unionSet(int i, int j) {
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x;
setSize[x] += setSize[y];
} else {
p[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y])
rank[y]++;
}
}
public int numDisjointSets() {
return numSets;
}
public int sizeOfSet(int i) {
return setSize[findSet(i)];
}
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 233333;
vector<int> g[maxn];
int r[maxn];
int f[maxn];
bool p[maxn];
queue<int> que;
int find(int u) {
int v = u;
while (v != f[v]) v = f[v];
while (u != f[u]) {
int w = f[u];
f[u] = v;
u = w;
}
return u;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) f[i] = i;
for (int i = 1; i <= m; ++i) {
int a, b;
scanf("%d%d", &a, &b);
g[a].push_back(b);
++r[b];
if (find(a) != find(b)) f[f[a]] = f[b];
}
for (int i = 1; i <= n; ++i)
if (r[i] == 0) que.push(i);
while (!que.empty()) {
int u = que.front();
p[u] = 1;
que.pop();
for (int i = 0; i < (int)g[u].size(); ++i)
if (--r[g[u][i]] == 0) que.push(g[u][i]);
}
for (int i = 1; i <= n; ++i)
if (!p[i]) p[find(i)] = 0;
int ans = n;
for (int i = 1; i <= n; ++i)
if (find(i) == i && p[i]) --ans;
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int SZ = 100101;
vector<int> g[SZ], g1[SZ];
vector<int> used;
int c[SZ], c_color[SZ], cnt[SZ];
void dfs(int u) {
used[u] = -1;
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (!used[v])
dfs(v);
else if (used[v] == -1)
c[u] = 1;
}
used[u] = 1;
}
void dfs1(int u, int k) {
used[u] = k;
cnt[k]++;
if (c[u]) c_color[k] = 1;
for (int i = 0; i < g1[u].size(); i++) {
int v = g1[u][i];
if (!used[v]) dfs1(v, k);
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
int u, v;
scanf("%d %d", &u, &v);
g[u - 1].push_back(v - 1);
g1[u - 1].push_back(v - 1);
g1[v - 1].push_back(u - 1);
}
used.assign(n + 1, 0);
for (int i = 0; i < n; i++) {
if (!used[i]) dfs(i);
}
int color = 1;
used.assign(n + 1, 0);
for (int i = 0; i < n; i++) {
if (!used[i]) dfs1(i, color++);
}
int res = 0;
for (int i = 1; i < color; i++) res += cnt[i] - 1 + c_color[i];
cout << res;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class B {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static ArrayList<Integer>[]ages;
static ArrayList<Integer>[]ages2;
static int[]color;
static boolean cicle;
static ArrayList<Integer> comp;
static boolean[]used;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
ages = new ArrayList[n+1];
ages2 = new ArrayList[n+1];
for (int i = 1; i <= n; i++) {
ages[i] = new ArrayList<>();
ages2[i] = new ArrayList<>();
}
int m = nextInt();
for (int i = 1; i <= m; i++) {
int v1 = nextInt();
int v2 = nextInt();
ages[v1].add(v2);
ages2[v1].add(v2);
ages2[v2].add(v1);
}
color = new int[n+1];
comp = new ArrayList<>();
used = new boolean[n+1];
int ans = 0;
for (int i = 1; i <= n; i++) {
if (color[i]==0) {
comp.clear();
dfs(i);
cicle = false;
for (int j : comp) {
if (color[j]==0)
dfs2(j);
}
if (!cicle)
ans += comp.size()-1;
else
ans += comp.size();
}
}
System.out.println(ans);
pw.close();
}
private static void dfs2(int v) {
color[v] = 1;
for (int to : ages[v]) {
if (color[to]==0)
dfs2(to);
else if (color[to]==1)
cicle = true;
}
color[v] = 2;
}
private static void dfs(int v) {
used[v] = true;
comp.add(v);
for (int to : ages2[v]) {
if (!used[to])
dfs(to);
}
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.util.ArrayList;
import java.util.Scanner;
public class DFSTEST {
static boolean[] components ;
static class Node{
ArrayList<Node> out = new ArrayList<>() , in = new ArrayList<>() ;
int component = 0 ;
int state = 0 ;
}
static void dfs(Node node , int component){
node.component = component ;
for(Node neighbor : node.out)
if(neighbor.component == 0)
dfs(neighbor , component);
for(Node neighbor : node.in)
if(neighbor.component == 0)
dfs(neighbor , component);
}
static void check(Node node){
node.state = 1 ;
for(Node neighbor:node.out) {
if (neighbor.state == 0)
check(neighbor);
if (neighbor.state == 1)
components[node.component] = true;
}
node.state = 2 ;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in) ;
int n = scanner.nextInt() ;
int m = scanner.nextInt() ;
Node[] nodes = new Node[n] ;
for(int i = 0 ; i < n ; i ++)
nodes[i] = new Node() ;
for(int i = 0 ; i < m ; i ++){
int x = scanner.nextInt() - 1 , y = scanner.nextInt() - 1 ;
nodes[x].out.add(nodes[y]) ;
nodes[y].in.add(nodes[x]) ;
}
int now = 0 ;
for(int i = 0; i < n ; i ++) {
if (nodes[i].component == 0)
dfs(nodes[i], ++now);
}
components = new boolean[now + 1] ;
for(int i = 0; i < n ; i ++) {
if(nodes[i].state == 0)
check(nodes[i]);
}
int ans = n ;
for(int i = 0 ; i < now ; i ++){
if(!components[i + 1])
ans -- ;
}
System.out.println(ans);
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int g_n, g_m;
vector<int> vvi_edge[maxn], has[maxn], vvi_uv[maxn];
int vi_dg[maxn];
int mark;
int vi_mark[maxn];
void dfs(int u) {
vi_mark[u] = mark;
int len = vvi_edge[u].size();
for (int i = 0; i < len; i++) {
int v = vvi_edge[u][i];
if (vi_mark[v]) continue;
dfs(v);
}
}
bool can(int id) {
int len = has[id].size();
queue<int> q;
for (int i = 0; i < len; i++)
if (vi_dg[has[id][i]] == 0) q.push(has[id][i]);
while (!q.empty()) {
int u = q.front();
q.pop();
len = vvi_uv[u].size();
for (int i = 0; i < len; i++) {
vi_dg[vvi_uv[u][i]]--;
if (!vi_dg[vvi_uv[u][i]]) q.push(vvi_uv[u][i]);
}
}
len = has[id].size();
for (int i = 0; i < len; i++)
if (vi_dg[has[id][i]]) return true;
return false;
}
int main() {
while (scanf("%d%d", &g_n, &g_m) != EOF) {
int u, v;
memset(vi_dg, 0, sizeof(vi_dg));
for (int i = 0; i <= g_n; i++) {
vvi_uv[i].clear();
vvi_edge[i].clear();
has[i].clear();
}
for (int i = 1; i <= g_m; i++) {
scanf("%d%d", &u, &v);
vvi_edge[u].push_back(v);
vvi_edge[v].push_back(u);
vvi_uv[v].push_back(u);
vi_dg[u]++;
}
mark = 1;
memset(vi_mark, 0, sizeof(vi_mark));
for (int i = 1; i <= g_n; i++) {
if (!vi_mark[i]) {
dfs(i);
mark++;
}
}
for (int i = 1; i <= g_n; i++) has[vi_mark[i]].push_back(i);
int ans = 0;
for (int i = 1; i < mark; i++)
if (can(i)) ans++;
printf("%d\n", g_n - mark + 1 + ans);
}
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class B {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
UnionFind uf = new UnionFind(n);
int[][] graph = buildDirectedGraph(in, n, m);
for (int i = 0 ; i < n ; i++) {
for (int j : graph[i]) {
uf.unite(i, j);
}
}
int ans = n;
boolean[] isok = new boolean[n];
Arrays.fill(isok, true);
SCC scc = new SCC(graph);
scc.scc();
for (int[] g : scc.groups()) {
if (g.length >= 2) {
int head = g[0];
int comp = uf.find(head);
isok[comp] = false;
}
}
boolean[] done = new boolean[n];
for (int i = 0 ; i < n ; i++) {
int g = uf.find(i);
if (!done[g]) {
done[g] = true;
if (isok[g]) {
ans--;
}
}
}
out.println(ans);
out.flush();
}
static int[][] buildDirectedGraph(InputReader in, int n, int m) {
int[][] edges = new int[m][];
int[][] graph = new int[n][];
int[] deg = new int[n];
for (int i = 0 ; i < m ; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
deg[a]++;
edges[i] = new int[]{a, b};
}
for (int i = 0 ; i < n ; i++) {
graph[i] = new int[deg[i]];
}
for (int i = 0 ; i < m ; i++) {
int a = edges[i][0];
int b = edges[i][1];
graph[a][--deg[a]] = b;
}
return graph;
}
static class SCC {
boolean[] visited;
int[] node_id;
List<Integer> rev;
int n;
int[][] graph;
int[][] r_graph;
SCC(int[][] g) {
n = g.length;
graph = g;
r_graph = new int[n][];
int[] deg = new int[n];
for (int i = 0 ; i < n ; i++) {
for (int j : graph[i]) {
deg[j]++;
}
}
for (int i = 0 ; i < n ; i++) {
r_graph[i] = new int[deg[i]];
}
for (int i = 0 ; i < n ; i++) {
for (int j : graph[i]) {
r_graph[j][--deg[j]] = i;
}
}
}
int[] scc() {
visited = new boolean[n];
rev = new ArrayList<Integer>();
for (int i = 0; i<n; i++) {
if (!visited[i]) {
dfs(i);
}
}
int id = 0;
node_id = new int[n];
visited = new boolean[n];
for (int i = rev.size()-1; i>=0; i--) {
if (!visited[rev.get(i)]) {
rdfs(rev.get(i), id);
id++;
}
}
return node_id;
}
int[][] groups() {
int max = 0;
for (int nid : node_id) {
max = Math.max(max, nid+1);
}
int[] gnum = new int[max];
for (int nid : node_id) {
gnum[nid]++;
}
int[][] groups = new int[max][];
for (int i = 0 ; i < max ; i++) {
groups[i] = new int[gnum[i]];
}
for (int i = 0 ; i < n ; i++) {
int nid = node_id[i];
groups[nid][--gnum[nid]] = i;
}
return groups;
}
public void dfs(int i) {
visited[i] = true;
for (int next : graph[i]) {
if (!visited[next]) {
dfs(next);
}
}
rev.add(i);
}
public void rdfs(int i, int id) {
visited[i] = true;
node_id[i] = id;
for (int next : r_graph[i]) {
if (!visited[next]) {
rdfs(next, id);
}
}
}
}
static class UnionFind {
int[] parent, rank;
UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0 ; i < n ; i++) {
parent[i] = i;
rank[i] = 0;
}
}
int find(int x) {
if (parent[x] == x) {
return x;
}
parent[x] = find(parent[x]);
return parent[x];
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return;
}
if (rank[x] < rank[y]) {
parent[x] = y;
} else {
parent[y] = x;
if (rank[x] == rank[y]) {
rank[x]++;
}
}
}
boolean issame(int x, int y) {
return (find(x) == find(y));
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int next() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int n, m, num, ans, col[N];
bool flag[N], vis[N], vis2[N];
vector<int> g1[N], g2[N];
void dfs1(int u) {
col[u] = num;
for (auto v : g2[u]) {
if (!col[v]) dfs1(v);
}
}
void dfs2(int u) {
vis[u] = vis2[u] = 1;
for (auto v : g1[u]) {
if (!vis[v])
dfs2(v);
else
flag[col[v]] |= vis2[v];
}
vis2[u] = 0;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int u, v;
scanf("%d%d", &u, &v);
g1[u].push_back(v);
g2[u].push_back(v);
g2[v].push_back(u);
}
for (int i = 1; i <= n; i++)
if (!col[i]) {
++num;
dfs1(i);
}
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs2(i);
for (int i = 1; i <= num; i++) ans += flag[i];
printf("%d", n - num + ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int N, tot, m, ans;
vector<int> Ed[100005];
int pp[200005], ne[200005], he[200005], in[200005], g[200005], q[200005];
bool bo[200005];
inline int IN() {
char c;
register int first = 0;
while ((c = getchar()) < 48 && c ^ '-' || c > 57)
;
bool f = c == '-';
if (f) (c = getchar());
for (; c > 47 && c < 58; (c = getchar())) first = first * 10 + c - 48;
if (f) first = -first;
return first;
}
inline void Link(int u, int v) {
if (u == v) return;
Ed[u].push_back(v);
Ed[v].push_back(u);
pp[++tot] = v;
ne[tot] = he[u];
he[u] = tot;
++in[v];
}
inline int topu(int u) {
int l, r;
bo[u] = 1;
for (g[l = r = 1] = u; l <= r; ++l) {
int v = g[l];
for (int w : Ed[v])
if (!bo[w]) {
g[++r] = w;
bo[w] = 1;
}
}
*q = 0;
for (int _r = r, i = 1; i <= _r; ++i)
if (!in[g[i]]) {
q[++*q] = g[i];
}
for (int i = 1; i <= *q; ++i) {
int v = q[i];
for (int e = he[v]; e; e = ne[e]) {
int w = pp[e];
if (!(--in[w])) q[++*q] = w;
}
}
return r - (*q == r);
}
int main() {
N = IN();
m = IN();
for (int _r = m, i = 1; i <= _r; ++i) {
int u = IN(), v = IN();
Link(u, v);
}
for (int _r = N, i = 1; i <= _r; ++i)
if (!bo[i]) ans += topu(i);
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
public class B {
ArrayList<Integer>[] from;
ArrayList<Integer>[] to;
int[] color;
int[] tOut;
boolean[] mark;
int[] size;
int time;
void run() {
int n = in.nextInt();
int pairs = in.nextInt();
int[] a = new int[pairs];
int[] b = new int[pairs];
from = new ArrayList[n];
to = new ArrayList[n];
color = new int[n];
tOut = new int[n];
mark = new boolean[n];
size = new int[n];
for (int i = 0; i < n; i++) {
from[i] = new ArrayList<Integer>();
to[i] = new ArrayList<Integer>();
}
for (int i = 0; i < pairs; i++) {
a[i] = in.nextInt() - 1;
b[i] = in.nextInt() - 1;
from[a[i]].add(b[i]);
to[b[i]].add(a[i]);
}
Arrays.fill(color, -1);
int comp = 0;
for (int i = 0; i < n; i++) {
if (color[i] >= 0) {
continue;
}
dfs1(i, comp);
comp++;
}
for (int i = 0; i < n; i++) {
dfs2(i);
}
boolean[] cycle = new boolean[comp];
for (int i = 0; i < pairs; i++) {
if (tOut[a[i]] > tOut[b[i]]) {
continue;
}
cycle[color[a[i]]] = true;
}
int ans = 0;
for (int i = 0; i < comp; i++) {
ans += size[i] - (cycle[i] ? 0 : 1);
}
out.println(ans);
}
void dfs1(int v, int comp) {
if (color[v] == comp) {
return;
}
color[v] = comp;
size[comp]++;
for (int u : from[v]) {
dfs1(u, comp);
}
for (int u : to[v]) {
dfs1(u, comp);
}
}
void dfs2(int v) {
if (mark[v]) {
return;
}
mark[v] = true;
for (int u : from[v]) {
dfs2(u);
}
tOut[v] = time;
time++;
}
static boolean stdStreams = true;
static String fileName = B.class.getSimpleName().replaceFirst("_.*", "").toLowerCase();
static String inputFileName = fileName + ".in";
static String outputFileName = fileName + ".out";
static MyScanner in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
BufferedReader br;
if (stdStreams) {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
br = new BufferedReader(new FileReader(inputFileName));
out = new PrintWriter(outputFileName);
}
in = new MyScanner(br);
int tests = 1;//in.nextInt();
for (int test = 0; test < tests; test++) {
new B().run();
}
br.close();
out.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
public class R286qBMrKitayatuTech {
static int n,m,ans,s,count;
static ArrayList<Integer> forw[],revs[],list[];
static int vis[];
@SuppressWarnings("unchecked")
public static void main(String args[] ) throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
n = in.nextInt();
m = in.nextInt();
forw = new ArrayList[n];
revs = new ArrayList[n];
list = new ArrayList[n];
for(int i=0;i<n;i++){
forw[i] = new ArrayList<Integer>();
revs[i] = new ArrayList<Integer>();
}
for(int i=0;i<m;i++){
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
forw[a].add(b);
revs[b].add(a);
}
ans = n;
vis = new int[n];
for(int i=0;i<n;i++){
if(vis[i] == 0){
list[count] = new ArrayList<Integer>();
vis[i] = 1;
dfs(i);
count++;
}
}
ans -= count;
Arrays.fill(vis, 0);
for(int i=0;i<count;i++){
for(int j : list[i]){
if(vis[j] == 0){
if(dfs2(j)){
ans++;
break;
}
}
}
}
w.println(ans);
w.close();
}
public static void dfs(int curr){
list[count].add(curr);
for(int i=0;i<forw[curr].size();i++){
int nxt = forw[curr].get(i);
if(vis[nxt] == 0){
vis[nxt] = 1;
dfs(nxt);
}
}
for(int i=0;i<revs[curr].size();i++){
int nxt = revs[curr].get(i);
if(vis[nxt] == 0){
vis[nxt] = 1;
dfs(nxt);
}
}
}
public static boolean dfs2(int curr){
vis[curr] = 1;
for(int i=0;i<forw[curr].size();i++){
int nxt = forw[curr].get(i);
if(vis[nxt] == 1)
return true;
else if(vis[nxt] == 0 && dfs2(nxt))
return true;
}
vis[curr] = 2;
return false;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | // package Div2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Sketch {
private static class Node {
public int src;
public int last;
public boolean isHead;
public boolean hasCircle;
public int numNodes;
public Node(int i){
src = i;
last = -1;
isHead = true;
hasCircle = false;
numNodes = 1;
}
public int getSrc(){
int cur = src;
while(!nodes[cur].isHead){
cur = nodes[cur].src;
}
src = cur;
return cur;
}
}
private static class Edge {
public int prev;
public int next;
public Edge(int prev, int next){
this.prev = prev;
this.next = next;
}
}
private static final int LEN = 100000;
private static Node[] nodes = new Node[LEN];
private static Edge[] edges = new Edge[LEN];
private static int end = 0;
private static boolean[] visited;
private static boolean[] edgeVisited = new boolean[LEN];
private static boolean[] passed;
private static void addEdge(int u, int v){
edges[end] = new Edge(nodes[u].last, v);
nodes[u].last = end++;
int a = nodes[u].getSrc();
int b = nodes[v].getSrc();
if(a!=b) {
if(nodes[a].numNodes > nodes[b].numNodes){
nodes[a].isHead = false;
nodes[a].src = b;
nodes[b].numNodes += nodes[a].numNodes;
}
else {
nodes[b].isHead = false;
nodes[b].src = a;
nodes[a].numNodes += nodes[b].numNodes;
}
}
}
private static void dfs(int u){
Stack<Integer> stack = new Stack<Integer>();
int src = nodes[u].getSrc();
if(nodes[src].hasCircle)
return;
visited[u] = true;
stack.push(u);
boolean circle = false;
while(!stack.empty()){
int idx = stack.peek();
passed[idx] = true;
boolean flag = false;
for(int e=nodes[idx].last; e!=-1; e=edges[e].prev){
int nxt = edges[e].next;
if(passed[nxt]){
circle = true;
break;
}
if(!edgeVisited[e]){
flag = true;
stack.push(nxt);
visited[nxt] = true;
edgeVisited[e] = true;
}
}
if(!flag){
passed[idx] = false;
stack.pop();
}
}
if(circle){
nodes[src].hasCircle = true;
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
for(int i=0; i<n; i++)
nodes[i] = new Node(i);
for(int i=0; i<m; i++){
int u = input.nextInt()-1;
int v = input.nextInt()-1;
addEdge(u, v);
}
input.close();
visited = new boolean[n];
passed = new boolean[n];
for(int i=0; i<n; i++){
if(!visited[i]){
dfs(i);
}
}
int ret = n;
for(int i=0; i<n; i++){
if(nodes[i].isHead && !nodes[i].hasCircle){
ret--;
}
}
System.out.println(ret);
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxx = 1e5 + 20;
int markk[maxx];
bool hasCycle, mark[maxx];
vector<int> adj[maxx];
vector<int> nei[maxx];
vector<int> vec;
void DFS(int v) {
mark[v] = true;
vec.push_back(v);
for (int i = 0; i < adj[v].size(); i++)
if (!mark[adj[v][i]]) DFS(adj[v][i]);
}
void find_cycle(int v) {
markk[v] = 1;
for (int i = 0; i < nei[v].size(); i++) {
int u = nei[v][i];
if (markk[u] == 0)
find_cycle(u);
else if (markk[u] == 1)
hasCycle = true;
}
markk[v] = 2;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
adj[u].push_back(v);
adj[v].push_back(u);
nei[u].push_back(v);
}
int ans = n;
for (int i = 0; i < n; i++) {
if (!markk[i]) {
vec.clear();
DFS(i);
for (int i = 0; i < vec.size(); i++) find_cycle(vec[i]);
if (!hasCycle) ans--;
hasCycle = false;
}
}
cout << ans << "\n";
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Map.Entry;
import java.util.Stack;
public class B {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
class SCC {
int n;
boolean[] visited;
ArrayList<Integer>[] g, rg;
ArrayList<Integer> vs; //post order
int[] cmp;
SCC(ArrayList<Integer>[] g) {
this.g = g;
this.n = g.length;
this.visited = new boolean[n];
this.vs = new ArrayList<Integer>();
// set reverse graph
rg = new ArrayList[n];
for (int i = 0; i < n; i++)
rg[i] = new ArrayList<Integer>();
for (int u = 0; u < n; u++) {
for (int v : g[u]) {
rg[v].add(u);
}
}
}
void dfs(int u) {
visited[u] = true;
for (int v : g[u]) {
if (!visited[v]) dfs(v);
}
vs.add(u);
}
void rdfs(int u, int idx) {
visited[u] = true;
cmp[u] = idx;
for (int v : rg[u]) {
if (!visited[v]) rdfs(v, idx);
}
}
ArrayList<Integer> getPostOrderList() {
vs.clear();
Arrays.fill(visited, false);
for (int i = 0; i < n; i++) {
if (!visited[i]) dfs(i);
}
return vs;
}
int[] doit() {
cmp = new int[n];
Arrays.fill(visited, false);
for (int i = 0; i < n; i++) {
if (!visited[i]) dfs(i);
}
int idx = 0;
Arrays.fill(visited, false);
for (int i = n - 1; i >= 0; i--) {
int next = vs.get(i);
if (!visited[next]) rdfs(next, idx++);
}
return cmp;
}
}
void dfs(int u, int[] cmp) {
visited[u] = true;
if (hash.containsKey(cmp[u])) {
int x = hash.get(cmp[u]);
hash.put(cmp[u], x + 1);
} else {
hash.put(cmp[u], 1);
}
for (int v : g[u]) {
if (!visited[v]) dfs(v, cmp);
}
}
boolean[] visited;
HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
ArrayList<Integer>[] g;
public void run() {
int n = in.nextInt(), m = in.nextInt();
int[] a = new int[m];
int[] b = new int[m];
g = new ArrayList[n];
for (int i = 0; i < n; i++)
g[i] = new ArrayList<Integer>();
HashSet<Long> used = new HashSet<Long>();
int res = 0;
for (int i = 0; i < m; i++) {
a[i] = in.nextInt() - 1;
b[i] = in.nextInt() - 1;
g[a[i]].add(b[i]);
used.add(a[i] * 1000000L + b[i]);
}
SCC scc = new SCC(g);
int[] cmp = scc.doit();
for (int i = 0; i < m; i++) {
if (!used.contains(b[i] * 1000000L + b[i]))
g[b[i]].add(a[i]);
}
ArrayList<Integer> vs = scc.getPostOrderList();
visited = new boolean[n];
for (int i = n - 1; i >= 0; i--) {
int next = vs.get(i);
if (!visited[next]) {
hash.clear();
dfs(next, cmp);
int sum = 0;
int loop = 0;
for (Entry<Integer, Integer> e : hash.entrySet()) {
sum += e.getValue();
if (e.getValue() != 1) loop = 1;
}
res += sum - 1 + loop;
}
}
System.out.println(res);
out.close();
}
public static void main(String[] args) {
new B().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
int m, n, ans = 0;
bool st[N], en[N];
vector<int> gr[N], lis[N];
int par[N];
bool DAG;
int fin(int u) {
if (par[u] == u) return u;
return par[u] = fin(par[u]);
}
void dj(int u, int v) {
int pu = fin(u), pv = fin(v);
par[pu] = pv;
}
void dfs(int i) {
if (DAG) return;
st[i] = true;
for (int j : gr[i]) {
if (st[j]) {
if (en[j] == false) {
DAG = true;
break;
}
} else
dfs(j);
}
en[i] = true;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) par[i] = i;
while (m--) {
int u, v;
cin >> u >> v;
gr[u].push_back(v);
dj(u, v);
}
for (int i = 1; i <= n; i++) {
lis[fin(i)].push_back(i);
}
for (int i = 1; i <= n; i++) {
if (lis[i].size() <= 1) continue;
DAG = false;
for (int j : lis[i]) {
if (DAG) break;
if (!st[j]) dfs(j);
}
if (DAG)
ans += lis[i].size();
else
ans += lis[i].size() - 1;
}
cout << ans;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.util.*;
import java.io.*;
public class Main {
static BufferedReader in;
static PrintWriter out;
public static void main(String[] arguments) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
CF48D solve = new CF48D(in,out);
solve.solve();
out.close();
}
}
class InputLoad {
BufferedReader in;
StringTokenizer Input;
public InputLoad(BufferedReader in) {
this.in = in;
}
String nextToken() {
while (Input == null || !Input.hasMoreTokens())
try {
Input = new StringTokenizer(in.readLine());
} catch (IOException e) {
return null;
}
return Input.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
}
class CF48D {
InputLoad in;
PrintWriter out;
List<Integer>[] ke;
class Pair {
Integer first, second;
public Integer first() {
return this.first;
}
public Integer second() {
return this.second;
}
public Pair (int first,int second) {
this.first = first;
this.second = second;
}
}
public CF48D (BufferedReader in, PrintWriter out) {
this.in = new InputLoad(in);
this.out = out;
}
void tarjan(int s) {
Stack<Pair> stDFS = new Stack<Pair>();
stDFS.clear();
stDFS.push(new Pair(s,0));
while (!stDFS.empty()) {
int u = stDFS.peek().first();
int sta = stDFS.peek().second();
stDFS.pop();
if (sta == 0) {
st.push(u);
low[u] = n+1;
dem++;
num[u] = dem;
}
boolean stop = false;
for(int i=sta; i<ke[u].size(); i++) {
int v = ke[u].get(i);
if (tp[v] == 0)
if (num[v] == 0) {
tr[v] = u;
stDFS.push(new Pair(u,i+1));
stDFS.push(new Pair(v,0));
stop = true;
break;
} else low[u] = Math.min(low[u], num[v]);
}
if (!stop) {
for(int i=0; i<ke[u].size(); i++) {
int v = ke[u].get(i);
if (tp[v] == 0 && tr[v] == u)
low[u] = Math.min(low[v], low[u]);
}
if (low[u] >= num[u]) {
++demTp;
int dinh;
do {
dinh = st.pop();
tp[dinh] = demTp;
++slDinh[demTp];
} while (dinh != u);
}
}
}
}
int loang(int s) {
Queue<Integer> hd = new LinkedList();
while (!hd.isEmpty()) hd.remove();
hd.add(new Integer(s));
tr[s] = -1;
int res = 0;
boolean scc = false;
while (!hd.isEmpty()) {
int u = hd.remove();
++res;
for(int i=0; i<ke[u].size(); i++) {
int v= ke[u].get(i);
if (tr[v] == 0) {
tr[v] = u;
hd.add(new Integer(v));
}
if (slDinh[tp[u]] > 1) scc = true;
}
}
if (!scc) --res;
return res;
}
public void solve() {
n = in.nextInt();
m = in.nextInt();
low = new int[n+1];
num = new int[n+1];
scc = new int[n+1];
tp = new int[n+1];
slDinh = new int[n+1];
tr = new int[n+1];
int[][] ca = new int[m+1][2];
ke = (List<Integer>[]) new List[n+1];
st = new Stack<Integer>();
for(int i=0; i<=n; i++) ke[i] = new ArrayList<Integer>();
for(int i=0; i<m; i++) {
int x,y;
x = in.nextInt();
y = in.nextInt();
ca[i][0] = x;
ca[i][1] = y;
ke[x].add(y);
}
for(int i=1; i<=n; i++)
if (tp[i] == 0) tarjan(i);
for(int i=0; i<m; i++)
ke[ca[i][1]].add(ca[i][0]);
int res = 0;
Arrays.fill(tr,0);
for(int i=1; i<=n; i++)
if (tr[i] == 0)
res += loang(i);
out.print(res);
}
int n,m, dem, demTp;
int[] low, num, scc, tr, tp, slDinh;
Stack<Integer> st;
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int inf = 1 << 30;
const long double eps = 1e-9;
vector<pair<int, int> > v[300000], ts;
int was[300000];
int colour;
int c[300000];
bool wc[300000];
bool topsort(int u) {
if (was[u] == 2) return true;
if (was[u] == 1) return false;
was[u] = 1;
bool res = true;
for (int i = 0; i < (int)v[u].size(); i++)
if (v[u][i].second == 1) res &= topsort(v[u][i].first);
was[u] = 2;
return res;
}
void dfs(int u) {
if (c[u]) return;
c[u] = colour;
for (int i = 0; i < (int)v[u].size(); i++) dfs(v[u][i].first);
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
int u1, u2;
for (int i = 0; i < (int)m; i++) {
scanf("%d%d", &u1, &u2);
v[u1].push_back(make_pair(u2, 1));
v[u2].push_back(make_pair(u1, 0));
}
for (int i = 1; i <= (int)n; i++)
if (!c[i]) {
colour++;
dfs(i);
}
for (int i = 1; i <= (int)n; i++)
if (!topsort(i) && !wc[c[i]]) wc[c[i]] = true;
int ans = n;
for (int i = 1; i <= (int)colour; i++)
if (!wc[i]) ans--;
cout << ans;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
vector<long long> g[N];
vector<long long> rg[N];
vector<long long> vs;
bool used[N];
int cmp[N], cmpsize[N];
void add_edge(int from, int to) {
g[from].push_back(to);
rg[to].push_back(from);
}
void dfs(int v) {
used[v] = 1;
for (int i = 0; i < (((int)(g[v]).size())); i++) {
if (!used[g[v][i]]) dfs(g[v][i]);
}
vs.push_back(v);
}
void rdfs(int v, int k) {
used[v] = 1;
cmp[v] = k;
for (int i = 0; i < (((int)(rg[v]).size())); i++) {
if (!used[rg[v][i]]) rdfs(rg[v][i], k);
}
}
int scc() {
memset(used, 0, sizeof(used));
vs.clear();
for (int v = 0; v < (n); v++) {
if (!used[v]) dfs(v);
}
memset(used, 0, sizeof(used));
int k = 0;
for (int i = ((int)(vs).size()) - 1; i >= 0; i--) {
if (!used[vs[i]]) rdfs(vs[i], k++);
}
return k;
}
int dfs2(int v) {
used[v] = 1;
int res = cmpsize[cmp[v]] == 1;
for (int i = 0; i < (((int)(g[v]).size())); i++)
if (!used[g[v][i]]) {
res &= dfs2(g[v][i]);
}
for (int i = 0; i < (((int)(rg[v]).size())); i++)
if (!used[rg[v][i]]) {
res &= dfs2(rg[v][i]);
}
return res;
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n >> m;
for (int i = 0; i < (m); i++) {
int a, b;
cin >> a >> b;
add_edge(a - 1, b - 1);
}
scc();
memset(cmpsize, 0, sizeof(cmpsize));
for (int i = 0; i < (n); i++) {
cmpsize[cmp[i]]++;
}
memset(used, 0, sizeof(used));
int ans = n;
for (int i = 0; i < (n); i++)
if (!used[i]) {
ans -= dfs2(i);
}
cout << ans << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m, cual;
vector<vector<int> > G, GT;
vector<int> scc;
vector<int> cuantosporssc;
vector<bool> ok;
stack<int> orden;
void dfs1(int curr) {
if (not ok[curr]) {
ok[curr] = true;
for (int adj : G[curr]) dfs1(adj);
orden.push(curr);
}
}
void dfs2(int curr) {
if (not ok[curr]) {
ok[curr] = true;
scc[curr] = cual;
++cuantosporssc[cual];
for (int adj : GT[curr]) dfs2(adj);
}
}
pair<int, bool> dfs3(int v) {
if (not ok[v]) {
pair<int, bool> ret = {1, cuantosporssc[scc[v]] > 1};
ok[v] = true;
for (int adj : G[v]) {
auto rec = dfs3(adj);
ret.first += rec.first;
ret.second |= rec.second;
}
for (int adj : GT[v]) {
auto rec = dfs3(adj);
ret.first += rec.first;
ret.second |= rec.second;
}
return ret;
}
return {0, false};
}
int main() {
cin >> n >> m;
G = vector<vector<int> >(n, vector<int>());
GT = vector<vector<int> >(n, vector<int>());
scc = vector<int>(n);
cuantosporssc = vector<int>(n, 0);
ok = vector<bool>(n, false);
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
--u, --v;
G[u].push_back(v);
GT[v].push_back(u);
}
for (int i = 0; i < n; ++i)
if (not ok[i]) dfs1(i);
cual = 0;
ok = vector<bool>(n, false);
while (not orden.empty()) {
int v = orden.top();
orden.pop();
if (not ok[v]) {
dfs2(v);
++cual;
}
}
ok = vector<bool>(n, false);
int ans = 0;
for (int i = 0; i < n; ++i) {
if (not ok[i]) {
pair<int, bool> cuantosyciclos = dfs3(i);
if (cuantosyciclos.second)
ans += cuantosyciclos.first;
else
ans += cuantosyciclos.first - 1;
}
}
cout << ans << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
inline int in() {
int x;
scanf("%d", &x);
return x;
}
const int INF = 1e9 + 10;
const long long LINF = 1000ll * 1000 * 1000 * 1000 * 1000 * 1000 + 100;
const int MN = 1e5 + 10;
int mk[MN];
vector<int> adj[MN];
int n, m;
int col[MN];
vector<int> imp[MN], comp[MN];
void input() {
n = in();
m = in();
for (int i = 0; i < m; ++i) {
int a, b;
a = in(), b = in();
--a, --b;
adj[a].push_back(b);
imp[a].push_back(b), imp[b].push_back(a);
}
}
bool flag;
void dfs1(int s, int c) {
col[s] = c;
mk[s] = 1;
for (int i = 0; i < imp[s].size(); ++i)
if (!mk[imp[s][i]]) dfs1(imp[s][i], c);
}
void dfs(int s) {
mk[s] = 2;
for (int i = 0; i < adj[s].size(); ++i) {
if (!mk[adj[s][i]])
dfs(adj[s][i]);
else if (mk[adj[s][i]] == 2)
flag = false;
}
mk[s] = 1;
}
int main() {
input();
int C = 0, ans = n;
for (int i = 0; i < n; ++i)
if (!mk[i]) dfs1(i, C++);
for (int i = 0; i < n; ++i) comp[col[i]].push_back(i);
memset(mk, 0, sizeof mk);
for (int i = 0; i < n; ++i) {
if (comp[i].empty()) continue;
flag = true;
for (int j = 0; j < comp[i].size(); ++j)
if (!mk[comp[i][j]]) dfs(comp[i][j]);
ans -= flag;
}
cout << ans << '\n';
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> Tp[100001], adj[100001], temp;
int n, m, C, Cyc, backT[100001];
bool vis[100001];
void TopS(int x) {
vis[x] = 1;
temp.push_back(x);
for (int i = 0; i < Tp[x].size(); i++) {
if (!vis[Tp[x][i]]) TopS(Tp[x][i]);
}
}
void CheckC(int x) {
backT[x] = 1;
for (int i = 0; i < adj[x].size(); i++) {
if (backT[adj[x][i]] == 1) Cyc = 1;
if (!backT[adj[x][i]]) CheckC(adj[x][i]);
}
backT[x] = 2;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
Tp[a].push_back(b);
Tp[b].push_back(a);
adj[a].push_back(b);
}
for (int i = 1; i <= n; i++) {
temp.clear();
Cyc = 0;
if (!vis[i]) {
TopS(i);
for (int j = 0; j < temp.size(); j++) {
if (!backT[temp[j]]) CheckC(temp[j]);
}
C += temp.size() - 1 + Cyc;
}
}
printf("%d", C);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int64_t DESPACITO = 2e18;
const int INF = 2e9, MOD = 1e9 + 7;
const int N = 2e5 + 5;
int indeg[N];
struct DSU {
int n, components;
vector<int> data, rootID, roots;
DSU(int n)
: n(n),
components(n),
data(vector<int>(n + 1, -1)),
rootID(vector<int>(n + 1, -1)) {}
int par(int x) { return data[x] < 0 ? x : data[x] = par(data[x]); }
int SZ(int x) { return -data[par(x)]; }
bool merge(int x, int y) {
x = par(x);
y = par(y);
if (x == y) return false;
if (-data[x] < -data[y]) swap(x, y);
data[x] += data[y];
data[y] = x;
components--;
return true;
}
void getRoots() {
int cnt = 0;
for (int i = 0; i < n; i++) {
if (data[i] >= 0) continue;
rootID[i] = cnt++;
roots.emplace_back(i);
}
assert(cnt == components);
}
};
int32_t main() {
cin.tie(nullptr)->sync_with_stdio(false);
int i, n, m, ans = 0;
cin >> n >> m;
vector<vector<int>> g(n);
DSU d(n);
for (i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
d.merge(--u, --v);
g[u].emplace_back(v);
indeg[v]++;
}
d.getRoots();
vector<vector<int>> components(d.components);
for (i = 0; i < n; i++) components[d.rootID[d.par(i)]].emplace_back(i);
auto topsort = [&](vector<int>& nodes) {
queue<int> q;
int size = 0;
for (auto& u : nodes)
if (!indeg[u]) q.push(u);
while (!q.empty()) {
auto v = q.front();
q.pop();
size++;
for (auto& x : g[v])
if (!--indeg[x]) q.push(x);
}
return int(nodes.size()) - (size == int(nodes.size()));
};
for (auto& v : components) ans += topsort(v);
cout << ans << '\n';
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int tot = 0, fa[400100], link[400100], size[400100], vis[400100], ans[400100],
final_ans = 0, n, m;
struct rec {
int num, next;
} e[1000010];
void add_edge(int x, int y) {
tot++;
e[tot].num = y;
e[tot].next = link[x];
link[x] = tot;
}
int get_fa(int x) {
if (fa[x] == x) return x;
return fa[x] = get_fa(fa[x]);
}
void combine(int x, int y) {
size[get_fa(x)] += size[get_fa(y)];
fa[get_fa(y)] = get_fa(x);
}
void dfs(int x) {
vis[x] = 1;
for (int p = link[x]; p; p = e[p].next) {
if (vis[e[p].num] == 1) ans[get_fa(x)] = 1;
if (vis[e[p].num] == 0) dfs(e[p].num);
}
vis[x] = 2;
}
int main() {
int i, a, b;
scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++) {
fa[i] = i;
size[i] = 1;
vis[i] = 0;
}
for (i = 1; i <= m; i++) {
scanf("%d %d", &a, &b);
add_edge(a, b);
if (get_fa(a) != get_fa(b)) combine(a, b);
}
for (i = 1; i <= n; i++)
if (vis[i] == 0) dfs(i);
for (i = 1; i <= n; i++)
if (fa[i] == i) {
final_ans += ans[i];
final_ans += size[i] - 1;
}
printf("%d", final_ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const long double eps = 1e-9;
const int inf = (1 << 30) - 1;
const long long inf64 = ((long long)1 << 62) - 1;
const long double pi = acos(-1);
template <class T>
T sqr(T x) {
return x * x;
}
template <class T>
T abs(T x) {
return x < 0 ? -x : x;
}
const int MAXN = 120 * 1000;
vector<int> adj0[MAXN], adj1[MAXN];
int color[MAXN], used[MAXN];
bool good_color[MAXN];
void dfs1(int v, int c) {
color[v] = c;
for (int i = 0; i < ((int)(adj1[v]).size()); ++i) {
if (color[adj1[v][i]] == -1) {
dfs1(adj1[v][i], c);
}
}
}
void dfs0(int v) {
used[v] = 1;
for (int i = 0; i < ((int)(adj0[v]).size()); ++i) {
int u = adj0[v][i];
if (used[u] == 1) {
good_color[color[v]] = false;
}
if (used[u] == 0) {
dfs0(u);
}
}
used[v] = 2;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
int v1, v2;
for (int i = 0; i < m; ++i) {
scanf("%d%d", &v1, &v2);
v1--, v2--;
adj0[v1].push_back(v2);
adj1[v1].push_back(v2);
adj1[v2].push_back(v1);
}
for (int i = 0; i < n; ++i) {
color[i] = -1;
}
int num_color = 0;
for (int i = 0; i < n; ++i) {
if (color[i] == -1) {
dfs1(i, num_color);
num_color++;
}
}
for (int i = 0; i < num_color; ++i) {
good_color[i] = true;
}
for (int i = 0; i < n; ++i) {
if (used[i] == 0) {
dfs0(i);
}
}
int ans = n;
for (int i = 0; i < num_color; ++i) {
if (good_color[i]) {
ans--;
}
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public final class CF_KitayutaTechnology {
void log(int[] X){
int L=X.length;
for (int i=0;i<L;i++){
logWln(X[i]+" ");
}
log("");
}
void log(long[] X){
int L=X.length;
for (int i=0;i<L;i++){
logWln(X[i]+" ");
}
log("");
}
void log(Object[] X){
int L=X.length;
for (int i=0;i<L;i++){
logWln(X[i]+" ");
}
log("");
}
void log(Object o){
logWln(o+"\n");
}
void logWln(Object o){
//System.out.print(o);
outputWln(o);
}
void info(Object o){
System.out.println(o);
//output(o);
}
void output(Object o){
outputWln(""+o+"\n");
}
void outputWln(Object o){
// System.out.print(o);
try {
out.write(""+ o);
} catch (Exception e) {
}
}
String next(){
while (st== null|| !st.hasMoreTokens()) {
try {
st=new StringTokenizer(in.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
String nextLine(){
try {
return in.readLine();
} catch (Exception e) {
}
return null;
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
// Global vars
StringTokenizer st;
BufferedReader in;
BufferedWriter out;
int N,M;
ArrayList<Integer>[] children,parents;
boolean[] visited,test;
int[] tin,tout;
int[] x,y;
int time;
boolean[] looped;
int[] anc;
int cnt;
boolean connected;
/*
ArrayList<Integer>[] fusion;
void link(int x,int y){
fusion[x].add(y);
fusion[y].add(x);
}
boolean linked(int x,int y){
return fusion[x].contains(y);
}
*/
void connect(int x,int y){
children[x].add(y);
parents[y].add(x);
}
void downFill(int node,int oldAnc,int newAnc){
anc[node]=newAnc;
for (int i=0;i<children[node].size();i++){
int y=children[node].get(i);
if (anc[y]==oldAnc){
downFill(y,oldAnc,newAnc);
}
}
}
void fullScan(int node,int ancestor){
//log("Fullscan node:"+node+" root:"+ancestor);
anc[node]=ancestor;
visited[node]=true;
cnt++;
for (int y:children[node])
if (!visited[y])
fullScan(y,ancestor);
for (int y:parents[node])
if (!visited[y])
fullScan(y,ancestor);
}
void directedScan(int node){
//log("update node:"+node+" parent:"+parent);
tin[node]=time++;
visited[node]=true;
for (int y:children[node])
if (!visited[y])
directedScan(y);
tout[node]=time++;
}
void solve(){
visited=new boolean[N];
looped=new boolean[N];
tin=new int[N];
tout=new int[N];
time=0;
int sum=0;
looped=new boolean[N];
anc=new int[N];
// composantes connexes
for (int i=0;i<N;i++){
cnt=0;
if (test[i] && !visited[i]){
fullScan(i,i);
sum+=cnt-1;
}
}
Arrays.fill(visited,false);
// maintenant on cherche les boucles
// d'abord on définit les ancêtres
for (int i=0;i<N;i++){
if (test[i] && !visited[i]){
directedScan(i);
}
}
// ensuite on regarde si contradiction
// une contradiction max par composante connexe
for (int i=0;i<M;i++){
// x-->y, donc y doit être child de x
// si x est child de y alors bug
if (tin[x[i]]>tin[y[i]] && tout[x[i]]<tout[y[i]]){
// log("Loop for "+(x[i]+1)+" and "+(y[i]+1)+" anc:"+anc[x[i]]+"/"+anc[y[i]]);
if (!looped[anc[x[i]]]){
looped[anc[x[i]]]=true;
sum++;
}
}
}
output(sum);
}
void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
in=new BufferedReader(new InputStreamReader(System.in));
N=nextInt();
children=new ArrayList[N];
parents=new ArrayList[N];
for (int i=0;i<N;i++) {
children[i]=new ArrayList<Integer>();
parents[i]=new ArrayList<Integer>();
}
test=new boolean[N];
M=nextInt();
x=new int[M];
y=new int[M];
for (int i=0;i<M;i++){
x[i]=nextInt()-1;
y[i]=nextInt()-1;
test[x[i]]=true;
test[y[i]]=true;
connect(x[i],y[i]);
}
solve();
try {
out.close();
}
catch (Exception e){}
}
public static void main(String[] args) throws Exception {
CF_KitayutaTechnology J=new CF_KitayutaTechnology();
J.process();
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int C;
vector<int> comp[100007];
int vi[100007];
int de[100007];
vector<int> g[100007];
vector<int> go[100007];
vector<int> gi[100007];
int I[100007];
int O[100007];
void DFS(int v, int p) {
if (vi[v]) return;
vi[v] = 1;
comp[C].push_back(v);
for (int i = (0); i < (g[v].size()); i++) {
int u = g[v][i];
if (u == p) continue;
DFS(u, v);
}
}
int main() {
int N, M;
scanf("%d %d ", &N, &M);
;
for (int i = (0); i < (M); i++) {
int a, b;
scanf("%d %d ", &a, &b);
;
g[a].push_back(b);
g[b].push_back(a);
go[a].push_back(b);
gi[b].push_back(a);
}
for (int i = (1); i < (N + 1); i++) {
if (!vi[i]) {
DFS(i, 0);
C++;
}
}
int sum = 0;
for (int c = (0); c < (C); c++) {
queue<int> q;
for (int i = (0); i < (comp[c].size()); i++) {
int v = comp[c][i];
I[v] = gi[v].size();
if (I[v] == 0) q.push(v);
}
int cnt = 0;
while (!q.empty()) {
cnt++;
int v = q.front();
q.pop();
for (int i = (0); i < (go[v].size()); i++) {
int u = go[v][i];
if (--I[u] == 0) q.push(u);
}
}
if (cnt == comp[c].size())
sum += comp[c].size() - 1;
else
sum += comp[c].size();
}
cout << sum << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > g, dg, cs;
vector<int> gehort;
vector<bool> vis, loop;
void dfs1(int n) {
cs.back().push_back(n);
gehort[n] = cs.size() - 1;
vis[n] = 1;
for (int i = 0; i < g[n].size(); i++) {
if (!vis[g[n][i]]) dfs1(g[n][i]);
}
}
vector<bool> inStk;
stack<int> stk;
vector<int> ord, low;
vector<vector<int> > comps;
int o;
void tarjan(int node) {
ord[node] = low[node] = o++;
stk.push(node);
inStk[node] = 1;
for (int i = 0; i < dg[node].size(); i++) {
if (ord[dg[node][i]] == -1) {
tarjan(dg[node][i]);
low[node] = min(low[node], low[dg[node][i]]);
} else if (inStk[dg[node][i]])
low[node] = min(low[node], low[dg[node][i]]);
}
if (low[node] == ord[node]) {
comps.push_back(vector<int>());
while (1) {
comps.back().push_back(stk.top());
inStk[stk.top()] = 0;
if (stk.top() == node) {
stk.pop();
break;
}
stk.pop();
}
}
}
void build() {
low.assign(dg.size(), 0);
ord.assign(dg.size(), -1);
inStk.assign(dg.size(), 0);
comps.clear();
o = 0;
for (int i = 0; i < dg.size(); i++) {
if (ord[i] == -1) tarjan(i);
}
}
int main() {
int n, m;
cin >> n >> m;
g.resize(n);
dg.resize(n);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--, b--;
g[a].push_back(b);
g[b].push_back(a);
dg[a].push_back(b);
}
vis.resize(n);
gehort.resize(n);
for (int i = 0; i < n; i++) {
if (!vis[i]) {
cs.push_back(vector<int>());
dfs1(i);
}
}
build();
loop.resize(cs.size());
for (int i = 0; i < comps.size(); i++) {
if (comps[i].size() - 1) loop[gehort[comps[i][0]]] = 1;
}
int out = n - cs.size();
for (int i = 0; i < loop.size(); i++) {
out += loop[i];
}
cout << out;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
template <class T>
bool uax(T& a, const T& b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
bool uin(T& a, const T& b) {
if (a > b) {
a = b;
return true;
}
return false;
}
const int N = 100500;
int c[N];
vector<int> g[N];
vector<int> gt[N];
vector<int> gg[N];
int dsu[N];
int get(int v) { return dsu[v] == v ? v : dsu[v] = get(dsu[v]); }
bool unite(int v, int u) {
if ((v = get(v)) != (u = get(u))) {
if (rand() & 1) swap(u, v);
dsu[v] = u;
return true;
} else
return false;
}
vector<int> ord;
int cmp[N];
int szcmp[N];
bool there_cycle[N];
int kcmp;
void dfs_cmp(int v) {
if (cmp[v]) return;
cmp[v] = kcmp;
szcmp[kcmp] += 1;
for (int u : gt[v]) dfs_cmp(u);
}
void dfs_ord(int v) {
if (c[v]) return;
c[v] = 1;
for (int u : g[v]) dfs_ord(u);
c[v] = 2;
ord.push_back(v);
}
void solve() {
int n, m;
cin >> n >> m;
for (int i = 0; i < (int)(m); ++i) {
int a, b;
cin >> a >> b;
--a;
--b;
g[a].push_back(b);
gt[b].push_back(a);
}
for (int i = 0; i < (int)(n); ++i) c[i] = 0;
for (int i = 0; i < (int)(n); ++i)
if (!c[i]) dfs_ord(i);
reverse((ord).begin(), (ord).end());
for (int v : ord)
if (!cmp[v]) {
++kcmp;
dfs_cmp(v);
}
int ans = n;
for (int i = (int)(1); i <= (int)(kcmp); ++i) dsu[i] = i;
for (int v = 0; v < (int)(n); ++v)
for (int u : g[v])
if (cmp[v] != cmp[u]) {
if (unite(cmp[v], cmp[u]))
;
}
for (int i = (int)(1); i <= (int)(kcmp); ++i) {
there_cycle[get(i)] |= (szcmp[i] > 1);
}
for (int i = (int)(1); i <= (int)(kcmp); ++i)
if (get(i) == i) {
ans -= !there_cycle[i];
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout << fixed;
cout.precision(15);
cerr << fixed;
cerr.precision(15);
solve();
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int n, m;
int mark[maxn];
vector<int> G[maxn], adj[maxn];
bool res = 0;
int sz = 0;
vector<int> vec;
void dfs(int v) {
mark[v] = 1;
sz++;
vec.push_back(v);
for (int u : G[v])
if (!mark[u]) dfs(u);
}
void DFS(int v) {
mark[v] = 1;
for (int u : adj[v]) {
if (mark[u] == 2) continue;
if (mark[u] == 1) {
res = 1;
continue;
}
DFS(u);
}
mark[v] = 2;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
int u, v;
for (int i = 0; i < m; i++) {
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
adj[u].push_back(v);
}
int ans = 0;
for (int v = 1; v <= n; v++) {
if (mark[v] > 0) continue;
vec.clear();
res = 0, sz = 0;
dfs(v);
for (int vi : vec) mark[vi] = 0;
for (int vi : vec) {
if (mark[vi] > 0) continue;
DFS(vi);
}
ans += (res ? sz : sz - 1);
}
cout << ans << '\n';
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class CF506B {
static ArrayList<Integer>[] edges, redges;
static boolean[] topcol, compcol, cycle;
static int[] topsort;
static int topsortEnd;
static void topdfs(int i) {
if (topcol[i]) {
return;
}
topcol[i] = true;
for (int e : edges[i]) {
topdfs(e);
}
topsort[topsortEnd++] = i;
}
static int compdfs(int i) {
if (compcol[i]) {
return 0;
}
int r = 1;
compcol[i] = true;
for (int e : redges[i]) {
r += compdfs(e);
}
return r;
}
static boolean compdfs2(int i) {
if (topcol[i]) {
return false;
}
boolean ret = cycle[i];
topcol[i] = true;
for (int e : edges[i]) {
ret |= compdfs2(e);
}
for (int e : redges[i]) {
ret |= compdfs2(e);
}
return ret;
}
public static void solve(Input in, PrintWriter out) throws IOException {
int n = in.nextInt();
int m = in.nextInt();
edges = new ArrayList[n];
redges = new ArrayList[n];
topcol = new boolean[n];
compcol = new boolean[n];
topsort = new int[n];
cycle = new boolean[n];
for (int i = 0; i < n; ++i) {
edges[i] = new ArrayList<Integer>();
redges[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; ++i) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
edges[a].add(b);
redges[b].add(a);
}
for (int i = 0; i < n; ++i) {
topdfs(i);
}
if (topsortEnd != n) {
throw new AssertionError();
}
for (int it = 0; it < n; ++it) {
int i = topsort[n - it - 1];
if (!compcol[i]) {
int size = compdfs(i);
if (size > 1) {
cycle[i] = true;
}
}
}
Arrays.fill(topcol, false);
int ans = n;
for (int i = 0; i < n; ++i) {
if (!topcol[i]) {
if (!compdfs2(i)) {
ans--;
}
}
}
out.println(ans);
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
out.close();
}
static class Input {
BufferedReader in;
StringBuilder sb = new StringBuilder();
public Input(BufferedReader in) {
this.in = in;
}
public Input(String s) {
this.in = new BufferedReader(new StringReader(s));
}
public String next() throws IOException {
sb.setLength(0);
while (true) {
int c = in.read();
if (c == -1) {
return null;
}
if (" \n\r\t".indexOf(c) == -1) {
sb.append((char)c);
break;
}
}
while (true) {
int c = in.read();
if (c == -1 || " \n\r\t".indexOf(c) != -1) {
break;
}
sb.append((char)c);
}
return sb.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | def main():
n, m = map(int, input().split())
n += 1
cluster, dest, avail, ab = list(range(n)), [0] * n, [True] * n, [[] for _ in range(n)]
def getroot(x):
while x != cluster[x]:
x = cluster[x]
return x
def setroot(x, r):
if r < x != cluster[x]:
setroot(cluster[x], r)
cluster[x] = r
for _ in range(m):
a, b = map(int, input().split())
ab[a].append(b)
dest[b] += 1
u, v = getroot(a), getroot(b)
if u > v:
u = v
setroot(a, u)
setroot(b, u)
pool = [a for a in range(1, n) if not dest[a]]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b]:
pool.append(b)
for a in range(1, n):
avail[getroot(a)] &= not dest[a]
print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, avail)))
if __name__ == '__main__':
from sys import setrecursionlimit
setrecursionlimit(100500)
main() | PYTHON3 |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class B {
static class SCC {
public static final int NULL = -1;
List<Integer>[] adj;
int dfsIndex;
int[] dfsNum;
int[] dfsLow;
Stack<Integer> stack;
boolean[] stackSet;
int[] comp;
public SCC(List<Integer>[] adj) {
this.adj = adj;
int n = adj.length;
dfsIndex = 0;
dfsNum = new int[n];
Arrays.fill(dfsNum, NULL);
dfsLow = new int[n];
stack = new Stack<Integer>();
stackSet = new boolean[n];
comp = new int[n];
for (int u=0; u<n; u++) {
if (dfsNum[u]!=NULL) continue;
tarjan(u);
}
}
public void tarjan(int u) {
dfsNum[u] = dfsLow[u] = dfsIndex++;
stack.push(u);
stackSet[u] = true;
for (int v:adj[u]) {
if (dfsNum[v]==NULL) tarjan(v);
if (stackSet[v]) dfsLow[u] = min(dfsLow[u], dfsLow[v]);
}
if (dfsLow[u]!=dfsNum[u]) return ;
while (true) {
int v = stack.pop();;
stackSet[v] = false;
// v and u is in the same strongly connected component
comp[v] = u;
if (v==u) break;
}
}
}
int dfs(int cur) {
int r = size[comp[cur]]==1?1:0;
visited[cur] = true;
for (int nbr:g[cur]) {
if (visited[nbr]) continue;
r &= dfs(nbr);
}
for (int nbr:rg[cur]) {
if (visited[nbr]) continue;
r &= dfs(nbr);
}
return r;
}
List<Integer>[] g;
List<Integer>[] rg;
int[] comp;
int[] size;
boolean[] visited;
public B() throws Exception {
int n = in.nextInt();
int m = in.nextInt();
g = new List[n];
rg = new List[n];
for (int i=0; i<n; i++) g[i] = new ArrayList<>();
for (int i=0; i<n; i++) rg[i] = new ArrayList<>();
for (int i=0; i<m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
g[a].add(b);
rg[b].add(a);
}
SCC scc = new SCC(g);
comp = scc.comp;
size = new int[n];
for (int i=0; i<n; i++) size[comp[i]]++;
int ans = n;
visited = new boolean[n];
for (int i=0; i<n; i++) {
if (visited[i]) continue;
ans -= dfs(i);
}
buf.append(ans).append('\n');
}
public static Scanner in = new Scanner(System.in);
public static StringBuilder buf = new StringBuilder();
public static void debug(Object... arr) { // {{{
System.err.println(Arrays.deepToString(arr));
} // }}}
public static void main(String[] args) throws Exception { // {{{
new B();
System.out.print(buf);
} // }}}
public static class Scanner { // {{{
BufferedReader br;
String line;
StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public boolean hasNext() throws IOException {
while ((st==null||!st.hasMoreTokens())&&(line=br.readLine())!=null)
st = new StringTokenizer(line);
return st.hasMoreTokens();
}
public String next() throws IOException {
if (hasNext()) return st.nextToken();
throw new NoSuchElementException();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} // }}}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m;
int cost[200005];
struct edge {
int from;
int to;
int next;
} E[100005];
int head[200005];
int sz = 0;
void add_edge(int u, int v) {
sz++;
E[sz].from = u;
E[sz].to = v;
E[sz].next = head[u];
head[u] = sz;
}
stack<int> s;
int ins[200005];
int dfn[200005];
int low[200005];
int id[200005];
int cntv[200005];
int num = 0;
int scc_cnt = 0;
void tarjan(int x) {
ins[x] = 1;
s.push(x);
low[x] = dfn[x] = ++num;
for (int i = head[x]; i; i = E[i].next) {
int y = E[i].to;
if (!dfn[y]) {
tarjan(y);
low[x] = min(low[x], low[y]);
} else if (ins[y]) {
low[x] = min(low[x], dfn[y]);
}
}
if (low[x] == dfn[x]) {
scc_cnt++;
int y;
do {
y = s.top();
ins[y] = 0;
s.pop();
id[y] = scc_cnt;
cntv[scc_cnt]++;
} while (y != x);
}
}
int mark[200005];
int fa[200005];
int find(int x) {
if (fa[x] == x)
return x;
else
return fa[x] = find(fa[x]);
}
int main() {
int u, v;
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d %d", &u, &v);
add_edge(u, v);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) tarjan(i);
}
for (int i = 1; i <= scc_cnt; i++) {
if (cntv[i] != 1) mark[i] = 1;
}
for (int i = 1; i <= scc_cnt; i++) fa[i] = i;
for (int i = 1; i <= m; i++) {
u = E[i].from;
v = E[i].to;
int p = find(id[u]);
int q = find(id[v]);
if (p != q) {
fa[q] = p;
cntv[p] += cntv[q];
mark[p] |= mark[q];
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (fa[i] == i) {
if (mark[i])
ans += cntv[i];
else
ans += cntv[i] - 1;
}
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class KitayutaTechnology {
int[] in;
int[] low;
int[] group;
boolean[] groupHasCycle;
int[] dfsNum;
ArrayList<Integer>[] adj;
ArrayList<Integer>[] comingIn;
int time;
public static void main(String[] args) throws IOException {
new KitayutaTechnology().solve();
}
private void solve() throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer tokenizer = new StringTokenizer(f.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int m = Integer.parseInt(tokenizer.nextToken());
adj = new ArrayList[n];
comingIn = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
comingIn[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
tokenizer = new StringTokenizer(f.readLine());
int a = Integer.parseInt(tokenizer.nextToken()) - 1;
int b = Integer.parseInt(tokenizer.nextToken()) - 1;
adj[a].add(b);
comingIn[b].add(a);
}
time = 0;
in = new int[n];
low = new int[n];
group = new int[n];
groupHasCycle = new boolean[n];
Arrays.fill(group, -1);
int groupNum = 0;
for (int i = 0; i < n; i++) {
if (group[i] == -1) {
makeGroups(i, groupNum);
groupNum++;
}
}
Arrays.fill(in, 0);
for (int i = 0; i < n; i++) {
if (in[i] == 0) {
dfs(i);
}
}
int res = 0;
int[] nodesInGroup = new int[n];
for (int i = 0; i < n; i++) {
nodesInGroup[group[i]]++;
}
for (int i = 0; i < n; i++) {
if (nodesInGroup[i] > 1) res += nodesInGroup[i] - 1;
}
for (boolean cycle : groupHasCycle) if (cycle) res++;
out.println(res);
out.close();
}
private void makeGroups(int node, int groupNum) {
group[node] = groupNum;
for (int adjacent : adj[node]) {
if (group[adjacent] == -1) makeGroups(adjacent, groupNum);
}
for (int adjacent : comingIn[node]) {
if (group[adjacent] == -1) makeGroups(adjacent, groupNum);
}
}
private void dfs(int node) {
in[node] = time;
low[node] = time;
time++;
for (int adjacent : adj[node]) {
if (in[adjacent] == 0) dfs(adjacent);
if (in[adjacent] != -1) low[node] = Math.min(low[node], low[adjacent]);
}
if (low[node] < in[node]) {
groupHasCycle[group[node]] = true;
}
in[node] = -1;
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
}
class SCCKosaraju {
public static List<List<Integer>> scc(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> order = new ArrayList<>();
for (int i = 0; i < n; i++)
if (!used[i])
dfs(graph, used, order, i);
List<Integer>[] reverseGraph = new List[n];
for (int i = 0; i < n; i++)
reverseGraph[i] = new ArrayList<>();
for (int i = 0; i < n; i++)
for (int j : graph[i])
reverseGraph[j].add(i);
List<List<Integer>> components = new ArrayList<>();
Arrays.fill(used, false);
Collections.reverse(order);
for (int u : order)
if (!used[u]) {
List<Integer> component = new ArrayList<>();
dfs(reverseGraph, used, component, u);
components.add(component);
}
return components;
}
static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res,
int u) {
used[u] = true;
for (int v : graph[u])
if (!used[v])
dfs(graph, used, res, v);
res.add(u);
}
// Usage example
public static void main(String[] args) {
List<Integer>[] g = new List[3];
for (int i = 0; i < g.length; i++)
g[i] = new ArrayList<>();
g[2].add(0);
g[2].add(1);
g[0].add(1);
g[1].add(0);
List<List<Integer>> components = scc(g);
System.out.println(components);
}
}
class Task {
int[] arr, rev;
boolean[] vis;
List<Integer>[] adjl;
Graph graph;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt(), m = in.readInt(), ret = n, M = m;
adjl = new List[n];
arr = new int[n];
rev = new int[n];
vis = new boolean[n];
for (int i=0; i<n; i++) adjl[i]=new ArrayList<Integer>();
while (m-->0) {
int a=in.readInt()-1, b=in.readInt()-1;
adjl[a].add(b);
}
List<List<Integer>> list=SCCKosaraju.scc(adjl);
// if (M != 6970)
{
for (int i=0; i<list.size(); i++) {
// out.printLine(list.get(i));
for (int j: list.get(i)) arr[j]=i;
}
graph = new Graph(list.size());
for (int i=0; i<n; i++) if (!vis[i]) makeGraph(i);
n = graph.vertexCount();
rev = new int[n];
// out.printLine(arr);
for (int i: arr) rev[i]++;
// out.printLine(arr);
Arrays.fill(vis, false);
for (int i = 0; i < n; i++)
if (!vis[i]) {
ret -= dfs(i);
// out.printLine(i, ret);
}
out.printLine(ret);
}
}
void makeGraph(int u) {
vis[u]=true;
for (int v: adjl[u]) {
graph.addSimpleEdge(arr[u], arr[v]);
if (!vis[v]) makeGraph(v);
}
}
int dfs(int u) {
// if (x++>100000) return 0;
int ret = rev[u] == 1 ? 1 : 0;
vis[u] = true;
for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) {
int v = graph.destination(i);
if (!vis[v])
ret &= dfs(v);
}
for (int i = graph.firstInbound(u); i != -1; i = graph.nextInbound(i)) {
int v = graph.source(i);
if (!vis[v])
ret &= dfs(v);
}
return ret;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void printLine() {
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void printLine(char i) {
writer.println(i);
}
public void printLine(char[] array) {
writer.println(array);
}
public void printFormat(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void printLine(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void printLine(int i) {
writer.println(i);
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static long[] readLongArray(InputReader in, int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = in.readLong();
return array;
}
public static double[] readDoubleArray(InputReader in, int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++)
array[i] = in.readDouble();
return array;
}
public static String[] readStringArray(InputReader in, int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++)
array[i] = in.readString();
return array;
}
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++)
array[i] = in.readCharacter();
return array;
}
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
public static void readLongArrays(InputReader in, long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readLong();
}
}
public static void readDoubleArrays(InputReader in, double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readDouble();
}
}
public static char[][] readTable(InputReader in, int rowCount,
int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readCharArray(in, columnCount);
return table;
}
public static int[][] readIntTable(InputReader in, int rowCount,
int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
public static double[][] readDoubleTable(InputReader in, int rowCount,
int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readDoubleArray(in, columnCount);
return table;
}
public static long[][] readLongTable(InputReader in, int rowCount,
int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readLongArray(in, columnCount);
return table;
}
public static String[][] readStringTable(InputReader in, int rowCount,
int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readStringArray(in, columnCount);
return table;
}
public static String readText(InputReader in) {
StringBuilder result = new StringBuilder();
while (true) {
int character = in.read();
if (character == '\r')
continue;
if (character == -1)
break;
result.append((char) character);
}
return result.toString();
}
public static void readStringArrays(InputReader in, String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readString();
}
}
public static void printTable(OutputWriter out, char[][] table) {
for (char[] row : table)
out.printLine(new String(row));
}
}
class SumIntervalTree extends LongIntervalTree {
public SumIntervalTree(int size) {
super(size);
}
@Override
protected long joinValue(long left, long right) {
return left + right;
}
@Override
protected long joinDelta(long was, long delta) {
return was + delta;
}
@Override
protected long accumulate(long value, long delta, int length) {
return value + delta * length;
}
@Override
protected long neutralValue() {
return 0;
}
@Override
protected long neutralDelta() {
return 0;
}
}
abstract class IntervalTree {
protected int size;
protected IntervalTree(int size) {
this(size, true);
}
public IntervalTree(int size, boolean shouldInit) {
this.size = size;
int nodeCount = Math.max(1, Integer.highestOneBit(size) << 2);
initData(size, nodeCount);
if (shouldInit)
init();
}
protected abstract void initData(int size, int nodeCount);
protected abstract void initAfter(int root, int left, int right, int middle);
protected abstract void initBefore(int root, int left, int right, int middle);
protected abstract void initLeaf(int root, int index);
protected abstract void updatePostProcess(int root, int left, int right,
int from, int to, long delta, int middle);
protected abstract void updatePreProcess(int root, int left, int right,
int from, int to, long delta, int middle);
protected abstract void updateFull(int root, int left, int right, int from,
int to, long delta);
protected abstract long queryPostProcess(int root, int left, int right,
int from, int to, int middle, long leftResult, long rightResult);
protected abstract void queryPreProcess(int root, int left, int right,
int from, int to, int middle);
protected abstract long queryFull(int root, int left, int right, int from,
int to);
protected abstract long emptySegmentResult();
public void init() {
if (size == 0)
return;
init(0, 0, size - 1);
}
private void init(int root, int left, int right) {
if (left == right) {
initLeaf(root, left);
} else {
int middle = (left + right) >> 1;
initBefore(root, left, right, middle);
init(2 * root + 1, left, middle);
init(2 * root + 2, middle + 1, right);
initAfter(root, left, right, middle);
}
}
public void update(int from, int to, long delta) {
update(0, 0, size - 1, from, to, delta);
}
protected void update(int root, int left, int right, int from, int to,
long delta) {
if (left > to || right < from)
return;
if (left >= from && right <= to) {
updateFull(root, left, right, from, to, delta);
return;
}
int middle = (left + right) >> 1;
updatePreProcess(root, left, right, from, to, delta, middle);
update(2 * root + 1, left, middle, from, to, delta);
update(2 * root + 2, middle + 1, right, from, to, delta);
updatePostProcess(root, left, right, from, to, delta, middle);
}
public long query(int from, int to) {
return query(0, 0, size - 1, from, to);
}
protected long query(int root, int left, int right, int from, int to) {
if (left > to || right < from)
return emptySegmentResult();
if (left >= from && right <= to)
return queryFull(root, left, right, from, to);
int middle = (left + right) >> 1;
queryPreProcess(root, left, right, from, to, middle);
long leftResult = query(2 * root + 1, left, middle, from, to);
long rightResult = query(2 * root + 2, middle + 1, right, from, to);
return queryPostProcess(root, left, right, from, to, middle,
leftResult, rightResult);
}
}
abstract class LongIntervalTree extends IntervalTree {
protected long[] value;
protected long[] delta;
protected LongIntervalTree(int size) {
this(size, true);
}
public LongIntervalTree(int size, boolean shouldInit) {
super(size, shouldInit);
}
@Override
protected void initData(int size, int nodeCount) {
value = new long[nodeCount];
delta = new long[nodeCount];
}
protected abstract long joinValue(long left, long right);
protected abstract long joinDelta(long was, long delta);
protected abstract long accumulate(long value, long delta, int length);
protected abstract long neutralValue();
protected abstract long neutralDelta();
protected long initValue(int index) {
return neutralValue();
}
@Override
protected void initAfter(int root, int left, int right, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
delta[root] = neutralDelta();
}
@Override
protected void initBefore(int root, int left, int right, int middle) {
}
@Override
protected void initLeaf(int root, int index) {
value[root] = initValue(index);
delta[root] = neutralDelta();
}
@Override
protected void updatePostProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
}
@Override
protected void updatePreProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
pushDown(root, left, middle, right);
}
protected void pushDown(int root, int left, int middle, int right) {
value[2 * root + 1] = accumulate(value[2 * root + 1], delta[root],
middle - left + 1);
value[2 * root + 2] = accumulate(value[2 * root + 2], delta[root],
right - middle);
delta[2 * root + 1] = joinDelta(delta[2 * root + 1], delta[root]);
delta[2 * root + 2] = joinDelta(delta[2 * root + 2], delta[root]);
delta[root] = neutralDelta();
}
@Override
protected void updateFull(int root, int left, int right, int from, int to,
long delta) {
value[root] = accumulate(value[root], delta, right - left + 1);
this.delta[root] = joinDelta(this.delta[root], delta);
}
@Override
protected long queryPostProcess(int root, int left, int right, int from,
int to, int middle, long leftResult, long rightResult) {
return joinValue(leftResult, rightResult);
}
@Override
protected void queryPreProcess(int root, int left, int right, int from,
int to, int middle) {
pushDown(root, left, middle, right);
}
@Override
protected long queryFull(int root, int left, int right, int from, int to) {
return value[root];
}
@Override
protected long emptySegmentResult() {
return neutralValue();
}
}
class IntPair implements Comparable<IntPair> {
public final int first, second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
return "(" + first + "," + second + ")";
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
IntPair intPair = (IntPair) o;
return first == intPair.first && second == intPair.second;
}
@Override
public int hashCode() {
int result = first;
result = 31 * result + second;
return result;
}
public int compareTo(IntPair o) {
if (first < o.first)
return -1;
if (first > o.first)
return 1;
if (second < o.second)
return -1;
if (second > o.second)
return 1;
return 0;
}
}
class Matrix {
public static long mod = Long.MAX_VALUE;
public final long[][] data;
public final int rowCount;
public final int columnCount;
public Matrix(int rowCount, int columnCount) {
this.rowCount = rowCount;
this.columnCount = columnCount;
this.data = new long[rowCount][columnCount];
}
public Matrix(long[][] data) {
this.rowCount = data.length;
this.columnCount = data[0].length;
this.data = data;
}
public static Matrix add(Matrix first, Matrix second) {
Matrix result = new Matrix(first.rowCount, first.columnCount);
for (int i = 0; i < result.rowCount; i++) {
for (int j = 0; j < result.columnCount; j++) {
result.data[i][j] = first.data[i][j] + second.data[i][j];
if (result.data[i][j] >= mod)
result.data[i][j] -= mod;
}
}
return result;
}
public static Matrix multiply(Matrix first, Matrix second) {
Matrix result = new Matrix(first.rowCount, second.columnCount);
for (int i = 0; i < first.rowCount; i++) {
for (int j = 0; j < second.rowCount; j++) {
for (int k = 0; k < second.columnCount; k++)
result.data[i][k] = (result.data[i][k] + first.data[i][j]
* second.data[j][k])
% mod;
}
}
return result;
}
public static Matrix fastMultiply(Matrix first, Matrix second) {
Matrix result = new Matrix(first.rowCount, second.columnCount);
for (int i = 0; i < first.rowCount; i++) {
for (int j = 0; j < second.rowCount; j++) {
for (int k = 0; k < second.columnCount; k++)
result.data[i][k] += first.data[i][j] * second.data[j][k];
}
}
for (int i = 0; i < first.rowCount; i++) {
for (int j = 0; j < second.columnCount; j++)
result.data[i][j] %= mod;
}
return result;
}
public static Matrix identityMatrix(int size) {
Matrix result = new Matrix(size, size);
for (int i = 0; i < size; i++)
result.data[i][i] = 1;
return result;
}
public static long[] convert(long[][] matrix) {
long[] result = new long[matrix.length * matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++)
result[i * matrix.length + j] = matrix[i][j];
}
return result;
}
public static long[] sumPowers(long[] matrix, long exponent, long mod,
int side) {
long[] result = new long[matrix.length];
long[] power = new long[matrix.length];
long[] temp = new long[matrix.length];
long[] temp2 = new long[matrix.length];
sumPowers(matrix, result, power, temp, temp2, exponent + 1, mod, side);
return result;
}
private static void sumPowers(long[] matrix, long[] result, long[] power,
long[] temp, long[] temp2, long exponent, long mod, int side) {
if (exponent == 0) {
for (int i = 0; i < matrix.length; i += side + 1)
power[i] = 1 % mod;
return;
}
if ((exponent & 1) == 0) {
sumPowers(matrix, result, temp, power, temp2, exponent >> 1, mod,
side);
multiply(temp2, result, temp, mod, side);
add(result, temp2, mod, side);
multiply(power, temp, temp, mod, side);
} else {
sumPowers(matrix, result, temp, power, temp2, exponent - 1, mod,
side);
add(result, temp, mod, side);
multiply(power, temp, matrix, mod, side);
}
}
public static long[][] convert(long[] matrix, int side) {
long[][] result = new long[side][side];
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++)
result[i][j] = matrix[i * side + j];
}
return result;
}
public static long[] power(long[] matrix, long exponent, long mod, int side) {
long[] result = new long[matrix.length];
long[] temp = new long[result.length];
power(matrix, result, temp, exponent, mod, side);
return result;
}
private static void power(long[] matrix, long[] result, long[] temp,
long exponent, long mod, int side) {
if (exponent == 0) {
for (int i = 0; i < matrix.length; i += side + 1)
result[i] = 1 % mod;
return;
}
if ((exponent & 1) == 0) {
power(matrix, temp, result, exponent >> 1, mod, side);
multiply(result, temp, temp, mod, side);
} else {
power(matrix, temp, result, exponent - 1, mod, side);
multiply(result, temp, matrix, mod, side);
}
}
public static void multiply(long[] c, long[] a, long[] b, long mod, int side) {
Arrays.fill(c, 0);
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++) {
for (int k = 0; k < side; k++) {
c[i * side + k] += a[i * side + j] * b[j * side + k];
if ((j & 3) == 3) {
c[i * side + k] %= mod;
}
}
}
}
for (int i = 0; i < c.length; i++)
c[i] %= mod;
}
public static void add(long[] c, long[] a, long mod, int side) {
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++) {
c[i * side + j] += a[i * side + j];
if (c[i * side + j] >= mod)
c[i * side + j] -= mod;
}
}
}
public static long[] fastPower(long[] matrix, long exponent, long mod,
int side) {
long[] result = new long[matrix.length];
long[] temp = new long[result.length];
fastPower(matrix, result, temp, exponent, mod, side);
return result;
}
private static void fastPower(long[] matrix, long[] result, long[] temp,
long exponent, long mod, int side) {
if (exponent == 0) {
for (int i = 0; i < matrix.length; i += side + 1)
result[i] = 1;
return;
}
if ((exponent & 1) == 0) {
fastPower(matrix, temp, result, exponent >> 1, mod, side);
fastMultiply(result, temp, temp, mod, side);
} else {
power(matrix, temp, result, exponent - 1, mod, side);
fastMultiply(result, temp, matrix, mod, side);
}
}
public static void fastMultiply(long[] c, long[] a, long[] b, long mod,
int side) {
Arrays.fill(c, 0);
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++) {
for (int k = 0; k < side; k++)
c[i * side + k] += a[i * side + j] * b[j * side + k];
}
}
for (int i = 0; i < c.length; i++)
c[i] %= mod;
}
public Matrix power(long exponent) {
if (exponent == 0)
return identityMatrix(rowCount);
if (exponent == 1)
return this;
Matrix result = power(exponent >> 1);
result = multiply(result, result);
if ((exponent & 1) == 1)
result = multiply(result, this);
return result;
}
public Matrix fastPower(long exponent) {
if (exponent == 0)
return identityMatrix(rowCount);
if (exponent == 1)
return this;
Matrix result = power(exponent >> 1);
result = fastMultiply(result, result);
if ((exponent & 1) == 1)
result = fastMultiply(result, this);
return result;
}
}
class MiscUtils {
public static final int[] DX4 = { 1, 0, -1, 0 };
public static final int[] DY4 = { 0, -1, 0, 1 };
public static final int[] DX8 = { 1, 1, 1, 0, -1, -1, -1, 0 };
public static final int[] DY8 = { -1, 0, 1, 1, 1, 0, -1, -1 };
public static final int[] DX_KNIGHT = { 2, 1, -1, -2, -2, -1, 1, 2 };
public static final int[] DY_KNIGHT = { 1, 2, 2, 1, -1, -2, -2, -1 };
private static final String[] ROMAN_TOKENS = { "M", "CM", "D", "CD", "C",
"XC", "L", "XL", "X", "IX", "V", "IV", "I" };
private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1 };
public static long josephProblem(long n, int k) {
if (n == 1)
return 0;
if (k == 1)
return n - 1;
if (k > n)
return (josephProblem(n - 1, k) + k) % n;
long count = n / k;
long result = josephProblem(n - count, k);
result -= n % k;
if (result < 0)
result += n;
else
result += result / (k - 1);
return result;
}
public static boolean isValidCell(int row, int column, int rowCount,
int columnCount) {
return row >= 0 && row < rowCount && column >= 0
&& column < columnCount;
}
public static long maximalRectangleSum(long[][] array) {
int n = array.length;
int m = array[0].length;
long[][] partialSums = new long[n + 1][m + 1];
for (int i = 0; i < n; i++) {
long rowSum = 0;
for (int j = 0; j < m; j++) {
rowSum += array[i][j];
partialSums[i + 1][j + 1] = partialSums[i][j + 1] + rowSum;
}
}
long result = Long.MIN_VALUE;
for (int i = 0; i < m; i++) {
for (int j = i; j < m; j++) {
long minPartialSum = 0;
for (int k = 1; k <= n; k++) {
long current = partialSums[k][j + 1] - partialSums[k][i];
result = Math.max(result, current - minPartialSum);
minPartialSum = Math.min(minPartialSum, current);
}
}
}
return result;
}
public static int parseIP(String ip) {
String[] components = ip.split("[.]");
int result = 0;
for (int i = 0; i < 4; i++)
result += (1 << (24 - 8 * i)) * Integer.parseInt(components[i]);
return result;
}
public static String buildIP(int mask) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (i != 0)
result.append('.');
result.append(mask >> (24 - 8 * i) & 255);
}
return result.toString();
}
public static <T> boolean equals(T first, T second) {
return first == null && second == null || first != null
&& first.equals(second);
}
public static boolean isVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'
|| ch == 'Y';
}
public static boolean isStrictVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
public static String convertToRoman(int number) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number >= ROMAN_VALUES[i]) {
number -= ROMAN_VALUES[i];
result.append(ROMAN_TOKENS[i]);
}
}
return result.toString();
}
public static int convertFromRoman(String number) {
int result = 0;
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number.startsWith(ROMAN_TOKENS[i])) {
number = number.substring(ROMAN_TOKENS[i].length());
result += ROMAN_VALUES[i];
}
}
return result;
}
public static int distance(int x1, int y1, int x2, int y2) {
int dx = x1 - x2;
int dy = y1 - y2;
return dx * dx + dy * dy;
}
public static <T extends Comparable<T>> T min(T first, T second) {
if (first.compareTo(second) <= 0)
return first;
return second;
}
public static <T extends Comparable<T>> T max(T first, T second) {
if (first.compareTo(second) <= 0)
return second;
return first;
}
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++)
array[i]--;
}
}
public static int[] getIntArray(String s) {
String[] tokens = s.split(" ");
int[] result = new int[tokens.length];
for (int i = 0; i < result.length; i++)
result[i] = Integer.parseInt(tokens[i]);
return result;
}
}
class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
public long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public static Graph createGraph(int vertexCount, int[] from, int[] to) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addSimpleEdge(from[i], to[i]);
return graph;
}
public static Graph createWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addWeightedEdge(from[i], to[i], weight[i]);
return graph;
}
public static Graph createFlowGraph(int vertexCount, int[] from, int[] to,
long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowEdge(from[i], to[i], capacity[i]);
return graph;
}
public static Graph createFlowWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight, long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]);
return graph;
}
public static Graph createTree(int[] parent) {
Graph graph = new Graph(parent.length + 1, parent.length);
for (int i = 0; i < parent.length; i++)
graph.addSimpleEdge(parent[i], i + 1);
return graph;
}
public int addEdge(int fromID, int toID, long weight, long capacity,
int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1)
nextOutbound[edgeCount] = firstOutbound[fromID];
else
nextOutbound[edgeCount] = -1;
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1)
nextInbound[edgeCount] = firstInbound[toID];
else
nextInbound[edgeCount] = -1;
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null)
this.capacity = new long[from.length];
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null)
this.weight = new long[from.length];
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null)
edges[edgeCount] = createEdge(edgeCount);
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight,
long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addFlowEdge(int from, int to, long capacity) {
return addFlowWeightedEdge(from, to, 0, capacity);
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
public final int addSimpleEdge(int from, int to) {
return addWeightedEdge(from, to, 0);
}
public final int vertexCount() {
return vertexCount;
}
public final int edgeCount() {
return edgeCount;
}
protected final int edgeCapacity() {
return from.length;
}
public final Edge edge(int id) {
initEdges();
return edges[id];
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int firstInbound(int vertex) {
initInbound();
int id = firstInbound[vertex];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int nextInbound(int id) {
initInbound();
id = nextInbound[id];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int source(int id) {
return from[id];
}
public final int destination(int id) {
return to[id];
}
public final long weight(int id) {
if (weight == null)
return 0;
return weight[id];
}
public final long capacity(int id) {
if (capacity == null)
return 0;
return capacity[id];
}
public final long flow(int id) {
if (reverseEdge == null)
return 0;
return capacity[reverseEdge[id]];
}
public final void pushFlow(int id, long flow) {
if (flow == 0)
return;
if (flow > 0) {
if (capacity(id) < flow)
throw new IllegalArgumentException("Not enough capacity");
} else {
if (flow(id) < -flow)
throw new IllegalArgumentException("Not enough capacity");
}
capacity[id] -= flow;
capacity[reverseEdge[id]] += flow;
}
public int transposed(int id) {
return -1;
}
public final int reverse(int id) {
if (reverseEdge == null)
return -1;
return reverseEdge[id];
}
public final void addVertices(int count) {
ensureVertexCapacity(vertexCount + count);
Arrays.fill(firstOutbound, vertexCount, vertexCount + count, -1);
if (firstInbound != null)
Arrays.fill(firstInbound, vertexCount, vertexCount + count, -1);
vertexCount += count;
}
protected final void initEdges() {
if (edges == null) {
edges = new Edge[from.length];
for (int i = 0; i < edgeCount; i++)
edges[i] = createEdge(i);
}
}
public final void removeVertex(int vertex) {
int id = firstOutbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextOutbound[id];
}
initInbound();
id = firstInbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextInbound[id];
}
}
private void initInbound() {
if (firstInbound == null) {
firstInbound = new int[firstOutbound.length];
Arrays.fill(firstInbound, 0, vertexCount, -1);
nextInbound = new int[from.length];
for (int i = 0; i < edgeCount; i++) {
nextInbound[i] = firstInbound[to[i]];
firstInbound[to[i]] = i;
}
}
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final void setFlag(int id, int bit) {
flags[id] |= 1 << bit;
}
public final void removeFlag(int id, int bit) {
flags[id] &= -1 - (1 << bit);
}
public final void removeEdge(int id) {
setFlag(id, REMOVED_BIT);
}
public final void restoreEdge(int id) {
removeFlag(id, REMOVED_BIT);
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
public final Iterable<Edge> outbound(final int id) {
initEdges();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstOutbound, nextOutbound);
}
};
}
public final Iterable<Edge> inbound(final int id) {
initEdges();
initInbound();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstInbound, nextInbound);
}
};
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null)
edges = resize(edges, newSize);
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null)
nextInbound = resize(nextInbound, newSize);
if (weight != null)
weight = resize(weight, newSize);
if (capacity != null)
capacity = resize(capacity, newSize);
if (reverseEdge != null)
reverseEdge = resize(reverseEdge, newSize);
flags = resize(flags, newSize);
}
}
private void ensureVertexCapacity(int size) {
if (firstOutbound.length < size) {
int newSize = Math.max(size, 2 * from.length);
firstOutbound = resize(firstOutbound, newSize);
if (firstInbound != null)
firstInbound = resize(firstInbound, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public final boolean isSparse() {
return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
public int getSource() {
return source(id);
}
public int getDestination() {
return destination(id);
}
public long getWeight() {
return weight(id);
}
public long getCapacity() {
return capacity(id);
}
public long getFlow() {
return flow(id);
}
public void pushFlow(long flow) {
Graph.this.pushFlow(id, flow);
}
public boolean getFlag(int bit) {
return flag(id, bit);
}
public void setFlag(int bit) {
Graph.this.setFlag(id, bit);
}
public void removeFlag(int bit) {
Graph.this.removeFlag(id, bit);
}
public int getTransposedID() {
return transposed(id);
}
public Edge getTransposedEdge() {
int reverseID = getTransposedID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getReverseID() {
return reverse(id);
}
public Edge getReverseEdge() {
int reverseID = getReverseID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getID() {
return id;
}
public void remove() {
removeEdge(id);
}
public void restore() {
restoreEdge(id);
}
}
public class EdgeIterator implements Iterator<Edge> {
private int edgeID;
private final int[] next;
private int lastID = -1;
public EdgeIterator(int id, int[] first, int[] next) {
this.next = next;
edgeID = nextEdge(first[id]);
}
private int nextEdge(int id) {
while (id != -1 && isRemoved(id))
id = next[id];
return id;
}
public boolean hasNext() {
return edgeID != -1;
}
public Edge next() {
if (edgeID == -1)
throw new NoSuchElementException();
lastID = edgeID;
edgeID = nextEdge(next[lastID]);
return edges[lastID];
}
public void remove() {
if (lastID == -1)
throw new IllegalStateException();
removeEdge(lastID);
lastID = -1;
}
}
}
interface Edge {
public int getSource();
public int getDestination();
public long getWeight();
public long getCapacity();
public long getFlow();
public void pushFlow(long flow);
public boolean getFlag(int bit);
public void setFlag(int bit);
public void removeFlag(int bit);
public int getTransposedID();
public Edge getTransposedEdge();
public int getReverseID();
public Edge getReverseEdge();
public int getID();
public void remove();
public void restore();
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> g[100001];
vector<int> gg[100001];
bool vis[100001];
int bel[100001];
void dfs1(int x, int w) {
bel[x] = w;
vis[x] = 1;
for (int i = 0; i < gg[x].size(); i++) {
int v = gg[x][i];
if (vis[v]) continue;
dfs1(v, w);
}
}
int degree[100001];
vector<int> pk[100001];
int ans = 0;
queue<int> q;
void solve(int x) {
int num = 0;
for (int i = 0; i < pk[x].size(); i++) {
int a = pk[x][i];
if (degree[a] == 0) {
num++;
q.push(a);
}
}
while (!q.empty()) {
int a = q.front();
q.pop();
for (int i = 0; i < g[a].size(); i++) {
int v = g[a][i];
degree[v]--;
if (degree[v] == 0) {
num++;
q.push(v);
}
}
}
if (num == pk[x].size())
ans += num - 1;
else
ans += pk[x].size();
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1, a, b; i <= m; i++) {
scanf("%d%d", &a, &b);
g[a].push_back(b);
degree[b]++;
gg[a].push_back(b);
gg[b].push_back(a);
}
int o = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
o++;
dfs1(i, o);
}
}
for (int i = 1; i <= n; i++) {
pk[bel[i]].push_back(i);
}
for (int i = 1; i <= o; i++) {
solve(i);
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m, rt[100100], x[100100], y[100100];
int find_rt(int u) { return rt[u] == u ? u : rt[u] = find_rt(rt[u]); }
void link(int u, int v) {
u = find_rt(u), v = find_rt(v);
if (u != v) rt[u] = v;
}
vector<int> adj[100100], edge[100100], node[100100];
int C, col[100100], ord[100100], ft;
bool vis[100100];
vector<int> v[100100], rv[100100];
void dfs(int x) {
vis[x] = 1;
for (auto y : v[x])
if (!vis[y]) dfs(y);
ord[ft--] = x;
}
void rdfs(int x) {
col[x] = C;
for (auto y : rv[x])
if (!col[y]) rdfs(y);
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) rt[i] = i;
for (int i = 0; i < m; i++) scanf("%d %d", &x[i], &y[i]), link(x[i], y[i]);
for (int i = 0; i < m; i++) edge[find_rt(x[i])].push_back(i);
for (int i = 1; i <= n; i++) node[find_rt(i)].push_back(i);
int rlt = 0;
for (int i = 1; i <= n; i++) {
if (node[i].size()) {
for (auto j : edge[i]) v[x[j]].push_back(y[j]), rv[y[j]].push_back(x[j]);
int sz = node[i].size();
ft = sz;
for (auto u : node[i])
if (!vis[u]) dfs(u);
C = 0;
for (int i = 1; i <= sz; i++)
if (!col[ord[i]]) C++, rdfs(ord[i]);
rlt += C == sz ? sz - 1 : sz;
}
}
printf("%d\n", rlt);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int MX = 200005;
long long N, M;
bool vis[100005], instack[100005];
vector<int> G[100005];
int par[100005], size[100005];
bool cycle[100005];
bool ok;
int findF(int x) { return par[x] == x ? x : findF(par[x]); }
void unionF(int x, int y) {
x = findF(x), y = findF(y);
if (x == y) return;
if (size[x] < size[y]) swap(x, y);
size[x] += size[y];
par[y] = x;
}
void dfs(int u) {
if (instack[u]) ok = 1;
if (vis[u]) return;
vis[u] = 1;
instack[u] = 1;
for (int i = 0; i < (int)G[u].size(); i++) {
dfs(G[u][i]);
}
instack[u] = 0;
}
void go_solver() {
ios::sync_with_stdio(false);
cin >> N >> M;
for (int i = 1; i <= N; i++) par[i] = i, size[i] = 1;
for (int i = 0; i < M; i++) {
int x, y;
cin >> x >> y;
G[x].push_back(y);
unionF(x, y);
}
for (int i = 1; i <= N; i++) {
ok = 0;
if (!vis[i]) dfs(i), cycle[findF(i)] |= ok;
}
memset(vis, 0, sizeof vis);
int ans = 0;
for (int i = 1; i <= N; i++) {
int x = findF(i);
if (vis[x]) continue;
vis[x] = 1;
ans += size[x] - 1 + cycle[x];
}
cout << ans << "\n";
}
int main() {
go_solver();
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void Int(T &n) {
n = 0;
int f = 1;
register int ch = getchar();
for (; !isdigit(ch); ch = getchar())
if (ch == '-') f = -1;
for (; isdigit(ch); ch = getchar()) n = (n << 3) + (n << 1) + ch - '0';
n = n * f;
}
template <typename T>
T gcd(T a, T b) {
return !b ? a : gcd(b, a % b);
}
template <typename T>
inline void umin(T &a, T b) {
a = a < b ? a : b;
}
template <typename T>
inline void umax(T &a, T b) {
a = a > b ? a : b;
}
template <typename T, typename W>
inline void Int(T &x, W &y) {
Int(x), Int(y);
}
template <typename T, typename W, typename Q>
inline void Int(T &x, W &y, Q &z) {
Int(x, y), Int(z);
}
const int N = 1e5 + 7;
const int inf = 1e9 + 7;
int nd, d[N], used[N];
vector<int> g[N], t[N];
void dfs(int u) {
if (used[u]) return;
used[u] = 1, ++nd;
for (int v : g[u]) dfs(v);
for (int v : t[u]) dfs(v);
}
int solve() {
int n, m;
Int(n, m);
for (int i = 1; i <= m; ++i) {
int u, v;
Int(u, v);
++d[v];
g[u].push_back(v);
t[v].push_back(u);
}
vector<int> V;
for (int i = 1; i <= n; ++i)
if (!d[i]) V.push_back(i);
for (int i = 0; i <= (int)V.size() - 1; ++i) {
int u = V[i];
for (int v : g[u])
if (!--d[v]) V.push_back(v);
}
int res = 0;
for (int i = 1; i <= n; ++i)
if (!used[i] and d[i]) {
nd = 0;
dfs(i);
res += nd;
}
for (int i = 1; i <= n; ++i)
if (!used[i] and !d[i]) {
nd = 0;
dfs(i);
res += nd - 1;
}
printf("%d\n", res);
return 0;
}
int main() {
int tests = 1, CaseNo = 0;
while (tests--) {
solve();
}
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> g[100500], f[100500];
char was[100500];
int C, cl[100500];
vector<int> a[100500];
void dfs1(int v) {
a[C].push_back(v);
was[v] = 1;
for (int i = 0; i < f[v].size(); ++i) {
int to = f[v][i];
if (!was[to]) dfs1(to);
}
return;
}
bool dfs2(int v) {
cl[v] = 1;
for (int i = 0; i < g[v].size(); ++i) {
int to = g[v][i];
if (cl[to] != 0) {
if (cl[to] == 1) return 1;
} else {
if (dfs2(to)) return 1;
}
}
cl[v] = 2;
return 0;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
int v, u;
scanf("%d%d", &v, &u);
g[v].push_back(u);
f[v].push_back(u);
f[u].push_back(v);
}
C = 0;
for (int i = 1; i <= n; ++i) {
if (!was[i]) {
dfs1(i);
C++;
}
}
int ans = 0;
for (int i = 0; i < C; ++i) {
bool cycle = 0;
for (int j = 0; j < a[i].size(); ++j) {
int v = a[i][j];
if (!cl[v]) {
cycle |= dfs2(v);
}
}
ans += (a[i].size() - 1);
if (cycle) ++ans;
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> been;
vector<vector<int> > sorted;
vector<vector<pair<int, bool> > > graph;
void dfs(int index) {
been[index] = 1;
for (int i = 0; i < graph[index].size(); i++)
if (!been[graph[index][i].first]) dfs(graph[index][i].first);
sorted[sorted.size() - 1].push_back(index);
}
bool dfs2(int index) {
bool res = false;
been[index] = 1;
for (int i = 0; i < graph[index].size(); i++)
if (graph[index][i].second) {
if (been[graph[index][i].first] == 1) res = true;
if (!been[graph[index][i].first]) res |= dfs2(graph[index][i].first);
}
been[index] = 2;
return res;
}
int main() {
int n, m, i, j, a, b;
cin >> n >> m;
graph = vector<vector<pair<int, bool> > >(n);
vector<bool> leads(n, true);
for (i = 0; i < m; i++) {
cin >> a >> b;
a--;
b--;
graph[a].push_back(make_pair(b, true));
graph[b].push_back(make_pair(a, false));
leads[b] = false;
}
been = vector<int>(n);
for (i = 0; i < n; i++)
if (!been[i]) {
sorted.push_back(vector<int>());
dfs(i);
}
vector<int> which(n);
for (i = 0; i < sorted.size(); i++)
for (j = 0; j < sorted[i].size(); j++) which[sorted[i][j]] = i;
vector<int> leadwho(sorted.size(), -1);
for (i = 0; i < n; i++) {
been[i] = 0;
if (leads[i]) leadwho[which[i]] = i;
}
int res = 0;
bool loop;
for (i = 0; i < sorted.size(); i++) {
loop = false;
for (j = 0; j < sorted[i].size(); j++)
if (!been[sorted[i][j]]) loop |= dfs2(sorted[i][j]);
res += sorted[i].size() - 1 + loop;
}
cout << res;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
static int n;
static int m;
static List<Integer>[] g;
static List<Integer>[] rg;
static List<Integer>[] comp;
static int[] visit;
static int compCount = 0;
public void solve(int testNumber, FastReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
g = new List[n];
rg = new List[n];
comp = new List[n];
visit = new int[n];
for (int i = 0; i < n; ++i) {
g[i] = new ArrayList<>();
rg[i] = new ArrayList<>();
}
for (int i = 0; i < m; ++i) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
g[u].add(v);
rg[v].add(u);
}
int ans = n;
for (int i = 0; i < n; ++i) {
if (visit[i] == 0) {
comp[compCount] = new ArrayList<>();
visit[i] = 1;
dfs(i);
++compCount;
}
}
ans -= compCount;
ArrayUtils.fill(visit, 0);
for (int i = 0; i < compCount; ++i) {
for (Integer cur : comp[i]) {
if (visit[cur] == 0) {
if (dfs2(cur)) {
++ans;
break;
}
}
}
}
out.println(ans);
}
public static void dfs(int cur) {
comp[compCount].add(cur);
for (Integer next : g[cur]) {
if (visit[next] == 0) {
visit[next] = 1;
dfs(next);
}
}
for (Integer next : rg[cur]) {
if (visit[next] == 0) {
visit[next] = 1;
dfs(next);
}
}
}
public static boolean dfs2(int cur) {
visit[cur] = 1;
for (Integer next : g[cur]) {
if (visit[next] == 1)
return true;
else if (visit[next] == 0 && dfs2(next))
return true;
}
visit[cur] = 2;
return false;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class ArrayUtils {
public static void fill(int[] array, int value) {
Arrays.fill(array, value);
}
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
vector<int> graph[maxn];
vector<int> g[maxn];
bool mark[maxn];
int n, m;
int par[maxn];
int cm[maxn];
bool comp[maxn];
int mk[maxn];
int moalefe[maxn];
void dfs(int x, int y) {
mark[x] = 1;
cm[x] = y;
moalefe[y]++;
for (int v : graph[x])
if (!mark[v]) dfs(v, y);
}
void ddfs(int x) {
mk[x] = 1;
for (int v : g[x]) {
if (mk[v] == 0)
ddfs(v);
else if (mk[v] == 1)
comp[cm[v]] = 1;
}
mk[x] = 2;
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int t1, t2;
cin >> t1 >> t2;
t1--;
t2--;
graph[t1].push_back(t2);
graph[t2].push_back(t1);
g[t1].push_back(t2);
}
int mo = 1;
for (int i = 0; i < n; i++) {
if (!mark[i]) {
dfs(i, mo);
mo++;
}
}
for (int i = 0; i < n; i++) {
if (mk[i] == 0) ddfs(i);
}
int ans = 0;
for (int i = 1; i < mo; i++) {
if (comp[i])
ans += moalefe[i];
else
ans += moalefe[i] - 1;
}
cout << ans;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK: 1024000000,1024000000")
using namespace std;
const int N = 1e5 + 15;
struct Edge {
int u, v, nxt;
Edge() {}
Edge(int t2, int t3, int t4) : u(t2), v(t3), nxt(t4) {}
};
Edge e[N * 30];
int h[N], ect;
int low[N], dfn[N], vis[N], col[N], sz[N], s[N], tp, sm, tme;
vector<int> R[N * 10], C[N * 10];
int r[N], c[N], op[N];
map<pair<int, int>, int> M;
int in[N], val[N], cyc[N];
void init() {
memset(h, 0, sizeof(h));
ect = sm = tp = tme = 0;
}
void add(int u, int v) {
e[++ect] = Edge(u, v, h[u]);
h[u] = ect;
}
void tarjan(int u) {
vis[u] = 1;
low[u] = dfn[u] = ++tme;
s[++tp] = u;
for (int i = h[u]; i; i = e[i].nxt) {
int v = e[i].v;
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (vis[v])
low[u] = min(low[u], dfn[v]);
}
if (low[u] == dfn[u]) {
vis[u] = 0;
col[u] = ++sm;
sz[sm]++;
while (s[tp] != u) {
vis[s[tp]] = 0;
col[s[tp--]] = sm;
sz[sm]++;
}
tp--;
if (sz[sm] > 1) cyc[sm] = 1;
}
}
int fa[N];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0, u, v; i < m; i++) {
scanf("%d%d", &u, &v);
add(u, v);
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
for (int i = 1; i <= sm; i++) fa[i] = i;
for (int i = 1; i <= ect; i++) {
int u = e[i].u, v = e[i].v;
u = col[u], v = col[v];
u = find(u), v = find(v);
if (u != v) {
cyc[u] |= cyc[v];
sz[u] += sz[v];
fa[v] = u;
}
}
int ans = 0;
for (int i = 1; i <= sm; i++)
if (fa[i] == i) ans += sz[i] - (cyc[i] == 0);
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
const long long base = 1e18 + 7;
const long long mod = 1e9 + 7;
const int M = (1 << 9) + 7;
int n, m, pa[N], deg[N], sz[N];
bool cycle[N];
vector<int> ke[N];
queue<int> q;
int getroot(int u) {
if (u == pa[u]) return u;
return pa[u] = getroot(pa[u]);
}
void join(int u, int v) {
u = getroot(u);
v = getroot(v);
pa[u] = v;
}
void topo_sort() {
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : ke[u]) {
deg[v]--;
if (deg[v] == 0) q.push(v);
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int j = 1; j <= n; j++) pa[j] = j;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
ke[u].push_back(v);
join(u, v);
deg[v]++;
}
for (int i = 1; i <= n; i++) {
sz[getroot(i)]++;
if (!deg[i]) q.push(i);
}
topo_sort();
for (int i = 1; i <= n; i++)
if (deg[i]) cycle[getroot(i)] = 1;
int res = 0;
for (int i = 1; i <= n; i++) {
if (pa[i] == i) {
res = res + sz[i];
if (!cycle[i]) res--;
}
}
cout << res;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
vector<int> G[maxn], E[maxn];
int n, m;
int vis[maxn];
vector<int> vec;
int C, col[maxn];
void dfs(int u) {
vis[u] = 1;
col[u] = C;
vec.push_back(u);
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (!vis[v]) dfs(v);
}
}
int ins[maxn], vis2[maxn];
bool dfs2(int u) {
ins[u] = C;
vis2[u] = C;
for (int i = 0; i < E[u].size(); i++) {
int v = E[u][i];
if (ins[v] == C) return true;
if (vis2[v] != C)
if (dfs2(v)) return true;
}
ins[u] = 0;
return false;
}
int main() {
scanf("%d%d", &n, &m);
while (m--) {
int u, v;
scanf("%d%d", &u, &v);
E[u].push_back(v);
G[u].push_back(v);
G[v].push_back(u);
}
int ans = n;
for (int i = 1; i <= n; i++)
if (!vis[i]) {
vec.clear();
C++;
dfs(i);
int flag = 0;
for (int i = 0; i < vec.size(); i++)
if (dfs2(vec[i])) {
flag = 1;
break;
}
ans -= !flag;
}
cout << ans << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int recur_depth = 0;
const long long sz = 1e5 + 10;
vector<long long> g[sz], g2[sz], comp;
bitset<sz> ase;
long long tot, vis[sz], cyc = 0;
void dfs(long long u) {
vis[u] = 1;
for (long long& v : g[u]) {
if (!vis[v])
dfs(v);
else if (vis[v] == 1)
cyc = 1;
}
vis[u] = 2;
}
void dfs2(long long u) {
vis[u] = 1;
comp.push_back(u);
for (long long& v : g2[u])
if (!vis[v]) dfs2(v);
}
int main() {
long long n, m;
scanf("%lld", &n), scanf("%lld", &m);
for (long long i = 1; i <= m; ++i) {
long long u, v;
scanf("%lld", &u), scanf("%lld", &v);
g[u].push_back(v);
g2[u].push_back(v), g2[v].push_back(u);
ase[u] = ase[v] = 1;
}
long long ans = 0;
for (long long i = 1; i <= n; ++i) {
if (!ase[i] || vis[i]) continue;
comp.clear();
dfs2(i);
for (long long& x : comp) vis[x] = 0;
cyc = 0;
for (long long& x : comp) {
if (vis[x]) continue;
dfs(x);
}
if (cyc)
ans += comp.size();
else
ans += comp.size() - 1;
}
cout << ans << '\n';
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
vector<int> v[N], u[N], w;
int c[N];
int d[N];
int n, m, a, b, ans;
int dfs(int i) {
c[i]++;
for (auto k : v[i]) {
if (c[k] == 1) return 1;
if (c[k] == 0 && dfs(k)) return 1;
}
c[i]++;
return 0;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
v[a].push_back(b);
u[a].push_back(b);
u[b].push_back(a);
}
for (int i = 0; i <= n; i++) {
if (d[i] || !u[i].size()) continue;
d[i]++;
w.clear();
deque<int> q;
q.push_back(i);
while (!q.empty()) {
int j = q.front();
q.pop_front();
w.push_back(j);
for (auto k : u[j])
if (!d[k]) {
q.push_back(k);
d[k]++;
ans++;
}
}
for (auto l : w) {
if (c[l]) continue;
if (dfs(l)) {
ans++;
break;
}
}
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
const int dx[] = {1, -1, 0, 0, 1, -1, 1, -1};
const int dy[] = {0, 0, 1, -1, 1, 1, -1, -1};
const int kx[] = {2, 2, -2, -2, 1, -1, 1, -1};
const int ky[] = {1, -1, 1, -1, 2, 2, -2, -2};
bool check(int a, int p) { return (bool)(a & (1 << p)); }
int on(int a, int p) { return (a | (1 << p)); }
using namespace std;
bool fl;
short visit[200010];
bool cycle[200010];
int par[200010];
int size_[200010];
vector<int> adj[200010];
void dfs(int v) {
visit[v] = 1;
for (int u : adj[v]) {
if (visit[u] == 1) {
fl = 1;
}
if (visit[u] == 0) {
dfs(u);
}
}
visit[v] = 2;
}
int find_(int v) {
if (v == par[v]) {
return v;
}
return par[v] = find_(par[v]);
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
par[i] = i;
size_[i] = 1;
}
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d %d", &a, &b);
adj[a].push_back(b);
int x = find_(a);
int y = find_(b);
if (x != y) par[y] = x, size_[x] += size_[y];
}
for (int i = 1; i <= n; i++) {
if (visit[i] == 0) {
fl = 0;
dfs(i);
if (fl) {
int x = find_(i);
cycle[x] = 1;
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
int x = find_(i);
if (visit[x] == 2) {
ans += size_[x] - 1;
if (cycle[x]) {
ans++;
}
visit[x] = 4;
}
}
cout << ans << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> adj[100005], dir[100005], vec;
int vis1[100005], vis2[100005], vis3[100005], fl = 0;
void dfs1(int u) {
vis1[u] = 1;
vec.push_back(u);
for (int i = (int)0; i <= (int)adj[u].size() - 1; i++) {
if (!vis1[adj[u][i]]) dfs1(adj[u][i]);
}
}
void dfs2(int u) {
vis2[u] = 1;
vis3[u] = 1;
for (int i = (int)0; i <= (int)dir[u].size() - 1; i++) {
if (!vis2[dir[u][i]]) dfs2(dir[u][i]);
if (vis3[dir[u][i]]) fl = 1;
}
vis3[u] = 0;
}
int fun() {
int ret = 0;
for (int j = (int)0; j <= (int)vec.size() - 1; j++) {
if (!vis2[vec[j]]) {
fl = 0;
dfs2(vec[j]);
ret += fl;
}
}
return (ret == 0);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = (int)1; i <= (int)m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
dir[u].push_back(v);
}
int ans = 0;
for (int i = (int)1; i <= (int)n; i++) {
if (!vis1[i]) {
vec.clear();
dfs1(i);
ans += vec.size() - fun();
}
}
cout << ans << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9 + 10;
const long long N = 1e5 + 10;
vector<long long> g[N], rg[N], gg[N], order;
long long c[N], x[N];
bool used[N], kek;
void dfs(long long v) {
used[v] = true;
for (auto u : g[v]) {
if (!used[u]) {
dfs(u);
}
}
order.push_back(v);
}
void dfs2(long long v, long long color) {
c[v] = color;
x[color]++;
for (auto u : rg[v]) {
if (!c[u]) {
dfs2(u, color);
}
}
}
void go(long long v) {
used[v] = true;
if (x[v] > 1) {
kek = true;
}
for (auto u : gg[v]) {
if (!used[u]) {
go(u);
}
}
}
signed main() {
ios_base::sync_with_stdio(0);
long long n, m;
cin >> n >> m;
vector<pair<long long, long long>> edge;
for (long long i = 0; i < m; i++) {
long long u, v;
cin >> u >> v;
g[u].push_back(v);
rg[v].push_back(u);
edge.push_back({u, v});
}
for (long long i = 1; i <= n; i++) {
if (!used[i]) {
dfs(i);
}
}
reverse((order).begin(), (order).end());
long long cnt = 0;
for (long long v : order) {
if (!c[v]) {
dfs2(v, ++cnt);
}
}
long long ans = 0;
for (auto it : edge) {
if (c[it.first] != c[it.second]) {
gg[c[it.first]].push_back(c[it.second]);
gg[c[it.second]].push_back(c[it.first]);
}
}
for (long long i = 1; i <= cnt; i++) {
sort((gg[i]).begin(), (gg[i]).end());
gg[i].resize(unique((gg[i]).begin(), (gg[i]).end()) - gg[i].begin());
used[i] = false;
}
long long comps = 0;
for (long long i = 1; i <= cnt; i++) {
if (!used[i]) {
kek = false;
go(i);
comps++;
if (kek) {
ans++;
}
}
}
ans += n - comps;
cout << ans << '\n';
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int n, m, ans, l, r;
int line[MAXN];
int du[MAXN];
int nxt[MAXN];
bool boo[MAXN];
bool bbb[MAXN];
vector<int> v[MAXN];
int Find(int k) {
if (nxt[k] != k) nxt[k] = Find(nxt[k]);
return nxt[k];
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) nxt[i] = i;
for (int i = 1; i <= m; ++i) {
int x, y;
scanf("%d%d", &x, &y);
v[x].push_back(y);
int xx = Find(x), yy = Find(y);
if (xx != yy) nxt[xx] = yy;
++du[y];
}
ans = n;
for (int i = 1; i <= n; ++i) {
int tmp = Find(i);
if (!boo[tmp]) {
boo[tmp] = true;
--ans;
}
}
memset(boo, 0, sizeof(boo));
for (int i = 1; i <= n; ++i)
if (!du[i]) line[++r] = i;
for (l = 1; l <= r; ++l) {
bbb[line[l]] = true;
for (__typeof(v[line[l]].begin()) p = v[line[l]].begin();
p != v[line[l]].end(); ++p) {
--du[*p];
if (!du[*p]) line[++r] = *p;
}
}
for (int i = 1; i <= n; ++i)
if (!bbb[i]) {
int tmp = Find(i);
if (!boo[tmp]) {
boo[tmp] = true;
++ans;
}
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
const int mo = 1e9 + 7;
const int N = 2e5 + 10;
vector<int> mem[N], son[N];
int fa[N], du[N];
bool finish[N];
int getfa(int x) { return (fa[x] == x) ? x : (fa[x] = getfa(fa[x])); }
queue<int> Q;
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i, du[i] = 0;
for (int x, y, i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
son[x].push_back(y);
du[y]++;
x = getfa(x);
y = getfa(y);
if (x != y) fa[x] = y;
}
for (int i = 1; i <= n; i++) {
int x = getfa(i);
mem[x].push_back(i);
}
int ans = n;
memset(finish, 0, sizeof finish);
for (int i = 1; i <= n; i++)
if (!finish[fa[i]]) {
int x = fa[i];
int tot = mem[x].size();
finish[x] = 1;
int num = 0;
for (int j = 0; j < tot; j++)
if (du[mem[x][j]] == 0) Q.push(mem[x][j]), num++;
while (!Q.empty()) {
int x = Q.front();
Q.pop();
for (int k = 0; k < son[x].size(); k++) {
int y = son[x][k];
du[y]--;
if (du[y] == 0) Q.push(y), num++;
}
}
if (num == tot) ans--;
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
const double PI = acos(-1);
using namespace std;
const int MAX = 100 * 1000 + 10;
int n, m;
int A[MAX], B[MAX];
vector<int> I[MAX], rI[MAX], G[MAX], rG[MAX];
vector<int> SCC[MAX];
int id[MAX], scc_cnt;
vector<int> ord;
bool vis[MAX];
void dfs(int u) {
if (vis[u]) return;
vis[u] = 1;
for (int v : I[u]) dfs(v);
ord.push_back(u);
}
void dfs(int u, int scc) {
if (vis[u]) return;
id[u] = scc;
SCC[scc].push_back(u);
vis[u] = 1;
for (int v : rI[u]) dfs(v, scc);
}
int ans = 0;
void prepare() {
for (int i = 1; i <= n; i++) dfs(i);
fill(vis, vis + n + 1, 0);
reverse(ord.begin(), ord.end());
for (int i : ord)
if (!vis[i]) dfs(i, scc_cnt++);
for (int i = 0; i < scc_cnt; i++) {
int s = ((int)SCC[i].size());
if (s <= 1) continue;
ans += s;
}
auto conv = [](const int &x) { return SCC[id[x]][0]; };
for (int e = 0; e < m; e++) {
A[e] = conv(A[e]);
B[e] = conv(B[e]);
}
}
int inDeg[MAX], L;
vector<int> lev[MAX];
int H[MAX];
void hang() {
queue<int> q;
for (int e = 0; e < m; e++) {
if (A[e] == B[e]) continue;
inDeg[B[e]]++;
G[A[e]].push_back(B[e]);
rG[B[e]].push_back(A[e]);
}
for (int i = 1; i <= n; i++)
if (inDeg[i] == 0) q.push(i);
for (L = 0; !q.empty(); L++) {
for (int s = q.size(); s > 0; s--) {
int u = q.front();
q.pop();
lev[L].push_back(u);
H[u] = L;
for (int v : G[u]) {
inDeg[v]--;
if (inDeg[v] == 0) q.push(v);
}
}
}
}
int ID[MAX], W[MAX], sccContent[MAX];
int find(int a) { return ID[a] = (a == ID[a]) ? a : find(ID[a]); }
void join(int a, int b) {
a = find(a), b = find(b);
if (a == b) return;
if (W[a] < W[b]) swap(a, b);
W[a] += W[b];
ID[b] = a;
sccContent[a] += sccContent[b];
}
bool areConnected(int a, int b) { return find(a) == find(b); }
void compute() {
for (int i = 1; i <= n; i++) {
ID[i] = i;
W[i] = 1;
sccContent[i] = ((int)SCC[id[i]].size()) > 1;
}
for (int l = 0; l < L; l++) {
for (int u : lev[l]) {
sort(rG[u].begin(), rG[u].end(),
[](const int &a, const int &b) { return H[a] > H[b]; });
for (int v : rG[u]) {
if (areConnected(u, v)) continue;
ans++;
join(u, v);
int &s = sccContent[find(u)];
ans -= s > 1;
s = min(s, 1);
}
}
}
}
int main(int argc, char **argv) {
scanf("%d %d", &n, &m);
for (int e = 0; e < m; e++) {
scanf("%d %d", A + e, B + e);
I[A[e]].push_back(B[e]);
rI[B[e]].push_back(A[e]);
}
prepare();
hang();
compute();
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
final static String fileName = "";
final static boolean useFiles = false;
public static void main(String[] args) throws FileNotFoundException {
InputStream inputStream;
OutputStream outputStream;
if (useFiles) {
inputStream = new FileInputStream(fileName + ".in");
outputStream = new FileOutputStream(fileName + ".out");
} else {
inputStream = System.in;
outputStream = System.out;
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task(in, out);
Debug.out = out;
solver.solve();
out.close();
}
}
class Graph {
int n;
int edgesCount = 0;
List<List<Edge>> g;
Graph(int n) {
this.n = n;
g = new ArrayList<List<Edge>>(n);
for (int i = 0; i < n; i++)
g.add(new ArrayList<Edge>());
}
void AddEdge(int from, Edge edge) {
edgesCount++;
g.get(from).add(edge);
}
int getEdgesCount() {
return edgesCount;
}
int getVertexesCount(){
return n;
}
}
class Edge {
Edge(int f, int t) {
From = f;
To = t;
}
int From, To;
}
class Task {
int n, m;
Graph g;
boolean[] used;
List<Integer> component;
void dfs(int v){
used[v] = true;
component.add(v);
for (int i = 0; i < g.g.get(v).size(); i++){
int to = g.g.get(v).get(i).To;
if (!used[to])
dfs(to);
}
}
Graph ori;
boolean[] usedOrder;
List<Integer> orderList;
void order(int v){
usedOrder[v] = true;
for (int i = 0; i < ori.g.get(v).size(); i++){
int to = ori.g.get(v).get(i).To;
if (!usedOrder[to])
order(to);
}
orderList.add(v);
}
public void solve() {
n = in.nextInt();
m = in.nextInt();
g = new Graph(n);
ori = new Graph(n);
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1,
b = in.nextInt() - 1;
ori.AddEdge(a, new Edge(a, b));
g.AddEdge(a, new Edge(a, b));
g.AddEdge(b, new Edge(b, a));
}
used = new boolean[n];
component = new ArrayList<>(n);
usedOrder = new boolean[n];
int[] index = new int[n];
int result = 0;
orderList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
if (!used[i]) {
dfs(i);
for (int j= 0; j < component.size(); j++){
if (!usedOrder[component.get(j)])
order(component.get(j));
}
// for (int elem : orderList){
// out.print(elem + " ");
// }
// out.println();
for (int j = 0; j < orderList.size(); j++)
index[orderList.get(j)] = j;
// for (int j = 0; j < orderList.size(); j++){
// out.print(index[j] + " ");
// }
// out.println();
boolean cyclic = false;
exFor:
for (int j = 0; j < orderList.size(); j++){
int v = orderList.get(j);
for (int k = 0; k < ori.g.get(v).size(); k++){
int to = ori.g.get(v).get(k).To;
if (index[v] < index[to]){
cyclic = true;
break exFor;
}
}
}
if (cyclic)
result += orderList.size();
else
result += orderList.size() - 1;
orderList.clear();
component.clear();
}
}
out.print(result);
}
private InputReader in;
private PrintWriter out;
Task(InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
}
class Debug {
public static PrintWriter out;
public static void printObjects(Object... objects) {
out.println(Arrays.deepToString(objects));
out.flush();
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public double nextDouble(){
return Double.parseDouble(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> arr[100005];
vector<int> rev[100005];
int ans[100005];
int comp[100005];
int fans = 0;
vector<int> f;
bool vis[100005];
bool visC[100005];
bool flag;
int cnt, sumC;
void dfs(int v) {
vis[v] = true;
vector<int> tmp;
if (flag)
tmp = arr[v];
else
tmp = rev[v];
for (int i = 0; i < tmp.size(); i++) {
if (vis[tmp[i]]) continue;
dfs(tmp[i]);
}
if (flag)
f.push_back(v);
else
ans[cnt]++, comp[v] = cnt;
}
int cntC;
void dfs2(int v) {
vis[v] = true;
if (!visC[comp[v]]) {
if (ans[comp[v]] > 1) flag = true;
cntC++, visC[comp[v]] = true;
sumC += ans[comp[v]];
}
for (int i = 0; i < arr[v].size(); i++)
if (!vis[arr[v][i]]) dfs2(arr[v][i]);
for (int i = 0; i < rev[v].size(); i++)
if (!vis[rev[v][i]]) dfs2(rev[v][i]);
}
void func() {
flag = true;
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs(i);
memset(vis, false, sizeof(vis));
flag = false;
for (int i = f.size() - 1; i >= 0; i--)
if (!vis[f[i]]) {
cnt++, dfs(f[i]);
}
memset(vis, false, sizeof(vis));
for (int i = 1; i <= n; i++) {
if (visC[comp[i]]) continue;
flag = false;
dfs2(i);
if (flag)
fans += sumC;
else
fans += (cntC - 1);
cntC = 0;
sumC = 0;
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d%d", &x, &y);
arr[x].push_back(y);
rev[y].push_back(x);
}
func();
cout << (fans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1E5 + 5;
int n, m;
bool foundCir, mark[MAXN], inPath[MAXN];
vector<int> adj[MAXN], adj2[MAXN], st;
void go1(int u) {
st.push_back(u);
mark[u] = 1;
for (int i = 0; i < int(adj2[u].size()); ++i) {
int v = adj2[u][i];
if (!mark[v]) go1(v);
}
}
void go2(int u) {
mark[u] = 1;
inPath[u] = 1;
for (int i = 0; i < int(adj[u].size()); ++i) {
int v = adj[u][i];
if (!mark[v])
go2(v);
else if (inPath[v])
foundCir = 1;
}
inPath[u] = 0;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0, _n = m; i < _n; ++i) {
int u, v;
scanf("%d%d", &u, &v);
adj[u].push_back(v);
adj2[u].push_back(v);
adj2[v].push_back(u);
}
int res = 0;
for (int u = 1; u <= n; ++u)
if (!mark[u]) {
st.clear();
go1(u);
for (int i = 0; i < int(st.size()); ++i) mark[st[i]] = 0;
foundCir = 0;
for (int i = 0; i < int(st.size()); ++i)
if (!mark[st[i]]) go2(st[i]);
res += st.size();
if (!foundCir) --res;
}
printf("%d", res);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 3e5 + 10;
int n, m, ans;
vector<int> G[maxn], g[maxn], gr[maxn], comp;
bool mark[maxn], in[maxn], out[maxn];
bool dfs(int x) {
in[x] = 1;
for (int u : g[x]) {
if (in[u] && !out[u]) return 0;
if (!in[u] && !dfs(u)) return 0;
}
out[x] = 1;
return 1;
}
void pfs(int x) {
mark[x] = 1;
comp.push_back(x);
for (int u : G[x])
if (!mark[u]) pfs(u);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
while (m--) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
gr[v].push_back(u);
G[u].push_back(v);
G[v].push_back(u);
}
for (int i = 1; i <= n; i++)
if (!mark[i]) {
comp.clear();
pfs(i);
bool has_cycle = 0;
for (int j : comp)
if (!in[j]) has_cycle |= (!dfs(j));
ans += comp.size() + has_cycle - 1;
}
cout << ans;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int SIZE = 1e6 + 10;
vector<int> e[SIZE];
vector<pair<int, int> > pp;
bool used[SIZE];
int id, order[SIZE], num;
void dfs(int x) {
used[x] = 1;
num++;
for (int i = 0; i < (((int)(e[x]).size())); ++i) {
int y = e[x][i];
pp.push_back(make_pair(x, y));
if (used[y]) continue;
dfs(y);
}
order[x] = id++;
}
struct Union_Find {
int d[SIZE];
void init(int n) {
for (int i = 0; i < (n); ++i) d[i] = i;
}
int find(int x) { return (x != d[x]) ? (d[x] = find(d[x])) : x; }
bool uu(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return 0;
d[x] = y;
return 1;
}
} U;
vector<int> gg[SIZE];
int main() {
int n, m;
scanf("%d%d", &n, &m);
U.init(n);
for (int i = 0; i < (m); ++i) {
int x, y;
scanf("%d%d", &x, &y);
x--;
y--;
U.uu(x, y);
e[x].push_back(y);
}
for (int i = 0; i < (n); ++i) gg[U.find(i)].push_back(i);
int an = 0;
for (int i = 0; i < (n); ++i) {
if (((int)(gg[i]).size())) {
pp.clear();
num = 0;
for (int k = 0; k < (((int)(gg[i]).size())); ++k)
if (!used[gg[i][k]]) dfs(gg[i][k]);
an += num - 1;
bool suc = 1;
for (int i = 0; i < (((int)(pp).size())); ++i) {
if (order[pp[i].first] < order[pp[i].second]) suc = 0;
}
if (!suc) an++;
}
}
printf("%d\n", an);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int Stack[100009], top;
int Index[100009], Lowlink[100009], Onstack[100009];
int idx, components;
vector<int> G[100009];
bool ok;
bool vis[100009];
int have;
vector<int> V[100009];
bool taken[100009];
int comp[100009];
void DFS(int u) {
if (vis[u]) return;
vis[u] = true;
have++;
if (taken[comp[u]]) ok = true;
for (int i = 0; i < V[u].size(); i++) {
if (!vis[V[u][i]]) DFS(V[u][i]);
}
}
vector<int> sc[100009];
void tarjan(int u) {
int v, i, sz = G[u].size();
Index[u] = Lowlink[u] = idx++;
Stack[top++] = u;
Onstack[u] = 1;
for (i = 0; i < sz; i++) {
v = G[u][i];
if (Index[v] == -1) {
tarjan(v);
Lowlink[u] = min(Lowlink[u], Lowlink[v]);
} else if (Onstack[v])
Lowlink[u] = min(Lowlink[u], Index[v]);
}
if (Lowlink[u] == Index[u]) {
components++;
int cnt = 0;
do {
cnt++;
v = Stack[--top];
Onstack[v] = 0;
comp[v] = components;
} while (u != v);
if (cnt > 1) {
taken[components] = true;
}
}
}
int cost[100009];
int tot;
int res;
vector<int> st;
void findSCC(int n) {
components = top = idx = 0;
memset(Index, -1, sizeof Index);
memset(Onstack, 0, sizeof Onstack);
memset(Lowlink, 0x3f, sizeof Lowlink);
for (int i = 0; i < st.size(); i++) {
have = 0;
if (Index[st[i]] == -1) tarjan(st[i]);
}
}
bool is[100009];
int in[100009];
int out[100009];
int main() {
int n, e, i, u, v;
scanf("%d", &n);
scanf("%d", &e);
for (i = 0; i < e; i++) {
scanf("%d %d", &u, &v);
G[u].push_back(v);
V[u].push_back(v);
V[v].push_back(u);
is[u] = is[v] = true;
out[u]++;
in[v]++;
}
for (i = 1; i <= n; i++) {
if (out[i]) {
st.push_back(i);
}
}
findSCC(n);
for (i = 1; i <= n; i++) {
if (is[i] && !vis[i]) {
ok = false;
have = 0;
DFS(i);
if (ok)
res += have;
else
res += (have - 1);
}
}
cout << res << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > v1(100005), v2(100005);
vector<int> v;
int u[100005];
int a[100005];
int r;
void dfs1(int cur) {
u[cur] = 1;
v.push_back(cur);
int i, x;
for (i = 0; i < v1[cur].size(); i++) {
x = v1[cur][i];
if (u[x] == 0) {
dfs1(x);
}
}
for (i = 0; i < v2[cur].size(); i++) {
x = v2[cur][i];
if (u[x] == 0) {
dfs1(x);
}
}
}
void dfs2(int cur) {
if (r == 1) {
return;
}
if (a[cur] == 2) {
return;
}
if (a[cur] == 1) {
r = 1;
return;
}
a[cur] = 1;
int i, x;
for (i = 0; i < v1[cur].size(); i++) {
x = v1[cur][i];
dfs2(x);
}
a[cur] = 2;
}
int i, j, k, n, m, x, y, z, t, res;
int main() {
cin >> n >> m;
for (i = 0; i < m; i++) {
cin >> x >> y;
x--;
y--;
v1[x].push_back(y);
v2[y].push_back(x);
}
for (i = 0; i < n; i++) {
if (u[i] == 0) {
v.clear();
dfs1(i);
r = 0;
for (j = 0; j < v.size(); j++) {
if (a[v[j]] == 0) {
dfs2(v[j]);
}
}
res += v.size();
if (r == 0) {
res--;
}
}
}
cout << res << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 100010;
long long n, m, x, y, res, cycle;
long long cost[maxn];
vector<long long> adj[maxn], alt[maxn];
vector<long long> visited, col;
vector<long long> component;
stack<long long> order;
void dfs1(long long x) {
col[x] = 1;
for (auto i : adj[x])
if (col[i] == 1)
cycle = 1;
else if (col[i] == 0)
dfs1(i);
col[x] = 2;
}
void dfs2(long long x) {
visited[x] = true;
component.push_back(x);
for (auto i : alt[x])
if (!visited[i]) dfs2(i);
}
void solve() {
cin >> n >> m;
visited.resize(n);
for (long long i = 0; i < m; i++) {
cin >> x >> y;
x--;
y--;
adj[x].push_back(y);
alt[y].push_back(x);
alt[x].push_back(y);
}
col.resize(n);
col.assign(n, 0);
visited.assign(n, 0);
for (long long i = 0; i < n; i++) {
if (!visited[i]) {
component.clear();
dfs2(i);
cycle = 0;
for (auto x : component)
if (!col[x]) dfs1(x);
res += (long long)component.size();
if (!cycle) res--;
}
}
cout << res;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long t = 1;
while (t--) {
solve();
}
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 5;
long long n, m, s, grp = 0, check = 0, vertices = 0, ans = 0;
vector<long long> g[N], undirG[N], rg[N], todo;
long long comp[N], sizecomp[N];
bool vis[N], checkSCC[N];
vector<long long> mark[N];
void dfs(long long k) {
vis[k] = 1;
for (auto it : g[k]) {
if (!vis[it]) dfs(it);
}
todo.push_back(k);
}
void dfs2(long long k, long long val) {
comp[k] = val;
sizecomp[val]++;
mark[val].push_back(k);
for (auto it : rg[k]) {
if (comp[it] == -1) dfs2(it, val);
}
}
void sccAddEdge(long long from, long long to) {
g[from].push_back(to);
rg[to].push_back(from);
}
void scc() {
for (long long i = 1; i <= n; i++) comp[i] = -1;
for (long long i = 1; i <= n; i++) {
if (!vis[i]) dfs(i);
}
reverse(todo.begin(), todo.end());
for (auto it : todo) {
if (comp[it] == -1) {
dfs2(it, ++grp);
if (sizecomp[grp] > 1) {
for (auto it : mark[grp]) {
checkSCC[it] = true;
}
}
}
}
}
void newdfs(long long k) {
if (vis[k]) return;
vertices++;
vis[k] = 1;
check |= checkSCC[k];
for (auto it : undirG[k]) newdfs(it);
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
cin >> n >> m;
for (long long i = 1; i <= m; i++) {
long long u, v;
cin >> u >> v;
sccAddEdge(u, v);
undirG[u].push_back(v);
undirG[v].push_back(u);
}
scc();
memset(vis, 0, sizeof(vis));
for (long long i = 1; i <= n; i++) {
if (vis[i]) continue;
check = 0;
vertices = 0;
newdfs(i);
if (check)
ans += vertices;
else
ans += vertices - 1;
}
cout << ans;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const double EPS = -1e8;
const double Pi = acos(-1);
bool inline equ(double a, double b) { return fabs(a - b) < EPS; }
const int MAXN = 100010;
struct DSJ {
int mom[MAXN];
void init(int x) {
for (int i = 1; i <= x; i++) mom[i] = i;
}
int find(int x) { return mom[x] = mom[x] == x ? x : find(mom[x]); }
void merge(int a, int b) { mom[find(a)] = find(b); }
};
int n, m;
vector<int> g[MAXN], rg[MAXN], vs;
bool vis[MAXN];
DSJ dsj;
int id[MAXN];
vector<int> scc[MAXN];
bool ok[MAXN];
int sz[MAXN];
void dfs(int u) {
vis[u] = 1;
for (auto v : g[u])
if (!vis[v]) dfs(v);
vs.push_back(u);
}
void rdfs(int u, int mk) {
vis[u] = 1;
id[u] = mk;
scc[mk].push_back(u);
for (auto v : rg[u])
if (!vis[v]) rdfs(v, mk);
}
int main() {
scanf("%d%d", &n, &m);
dsj.init(n);
for (int i = (1); i <= (m); i++) {
int u, v;
scanf("%d%d", &u, &v);
dsj.merge(u, v);
g[u].push_back(v);
rg[v].push_back(u);
}
for (int i = (1); i <= (n); i++) sz[dsj.find(i)]++;
int cnt = 0;
for (int i = (1); i <= (n); i++)
if (!vis[i]) dfs(i);
reverse((vs).begin(), (vs).end());
fill(vis, vis + MAXN, 0);
for (int u : vs)
if (!vis[u]) {
rdfs(u, ++cnt);
if ((int)(scc[cnt]).size() > 1) ok[dsj.find(u)] = 1;
}
int ans = 0;
for (int i = (1); i <= (n); i++)
if (sz[i] > 0) {
if (ok[i])
ans += sz[i];
else
ans += sz[i] - 1;
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int used[maxn], used2[maxn], exists[maxn], in[maxn];
vector<int> org[maxn], g[maxn];
vector<vector<int> > components;
int cur;
void dfs1(int v) {
if (used[v]) return;
used[v] = 1;
components.back().push_back(v);
for (auto i : g[v]) dfs1(i);
}
void topsort(int v) {
if (used2[v]) return;
used2[v] = 1;
for (auto i : org[v]) topsort(i);
in[v] = cur++;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
org[a].push_back(b);
g[a].push_back(b);
g[b].push_back(a);
exists[a] = exists[b] = 1;
}
for (int i = 1; i <= n; i++) {
if (exists[i] && !used[i]) {
components.push_back(vector<int>());
dfs1(i);
}
}
int ans = 0;
for (auto i : components) {
for (auto j : i) topsort(j);
bool flag = 0;
for (auto j : i) {
for (auto nxt : org[j]) {
if (in[nxt] > in[j]) flag = 1;
}
}
ans += i.size();
if (!flag) ans--;
}
cout << ans << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
/*
5 8
1 2
2 3
3 4
4 1
5 4
5 1
5 2
5 3
7 7
1 2
2 3
4 1
4 3
5 4
6 7
7 6
*/
public class d {
static class Graph
{
ArrayList<Integer>[] adjList;
ArrayList<Integer>[] revAdjList;
int n;
@SuppressWarnings("unchecked")
Graph(int n)
{
this.n = n;
adjList = new ArrayList[n];
revAdjList = new ArrayList[n];
for(int curr = 0; curr < n; ++curr)
{
adjList[curr] = new ArrayList<Integer>();
revAdjList[curr] = new ArrayList<Integer>();
}
}
void addEdge(int v1, int v2)
{
adjList[v1].add(v2);
revAdjList[v2].add(v1);
}
boolean[] visited;
ArrayList<ArrayList<Integer>> components;
int index;
int[] indices;
int[] lowlink;
ArrayDeque<Integer> stack;
ArrayList<ArrayList<Integer>> stronglyConnectedComponents()
{
visited = new boolean[n];
components = new ArrayList<ArrayList<Integer>>();
stack = new ArrayDeque<Integer>();
index = 1;
lowlink = new int[n];
indices = new int[n];
for(int curr = 0; curr < n; ++curr)
{
if(indices[curr] == 0)
{
dfs(curr);
}
}
return components;
}
void dfs(int node)
{
indices[node] = index;
lowlink[node] = index;
++index;
stack.push(node);
visited[node] = true;
for(int next: adjList[node])
{
if(indices[next] == 0)
{
dfs(next);
lowlink[node] = Math.min(lowlink[node], lowlink[next]);
}
else if(visited[next])
{
lowlink[node] = Math.min(lowlink[node], indices[next]);
}
}
if(lowlink[node] == indices[node])
{
ArrayList<Integer> component = new ArrayList<Integer>();
int next;
while(node != (next = stack.pop()))
{
visited[next] = false;
component.add(next);
}
component.add(node);
visited[node] = false;
components.add(component);
}
}
int bfs(int start, boolean[] cycle)
{
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
int count = 1;
visited[start] = true;
q.add(start);
boolean containsCycle = false;
while(!q.isEmpty())
{
int node = q.poll();
containsCycle |= cycle[node];
for(int next: adjList[node])
{
if(!visited[next])
{
visited[next] = true;
q.add(next);
++count;
}
}
for(int next: revAdjList[node])
{
if(!visited[next])
{
visited[next] = true;
q.add(next);
++count;
}
}
}
return count - (containsCycle?0:1);
}
int getRequired()
{
ArrayList<ArrayList<Integer>> scc = stronglyConnectedComponents();
// System.out.println(scc);
boolean[] cycle = new boolean[n];
for(ArrayList<Integer> ar: scc)
{
if(ar.size() > 1)
{
for(int node: ar)
{
cycle[node] = true;
}
}
}
int count = 0;
Arrays.fill(visited, false);
for(int curr = 0; curr < n; ++curr)
{
if(!visited[curr])
{
count += bfs(curr, cycle);
}
}
return count;
}
}
public static void main(String[] args)
{
FastScanner in = new FastScanner();
int n = in.nextInt();
int m = in.nextInt();
Graph g = new Graph(n);
for(int currEdge = 0; currEdge < m; ++currEdge)
{
g.addEdge(in.nextInt()-1, in.nextInt()-1);
}
System.out.println(g.getRequired());
}
static class FastScanner{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner()
{
stream = System.in;
}
int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c)
{
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
boolean isEndline(int c)
{
return c=='\n'||c=='\r'||c==-1;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String next(){
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isSpaceChar(c));
return res.toString();
}
String nextLine(){
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isEndline(c));
return res.toString();
}
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int N, M;
vector<int> G[100005];
vector<int> GG[100005];
vector<int> Area[100005];
int Sort[100005], number, cycle;
int Poz[100005], area;
bool Use[100005];
void Read() {
cin >> N >> M;
for (int i = 1; i <= M; i++) {
int x, y;
cin >> x >> y;
G[x].push_back(y);
GG[x].push_back(y);
GG[y].push_back(x);
}
}
void DFS2(int node) {
Use[node] = 1;
Area[area].push_back(node);
for (int i = 0; i < GG[node].size(); i++) {
int neighb = GG[node][i];
if (Use[neighb] == 0) DFS2(neighb);
}
}
void DFS(int node) {
++number;
Use[node] = 1;
for (int i = 0; i < G[node].size(); i++) {
int neighb = G[node][i];
if (Use[neighb] == 0) {
DFS(neighb);
} else if (Poz[neighb] == 0)
cycle = 1;
}
Sort[++Sort[0]] = node;
Poz[node] = Sort[0];
}
void precalcArea() {
for (int i = 1; i <= N; i++)
if (Use[i] == 0) {
++area;
DFS2(i);
}
memset(Use, 0, sizeof(Use));
}
void Browse() {
int i, result = 0;
for (i = 1; i <= area; i++) {
for (int j = 0; j < Area[i].size(); j++)
if (Use[Area[i][j]] == 0) DFS(Area[i][j]);
result += cycle + Area[i].size() - 1;
number = 0;
Sort[0] = 0;
cycle = 0;
}
cout << result << "\n";
}
int main() {
Read();
precalcArea();
Browse();
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int id[300010], sz[300010], dg[300010];
vector<int> adj[300010], comp[300010];
void ufinit(int n) {
for (int i = 0; i < (n); ++i) id[i] = i, sz[i] = 1;
}
int uffind(int i) {
if (i == id[i]) return i;
return id[i] = uffind(id[i]);
}
void ufunion(int v, int w) {
v = uffind(v);
w = uffind(w);
if (v == w) return;
if (sz[v] > sz[w]) swap(v, w);
id[v] = w;
if (sz[v] == sz[w]) sz[w]++;
}
int main() {
int n, m;
scanf(" %d %d", &n, &m);
ufinit(n);
for (int i = 0; i < (m); ++i) {
int a, b;
scanf(" %d %d", &a, &b);
a--;
b--;
dg[a]++;
adj[b].push_back(a);
ufunion(a, b);
}
for (int i = 0; i < (n); ++i) comp[uffind(i)].push_back(i);
int ans = 0;
for (int i = 0; i < (n); ++i) {
int sz = comp[i].size();
if (!sz) continue;
queue<int> q;
int nvis = 0;
for (int j = 0; j < (sz); ++j) {
int x = comp[i][j];
if (dg[x] == 0) {
q.push(x);
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
nvis++;
for (int j = 0; j < (adj[u].size()); ++j) {
int pu = adj[u][j];
dg[pu]--;
if (dg[pu] == 0) {
q.push(pu);
}
}
}
if (nvis == sz)
ans += sz - 1;
else
ans += sz;
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.*;
import java.util.*;
public class Main {
int[] p;
ArrayList<Integer>[] g;
int[] was;
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
boolean dfs(int x) {
was[x] = 1;
for (int y : g[x]) {
if (was[y] == 1) {
return false;
}
if (was[y] == 0) {
if (!dfs(y)) {
return false;
}
}
}
was[x] = 2;
return true;
}
void solve() {
int n = in.nextInt();
int m = in.nextInt();
p = new int[n + 1];
g = new ArrayList[n + 1];
was = new int[n + 1];
for (int i = 1; i <= n; ++i) {
p[i] = i;
g[i] = new ArrayList<>();
}
for (int i = 0; i < m; ++i) {
int x = in.nextInt();
int y = in.nextInt();
g[x].add(y);
int px = find(x);
int py = find(y);
if (px != py) {
p[px] = py;
}
}
ArrayList<Integer>[] comp = new ArrayList[n + 1];
for (int i = 1; i <= n; ++i) {
comp[i] = new ArrayList<>();
}
for (int i = 1; i <= n; ++i) {
comp[find(i)].add(i);
}
Arrays.fill(was, 0);
int ans = 0;
for (int i = 1; i <= n; ++i) {
if (comp[i].isEmpty()) {
continue;
}
boolean hasCycle = false;
for (int x : comp[i]) {
if (was[x] == 0) {
if (!dfs(x)) {
hasCycle = true;
}
}
}
ans += comp[i].size() - 1;
if (hasCycle) {
ans += 1;
}
}
out.println(ans);
}
void run() {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
InputReader in;
PrintWriter out;
class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
st = null;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] args) {
new Main().run();
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.LinkedHashSet;
import java.util.StringTokenizer;
public class MrKitayutasTechnology {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int N = sc.nextInt();
int M = sc.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; i++){
nodes[i] = new Node(i);
}
for (int i = 0; i < M; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
nodes[a].nexts.add(nodes[b]);
nodes[b].prevs.add(nodes[a]);
}
// for (int i = 1; i <= N; i++) {
// System.out.println("NODE " + i);
// for (Node n : nodes[i].nexts) {
// System.out.println(" --> " + n.index);
// }
// }
// System.out.println("cycle: " + componentHasCycle());
// HashSet<Node> tmp = new HashSet<Node>();
// Node n1 = new Node(10);
// Node n2 = new Node(20);
// n1.nexts.add(n2);
// n2.nexts.add(n1);
// tmp.add(n1);
// tmp.add(n2);
// System.out.println("cycle: " + (toplogicalSort(tmp) == null));
int cnt = 0;
HashSet<Node> visited = new HashSet<Node>();
for (int i = 1; i <= N; i++) {
if (!visited.contains(nodes[i])) {
HashSet<Node> comp = getComponent(nodes[i]);
if (toplogicalSort(comp) == null) {
cnt += comp.size();
} else {
cnt += comp.size() - 1;
}
for (Node n : comp) {
visited.add(n);
}
}
}
System.out.println(cnt);
}
public static HashSet<Node> getComponent(Node seed) {
HashSet<Node> visited = new HashSet<Node>();
LinkedList<Node> q = new LinkedList<Node>();
q.addLast(seed);
while (!q.isEmpty()) {
Node curr = q.removeFirst();
if (visited.contains(curr)) {
continue;
}
visited.add(curr);
for (Node n : curr.nexts) {
q.addLast(n);
}
for (Node n : curr.prevs) {
q.addLast(n);
}
}
return visited;
}
public static boolean hasCycle(Node seed, HashSet<Node> visited, HashSet<Node> completed) {
LinkedList<Node> stack = new LinkedList<Node>();
stack.addFirst(seed);
HashSet<Node> qSet = new HashSet<Node>();
qSet.add(seed);
while (!stack.isEmpty()) {
Node curr = stack.removeFirst();
qSet.remove(curr);
if (completed.contains(curr)) {
continue;
}
if (qSet.contains(curr)) {
return true;
}
visited.add(curr);
for (Node n : curr.nexts) {
stack.addFirst(n);
qSet.add(curr);
}
completed.add(curr);
}
return false;
}
public static boolean componentHasCycle(HashSet<Node> nodes) {
HashSet<Node> visited = new HashSet<Node>();
HashSet<Node> completed = new HashSet<Node>();
for (Node n : nodes) {
if (hasCycle(n, visited, completed)) {
return true;
}
}
return false;
}
// NOTE: destructively modifies the input nodes
public static ArrayList<Node> toplogicalSort(HashSet<Node> nodes) {
ArrayList<Node> lst = new ArrayList<Node>();
HashSet<Node> starts = new HashSet<Node>();
LinkedList<Node> q = new LinkedList<Node>();
for (Node n : nodes) {
if (n.prevs.size() == 0) {
starts.add(n);
q.addLast(n);
}
}
while (!q.isEmpty()) {
Node n = q.removeFirst();
if (!starts.contains(n)) {
continue;
}
lst.add(n);
for (Node m : n.nexts) {
m.prevs.remove(n);
if (m.prevs.size() == 0) {
starts.add(m);
q.addLast(m);
}
}
n.nexts.clear();
}
for (Node n : nodes) {
if ((n.prevs.size() > 0) || (n.nexts.size() > 0)) {
return null;
}
}
return lst;
}
public static class Node {
public int index;
public HashSet<Node> nexts;
public HashSet<Node> prevs;
public Node(int idx) {
this.index = idx;
this.nexts = new HashSet<Node>();
this.prevs = new HashSet<Node>();
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
String str = "";
try { str = br.readLine(); }
catch (IOException e) { e.printStackTrace(); }
return str;
}
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9 + 10, MAX = 2e5 + 1e4, MOD = 1e9 + 7, MAXL = 25;
void OUT(long double o, int x) {
cout << fixed << setprecision(x) << o;
return;
}
long long t[MAX], vis[MAX], mo = 0;
vector<int> adj[MAX], vec, ad[MAX], rev[MAX];
void dfs(int v) {
vis[v] = 1;
for (int u : adj[v])
if (!vis[u]) dfs(u);
vec.push_back(v);
}
void sfd(int v) {
vis[v] = mo;
t[mo]++;
for (int u : rev[v]) {
if (!vis[u])
sfd(u);
else if (vis[u] != mo) {
ad[mo].push_back(vis[u]);
ad[vis[u]].push_back(mo);
}
}
}
pair<long long, long long> dfs2(int v) {
vis[v] = 1;
long long x = 0, y = 0;
if (t[v] == 1)
x++;
else
y++;
for (int u : ad[v])
if (!vis[u]) {
pair<long long, long long> z = dfs2(u);
x += z.first, y += z.second;
}
return {x, y};
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
long long x, y;
cin >> x >> y;
adj[x].push_back(y);
rev[y].push_back(x);
}
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs(i);
reverse(vec.begin(), vec.end());
for (int i = 1; i <= n; i++) vis[i] = 0;
long long x = 0;
for (int u : vec)
if (!vis[u]) {
mo++;
sfd(u);
if (t[mo] != 1) x += t[mo];
}
for (int i = 1; i <= n; i++) vis[i] = 0;
for (int i = 1; i <= n; i++)
if (!vis[i]) {
pair<long long, long long> y = dfs2(i);
x += y.first;
if (y.second == 0) x--;
}
cout << x;
return 0;
}
| CPP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.