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;
const int N = 100 * 1000 + 20;
int n, m, markTopol[N], ans;
bool flag = false, mark[N];
vector<int> adj[N], out[N], ver;
void dfs(int v) {
mark[v] = true;
ver.push_back(v);
for (auto u : adj[v])
if (!mark[u]) dfs(u);
}
void dfs_topol(int v) {
markTopol[v] = 1;
for (auto u : out[v]) {
if (!markTopol[u])
dfs_topol(u);
else if (markTopol[u] == 1)
flag = true;
if (flag) return;
}
markTopol[v] = 2;
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int v, u;
cin >> v >> u;
adj[--v].push_back(--u);
adj[u].push_back(v);
out[v].push_back(u);
}
for (int i = 0; i < n; i++) {
if (!mark[i]) {
dfs(i);
for (auto j : ver)
if (!markTopol[j]) dfs_topol(j);
ans += ver.size() - 1 + flag;
ver.clear();
flag = false;
}
}
return cout << ans << endl, 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 | def main():
n, m = map(int, input().split())
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())
a -= 1
b -= 1
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, f in enumerate(dest) if not f and ab[a]]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b] and ab[a]:
pool.append(b)
for a, f in enumerate(dest):
avail[getroot(a)] &= not f
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 | #include <bits/stdc++.h>
using namespace std;
const long long int INF = (1LL << 58);
const bool DEBUG = 0;
const int NODES_LIMIT = 100005;
int nodes, edges;
std::vector<int> adj[2][NODES_LIMIT];
bool vis[NODES_LIMIT];
int color[NODES_LIMIT], globalColor = 1;
int componentSize[NODES_LIMIT];
bool hasCycle[NODES_LIMIT];
int doColor(int node, int thisColor) {
vis[node] = 1;
color[node] = thisColor;
int i, limit = adj[0][node].size();
int ret = 0;
for (i = 0; i < limit; i++) {
int v = adj[0][node][i];
if (!vis[v]) ret += doColor(v, thisColor);
}
return ret + 1;
}
bool recStack[NODES_LIMIT];
bool detectCycle(int node) {
int limit = adj[1][node].size();
vis[node] = 1;
recStack[node] = 1;
for (int i = 0; i < limit; i++) {
int v = adj[1][node][i];
if (!vis[v]) {
if (detectCycle(v)) return 1;
} else if (recStack[v] == 1)
return 1;
}
recStack[node] = 0;
return 0;
}
int main() {
int i, j;
scanf("%d", &nodes);
scanf("%d", &edges);
for (i = 0; i < edges; i++) {
int x, y;
scanf("%d", &x);
scanf("%d", &y);
x--;
y--;
adj[0][x].push_back(y);
adj[0][y].push_back(x);
adj[1][x].push_back(y);
}
for (i = 0; i < nodes; i++) {
if (!vis[i]) {
componentSize[globalColor] = doColor(i, globalColor);
globalColor++;
}
}
memset(vis, 0, sizeof(vis));
for (i = 0; i < nodes; i++)
if (!vis[i]) hasCycle[color[i]] |= detectCycle(i);
int ans = 0;
for (i = 1; i < globalColor; i++)
ans += (componentSize[i] - 1) + (int)hasCycle[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 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* @author Pavel Mavrin
*/
public class B {
private void solve() throws IOException {
int n = nextInt();
int m = nextInt();
init(n, m);
for (int i = 0; i < m; i++) {
addEdge(nextInt() - 1, nextInt() - 1);
}
int res = 0;
for (int i = 0; i < n; i++) {
if (!z[i]) {
pn = 0;
dfs1(i);
res += pn;
boolean ok = true;
for (int j = 0; j < pn; j++) {
if (dfs2(p[j])) {
ok = false;
}
}
if (ok) {
res--;
}
}
}
out.println(res);
}
void init(int n, int m) {
m *= 2;
this.n = n;
this.m = m;
last = 0;
head = new int[n];
nx = new int[m];
dst = new int[m];
src = new int[m];
cp = new int[m];
Arrays.fill(head, -1);
z = new boolean[n];
z2 = new int[n];
p = new int[n];
}
void addEdge(int x, int y) {
nx[last] = head[x];
src[last] = x;
dst[last] = y;
cp[last] = 1;
head[x] = last;
last++;
nx[last] = head[y];
src[last] = y;
dst[last] = x;
cp[last] = 0;
head[y] = last;
last++;
}
private void dfs1(int x) {
if (z[x]) return;
p[pn++] = x;
z[x] = true;
int j = head[x];
while (j >= 0) {
int y = dst[j];
dfs1(y);
j = nx[j];
}
}
private boolean dfs2(int x) {
if (z2[x] == 1) return true;
if (z2[x] == 2) return false;
z2[x] = 1;
int j = head[x];
while (j >= 0) {
int y = dst[j];
if (cp[j] == 1) {
if (dfs2(y)) return true;
}
j = nx[j];
}
z2[x] = 2;
return false;
}
private static final long INF = Long.MAX_VALUE;
int n, m;
int[] head;
int[] nx;
int[] src;
int[] dst;
int[] cp;
boolean[] z;
int[] z2;
int last;
int[] p;
int pn;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter out = new PrintWriter(System.out);
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static void main(String[] args) throws IOException {
new B().run();
}
private void run() throws IOException {
solve();
out.close();
}
}
| 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 = 1000 * 100 + 5;
const long long inf = 9223372036854775807;
int n, m, mark[maxn], comp[maxn], ans, cnt = 1, sz[maxn];
pair<int, int> e[maxn];
vector<int> adj[maxn], g[maxn], radj[maxn], t;
bool dfs2(int v) {
bool b = true;
if (sz[v] != 1) b = false;
mark[v] = 1;
for (auto u : g[v]) {
if (mark[u] == 0) {
b = b & dfs2(u);
}
}
return b;
}
void sfd(int v, int c) {
comp[v] = c;
sz[c]++;
for (auto u : radj[v]) {
if (comp[u] == 0) {
sfd(u, c);
}
}
}
void dfs(int v) {
mark[v] = 1;
for (auto u : adj[v]) {
if (mark[u] == 0) {
dfs(u);
}
}
t.push_back(v);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
radj[v].push_back(u);
e[i] = {u, v};
}
for (int i = 1; i <= n; i++) {
if (mark[i] == 0) {
dfs(i);
}
}
reverse(t.begin(), t.end());
for (int i = 0; i < t.size(); i++) {
if (comp[t[i]] == 0) {
sfd(t[i], cnt++);
}
}
for (int i = 1; i <= m; i++) {
int u = e[i].first, v = e[i].second;
u = comp[u], v = comp[v];
if (u != v) {
g[u].push_back(v);
g[v].push_back(u);
}
}
memset(mark, 0, sizeof mark);
ans = n;
for (int i = 1; i < cnt; i++) {
if (mark[i] == 0) {
if (dfs2(i)) {
ans--;
}
}
}
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>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
inline void base() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed << setprecision(6);
}
const int N = 1e5;
vector<int> adj[N + 5];
int low[N + 5], num[N + 5], scc[N + 5], sccid = 0, id = 0;
bool inStack[N + 5];
int sccsize[N + 5];
stack<int> stk;
int ans = 0;
void tarjan(int x) {
if (num[x] != -1) return;
num[x] = low[x] = ++id;
stk.push(x);
inStack[x] = true;
for (int i = 0; i < adj[x].size(); ++i) {
int nx = adj[x][i];
if (num[nx] == -1) {
tarjan(nx);
low[x] = min(low[nx], low[x]);
} else if (inStack[nx]) {
low[x] = min(low[nx], low[x]);
}
}
if (low[x] == num[x]) {
sccid++;
sccsize[sccid] = 1;
while (stk.top() != x) {
scc[stk.top()] = sccid;
inStack[stk.top()] = false;
stk.pop();
sccsize[sccid]++;
}
scc[x] = sccid;
inStack[x] = false;
stk.pop();
}
}
vector<int> comp[N + 5];
bool vis[N + 5];
bool vis2[N + 5];
int dfs(int x) {
if (vis[x]) return 0;
vis[x] = 1;
int res = sccsize[x];
for (int i = 0; i < comp[x].size(); ++i) {
res += dfs(comp[x][i]);
}
return res;
}
bool cycleExist(int x) {
if (vis2[x]) return false;
vis2[x] = true;
if (sccsize[x] > 1) return true;
for (int i = 0; i < comp[x].size(); ++i) {
if (cycleExist(comp[x][i])) return true;
}
return false;
}
int main() {
base();
memset(num, -1, sizeof num);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
}
ans = 0;
for (int i = 1; i <= n; ++i) {
tarjan(i);
}
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < adj[i].size(); ++j) {
int nx = adj[i][j];
if (scc[i] == scc[nx]) continue;
comp[scc[i]].push_back(scc[nx]);
comp[scc[nx]].push_back(scc[i]);
}
}
for (int i = 1; i <= sccid; ++i) {
int tmp = dfs(i);
if (tmp > 0) {
bool tmp2 = cycleExist(i);
ans += tmp - (!tmp2);
}
}
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 int MAXN = 100 * 1000 + 14;
vector<int> uadj[MAXN], adj[MAXN], vcomp;
bool cycle;
int visited[MAXN], vvisited[MAXN];
void uDfs(int v) {
visited[v] = 1;
vcomp.push_back(v);
for (auto u : uadj[v]) {
if (visited[u] == 0) uDfs(u);
}
}
void dfs(int v) {
vvisited[v] = 1;
for (auto u : adj[v]) {
if (vvisited[u] == 0)
dfs(u);
else if (vvisited[u] == 1)
cycle = true;
}
vvisited[v] = 2;
}
int main() {
int n, m;
cin >> n >> m;
while (m--) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
uadj[a].push_back(b);
uadj[b].push_back(a);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (visited[i] == 0) {
uDfs(i);
for (auto u : vcomp) {
if (vvisited[u] == 0) dfs(u);
}
ans += vcomp.size() - (cycle ^ 1);
cycle = false;
vcomp.clear();
}
}
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> g[100100], rg[100100], gg[100100], l[100100];
vector<int> vs;
int pos[100100];
set<int> occur;
bool vis[100100];
int cnt[100100];
int n, m, num;
void dfs(int v) {
vis[v] = 1;
for (int i = 0; i < g[v].size(); i++)
if (!vis[g[v][i]]) dfs(g[v][i]);
vs.push_back(v);
}
void rdfs(int v, int id) {
vis[v] = 1;
cnt[id]++;
pos[v] = id;
for (int i = 0; i < rg[v].size(); i++)
if (!vis[rg[v][i]]) rdfs(rg[v][i], id);
}
void dfs2(int v, int id) {
vis[v] = 1;
l[id].push_back(v);
for (int i = 0; i < gg[v].size(); i++)
if (!vis[gg[v][i]]) dfs2(gg[v][i], id);
}
void scc() {
memset(vis, false, sizeof(vis));
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs(i);
memset(vis, false, sizeof(vis));
for (int i = vs.size() - 1; i >= 0; i--)
if (!vis[vs[i]]) rdfs(vs[i], ++num);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
g[x].push_back(y);
rg[y].push_back(x);
gg[x].push_back(y);
gg[y].push_back(x);
}
scc();
memset(vis, 0, sizeof(vis));
int c = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) dfs2(i, ++c);
}
int ans = n;
for (int i = 1; i <= c; i++) {
int f = 1;
for (int j = 0; j < l[i].size(); j++) {
int x = l[i][j];
if (cnt[pos[x]] > 1) f = 0;
}
ans -= f;
}
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_ = 100500;
int N, M;
vector<int> gph[N_], rev[N_], bth[N_];
int outdg[N_], indg[N_];
bool visited[N_];
vector<int> ord;
void dfs(int u) {
visited[u] = true;
for (int i = 0; i < gph[u].size(); i++) {
int v = gph[u][i];
if (!visited[v]) dfs(v);
}
ord.push_back(u);
}
queue<int> que;
int grp[N_], gn;
int c1[N_], c2[N_];
void dfs2(int u) {
visited[u] = true;
++c1[gn];
grp[u] = gn;
for (int i = 0; i < bth[u].size(); i++) {
int v = bth[u][i];
if (!visited[v]) dfs2(v);
}
}
int cnt3;
void dfs3(int u) {
visited[u] = true;
++cnt3;
for (int i = 0; i < rev[u].size(); i++) {
int v = rev[u][i];
if (!visited[v]) dfs3(v);
}
}
int main() {
scanf("%d%d", &N, &M);
for (int e = 1; e <= M; e++) {
int u, v;
scanf("%d%d", &u, &v);
gph[u].push_back(v);
rev[v].push_back(u);
bth[u].push_back(v);
bth[v].push_back(u);
++outdg[u];
++indg[v];
}
memset(visited, 0, sizeof visited);
for (int i = 1; i <= N; i++)
if (!visited[i]) dfs(i);
memset(visited, 0, sizeof visited);
for (int i = 1; i <= N; i++)
if (!visited[i]) {
++gn;
dfs2(i);
}
memset(visited, 0, sizeof visited);
for (int i = ord.size(); i--;) {
int u = ord[i];
if (!visited[u]) {
cnt3 = 0;
dfs3(u);
if (cnt3 >= 2) c2[grp[u]] += 1;
}
}
int ans = 0;
for (int g = 1; g <= gn; g++) {
c2[g] += c1[g] - 1;
ans += min(c1[g], c2[g]);
}
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>
int N, M;
std::vector<int> G[100001];
int pre[100001], dfs_clock, scc[100001], sccno;
int S[100001], top;
int fa[100001];
int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
int cnt[100001];
int dfs(int u) {
int lowu = pre[u] = ++dfs_clock;
S[top++] = u;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (!pre[v]) {
lowu = std::min(lowu, dfs(v));
} else if (!scc[v]) {
lowu = std::min(lowu, pre[v]);
}
}
if (lowu == pre[u]) {
sccno++;
int t = 0;
for (int v = -1; v != u;) {
v = S[--top];
scc[v] = sccno;
t++;
}
if (t > 1) cnt[find(u)] = 1;
}
return lowu;
}
int main() {
int answer = 0;
scanf("%d%d", &N, &M);
for (int i = 0; i < N; i++) fa[i] = i;
for (int i = 0; i < M; i++) {
int u, v;
scanf("%d%d", &u, &v);
u--, v--;
if (find(u) != find(v)) fa[find(u)] = find(v), answer++;
G[u].push_back(v);
}
for (int i = 0; i < N; i++)
if (!pre[i]) {
dfs(i);
}
for (int i = 0; i < N; i++) answer += cnt[i];
printf("%d\n", answer);
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.HashSet;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
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;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
static TaskD.Vertex[] graph;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt();
graph = new TaskD.Vertex[n + 1];
for (int i = 1; i <= n; i++) graph[i] = new TaskD.Vertex(i);
for (int i = 1; i <= m; i++) {
TaskD.Vertex u = graph[in.nextInt()], v = graph[in.nextInt()];
u.adjOriented.add(v);
u.adjNOriented.add(v);
v.adjNOriented.add(u);
}
int cc = 0;
for (int i = 1; i <= n; i++) {
if (!graph[i].visitedNOriented) TaskD.Vertex.ccCount.put(cc, graph[i].dfsNOriented(cc++));
}
int answer = 0;
HashSet<Integer> ccVisited = new HashSet<>();
for (int i = 1; i <= n; i++) {
if (!graph[i].visitedOriented && !ccVisited.contains(graph[i].cc)) {
if (graph[i].isCyclic()) {
ccVisited.add(graph[i].cc);
answer += TaskD.Vertex.ccCount.get(graph[i].cc);
}
}
}
for (int i = 0; i < cc; i++) {
if (!ccVisited.contains(i)) answer += TaskD.Vertex.ccCount.get(i) - 1;
}
out.println(answer);
}
static class Vertex {
int key;
ArrayList<TaskD.Vertex> adjOriented = new ArrayList<>();
ArrayList<TaskD.Vertex> adjNOriented = new ArrayList<>();
boolean visitedOriented;
boolean visitedNOriented;
boolean visitedOrientedStack;
int root;
int cc;
static HashMap<Integer, Integer> ccCount = new HashMap<>();
Vertex(int key) {
this.root = this.key = key;
}
int dfsNOriented(int cc) {
visitedNOriented = true;
this.cc = cc;
int sum = 1;
for (TaskD.Vertex v : adjNOriented) {
if (!v.visitedNOriented) sum += v.dfsNOriented(cc);
}
return sum;
}
boolean isCyclic() {
visitedOriented = visitedOrientedStack = true;
for (TaskD.Vertex v : adjOriented) {
if (!v.visitedOriented && v.isCyclic()) return true;
else if (v.visitedOrientedStack) return true;
}
return visitedOrientedStack = false;
}
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(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.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 + a[i])) {
used.add(b[i] * 1000000L + a[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 = 100005;
struct sx {
int from, to, last;
};
struct sl {
sx line[N], fl[2 * N];
int last[N], color[N], sta[N], top, num, fnum, dfn[N], low[N], tot, colornum,
fla[N], pointnum[N];
bool c[N], cc[N];
void add(int x, int y) {
line[++num].to = y;
line[num].from = x;
line[num].last = last[x];
last[x] = num;
}
void fadd(int x, int y) {
fl[++fnum].to = y;
fl[fnum].last = fla[x];
fla[x] = fnum;
}
void dfs(int l) {
c[l] = cc[l] = true;
sta[++top] = l;
dfn[l] = low[l] = ++tot;
for (int j = last[l]; j > 0; j = line[j].last) {
if (!c[line[j].to]) {
dfs(line[j].to);
low[l] = min(low[l], low[line[j].to]);
} else if (cc[line[j].to])
low[l] = min(low[l], dfn[line[j].to]);
}
if (low[l] == dfn[l]) {
++colornum;
while (sta[top] != l) {
color[sta[top]] = colornum;
++pointnum[colornum];
cc[sta[top]] = false;
--top;
}
color[l] = colornum;
++pointnum[colornum];
cc[sta[top]] = false;
--top;
}
}
void tarjan(int n) {
tot = 0;
for (int i = 1; i <= n; ++i)
if (!c[i]) dfs(i);
}
void addfl() {
for (int i = 1; i <= num; ++i)
if (color[line[i].from] != color[line[i].to]) {
fadd(color[line[i].from], color[line[i].to]);
fadd(color[line[i].to], color[line[i].from]);
}
}
} Tarjan;
int ans, n, m, z, x, y;
bool c[N];
int DFS(int l) {
int ans = 0;
c[l] = true;
for (int j = Tarjan.fla[l]; j > 0; j = Tarjan.fl[j].last)
if (!c[Tarjan.fl[j].to]) ans += DFS(Tarjan.fl[j].to);
if (Tarjan.pointnum[l] > 1) ++ans;
return ans;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; ++i) {
scanf("%d%d", &x, &y);
Tarjan.add(x, y);
}
Tarjan.tarjan(n);
Tarjan.addfl();
for (int i = 1; i <= Tarjan.colornum; ++i)
if (Tarjan.pointnum[i] > 1) ans += Tarjan.pointnum[i];
ans += Tarjan.colornum;
for (int i = 1; i <= Tarjan.colornum; ++i)
if (c[i] == false) {
z = DFS(i);
if (z > 0)
ans -= z;
else
--ans;
}
printf("%d", 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;
int n, m;
vector<int> g[1000000];
vector<int> gdir[1000000];
int aridadin[1000000];
int visto[1000000];
void genera(int u, int &numnod, queue<int> &q) {
if (visto[u]) return;
visto[u] = 1;
numnod++;
vector<int> &ar = g[u];
if (aridadin[u] == 0) q.push(u);
for (int i = 0; i < int(ar.size()); i++) {
int v = ar[i];
genera(v, numnod, q);
}
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
gdir[u].push_back(v);
aridadin[v]++;
}
int sol = 0;
for (int i = 1; i <= n; i++) {
int u = i;
if (not visto[u]) {
int numnod = 0;
queue<int> q;
genera(u, numnod, q);
int amount = 0;
while (not q.empty()) {
u = q.front();
q.pop();
amount++;
vector<int> &ar = gdir[u];
for (int i = 0; i < int(ar.size()); i++) {
int v = ar[i];
aridadin[v]--;
if (aridadin[v] == 0) q.push(v);
}
}
if (amount == numnod)
sol += numnod - 1;
else
sol += numnod;
}
}
cout << sol << 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 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main implements Runnable {
private static final String inputFilePath = "";
List<List<Integer>> adj = null;
List<List<Integer>> radj = null;
List<List<Integer>> sccAdj = null;
int[] fa = null;
int[] treeSize = null;
int[] sccSize = null;
boolean[] visit = null;
Stack<Integer> stack = new Stack<Integer>();
private void solve(QuickScanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
adj = new ArrayList<List<Integer>>();
radj = new ArrayList<List<Integer>>();
sccAdj = new ArrayList<List<Integer>>();
for (int i = 0; i <= n; i++) {
adj.add(new ArrayList<Integer>());
radj.add(new ArrayList<Integer>());
sccAdj.add(new ArrayList<Integer>());
}
fa = new int[n + 1];
visit = new boolean[n + 1];
for (int i = 0; i < m; i++) {
int f = in.nextInt();
int t = in.nextInt();
adj.get(f).add(t);
radj.get(t).add(f);
}
for (int i = 1; i <= n; i++) {
if (!visit[i]) {
dfs1(i);
}
}
Arrays.fill(visit, false);
treeSize = new int[n + 1];
sccSize = new int[n + 1];
int sccNode = 0;
while (!stack.empty()) {
int now = stack.pop();
if (!visit[now]) {
sccNode++;
dfs2(now, sccNode);
}
}
for (int i = 1; i <= n; i++) {
for (int j : adj.get(i)) {
sccAdj.get(fa[i]).add(fa[j]);
sccAdj.get(fa[j]).add(fa[i]);
}
}
Arrays.fill(visit, false);
int ans = 0;
for (int i = 1; i <= sccNode; i++) {
if (!visit[i]) {
boolean check = dfs3(i, i);
if (check) {
ans += treeSize[i];
} else {
ans += treeSize[i] - 1;
}
}
}
out.println(ans);
}
private boolean dfs3(int now, int id) {
if (visit[now]) {
return false;
}
visit[now] = true;
treeSize[id] += sccSize[now];
boolean ret = sccSize[now] > 1;
for (int next : sccAdj.get(now)) {
ret |= dfs3(next, id);
}
return ret;
}
private void dfs2(int now, int id) {
if (visit[now]) {
return;
}
visit[now] = true;
fa[now] = id;
sccSize[id]++;
for (int next : radj.get(now)) {
dfs2(next, id);
}
}
private void dfs1(int now) {
if (visit[now]) {
return;
}
visit[now] = true;
for (int next : adj.get(now)) {
dfs1(next);
}
stack.push(now);
}
// Tedious code.
public Main() {}
private class QuickScanner {
private BufferedReader bufferedReader = null;
private StringTokenizer stringTokenizer = null;
private String nextHolder = null;
QuickScanner(Reader reader) {
bufferedReader = new BufferedReader(reader);
}
boolean hasNext() {
// Try to get next and put it into nextHolder.
if (nextHolder == null) {
nextHolder = next();
}
return nextHolder != null;
}
String next() {
// If called hasNext before, should return string in nextHolder.
if (nextHolder != null) {
String next = nextHolder;
nextHolder = null;
return next;
}
try {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
String newLine = bufferedReader.readLine();
if (newLine != null) {
stringTokenizer = new StringTokenizer(newLine);
} else {
return null;
}
}
return stringTokenizer.nextToken();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
int nextInt() {
return Integer.parseInt(next());
}
int nextInt(int radix) {
return Integer.parseInt(next(), radix);
}
long nextLong() {
return Long.parseLong(next());
}
long nextLong(int radix) {
return Long.parseLong(next(), radix);
}
double nextDouble() {
return Double.parseDouble(next());
}
BigInteger nextBigInteger() {
return new BigInteger(next());
}
BigInteger nextBigInteger(int radix) {
return new BigInteger(next(), radix);
}
BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
private static long currentTimeInMiiliSeconds() {
return System.currentTimeMillis();
}
private static void debug(Object... objects) {
System.err.println(Arrays.deepToString(objects));
}
private static void checkCondition(boolean cond) {
if (!cond) {
throw new AssertionError();
}
}
private static void checkCondition(boolean cond, String errorMessage) {
if (!cond) {
throw new AssertionError(errorMessage);
}
}
@Override
public void run() {
PrintWriter out = new PrintWriter(System.out);
try {
Reader reader = null;
if (inputFilePath.isEmpty()) {
reader = new InputStreamReader(System.in);
} else {
reader = new FileReader(inputFilePath);
}
QuickScanner in = new QuickScanner(reader);
solve(in, out);
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// To make sure PrintWriter will always flush to stdout.
out.flush();
}
}
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 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
vector<vector<int> > v, g, comp(1);
char u[N];
int T = 0;
bool CYCLE;
void dfs0(int st) {
u[st] = 1;
comp[T].push_back(st);
for (int i = 0; i < g[st].size(); ++i) {
int to = g[st][i];
if (!u[to]) dfs0(to);
}
}
void dfs(int st) {
u[st] = 1;
for (int i = 0; i < v[st].size(); ++i) {
int to = v[st][i];
if (u[to] == 0)
dfs(to);
else if (u[to] == 1)
CYCLE = true;
}
u[st] = 2;
}
int main() {
int n, m;
cin >> n >> m;
v.resize(n);
g.resize(n);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
--a;
--b;
v[a].push_back(b);
g[a].push_back(b);
g[b].push_back(a);
}
for (int i = 0; i < n; ++i)
if (!u[i]) {
dfs0(i);
++T;
comp.resize(comp.size() + 1);
}
memset(u, 0, sizeof(u));
int res = n - T;
for (int i = 0; i < T; ++i) {
CYCLE = 0;
for (int j = 0; j < comp[i].size(); ++j)
if (!u[comp[i][j]]) dfs(comp[i][j]);
res += CYCLE;
}
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 max_n = 100000;
int n;
vector<int> neigh[max_n];
int val[max_n];
int c;
int s[max_n], s_ed;
int b[2 * max_n], b_ed;
void run_dfs(int v) {
s[++s_ed] = v;
val[v] = s_ed;
b[++b_ed] = val[v];
for (int j = 0; j < int(neigh[v].size()); j++) {
int w = neigh[v][j];
if (val[w] == -1)
run_dfs(w);
else
while (val[w] < b[b_ed]) b_ed--;
}
if (val[v] == b[b_ed]) {
b_ed--;
c++;
while (val[v] <= s_ed) val[s[s_ed--]] = c;
}
}
void strong() {
s_ed = b_ed = -1;
for (int v = 0; v < n; v++) val[v] = -1;
c = n - 1;
for (int v = 0; v < n; v++)
if (val[v] == -1) run_dfs(v);
for (int v = 0; v < n; v++)
if (val[v] != -1) val[v] -= n;
}
int rsize[max_n];
vector<int> rneigh[max_n];
bool rvis[max_n];
void rdfs(int v, int &tot_size, bool &over) {
if (!rvis[v]) {
rvis[v] = true;
tot_size += rsize[v];
if (rsize[v] > 1) over = true;
for (int j = 0; j < int(rneigh[v].size()); j++)
rdfs(rneigh[v][j], tot_size, over);
}
}
int main() {
int m;
scanf("%d %d", &n, &m);
while (m--) {
int u, v;
scanf("%d %d", &u, &v);
u--;
v--;
neigh[u].push_back(v);
}
strong();
for (int v = 0; v < n; v++) {
rsize[val[v]]++;
for (int j = 0; j < int(neigh[v].size()); j++) {
int a = val[v];
int b = val[neigh[v][j]];
rneigh[a].push_back(b);
rneigh[b].push_back(a);
}
}
int ans = 0;
for (int v = n - 1; v >= 0; v--)
if (!rvis[v] && rsize[v] > 0) {
int tot_size = 0;
bool over = false;
rdfs(v, tot_size, over);
ans += tot_size - 1 + int(over);
}
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 MAXN = 100005;
const int MAXE = 200005;
struct Edge {
int v, n;
Edge() {}
Edge(int v, int n) : v(v), n(n) {}
};
Edge E[MAXE];
int H[MAXN], N[MAXN], cntE;
int Q[MAXN], head, tail;
int in[MAXN];
int n, m;
int cnt;
int p[MAXN], num[MAXN];
void clear() {
cntE = 0;
memset(H, -1, sizeof H);
memset(N, -1, sizeof N);
memset(in, 0, sizeof in);
memset(num, 0, sizeof num);
for (int i = (0); i < (MAXN); ++i) p[i] = i;
}
void addedge(int u, int v, int H[]) {
E[cntE] = Edge(v, H[u]);
H[u] = cntE++;
}
int find(int x) { return p[x] == x ? x : (p[x] = find(p[x])); }
int topo(int n) {
int cnt = 0;
while (head != tail) {
int u = Q[head++];
++cnt;
for (int i = H[u]; ~i; i = E[i].n) {
int v = E[i].v;
if (0 == --in[v]) Q[tail++] = v;
}
}
return cnt == n;
}
void solve() {
int ans = 0;
int u, v;
clear();
for (int i = (0); i < (m); ++i) {
scanf("%d%d", &u, &v);
addedge(u, v, H);
p[find(u)] = find(v);
++in[v];
}
for (int i = (1); i <= (n); ++i) {
addedge(find(i), i, N);
++num[find(i)];
}
for (int i = (1); i <= (n); ++i)
if (num[i]) {
u = i;
ans += num[i];
head = tail = 0;
for (int j = N[u]; ~j; j = E[j].n) {
v = E[j].v;
if (!in[v]) Q[tail++] = v;
}
ans -= topo(num[i]);
}
printf("%d\n", ans);
}
int main() {
while (~scanf("%d%d", &n, &m)) 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;
vector<int> mg[100005], um[100005];
int marka[100005], pos[100005], uk, niz[100005], f;
void dfs(int cvor) {
int i, x;
pos[cvor] = 1;
uk++;
niz[uk] = cvor;
for (i = 0; i < mg[cvor].size(); i++) {
x = mg[cvor][i];
if (pos[x] == 0) dfs(x);
}
}
void nciklus(int cvor) {
int i, x;
marka[cvor] = 1;
for (i = 0; i < um[cvor].size(); i++) {
x = um[cvor][i];
if (marka[x] == 1) {
f = 1;
} else if (marka[x] == 0)
nciklus(x);
}
marka[cvor] = 2;
}
int main() {
int n, m, i, j, k, a, b, t, res = 0, x;
cin >> n >> m;
for (i = 1; i <= m; i++) {
cin >> a >> b;
mg[a].push_back(b);
mg[b].push_back(a);
um[a].push_back(b);
}
for (i = 1; i <= n; i++) {
if (pos[i] == 0) {
uk = 0;
dfs(i);
f = 0;
for (j = 1; j <= uk; j++) {
x = niz[j];
if (marka[x] == 0) nciklus(x);
}
if (f)
res = res + uk;
else
res = res + uk - 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;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int N, M;
cin >> N >> M;
vector<vector<int> > G(N);
vector<vector<int> > Gr(N);
vector<int> D(N, 0);
for (int i = 0; i < M; i++) {
int a, b;
cin >> a >> b;
G[--a].push_back(--b);
G[b].push_back(a);
Gr[a].push_back(b);
D[b]++;
}
queue<int> q;
vector<bool> vis(N, false);
int ans = 0;
for (int i = 0; i < N; i++)
if (!vis[i]) {
vis[i] = true;
vector<int> v(1, i);
q.push(i);
while (!q.empty()) {
for (auto it = G[q.front()].begin(); it != G[q.front()].end(); it++)
if (!vis[*it]) {
vis[*it] = true;
v.push_back(*it);
q.push(*it);
}
q.pop();
}
for (auto it = v.begin(); it != v.end(); it++)
if (D[*it] == 0) q.push(*it);
while (!q.empty()) {
for (auto it = Gr[q.front()].begin(); it != Gr[q.front()].end(); it++) {
D[*it]--;
if (D[*it] == 0) q.push(*it);
}
q.pop();
}
bool isC = false;
for (auto it = v.begin(); it != v.end(); it++)
if (D[*it] != 0) isC = true;
ans += (!isC) ? ((int)v.size() - 1) : v.size();
}
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> G[100005];
vector<int> rG[100005];
vector<int> vec;
bool used[100005], done[100005], onstack[100005];
int n, m;
void add_edge(int from, int to) {
G[from].push_back(to);
rG[to].push_back(from);
}
int wcc(int v) {
int ret = 1;
used[v] = true;
vec.push_back(v);
for (size_t i = 0; i < G[v].size(); i++) {
if (!used[G[v][i]]) {
ret += wcc(G[v][i]);
}
}
for (size_t i = 0; i < rG[v].size(); i++) {
if (!used[rG[v][i]]) {
ret += wcc(rG[v][i]);
}
}
return ret;
}
bool dfs(int u) {
onstack[u] = true;
done[u] = true;
for (size_t i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (onstack[v] || (!done[v] && dfs(v))) {
onstack[u] = false;
return true;
}
}
onstack[u] = false;
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin >> n >> m;
int u, v;
for (int i = 0; i < m; i++) {
cin >> u >> v;
add_edge(u, v);
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (!used[i]) {
vec.clear();
cnt += (wcc(i) - 1);
for (size_t j = 0; j < vec.size(); j++) {
if (!done[vec[j]] && dfs(vec[j])) {
cnt++;
break;
}
}
}
}
cout << cnt << 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;
void RI(int& x) {
x = 0;
char c = getchar();
while (!(c >= '0' && c <= '9' || c == '-')) c = getchar();
bool flag = 1;
if (c == '-') {
flag = 0;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
if (!flag) x = -x;
}
void RII(int& x, int& y) { RI(x), RI(y); }
void RIII(int& x, int& y, int& z) { RI(x), RI(y), RI(z); }
void RC(char& c) {
c = getchar();
while (c == ' ' || c == '\n') c = getchar();
}
char RC() {
char c = getchar();
while (c == ' ' || c == '\n') c = getchar();
return c;
}
const long long mod = 1e9 + 7;
const long long LINF = 1e18;
const int INF = 1e9;
const double EPS = 1e-8;
const int Maxn = 300000, Maxm = 300000;
int n, m, u, v, i, ans, tot, e0, num, t, s[Maxn], dfn[Maxn], low[Maxn],
val[Maxn], top[Maxn], col[Maxn], e[Maxm * 3][3];
bool bo[Maxn], vis[Maxn], instack[Maxn];
void build(int u, int v) {
e[++e0][0] = v;
e[e0][1] = top[u];
top[u] = e0;
}
void dfs(int u) {
dfn[u] = low[u] = t++;
vis[u] = instack[u] = 1;
s[++s[0]] = u;
int p = top[u];
while (p) {
int v = e[p][0];
if (!vis[v])
dfs(v), low[u] = min(low[u], low[v]);
else if (instack[v])
low[u] = min(low[u], dfn[v]);
p = e[p][1];
}
if (dfn[u] == low[u]) {
num++;
do {
val[num]++;
p = s[s[0]--];
col[p] = num;
instack[p] = 0;
} while (p != u);
}
}
map<pair<int, int>, int> ck;
int cnt[Maxn], Yes[Maxn];
struct edge {
int v, nt;
} e2[Maxm];
int e02 = 0, top2[Maxn];
void build2(int u, int v) {
e2[++e02].v = v;
e2[e02].nt = top2[u];
top2[u] = e02;
}
int f[Maxn], sum[Maxn];
int gf(int x) {
if (x == f[x]) return f[x];
return f[x] = gf(f[x]);
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
Yes[u] = Yes[v] = 1;
build(u, v);
}
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs(i);
for (int i = 1; i <= n; i++)
if (Yes[i]) cnt[col[i]]++;
for (int i = 1; i <= num; i++) f[i] = i;
for (int u = 1; u <= n; u++) {
for (int p = top[u]; p; p = e[p][1]) {
int v = e[p][0];
int x = col[u], y = col[v];
if (x != y) {
x = gf(x);
y = gf(y);
f[x] = y;
}
}
}
memset(sum, 0, sizeof(sum));
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= num; i++) {
sum[gf(i)] += cnt[i];
if (cnt[i] > 1) vis[gf(i)] = 1;
}
for (int i = 1; i <= num; i++) {
if (sum[i]) {
if (vis[i])
ans += sum[i];
else
ans += sum[i] - 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;
const long long INF = 1 << 28;
const long long LINF = 1ll << 61;
int n, m, ans;
vector<int> con[100111], rev[100111], arr;
int vis[100111], cycle;
void dfs1(int x) {
arr.push_back(x);
vis[x] = 1;
for (int i = 0; i < con[x].size(); i++) {
int u = con[x][i];
if (vis[u]) continue;
dfs1(u);
}
for (int i = 0; i < rev[x].size(); i++) {
int u = rev[x][i];
if (vis[u]) continue;
dfs1(u);
}
}
void dfs2(int x) {
vis[x] = 3;
for (int i = 0; i < con[x].size(); i++) {
int u = con[x][i];
if (vis[u] == 2) continue;
if (vis[u] == 3) {
cycle = 1;
continue;
}
dfs2(u);
}
vis[x] = 2;
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
con[x].push_back(y);
rev[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
arr.clear();
cycle = 0;
dfs1(i);
for (int j = 0; j < arr.size(); j++)
if (vis[arr[j]] == 1) dfs2(arr[j]);
if (cycle)
ans += arr.size();
else
ans += arr.size() - 1;
}
}
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 int maxn = 100500;
int n, m, ans, scc, idx;
int d[maxn], vis[maxn];
vector<int> g[maxn], e[maxn], vec;
queue<int> q;
void dfs(int u) {
if (vis[u]) return;
vis[u] = 1;
vec.push_back(u);
for (auto v : e[u]) {
dfs(v);
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
g[x].push_back(y);
e[x].push_back(y);
e[y].push_back(x);
d[y]++;
}
for (int i = 1; i <= n; i++)
if (!vis[i]) {
vec.clear();
dfs(i);
int sum = vec.size(), sz = 0;
for (auto v : vec)
if (!d[v]) q.push(v), sz++;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto v : g[u]) {
d[v]--;
if (!d[v]) {
sz++;
q.push(v);
}
}
}
if (sz == sum)
ans += sum - 1;
else
ans += sum;
}
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, tot, ans, Head[100000 + 5], q[100000 + 5], T[100000 + 5],
Deg[100000 + 5];
bool Flag[100000 + 5];
struct Edge {
int next, node;
} h[100000 + 5 << 1];
inline void addedge(int u, int v) {
h[++tot].next = Head[u], Head[u] = tot;
h[tot].node = v;
}
inline void dfs(int z) {
if (Flag[z]) return;
Flag[z] = 1;
q[++q[0]] = z;
for (int i = Head[z]; i; i = h[i].next) {
int d = h[i].node;
dfs(d);
}
}
inline bool T_Sort() {
int l = 1, r = 0;
for (int i = 1; i <= q[0]; i++)
if (!Deg[q[i]]) T[++r] = q[i];
while (l <= r) {
int z = T[l++];
for (int i = Head[z]; i; i = h[i].next) {
if (i + 1 & 1) continue;
int d = h[i].node;
Deg[d]--;
if (!Deg[d]) T[++r] = d;
}
}
return r == q[0];
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1, u, v; i <= m; i++) {
scanf("%d%d", &u, &v);
addedge(u, v), addedge(v, u);
Deg[v]++;
}
for (int i = 1; i <= n; i++) {
if (Flag[i]) continue;
q[0] = 0;
dfs(i);
ans += T_Sort() ? q[0] - 1 : q[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 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/*
public class _505D {
}
*/
public class _505D
{
public void solve() throws FileNotFoundException
{
InputStream inputStream = System.in;
InputHelper inputHelper = new InputHelper(inputStream);
PrintStream out = System.out;
// actual solution
int n = inputHelper.readInteger();
int m = inputHelper.readInteger();
List[] g = new List[n];
List[] gu = new List[n];
for (int i = 0; i < n; i++)
{
g[i] = new ArrayList<Integer>();
gu[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++)
{
int a = inputHelper.readInteger();
int b = inputHelper.readInteger();
a--;
b--;
g[a].add(b);
gu[a].add(b);
gu[b].add(a);
}
int[] vu = new int[n];
for (int i = 0; i < n; i++)
{
vu[i] = -1;
}
int cn = 0;
for (int i = 0; i < n; i++)
{
if (vu[i] == -1)
{
dfs(i, gu, vu, cn);
cn++;
}
}
int[] compSize = new int[cn];
for (int i = 0; i < n; i++)
{
compSize[vu[i]]++;
}
boolean[] containsCycle = new boolean[cn];
boolean[] recStack = new boolean[n];
boolean[] vis = new boolean[n];
for (int i = 0; i < n; i++)
{
if (!vis[i])
{
containsCycle[vu[i]] |= cc(i, g, recStack, vis);
}
}
int ans = 0;
for (int i = 0; i < cn; i++)
{
if (containsCycle[i])
{
ans += compSize[i];
}
else
{
ans += compSize[i] - 1;
}
}
System.out.println(ans);
// end here
}
boolean cc(int u, List[] g, boolean[] recStack, boolean[] vis)
{
recStack[u] = true;
vis[u] = true;
boolean cc = false;
for (int i = 0; i < g[u].size(); i++)
{
int v = (int) g[u].get(i);
if (recStack[v])
{
cc |= true;
}
if (!vis[v])
{
cc |= cc(v, g, recStack, vis);
}
}
recStack[u] = false;
return cc;
}
void dfs(int u, List[] g, int[] v, int cn)
{
v[u] = cn;
for (int i = 0; i < g[u].size(); i++)
{
if (v[(int) g[u].get(i)] == -1)
{
dfs((int) g[u].get(i), g, v, cn);
}
}
}
public static void main(String[] args) throws FileNotFoundException
{
(new _505D()).solve();
}
class InputHelper
{
StringTokenizer tokenizer = null;
private BufferedReader bufferedReader;
public InputHelper(InputStream inputStream)
{
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
bufferedReader = new BufferedReader(inputStreamReader, 16384);
}
public String read()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
String line = bufferedReader.readLine();
if (line == null)
{
return null;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public Integer readInteger()
{
return Integer.parseInt(read());
}
public Long readLong()
{
return Long.parseLong(read());
}
}
}
| 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;
vector<vector<int> > adj, adj2;
int D[200010];
int I[200010];
int V1[200010];
int V2[200010];
int SEEN, VIS;
void dfs(int u, vector<int> &PV) {
V1[u] = 1;
PV.push_back(u);
for (int i = 0; i < adj[u].size(); ++i) {
int v = adj[u][i];
D[v]--;
if (D[v] == 0) {
dfs(v, PV);
}
}
}
void dfs2(int u, vector<int> &PV) {
V2[u] = 1;
PV.push_back(u);
for (int i = 0; i < adj2[u].size(); ++i) {
int v = adj2[u][i];
if (V2[v]) continue;
dfs2(v, PV);
}
}
int main() {
int N, M;
cin >> N >> M;
adj = vector<vector<int> >(N);
adj2 = vector<vector<int> >(N);
int cnt = 0;
for (int i = 0; i < M; ++i) {
int u, v;
cin >> u >> v;
u--;
v--;
D[v]++;
adj[u].push_back(v);
cnt += I[u] == 0;
cnt += I[v] == 0;
I[u] = I[v] = 1;
adj2[u].push_back(v);
adj2[v].push_back(u);
}
int ans = 0;
for (int i = 0; i < N; ++i) {
if (V2[i]) continue;
vector<int> CC;
dfs2(i, CC);
if (CC.size() <= 1) continue;
vector<int> PV;
for (int j = 0; j < CC.size(); ++j) {
if (V1[CC[j]] == 0 && D[CC[j]] == 0) {
dfs(CC[j], PV);
}
}
ans += (int)CC.size() - ((int)CC.size() == (int)PV.size());
}
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;
const int N = 100100;
int n, m, u, v, color[N], f[N], sz[N], cycle[N], res;
vector<int> g[N];
int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); }
void merge(int u, int v) {
if ((u = find(u)) == (v = find(v))) return;
if (sz[u] < sz[v]) swap(u, v);
sz[u] += sz[v];
f[v] = u;
}
void dfs(int u) {
color[u] = 1;
for (int x : g[u]) {
merge(u, x);
if (color[x] == 0)
dfs(x);
else if (color[x] == 1) {
cycle[x] = 1;
}
}
color[u] = 2;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = (int)(1); i <= (int)(m); ++i) {
scanf("%d %d", &u, &v);
g[u].push_back(v);
}
for (int i = (int)(1); i <= (int)(n); ++i) f[i] = i, sz[i] = 1;
for (int i = (int)(1); i <= (int)(n); ++i)
if (!color[i]) {
dfs(i);
}
for (int i = (int)(1); i <= (int)(n); ++i) cycle[find(i)] |= cycle[i];
for (int i = (int)(1); i <= (int)(n); ++i)
if (find(i) == i) {
if (cycle[i])
res += sz[i];
else
res += sz[i] - 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>
using namespace std;
int n, m, ptr;
bool mark[100010];
bool bad[100010];
int ord[100010];
vector<int> dir[100010];
vector<int> rev[100010];
vector<int> adj[100010];
bool dfs(int idx) {
bool ret = bad[idx];
mark[idx] = true;
for (int i = 0; i < adj[idx].size(); i++)
if (!mark[adj[idx][i]]) ret |= dfs(adj[idx][i]);
return ret;
}
void setOrd(int idx) {
mark[idx] = true;
for (int i = 0; i < dir[idx].size(); i++)
if (!mark[dir[idx][i]]) setOrd(dir[idx][i]);
ord[--ptr] = idx;
}
int ccf(int idx) {
int cnt = 1;
mark[idx] = true;
for (int i = 0; i < rev[idx].size(); i++)
if (!mark[rev[idx][i]]) cnt += ccf(rev[idx][i]);
return cnt;
}
int main() {
cin >> n >> m;
ptr = n;
int a, b;
for (int i = 0; i < m; i++) {
cin >> a >> b;
a--, b--;
dir[a].push_back(b);
rev[b].push_back(a);
adj[a].push_back(b);
adj[b].push_back(a);
}
int res = n;
for (int i = 0; i < n; i++)
if (!mark[i]) setOrd(i);
memset(mark, false, sizeof mark);
for (int i = 0; i < n; i++) {
if (!mark[ord[i]]) {
int tmp = ccf(ord[i]);
if (tmp > 1) bad[ord[i]] = true;
}
}
memset(mark, false, sizeof mark);
for (int i = 0; i < n; i++)
if (!mark[i] && !dfs(i)) 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 int mxi = 1e5 + 666;
const long long mod = 1e9 + 7;
const long long inf = -1e17;
int n, m, ans, mark[mxi], mark2[mxi];
vector<long long> g[mxi], ne[mxi], ts;
bool cy;
void tso(int v) {
ts.push_back(v);
mark2[v] = 1;
for (auto u : ne[v]) {
if (!mark2[u]) tso(u);
}
}
void dfs(int v) {
mark[v] = 1;
for (auto u : g[v]) {
if (mark[u] == 1) cy = 1;
if (!mark[u]) dfs(u);
}
mark[v] = 2;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
ans = n;
for (long long i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
g[u].push_back(v);
ne[u].push_back(v);
ne[v].push_back(u);
}
for (long long i = 0; i < n; i++) {
if (!mark2[i]) {
ts.clear();
tso(i);
cy = 0;
for (long long j = 0; j < ts.size(); j++) {
if (!mark[ts[j]]) dfs(ts[j]);
}
if (!cy) ans--;
}
}
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.List;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author ilyakor
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
ArrayList<Integer>[] g1, g2;
boolean[] u;
int[] ind;
int[] pos;
ArrayList<Integer> inds;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
g1 = new ArrayList[n];
g2 = new ArrayList[n];
for (int i = 0; i < n; ++i)
g1[i] = new ArrayList<>();
for (int i = 0; i < n; ++i)
g2[i] = new ArrayList<>();
for (int i = 0; i < m; ++i) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
g1[x].add(y);
g1[y].add(x);
g2[x].add(y);
}
u = new boolean[n];
ind = new int[n];
pos = new int[n];
int res = 0;
for (int i = 0; i < n; ++i) {
if (u[i]) continue;
inds = new ArrayList<>();
dfs(i);
if (inds.size() <= 1) continue;
ArrayList<Integer>[] subG = new ArrayList[inds.size()];
for (int j = 0; j < subG.length; ++j) {
subG[j] = new ArrayList<>();
for (int x : g2[inds.get(j)])
subG[j].add(ind[x]);
}
List<Integer> order = TopologicalSort.topologicalSort(subG);
boolean ok = true;
for (int j = 0; j < order.size(); ++j)
pos[order.get(j)] = j;
for (int j = 0; j < subG.length; ++j)
for (int x : subG[j]) {
if (pos[x] < pos[j])
ok = false;
}
if (ok) res += inds.size() - 1;
else res += inds.size();
}
out.printLine(res);
}
private void dfs(int x) {
u[x] = true;
ind[x] = inds.size();
inds.add(x);
for (int y : g1[x])
if (!u[y])
dfs(y);
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
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(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class TopologicalSort {
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);
}
public static List<Integer> topologicalSort(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> res = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
if (!used[i])
dfs(graph, used, res, i);
Collections.reverse(res);
return res;
}
}
| 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.text.DecimalFormat;
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Reader in = new Reader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solve solver = new Solve();
solver.solve(1, in, out);
out.close();
}
}
class Solve{
public void solve(int testNumber, Reader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n];
for(int x = 0; x < adj.length; x++)
{
adj[x] = new ArrayList<Integer>();
}
int[] degree = new int[n];
DisjointSet ds = new DisjointSet(n);
int components = n;
for(int y = 0; y < m; y++)
{
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
adj[a].add(b);
degree[b]++;
if(ds.union(a, b))
{
components--;
}
}
ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
for(int z = 0; z < degree.length; z++)
{
if(degree[z] == 0)
{
queue.add(z);
}
}
boolean[] visited = new boolean[n];
while(queue.size() > 0)
{
int node = queue.remove();
visited[node] = true;
for(int next : adj[node])
{
degree[next]--;
if(degree[next] == 0)
{
queue.add(next);
}
}
}
HashSet<Integer> hs = new HashSet<Integer>();
for(int a = 0; a < visited.length; a++)
{
if(!visited[a])
{
hs.add(ds.find(a));
}
}
out.println(n - components + hs.size());
}
static class DisjointSet
{
int[] parent;
int[] rank;
public DisjointSet(int n)
{
parent = new int[n];
rank = new int[n];
for(int i = 0; i < parent.length; i++)
{
parent[i] = i;
}
}
public int find(int x)
{
if(parent[x] != x)
{
parent[x] = find(parent[x]);
}
return parent[x];
}
public boolean union(int x, int y)
{
int a = find(x);
int b = find(y);
if(a == b)
{
return false;
}
else
{
if(rank[a] < rank[b])
{
parent[a] = b;
}
else if(rank[a] > rank[b])
{
parent[b] = a;
}
else
{
parent[b] = a;
rank[a]++;
}
return true;
}
}
}
}
class Reader {
private BufferedReader in;
private StringTokenizer st;
public Reader(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(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;
template <class T>
inline T gcd(T a, T b) {
return (b) == 0 ? (a) : gcd((b), ((a) % (b)));
}
template <class T>
inline T lcm(T a, T b) {
return ((a) / gcd((a), (b)) * (b));
}
template <class T>
inline T BigMod(T Base, T power, T M = 1000000007) {
if (power == 0) return 1;
if (power & 1)
return ((Base % M) * (BigMod(Base, power - 1, M) % M)) % M;
else {
T y = BigMod(Base, power / 2, M) % M;
return (y * y) % M;
}
}
template <class T>
inline T ModInv(T A, T M = 1000000007) {
return BigMod(A, M - 2, M);
}
int fx[] = {-1, +0, +1, +0, +1, +1, -1, -1, +0};
int fy[] = {+0, -1, +0, +1, +1, -1, +1, -1, +0};
int day[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int N = 1e5 + 100;
vector<int> g_bi[N], g_uni[N];
int col[N];
bool cycle_found;
set<int> visited;
int comp = 0;
vector<int> node;
bool find_cycle;
int ache[N];
void cycle(int u) {
if (find_cycle) return;
col[u] = 1;
for (int v : g_uni[u]) {
if (col[v] == 1) {
find_cycle = true;
return;
}
if (col[v] == 0) cycle(v);
if (find_cycle) return;
}
col[u] = 2;
}
int vis[N];
void dfs(int u) {
vis[u] = comp;
node.push_back(u);
for (int v : g_bi[u]) {
if (vis[v] == 0) dfs(v);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
g_uni[u].push_back(v);
g_bi[u].push_back(v);
g_bi[v].push_back(u);
ache[u] = ache[v] = 1;
}
int ans = 0;
for (int i = 1; i <= n; i++) {
ans += ache[i];
}
for (int i = 1; i <= n; i++) {
if (ache[i] && vis[i] == 0) {
comp++;
node.clear();
dfs(i);
ans--;
find_cycle = false;
for (int u : node) {
if (col[u] == 0 && find_cycle != true) {
cycle(u);
}
}
ans += find_cycle;
}
}
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 MX = 1e5 + 5;
int low[MX], depth[MX], timer = 0, compcnt = 0, comp[MX], compsz[MX], vi[MX];
vector<int> adj[MX], adj1[MX];
stack<int> S;
void dfs(int x) {
low[x] = depth[x] = ++timer;
S.push(x);
vi[x] = 1;
int sz_ = adj[x].size(), nxt;
for (int j = 0; j < sz_; j++) {
nxt = adj[x][j];
if (depth[nxt] == -1) {
dfs(nxt);
low[x] = min(low[x], low[nxt]);
} else if (vi[nxt])
low[x] = min(low[x], depth[nxt]);
}
if (low[x] == depth[x]) {
++compcnt;
while (1) {
nxt = S.top();
comp[nxt] = compcnt;
vi[nxt] = 0;
compsz[compcnt]++;
S.pop();
if (nxt == x) break;
}
}
}
int in[MX], par[MX];
bool vis[MX], big;
int dfs2(int x) {
vis[x] = 1;
if (compsz[x] > 1) big = 1;
int ret = compsz[x];
for (auto nxt : adj1[x]) {
if (vis[nxt]) continue;
ret += dfs2(nxt);
}
return ret;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
adj[u].push_back(v);
}
memset(depth, -1, sizeof depth);
for (int i = 1; i <= n; ++i)
if (depth[i] == -1) dfs(i);
for (int i = 1; i <= n; ++i) {
int x = comp[i];
for (auto nxt : adj[i]) {
nxt = comp[nxt];
if (x == nxt) continue;
adj1[x].push_back(nxt);
adj1[nxt].push_back(x);
}
}
int ans = 0;
for (int i = 1; i <= compcnt; ++i) {
if (vis[i]) continue;
big = 0;
int sz = dfs2(i);
ans += sz - 1 + big;
}
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;
long long qpow(long long a, long long b) {
long long res = 1, base = a;
while (b) {
if (b % 2) res = res * base;
base = base * base;
b /= 2;
}
return res;
}
long long powmod(long long a, long long b) {
long long res = 1, base = a;
while (b) {
if (b % 2) res = res * base % 1000000007;
base = base * base % 1000000007;
b /= 2;
}
return res;
}
struct node {
int v;
node *next;
} * H[200005], E[400005], *edges;
bool vis1[200005];
bool vis2[200005];
bool cyc[200005];
int f[200005];
int n, m, ans;
void addedges(int u, int v) {
edges->v = v;
edges->next = H[u];
H[u] = edges++;
}
int find(int u) { return f[u] = u == f[u] ? f[u] : find(f[u]); }
bool merge(int a, int b) {
int aa = find(a), bb = find(b);
if (aa == bb) return false;
f[aa] = bb;
return true;
}
void init(void) {
edges = E;
ans = 0;
memset(H, 0, sizeof H);
}
void read(void) {
int u, v;
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++) f[i] = i;
while (m--) {
scanf("%d%d", &u, &v);
addedges(u, v);
ans += merge(u, v);
}
}
void dfs(int u) {
vis1[u] = 1;
for (node *e = H[u]; e; e = e->next) {
if (vis2[e->v]) cyc[find(u)] = true;
if (vis1[e->v]) continue;
vis2[e->v] = true;
dfs(e->v);
vis2[e->v] = false;
}
}
void work(void) {
for (int i = 1; i <= n; i++)
if (!vis1[i]) {
vis2[i] = true;
dfs(i);
vis2[i] = false;
}
for (int i = 1; i <= n; i++) ans += cyc[i];
printf("%d\n", ans);
}
int main(void) {
init();
read();
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;
long long power(long long x, long long y, long long mod) {
if (y < 0) return power(power(x, mod - 2, mod), -y, mod);
long long res = 1;
while (y) {
if (y & 1) res = res * x % mod;
y >>= 1;
x = x * x % mod;
}
return res;
}
const int nn = 100010;
int v[nn], q[nn], inq[nn], p[nn], f[nn];
vector<int> e[nn];
int n, m, qr;
int find(int x) {
if (f[x] != x) f[x] = find(f[x]);
return f[x];
}
int bfs() {
int l = 0, r = 0;
for (int i = (int)1; i <= (int)qr; ++i) {
if (inq[q[i]] == 0) p[++r] = q[i];
}
while (l < r) {
int x = p[++l];
for (int i = (int)0; i <= (int)((int)(e[x].size())) - 1; ++i) {
int j = e[x][i];
if (--inq[j] == 0) p[++r] = j;
}
}
return r != qr;
}
vector<int> r[nn];
int main() {
scanf("%d%d", &n, &m);
for (int i = (int)1; i <= (int)n; ++i) f[i] = i;
for (int i = (int)1; i <= (int)m; ++i) {
int x, y;
cin >> x >> y;
e[x].push_back(y);
++inq[y];
int fx = find(x), fy = find(y);
f[fx] = fy;
}
for (int i = (int)1; i <= (int)n; ++i) r[find(i)].push_back(i);
int res = 0;
for (int i = (int)1; i <= (int)n; ++i)
if (((int)(r[i].size()))) {
qr = 0;
for (int _ = (int)0; _ <= (int)((int)(r[i].size())) - 1; ++_)
q[++qr] = r[i][_];
res += qr - 1 + bfs();
}
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 int MAX = 100005;
vector<int> adj[MAX], neg[MAX];
int mark[MAX], mark2[MAX];
bool cycle;
void dfs(int v) {
mark[v] = 1;
for (int i = 0; i < adj[v].size(); i++) {
int u = adj[v][i];
if (mark[u] == 1) cycle = true;
if (!mark[u]) dfs(u);
}
mark[v] = 2;
}
vector<int> ver;
void go(int v) {
ver.push_back(v);
mark2[v] = 1;
for (int i = 0; i < neg[v].size(); i++) {
int u = neg[v][i];
if (!mark2[u]) go(u);
}
}
int main() {
ios::sync_with_stdio(false);
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);
neg[u].push_back(v);
neg[v].push_back(u);
}
int ans = n;
for (int i = 0; i < n; i++)
if (!mark2[i]) {
ver.clear();
go(i);
cycle = false;
for (int j = 0; j < ver.size(); j++)
if (!mark[ver[j]]) dfs(ver[j]);
if (!cycle) 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.util.Arrays;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* 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;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
private int n, m, cc;
private ArrayList<Integer>[] head, re_head;
private ArrayList<Integer> list;
private boolean[] mark;
private int[] id, cnt;
private void Topo(int u) {
mark[u] = true;
for(int v : head[u])
if (!mark[v]) Topo(v);
list.add(u);
}
private void CC(int u) {
mark[u] = true; id[u] = cc;
for(int v : re_head[u])
if (!mark[v]) CC(v);
}
private void scc() {
Arrays.fill(mark, false);
for(int i = 1; i <= n; ++i)
if (!mark[i]) Topo(i);
Arrays.fill(mark, false);
for(int i = list.size() - 1; i >= 0; --i)
if (!mark[list.get(i)]) {
++cc; CC(list.get(i));
}
for(int i = 1; i <= n; ++i) ++cnt[id[i]];
}
private boolean Check(int u) {
mark[u] = true;
boolean res = (cnt[id[u]] == 1);
for(int v : head[u])
if (!mark[v]) res &= Check(v);
for(int v : re_head[u])
if (!mark[v]) res &= Check(v);
return res;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt(); m = in.nextInt();
mark = new boolean[n + 1];
id = new int[n + 1];
cnt = new int[n + 1];
Arrays.fill(cnt, 0);
head = new ArrayList[n + 1];
re_head = new ArrayList[n + 1];
list = new ArrayList<>();
for(int i = 0; i <= n; ++i) {
head[i] = new ArrayList<>();
re_head[i] = new ArrayList<>();
}
for(int i = 1; i <= m; ++i) {
int u = in.nextInt(), v = in.nextInt();
head[u].add(v);
re_head[v].add(u);
}
scc();
int res = n;
Arrays.fill(mark, false);
for(int i = 1; i <= n; ++i)
if (!mark[i])
res -= (Check(i) == true ? 1 : 0);
out.print(res);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
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 int nextInt() {
return Integer.parseInt(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;
const int N = 4 * 1e5 + 2;
const int MOD = 1000000007;
int n, m;
vector<unordered_set<int>> vec;
vector<unordered_set<int>> vec_rev;
vector<bool> visited;
stack<int> stk;
vector<unordered_set<int>> SCC;
vector<int> dsu;
unordered_set<int> deleted;
int getParent(int node) {
if (dsu[node] == node) return node;
return dsu[node] = getParent(dsu[node]);
}
void makeParent(int a, int b) {
a = getParent(a);
b = getParent(b);
dsu[a] = b;
}
void dfs1(int node) {
if (visited[node]) return;
visited[node] = true;
for (int next : vec[node]) {
dfs1(next);
}
stk.push(node);
}
void dfs2(int node) {
if (visited[node]) return;
visited[node] = true;
SCC.back().insert(node);
for (int next : vec_rev[node]) {
dfs2(next);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
vec.resize(n + 2);
vec_rev.resize(n + 2);
int a, b;
dsu.resize(n + 2);
for (int i = 0; i <= n; i++) dsu[i] = i;
for (int i = 0; i < m; i++) {
cin >> a >> b;
vec[a].insert(b);
vec_rev[b].insert(a);
}
visited.resize(n + 2, false);
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
dfs1(i);
}
}
visited.clear();
visited.resize(n + 2, false);
while (stk.size()) {
int node = stk.top();
stk.pop();
if (!visited[node]) {
SCC.emplace_back();
dfs2(node);
}
}
visited.clear();
visited.resize(n + 2, false);
for (int i = 1; i <= n; i++) {
for (int next : vec[i]) {
makeParent(i, next);
}
}
unordered_set<int> par_SCC;
for (auto it : SCC) {
if (it.size() != 1) par_SCC.insert(getParent(*it.begin()));
}
for (int i = 1; i <= n; i++) {
if (par_SCC.count(getParent(i))) {
deleted.insert(i);
}
}
int ans = deleted.size();
visited.clear();
visited.resize(n + 2, false);
for (int i = 1; i <= n; i++) dsu[i] = i;
for (int i = 1; i <= n; i++) {
if (deleted.count(i)) {
continue;
}
for (int next : vec[i]) {
makeParent(i, next);
}
}
map<int, int> m;
for (int i = 1; i <= n; i++) {
if (deleted.count(i)) continue;
m[getParent(i)]++;
}
for (auto it : m) {
ans += it.second - 1;
}
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;
string s;
long long rez, h, q, n, i, j, k1, k2, k3, d, x, k, y, xx, yy, m, l, r, c, t,
sum, used[100500];
vector<long long> graph[100500], gr[100500], grb[100500];
vector<long long> comps[100500];
vector<long long> order;
void dfs(int v) {
if (used[v]) return;
used[v] = 1;
comps[j].push_back(v);
for (int i = 0; i < graph[v].size(); i++) dfs(graph[v][i]);
}
void dfs1(int v) {
if (used[v]) return;
used[v] = 1;
for (int i = 0; i < gr[v].size(); i++) dfs1(gr[v][i]);
order.push_back(v);
}
void dfs2(int v) {
if (used[v]) return;
used[v] = 1;
for (int i = 0; i < grb[v].size(); i++) dfs2(grb[v][i]);
}
int main() {
cin >> n >> m;
for (i = 0; i < m; i++) {
cin >> x >> y;
x--;
y--;
graph[x].push_back(y);
graph[y].push_back(x);
gr[x].push_back(y);
grb[y].push_back(x);
}
for (i = 0; i < n; i++)
if (!used[i]) {
dfs(i);
j++;
}
k = j;
for (i = 0; i < k; i++) {
for (j = 0; j < comps[i].size(); j++) used[comps[i][j]] = 0;
l = 0;
r = 0;
order.clear();
for (j = 0; j < comps[i].size(); j++)
if (!used[comps[i][j]]) {
dfs1(comps[i][j]);
l++;
}
for (j = 0; j < comps[i].size(); j++) used[comps[i][j]] = 0;
for (j = 0; j < order.size(); j++) {
if (!used[order[order.size() - 1 - j]]) {
dfs2(order[order.size() - 1 - j]);
r++;
}
}
if (comps[i].size() != r)
rez += comps[i].size();
else
rez += comps[i].size() - 1;
}
cout << rez << 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 main(void) {
srand(time(0));
cout << fixed << setprecision(7);
cerr << fixed << setprecision(7);
int n, m;
ios_base ::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
static vector<int> s[1 << 20];
static vector<int> v[1 << 20];
while (m--) {
int a, b;
cin >> a >> b;
s[a].push_back(b);
v[b].push_back(a);
}
vector<int> order;
int ans = 0;
static int was[1 << 20];
function<void(int)> dfs1 = [&](int node) {
was[node] = 1;
for (auto it : s[node])
if (!was[it]) dfs1(it);
order.push_back(node);
};
int mark = 0;
static int sz[1 << 20];
function<void(int)> dfs2 = [&](int node) {
was[node] = mark;
for (auto it : v[node])
if (!was[it]) dfs2(it);
};
function<int(int)> dfs = [&](int node) {
int ok = sz[was[node]] == 1;
was[node] = 0;
for (auto it : v[node])
if (was[it]) ok &= dfs(it);
for (auto it : s[node])
if (was[it]) ok &= dfs(it);
return ok;
};
for (int i = 1; i <= n; ++i)
if (!was[i]) dfs1(i);
reverse(order.begin(), order.end());
memset(was, 0, sizeof(was));
for (auto it : order)
if (!was[it]) ++mark, dfs2(it);
for (int i = 1; i <= n; ++i) ++sz[was[i]];
ans = n;
for (int i = 1; i <= n; ++i)
if (was[i]) ans -= dfs(i);
cout << ans << '\n';
cerr << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms"
<< '\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 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ProblemBMrKitayutasTechnology solver = new ProblemBMrKitayutasTechnology();
solver.solve(1, in, out);
out.close();
}
static class ProblemBMrKitayutasTechnology {
ArrayList<Integer>[] edge;
boolean[] used;
boolean[] visited;
boolean[] cycle;
int[] parent;
int[] count;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int m = in.readInt();
edge = new ArrayList[n + 1];
used = new boolean[n + 1];
visited = new boolean[n + 1];
parent = new int[n + 1];
count = new int[n + 1];
cycle = new boolean[n + 1];
for (int i = 1; i <= n; i++) parent[i] = i;
for (int i = 0; i <= n; i++) edge[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int u = in.readInt();
int v = in.readInt();
union(u, v);
edge[u].add(v);
}
for (int i = 1; i <= n; i++) {
count[find(i)]++;
if (used[i]) continue;
if (hasCycle(i)) cycle[find(i)] = true;
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (i != parent[i]) continue;
ans += count[i] - 1;
if (cycle[i]) ans++;
}
out.println(ans);
}
boolean hasCycle(int pos) {
if (visited[pos]) return true;
if (used[pos]) return false;
visited[pos] = true;
used[pos] = true;
for (int i : edge[pos]) {
if (hasCycle(i)) return true;
}
visited[pos] = false;
return false;
}
int find(int a) {
if (parent[a] == a) return a;
return parent[a] = find(parent[a]);
}
void union(int a, int b) {
parent[find(a)] = find(b);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.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 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 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;
}
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 | #include <bits/stdc++.h>
using namespace std;
int v[200005], h2[200005], in[200005], h[200005], tot = 0, k, n, m;
struct edge {
int y, ne;
} e[400005];
queue<int> q;
void Add(int x, int y) {
tot++;
e[tot].y = y;
e[tot].ne = h[x];
h[x] = tot;
}
void Add2(int x, int y) {
tot++;
e[tot].y = y;
e[tot].ne = h2[x];
h2[x] = tot;
}
void dfs(int x) {
if (!in[x]) q.push(x);
tot++;
v[x] = 1;
for (int i = h2[x]; i; i = e[i].ne) {
int y = e[i].y;
if (v[y]) continue;
dfs(y);
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
Add(x, y);
Add2(x, y);
Add2(y, x);
in[y]++;
}
int ans = 0;
for (int i = 1; i <= n; i++)
if (!v[i]) {
tot = 0;
k = 0;
while (!q.empty()) q.pop();
dfs(i);
if (tot == 1) continue;
int ok = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
ok++;
if (ok > tot) break;
for (int i = h[x]; i; i = e[i].ne) {
in[e[i].y]--;
if (!in[e[i].y]) q.push(e[i].y);
}
}
if (ok == tot)
ans += (tot - 1);
else
ans += tot;
}
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;
struct bian {
int next, point;
} b[210000];
int p[110000], len, in[110000], s[110000], dfs[110000], low[110000], pd[110000],
now, sign, w[110000], size[110000], n, m;
void ade(int k1, int k2) {
b[++len] = (bian){p[k1], k2};
p[k1] = len;
}
void add(int k1, int k2) {
ade(k1, k2);
ade(k2, k1);
}
void solve(int k) {
s[++len] = k;
dfs[k] = ++sign;
low[k] = sign;
pd[k] = 1;
in[k] = 1;
for (int i = p[k]; i != -1; i = b[i].next) {
if (i & 1) continue;
int j = b[i].point;
if (pd[j] == 0) {
solve(j);
low[k] = min(low[k], low[j]);
} else if (in[j])
low[k] = min(low[k], dfs[j]);
}
if (low[k] == dfs[k]) {
now++;
while (s[len + 1] != k) {
w[s[len]] = now;
in[s[len]] = 0;
len--;
size[now]++;
}
}
}
int dfss(int k) {
int num = 1;
pd[k] = 1;
for (int i = p[k]; i != -1; i = b[i].next) {
int j = b[i].point;
if (pd[j] == 0) num += dfss(j);
}
return num;
}
int main() {
scanf("%d%d", &n, &m);
len = -1;
memset(p, 0xff, sizeof p);
for (int i = 1; i <= m; i++) {
int k1, k2;
scanf("%d%d", &k1, &k2);
add(k1, k2);
}
len = 0;
for (int i = 1; i <= n; i++)
if (pd[i] == 0) solve(i);
int ans = 0;
memset(pd, 0x00, sizeof pd);
for (int i = 1; i <= n; i++)
if (size[w[i]] > 1 && pd[i] == 0) ans += dfss(i);
for (int i = 1; i <= n; i++)
if (pd[i] == 0) ans += dfss(i) - 1;
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.InputStreamReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.TreeSet;
public class Main {
static Reader in;
static PrintWriter out;
static final int INF = 1111111111;
static List<Integer>[] adj = new List[100000];
static int[] start_time = new int[100000];
static int[] stack = new int[100000];
static boolean[] in_path = new boolean[100000];
static boolean[] visited = new boolean[100000];
static int top, timer, nscc;
static int[] component = new int[100000];
static ArrayList<Boolean> has_cycle = new ArrayList<>();
static int dfs(int s) {
if(visited[s]) {
if(in_path[s]) return start_time[s];
return INF;
}
visited[s] = true;
stack[top++] = s;
int ast = start_time[s] = timer++;
for(int ei: adj[s]) ast = Math.min(ast, dfs(ei));
if(ast == start_time[s]) {
int v, cnt = 0;
do {
v = stack[--top];
in_path[v] = false;
component[v] = nscc;
cnt++;
} while(v != s);
has_cycle.add((cnt>1 ? true:false));
++nscc;
}
return ast;
}
static int[] p;
static int find(int i) { return (i == p[i]) ? i:(p[i] = find(p[i])); }
static void solve() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
for(int i=0; i<n; i++) {
adj[i] = new ArrayList<>();
visited[i] = false;
in_path[i] = true;
}
for(int i=0; i<m; i++) adj[in.nextInt()-1].add(in.nextInt()-1);
top = timer = nscc = 0;
for(int i=0; i<n; i++) {
if(!visited[i]) dfs(i);
}
p = new int[nscc];
for(int i=0; i<nscc; i++) p[i] = i;
for(int i=0; i<n; i++) {
int u = find(component[i]);
for(int ei: adj[i]) {
int v = find(component[ei]);
if(u != v) p[v] = u;
}
}
boolean[] flag = new boolean[nscc];
Arrays.fill(flag, false);
for(int i=0; i<nscc; i++) {
if(has_cycle.get(i)) flag[find(i)] = true;
}
int cnt = 0;
for(int i=0; i<nscc; i++) {
if(i == find(i) && !flag[i]) cnt++;
}
out.println((n - cnt));
}
public static void main(String[] args) {
try {
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter bw = new BufferedWriter(osw);
in = new Reader();
out = new PrintWriter(bw);
solve();
in.close();
out.close();
bw.close();
osw.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
static class Reader {
InputStreamReader isr;
BufferedReader br;
StringTokenizer tk;
String str;
Reader() {
br = new BufferedReader((isr = new InputStreamReader(System.in)));
tk = new StringTokenizer("");
}
String nextLine() throws IOException {
while(((str = br.readLine()) != null) && (str.length() == 0));
return str;
}
String next() throws IOException {
if(!tk.hasMoreTokens()) {
if(nextLine() == null) return null;
tk = new StringTokenizer(str);
}
return tk.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
void flush() {
tk = new StringTokenizer("");
}
void close() throws IOException {
br.close();
isr.close();
}
}
}
| 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 = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, m;
int cmpsize[100010];
vector<int> G[100010];
vector<int> rG[100010];
bool vis[100010];
int cmp[100010];
vector<int> vs;
void dfs(int v) {
vis[v] = true;
for (int i = 0; i < G[v].size(); i++) {
if (!vis[G[v][i]]) dfs(G[v][i]);
}
vs.push_back(v);
}
void rdfs(int v, int k) {
vis[v] = true;
cmp[v] = k;
for (int i = 0; i < rG[v].size(); i++) {
if (!vis[rG[v][i]]) rdfs(rG[v][i], k);
}
}
int scc() {
memset(vis, 0, sizeof(vis));
vs.clear();
for (int i = 0; i < n; i++) {
if (!vis[i]) dfs(i);
}
memset(vis, 0, sizeof(vis));
int k = 0;
for (int i = vs.size() - 1; i >= 0; i--) {
if (!vis[vs[i]]) rdfs(vs[i], k++);
}
return k;
}
int dfs2(int v) {
vis[v] = true;
int ans = cmpsize[cmp[v]] == 1;
for (int i = 0; i < G[v].size(); i++) {
if (!vis[G[v][i]]) ans &= dfs2(G[v][i]);
}
for (int i = 0; i < rG[v].size(); i++) {
if (!vis[rG[v][i]]) ans &= dfs2(rG[v][i]);
}
return ans;
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--, v--;
G[u].push_back(v);
rG[v].push_back(u);
}
scc();
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; i++) {
cmpsize[cmp[i]]++;
}
int ans = n;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
ans -= dfs2(i);
}
}
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 mod = 1e9 + 7;
const int N = 3e5 + 5;
int n, m, cnt, h[N], num, ser[N], low[N], dfn[N], tot, sta[N], top, siz[N],
flag[N];
bool vis[N];
struct Edge {
int to, next;
} e[N];
int to[N], fa[N];
long long ans;
void add(int u, int v) {
e[++cnt] = (Edge){v, h[u]};
h[u] = cnt;
}
void Dfs(int u) {
dfn[u] = low[u] = ++tot;
vis[u] = 1;
sta[++top] = u;
for (int i = h[u]; i; i = e[i].next) {
int v = e[i].to;
if (!dfn[v]) {
Dfs(v);
low[u] = min(low[u], low[v]);
} else if (vis[v])
low[u] = min(low[u], dfn[v]);
}
if (low[u] == dfn[u]) {
int cur;
num++;
do {
siz[num]++;
cur = sta[top--];
vis[cur] = 0;
to[cur] = num;
} while (cur != u);
}
}
int get(int u) { return (u == fa[u]) ? u : fa[u] = get(fa[u]); }
int main() {
cin >> n >> m;
for (register int i = 1; i <= m; i++) {
int u, v;
scanf("%d%d", &u, &v);
add(u, v);
}
for (register int i = 1; i <= n; i++)
if (!dfn[i]) Dfs(i);
for (register int i = 1; i <= num; i++) {
fa[i] = i;
if (siz[i] > 1) flag[i] = 1;
}
for (register int u = 1; u <= n; u++) {
int x = to[u];
for (int i = h[u]; i; i = e[i].next) {
int v = e[i].to;
int y = to[v];
int fx = get(x), fy = get(y);
if (fx == fy) continue;
if (siz[fx] > 1 || siz[fy] > 1) flag[fx] = 1;
fa[fy] = fx;
flag[fx] += flag[fy];
}
}
for (register int i = 1; i <= n; i++) {
ans += siz[i];
int fx = get(i);
if (fx == i && !flag[i]) ans--;
}
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, ok, k, v[100005], x, y, ans;
vector<int> a[100005], b[100005], c;
bitset<100005> w;
void udfs(int x) {
w[x] = 1;
vector<int>::iterator it;
c.push_back(x);
for (it = b[x].begin(); it != b[x].end(); ++it)
if (!w[*it]) udfs(*it);
}
void dfs(int x) {
v[x] = 2;
vector<int>::iterator it;
for (it = a[x].begin(); it != a[x].end() && !ok; ++it) {
if (v[*it] == 2)
ok = 1;
else if (!v[*it])
dfs(*it);
}
k++;
v[x] = 1;
}
int main() {
cin >> n >> m;
ans = n;
for (int i = 1; i <= m; ++i) {
cin >> x >> y;
a[x].push_back(y);
b[x].push_back(y);
b[y].push_back(x);
}
vector<int>::iterator it;
for (int i = 1; i <= n; ++i)
if (!v[i]) {
ok = 0;
k = 0;
c.clear();
udfs(i);
for (it = c.begin(); it != c.end(); ++it) dfs(*it);
if (!ok) 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 INF = 1000000000;
const int dir_4[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
const int dir_8[8][2] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1},
{-1, 0}, {-1, -1}, {0, -1}, {1, -1}};
const int kaijou[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
int par[150010], r[150010], lar[150010];
void init() {
for (int i = 0; i < 150010; i++) {
par[i] = i;
r[i] = 0;
lar[i] = 1;
}
}
int find(int x) {
if (x == par[x]) return x;
return par[x] = find(par[x]);
}
bool same(int x, int y) { return find(x) == find(y); }
void unit(int x, int y) {
if (same(x, y)) return;
x = find(x);
y = find(y);
if (r[x] < r[y]) {
par[x] = y;
lar[y] += lar[x];
} else {
par[y] = x;
lar[x] += lar[y];
if (r[x] == r[y]) r[x]++;
}
}
int n, m;
vector<int> G[100010];
vector<int> rG[100010];
vector<int> vec[100010];
vector<int> vs;
bool used[100010];
void dfs(int v) {
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
if (!used[G[v][i]]) dfs(G[v][i]);
}
vs.push_back(v);
}
int cnt(int v) {
vs.clear();
for (int i = 0; i < 100010; i++) used[i] = false;
for (int i = 0; i < vec[v].size(); i++) {
if (!used[vec[v][i]]) {
dfs(vec[v][i]);
}
}
for (int i = 0; i < 100010; i++) used[i] = false;
for (int i = vs.size() - 1; i > 0; i--) {
int p = vs[i];
for (int j = 0; j < rG[p].size(); j++) {
if (!used[rG[p][j]]) return lar[v];
}
used[p] = true;
}
return lar[v] - 1;
}
int main() {
init();
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);
rG[b].push_back(a);
unit(a, b);
}
for (int i = 1; i <= n; i++) {
vec[find(i)].push_back(i);
}
int ret = 0;
bool used_[100010];
for (int i = 0; i < 100010; i++) used_[i] = false;
for (int i = 1; i <= n; i++) {
if (par[i] == i) {
ret += cnt(i);
used_[i] = true;
}
}
printf("%d\n", ret);
}
| 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>
int e[2][100010LL], star[100010LL] = {0}, tote = 0;
inline void AddEdge(int u, int v) {
tote++, e[0][tote] = v, e[1][tote] = star[u], star[u] = tote;
}
int fa[100010LL] = {0};
inline int GetAnc(int u) { return fa[u] ? fa[u] = GetAnc(fa[u]) : u; }
inline void Union(int u, int v) {
u = GetAnc(u), v = GetAnc(v);
if (u != v) fa[u] = v;
}
int ind[100010LL] = {0}, poi[100010LL];
inline bool cmp(const int& a, const int& b) {
return fa[a] == fa[b] ? ind[a] < ind[b] : fa[a] < fa[b];
}
int sta[100010LL], top;
inline bool Circle(int L, int R) {
int i, u, p;
top = 0;
for (i = L; i <= R; i++)
if (ind[poi[i]] == 0)
sta[++top] = poi[i];
else
break;
while (top) {
u = sta[top--];
for (p = star[u]; p; p = e[1][p])
if ((--ind[e[0][p]]) == 0) sta[++top] = e[0][p];
}
for (i = R; i >= L; i--)
if (ind[poi[i]] > 0) return true;
return false;
}
int n, m;
int main() {
int i, u, v, ans, last;
scanf("%d%d", &n, &m);
for (i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
AddEdge(u, v), Union(u, v), ind[v]++;
}
for (i = 1; i <= n; i++) GetAnc(i), poi[i] = i;
for (i = 1; i <= n; i++)
if (!fa[i]) fa[i] = i;
std::sort(poi + 1, poi + n + 1, cmp);
ans = 0, last = 1;
poi[n + 1] = n + 1, fa[n + 1] = -1;
for (i = 1; i <= n; i++)
if (fa[poi[i]] != fa[poi[i + 1]]) {
if (Circle(last, i))
ans += i - last + 1;
else
ans += i - last;
last = 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 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100100;
vector<int> g[maxn], dg[maxn];
int dfs_enter[maxn], dfs_f[maxn], n, m, cnt;
bool visited[maxn];
bool cycle[maxn];
vector<int> st;
void dfs(int node) {
if (visited[node]) return;
st.push_back(node);
visited[node] = true;
dfs_enter[node] = dfs_f[node] = cnt++;
for (int i : g[node]) {
if (dfs_enter[i] == -1) {
dfs(i);
}
if (visited[i]) dfs_f[node] = min(dfs_f[node], dfs_f[i]);
}
if (dfs_f[node] == dfs_enter[node]) {
vector<int> comp;
while (true) {
int curr = st.back();
st.pop_back();
visited[curr] = false;
comp.push_back(curr);
if (curr == node) break;
}
if (comp.size() > 1) {
for (int i : comp) cycle[i] = true;
}
}
}
bool dfscomp(int node) {
if (visited[node]) return false;
visited[node] = true;
bool check = false;
if (cycle[node]) check = true;
for (int i : dg[node]) {
if (!visited[i]) {
check |= dfscomp(i);
}
}
return check;
}
int main() {
cin >> n >> m;
int u, v;
for (int i = 0; i < m; i++) {
cin >> u >> v;
g[u].push_back(v);
dg[u].push_back(v);
dg[v].push_back(u);
}
memset(dfs_enter, -1, sizeof(dfs_enter));
for (int i = 1; i <= n; i++) {
if (dfs_enter[i] == -1) dfs(i);
}
int components = 0, cycles = 0;
memset(visited, false, sizeof(visited));
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
components++;
cycles += dfscomp(i);
}
}
int result = n - (components - cycles);
cout << result << "\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;
long long gcd(long long a, long long b) {
long long r;
while (b != 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
const int maxn = 100010;
int n, m;
vector<int> adj1[maxn];
vector<int> adj2[maxn];
vector<int> tmp;
int vis1[maxn];
int vis2[maxn];
int iscyc;
void dfs1(int u) {
vis1[u] = 1;
tmp.push_back(u);
for (int i = 0; i < int((adj1[u]).size()); i++) {
int v = adj1[u][i];
if (!vis1[v]) dfs1(v);
}
}
void dfs2(int u) {
vis2[u] = 1;
for (int i = 0; i < int((adj2[u]).size()); i++) {
int v = adj2[u][i];
if (vis2[v] == 1) iscyc = 1;
if (!vis2[v]) dfs2(v);
}
vis2[u] = 2;
}
void solve() {
memset(vis1, 0, sizeof(vis1));
memset(vis2, 0, sizeof(vis2));
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
a--;
b--;
adj1[a].push_back(b);
adj1[b].push_back(a);
adj2[a].push_back(b);
}
int ans = 0;
for (int i = 0; i < n; i++)
if (!vis1[i]) {
tmp.clear();
dfs1(i);
iscyc = 0;
for (int j = 0; j < int((tmp).size()); j++) {
int u = tmp[j];
if (!vis2[u]) dfs2(u);
}
ans += int((tmp).size()) + iscyc - 1;
}
printf("%d", ans);
}
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;
vector<int> g[100005], f[100005], vc;
int used[100005], n, m, cycle;
bool visit[100005];
void dfs(int i) {
int j, x;
used[i] = 1;
for (j = 0; j < g[i].size(); j++) {
x = g[i][j];
if (used[x] == 1) cycle = 1;
if (!used[x]) dfs(x);
}
used[i] = 2;
}
void dfsu(int i) {
if (visit[i]) return;
int j;
visit[i] = true;
vc.push_back(i);
for (j = 0; j < f[i].size(); j++) dfsu(f[i][j]);
}
int main() {
int i, j, a, b, res = 0;
scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++) {
g[i].clear();
f[i].clear();
}
for (i = 0; i < m; i++) {
scanf("%d %d", &a, &b);
g[a].push_back(b);
f[a].push_back(b);
f[b].push_back(a);
}
memset(visit, false, sizeof(visit));
memset(used, 0, sizeof(used));
for (i = 1; i <= n; i++) {
if (!visit[i]) {
cycle = 0;
vc.clear();
dfsu(i);
for (j = 0; j < vc.size(); j++)
if (!used[vc[j]]) dfs(vc[j]);
res += vc.size() - 1 + cycle;
}
}
printf("%d", 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;
int a[100000];
int par[100000];
vector<int> v[100000];
vector<int> w[100000];
int find(int x) {
if (par[x] == x) return x;
return par[x] = find(par[x]);
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
par[x] = y;
}
int main() {
int n, m, ans = 0, i, j;
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++) par[i] = i;
for (i = 0; i < m; i++) {
int x, y;
scanf("%d %d", &x, &y);
x--;
y--;
a[y]++;
v[x].push_back(y);
unite(x, y);
}
for (i = 0; i < n; i++) w[find(i)].push_back(i);
for (i = 0; i < n; i++) {
if (w[i].size() >= 2) {
int c = 0;
queue<int> q;
for (j = 0; j < w[i].size(); j++) {
if (a[w[i][j]] == 0) q.push(w[i][j]);
}
while (!q.empty()) {
int x = q.front();
q.pop();
c++;
for (j = 0; j < v[x].size(); j++) {
a[v[x][j]]--;
if (a[v[x][j]] == 0) q.push(v[x][j]);
}
}
if (c == w[i].size()) {
ans += w[i].size() - 1;
} else {
ans += w[i].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>
using namespace std;
const double PI = acos(-1.0);
const long long INF = 1e9 + 47;
const long long LINF = INF * INF;
const int MAX = 100 * 1000 + 7;
vector<int> g[MAX], gr[MAX];
int used[MAX];
vector<int> order, component;
void dfs1(int v) {
used[v] = 1;
for (int i = (0); i < ((int)((g[v]).size())); ++i)
if (!used[g[v][i]]) dfs1(g[v][i]);
order.push_back(v);
}
void dfs2(int v) {
used[v] = 1;
component.push_back(v);
for (int i = (0); i < ((int)((gr[v]).size())); ++i)
if (!used[gr[v][i]]) dfs2(gr[v][i]);
}
int col[MAX];
vector<int> G[MAX];
set<int> foo;
int cnt;
void dfs(int v) {
cnt++;
foo.insert(col[v]);
used[v] = 1;
for (int i = (0); i < ((int)((G[v]).size())); ++i)
if (!used[G[v][i]]) dfs(G[v][i]);
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = (0); i < (m); ++i) {
int a, b;
cin >> a >> b;
a--;
b--;
g[a].push_back(b);
gr[b].push_back(a);
G[a].push_back(b);
G[b].push_back(a);
}
memset(used, 0, sizeof(used));
for (int i = 0; i < n; ++i)
if (!used[i]) dfs1(i);
int ans = 0;
memset(used, 0, sizeof(used));
int color = 1;
for (int i = (0); i < (n); ++i) {
int v = order[n - 1 - i];
if (!used[v]) {
dfs2(v);
ans += (int)((component).size()) - 1 + ((int)((component).size()) > 1);
for (int j = (0); j < ((int)((component).size())); ++j)
col[component[j]] = color;
color++;
component.clear();
}
}
memset(used, 0, sizeof(used));
ans = 0;
for (int i = (0); i < (n); ++i)
if (!used[i]) {
foo.clear();
cnt = 0;
dfs(i);
ans += cnt - 1;
ans += (cnt != (int)((foo).size()));
}
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;
int n, m, t, r, rez;
vector<int> G[100005], GT[100005], C[100005];
vector<int> H[100005];
char viz[100005];
struct nod {
int a, b;
};
nod A[100005];
bool mark[100005], good[100005];
void read() {
scanf("%d%d", &n, &m);
int x, y;
while (m) {
scanf("%d%d", &x, &y);
mark[x] = mark[y] = true;
H[x].push_back(y);
H[y].push_back(x);
G[x].push_back(y);
GT[y].push_back(x);
m--;
}
}
void dfs1(int nod) {
viz[nod] = 1;
t++;
int i;
for (i = 0; i < (int)G[nod].size(); i++)
if (!viz[G[nod][i]]) dfs1(G[nod][i]);
A[++r].a = nod;
A[r].b = ++t;
}
void dfs2(int nod) {
viz[nod] = 1;
int i;
C[rez].push_back(nod);
for (i = 0; i < (int)GT[nod].size(); i++)
if (!viz[GT[nod][i]]) dfs2(GT[nod][i]);
}
void solve() {
int i;
for (i = 1; i <= n; i++)
if (!viz[i]) dfs1(i);
memset(viz, 0, sizeof(viz));
for (i = r; i >= 1; i--)
if (!viz[A[i].a]) {
rez++;
dfs2(A[i].a);
}
}
bool hasCycle;
int compSize;
void dfsComp(int node) {
viz[node] = true;
compSize++;
if (good[node]) hasCycle = true;
int x;
for (int i = 0; i < (int)H[node].size(); i++) {
x = H[node][i];
if (!viz[x]) dfsComp(x);
}
}
void show() {
int i, res = 0;
for (i = 1; i <= rez; i++)
if (C[i].size() > 1)
for (int j = 0; j < (int)C[i].size(); j++) good[C[i][j]] = true;
memset(viz, false, sizeof(viz));
for (int i = 1; i <= n; i++)
if (mark[i] && !viz[i]) {
hasCycle = false;
compSize = 0;
dfsComp(i);
if (hasCycle)
res += compSize;
else
res += compSize - 1;
}
printf("%d\n", res);
}
int main() {
read();
solve();
show();
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 + 1000;
const int maxE = maxN << 1;
int n, m;
int h[maxN], nxt[maxE], to[maxE], e;
int ind[maxN];
int vis[maxN];
int que[maxN], qh, qt;
int que2[maxN], qh2, qt2;
int main() {
e = 0;
memset(h, -1, sizeof h);
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; ++i) {
int u, v;
scanf("%d %d", &u, &v);
++ind[v];
to[e] = v, nxt[e] = h[u], h[u] = e++;
to[e] = u, nxt[e] = h[v], h[v] = e++;
}
int ans = 0;
for (int i = 1; i <= n; ++i)
if (!vis[i]) {
vis[i] = 1;
que[qh = qt = 0] = i;
qh2 = 0, qt2 = -1;
while (qh <= qt) {
int u = que[qh++];
if (ind[u] == 0) que2[++qt2] = u;
for (int j = h[u]; j != -1; j = nxt[j]) {
int v = to[j];
if (!vis[v]) {
que[++qt] = v;
vis[v] = 1;
}
}
}
if (qt2 == -1)
ans += qh;
else {
int flg = qt;
while (qh2 <= qt2) {
int u = que2[qh2++];
for (int j = h[u]; j != -1; j = nxt[j]) {
if (j & 1) continue;
int v = to[j];
--ind[v];
if (ind[v] == 0) que2[++qt2] = v;
}
}
ans += qh - (qh2 == qh);
}
}
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 maxn = 100100;
int n, m;
vector<int> arc[maxn], meta[maxn];
stack<int> stk;
int ind, ans;
int dis[maxn], low[maxn];
bool vs[maxn];
int T;
int sccid[maxn];
int cycle[maxn];
void tarjan(int u) {
vs[u] = true;
dis[u] = low[u] = T++;
stk.push(u);
for (int i = 0; i < arc[u].size(); i++) {
int v = arc[u][i];
if (dis[v] == -1) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (vs[v])
low[u] = min(low[u], dis[v]);
}
if (low[u] == dis[u]) {
int scc = 0;
while (1) {
int v = stk.top();
stk.pop();
scc++;
vs[v] = false;
sccid[v] = ind;
if (v == u) break;
}
if (scc != 1) {
cycle[ind] = 1;
}
ind++;
}
}
bool cycles = false;
int dfs(int s) {
vs[s] = true;
int sum = 1;
if (cycle[sccid[s]] == 1) cycles = true;
for (int i = 0; i < meta[s].size(); i++) {
int j = meta[s][i];
if (!vs[j]) sum += dfs(j);
}
return sum;
}
int main() {
scanf("%d %d", &n, &m);
while (m--) {
int a, b;
scanf("%d%d", &a, &b);
arc[a].push_back(b);
meta[a].push_back(b);
meta[b].push_back(a);
}
for (int i = 1; i <= n; i++) {
dis[i] = -1;
}
for (int i = 1; i <= n; i++)
if (dis[i] == -1) tarjan(i);
for (int i = 1; i <= n; i++) {
if (!vs[i]) {
cycles = false, ans += (dfs(i) - 1);
if (cycles) ans++;
}
}
printf("%d", 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;
void prologue() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
const int MAX = 100007;
bool visited[MAX];
vector<vector<int>> g, rg;
vector<int> finish;
vector<int> scc;
void ddfs(int node) {
if (visited[node]) return;
visited[node] = true;
for (int i = 0; i < g[node].size(); ++i) {
ddfs(g[node][i]);
}
finish.push_back(node);
}
void rddfs(int node, int scc_num) {
if (visited[node]) return;
visited[node] = true;
scc[node] = scc_num;
for (int i = 0; i < rg[node].size(); ++i) {
rddfs(rg[node][i], scc_num);
}
}
bool dfs(int node) {
if (visited[node]) return false;
visited[node] = true;
bool cycle_found = false;
for (int i = 0; i < g[node].size(); ++i) {
cycle_found |= (scc[node] == scc[g[node][i]]);
cycle_found |= dfs(g[node][i]);
}
for (int i = 0; i < rg[node].size(); ++i) {
cycle_found |= (scc[node] == scc[rg[node][i]]);
cycle_found |= dfs(rg[node][i]);
}
return cycle_found;
}
int main() {
prologue();
int n, m;
cin >> n >> m;
g.assign(n, decltype(g)::value_type());
rg.assign(n, decltype(rg)::value_type());
scc.assign(n, 0);
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
g[u - 1].push_back(v - 1);
rg[v - 1].push_back(u - 1);
}
memset(visited, 0, sizeof(visited));
for (int i = 0; i < n; ++i) {
if (!visited[i]) ddfs(i);
}
memset(visited, 0, sizeof(visited));
int scc_num = 0;
for (int i = finish.size() - 1; i >= 0; --i) {
if (!visited[finish[i]]) rddfs(finish[i], ++scc_num);
}
memset(visited, 0, sizeof(visited));
int no_cycles = 0;
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
no_cycles += !dfs(i);
}
}
cout << n - no_cycles;
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> g1[111111], g2[111111], dfn, g3[111111];
int N, M, C[111111], gcnt, gnum, P[111111];
int ans, S[111111], chk;
void dfs(int node) {
int i;
C[node] = 1;
for (i = 0; i < g1[node].size(); i++)
if (!C[g1[node][i]]) dfs(g1[node][i]);
dfn.push_back(node);
}
void dfs2(int node) {
int i;
C[node] = 1;
P[node] = gcnt;
gnum++;
for (i = 0; i < g2[node].size(); i++)
if (!C[g2[node][i]]) dfs2(g2[node][i]);
}
void dfs3(int node) {
int i;
C[node] = 1;
gnum++;
if (S[node]) chk = 1;
for (i = 0; i < g3[node].size(); i++)
if (!C[g3[node][i]]) dfs3(g3[node][i]);
}
int main() {
int i, j, a, b;
scanf("%d%d", &N, &M);
for (i = 1; i <= M; i++) {
scanf("%d%d", &a, &b);
g1[a].push_back(b);
g2[b].push_back(a);
}
for (i = 1; i <= N; i++)
if (!C[i]) dfs(i);
memset(C, 0, sizeof C);
for (i = dfn.size() - 1; i >= 0; i--) {
if (!C[dfn[i]]) {
gcnt++;
gnum = 0;
dfs2(dfn[i]);
if (gnum > 1) {
ans += gnum - 1;
S[gcnt] = 1;
}
}
}
for (i = 1; i <= N; i++) {
for (j = 0; j < g1[i].size(); j++) {
if (P[i] == P[g1[i][j]]) continue;
g3[P[i]].push_back(P[g1[i][j]]);
g3[P[g1[i][j]]].push_back(P[i]);
}
}
memset(C, 0, sizeof C);
for (i = 1; i <= gcnt; i++) {
if (!C[i]) {
gnum = 0;
chk = 0;
dfs3(i);
if (chk)
ans += (gnum);
else
ans += gnum - 1;
}
}
printf("%d", 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 MAXN = 1e5 + 10;
struct edge {
int u, v, st, nt;
} e[MAXN * 2];
vector<int> lis;
int hd[MAXN], etot, used[MAXN], in[MAXN], u[MAXN], v[MAXN];
void addedge(int u, int v, int st) {
e[etot].u = u;
e[etot].v = v;
e[etot].st = st;
e[etot].nt = hd[u];
hd[u] = etot++;
}
void dfs(int p) {
used[p] = 1;
lis.push_back(p);
for (int i = hd[p]; ~i; i = e[i].nt) {
if (used[e[i].v]) continue;
dfs(e[i].v);
}
}
queue<int> Q;
int topsort() {
for (int i = 0; i < (int)lis.size(); i++)
if (!in[lis[i]]) Q.push(lis[i]);
int cnt = 0, u;
for (; !Q.empty();) {
cnt++;
u = Q.front();
Q.pop();
for (int i = hd[u]; ~i; i = e[i].nt) {
if (!e[i].st) continue;
in[e[i].v]--;
if (!in[e[i].v]) Q.push(e[i].v);
}
}
return cnt == (int)lis.size();
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
etot = 0;
memset(hd, -1, sizeof(hd));
for (int i = 0; i < m; i++) {
scanf("%d%d", u + i, v + i);
addedge(u[i], v[i], 1);
addedge(v[i], u[i], 0);
in[v[i]]++;
}
int ans = 0;
for (int i = 1; i < n + 1; i++) {
lis.clear();
if (!used[i]) dfs(i);
if ((int)lis.size() == 0) continue;
ans += (int)lis.size() - topsort();
}
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.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.StringTokenizer;
public class Main implements Runnable {
ArrayList<Integer>[] v = new ArrayList[100100];
ArrayList<Integer>[] vo = new ArrayList[100100];
int[] cs = new int[100100];
boolean[] was = new boolean[100100];
void dfsts(int q, ArrayList<Integer> ts) {
was[q] = true;
for (int i : v[q]) {
if (!was[i]) dfsts(i, ts);
}
ts.add(q);
}
void dfscs(int q, int csc) {
cs[q] = csc;
for (int i : vo[q]) {
if (cs[i] == 0) dfscs(i, csc);
}
}
void solve() {
int n = nextInt();
int m = nextInt();
for (int i = 1; i <= n; i++) {
v[i] = new ArrayList<Integer>();
vo[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
int b = nextInt(), e = nextInt();
v[b].add(e);
vo[b].add(e);
vo[e].add(b);
}
int csc = 1;
for (int i = 1; i <= n; i++) {
if (cs[i] == 0) {
dfscs(i, csc++);
}
}
csc--;
int ans = n - csc;
ArrayList<Integer> ts = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
if (!was[i]) dfsts(i, ts);
}
int[] nn = new int[100100];
for (int i = ts.size() - 1; i >= 0; i--) {
nn[ts.get(i)] = i;
}
boolean[] csw = new boolean[100100];
for (int i = 1; i <= n; i++) {
for (int j : v[i]) {
if (nn[i] < nn[j]) {
if (!csw[cs[i]]) {
csw[cs[i]] = true;
ans++;
}
}
}
}
out.println(ans);
}
int nextInt() {
return Integer.parseInt(nextToken());
}
String nextToken() {
try {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
return st.nextToken();
} catch (Exception e) {
return null;
}
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
public static void main(String[] args) {
new Thread(null, new Main(), "name", 1 << 28).start();
}
}
| 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, vis[N], du[N];
vector<int> a[N], b[N];
queue<int> q;
int dfs(int x) {
vis[x] = 1;
int ans = 1;
if (du[x] == 0) q.push(x);
for (int i = 0; i < a[x].size(); i++)
if (!vis[a[x][i]]) ans += dfs(a[x][i]);
return ans;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d%d", &x, &y);
a[x].push_back(y);
a[y].push_back(x);
b[x].push_back(y);
du[y]++;
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (vis[i]) continue;
int n = dfs(i), dqsum = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
dqsum++;
for (int i = 0; i < b[x].size(); i++)
if (--du[b[x][i]] == 0) q.push(b[x][i]);
}
if (dqsum == n)
ans += n - 1;
else
ans += n;
}
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> order, all[100001], g[100001];
int n, m, x, y, ans, color[100001], i;
bool cycle, u[100001];
void dfs1(int v) {
u[v] = true;
order.push_back(v);
for (int j = 0; j < all[v].size(); j++) {
int to = all[v][j];
if (!u[to]) dfs1(to);
}
}
void dfscolor(int v) {
color[v] = 1;
for (int j = 0; j < g[v].size(); j++) {
int to = g[v][j];
if (color[to] == 0)
dfscolor(to);
else if (color[to] == 1)
cycle = 0;
}
color[v] = 2;
}
int main() {
srand(time(NULL));
cin >> n >> m;
for (i = 1; i <= m; i++) {
cin >> x >> y;
all[x].push_back(y);
all[y].push_back(x);
g[x].push_back(y);
}
for (i = 1; i <= n; i++)
if (!u[i]) {
order.clear();
dfs1(i);
cycle = 1;
for (int j = 0; j < order.size(); ++j)
if (color[order[j]] == 0) dfscolor(order[j]);
ans += order.size() - cycle;
}
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;
const int inf = int(1e9);
const double eps = 1e-9;
const double pi = 4 * atan(double(1));
const int N = int(1e5) + 100;
bool cyc;
int sz;
int use[N];
bool used[N];
int lst[N];
vector<int> g[N], g2[N];
void dfs1(int v) {
used[v] = true;
lst[sz++] = v;
for (int i = 0; i < int((g[v]).size()); ++i) {
if (!used[g[v][i]]) {
dfs1(g[v][i]);
}
}
}
void dfs2(int v) {
use[v] = 1;
for (int i = 0; i < int((g2[v]).size()); ++i) {
if (use[g2[v][i]] == 0) {
dfs2(g2[v][i]);
} else if (use[g2[v][i]] == 1) {
cyc = true;
}
}
use[v] = 2;
}
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);
--a;
--b;
g[a].push_back(b);
g[b].push_back(a);
g2[a].push_back(b);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (!used[i]) {
sz = 0;
dfs1(i);
cyc = false;
for (int j = 0; j < sz; ++j) {
if (use[lst[j]] == 0) {
dfs2(lst[j]);
}
}
if (cyc) {
ans += sz;
} else {
ans += sz - 1;
}
}
}
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 n, m, color[100010], cont_color[100010];
vector<int> adj[100010], radj[100010], st;
bool ctrl[100010];
int g(int ind) {
int res = cont_color[color[ind]] == 1;
ctrl[ind] = true;
for (int i = 0; i < adj[ind].size(); i++) {
if (!ctrl[adj[ind][i]]) res &= g(adj[ind][i]);
}
for (int i = 0; i < radj[ind].size(); i++) {
if (!ctrl[radj[ind][i]]) res &= g(radj[ind][i]);
}
return res;
}
void dfs(int ind) {
ctrl[ind] = true;
for (int i = 0; i < adj[ind].size(); i++) {
if (!ctrl[adj[ind][i]]) dfs(adj[ind][i]);
}
st.push_back(ind);
}
void rdfs(int ind, int c) {
color[ind] = c;
ctrl[ind] = true;
for (int i = 0; i < radj[ind].size(); i++) {
if (!ctrl[radj[ind][i]]) rdfs(radj[ind][i], c);
}
}
void scc() {
for (int i = 1; i <= n; i++) {
if (!ctrl[i]) dfs(i);
}
memset(ctrl, false, sizeof(ctrl));
int c = 0;
for (int i = st.size() - 1; i >= 0; i--) {
if (!ctrl[st[i]]) rdfs(st[i], c++);
}
}
int main() {
cin >> n >> m;
for (int x, y, i = 0; i < m; i++) {
scanf("%d %d", &x, &y);
adj[x].push_back(y);
radj[y].push_back(x);
}
memset(ctrl, false, sizeof(ctrl));
memset(color, -1, sizeof(color));
memset(cont_color, 0, sizeof(cont_color));
scc();
for (int i = 1; i <= n; i++) cont_color[color[i]]++;
memset(ctrl, false, sizeof(ctrl));
int res = n;
for (int i = 1; i <= n; i++) {
if (!ctrl[i]) res -= g(i);
}
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<int> dfs_num;
vector<vector<int> > wccs;
vector<int> sccs;
vector<vector<int> > graph;
vector<vector<int> > graph_rev;
int wcc, leader;
stack<int> korasaju;
void dfs_aux(int v) {
dfs_num[v] = 1;
wccs[wcc].push_back(v);
for (int i = 0; i < graph[v].size(); i++) {
int u = graph[v][i];
if (dfs_num[u] != 1) dfs_aux(u);
}
for (int i = 0; i < graph_rev[v].size(); i++) {
int u = graph_rev[v][i];
if (dfs_num[u] != 1) dfs_aux(u);
}
}
void dfs_wccs() {
for (int i = 0; i < graph.size(); i++) {
if (dfs_num[i] == 0) {
dfs_aux(i);
wcc++;
}
}
}
void dfs_aux_korasaju(int v) {
dfs_num[v] = 1;
for (int i = 0; i < graph[v].size(); i++) {
int u = graph[v][i];
if (dfs_num[u] != 1) dfs_aux_korasaju(u);
}
korasaju.push(v);
}
void dfs_korasaju() {
for (int i = 0; i < graph.size(); i++) {
if (dfs_num[i] == 0) {
dfs_aux_korasaju(i);
}
}
}
void dfs_rev_aux(int v) {
dfs_num[v] = 1;
sccs[v] = leader;
for (int i = 0; i < graph_rev[v].size(); i++) {
int u = graph_rev[v][i];
if (dfs_num[u] != 1) dfs_rev_aux(u);
}
}
void dfs_rev() {
while (korasaju.size()) {
int v = korasaju.top();
korasaju.pop();
if (dfs_num[v] == 0) {
leader = v;
dfs_rev_aux(v);
}
}
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
int n, m;
cin >> n >> m;
graph.clear();
graph.resize(n);
graph_rev.clear();
graph_rev.resize(n);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
graph[a].push_back(b);
graph_rev[b].push_back(a);
}
dfs_num.assign(n, 0);
wccs.clear();
wccs.resize(n);
dfs_wccs();
dfs_num.assign(n, 0);
dfs_korasaju();
dfs_num.assign(n, 0);
sccs.assign(n, -1);
dfs_rev();
int ans = 0;
for (int i = 0; i < wcc; i++) {
bool has_cycle = false;
for (int j = 0; j < wccs[i].size(); j++) {
has_cycle |= sccs[wccs[i][j]] != wccs[i][j];
}
ans += wccs[i].size() - (has_cycle ? 0 : 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 | #include <bits/stdc++.h>
using namespace std;
const int Mod = 1e9 + 7;
inline int FIX(long long a) { return (a % Mod + Mod) % Mod; }
const int N = 1e5 + 5;
vector<int> E[N];
int n, m;
int fa[N];
int find_set(int rt) { return fa[rt] == rt ? rt : (fa[rt] = find_set(fa[rt])); }
void union_set(int x, int y) {
fa[find_set(x)] = find_set(y);
return;
}
int cnt[N], used[N], circle[N];
void dfs(int rt) {
used[rt] = 1;
for (auto x : E[rt]) {
if (used[x] == 0) {
dfs(x);
} else if (used[x] == 1) {
circle[find_set(x)] = 1;
}
}
used[rt] = 2;
return;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d %d", &a, &b);
E[a].push_back(b);
union_set(a, b);
}
for (int i = 1; i <= n; i++) {
if (used[i] == 0) dfs(i);
}
for (int i = 1; i <= n; i++) {
cnt[find_set(i)]++;
}
int res = 0;
for (int i = 1; i <= n; i++) {
if (find_set(i) == i) {
res += (circle[i] == 1 ? cnt[i] : cnt[i] - 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 | import java.util.*;
public class HW1_ex5 {
static ArrayList<Node> outOfNode;
static int k;
static int[] component;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
Graphs firstGraph = new Graphs(n);
// Graphs secondGraph = new Graphs(n);
outOfNode = new ArrayList<>();
for (int i = 0; i < m; i++) {
int first = scanner.nextInt();
int second = scanner.nextInt();
firstGraph.addEdge(first - 1, second - 1);
// .addEdge(second - 1, first - 1);
}
firstGraph.dfs();
int answer = n;
Collections.sort(outOfNode, Node.compareTime);
for (int i = 0; i < firstGraph.size; i++) {
firstGraph.visited[i] = false;
firstGraph.componentNum = 0;
firstGraph.components[i] = 0;
}
k = 0;
for (int i = outOfNode.size() - 1; i >= 0; i--) {
if (!firstGraph.visited[outOfNode.get(i).num]) {
firstGraph.dfsVisit2(outOfNode.get(i).num);
k++;
if (firstGraph.numOfEverySCC != 1) {
// answer += firstGraph.numOfEverySCC;
firstGraph.numOfEverySCC = 0;
}
}
}
component = new int[k];
for (int i = 0; i < n; i++) {
component[firstGraph.components[i]]++;
}
for (int i = 0; i < firstGraph.size; i++) {
firstGraph.visited[i] = false;
}
for (int i = 0; i < n; i++) {
if (!firstGraph.visited[i]) {
if (firstGraph.dfs2(i)) {
answer--;
}
}
}
System.out.println(answer);
}
}
class Graphs {
int size;
boolean[] visited;
LinkedList<Integer> adj[];
LinkedList<Integer> adj2[];
int time = 0;
Node[] nodes;
int numOfEverySCC = 0;
// ArrayList<Integer> thisDfs;
// boolean see = false;
int componentNum;
int[] components;
public Graphs(int size) {
// thisDfs = new ArrayList<>();
this.size = size;
visited = new boolean[size];
adj = new LinkedList[size];
adj2 = new LinkedList[size];
components = new int[size];
nodes = new Node[size];
for (int i = 0; i < size; ++i) {
adj[i] = new LinkedList();
adj2[i] = new LinkedList();
nodes[i] = new Node(i);
}
}
public void addEdge(int v, int u) {
adj[v].add(u);
adj2[u].add(v);
}
public void dfsVisit(int v) {
visited[v] = true;
nodes[v].enter = time;
time++;
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
// numOfEverySCC++;
// components[n] = HW1_ex5.k;
dfsVisit(n);
}
}
nodes[v].out = time;
time++;
HW1_ex5.outOfNode.add(nodes[v]);
}
public void dfsVisit2(int v) {
visited[v] = true;
components[v]=HW1_ex5.k;
Iterator<Integer> i = adj2[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
numOfEverySCC++;
components[n] = HW1_ex5.k;
dfsVisit2(n);
}
}
}
public void dfs() {
for (int i = 0; i < size; i++) {
if (!visited[i]) {
dfsVisit(i);
}
}
}
public boolean dfs2(int v) {
visited[v] = true;
boolean visit = HW1_ex5.component[components[v]] == 1;
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visit &= dfs2(n);
}
}
Iterator<Integer> j = adj2[v].listIterator();
while (j.hasNext()) {
int n = j.next();
if (!visited[n]) {
visit &= dfs2(n);
}
}
return visit;
}
}
class Node {
int num;
int enter;
int out;
public Node(int num) {
this.num = num;
}
public static Comparator<Node> compareTime = new Comparator<Node>() {
public int compare(Node s1, Node s2) {
Integer w1 = s1.out;
Integer w2 = s2.out;
//ascending order
return w1.compareTo(w2);
}
};
} | 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;
using vint = vector<long long>;
using pint = pair<long long, long long>;
using vpint = vector<pint>;
template <typename A, typename B>
inline void chmin(A& a, B b) {
if (a > b) a = b;
}
template <typename A, typename B>
inline void chmax(A& a, B b) {
if (a < b) a = b;
}
template <class A, class B>
ostream& operator<<(ostream& ost, const pair<A, B>& p) {
ost << "{" << p.first << "," << p.second << "}";
return ost;
}
template <class T>
ostream& operator<<(ostream& ost, const vector<T>& v) {
ost << "{";
for (long long i = 0; i < v.size(); i++) {
if (i) ost << ",";
ost << v[i];
}
ost << "}";
return ost;
}
inline long long topbit(unsigned long long x) {
return x ? 63 - __builtin_clzll(x) : -1;
}
inline long long popcount(unsigned long long x) {
return __builtin_popcountll(x);
}
inline long long parity(unsigned long long x) { return __builtin_parity(x); }
namespace SCC {
void visit(const vector<vector<long long>>& G, vector<long long>& vs,
vector<long long>& used, long long v) {
used[v] = true;
for (auto u : G[v]) {
if (!used[u]) visit(G, vs, used, u);
}
vs.push_back(v);
}
void visit2(const vector<vector<long long>>& T, vector<long long>& used,
vector<long long>& comp, vector<long long>& vec, long long k,
long long v) {
comp[v] = k;
used[v] = true;
vec.push_back(v);
for (auto u : T[v]) {
if (!used[u]) visit2(T, used, comp, vec, k, u);
}
}
void decompose(const vector<vector<long long>>& G, vector<vector<long long>>& H,
vector<long long>& comp) {
vector<vector<long long>> T(G.size());
for (long long i = 0; i < G.size(); i++) {
for (auto v : G[i]) {
T[v].push_back(i);
}
}
comp.resize(G.size());
vector<long long> vs(G.size());
vector<long long> used(G.size());
for (long long i = 0; i < G.size(); i++) {
if (!used[i]) visit(G, vs, used, i);
}
reverse(vs.begin(), vs.end());
fill(used.begin(), used.end(), 0);
long long K = 0;
vector<vector<long long>> S;
for (auto v : vs) {
if (!used[v]) {
S.push_back(vector<long long>());
visit2(T, used, comp, S.back(), K++, v);
}
}
H.resize(K);
fill(used.begin(), used.end(), 0);
for (long long i = 0; i < K; i++) {
for (auto v : S[i]) {
for (auto u : G[v]) {
if (used[comp[u]] || comp[v] == comp[u]) continue;
used[comp[u]] = true;
H[comp[v]].push_back(comp[u]);
}
}
for (auto v : H[i]) used[v] = false;
}
}
} // namespace SCC
struct UnionFindTree {
vector<int32_t> par, sz;
vector<long long> cy;
UnionFindTree(int32_t n = 0) : par(n), sz(n), cy(n) {
for (int32_t i = 0; i < n; i++) {
par[i] = i;
sz[i] = 1;
}
}
int32_t find(int32_t x) { return x == par[x] ? x : par[x] = find(par[x]); }
void unite(int32_t x, int32_t y) {
x = find(x);
y = find(y);
if (x == y) return;
if (sz[x] < sz[y]) swap(x, y);
sz[x] += sz[y];
cy[x] |= cy[y];
par[y] = x;
}
bool same(int32_t x, int32_t y) { return find(x) == find(y); }
int32_t size(int32_t x) { return sz[find(x)]; }
};
signed main() {
long long N, M;
cin >> N >> M;
vector<vint> G(N);
for (long long i = 0; i < (M); i++) {
long long a, b;
cin >> a >> b;
a--;
b--;
G[a].emplace_back(b);
}
vector<vint> H;
vint comp;
SCC::decompose(G, H, comp);
vint cnt(H.size());
for (long long i = 0; i < (N); i++) cnt[comp[i]]++;
UnionFindTree uf(H.size());
for (long long i = 0; i < (N); i++)
for (auto j : G[i]) uf.unite(comp[i], comp[j]);
for (long long i = 0; i < (H.size()); i++)
if (cnt[i] > 1) uf.cy[uf.find(i)] = 1;
long long ans = N;
for (long long i = 0; i < (H.size()); i++)
if (uf.find(i) == i && uf.cy[i] == 0) 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 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100 * 1000 + 123;
int n, m, charger, charge[MAXN], miz;
vector<int> g[MAXN], rev[MAXN];
stack<int> st;
bool mark[MAXN], maze[MAXN], iss;
void inp();
void dfs(int);
void solve();
void rfs(int);
void cfs(int);
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
inp();
solve();
return 0;
}
void inp() {
cin >> n >> m;
int u, v;
for (int i = 0; i < m; i++) {
cin >> u >> v;
g[--u].push_back(--v), rev[v].push_back(u);
}
}
void dfs(int v) {
mark[v] = true;
for (int u : g[v])
if (!mark[u]) dfs(u);
st.push(v);
}
void solve() {
for (int i = 0; i < n; i++)
if (!mark[i]) dfs(i);
memset(mark, 0, sizeof mark);
while (!st.empty()) {
if (!mark[st.top()]) {
miz = 0;
rfs(st.top());
maze[charger] = (miz == 1);
charger++;
}
st.pop();
}
memset(mark, 0, sizeof mark);
int w = 0;
for (int i = 0; i < n; i++)
if (!mark[i]) {
iss = true;
cfs(i);
if (iss) w++;
}
cout << n - w;
}
void rfs(int v) {
mark[v] = true;
for (int u : rev[v])
if (!mark[u]) rfs(u);
charge[v] = charger;
miz++;
}
void cfs(int v) {
mark[v] = true;
for (int u : g[v])
if (!mark[u]) cfs(u);
for (int u : rev[v])
if (!mark[u]) cfs(u);
iss &= maze[charge[v]];
}
| 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;
struct Graph {
int n;
vector<vector<int>> adj;
vector<vector<int>> rev;
vector<bool> was;
vector<int> color;
vector<int> mark;
Graph(int _n)
: n(_n),
adj(_n + 1),
rev(_n + 1),
was(_n + 1),
color(_n + 1),
mark(_n + 1) {}
void addEdge(int a, int b) {
adj[a].push_back(b);
rev[b].push_back(a);
}
void clearWas() { fill(was.begin(), was.end(), false); }
void colorize(int v, int col) {
color[v] = col;
for (int u : adj[v])
if (color[u] == 0) colorize(u, col);
for (int u : rev[v])
if (color[u] == 0) colorize(u, col);
}
int countCompSize(int v) {
int result = 1;
was[v] = true;
for (int u : adj[v])
if (!was[u]) result += countCompSize(u);
for (int u : rev[v])
if (!was[u]) result += countCompSize(u);
return result;
}
bool findCycle(int v) {
was[v] = true;
mark[v] = 2;
for (int u : adj[v]) {
if (mark[u] == 2) return true;
if (mark[u] == 0 && findCycle(u)) return true;
}
mark[v] = 1;
return false;
}
};
struct DirectedGraph : Graph {
vector<int> color;
DirectedGraph(int _n) : Graph(_n), color(_n + 1) {}
void addEdge(int a, int b) { adj[a].push_back(b); }
void dfs(int v, vector<int> &order) {
was[v] = true;
for (int u : adj[v])
if (!was[u]) dfs(u, order);
order.push_back(v);
}
bool hasCycle(int v) {
color[v] = 2;
for (int u : adj[v]) {
if (color[u] == 2) return true;
if (color[u] == 0 && hasCycle(u)) return true;
}
color[v] = 1;
return false;
}
};
struct UndirectedGraph : Graph {
UndirectedGraph(int _n) : Graph(_n) {}
void addEdge(int a, int b) {
adj[a].push_back(b);
adj[b].push_back(a);
}
int countSize(int v) {
int result = 1;
was[v] = true;
for (int u : adj[v])
if (!was[u]) result += countSize(u);
return result;
}
};
int main() {
ios_base::sync_with_stdio(false);
int n, m;
cin >> n >> m;
Graph g(n);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
g.addEdge(a, b);
}
int comps = 0;
for (int v = 1; v <= n; ++v)
if (g.color[v] == 0) g.colorize(v, ++comps);
vector<int> compSize(comps + 1);
for (int v = 1; v <= n; ++v)
if (!g.was[v]) compSize[g.color[v]] += g.countCompSize(v);
g.clearWas();
vector<bool> hasCycle(comps + 1);
for (int v = 1; v <= n; ++v)
if (!g.was[v] && g.findCycle(v)) hasCycle[g.color[v]] = true;
int result = 0;
for (int c = 1; c <= comps; ++c)
if (hasCycle[c])
result += compSize[c];
else
result += compSize[c] - 1;
cout << result << 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 | // package CF;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
static ArrayList<Integer> [] adj;
static int [] vis;
static boolean [] e;
static UnionFind uf;
static final int UN = 0, EX = 1, VIS = 2;
static void dfs(int u)
{
vis[u] = EX;
for(int v:adj[u]){
uf.unionSet(u, v);
if(vis[v] == UN)
dfs(v);
else if(vis[v] == EX)
e[uf.findSet(v)] = true;
}
vis[u] = VIS;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), m = sc.nextInt();
adj = new ArrayList[n];
for (int i = 0; i < adj.length; i++) {
adj[i] = new ArrayList<>();
}
while(m-->0){
int a = sc.nextInt()-1, b = sc.nextInt()-1;
adj[a].add(b);
}
vis = new int[n];
e = new boolean[n];
uf = new UnionFind(n);
for (int i = 0; i < n; i++) {
if(vis[i] == UN)
dfs(i);
}
int ans = 0;
for (int i = 0; i < n; i++) {
int p = uf.findSet(i);
if(p != i) continue;
ans += uf.sizeOfSet(p) -1 + (e[p]?1:0);
}
out.println(ans);
out.flush();
out.close();
}
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]; e[x] |= e[y]; }
else
{ p[x] = y; setSize[y] += setSize[x];
e[y] |= e[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 Scanner(FileReader fileReader) {
br = new BufferedReader(fileReader);
}
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 boolean ready() throws IOException {
return br.ready();
}
}
} | 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;
vector<int> G[100005], g[100005], st;
int vis[100005];
int mk[100005];
int flag;
void dfs(int v) {
st.push_back(v);
vis[v] = 1;
for (int i = 0; i < G[v].size(); i++) {
int to = G[v][i];
if (!vis[to]) dfs(to);
}
}
void dfs2(int v) {
mk[v] = 1;
for (int i = 0; i < g[v].size(); i++) {
int to = g[v][i];
if (mk[to] == 0)
dfs2(to);
else if (mk[to] == 1) {
flag = 1;
}
}
mk[v] = 2;
}
int main() {
int n, m, x, y;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
G[i].clear();
g[i].clear();
}
for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
g[x].push_back(y);
}
int ans = n;
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
flag = 0;
dfs(i);
for (int j = 0; j < st.size(); j++) mk[st[j]] = 0;
for (int j = 0; j < st.size(); j++) {
int to = st[j];
if (mk[to] == 0) dfs2(to);
}
if (flag == 0) ans--;
st.clear();
}
}
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;
template <typename T>
struct Pt {
T x, y;
void scan() { cin >> x >> y; }
};
template <typename T>
inline T sqr(const T& a) {
return a * a;
}
template <typename T>
inline int sign(const T& a) {
return a < 0 ? -1 : a > 0;
}
void task();
int main() {
task();
return 0;
}
struct T {
int to;
bool is_rev;
};
struct S {
vector<T> v;
int comp_id;
S() : comp_id(0){};
};
vector<S> g;
bool comp_circle[int(1e5) + 10];
int comp_sz[int(1e5) + 10];
int comp_cnt = 0;
int n, m;
int visit[int(1e5) + 10];
void bfs(int v) {
if (g[v].comp_id) return;
++comp_cnt;
queue<int> q;
q.push(v);
while (!q.empty()) {
int p = q.front();
q.pop();
if (g[p].comp_id != 0) continue;
g[p].comp_id = comp_cnt;
++comp_sz[comp_cnt];
for (auto& to : g[p].v) q.push(to.to);
}
}
bool dfs(int v) {
if (visit[v]) return false;
visit[v] = 1;
for (auto& x : g[v].v)
if (x.is_rev == false) {
if (visit[x.to] == 1 || dfs(x.to)) return true;
}
visit[v] = 2;
return false;
}
void task() {
ios_base::sync_with_stdio(0);
cin >> n >> m;
g.resize(n);
for (int i = 0; i < m; ++i) {
int f, t;
cin >> f >> t;
--f, --t;
g[f].v.push_back({t, 0});
g[t].v.push_back({f, 1});
}
for (int i = 0; i < n; ++i) bfs(i);
for (int i = 0; i < n; ++i)
if (dfs(i)) {
comp_circle[g[i].comp_id] = 1;
}
int ans = n;
for (int i = 1; i <= comp_cnt; ++i) ans -= !comp_circle[i];
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;
struct edge {
int to;
int next;
} e[210000], E[310000];
int head[200010], bian, bian2, head2[200010];
void add(int x, int y) {
bian++;
e[bian].next = head[x];
head[x] = bian;
e[bian].to = y;
}
void add2(int x, int y) {
bian2++;
E[bian2].next = head2[x];
head2[x] = bian2;
E[bian2].to = y;
}
int low[200010], dnf[200010], vs[200010], cnt, z, sh[200010], mh[200010];
stack<int> q;
void targan(int x) {
cnt++;
low[x] = dnf[x] = cnt;
q.push(x);
vs[x] = 1;
for (int i = head[x]; i != -1; i = e[i].next) {
int y = e[i].to;
if (!dnf[y]) {
targan(y);
low[x] = min(low[x], low[y]);
} else if (vs[y])
low[x] = min(low[x], dnf[y]);
}
if (low[x] == dnf[x]) {
z++;
while (1) {
int p = q.top();
q.pop();
sh[p] = z;
mh[z]++;
vs[p] = 0;
if (p == x) break;
}
}
}
int pp;
int vas[200100];
void dfs(int x) {
vas[x] = 1;
pp++;
for (int i = head2[x]; i != -1; i = E[i].next) {
int y = E[i].to;
if (!vas[y]) {
dfs(y);
}
}
}
int main() {
int n, m;
while (scanf("%d%d", &n, &m) != EOF) {
memset(head, -1, sizeof(head));
bian = 0;
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
cnt = z = 0;
memset(low, 0, sizeof(low));
memset(mh, 0, sizeof(mh));
memset(dnf, 0, sizeof(dnf));
memset(sh, 0, sizeof(sh));
memset(vs, 0, sizeof(vs));
for (int i = 1; i <= n; i++) {
if (!dnf[i]) targan(i);
}
int zz = 0;
memset(head2, -1, sizeof(head2));
bian2 = 0;
for (int j = 1; j <= n; j++) {
for (int i = head[j]; i != -1; i = e[i].next) {
int y = e[i].to;
add2(j, y);
add2(y, j);
}
}
int tt = 0;
memset(vas, 0, sizeof(vas));
int ha[210000] = {0};
for (int i = 1; i <= z; i++) {
if (mh[i] >= 2) {
for (int j = 1; j <= n; j++) {
if (sh[j] == i && !vas[j]) {
tt++;
pp = 0;
dfs(j);
ha[tt] = pp;
break;
}
}
}
}
int qian = tt;
for (int j = 1; j <= n; j++) {
if (!vas[j]) {
tt++;
pp = 0;
dfs(j);
ha[tt] = pp;
}
}
for (int i = 1; i <= qian; i++) {
if (ha[i] >= 2) zz += ha[i];
}
for (int i = qian + 1; i <= tt; i++) zz += (ha[i] - 1);
printf("%d\n", zz);
}
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.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Kartik Singal (ka4tik)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
ArrayList<Integer> g[], gt[], gu[], cmps[];
int n;
boolean used[];
int comp[];
ArrayList<Integer> order;
void dfs1(int u) {
used[u] = true;
for (int i = 0; i < g[u].size(); i++) {
int v = g[u].get(i);
if (!used[v])
dfs1(v);
}
order.add(u);
}
void dfs2(int u, int cl) {
comp[u] = cl;
for (int i = 0; i < gt[u].size(); i++) {
int v = gt[u].get(i);
if (comp[v] == -1)
dfs2(v, cl);
}
}
int scc() {
order.clear();
for (int i = 0; i < n; i++)
used[i] = false;
for (int i = 0; i < n; i++)
if (!used[i])
dfs1(i);
for (int i = 0; i < comp.length; i++)
comp[i] = -1;
int c = 0;
for (int i = 0; i < n; i++) {
int v = order.get(n - i - 1);
if (comp[v] == -1)
dfs2(v, c++);
}
return c;
}
void dfs3(int u, int cl) {
used[u] = true;
cmps[cl].add(u);
for (int i = 0; i < gu[u].size(); i++) {
int v = gu[u].get(i);
if (!used[v])
dfs3(v, cl);
}
}
int find_components() {
int components = 0;
used = new boolean[n];
for (int i = 0; i < n; i++) used[i] = false;
for (int i = 0; i < n; i++)
if (!used[i])
dfs3(i, components++);
return components;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
used = new boolean[n];
comp = new int[n];
order = new ArrayList<Integer>();
int m = in.nextInt();
g = new ArrayList[n];
gt = new ArrayList[n];
gu = new ArrayList[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<Integer>();
gt[i] = new ArrayList<Integer>();
gu[i] = new ArrayList<Integer>();
}
TreeSet<Integer> set = new TreeSet<Integer>();
while (m-- > 0) {
int u = in.nextInt();
int v = in.nextInt();
u--;
v--;
set.add(u);
set.add(v);
g[u].add(v);
gt[v].add(u);
gu[v].add(u);
gu[u].add(v);
}
int components = scc();
int cnts[] = new int[components];
for (int i = 0; i < n; i++)
cnts[comp[i]]++;
cmps = new ArrayList[n];
for (int i = 0; i < cmps.length; i++)
cmps[i] = new ArrayList<Integer>();
int ans = 0;
int undirected_components = find_components();
for (int i = 0; i < undirected_components; i++) {
if (!set.contains(cmps[i].get(0)))
continue;
int mx = 0;
for (int j = 0; j < cmps[i].size(); j++) {
mx = Math.max(mx, cnts[comp[cmps[i].get(j)]]);
}
if (mx > 1)
ans += cmps[i].size();
else
ans += cmps[i].size() - 1;
}
out.println(ans);
}
}
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 int nextInt() {
return Integer.parseInt(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;
const int N = 100000 + 5;
int fa[N], cnt[N], ru[N];
vector<int> G[N];
queue<int> qu[N];
int n, m;
int find_fa(int x) { return fa[x] = fa[x] == x ? x : find_fa(fa[x]); }
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
int u, v;
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
G[u].push_back(v);
ru[v]++;
fa[find_fa(u)] = find_fa(v);
}
for (int i = 1; i <= n; i++) cnt[find_fa(i)]++;
for (int i = 1; i <= n; i++)
if (ru[i] == 0) {
qu[fa[i]].push(i);
}
int ans = 0;
for (int i = 1; i <= n; i++)
if (fa[i] == i) {
int sum = 0;
while (!qu[i].empty()) {
int u = qu[i].front();
qu[i].pop();
sum++;
for (int v : G[u]) {
if ((--ru[v]) == 0) qu[i].push(v);
}
}
ans += cnt[i] - (sum == cnt[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 | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
FastScanner in = new FastScanner();
PrintWriter out;
ArrayList<Integer> g[];
ArrayList<Integer> rg[];
LinkedList<Integer> vl = new LinkedList<>();
boolean vis[];
int comp[];
int compSize[];
boolean cycle;
public void solve() throws IOException {
int N = in.nextInt();
int M = in.nextInt();
g = new ArrayList[N];
rg = new ArrayList[N];
vis = new boolean[N];
comp = new int[N];
compSize = new int[N];
Arrays.fill(vis, false);
for (int n = 0; n < N; n++) {
g[n] = new ArrayList();
rg[n] = new ArrayList();
}
for (int m = 0; m < M; m++) {
int A = in.nextInt() - 1;
int B = in.nextInt() - 1;
g[A].add(B);
rg[B].add(A);
}
for (int v = 0; v < N; v++) {
if (!vis[v]) {
dfs(v);
}
}
Arrays.fill(vis, false);
int c = 0;
for (int v: vl) {
if (!vis[v]) {
rdfs(v, c++);
}
}
Arrays.fill(vis, false);
int r = 0;
for (int n = 0; n < N; n++) {
if (!vis[n]) {
cycle = false;
r += dfsU(n);
if (!cycle) {
r -= 1;
}
}
}
System.out.println(r);
}
private void dfs(int v) {
vis[v] = true;
for (int nb: g[v]) {
if (!vis[nb]) {
dfs(nb);
}
}
vl.addFirst(v);
}
private void rdfs(int v, int c) {
vis[v] = true;
comp[v] = c;
compSize[c]++;
for (int nb: rg[v]) {
if (!vis[nb]) {
rdfs(nb, c);
}
}
}
private int dfsU(int v) {
vis[v] = true;
if (compSize[comp[v]] != 1) {
cycle = true;
}
int r = 0;
for (int nb: g[v]) {
if (!vis[nb]) {
r += dfsU(nb);
}
}
for (int nb: rg[v]) {
if (!vis[nb]) {
r += dfsU(nb);
}
}
return r + 1;
}
public void run() {
try {
solve();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int read() throws IOException {
return br.read();
}
}
// http://stackoverflow.com/questions/521171/a-java-collection-of-value-pairs-tuples
public class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
public static void main(String[] arg) {
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 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100 * 1000 + 10;
int n, m, u, v, ans, d[maxn], cur;
vector<int> vec[maxn], a[maxn][2], M, topol;
bool mark[maxn], park[maxn], flg;
void dfs(int x) {
park[x] = 1;
M.push_back(x);
for (int i = 0; i < ((int(vec[x].size()))); i++) {
if (!park[vec[x][i]]) dfs(vec[x][i]);
}
}
void tpl(int x) {
mark[x] = 1;
for (int i = 0; i < ((int(a[x][0].size()))); i++) {
if (!mark[a[x][0][i]]) tpl(a[x][0][i]);
}
topol.push_back(x);
}
int main() {
ios::sync_with_stdio(0);
cin >> n >> m;
ans = n;
for (int i = 0; i < m; i++) {
cin >> u >> v;
u--;
v--;
d[u]++;
vec[u].push_back(v);
vec[v].push_back(u);
a[u][0].push_back(v);
a[v][1].push_back(u);
}
for (int i = 0; i < n; i++) {
if (!park[i]) {
flg = 0;
ans--;
cur = 0;
M.clear();
topol.clear();
dfs(i);
for (int j = 0; j < ((int(M.size()))); j++) {
if (!mark[M[j]]) {
tpl(M[j]);
for (; cur < ((int(topol.size()))); cur++) {
if (d[topol[cur]] > 0) {
ans++;
flg = 1;
break;
}
for (int k = 0; k < ((int(a[topol[cur]][1].size()))); k++)
d[a[topol[cur]][1][k]]--;
}
}
if (flg) break;
}
}
}
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;
int M;
const int N = 100005;
vector<int> v[N];
vector<int> to[N];
int seen[N];
int in[N];
vector<int> cur;
void dfs(int at) {
seen[at] = 1;
for (auto(i) = (0); (i) < ((int)v[at].size()); (i)++) {
int next = v[at][i];
if (!seen[next]) dfs(next);
}
cur.push_back(at);
}
int main() {
int ans = 0;
int n, m;
scanf("%d %d\n", &n, &m);
for (auto(i) = (0); (i) < (m); (i)++) {
int a, b;
scanf("%d %d", &a, &b);
to[a].push_back(b);
v[a].push_back(b);
v[b].push_back(a);
in[b]++;
}
for (auto(i) = (1); (i) < (n + 1); (i)++) {
if (seen[i] == 0) {
cur.clear();
dfs(i);
queue<int> q;
int cnt = 0;
for (int thing : cur) {
if (in[thing] == 0) {
q.push(thing);
cnt++;
}
}
while ((int)q.size()) {
int asdf = q.front();
q.pop();
for (int thing : to[asdf]) {
in[thing]--;
if (in[thing] == 0) {
cnt++;
q.push(thing);
}
}
}
if (cnt == (int)cur.size()) {
ans += (int)cur.size() - 1;
} else {
ans += (int)cur.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>
using namespace std;
const int INF = 1e9;
const int MOD = 1e9 + 7;
struct UnionFind {
vector<int> data;
UnionFind(int size) : data(size, -1) {}
bool unionSet(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (data[y] < data[x]) swap(x, y);
data[x] += data[y];
data[y] = x;
}
return x != y;
}
bool findSet(int x, int y) { return root(x) == root(y); }
int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); }
int size(int x) { return -data[root(x)]; }
};
void dfs(int v, vector<vector<int> > &g, vector<int> &used, vector<int> &vs) {
used[v] = 1;
for (__typeof((g[v]).begin()) e = (g[v]).begin(); e != (g[v]).end(); ++e)
if (!used[*e]) dfs(*e, g, used, vs);
vs.push_back(v);
}
void rdfs(int v, vector<vector<int> > &rg, vector<int> &used, vector<int> &rd) {
used[v] = 1;
for (__typeof((rg[v]).begin()) e = (rg[v]).begin(); e != (rg[v]).end(); ++e)
if (!used[*e]) rdfs(*e, rg, used, rd);
rd.push_back(v);
}
void scc(vector<vector<int> > &g, vector<vector<int> > &gscc, UnionFind &uf,
vector<pair<int, int> > &cnt, vector<int> &loop) {
int V = g.size();
vector<int> used(V, 0);
vector<int> vs;
for (int i = 0; i < (int)(V); i++)
if (!used[i]) dfs(i, g, used, vs);
used = vector<int>(V, 0);
vector<vector<int> > rg(V);
for (int i = 0; i < (int)(V); i++)
for (__typeof((g[i]).begin()) e = (g[i]).begin(); e != (g[i]).end(); ++e)
rg[*e].push_back(i);
for (int i = (int)V - 1; i >= 0; i--)
if (!used[vs[i]]) {
vector<int> rd;
rdfs(vs[i], rg, used, rd);
gscc.push_back(rd);
}
for (int i = 0; i < (int)(gscc.size()); i++) {
int root = uf.root(gscc[i][0]);
if (gscc[i].size() != 1) {
loop[root] = 1;
}
cnt[root].first++;
cnt[root].second += (int)gscc[i].size();
}
}
int main(void) {
int n, m;
cin >> n >> m;
vector<vector<int> > g(n);
vector<vector<int> > gg(n);
vector<vector<int> > rgg(n);
UnionFind uf(n);
for (int i = 0; i < (int)(m); i++) {
int x, y;
cin >> x >> y;
x--;
y--;
g[x].push_back(y);
gg[x].push_back(y);
rgg[y].push_back(x);
uf.unionSet(x, y);
}
vector<vector<int> > gscc;
vector<pair<int, int> > cnt(n, pair<int, int>(0, 0));
vector<int> loop(n, 0);
scc(g, gscc, uf, cnt, loop);
int ans = 0;
for (int i = 0; i < (int)(n); i++) {
if (uf.root(i) != i) continue;
if (cnt[i].first == 1 && cnt[i].second == 1) continue;
ans += cnt[i].second - 1;
if (loop[i]) 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 | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> graph[100010];
vector<int> sg[100010];
bool visited[100010];
vector<int> cc[100010];
int cmp;
void dfs(int node) {
cc[cmp].push_back(node);
visited[node] = true;
for (int i = 0; i < (int)sg[node].size(); i++) {
int next = sg[node][i];
if (visited[next]) continue;
dfs(next);
}
}
bool hascycle[100010];
int dep[100010];
bool cycle(int cur) {
queue<int> q;
int sz = (int)cc[cur].size();
for (int i = 0; i < sz; i++) {
int node = cc[cur][i];
if (dep[node] == 0) q.push(node);
}
int total = 0;
while (!q.empty()) {
int node = q.front();
q.pop();
total++;
for (int i = 0; i < (int)graph[node].size(); i++) {
int next = graph[node][i];
dep[next]--;
if (dep[next] == 0) q.push(next);
}
}
return total != sz;
}
int main() {
scanf("%d %d", &n, &m);
memset(dep, 0, sizeof(dep));
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d %d", &x, &y);
graph[x].push_back(y);
dep[y]++;
sg[x].push_back(y);
sg[y].push_back(x);
}
cmp = 0;
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
dfs(i);
cmp++;
}
}
memset(visited, false, sizeof(visited));
int answer = 0;
for (int i = 0; i < cmp; i++) {
bool x = cycle(i);
int sz = (int)cc[i].size();
if (x)
answer += sz;
else
answer += (sz - 1);
}
printf("%d\n", answer);
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> gf[100000 + 3];
vector<int> gb[100000 + 3];
char used[100000 + 3];
char tused[100000 + 3];
vector<int> s;
void tsort(int v) {
tused[v] = 1;
for (int i = 0; i < gf[v].size(); i++) {
int to = gf[v][i];
if (!tused[to]) {
tsort(to);
}
}
for (int i = 0; i < gb[v].size(); i++) {
int to = gb[v][i];
if (!tused[to]) {
tsort(to);
}
}
s.push_back(v);
}
bool cycle(int v) {
used[v] = 2;
for (int i = 0; i < gf[v].size(); i++) {
int to = gf[v][i];
if (used[to] == 2) {
return true;
} else if (!used[to] && cycle(to)) {
return true;
}
}
used[v] = 1;
return false;
}
int main(int argc, char* argv[]) {
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d %d", &a, &b);
gf[a].push_back(b);
gb[b].push_back(a);
}
s.reserve(100000 + 3);
int S = 0;
for (int i = 0; i < n; i++) {
if (!tused[i]) {
s.clear();
tsort(i);
bool cycled = false;
for (int i = 0; i < s.size(); i++) {
int v = s[i];
if (!used[v] && cycle(v)) {
cycled = true;
break;
}
}
S += (int)s.size() - !cycled;
}
}
printf("%d\n", S);
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.Reader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
static boolean[] used;
static ArrayList<Integer>[] g;
static ArrayList<Integer>[] reverseG;
static ArrayList<Integer> topSort;
static int[] cmp;
static int[] cmpSize;
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int m = in.nextInt();
int ans = n;
used = new boolean[n];
cmp = new int [n];
cmpSize = new int [n];
topSort = new ArrayList<Integer>();
g = (ArrayList<Integer>[])(new ArrayList[n]);
reverseG = (ArrayList<Integer>[])(new ArrayList[n]);
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<Integer>();
reverseG[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
g[from].add(to);
reverseG[to].add(from);
}
Arrays.fill(used, false);
for (int i = 0; i < n; i++) {
if (used[i] == false) {
dfs(i);
}
}
Arrays.fill(used, false);
int k = 0;
for (int i = n - 1; i > -1; i--) {
int to = topSort.get(i);
if (used[to] == false) {
reverseDfs(to, k++);
}
}
Arrays.fill(used, false);
Arrays.fill(cmpSize, 0);
for (int i = 0; i < n; i++) {
cmpSize[cmp[i]]++;
}
for (int i = 0; i < n; i++) {
if (used[i] == false) {
ans -= dfs2(i);
}
}
out.println(ans);
}
void dfs(int v) {
used[v] = true;
for (int to : g[v]) {
if (used[to] == true) continue;
dfs(to);
}
topSort.add(v);
}
void reverseDfs(int v, int k) {
used[v] = true;
cmp[v] = k;
for (int to : reverseG[v]) {
if (used[to]) continue;
reverseDfs(to, k);
}
}
int dfs2(int v) {
used[v] = true;
int res = 0;
if (cmpSize[cmp[v]] == 1) res = 1;
for (int to : g[v]) {
if (used[to] == true) continue;
res &= dfs2(to);
}
for (int to : reverseG[v]) {
if (used[to]) continue;
res &= dfs2(to);
}
return res;
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
} | 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 + 9;
const int N = 1e5 + 10;
vector<int> v[N];
int low[N], dfn[N];
int in[N], s[N];
int sz[N];
int cnt, scccnt, top;
int flag[N];
int ans = 0;
class UnionSet {
public:
int fa[N];
void init() { memset((fa), (-1), sizeof(fa)); }
int treesize(int x) { return -fa[Find(x)]; }
int Find(int x) {
int root = x;
while (fa[root] >= 0) root = fa[root];
while (x != root) {
int tmp = fa[x];
fa[x] = root;
x = tmp;
}
return root;
}
void Union(int x, int y) {
int px = Find(x);
int py = Find(y);
if (fa[px] > fa[py]) swap(px, py);
int sz = fa[px] + fa[py];
fa[py] = px;
fa[px] = sz;
}
} uf;
void dfs(int x) {
dfn[x] = low[x] = ++cnt;
in[x] = 1;
s[top++] = x;
for (auto &y : v[x]) {
if (dfn[y]) {
if (in[y]) low[x] = min(low[x], dfn[y]);
} else {
dfs(y);
low[x] = min(low[x], low[y]);
}
}
if (low[x] == dfn[x]) {
scccnt++;
while (1) {
int y = s[--top];
in[y] = 0;
sz[scccnt]++;
if (x == y) break;
}
if (sz[scccnt] > 1) {
int &o = flag[uf.Find(x)];
ans += o;
o = 0;
}
}
}
int main() {
fill(flag, flag + N, 1);
int n, m;
cin >> n >> m;
uf.init();
while (m--) {
int x, y;
cin >> x >> y;
if (uf.Find(x) != uf.Find(y)) {
uf.Union(x, y);
}
v[x].push_back(y);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) dfs(i);
}
for (int i = 1; i <= n; i++) {
if (uf.Find(i) == i) ans += uf.treesize(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 | #include <bits/stdc++.h>
using namespace std;
const int MAXV = 100005;
int P[MAXV];
int R[MAXV];
int S[MAXV];
void init(int N) {
for (int i = 0; i < N; i++) {
P[i] = i;
R[i] = 0;
S[i] = 1;
}
}
int rep(int i) {
if (P[i] != i) P[i] = rep(P[i]);
return P[i];
}
bool unio(int a, int b) {
a = rep(a);
b = rep(b);
if (a == b) return false;
if (R[a] < R[b]) {
P[a] = b;
S[b] += S[a];
} else {
P[b] = a;
S[a] += S[b];
}
if (R[a] == R[b]) R[a]++;
return true;
}
int N, M;
vector<int> fam[MAXV];
vector<int> inc[MAXV];
int out[MAXV];
int topo(int who) {
if (fam[who].size() == 0) return 0;
int proc = 0;
queue<int> q;
for (int v : fam[who])
if (out[v] == 0) q.push(v);
while (!q.empty()) {
int v = q.front();
q.pop();
proc++;
for (int p : inc[v]) {
--out[p];
if (out[p] == 0) q.push(p);
}
}
if (proc == fam[who].size()) return fam[who].size() - 1;
return fam[who].size();
}
int main() {
ios_base::sync_with_stdio(false);
cin >> N >> M;
init(N);
for (int i = 0; i < M; i++) {
int A, B;
cin >> A >> B;
A--;
B--;
inc[B].push_back(A);
out[A]++;
unio(A, B);
}
for (int i = 0; i < N; i++) {
int who = rep(i);
fam[who].push_back(i);
}
int ans = 0;
for (int i = 0; i < N; i++) {
int edge = topo(i);
ans += edge;
}
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 int N = 100100;
int dfn[N], low[N], sccno[N], scc_cnt, idx, sz[N];
stack<int> st;
vector<int> g[N];
vector<int> cc[N], dd[N];
void dfs(int u) {
dfn[u] = low[u] = ++idx;
st.push(u);
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (!dfn[v]) {
dfs(v);
low[u] = min(low[u], low[v]);
} else if (!sccno[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (low[u] == dfn[u]) {
scc_cnt++;
while (1) {
int x = st.top();
st.pop();
sccno[x] = scc_cnt;
sz[scc_cnt]++;
cc[scc_cnt].push_back(x);
if (x == u) break;
}
}
}
void find_scc(int n) {
for (int i = 1; i <= n; i++) {
if (!dfn[i]) dfs(i);
}
}
pair<int, int> re[N];
int p[N];
int f(int x) { return x == p[x] ? x : p[x] = f(p[x]); }
int ff[N];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) p[i] = i;
for (int i = 0; i < m; i++) {
scanf("%d%d", &re[i].first, &re[i].second);
g[re[i].first].push_back(re[i].second);
int fx = f(re[i].first), fy = f(re[i].second);
if (fx != fy) {
p[fx] = fy;
}
}
for (int i = 1; i <= n; i++) {
ff[i] = f(i);
dd[ff[i]].push_back(i);
}
find_scc(n);
int ret = 0;
for (int i = 1; i <= n; i++) {
if (0 == dd[i].size()) continue;
set<int> s;
bool judge = true;
for (int j = 0; j < dd[i].size(); j++) {
if (s.count(sccno[dd[i][j]])) {
judge = false;
break;
}
s.insert(sccno[dd[i][j]]);
}
if (judge)
ret += (dd[i].size() - 1);
else
ret += dd[i].size();
}
printf("%d\n", ret);
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> u[100005];
vector<int> u2[100005];
bool s[100005];
int deg[100005];
int n, m;
vector<int> c;
void fc(int i) {
s[i] = true;
c.push_back(i);
for (int j : u2[i])
if (!s[j]) fc(j);
}
int Q[100005], qs, qe;
bool topsort(vector<int> v) {
qs = qe = 0;
for (int i : v)
if (deg[i] == 0) Q[qe++] = i;
while (qs != qe) {
int i = Q[qs++];
for (int j : u[i]) {
deg[j]--;
if (deg[j] == 0) Q[qe++] = j;
}
}
return qe == int(v.size());
}
int main() {
scanf("%d%d", &n, &m);
for (int i = (0); i < (m); i++) {
int x, y;
scanf("%d %d", &x, &y);
x--;
y--;
u[x].push_back(y);
deg[y]++;
u2[x].push_back(y);
u2[y].push_back(x);
}
int res = 0;
for (int i = (0); i < (n); i++)
if (!s[i]) {
c.clear();
fc(i);
if (topsort(c))
res += int(c.size()) - 1;
else
res += int(c.size());
}
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>
using namespace std;
int n, m;
vector<int> ady[100005], tra[100005];
bitset<100005> b;
int cmp[100005], cnt[100005];
stack<int> s;
void dfs(int curr) {
b[curr] = 1;
int next;
for (int i = 0; i < (int)ady[curr].size(); ++i) {
next = ady[curr][i];
if (b[next] == 0) dfs(next);
}
s.push(curr);
}
void dfs2(int curr, int k) {
b[curr] = 1;
int next;
cmp[curr] = k;
for (int i = 0; i < (int)tra[curr].size(); ++i) {
next = tra[curr][i];
if (b[next] == 0) dfs2(next, k);
}
}
int scc() {
b.reset();
for (int i = 0; i < n; ++i)
if (b[i] == 0) dfs(i);
b.reset();
int k = 0, curr;
while (!s.empty()) {
curr = s.top();
s.pop();
if (b[curr] == 1) continue;
dfs2(curr, k++);
}
return k;
}
int dfs3(int curr) {
b[curr] = 1;
int res = cnt[cmp[curr]] == 1, next;
for (int i = 0; i < (int)ady[curr].size(); ++i) {
next = ady[curr][i];
if (b[next] == 0) res &= dfs3(next);
}
for (int i = 0; i < (int)tra[curr].size(); ++i) {
next = tra[curr][i];
if (b[next] == 0) res &= dfs3(next);
}
return res;
}
int main() {
int x, y;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; ++i) {
scanf("%d %d", &x, &y);
x--;
y--;
ady[x].push_back(y);
tra[y].push_back(x);
}
scc();
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i < n; ++i) cnt[cmp[i]]++;
b.reset();
int ans = n;
for (int i = 0; i < n; ++i)
if (b[i] == 0) ans -= dfs3(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 | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > grafo;
vector<vector<int> > grafoinv;
vector<int> tams;
int cont = 0;
int n, m;
bool comp;
bool trace[100005];
bool vis[100005];
stack<int> pila;
int uf[100005];
int siz[100005];
bool ciclo[100005];
bool toc[100005];
void initUF(int n) {
for (int i = 0; i < n; i++) {
uf[i] = i;
}
}
int getParent(int n) {
if (n == uf[n]) {
return n;
} else {
return uf[n] = getParent(uf[n]);
}
}
void joinfind(int a, int b) { uf[getParent(uf[a])] = getParent(uf[b]); }
void calcSize(int n) {
for (int i = 0; i < n; i++) {
siz[getParent(i)]++;
}
}
bool hay_ciclo(int c) {
int tam = grafo[c].size();
vis[c] = true;
trace[c] = true;
toc[c] = true;
for (int i = 0; i < tam; i++) {
if (trace[grafo[c][i]]) {
return true;
} else {
if (!vis[grafo[c][i]] && hay_ciclo(grafo[c][i])) {
return true;
}
}
}
trace[c] = false;
return false;
}
int main() {
int aux, aux2;
scanf("%d %d", &n, &m);
grafo.resize(n + 1);
grafoinv.resize(n + 1);
initUF(n + 1);
memset(siz, 0, sizeof(siz));
memset(ciclo, false, sizeof(ciclo));
memset(toc, false, sizeof(toc));
for (int i = 0; i < m; i++) {
scanf("%d %d", &aux, &aux2);
grafo[aux].push_back(aux2);
joinfind(aux, aux2);
grafoinv[aux2].push_back(aux);
}
calcSize(n + 1);
for (int i = 1; i <= n; i++) {
memset(vis, false, sizeof(vis));
if (!toc[i] and !ciclo[getParent(i)] and hay_ciclo(i)) {
ciclo[getParent(i)] = true;
}
}
int sol = 0;
for (int i = 1; i <= n; i++) {
if (siz[i] != 0) {
sol += siz[i] - !ciclo[i];
}
}
printf("%i\n", sol);
}
| 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:100000000")
using namespace std;
const long double pi = acos(-1.0);
const int N = (int)1e5 + 10;
vector<int> adj[N];
int color[N], u, v, p[N], n, m;
bool bad[N], cycled;
int dsu_find(int v) { return (v == p[v]) ? v : (p[v] = dsu_find(p[v])); }
void dfs(int v) {
color[v] = 1;
for (int i = 0; i < ((int)(adj[v]).size()); ++i) {
int u = adj[v][i];
if (color[u] == 0)
dfs(u);
else if (color[u] == 1)
cycled = true;
}
color[v] = 2;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i) p[i] = i;
for (int i = 0; i < m; ++i) {
scanf("%d%d", &u, &v), --u, --v, adj[u].push_back(v);
p[dsu_find(u)] = dsu_find(v);
}
for (int i = 0; i < n; ++i) p[i] = dsu_find(i);
for (int i = 0; i < n; ++i)
if (color[i] == 0) {
cycled = false;
dfs(i);
bad[p[i]] |= cycled;
}
int ans = n;
for (int i = 0; i < n; ++i)
if ((i == p[i]) && !bad[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 MOD(1000000007);
const int INF((1 << 30) - 1);
const int MAXN(100005);
int cycle;
vector<int> a[MAXN], b[MAXN], component;
bool visited[MAXN];
int color[MAXN];
void dfs(int node) {
visited[node] = 1;
component.push_back(node);
for (int i = 0; i < a[node].size(); i++) {
int u = a[node][i];
if (!visited[u]) dfs(u);
}
}
void dfs2(int node) {
color[node] = 2;
for (int i = 0; i < b[node].size(); i++) {
int u = b[node][i];
if (color[u] == 0)
dfs2(u);
else if (color[u] == 2)
cycle = 1;
}
color[node] = 1;
}
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);
a[u].push_back(v);
a[v].push_back(u);
b[u].push_back(v);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
dfs(i);
cycle = 0;
for (int j = 0; j < component.size(); j++) {
int u = component[j];
if (color[u] == 0) dfs2(u);
}
ans += component.size() - (!cycle);
component.clear();
}
}
printf("%d", 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;
vector<vector<int>> adj, radj;
int n, m;
vector<int> vis;
vector<int> belongto;
vector<int> sz;
vector<pair<int, int>> edges;
stack<int> s;
int itr;
void dfs(int pos) {
vis[pos] = 1;
for (int &nxt : adj[pos])
if (!vis[nxt]) dfs(nxt);
s.push(pos);
}
int dfs2(int pos) {
int ret = 1;
vis[pos] = 1;
belongto[pos] = itr;
for (int &nxt : radj[pos])
if (!vis[nxt]) ret += dfs2(nxt);
return ret;
}
vector<int> par;
vector<int> ada, sz2;
int caripar(int x) {
if (par[x] == x) return x;
return par[x] = caripar(par[x]);
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
adj.resize(n);
radj.resize(n);
vis = vector<int>(n, 0);
belongto.resize(n);
itr = 0;
edges.resize(m);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
edges[i] = {u, v};
adj[u].push_back(v);
radj[v].push_back(u);
}
for (int i = 0; i < n; i++) {
if (!vis[i]) dfs(i);
}
vis = vector<int>(n, 0);
while (!s.empty()) {
if (!vis[s.top()]) {
sz.push_back(dfs2(s.top()));
itr++;
}
s.pop();
}
par.resize(n);
for (int i = 0; i < n; i++) par[i] = i;
sz2 = vector<int>(n, 1);
ada.resize(n);
for (int i = 0; i < n; i++) ada[i] = (sz[belongto[i]] > 1 ? 1 : 0);
vis = vector<int>(n, 0);
for (int i = 0; i < m; i++) {
int u, v;
u = edges[i].first, v = edges[i].second;
if (caripar(u) == caripar(v)) continue;
sz2[caripar(v)] += sz2[caripar(u)];
ada[caripar(v)] |= ada[caripar(u)];
par[caripar(u)] = caripar(v);
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (vis[caripar(i)]) continue;
vis[caripar(i)] = 1;
ans += sz2[caripar(i)] + ada[caripar(i)] - 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 | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
using namespace std;
const int N = 1e5 + 7;
const int M = -1;
vector<int> e[N], g[N];
int vis1[N], vis2[N], cyc[N], done[N], id[N];
void dfs1(int u, int c) {
vis1[u] = 1;
id[u] = c;
for (int v : g[u]) {
if (!vis1[v]) dfs1(v, c);
}
}
void dfs2(int u) {
vis2[u] = 1;
for (int v : e[u]) {
if (vis2[v]) {
if (!done[v]) cyc[id[v]] = 1;
} else
dfs2(v);
}
done[u] = 1;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < (m); ++i) {
int u, v;
scanf("%d%d", &u, &v);
u--, v--;
e[u].push_back(v);
g[u].push_back(v);
g[v].push_back(u);
}
int ans = n, _ = 0;
for (int i = 0; i < (n); ++i) {
if (!vis1[i]) dfs1(i, _++), ans--;
}
for (int i = 0; i < (n); ++i) {
if (!vis2[i]) dfs2(i);
}
for (int i = 0; i < (_); ++i) ans += cyc[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;
vector<int> g[100010];
bool vis[100010];
set<int> s;
vector<int> uf;
vector<int> sz;
bool cycle;
int root(int a) {
if (uf[a] == a) return a;
return uf[a] = root(uf[a]);
}
void join(int a, int b) {
a = root(a);
b = root(b);
if (a == b) return;
if (sz[a] > sz[b]) {
sz[a] += sz[b];
uf[b] = a;
} else {
sz[b] += sz[a];
uf[a] = b;
}
}
void dfs(int u) {
s.insert(u);
vis[u] = true;
int res = 0;
for (int v : g[u]) {
if (s.find(v) != s.end()) {
cycle = true;
}
if (!vis[v]) dfs(v);
}
s.erase(u);
}
int main() {
int n, m, a, b;
cin >> n >> m;
for (int i = 0; i <= n; i++) {
vis[i] = false;
sz.push_back(1);
uf.push_back(i);
}
for (int i = 0; i < m; ++i) {
cin >> a >> b;
a--, b--;
g[a].push_back(b);
join(a, b);
}
int c = 0;
map<int, bool> ma;
map<int, bool>::iterator it;
for (int i = 0; i < n; i++) {
cycle = false;
dfs(i);
ma[root(i)] = (ma[root(i)] || cycle);
}
for (it = ma.begin(); it != ma.end(); it++) {
if (!(it->second)) n--;
}
cout << 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 MAX = 100005;
int n, m;
int Stop, Bcnt, Dindex, DFN[MAX], LOW[MAX], Stap[MAX], Belong[MAX], num[MAX],
used[MAX];
bool instack[MAX];
vector<int> G[MAX], g[MAX], gg;
void tarjan(int i) {
int j;
DFN[i] = LOW[i] = ++Dindex;
instack[i] = true;
Stap[++Stop] = i;
for (int v = 0; v < G[i].size(); ++v) {
j = G[i][v];
if (!DFN[j]) {
tarjan(j);
if (LOW[j] < LOW[i]) LOW[i] = LOW[j];
} else if (instack[j] && DFN[j] < LOW[i])
LOW[i] = DFN[j];
}
if (DFN[i] == LOW[i]) {
Bcnt++;
do {
j = Stap[Stop--];
instack[j] = false;
Belong[j] = Bcnt;
} while (j != i);
}
}
void bfs(int s, int id) {
queue<int> que;
que.push(s);
used[s] = id;
while (!que.empty()) {
int u = que.front();
que.pop();
gg.push_back(u);
for (int i = 0; i < g[u].size(); ++i) {
int v = g[u][i];
if (used[v] != id) {
que.push(v);
used[v] = id;
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
g[u].push_back(v);
g[v].push_back(u);
}
int ans = 0;
for (int i = 1; i <= n; ++i) {
if (!DFN[i]) {
gg.clear();
bfs(i, i);
for (int i = 0; i < gg.size(); ++i) {
if (!DFN[gg[i]]) tarjan(gg[i]);
}
int flag = 1;
for (int i = 0; i < gg.size(); ++i) {
num[Belong[gg[i]]]++;
if (num[Belong[gg[i]]] > 1) flag = 0;
}
ans += gg.size() - flag;
}
}
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 long long inf = 2147383647;
const double pi = 2 * acos(0.0);
const double eps = 1e-9;
struct debugger {
template <typename T>
debugger& operator,(const T& v) {
cerr << v << " ";
return *this;
}
} dbg;
inline long long gcd(long long a, long long b) {
a = ((a) < 0 ? -(a) : (a));
b = ((b) < 0 ? -(b) : (b));
while (b) {
a = a % b;
swap(a, b);
}
return a;
}
int ext_gcd(int a, int b, int& x, int& y) {
if (a == 0) {
x = 0;
y = 1;
return b;
}
int x1, y1;
int d = ext_gcd(b % a, a, x1, y1);
x = y1 - (b / a) * x1;
y = x1;
return d;
}
inline long long modInv(int a, int m) {
int x, y;
ext_gcd(a, m, x, y);
if (x < 0) x += m;
return x;
}
inline long long power(long long a, long long p) {
long long res = 1, x = a;
while (p) {
if (p & 1) res = (res * x);
x = (x * x);
p >>= 1;
}
return res;
}
inline long long bigmod(long long a, long long p, long long m) {
long long res = 1, x = a % m;
while (p) {
if (p & 1) res = (res * x) % m;
x = (x * x) % m;
p >>= 1;
}
return res;
}
vector<int> adj[100010], two[100010];
int vis[100010];
vector<int> line;
int loop;
void gather(int s) {
if (vis[s]) return;
vis[s] = 1;
line.push_back(s);
for (int i = (0); i <= (((int)(two[s]).size()) - 1); ++i) {
int t = two[s][i];
gather(t);
}
}
int col[100010];
void topo(int s) {
if (col[s] != 0) return;
col[s] = 1;
for (int i = (0); i <= (((int)(adj[s]).size()) - 1); ++i) {
int t = adj[s][i];
if (col[t] == 1) {
loop = 1;
} else
topo(t);
}
col[s] = 2;
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = (0); i <= (m - 1); ++i) {
int u, v;
scanf("%d %d", &u, &v);
adj[u].push_back(v);
two[u].push_back(v);
two[v].push_back(u);
}
int res = 0;
for (int i = (1); i <= (n); ++i) {
if (vis[i] == 0) {
loop = 0;
line.clear();
gather(i);
for (int j = (0); j <= (((int)(line).size()) - 1); ++j) {
int x = line[j];
if (col[x] == 0) {
topo(x);
}
}
if (loop)
res += line.size();
else
res += ((int)(line).size()) - 1;
}
}
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 MAXN = 1e5 + 50;
vector<int> adj[MAXN], rev[MAXN];
int n, m;
void readInput() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v);
adj[u].push_back(v);
rev[v].push_back(u);
}
}
bool vis[MAXN];
void dfs(int v, vector<int> &order) {
for (auto c : adj[v])
if (!vis[c]) {
vis[c] = true;
dfs(c, order);
}
order.push_back(v);
}
int ci[MAXN];
vector<int> cmp[MAXN];
void rev_dfs(int v, int id) {
ci[v] = id;
cmp[id].push_back(v);
for (auto c : rev[v])
if (!vis[c]) {
vis[c] = true;
rev_dfs(c, id);
}
}
int SCC() {
vector<int> order;
for (int v = 1; v <= n; v++)
if (!vis[v]) {
vis[v] = true;
dfs(v, order);
}
for (int v = 1; v <= n; v++) vis[v] = false;
reverse(order.begin(), order.end());
int sz = 0;
for (auto v : order)
if (!vis[v]) {
vis[v] = true;
rev_dfs(v, ++sz);
}
return sz;
}
void solve(int sz) {
int cnt = n;
for (int i = 1; i <= sz; i++) vis[i] = false;
queue<int> que;
for (int i = 1; i <= sz; i++)
if (!vis[i]) {
vis[i] = true;
que.push(i);
bool noCycle = true;
while (!que.empty()) {
int x = que.front();
que.pop();
if ((int)cmp[x].size() > 1) noCycle = false;
for (auto v : cmp[x]) {
for (auto c : adj[v])
if (!vis[ci[c]]) {
vis[ci[c]] = true;
que.push(ci[c]);
}
for (auto c : rev[v])
if (!vis[ci[c]]) {
vis[ci[c]] = true;
que.push(ci[c]);
}
}
}
if (noCycle) cnt--;
}
printf("%d\n", cnt);
}
int main() {
readInput();
int sz = SCC();
solve(sz);
}
| 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.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int n, m;
static boolean[] visited;
static List<Integer> list;
public static void main(String[] args) throws IOException {
BufferedReader scanner = new BufferedReader(
new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(scanner.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
Graph Gdirected = new Graph(n, true);
Graph Gundirected = new Graph(n, false);
int[] inDegree = new int[n];
boolean[] imp = new boolean[n];
for(int i = 0; i < m; i++) {
st = new StringTokenizer(scanner.readLine());
int e1 = Integer.parseInt(st.nextToken()) - 1;
int e2 = Integer.parseInt(st.nextToken()) - 1;
imp[e1] = true;
imp[e2] = true;
inDegree[e2]++;
Gdirected.addEdge(e1, e2);
Gundirected.addEdge(e1, e2);
}
visited = new boolean[n];
int answer = 0;
for(int i = 0; i < n; i++) {
if(!visited[i] && imp[i]) {
list = new LinkedList<Integer>();
visited[i] = true;
dfs(Gundirected, i);
answer += list.size();
if(topologicalSortable(Gdirected)) {
answer--;
}
}
}
System.out.println(answer);
}
private static boolean topologicalSortable(Graph gundirected) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] dir = new int[list.size()];
int count = 0;
for(int a : list) {
dir[count] = a;
map.put(a, count++);
}
int[] inDegree = new int[list.size()];
for(int f : list) {
for(int z : gundirected.getNeighbors(f)) {
inDegree[map.get(z)]++;
}
}
count = 0;
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i < list.size(); i++) {
if(inDegree[i] == 0) stack.push(i);
}
while(!stack.isEmpty()) {
count++;
int element = stack.pop();
for(int z : gundirected.getNeighbors(dir[element])) {
inDegree[map.get(z)]--;
if(inDegree[map.get(z)] == 0) stack.push(map.get(z));
}
}
return (count == list.size());
}
static void dfs(Graph G, int v) {
list.add(v);
for(int w : G.getNeighbors(v)) {
if(!visited[w]) {
visited[w] = true;
dfs(G, w);
}
}
}
}
class Graph {
private int n;
private List<List<Integer>> adj;
private boolean directed;
public Graph(int n, boolean directed) {
this.directed = directed;
this.n = n;
adj = new ArrayList<List<Integer>>();
for(int i = 0; i < n; i++) {
adj.add(new LinkedList<Integer>());
}
}
public int getSize() {
return n;
}
public void addEdge(int e1, int e2) {
adj.get(e1).add(e2);
if(!directed) adj.get(e2).add(e1);
}
public List<Integer> getNeighbors(int v) {
return adj.get(v);
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
| JAVA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.