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 maxn = 1e5 + 10;
vector<int> G[maxn];
int pre[maxn], lowlink[maxn], sccno[maxn], dfs_clock, scc_cnt;
stack<int> S;
void dfs(int u) {
pre[u] = lowlink[u] = ++dfs_clock;
S.push(u);
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (!pre[v]) {
dfs(v);
lowlink[u] = min(lowlink[u], lowlink[v]);
} else if (!sccno[v]) {
lowlink[u] = min(lowlink[u], pre[v]);
}
}
if (lowlink[u] == pre[u]) {
scc_cnt++;
for (;;) {
int x = S.top();
S.pop();
sccno[x] = scc_cnt;
if (x == u) break;
}
}
}
void find_scc(int n) {
dfs_clock = scc_cnt = 0;
memset(sccno, 0, sizeof(sccno));
memset(pre, 0, sizeof(pre));
for (int i = 1; i <= n; i++)
if (!pre[i]) dfs(i);
}
int u[maxn], v[maxn], vis[maxn], num, flag, cnt[maxn];
void dfs2(int x) {
num++;
vis[x] = 1;
if (++cnt[sccno[x]] == 2) flag = 1;
for (auto y : G[x])
if (!vis[y]) dfs2(y);
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u[i], &v[i]);
G[u[i]].push_back(v[i]);
}
find_scc(n);
int ans = 0;
for (int i = 1; i <= m; i++) G[v[i]].push_back(u[i]);
for (int i = 1; i <= n; i++)
if (!vis[i]) {
num = flag = 0;
dfs2(i);
ans += num - 1 + flag;
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 105000;
struct Edge {
int nex, y;
} e[maxn * 2];
int lis[maxn], cnt;
vector<int> V[maxn];
int n, m, top, tim, tot, ans;
int belong[maxn], st[maxn], dfn[maxn], low[maxn], f[maxn];
bool flag, instack[maxn], v[maxn];
inline void addedge(int x, int y) {
e[++cnt] = (Edge){lis[x], y};
lis[x] = cnt;
}
void tarjan(int x) {
dfn[x] = low[x] = ++tim;
instack[st[++top] = x] = true;
for (int i = lis[x]; i; i = e[i].nex) {
int y = e[i].y;
if (!dfn[y]) {
tarjan(y);
if (low[x] > low[y]) low[x] = low[y];
} else if (instack[y] && dfn[x] > dfn[y])
dfn[x] = dfn[y];
}
if (dfn[x] == low[x]) {
int j;
++tot;
do {
instack[j = st[top--]] = false;
belong[j] = tot;
f[tot]++;
} while (j != x);
}
}
void dfs(int x) {
v[x] = true;
int p = belong[x];
if (f[p] > 1) flag = true;
for (auto y : V[x])
if (!v[y]) dfs(y);
}
int main() {
scanf("%d%d\n", &n, &m);
while (m--) {
int x, y;
scanf("%d%d\n", &x, &y);
V[x].push_back(y);
V[y].push_back(x);
addedge(x, y);
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
ans = 0;
for (int i = 1; i <= n; i++)
if (!v[i]) {
flag = false;
dfs(i);
if (!flag) ans++;
}
printf("%d\n", 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>
inline void in(int &MAGNUS) { scanf("%d", &MAGNUS); }
inline void out(int MAGNUS) { printf("%d\n", MAGNUS); }
inline void in(int &MAGNUS, int &CLAR) { scanf("%d%d", &MAGNUS, &CLAR); }
inline void out(int MAGNUS, int CLAR) { printf("%d %d\n", MAGNUS, CLAR); }
inline void inl(long long &LIV) { scanf("%lld", &LIV); }
inline void inl(long long &LIV, long long &MART) {
scanf("%lld%lld", &LIV, &MART);
}
inline void outl(long long LIV) { printf("%lld\n", LIV); }
inline void outl(long long LIV, long long MART) {
printf("%lld %lld\n", LIV, MART);
}
using namespace std;
int N, E;
int ccid[100005], ccsize[100005];
vector<int> vertex, graf[100005], igraf[100005];
bool vis[100005];
void dfs(int u) {
vis[u] = 1;
for (int i = 0; i <= (int)graf[u].size() - 1; i++) {
int v = graf[u][i];
if (vis[v]) continue;
dfs(v);
}
vertex.push_back(u);
}
void dfs2(int u, int id) {
vis[u] = 1;
ccid[u] = id;
for (int i = 0; i <= (int)igraf[u].size() - 1; i++) {
int v = igraf[u][i];
if (vis[v]) continue;
dfs2(v, id);
}
}
bool nocycle(int u) {
vis[u] = 1;
bool cycle = ccsize[ccid[u]] == 1;
for (int i = 0; i <= (int)graf[u].size() - 1; i++) {
int v = graf[u][i];
if (vis[v]) continue;
cycle &= nocycle(v);
}
for (int i = 0; i <= (int)igraf[u].size() - 1; i++) {
int v = igraf[u][i];
if (vis[v]) continue;
cycle &= nocycle(v);
}
return cycle;
}
int main() {
in(N, E);
for (int i = 1; i <= E; i++) {
int u, v;
in(u, v);
graf[u].push_back(v);
igraf[v].push_back(u);
}
for (int i = 1; i <= N; i++) {
if (!vis[i]) dfs(i);
}
memset(vis, 0, sizeof(vis));
int ccmany = 1;
reverse((vertex).begin(), (vertex).end());
for (int i = 0; i <= (int)vertex.size() - 1; i++)
if (!vis[vertex[i]]) dfs2(vertex[i], ccmany++);
ccmany--;
memset(ccsize, 0, sizeof(ccsize));
for (int i = 1; i <= N; i++) ccsize[ccid[i]]++;
int ans = N;
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= N; i++) {
if (!vis[i]) ans -= nocycle(i);
}
out(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 + 5;
vector<int> g[MAXN], gg[MAXN];
int used[MAXN], col[MAXN], cnt[MAXN], bad[MAXN];
void dfs1(int s, int cl) {
int i, to;
used[s] = 1;
col[s] = cl;
cnt[cl]++;
for (i = 0; i < (int)gg[s].size(); i++) {
to = gg[s][i];
if (!used[to]) {
dfs1(to, cl);
}
}
}
void dfs(int s) {
int i, to;
used[s] = 1;
for (i = 0; i < (int)g[s].size(); i++) {
to = g[s][i];
if (!used[to]) {
dfs(to);
} else if (used[to] == 1) {
bad[col[s]] = 1;
}
}
used[s] = 2;
}
void solve() {
int n, m, i, a, b, cl;
scanf("%d%d", &n, &m);
for (i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
g[a].push_back(b);
gg[a].push_back(b);
gg[b].push_back(a);
}
int ans = 0;
cl = 1;
for (i = 1; i <= n; i++) {
if (!used[i]) {
dfs1(i, cl++);
}
}
for (i = 1; i <= n; i++) {
used[i] = 0;
}
for (i = 1; i <= n; i++) {
if (!used[i]) {
dfs(i);
}
}
for (i = 1; i < cl; i++) {
ans += cnt[i] - 1 + bad[i];
}
printf("%d\n", ans);
}
int main() {
int t = 1;
while (t--) {
solve();
}
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int fa[maxn], siz[maxn];
bool hav[maxn];
int find(int x) { return fa[x] ? fa[x] = find(fa[x]) : x; }
bool merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b) {
return false;
}
fa[b] = a;
siz[a] += siz[b];
siz[b] = 0;
return true;
}
vector<int> G[maxn];
int dfn[maxn], low[maxn], dfs_clock;
bool ins[maxn];
void tarjan(int u) {
ins[u] = true;
low[u] = dfn[u] = ++dfs_clock;
for (int i = 0; i < (int)G[u].size(); i++) {
int v = G[u][i];
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (ins[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (low[u] != dfn[u]) {
hav[find(u)] = true;
}
ins[u] = false;
}
int n, m;
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
siz[i] = 1;
}
for (int i = 1, a, b; i <= m; i++) {
cin >> a >> b;
G[a].push_back(b);
merge(a, b);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) {
tarjan(i);
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (find(i) == i) {
if (hav[i]) {
ans += siz[i];
} else {
ans += siz[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.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.IOException;
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(in, out);
out.close();
}
}
class TaskD {
private ArrayList<Integer>[] r = new ArrayList[100008];
private ArrayList<Integer>[] ur = new ArrayList[100008];
private ArrayList<Integer> e = new ArrayList<Integer>();
private boolean visited[] = new boolean[100008];
private int visited2[] = new int[100008];
private int f = 0;
public void solve(InputReader in, PrintWriter out) {
for (int i = 0; i < 100008; i++) {
r[i] = new ArrayList<Integer>();
ur[i] = new ArrayList<Integer>();
visited[i] = false;
}
int n = in.nextInt();
int m = in.nextInt();
int x, y;
int answer = 0;
for (int i = 1; i <= m; i++) {
x = in.nextInt();
y = in.nextInt();
r[x].add(y);
ur[x].add(y);
ur[y].add(x);
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
e.clear();
dfsu(i);
f = 0;
for (int j = 0; j < e.size(); j++) {
if (visited2[e.get(j)] == 0) {
dfs(e.get(j));
}
}
answer += e.size() - 1 + f;
}
}
out.println(answer);
}
private void dfsu(int t) {
visited[t] = true;
e.add(t);
for (int i = 0; i < ur[t].size(); i++) {
if (!visited[ur[t].get(i)]) {
dfsu(ur[t].get(i));
}
}
}
private void dfs(int t) {
visited2[t] = 1;
for (int i = 0; i < r[t].size(); i++) {
if (visited2[r[t].get(i)] == 1) {
f = 1;
} else if (visited2[r[t].get(i)] == 0) {
dfs(r[t].get(i));
}
}
visited2[t] = 2;
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
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 long long INF = 1e+14;
const int MAXN = 120000;
vector<vector<int> > orient;
vector<vector<int> > nonori;
vector<vector<int> > comps;
vector<char> cl;
int compcnt;
int cycle_st;
bool used[MAXN];
void dfscomp(int v) {
used[v] = true;
comps[compcnt].push_back(v);
for (size_t i = 0; i < nonori[v].size(); ++i) {
int to = nonori[v][i];
if (!used[to]) dfscomp(to);
}
}
bool dfscyc(int v) {
cl[v] = 1;
for (size_t i = 0; i < orient[v].size(); ++i) {
int to = orient[v][i];
if (cl[to] == 0) {
if (dfscyc(to)) return true;
} else if (cl[to] == 1) {
cycle_st = to;
return true;
}
}
cl[v] = 2;
return false;
}
int main() {
ios_base::sync_with_stdio(0);
int i, j, n, m, d, st, a, b, ans = 0;
cin >> n >> m;
orient.clear();
nonori.clear();
orient.resize(n + 1);
nonori.resize(n + 1);
for (i = 0; i < m; i++) {
cin >> a >> b;
orient[a].push_back(b);
nonori[a].push_back(b);
nonori[b].push_back(a);
}
comps.clear();
for (i = 0; i < MAXN; ++i) used[i] = false;
for (i = 1; i <= n; ++i)
if (!used[i]) {
compcnt = comps.size();
comps.resize(comps.size() + 1);
dfscomp(i);
}
cl.assign(n + 1, 0);
for (i = 0; i < comps.size(); i++) {
cycle_st = -1;
for (int j = 0; j < comps[i].size(); ++j)
if (dfscyc(comps[i][j])) break;
if (cycle_st == -1)
ans += comps[i].size() - 1;
else
ans += comps[i].size();
}
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.util.List;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Igor Kraskevich
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
ArrayList<Integer>[] g;
ArrayList<Integer>[] gr;
ArrayList<Integer> od = new ArrayList<>();
boolean[] was;
int size;
int cnt;
int[] comp;
void dfs1(int v) {
was[v] = true;
for (int to : g[v])
if (!was[to])
dfs1(to);
od.add(v);
}
void dfs2(int v) {
comp[v] = cnt;
size++;
was[v] = true;
for (int to : gr[v])
if (!was[to])
dfs2(to);
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
g = new ArrayList[n];
gr = new ArrayList[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
gr[i] = new ArrayList<>();
}
was = new boolean[n];
for (int i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
a--;
b--;
g[a].add(b);
gr[b].add(a);
}
for (int i = 0; i < n; i++)
if (!was[i])
dfs1(i);
Collections.reverse(od);
Arrays.fill(was, false);
comp = new int[n];
ArrayList<Integer> sizes = new ArrayList<>();
for (int v : od)
if (!was[v]) {
size = 0;
dfs2(v);
sizes.add(size);
cnt++;
}
//System.err.println(Arrays.toString(comp));
Dsu dsu = new Dsu(cnt);
for (int i = 0; i < n; i++)
for (int to : g[i])
dsu.unite(comp[i], comp[to]);
boolean[] strong = new boolean[cnt];
int[] size = new int[cnt];
for (int i = 0; i < cnt; i++) {
int r = dsu.get(i);
size[r] += sizes.get(i);
if (sizes.get(i) > 1)
strong[r] = true;
}
int res = 0;
for (int i = 0; i < cnt; i++)
if (size[i] >= 1) {
if (strong[i])
res += size[i];
else
res += size[i] - 1;
}
out.println(res);
}
}
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
// ignore
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class Dsu {
private int[] par;
public Dsu(int n) {
par = new int[n];
for (int i = 0; i < n; i++)
par[i] = i;
}
public int get(int v) {
return par[v] == v ? v : (par[v] = get(par[v]));
}
public int unite(int a, int b) {
a = get(a);
b = get(b);
if (a != b) {
par[a] = b;
return 1;
} else {
return 0;
}
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, nxt;
} e[100005];
int head[100005], cnte, n, m;
void adde(int u, int v) {
e[++cnte] = (edge){v, head[u]};
head[u] = cnte;
}
int fa[100005];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void merge(int x, int y) {
if ((x = find(x)) ^ (y = find(y))) fa[x] = y;
}
queue<int> q;
int vis[100005], in[100005];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
while (m--) {
int u, v;
scanf("%d%d", &u, &v);
adde(u, v);
merge(u, v);
in[v]++;
}
int ans = n;
for (int i = 1; i <= n; i++)
fa[i] = find(i), ans -= vis[fa[i]] == 0, vis[fa[i]] = 1;
for (int i = 1; i <= n; i++)
if (!in[i]) q.push(i);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].to;
in[v]--;
if (!in[v]) q.push(v);
}
}
for (int i = 1; i <= n; i++)
if (in[i]) ans += vis[fa[i]], vis[fa[i]] = 0;
return printf("%d\n", ans), 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = int(1e5) + 10;
const int INF = int(2e9);
vector<int> graph[N], g[N];
int arr[N], dep[N], T;
int visited[N], vis[N];
bool cycle;
vector<int> cmp;
void dfs(int u) {
arr[u] = T++;
visited[u] = 1;
for (int i = 0; i < (int)(graph[u].size()); i++) {
int w = graph[u][i];
if (!visited[w])
dfs(w);
else if (dep[w] == INF)
cycle = true;
}
dep[u] = T++;
}
void dfs2(int u) {
cmp.push_back(u);
vis[u] = 1;
for (int i = 0; i < (int)(g[u].size()); i++)
if (!vis[g[u][i]]) dfs2(g[u][i]);
}
int main() {
int n, m;
scanf("%d", &n);
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int u, v;
scanf("%d", &u);
scanf("%d", &v);
u--;
v--;
graph[u].push_back(v);
g[u].push_back(v);
g[v].push_back(u);
}
int ans = 0;
for (int i = 0; i < n; i++) dep[i] = INF;
for (int i = 0; i < n; i++)
if (!vis[i]) {
cycle = false;
cmp.clear();
dfs2(i);
for (int j = 0; j < (int)(cmp.size()); j++)
if (!visited[cmp[j]]) dfs(cmp[j]);
ans += (cycle ? (int)(cmp.size()) : (int)(cmp.size()) - 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 = 200002;
vector<int> e[MAXN];
vector<int> eo[MAXN];
bool w[MAXN];
int cnt = 0;
vector<int> tout;
int g[MAXN], gc;
void dfs(int v) {
if (w[v]) return;
w[v] = true;
for (int i = 0; i < e[v].size(); i++) {
dfs(e[v][i]);
}
tout.push_back(v);
}
void dfs2(int v) {
if (w[v]) return;
w[v] = true;
cnt++;
g[v] = gc;
for (int i = 0; i < eo[v].size(); i++) {
dfs2(eo[v][i]);
}
}
vector<int> c3;
void dfs3(int v) {
if (w[v]) return;
w[v] = true;
c3.push_back(v);
for (int i = 0; i < e[v].size(); i++) {
dfs3(e[v][i]);
}
}
bool cmp(int a, int b) { return (g[a] < g[b]); }
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
e[a].push_back(b);
eo[b].push_back(a);
}
for (int i = 1; i <= n; i++) w[i] = false;
for (int i = 1; i <= n; i++) {
dfs(i);
}
for (int i = 1; i <= n; i++) w[i] = false;
for (int i = n - 1; i >= 0; i--) {
cnt = 0;
if (!w[tout[i]]) {
gc = i;
dfs2(tout[i]);
}
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j < eo[i].size(); j++) {
e[i].push_back(eo[i][j]);
}
}
int ans = n;
for (int i = 1; i <= n; i++) w[i] = false;
for (int i = 1; i <= n; i++) {
if (!w[i]) {
ans--;
c3.clear();
dfs3(i);
sort(c3.begin(), c3.end(), cmp);
for (int j = 0; j + 1 < c3.size(); j++) {
if (g[c3[j]] == g[c3[j + 1]]) {
ans++;
break;
}
}
}
}
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 = 1e5 + 10;
vector<int> nei[maxn], nei2[maxn];
int n, m, cnt;
bool cycle = false;
int col[maxn];
int mark[maxn], ans;
bool cmp[maxn];
void dfs(int v) {
col[v] = ans;
mark[v] = 1;
for (auto u : nei[v])
if (!mark[u]) dfs(u);
}
void dfs2(int v) {
mark[v] = 1;
for (auto u : nei2[v]) {
if (!mark[u])
dfs2(u);
else if (mark[u] == 1) {
cmp[col[u]] = true;
}
}
mark[v] = 2;
}
void dfs_all() {
for (int i = 0; i < n; i++) {
if (!mark[i]) {
dfs(i);
ans++;
}
}
memset(mark, 0, sizeof mark);
for (int i = 0; i < n; i++)
if (!mark[i]) dfs2(i);
for (int i = 0; i < ans; i++)
if (cmp[i]) cnt++;
cout << n - ans + cnt << endl;
}
int main() {
cin >> n >> m;
for (int i = 0, a, b; i < m; i++) {
cin >> a >> b;
a--, b--;
nei[a].push_back(b), nei[b].push_back(a);
nei2[a].push_back(b);
}
dfs_all();
}
| 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;
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)
if (!v[*it]) dfs(*it);
if (!ok)
ans += k - 1;
else
ans += k;
}
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 MAXN = 100100;
vector<int> adj[MAXN];
vector<int> bi_adj[MAXN];
int N, M;
int lbl = 0;
int comp[MAXN];
int sz[MAXN];
bool vis[MAXN];
bool iscyc[MAXN];
int in[MAXN];
void dfs(int cur, int x) {
vis[cur] = true;
comp[cur] = x;
++sz[x];
for (int nxt : bi_adj[cur]) {
if (!vis[nxt]) {
dfs(nxt, x);
}
}
}
void dfscyc(int cur) {
if (iscyc[comp[cur]]) return;
if (in[cur] == 2) {
iscyc[comp[cur]] = true;
return;
} else if (in[cur] == 1) {
return;
}
in[cur] = 2;
for (int nxt : adj[cur]) {
dfscyc(nxt);
}
in[cur] = 1;
}
int main() {
ios_base::sync_with_stdio(0);
cin >> N >> M;
for (int i = 0; i < M; ++i) {
int a, b;
cin >> a >> b;
--a, --b;
adj[a].push_back(b);
bi_adj[a].push_back(b);
bi_adj[b].push_back(a);
}
for (int i = 0; i < N; ++i) {
if (!vis[i]) {
dfs(i, lbl);
++lbl;
}
}
for (int i = 0; i < N; ++i) {
if (!in[i]) {
dfscyc(i);
}
}
int res = 0;
for (int i = 0; i < lbl; ++i) {
if (iscyc[i]) {
res += sz[i];
} else {
res += sz[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 | #include <bits/stdc++.h>
using namespace std;
bool jo, hibas[100001];
int n, m, ki, a, b, volt[100001], t[100001], tdb;
vector<int> v[100001], v2[100001];
void mely2(int p) {
volt[p] = 1;
for (int i = 0; i < v[p].size(); i++) {
if (volt[v[p][i]] == 0) mely2(v[p][i]);
}
t[p] = tdb--;
}
void mely(int p) {
if (hibas[p]) jo = false;
volt[p] = 1;
for (int i = 0; i < v2[p].size(); i++) {
if (volt[v2[p][i]] == 0) mely(v2[p][i]);
}
}
int main() {
cin >> n >> m;
ki = n;
tdb = n;
for (int i = 1; i <= m; i++) {
cin >> a >> b;
v[a].push_back(b);
v2[b].push_back(a);
v2[a].push_back(b);
}
for (int i = 1; i <= n; i++) volt[i] = 0;
for (int i = 1; i <= n; i++) {
if (!volt[i]) {
mely2(i);
}
}
for (int i = 1; i <= n; i++) volt[i] = 0;
for (int i = 1; i <= n; i++) hibas[i] = false;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < v[i].size(); j++) {
if (t[i] > t[v[i][j]]) hibas[i] = true;
}
}
for (int i = 1; i <= n; i++) {
if (!volt[i]) {
jo = true;
mely(i);
if (jo) ki--;
}
}
cout << ki << endl;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<vector<long long>> g(1000000 + 2);
long long id[1000005], idx, deg[1000005], fa[1000005], tag[1000005];
long long find(long long x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
void merge(long long x, long long y) {
x = find(x);
y = find(y);
fa[x] = y;
}
void dfs(long long p) {
id[p] = -1;
for (long long q : g[p]) {
if (id[q] == 0) dfs(q);
}
id[p] = ++idx;
}
signed main() {
ios::sync_with_stdio(false);
long long n, m;
cin >> n >> m;
for (long long i = 1; i <= n; i++) fa[i] = i;
for (long long i = 1; i <= m; i++) {
long long u, v;
cin >> u >> v;
g[u].push_back(v);
deg[v]++;
merge(u, v);
}
for (long long i = 1; i <= n; i++)
if (deg[i] == 0 && id[i] == 0) dfs(i);
for (long long i = 1; i <= n; i++)
if (id[i] == 0) tag[find(i)] = 1;
for (long long i = 1; i <= n; i++) {
for (auto j : g[i])
if (id[i] < id[j]) tag[find(i)] = 1;
}
long long ans = n;
for (long long i = 1; i <= n; i++)
if (find(i) == i) {
if (tag[i] == 0) 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;
const int N = 200000;
int n, m, x, y, ans = 0, r[N], deg[N];
bool vis[N];
vector<int> g[N];
vector<int> v[N];
int find(int x) {
if (x == r[x]) {
return r[x];
}
return r[x] = find(r[x]);
}
void join(int x, int y) {
x = find(x);
y = find(y);
r[y] = x;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
r[i] = i;
deg[i] = 0;
vis[i] = false;
}
for (int i = 0; i < m; i++) {
scanf("%d %d", &x, &y);
--x;
--y;
++deg[y];
join(x, y);
g[x].push_back(y);
}
for (int i = 0; i < n; i++) {
int z = find(i);
v[z].push_back(i);
}
for (int i = 0; i < n; i++) {
int z = find(i);
if (vis[z]) {
continue;
}
queue<int> q;
for (int j = 0; j < (int)v[z].size(); j++) {
int u = v[z][j];
if (deg[u] == 0) {
vis[u] = true;
q.push(u);
}
}
if (q.empty()) {
ans += v[z].size();
} else {
bool cyc = false;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int j = 0; j < (int)g[u].size(); j++) {
int w = g[u][j];
if (vis[w]) {
cyc = true;
break;
} else if (--deg[w] == 0) {
vis[w] = true;
q.push(w);
}
}
if (cyc) {
break;
}
}
for (int j = 0; j < (int)v[z].size(); j++) {
if (!vis[v[z][j]]) {
cyc = true;
}
}
ans += v[z].size();
if (!cyc) {
--ans;
}
}
for (int j = 0; j < (int)v[z].size(); j++) {
vis[v[z][j]] = true;
}
}
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 = 1e9;
long long gcd(long long a, long long b) { return (a ? gcd(b % a, a) : b); }
long long power(long long a, long long n) {
long long p = 1;
while (n > 0) {
if (n % 2) {
p = p * a;
}
n >>= 1;
a *= a;
}
return p;
}
const int n_ = 1e5 + 10;
vector<long long> e[n_], re[n_], vc;
bool vis[n_];
int n, m, c[n_], cs[n_];
int noCycle(int v) {
vis[v] = 1;
int ret = (cs[c[v]] == 1);
for (int(i) = 0; (i) < (e[v].size()); (i)++) {
if (!vis[e[v][i]]) {
ret = (ret & noCycle(e[v][i]));
}
}
for (int(i) = 0; (i) < (re[v].size()); (i)++) {
if (!vis[re[v][i]]) {
ret = (ret & noCycle(re[v][i]));
}
}
return ret;
}
void topolSort(int v) {
vis[v] = 1;
for (int(i) = 0; (i) < (e[v].size()); (i)++) {
if (!vis[e[v][i]]) {
topolSort(e[v][i]);
}
}
vc.push_back(v);
}
void rdfs(int v, int cmp) {
c[v] = cmp;
vis[v] = 1;
for (int(i) = 0; (i) < (re[v].size()); (i)++) {
if (!vis[re[v][i]]) {
rdfs(re[v][i], cmp);
}
}
}
void findStronglyConnectedCmp() {
memset(vis, 0, sizeof(vis));
vc.clear();
for (int(i) = 0; (i) < (n); (i)++) {
if (!vis[i]) topolSort(i);
}
memset(vis, 0, sizeof(vis));
int cmp = 0;
for (int(i) = (vc.size() - 1); (i) >= 0; (i)--) {
if (!vis[vc[i]]) {
rdfs(vc[i], cmp++);
}
}
}
int main() {
ios_base::sync_with_stdio(false);
int u, v, ans;
cin >> n >> m;
ans = n;
for (int(i) = 0; (i) < (m); (i)++) {
cin >> u >> v;
u--;
v--;
e[u].push_back(v);
re[v].push_back(u);
}
findStronglyConnectedCmp();
memset(cs, 0, sizeof(cs));
for (int(i) = 0; (i) < (n); (i)++) {
cs[c[i]]++;
}
memset(vis, 0, sizeof(vis));
for (int(i) = 0; (i) < (n); (i)++) {
if (!vis[i]) ans -= noCycle(i);
}
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 MAXN = 100010;
int N, M;
vector<int> adj[MAXN];
int par[MAXN], indeg[MAXN];
bool hascyc[MAXN];
int find(int x) { return x == par[x] ? x : par[x] = find(par[x]); }
int main() {
if (fopen("input.txt", "r")) {
freopen("input.txt", "r", stdin);
}
ios::sync_with_stdio(false);
cin >> N >> M;
for (int i = 1; i <= N; i++) {
par[i] = i;
}
while (M--) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
par[find(a)] = find(b);
indeg[b]++;
}
stack<int> nodeg;
for (int i = 1; i <= N; i++) {
if (!indeg[i]) {
nodeg.push(i);
}
}
while (!nodeg.empty()) {
int x = nodeg.top();
nodeg.pop();
for (int t : adj[x]) {
if (!--indeg[t]) {
nodeg.push(t);
}
}
}
int ans = N;
for (int i = 1; i <= N; i++) {
if (indeg[i]) {
hascyc[find(i)] = true;
}
}
for (int i = 1; i <= N; i++) {
ans -= (par[i] == i && !hascyc[i]);
}
cout << ans << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100 * 1000 + 10;
vector<int> from[MAX_N], to[MAX_N];
vector<int> topol, cmp[MAX_N];
vector<int> vec[MAX_N];
int color[MAX_N];
bool mark[MAX_N];
void dfs_topol(int u) {
mark[u] = true;
for (auto v : from[u])
if (!mark[v]) dfs_topol(v);
topol.push_back(u);
}
void dfs_cmp(int u, int c) {
mark[u] = true;
for (auto v : to[u])
if (!mark[v]) dfs_cmp(v, c);
cmp[c].push_back(u), color[u] = c;
}
void dfs(int u, int cnt) {
mark[u] = true;
for (auto v : to[u])
if (!mark[v]) dfs(v, cnt);
vec[cnt].push_back(u);
for (auto v : from[u])
if (!mark[v]) dfs(v, cnt);
}
int main() {
ios_base ::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--, v--;
from[u].push_back(v);
to[v].push_back(u);
}
for (int i = 0; i < n; i++)
if (!mark[i]) dfs_topol(i);
int tmp = 0;
memset(mark, false, sizeof mark);
reverse(topol.begin(), topol.end());
for (auto u : topol)
if (!mark[u]) dfs_cmp(u, tmp++);
tmp = 0;
memset(mark, false, sizeof mark);
for (int i = 0; i < n; i++)
if (!mark[i]) dfs(i, tmp++);
int ans = 0;
for (int i = 0; i < tmp; i++) {
bool cycle = false;
for (auto u : vec[i])
if (cmp[color[u]].size() > 1) cycle = true;
ans += vec[i].size() - 1 + cycle;
}
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 = 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;
struct edge {
int b, nt;
};
struct graph {
edge e[100010 * 2];
int p[100010], nn;
void anode(int x, int y) {
nn++;
e[nn].b = y;
e[nn].nt = p[x];
p[x] = nn;
}
} G1, G2;
int n, m;
int dfn[100010], low[100010], tt, num[100010];
int bl, num_scc, scc[100010], ins[100010], flag[100010];
stack<int> st;
void tarjan(int x) {
tt++;
dfn[x] = low[x] = tt;
st.push(x);
ins[x] = 1;
for (int i = G1.p[x]; i; i = G1.e[i].nt) {
int t = G1.e[i].b;
if (!dfn[t]) {
tarjan(t);
low[x] = min(low[x], low[t]);
} else if (ins[t])
low[x] = min(low[x], dfn[t]);
}
if (dfn[x] == low[x]) {
num_scc++;
int tmp = st.top();
do {
tmp = st.top();
scc[tmp] = num_scc;
num[num_scc]++;
st.pop();
ins[tmp] = 0;
} while (tmp != x);
}
}
int sum, in[100010], fa[100010];
int findf(int x) {
if (fa[x] != x) fa[x] = findf(fa[x]);
return fa[x];
}
void uni(int x, int y) {
int fx = findf(x), fy = findf(y);
fa[fx] = fy;
num[fy] += num[fx];
flag[fy] |= flag[fx];
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int aa, bb;
scanf("%d%d", &aa, &bb);
G1.anode(aa, bb);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) tarjan(i);
}
for (int i = 1; i <= num_scc; i++) fa[i] = i;
memset(flag, 0, sizeof(flag));
for (int i = 1; i <= num_scc; i++) {
if (num[i] >= 2) flag[i] = 1;
}
for (int x = 1; x <= n; x++) {
for (int i = G1.p[x]; i; i = G1.e[i].nt) {
int t = G1.e[i].b;
if (scc[t] != scc[x]) {
int aa = scc[t], bb = scc[x];
if (findf(aa) != findf(bb)) {
uni(aa, bb);
}
}
}
}
for (int i = 1; i <= n; i++) {
if (findf(i) == i) {
sum += num[i] - 1;
if (flag[i]) sum += 1;
}
}
printf("%d\n", sum);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100000;
int nodes[MAX_N + 10], to[MAX_N + 10], nxt[MAX_N + 10], en;
int n;
inline void addEdge(int f, int t) {
++en;
to[en] = t;
nxt[en] = nodes[f];
nodes[f] = en;
}
int low[MAX_N + 10], dfn[MAX_N + 10], clo;
int cn;
bool inS[MAX_N + 10];
stack<int> s;
int csize[MAX_N + 10], belong[MAX_N + 10];
void tarjan(int cur) {
low[cur] = dfn[cur] = ++clo;
inS[cur] = true;
s.push(cur);
for (int e = nodes[cur]; e; e = nxt[e]) {
if (!dfn[to[e]]) {
tarjan(to[e]);
if (low[to[e]] < low[cur]) {
low[cur] = low[to[e]];
}
} else if (inS[to[e]] && dfn[to[e]] < low[cur])
low[cur] = dfn[to[e]];
}
if (low[cur] == dfn[cur]) {
++cn;
int p;
do {
p = s.top();
s.pop();
inS[p] = false;
belong[p] = cn;
++csize[cn];
} while (p != cur);
}
}
int father[MAX_N + 10];
int findFather(int a) {
if (father[a] != a) father[a] = findFather(father[a]);
return father[a];
}
struct Edge {
int f, t;
};
bool has[MAX_N + 10];
Edge edges[MAX_N + 10];
int m;
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int f, t;
scanf("%d%d", &f, &t);
addEdge(f, t);
edges[i].f = f;
edges[i].t = t;
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
for (int i = 1; i <= cn; i++) father[i] = i;
for (int i = 1; i <= m; i++)
father[findFather(belong[edges[i].f])] = findFather(belong[edges[i].t]);
for (int i = 1; i <= cn; i++)
if (csize[i] > 1) has[findFather(i)] = true;
int tot = n;
for (int i = 1; i <= cn; i++)
if (findFather(i) == i && !has[i]) --tot;
printf("%d\n", tot);
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 = 2e5;
int n, m, sz, c[N], ans;
bool used[N];
vector<int> g[N], gg[N], gr[N], t, all, cc;
void dfs(int v) {
all.push_back(v);
used[v] = 1;
for (auto to : gg[v])
if (!used[to]) dfs(to);
}
void dfs_t(int v) {
used[v] = 1;
for (auto to : g[v])
if (!used[to]) dfs_t(to);
t.push_back(v);
}
void dfs_c(int v) {
used[v] = 1;
cc.push_back(v);
for (auto to : gr[v])
if (!used[to]) dfs_c(to);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0, a, b; i < m; i++) {
scanf("%d%d", &a, &b);
g[a].push_back(b);
gr[b].push_back(a);
gg[a].push_back(b), gg[b].push_back(a);
}
for (int i = 1; i <= n; i++)
if (!used[i]) {
all.clear();
dfs(i);
for (auto j : all) used[j] = 0;
t.clear();
for (auto j : all)
if (!used[j]) dfs_t(j);
reverse(t.begin(), t.end());
for (auto j : all) used[j] = 0;
bool cycle = 0;
for (auto j : t)
if (!c[j]) {
cc.clear();
dfs_c(j);
if (cc.size() > 1) cycle = 1;
}
if (cycle)
ans += all.size();
else
ans += all.size() - 1;
}
cout << ans;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
template <class T>
using vv = vector<vector<T>>;
template <class T>
ostream &operator<<(ostream &os, const vector<T> &t) {
os << "{";
for (int(i) = 0; (i) < (t.size()); ++(i)) {
os << t[i] << ",";
}
os << "}" << endl;
return os;
}
template <class S, class T>
ostream &operator<<(ostream &os, const pair<S, T> &t) {
return os << "(" << t.first << "," << t.second << ")";
}
struct Edge {
int src, dst;
int weight;
Edge(int src, int dst, int weight) : src(src), dst(dst), weight(weight) {}
};
ostream &operator<<(ostream &os, const Edge &e) {
return cout << "(" << e.src << "," << e.dst << ")";
}
bool operator<(const Edge &e, const Edge &f) {
return e.weight != f.weight ? e.weight > f.weight
: e.src != f.src ? e.src < f.src
: e.dst < f.dst;
}
bool operator==(const Edge &e, const Edge &f) {
return e.src == f.src && e.dst == f.dst;
}
void visit(const vector<vector<Edge>> &g, int v, vector<vector<int>> &scc,
stack<int> &S, vector<bool> &inS, vector<int> &low, vector<int> &num,
int &time) {
low[v] = num[v] = ++time;
S.push(v);
inS[v] = true;
for (auto e : g[v]) {
int w = e.dst;
if (num[w] == 0) {
visit(g, w, scc, S, inS, low, num, time);
low[v] = min(low[v], low[w]);
} else if (inS[w])
low[v] = min(low[v], num[w]);
}
if (low[v] == num[v]) {
scc.push_back(vector<int>());
while (1) {
int w = S.top();
S.pop();
inS[w] = false;
scc.back().push_back(w);
if (v == w) break;
}
}
}
void toDag(const vector<vector<Edge>> &g, const vector<vector<int>> &scc,
vector<int> &dagV, vector<vector<Edge>> &dag) {
dagV.resize(g.size());
dag.resize(scc.size());
for (int(i) = 0; (i) < (scc.size()); ++(i)) {
for (int(j) = 0; (j) < (scc[i].size()); ++(j)) {
dagV[scc[i][j]] = i;
}
}
for (int(i) = 0; (i) < (scc.size()); ++(i)) {
for (int(j) = 0; (j) < (scc[i].size()); ++(j)) {
for (auto e : g[scc[i][j]]) {
if (dagV[e.dst] != i) dag[i].push_back(Edge(i, dagV[e.dst], e.weight));
}
}
}
}
vector<int> Scc(const vector<vector<Edge>> &g, vector<vector<int>> &scc,
vector<vector<Edge>> &dag) {
const int n = g.size();
vector<int> num(n), low(n), dagV(n);
stack<int> S;
vector<bool> inS(n);
int time = 0;
for (int(u) = 0; (u) < (n); ++(u))
if (num[u] == 0) visit(g, u, scc, S, inS, low, num, time);
reverse((scc).begin(), (scc).end());
toDag(g, scc, dagV, dag);
for (int(i) = 0; (i) < (dag.size()); ++(i)) {
dag[i].erase(unique((dag[i]).begin(), (dag[i]).end()), dag[i].end());
}
return dagV;
}
pair<int, int> count(vector<vector<Edge>> &g, vv<int> &scc, vector<int> &usd,
int v) {
if (usd[v]) return pair<int, int>(0, 0);
pair<int, int> re = pair<int, int>(scc[v].size(), scc[v].size() > 1), tmp;
usd[v] = 1;
for (Edge e : g[v])
if (!usd[e.dst]) {
tmp = count(g, scc, usd, e.dst);
re.first += tmp.first;
re.second |= tmp.second;
}
return re;
}
void ccdfs(vector<vector<Edge>> &g, vector<int> &cc, vector<int> &usd, int v) {
if (usd[v]) return;
usd[v] = 1;
cc.push_back(v);
for (const Edge &e : g[v])
if (!usd[e.dst]) ccdfs(g, cc, usd, e.dst);
}
void CC(vector<vector<Edge>> &h, vv<int> &cc) {
int n = h.size();
vector<int> usd(n);
vector<vector<Edge>> g = h;
for (int(i) = 0; (i) < (n); ++(i))
for (const Edge &e : h[i]) g[e.dst].push_back(Edge(e.dst, e.src, e.weight));
for (int(i) = 0; (i) < (n); ++(i))
if (!usd[i]) {
cc.push_back(vector<int>());
ccdfs(g, cc.back(), usd, i);
}
}
bool topodfs(const vector<vector<Edge>> &g, int v, vector<int> &order,
vector<int> &usd, vector<int> &ex) {
usd[v] = 1;
for (const Edge &e : g[v])
if (*lower_bound((ex).begin(), (ex).end(), e.dst) == e.dst) {
if (usd[e.dst] == 2) continue;
if (usd[e.dst] == 1) return 0;
if (!topodfs(g, e.dst, order, usd, ex)) return 0;
}
order.push_back(v);
usd[v] = 2;
return 1;
}
bool topoSort(const vector<vector<Edge>> &g, vector<int> &ex,
vector<int> &order) {
int n = g.size();
vector<int> usd(n);
for (int(i) = 0; (i) < (n); ++(i))
if (!usd[i] && *lower_bound((ex).begin(), (ex).end(), i) == i)
if (!topodfs(g, i, order, usd, ex)) return 0;
reverse((order).begin(), (order).end());
return 1;
}
int main() {
ios_base::sync_with_stdio(false);
cout << fixed << setprecision(0);
int i, j, k;
int n, m;
scanf("%d %d", &n, &m);
vector<vector<Edge>> g(n);
int a, b;
for (int(i) = 0; (i) < (m); ++(i)) {
scanf("%d %d", &a, &b);
--a;
--b;
g[a].push_back(Edge(a, b, 1));
}
vv<int> scc;
vector<vector<Edge>> dag;
Scc(g, scc, dag);
int dn = scc.size(), re = 0;
vector<int> usd(dn);
vv<int> cc;
CC(dag, cc);
for (int(i) = 0; (i) < (cc.size()); ++(i)) {
int f = 0;
for (int(j) = 0; (j) < (cc[i].size()); ++(j)) {
f |= (scc[cc[i][j]].size() > 1);
re += scc[cc[i][j]].size();
}
if (!f) --re;
}
printf("%d\n", re);
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, pt, last, num, tot, ans;
int px[100010], py[100010];
int st[100010], ne[200010], go[200010];
int dfn[100010], low[100010], sta[100010], vis[100010], ss[100010],
mark[100010];
void Add(int x, int y) {
ne[++pt] = st[x];
st[x] = pt;
go[pt] = y;
}
void tarjan(int x) {
dfn[x] = low[x] = ++tot;
sta[++last] = x;
vis[x] = 1;
for (int i = st[x]; i; i = ne[i])
if (vis[go[i]] == 0) {
tarjan(go[i]);
low[x] = min(low[x], low[go[i]]);
} else if (vis[go[i]] == 1)
low[x] = min(low[x], dfn[go[i]]);
if (dfn[x] == low[x]) {
++num;
int p;
ss[num] = 0;
do {
p = sta[last];
mark[p] = num;
ss[num]++;
vis[p] = 2;
sta[last--] = 0;
} while (p != x);
}
}
bool floodfill(int x) {
vis[x] = 1;
bool flag = (ss[mark[x]] > 1);
for (int i = st[x]; i; i = ne[i])
if (!vis[go[i]]) {
flag |= floodfill(go[i]);
}
return flag;
}
int main() {
scanf("%d%d", &N, &M);
for (int i = 1; i <= M; i++) {
scanf("%d%d", &px[i], &py[i]);
Add(px[i], py[i]);
}
ans = N;
for (int i = 1; i <= N; i++)
if (!vis[i]) tarjan(i);
for (int i = 1; i <= M; i++) Add(py[i], px[i]);
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= N; i++)
if (!vis[i]) {
ans--;
bool flag = floodfill(i);
ans += 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 int maxn = 1e5 + 9;
const long long mod = 1e9 + 7;
vector<int> g[maxn], comp[maxn];
int par[maxn], vis[maxn];
bool f;
int root(int v) { return ((par[v] + 1) ? par[v] = root(par[v]) : v); }
void merge(int v, int u) {
v = root(v);
u = root(u);
if (v == u) return;
par[v] = u;
}
void dfs(int v) {
vis[v] = 1;
for (auto u : g[v]) {
if (vis[u] == 1) f = true;
if (vis[u] == 0) dfs(u);
}
vis[v] = 2;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(par, -1, sizeof par);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int v, u;
cin >> v >> u;
--v;
--u;
merge(v, u);
g[v].push_back(u);
}
for (int i = 0; i < n; i++) comp[root(i)].push_back(i);
int res = 0;
for (int i = 0; i < n; i++) {
if (comp[i].size() == 0) continue;
f = false;
for (auto u : comp[i])
if (!vis[u]) dfs(u);
res += comp[i].size() - ((f) ? 0 : 1);
}
cout << res << "\n";
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
vector<int> adj[N];
int p[N], cycle[N], sz[N];
bool vis[N], instack[N];
int fin(int i) {
if (p[i] != i) p[i] = fin(p[i]);
return p[i];
}
void merge(int x, int y) {
int px = fin(x), py = fin(y);
if (px == py) return;
p[px] = py;
sz[py] += sz[px];
}
void dfs(int s) {
if (vis[s]) return;
vis[s] = true;
instack[s] = true;
for (auto it : adj[s]) {
dfs(it);
if (instack[it]) {
cycle[fin(s)] = 1;
}
}
instack[s] = false;
}
int main() {
int n, m, i, ndc = 0, ans = 0, tc = 0;
scanf("%d%d", &n, &m);
for (i = 0; i < n; i++) p[i] = i, sz[i] = 1;
for (i = 0; i < m; i++) {
int x, y;
scanf("%d%d", &x, &y);
adj[x - 1].push_back(y - 1);
merge(x - 1, y - 1);
}
for (i = 0; i < n; i++) dfs(i);
for (i = 0; i < n; i++) {
if (fin(i) == i) {
ans += sz[i] + cycle[i] - 1;
}
}
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<int> c[100050];
int com[100050];
vector<int> g[100050];
vector<int> gra[100050];
int deg[100050];
int find(int s) { return com[s] == s ? s : com[s] = find(com[s]); }
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) com[i] = i;
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d%d", &x, &y);
c[x].push_back(y);
com[find(x)] = find(y);
}
int cnt = 0;
for (int i = 1; i <= n; i++) g[find(i)].push_back(i);
int ans = n;
for (int i = 1; i <= n; i++)
if (g[i].size() != 0) {
int cnt = 0;
for (int j = 0; j < g[i].size(); j++) gra[g[i][j]].clear(), cnt++;
for (int j = 0; j < g[i].size(); j++) {
int x = g[i][j];
for (int z = 0; z < c[x].size(); z++)
gra[x].push_back(c[x][z]), deg[c[x][z]]++;
}
queue<int> q;
for (int j = 0; j < g[i].size(); j++)
if (deg[g[i][j]] == 0) q.push(g[i][j]);
while (!q.empty()) {
cnt--;
int x = q.front();
q.pop();
for (int j = 0; j < gra[x].size(); j++) {
int y = gra[x][j];
deg[y]--;
if (deg[y] == 0) q.push(y);
}
}
if (cnt == 0) ans--;
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1 << 17;
int cc = 0;
vector<int> T;
struct node {
bool seen[2];
vector<int> N[2];
int c = -2;
} G[maxN];
struct component {
bool seen;
vector<int> N;
int sz = 0;
} D[maxN];
void DFS(int v, int d) {
G[v].seen[d] = true;
for (int u : G[v].N[d])
if (!G[u].seen[d]) DFS(u, d);
if (!d)
T.push_back(v);
else {
G[v].c = cc;
D[cc].sz++;
}
}
pair<int, bool> DFS_C(int v) {
D[v].seen = true;
pair<int, bool> R = {D[v].sz, D[v].sz > 1};
for (int u : D[v].N)
if (!D[u].seen) {
pair<int, bool> C = DFS_C(u);
R.first += C.first;
R.second |= C.second;
}
return R;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
G[u].N[0].push_back(v);
G[v].N[1].push_back(u);
}
for (int v = 1; v <= n; v++)
if (!G[v].seen[0]) DFS(v, 0);
reverse(T.begin(), T.end());
for (int v : T)
if (!G[v].seen[1]) {
DFS(v, 1);
cc++;
}
for (int v = 1; v <= n; v++)
for (int u : G[v].N[0])
if (G[v].c != G[u].c) {
D[G[v].c].N.push_back(G[u].c);
D[G[u].c].N.push_back(G[v].c);
}
int r = 0;
for (int v = 0; v < cc; v++)
if (!D[v].seen) {
pair<int, bool> c = DFS_C(v);
r += c.first;
if (!c.second) r--;
}
cout << r;
}
| 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>
std::vector<bool> seen;
std::vector<int> in_degree;
std::vector<std::vector<int>> G, H, ccs;
void dfs(const int& u, std::vector<int>& cc) {
seen[u] = true;
cc.push_back(u);
for (auto& v : H[u]) {
if (!seen[v]) {
dfs(v, cc);
}
}
}
int solve(const std::vector<int>& cc) {
int count, u, n;
std::queue<int> q;
n = cc.size();
count = 0;
for (auto& v : cc) {
if (in_degree[v] == 0) {
++count;
q.push(v);
}
}
while (!q.empty()) {
u = q.front();
q.pop();
for (auto& v : G[u]) {
if ((--in_degree[v]) == 0) {
++count;
q.push(v);
}
}
}
return n - (count == n);
}
int main(void) {
int answer, n, m, u, v, i;
std::cin >> n >> m;
G.resize(n + 1);
H.resize(n + 1);
seen.resize(n + 1);
in_degree.resize(n + 1);
for (i = 0; i < m; ++i) {
std::cin >> u >> v;
++in_degree[v];
G[u].push_back(v);
H[u].push_back(v);
H[v].push_back(u);
}
for (u = 1; u <= n; ++u) {
if (!seen[u]) {
ccs.push_back(std::vector<int>());
dfs(u, ccs.back());
}
}
answer = 0;
for (auto& cc : ccs) {
answer += solve(cc);
}
std::cout << answer << std::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 LN = (long long)(5e6), LK = (long long)(1e6),
INF = (long long)(1e18), MOD = (long long)(1e9) + 7;
long long N, M, ind, ans, tcount, tcomp;
vector<vector<int> > adj;
vector<set<int> > adj1;
struct SNode {
int disc, low, component;
bool visited, in_stack;
};
vector<SNode> node;
struct SSCC {
vector<vector<int> > component;
stack<int> path;
int C;
void build() { component.resize(N); }
void process(int u) {
int v = path.top();
while (v != u) {
component[C].push_back(v);
node[v].component = C;
node[v].in_stack = false;
path.pop();
v = path.top();
}
component[C].push_back(u);
node[v].component = C;
node[u].in_stack = false;
path.pop();
ans += component[C].size() - 1;
C++;
}
};
SSCC SCC;
void dfs(int u) {
SCC.path.push(u);
node[u].in_stack = true;
node[u].visited = true;
node[u].disc = node[u].low = ind++;
for (auto v : adj[u]) {
if (!node[v].visited) dfs(v);
if (node[v].in_stack) node[u].low = min(node[u].low, node[v].low);
}
if (node[u].disc == node[u].low) SCC.process(u);
}
void dfs1(int u) {
if (node[u].visited) return;
node[u].visited = true;
tcount++;
tcomp += (SCC.component[u].size() > 1 ? 1 : 0);
for (auto v : adj1[u]) dfs1(v);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> N;
adj.resize(N);
adj1.resize(N);
node.resize(N);
SCC.build();
cin >> M;
for (int i = 0, u, v; i < M; i++) {
cin >> u >> v;
u--;
v--;
adj[u].push_back(v);
}
for (int u = 0; u < N; u++)
if (!node[u].visited) dfs(u);
for (int u = 0; u < N; u++) {
node[u].visited = false;
for (auto v : adj[u])
if (node[u].component != node[v].component &&
!adj1[node[u].component].count(node[v].component))
adj1[node[u].component].insert(node[v].component),
adj1[node[v].component].insert(node[u].component);
}
for (int u = 0; u < N; u++, tcomp = tcount = 0) {
dfs1(u);
ans += (tcount ? tcount - 1 : 0);
ans += (tcomp ? 1 : 0);
}
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;
vector<int> gph[100005], rev[100005];
bool ok[100005];
int n, m;
vector<int> dfn;
int vis[100005], comp[100005], csz[100005], piv;
void dfs(int x) {
if (vis[x]) return;
vis[x] = 1;
for (auto &i : gph[x]) {
dfs(i);
}
dfn.push_back(x);
}
void rdfs(int x, int p) {
if (comp[x]) return;
comp[x] = p;
csz[p]++;
for (auto &i : rev[x]) {
rdfs(i, p);
}
}
bool vis2[100005];
bool find_cyc(int x) {
if (vis2[x]) return 0;
vis2[x] = 1;
bool ret = 0;
if (csz[comp[x]] > 1) ret = 1;
for (auto &i : gph[x]) {
if (find_cyc(i)) ret = 1;
}
for (auto &i : rev[x]) {
if (find_cyc(i)) ret = 1;
}
return ret;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
int s, e;
scanf("%d %d", &s, &e);
gph[s].push_back(e);
rev[e].push_back(s);
ok[s] = ok[e] = 1;
}
for (int i = 1; i <= n; i++) {
if (ok[i] && !vis[i]) {
dfs(i);
}
}
reverse(dfn.begin(), dfn.end());
for (auto &i : dfn) {
if (!comp[i]) rdfs(i, ++piv);
}
int ret = n;
for (int i = 1; i <= n; i++) {
if (!vis2[i] && !find_cyc(i)) ret--;
}
cout << 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>
using namespace std;
const int MAXN = 100010;
int par[MAXN], sub[MAXN];
void Init() {
for (int i = 0; i < MAXN; ++i) par[i] = i;
}
int Get(int vr) { return par[vr] == vr ? vr : par[vr] = Get(par[vr]); }
void Merge(int a, int b) { par[Get(a)] = Get(b); }
void SetSub() {
for (int i = 0; i < MAXN; ++i) ++sub[Get(i)];
}
int n, m;
vector<int> fo[MAXN], rev[MAXN];
vector<int> e[MAXN];
bool used[MAXN];
vector<int> ts;
void Dfs1(int vr) {
used[vr] = true;
for (int nxt : fo[vr])
if (!used[nxt]) Dfs1(nxt);
ts.push_back(vr);
}
void Dfs2(int vr) {
used[vr] = true;
for (int prev : rev[vr])
if (!used[prev]) Merge(vr, prev), Dfs2(prev);
}
vector<int> comp;
void Dfs3(int vr) {
used[vr] = true;
comp.push_back(vr);
for (int nxt : e[vr])
if (!used[nxt]) Dfs3(nxt);
}
int main() {
Init();
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
int a, b;
scanf("%d%d", &a, &b);
--a, --b;
fo[a].push_back(b), rev[b].push_back(a);
e[a].push_back(b), e[b].push_back(a);
}
for (int i = 0; i < n; ++i)
if (!used[i]) Dfs1(i);
memset(used, 0, sizeof used);
reverse(ts.begin(), ts.end());
for (int i : ts)
if (!used[i]) Dfs2(i);
SetSub();
memset(used, 0, sizeof used);
int ans = 0;
for (int i = 0; i < n; ++i)
if (!used[i]) {
bool has_cycle = false;
comp.clear();
Dfs3(i);
for (int vr : comp)
if (sub[Get(vr)] > 1) has_cycle = true;
if (has_cycle)
ans += ((int)(comp).size());
else
ans += ((int)(comp).size()) - 1;
}
cout << ans << '\n';
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxm = 1e7 + 9;
const int maxn = 2e5 + 9;
const int N = 1000 + 9;
const int mod = 20100403;
const int inf = 0x3f3f3f3f;
const int base = 131;
const double eps = 1e-4;
int n, m;
struct Edge {
int to, from;
} edge[maxn];
int last[maxn], cnt = 0;
bool vis[maxn];
int low[maxn], dfn[maxn], stck[maxn], head = 0, bl[maxn], scc_cnt = 0,
timee = 0, scc_num[maxn];
int ans = 0;
int fa[maxn];
vector<int> G[maxn];
int read() {
int a = 1, b = 0;
char c = getchar();
while (c > '9' || c < '0') {
if (c == '-') a = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
b = (b << 1) + (b << 3) + (c ^ '0');
c = getchar();
}
return a * b;
}
void print(int x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) print(x / 10);
putchar(x % 10 + '0');
}
void add(int x, int y) {
edge[++cnt].to = y;
edge[cnt].from = last[x];
last[x] = cnt;
}
inline int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void tarjan(int now) {
dfn[now] = low[now] = ++timee;
stck[++head] = now;
vis[now] = 1;
for (int i = last[now]; i; i = edge[i].from) {
if (!dfn[edge[i].to])
tarjan(edge[i].to), low[now] = min(low[edge[i].to], low[now]);
else if (vis[edge[i].to])
low[now] = min(dfn[edge[i].to], low[now]);
}
if (low[now] == dfn[now]) {
scc_cnt++;
int tmp;
do {
tmp = stck[head--];
scc_num[scc_cnt]++;
vis[tmp] = 0;
bl[tmp] = scc_cnt;
} while (tmp != now);
}
}
int main() {
int x, y;
n = read(), m = read();
for (int i = (1); i <= (n); ++i) fa[i] = i;
for (int i = (1); i <= (m); ++i) {
x = read(), y = read();
add(x, y);
fa[find(x)] = find(y);
}
for (int i = (1); i <= (n); ++i) G[find(i)].push_back(i);
for (int i = (1); i <= (n); ++i) {
if (find(i) == i) {
scc_cnt = 0;
timee = 0;
head = 0;
for (int j = 0, k = G[i].size(); j < k; ++j) {
if (!dfn[G[i][j]]) tarjan(G[i][j]);
}
if (scc_cnt == G[i].size())
ans += G[i].size() - 1;
else
ans += G[i].size();
}
}
print(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.math.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
}
class SCCKosaraju {
public static List<List<Integer>> scc(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> order = new ArrayList<>();
for (int i = 0; i < n; i++)
if (!used[i])
dfs(graph, used, order, i);
List<Integer>[] reverseGraph = new List[n];
for (int i = 0; i < n; i++)
reverseGraph[i] = new ArrayList<>();
for (int i = 0; i < n; i++)
for (int j : graph[i])
reverseGraph[j].add(i);
List<List<Integer>> components = new ArrayList<>();
Arrays.fill(used, false);
Collections.reverse(order);
for (int u : order)
if (!used[u]) {
List<Integer> component = new ArrayList<>();
dfs(reverseGraph, used, component, u);
components.add(component);
}
return components;
}
static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res,
int u) {
used[u] = true;
for (int v : graph[u])
if (!used[v])
dfs(graph, used, res, v);
res.add(u);
}
// Usage example
public static void main(String[] args) {
List<Integer>[] g = new List[3];
for (int i = 0; i < g.length; i++)
g[i] = new ArrayList<>();
g[2].add(0);
g[2].add(1);
g[0].add(1);
g[1].add(0);
List<List<Integer>> components = scc(g);
System.out.println(components);
}
}
class Task {
int[] arr, rev;
boolean[] vis;
List<Integer>[] adjl;
Graph graph;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt(), m = in.readInt(), ret = n, M = m;
adjl = new List[n];
arr = new int[n];
rev = new int[n];
vis = new boolean[n];
for (int i=0; i<n; i++) adjl[i]=new ArrayList<Integer>();
while (m-->0) {
int a=in.readInt()-1, b=in.readInt()-1;
adjl[a].add(b);
}
List<List<Integer>> list=SCCKosaraju.scc(adjl);
// if (M != 6970)
{
for (int i=0; i<list.size(); i++) {
// out.printLine(list.get(i));
for (int j: list.get(i)) arr[j]=i;
}
graph = new Graph(list.size());
for (int i=0; i<n; i++) if (!vis[i]) makeGraph(i);
n = graph.vertexCount();
rev = new int[n];
// out.printLine(arr);
for (int i: arr) rev[i]++;
// out.printLine(arr);
Arrays.fill(vis, false);
for (int i = 0; i < n; i++)
if (!vis[i]) {
ret -= dfs(i);
// out.printLine(i, ret);
}
out.printLine(ret);
}
}
void makeGraph(int u) {
vis[u]=true;
for (int v: adjl[u]) {
graph.addSimpleEdge(arr[u], arr[v]);
if (!vis[v]) makeGraph(v);
}
}
int dfs(int u) {
// if (x++>100000) return 0;
int ret = rev[u] == 1 ? 1 : 0;
vis[u] = true;
for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) {
int v = graph.destination(i);
if (!vis[v])
ret &= dfs(v);
}
for (int i = graph.firstInbound(u); i != -1; i = graph.nextInbound(i)) {
int v = graph.source(i);
if (!vis[v])
ret &= dfs(v);
}
return ret;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void printLine() {
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void printLine(char i) {
writer.println(i);
}
public void printLine(char[] array) {
writer.println(array);
}
public void printFormat(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void printLine(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void printLine(int i) {
writer.println(i);
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static long[] readLongArray(InputReader in, int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = in.readLong();
return array;
}
public static double[] readDoubleArray(InputReader in, int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++)
array[i] = in.readDouble();
return array;
}
public static String[] readStringArray(InputReader in, int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++)
array[i] = in.readString();
return array;
}
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++)
array[i] = in.readCharacter();
return array;
}
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
public static void readLongArrays(InputReader in, long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readLong();
}
}
public static void readDoubleArrays(InputReader in, double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readDouble();
}
}
public static char[][] readTable(InputReader in, int rowCount,
int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readCharArray(in, columnCount);
return table;
}
public static int[][] readIntTable(InputReader in, int rowCount,
int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
public static double[][] readDoubleTable(InputReader in, int rowCount,
int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readDoubleArray(in, columnCount);
return table;
}
public static long[][] readLongTable(InputReader in, int rowCount,
int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readLongArray(in, columnCount);
return table;
}
public static String[][] readStringTable(InputReader in, int rowCount,
int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readStringArray(in, columnCount);
return table;
}
public static String readText(InputReader in) {
StringBuilder result = new StringBuilder();
while (true) {
int character = in.read();
if (character == '\r')
continue;
if (character == -1)
break;
result.append((char) character);
}
return result.toString();
}
public static void readStringArrays(InputReader in, String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readString();
}
}
public static void printTable(OutputWriter out, char[][] table) {
for (char[] row : table)
out.printLine(new String(row));
}
}
class SumIntervalTree extends LongIntervalTree {
public SumIntervalTree(int size) {
super(size);
}
@Override
protected long joinValue(long left, long right) {
return left + right;
}
@Override
protected long joinDelta(long was, long delta) {
return was + delta;
}
@Override
protected long accumulate(long value, long delta, int length) {
return value + delta * length;
}
@Override
protected long neutralValue() {
return 0;
}
@Override
protected long neutralDelta() {
return 0;
}
}
abstract class IntervalTree {
protected int size;
protected IntervalTree(int size) {
this(size, true);
}
public IntervalTree(int size, boolean shouldInit) {
this.size = size;
int nodeCount = Math.max(1, Integer.highestOneBit(size) << 2);
initData(size, nodeCount);
if (shouldInit)
init();
}
protected abstract void initData(int size, int nodeCount);
protected abstract void initAfter(int root, int left, int right, int middle);
protected abstract void initBefore(int root, int left, int right, int middle);
protected abstract void initLeaf(int root, int index);
protected abstract void updatePostProcess(int root, int left, int right,
int from, int to, long delta, int middle);
protected abstract void updatePreProcess(int root, int left, int right,
int from, int to, long delta, int middle);
protected abstract void updateFull(int root, int left, int right, int from,
int to, long delta);
protected abstract long queryPostProcess(int root, int left, int right,
int from, int to, int middle, long leftResult, long rightResult);
protected abstract void queryPreProcess(int root, int left, int right,
int from, int to, int middle);
protected abstract long queryFull(int root, int left, int right, int from,
int to);
protected abstract long emptySegmentResult();
public void init() {
if (size == 0)
return;
init(0, 0, size - 1);
}
private void init(int root, int left, int right) {
if (left == right) {
initLeaf(root, left);
} else {
int middle = (left + right) >> 1;
initBefore(root, left, right, middle);
init(2 * root + 1, left, middle);
init(2 * root + 2, middle + 1, right);
initAfter(root, left, right, middle);
}
}
public void update(int from, int to, long delta) {
update(0, 0, size - 1, from, to, delta);
}
protected void update(int root, int left, int right, int from, int to,
long delta) {
if (left > to || right < from)
return;
if (left >= from && right <= to) {
updateFull(root, left, right, from, to, delta);
return;
}
int middle = (left + right) >> 1;
updatePreProcess(root, left, right, from, to, delta, middle);
update(2 * root + 1, left, middle, from, to, delta);
update(2 * root + 2, middle + 1, right, from, to, delta);
updatePostProcess(root, left, right, from, to, delta, middle);
}
public long query(int from, int to) {
return query(0, 0, size - 1, from, to);
}
protected long query(int root, int left, int right, int from, int to) {
if (left > to || right < from)
return emptySegmentResult();
if (left >= from && right <= to)
return queryFull(root, left, right, from, to);
int middle = (left + right) >> 1;
queryPreProcess(root, left, right, from, to, middle);
long leftResult = query(2 * root + 1, left, middle, from, to);
long rightResult = query(2 * root + 2, middle + 1, right, from, to);
return queryPostProcess(root, left, right, from, to, middle,
leftResult, rightResult);
}
}
abstract class LongIntervalTree extends IntervalTree {
protected long[] value;
protected long[] delta;
protected LongIntervalTree(int size) {
this(size, true);
}
public LongIntervalTree(int size, boolean shouldInit) {
super(size, shouldInit);
}
@Override
protected void initData(int size, int nodeCount) {
value = new long[nodeCount];
delta = new long[nodeCount];
}
protected abstract long joinValue(long left, long right);
protected abstract long joinDelta(long was, long delta);
protected abstract long accumulate(long value, long delta, int length);
protected abstract long neutralValue();
protected abstract long neutralDelta();
protected long initValue(int index) {
return neutralValue();
}
@Override
protected void initAfter(int root, int left, int right, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
delta[root] = neutralDelta();
}
@Override
protected void initBefore(int root, int left, int right, int middle) {
}
@Override
protected void initLeaf(int root, int index) {
value[root] = initValue(index);
delta[root] = neutralDelta();
}
@Override
protected void updatePostProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
}
@Override
protected void updatePreProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
pushDown(root, left, middle, right);
}
protected void pushDown(int root, int left, int middle, int right) {
value[2 * root + 1] = accumulate(value[2 * root + 1], delta[root],
middle - left + 1);
value[2 * root + 2] = accumulate(value[2 * root + 2], delta[root],
right - middle);
delta[2 * root + 1] = joinDelta(delta[2 * root + 1], delta[root]);
delta[2 * root + 2] = joinDelta(delta[2 * root + 2], delta[root]);
delta[root] = neutralDelta();
}
@Override
protected void updateFull(int root, int left, int right, int from, int to,
long delta) {
value[root] = accumulate(value[root], delta, right - left + 1);
this.delta[root] = joinDelta(this.delta[root], delta);
}
@Override
protected long queryPostProcess(int root, int left, int right, int from,
int to, int middle, long leftResult, long rightResult) {
return joinValue(leftResult, rightResult);
}
@Override
protected void queryPreProcess(int root, int left, int right, int from,
int to, int middle) {
pushDown(root, left, middle, right);
}
@Override
protected long queryFull(int root, int left, int right, int from, int to) {
return value[root];
}
@Override
protected long emptySegmentResult() {
return neutralValue();
}
}
class IntPair implements Comparable<IntPair> {
public final int first, second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
return "(" + first + "," + second + ")";
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
IntPair intPair = (IntPair) o;
return first == intPair.first && second == intPair.second;
}
@Override
public int hashCode() {
int result = first;
result = 31 * result + second;
return result;
}
public int compareTo(IntPair o) {
if (first < o.first)
return -1;
if (first > o.first)
return 1;
if (second < o.second)
return -1;
if (second > o.second)
return 1;
return 0;
}
}
class Matrix {
public static long mod = Long.MAX_VALUE;
public final long[][] data;
public final int rowCount;
public final int columnCount;
public Matrix(int rowCount, int columnCount) {
this.rowCount = rowCount;
this.columnCount = columnCount;
this.data = new long[rowCount][columnCount];
}
public Matrix(long[][] data) {
this.rowCount = data.length;
this.columnCount = data[0].length;
this.data = data;
}
public static Matrix add(Matrix first, Matrix second) {
Matrix result = new Matrix(first.rowCount, first.columnCount);
for (int i = 0; i < result.rowCount; i++) {
for (int j = 0; j < result.columnCount; j++) {
result.data[i][j] = first.data[i][j] + second.data[i][j];
if (result.data[i][j] >= mod)
result.data[i][j] -= mod;
}
}
return result;
}
public static Matrix multiply(Matrix first, Matrix second) {
Matrix result = new Matrix(first.rowCount, second.columnCount);
for (int i = 0; i < first.rowCount; i++) {
for (int j = 0; j < second.rowCount; j++) {
for (int k = 0; k < second.columnCount; k++)
result.data[i][k] = (result.data[i][k] + first.data[i][j]
* second.data[j][k])
% mod;
}
}
return result;
}
public static Matrix fastMultiply(Matrix first, Matrix second) {
Matrix result = new Matrix(first.rowCount, second.columnCount);
for (int i = 0; i < first.rowCount; i++) {
for (int j = 0; j < second.rowCount; j++) {
for (int k = 0; k < second.columnCount; k++)
result.data[i][k] += first.data[i][j] * second.data[j][k];
}
}
for (int i = 0; i < first.rowCount; i++) {
for (int j = 0; j < second.columnCount; j++)
result.data[i][j] %= mod;
}
return result;
}
public static Matrix identityMatrix(int size) {
Matrix result = new Matrix(size, size);
for (int i = 0; i < size; i++)
result.data[i][i] = 1;
return result;
}
public static long[] convert(long[][] matrix) {
long[] result = new long[matrix.length * matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++)
result[i * matrix.length + j] = matrix[i][j];
}
return result;
}
public static long[] sumPowers(long[] matrix, long exponent, long mod,
int side) {
long[] result = new long[matrix.length];
long[] power = new long[matrix.length];
long[] temp = new long[matrix.length];
long[] temp2 = new long[matrix.length];
sumPowers(matrix, result, power, temp, temp2, exponent + 1, mod, side);
return result;
}
private static void sumPowers(long[] matrix, long[] result, long[] power,
long[] temp, long[] temp2, long exponent, long mod, int side) {
if (exponent == 0) {
for (int i = 0; i < matrix.length; i += side + 1)
power[i] = 1 % mod;
return;
}
if ((exponent & 1) == 0) {
sumPowers(matrix, result, temp, power, temp2, exponent >> 1, mod,
side);
multiply(temp2, result, temp, mod, side);
add(result, temp2, mod, side);
multiply(power, temp, temp, mod, side);
} else {
sumPowers(matrix, result, temp, power, temp2, exponent - 1, mod,
side);
add(result, temp, mod, side);
multiply(power, temp, matrix, mod, side);
}
}
public static long[][] convert(long[] matrix, int side) {
long[][] result = new long[side][side];
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++)
result[i][j] = matrix[i * side + j];
}
return result;
}
public static long[] power(long[] matrix, long exponent, long mod, int side) {
long[] result = new long[matrix.length];
long[] temp = new long[result.length];
power(matrix, result, temp, exponent, mod, side);
return result;
}
private static void power(long[] matrix, long[] result, long[] temp,
long exponent, long mod, int side) {
if (exponent == 0) {
for (int i = 0; i < matrix.length; i += side + 1)
result[i] = 1 % mod;
return;
}
if ((exponent & 1) == 0) {
power(matrix, temp, result, exponent >> 1, mod, side);
multiply(result, temp, temp, mod, side);
} else {
power(matrix, temp, result, exponent - 1, mod, side);
multiply(result, temp, matrix, mod, side);
}
}
public static void multiply(long[] c, long[] a, long[] b, long mod, int side) {
Arrays.fill(c, 0);
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++) {
for (int k = 0; k < side; k++) {
c[i * side + k] += a[i * side + j] * b[j * side + k];
if ((j & 3) == 3) {
c[i * side + k] %= mod;
}
}
}
}
for (int i = 0; i < c.length; i++)
c[i] %= mod;
}
public static void add(long[] c, long[] a, long mod, int side) {
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++) {
c[i * side + j] += a[i * side + j];
if (c[i * side + j] >= mod)
c[i * side + j] -= mod;
}
}
}
public static long[] fastPower(long[] matrix, long exponent, long mod,
int side) {
long[] result = new long[matrix.length];
long[] temp = new long[result.length];
fastPower(matrix, result, temp, exponent, mod, side);
return result;
}
private static void fastPower(long[] matrix, long[] result, long[] temp,
long exponent, long mod, int side) {
if (exponent == 0) {
for (int i = 0; i < matrix.length; i += side + 1)
result[i] = 1;
return;
}
if ((exponent & 1) == 0) {
fastPower(matrix, temp, result, exponent >> 1, mod, side);
fastMultiply(result, temp, temp, mod, side);
} else {
power(matrix, temp, result, exponent - 1, mod, side);
fastMultiply(result, temp, matrix, mod, side);
}
}
public static void fastMultiply(long[] c, long[] a, long[] b, long mod,
int side) {
Arrays.fill(c, 0);
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++) {
for (int k = 0; k < side; k++)
c[i * side + k] += a[i * side + j] * b[j * side + k];
}
}
for (int i = 0; i < c.length; i++)
c[i] %= mod;
}
public Matrix power(long exponent) {
if (exponent == 0)
return identityMatrix(rowCount);
if (exponent == 1)
return this;
Matrix result = power(exponent >> 1);
result = multiply(result, result);
if ((exponent & 1) == 1)
result = multiply(result, this);
return result;
}
public Matrix fastPower(long exponent) {
if (exponent == 0)
return identityMatrix(rowCount);
if (exponent == 1)
return this;
Matrix result = power(exponent >> 1);
result = fastMultiply(result, result);
if ((exponent & 1) == 1)
result = fastMultiply(result, this);
return result;
}
}
class MiscUtils {
public static final int[] DX4 = { 1, 0, -1, 0 };
public static final int[] DY4 = { 0, -1, 0, 1 };
public static final int[] DX8 = { 1, 1, 1, 0, -1, -1, -1, 0 };
public static final int[] DY8 = { -1, 0, 1, 1, 1, 0, -1, -1 };
public static final int[] DX_KNIGHT = { 2, 1, -1, -2, -2, -1, 1, 2 };
public static final int[] DY_KNIGHT = { 1, 2, 2, 1, -1, -2, -2, -1 };
private static final String[] ROMAN_TOKENS = { "M", "CM", "D", "CD", "C",
"XC", "L", "XL", "X", "IX", "V", "IV", "I" };
private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1 };
public static long josephProblem(long n, int k) {
if (n == 1)
return 0;
if (k == 1)
return n - 1;
if (k > n)
return (josephProblem(n - 1, k) + k) % n;
long count = n / k;
long result = josephProblem(n - count, k);
result -= n % k;
if (result < 0)
result += n;
else
result += result / (k - 1);
return result;
}
public static boolean isValidCell(int row, int column, int rowCount,
int columnCount) {
return row >= 0 && row < rowCount && column >= 0
&& column < columnCount;
}
public static long maximalRectangleSum(long[][] array) {
int n = array.length;
int m = array[0].length;
long[][] partialSums = new long[n + 1][m + 1];
for (int i = 0; i < n; i++) {
long rowSum = 0;
for (int j = 0; j < m; j++) {
rowSum += array[i][j];
partialSums[i + 1][j + 1] = partialSums[i][j + 1] + rowSum;
}
}
long result = Long.MIN_VALUE;
for (int i = 0; i < m; i++) {
for (int j = i; j < m; j++) {
long minPartialSum = 0;
for (int k = 1; k <= n; k++) {
long current = partialSums[k][j + 1] - partialSums[k][i];
result = Math.max(result, current - minPartialSum);
minPartialSum = Math.min(minPartialSum, current);
}
}
}
return result;
}
public static int parseIP(String ip) {
String[] components = ip.split("[.]");
int result = 0;
for (int i = 0; i < 4; i++)
result += (1 << (24 - 8 * i)) * Integer.parseInt(components[i]);
return result;
}
public static String buildIP(int mask) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (i != 0)
result.append('.');
result.append(mask >> (24 - 8 * i) & 255);
}
return result.toString();
}
public static <T> boolean equals(T first, T second) {
return first == null && second == null || first != null
&& first.equals(second);
}
public static boolean isVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'
|| ch == 'Y';
}
public static boolean isStrictVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
public static String convertToRoman(int number) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number >= ROMAN_VALUES[i]) {
number -= ROMAN_VALUES[i];
result.append(ROMAN_TOKENS[i]);
}
}
return result.toString();
}
public static int convertFromRoman(String number) {
int result = 0;
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number.startsWith(ROMAN_TOKENS[i])) {
number = number.substring(ROMAN_TOKENS[i].length());
result += ROMAN_VALUES[i];
}
}
return result;
}
public static int distance(int x1, int y1, int x2, int y2) {
int dx = x1 - x2;
int dy = y1 - y2;
return dx * dx + dy * dy;
}
public static <T extends Comparable<T>> T min(T first, T second) {
if (first.compareTo(second) <= 0)
return first;
return second;
}
public static <T extends Comparable<T>> T max(T first, T second) {
if (first.compareTo(second) <= 0)
return second;
return first;
}
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++)
array[i]--;
}
}
public static int[] getIntArray(String s) {
String[] tokens = s.split(" ");
int[] result = new int[tokens.length];
for (int i = 0; i < result.length; i++)
result[i] = Integer.parseInt(tokens[i]);
return result;
}
}
class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
public long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public static Graph createGraph(int vertexCount, int[] from, int[] to) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addSimpleEdge(from[i], to[i]);
return graph;
}
public static Graph createWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addWeightedEdge(from[i], to[i], weight[i]);
return graph;
}
public static Graph createFlowGraph(int vertexCount, int[] from, int[] to,
long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowEdge(from[i], to[i], capacity[i]);
return graph;
}
public static Graph createFlowWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight, long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]);
return graph;
}
public static Graph createTree(int[] parent) {
Graph graph = new Graph(parent.length + 1, parent.length);
for (int i = 0; i < parent.length; i++)
graph.addSimpleEdge(parent[i], i + 1);
return graph;
}
public int addEdge(int fromID, int toID, long weight, long capacity,
int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1)
nextOutbound[edgeCount] = firstOutbound[fromID];
else
nextOutbound[edgeCount] = -1;
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1)
nextInbound[edgeCount] = firstInbound[toID];
else
nextInbound[edgeCount] = -1;
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null)
this.capacity = new long[from.length];
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null)
this.weight = new long[from.length];
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null)
edges[edgeCount] = createEdge(edgeCount);
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight,
long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addFlowEdge(int from, int to, long capacity) {
return addFlowWeightedEdge(from, to, 0, capacity);
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
public final int addSimpleEdge(int from, int to) {
return addWeightedEdge(from, to, 0);
}
public final int vertexCount() {
return vertexCount;
}
public final int edgeCount() {
return edgeCount;
}
protected final int edgeCapacity() {
return from.length;
}
public final Edge edge(int id) {
initEdges();
return edges[id];
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int firstInbound(int vertex) {
initInbound();
int id = firstInbound[vertex];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int nextInbound(int id) {
initInbound();
id = nextInbound[id];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int source(int id) {
return from[id];
}
public final int destination(int id) {
return to[id];
}
public final long weight(int id) {
if (weight == null)
return 0;
return weight[id];
}
public final long capacity(int id) {
if (capacity == null)
return 0;
return capacity[id];
}
public final long flow(int id) {
if (reverseEdge == null)
return 0;
return capacity[reverseEdge[id]];
}
public final void pushFlow(int id, long flow) {
if (flow == 0)
return;
if (flow > 0) {
if (capacity(id) < flow)
throw new IllegalArgumentException("Not enough capacity");
} else {
if (flow(id) < -flow)
throw new IllegalArgumentException("Not enough capacity");
}
capacity[id] -= flow;
capacity[reverseEdge[id]] += flow;
}
public int transposed(int id) {
return -1;
}
public final int reverse(int id) {
if (reverseEdge == null)
return -1;
return reverseEdge[id];
}
public final void addVertices(int count) {
ensureVertexCapacity(vertexCount + count);
Arrays.fill(firstOutbound, vertexCount, vertexCount + count, -1);
if (firstInbound != null)
Arrays.fill(firstInbound, vertexCount, vertexCount + count, -1);
vertexCount += count;
}
protected final void initEdges() {
if (edges == null) {
edges = new Edge[from.length];
for (int i = 0; i < edgeCount; i++)
edges[i] = createEdge(i);
}
}
public final void removeVertex(int vertex) {
int id = firstOutbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextOutbound[id];
}
initInbound();
id = firstInbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextInbound[id];
}
}
private void initInbound() {
if (firstInbound == null) {
firstInbound = new int[firstOutbound.length];
Arrays.fill(firstInbound, 0, vertexCount, -1);
nextInbound = new int[from.length];
for (int i = 0; i < edgeCount; i++) {
nextInbound[i] = firstInbound[to[i]];
firstInbound[to[i]] = i;
}
}
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final void setFlag(int id, int bit) {
flags[id] |= 1 << bit;
}
public final void removeFlag(int id, int bit) {
flags[id] &= -1 - (1 << bit);
}
public final void removeEdge(int id) {
setFlag(id, REMOVED_BIT);
}
public final void restoreEdge(int id) {
removeFlag(id, REMOVED_BIT);
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
public final Iterable<Edge> outbound(final int id) {
initEdges();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstOutbound, nextOutbound);
}
};
}
public final Iterable<Edge> inbound(final int id) {
initEdges();
initInbound();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstInbound, nextInbound);
}
};
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null)
edges = resize(edges, newSize);
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null)
nextInbound = resize(nextInbound, newSize);
if (weight != null)
weight = resize(weight, newSize);
if (capacity != null)
capacity = resize(capacity, newSize);
if (reverseEdge != null)
reverseEdge = resize(reverseEdge, newSize);
flags = resize(flags, newSize);
}
}
private void ensureVertexCapacity(int size) {
if (firstOutbound.length < size) {
int newSize = Math.max(size, 2 * from.length);
firstOutbound = resize(firstOutbound, newSize);
if (firstInbound != null)
firstInbound = resize(firstInbound, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public final boolean isSparse() {
return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
public int getSource() {
return source(id);
}
public int getDestination() {
return destination(id);
}
public long getWeight() {
return weight(id);
}
public long getCapacity() {
return capacity(id);
}
public long getFlow() {
return flow(id);
}
public void pushFlow(long flow) {
Graph.this.pushFlow(id, flow);
}
public boolean getFlag(int bit) {
return flag(id, bit);
}
public void setFlag(int bit) {
Graph.this.setFlag(id, bit);
}
public void removeFlag(int bit) {
Graph.this.removeFlag(id, bit);
}
public int getTransposedID() {
return transposed(id);
}
public Edge getTransposedEdge() {
int reverseID = getTransposedID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getReverseID() {
return reverse(id);
}
public Edge getReverseEdge() {
int reverseID = getReverseID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getID() {
return id;
}
public void remove() {
removeEdge(id);
}
public void restore() {
restoreEdge(id);
}
}
public class EdgeIterator implements Iterator<Edge> {
private int edgeID;
private final int[] next;
private int lastID = -1;
public EdgeIterator(int id, int[] first, int[] next) {
this.next = next;
edgeID = nextEdge(first[id]);
}
private int nextEdge(int id) {
while (id != -1 && isRemoved(id))
id = next[id];
return id;
}
public boolean hasNext() {
return edgeID != -1;
}
public Edge next() {
if (edgeID == -1)
throw new NoSuchElementException();
lastID = edgeID;
edgeID = nextEdge(next[lastID]);
return edges[lastID];
}
public void remove() {
if (lastID == -1)
throw new IllegalStateException();
removeEdge(lastID);
lastID = -1;
}
}
}
class MaxFlow {
private final Graph graph;
private int source;
private int destination;
private int[] queue;
private int[] distance;
private int[] nextEdge;
private MaxFlow(Graph graph, int source, int destination) {
this.graph = graph;
this.source = source;
this.destination = destination;
int vertexCount = graph.vertexCount();
queue = new int[vertexCount];
distance = new int[vertexCount];
nextEdge = new int[vertexCount];
}
public static long dinic(Graph graph, int source, int destination) {
return new MaxFlow(graph, source, destination).dinic();
}
private long dinic() {
long totalFlow = 0;
while (true) {
edgeDistances();
if (distance[destination] == -1)
break;
Arrays.fill(nextEdge, -2);
totalFlow += dinicImpl(source, Long.MAX_VALUE);
}
return totalFlow;
}
private void edgeDistances() {
Arrays.fill(distance, -1);
distance[source] = 0;
int size = 1;
queue[0] = source;
for (int i = 0; i < size; i++) {
int current = queue[i];
int id = graph.firstOutbound(current);
while (id != -1) {
if (graph.capacity(id) != 0) {
int next = graph.destination(id);
if (distance[next] == -1) {
distance[next] = distance[current] + 1;
queue[size++] = next;
}
}
id = graph.nextOutbound(id);
}
}
}
private long dinicImpl(int source, long flow) {
if (source == destination)
return flow;
if (flow == 0 || distance[source] == distance[destination])
return 0;
int id = nextEdge[source];
if (id == -2)
nextEdge[source] = id = graph.firstOutbound(source);
long totalPushed = 0;
while (id != -1) {
int nextDestinationID = graph.destination(id);
if (graph.capacity(id) != 0
&& distance[nextDestinationID] == distance[source] + 1) {
long pushed = dinicImpl(nextDestinationID,
Math.min(flow, graph.capacity(id)));
if (pushed != 0) {
graph.pushFlow(id, pushed);
flow -= pushed;
totalPushed += pushed;
if (flow == 0)
return totalPushed;
}
}
nextEdge[source] = id = graph.nextOutbound(id);
}
return totalPushed;
}
}
interface Edge {
public int getSource();
public int getDestination();
public long getWeight();
public long getCapacity();
public long getFlow();
public void pushFlow(long flow);
public boolean getFlag(int bit);
public void setFlag(int bit);
public void removeFlag(int bit);
public int getTransposedID();
public Edge getTransposedEdge();
public int getReverseID();
public Edge getReverseEdge();
public int getID();
public void remove();
public void restore();
}
class Point {
public static final Point ORIGIN = new Point(0, 0);
public final double x;
public final double y;
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Line line(Point other) {
if (equals(other))
return null;
double a = other.y - y;
double b = x - other.x;
double c = -a * x - b * y;
return new Line(a, b, c);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Point point = (Point) o;
return Math.abs(x - point.x) <= GeometryUtils.epsilon
&& Math.abs(y - point.y) <= GeometryUtils.epsilon;
}
@Override
public int hashCode() {
int result;
long temp;
temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L;
result = (int) (temp ^ (temp >>> 32));
temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
public double distance(Point other) {
return GeometryUtils.fastHypot(x - other.x, y - other.y);
}
public double distance(Line line) {
return Math.abs(line.a * x + line.b * y + line.c);
}
public double value() {
return GeometryUtils.fastHypot(x, y);
}
public double angle() {
return Math.atan2(y, x);
}
public static Point readPoint(InputReader in) {
double x = in.readDouble();
double y = in.readDouble();
return new Point(x, y);
}
public Point rotate(double angle) {
double nx = x * Math.cos(angle) - y * Math.sin(angle);
double ny = y * Math.cos(angle) + x * Math.sin(angle);
return new Point(nx, ny);
}
}
class Line {
public final double a;
public final double b;
public final double c;
public Line(Point p, double angle) {
a = Math.sin(angle);
b = -Math.cos(angle);
c = -p.x * a - p.y * b;
}
public Line(double a, double b, double c) {
double h = GeometryUtils.fastHypot(a, b);
this.a = a / h;
this.b = b / h;
this.c = c / h;
}
public Point intersect(Line other) {
if (parallel(other))
return null;
double determinant = b * other.a - a * other.b;
double x = (c * other.b - b * other.c) / determinant;
double y = (a * other.c - c * other.a) / determinant;
return new Point(x, y);
}
public boolean parallel(Line other) {
return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon;
}
public boolean contains(Point point) {
return Math.abs(value(point)) < GeometryUtils.epsilon;
}
public Line perpendicular(Point point) {
return new Line(-b, a, b * point.x - a * point.y);
}
public double value(Point point) {
return a * point.x + b * point.y + c;
}
public double distance(Point center) {
return Math.abs(value(center));
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Line line = (Line) o;
if (!parallel(line))
return false;
if (Math.abs(a * line.c - c * line.a) > GeometryUtils.epsilon
|| Math.abs(b * line.c - c * line.b) > GeometryUtils.epsilon)
return false;
return true;
}
}
class GeometryUtils {
public static double epsilon = 1e-8;
public static double fastHypot(double... x) {
if (x.length == 0)
return 0;
else if (x.length == 1)
return Math.abs(x[0]);
else {
double sumSquares = 0;
for (double value : x)
sumSquares += value * value;
return Math.sqrt(sumSquares);
}
}
public static double fastHypot(double x, double y) {
return Math.sqrt(x * x + y * y);
}
public static double fastHypot(double[] x, double[] y) {
if (x.length == 0)
return 0;
else if (x.length == 1)
return Math.abs(x[0] - y[0]);
else {
double sumSquares = 0;
for (int i = 0; i < x.length; i++) {
double diff = x[i] - y[i];
sumSquares += diff * diff;
}
return Math.sqrt(sumSquares);
}
}
public static double fastHypot(int[] x, int[] y) {
if (x.length == 0)
return 0;
else if (x.length == 1)
return Math.abs(x[0] - y[0]);
else {
double sumSquares = 0;
for (int i = 0; i < x.length; i++) {
double diff = x[i] - y[i];
sumSquares += diff * diff;
}
return Math.sqrt(sumSquares);
}
}
public static double missileTrajectoryLength(double v, double angle,
double g) {
return (v * v * Math.sin(2 * angle)) / g;
}
public static double sphereVolume(double radius) {
return 4 * Math.PI * radius * radius * radius / 3;
}
public static double triangleSquare(double first, double second,
double third) {
double p = (first + second + third) / 2;
return Math.sqrt(p * (p - first) * (p - second) * (p - third));
}
public static double canonicalAngle(double angle) {
while (angle > Math.PI)
angle -= 2 * Math.PI;
while (angle < -Math.PI)
angle += 2 * Math.PI;
return angle;
}
public static double positiveAngle(double angle) {
while (angle > 2 * Math.PI - GeometryUtils.epsilon)
angle -= 2 * Math.PI;
while (angle < -GeometryUtils.epsilon)
angle += 2 * Math.PI;
return angle;
}
}
class IntegerUtils {
public static long gcd(long a, long b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
long temp = a % b;
a = b;
b = temp;
}
return a;
}
public static int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
public static boolean[] generatePrimalityTable(int upTo) {
boolean[] isPrime = new boolean[upTo];
if (upTo < 2)
return isPrime;
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i < upTo; i++) {
if (isPrime[i]) {
for (int j = i * i; j < upTo; j += i)
isPrime[j] = false;
}
}
return isPrime;
}
public static int[] generateBitPrimalityTable(int upTo) {
int[] isPrime = new int[(upTo + 31) >> 5];
if (upTo < 2)
return isPrime;
Arrays.fill(isPrime, -1);
isPrime[0] &= -4;
for (int i = 2; i * i < upTo; i++) {
if ((isPrime[i >> 5] >>> (i & 31) & 1) == 1) {
for (int j = i * i; j < upTo; j += i)
isPrime[j >> 5] &= -1 - (1 << (j & 31));
}
}
return isPrime;
}
public static int[] generateDivisorTable(int upTo) {
int[] divisor = new int[upTo];
for (int i = 1; i < upTo; i++)
divisor[i] = i;
for (int i = 2; i * i < upTo; i++) {
if (divisor[i] == i) {
for (int j = i * i; j < upTo; j += i)
divisor[j] = i;
}
}
return divisor;
}
public static long powerInFactorial(long n, long p) {
long result = 0;
while (n != 0) {
result += n /= p;
}
return result;
}
public static int sumDigits(CharSequence number) {
int result = 0;
for (int i = number.length() - 1; i >= 0; i--)
result += digitValue(number.charAt(i));
return result;
}
public static int digitValue(char digit) {
if (Character.isDigit(digit))
return digit - '0';
if (Character.isUpperCase(digit))
return digit + 10 - 'A';
return digit + 10 - 'a';
}
public static int longCompare(long a, long b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
public static long[][] generateBinomialCoefficients(int n) {
long[][] result = new long[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
result[i][0] = 1;
for (int j = 1; j <= i; j++)
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
}
return result;
}
public static long[][] generateBinomialCoefficients(int n, long module) {
long[][] result = new long[n + 1][n + 1];
if (module == 1)
return result;
for (int i = 0; i <= n; i++) {
result[i][0] = 1;
for (int j = 1; j <= i; j++) {
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
if (result[i][j] >= module)
result[i][j] -= module;
}
}
return result;
}
public static long[] generateBinomialRow(int n, long module) {
long[] result = generateReverse(n + 1, module);
result[0] = 1;
for (int i = 1; i <= n; i++)
result[i] = result[i - 1] * (n - i + 1) % module * result[i]
% module;
return result;
}
public static int[] representationInBase(long number, int base) {
long basePower = base;
int exponent = 1;
while (number >= basePower) {
basePower *= base;
exponent++;
}
int[] representation = new int[exponent];
for (int i = 0; i < exponent; i++) {
basePower /= base;
representation[i] = (int) (number / basePower);
number %= basePower;
}
return representation;
}
public static int trueDivide(int a, int b) {
return (a - trueMod(a, b)) / b;
}
public static long trueDivide(long a, long b) {
return (a - trueMod(a, b)) / b;
}
public static int trueMod(int a, int b) {
a %= b;
a += b;
a %= b;
return a;
}
public static long trueMod(long a, long b) {
a %= b;
a += b;
a %= b;
return a;
}
public static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}
public static long factorial(int n, long mod) {
long result = 1;
for (int i = 2; i <= n; i++)
result = result * i % mod;
return result % mod;
}
public static long power(long base, long exponent) {
if (exponent == 0)
return 1;
long result = power(base, exponent >> 1);
result = result * result;
if ((exponent & 1) != 0)
result = result * base;
return result;
}
public static long power(long base, long exponent, long mod) {
if (base >= mod)
base %= mod;
if (exponent == 0)
return 1 % mod;
long result = power(base, exponent >> 1, mod);
result = result * result % mod;
if ((exponent & 1) != 0)
result = result * base % mod;
return result;
}
public static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static long[] generateFibonacci(long upTo) {
int count = 0;
long last = 0;
long current = 1;
while (current <= upTo) {
long next = last + current;
last = current;
current = next;
count++;
}
return generateFibonacci(count, -1);
}
public static long[] generateFibonacci(int count, long module) {
long[] result = new long[count];
if (module == -1) {
if (count != 0)
result[0] = 1;
if (count > 1)
result[1] = 1;
for (int i = 2; i < count; i++)
result[i] = result[i - 1] + result[i - 2];
} else {
if (count != 0)
result[0] = 1 % module;
if (count > 1)
result[1] = 1 % module;
for (int i = 2; i < count; i++)
result[i] = (result[i - 1] + result[i - 2]) % module;
}
return result;
}
public static long[] generateHappy(int digits) {
long[] happy = new long[(1 << (digits + 1)) - 2];
happy[0] = 4;
happy[1] = 7;
int first = 0;
int last = 2;
for (int i = 2; i <= digits; i++) {
for (int j = 0; j < last - first; j++) {
happy[last + 2 * j] = 10 * happy[first + j] + 4;
happy[last + 2 * j + 1] = 10 * happy[first + j] + 7;
}
int next = last + 2 * (last - first);
first = last;
last = next;
}
return happy;
}
public static long[] generateFactorial(int count, long module) {
long[] result = new long[count];
if (module == -1) {
if (count != 0)
result[0] = 1;
for (int i = 1; i < count; i++)
result[i] = result[i - 1] * i;
} else {
if (count != 0)
result[0] = 1 % module;
for (int i = 1; i < count; i++)
result[i] = (result[i - 1] * i) % module;
}
return result;
}
public static long reverse(long number, long module) {
return power(number, module - 2, module);
}
public static boolean isPrime(long number) {
if (number < 2)
return false;
for (long i = 2; i * i <= number; i++) {
if (number % i == 0)
return false;
}
return true;
}
public static long[] generateReverse(int upTo, long module) {
long[] result = new long[upTo];
if (upTo > 1)
result[1] = 1;
for (int i = 2; i < upTo; i++)
result[i] = (module - module / i * result[((int) (module % i))]
% module)
% module;
return result;
}
public static long[] generateReverseFactorials(int upTo, long module) {
long[] result = generateReverse(upTo, module);
if (upTo > 0)
result[0] = 1;
for (int i = 1; i < upTo; i++)
result[i] = result[i] * result[i - 1] % module;
return result;
}
public static long[] generatePowers(long base, int count, long mod) {
long[] result = new long[count];
if (count != 0)
result[0] = 1 % mod;
for (int i = 1; i < count; i++)
result[i] = result[i - 1] * base % mod;
return result;
}
public static long nextPrime(long from) {
if (from <= 2)
return 2;
from += 1 - (from & 1);
while (!isPrime(from))
from += 2;
return from;
}
public static long binomialCoefficient(int n, int m, long mod) {
if (m < 0 || m > n)
return 0;
if (2 * m > n)
m = n - m;
long result = 1;
for (int i = n - m + 1; i <= n; i++)
result = result * i % mod;
return result
* BigInteger.valueOf(factorial(m, mod))
.modInverse(BigInteger.valueOf(mod)).longValue() % mod;
}
public static boolean isSquare(long number) {
long sqrt = Math.round(Math.sqrt(number));
return sqrt * sqrt == number;
}
public static long findCommon(long aRemainder, long aMod, long bRemainder,
long bMod) {
long modGCD = gcd(aMod, bMod);
long gcdRemainder = aRemainder % modGCD;
if (gcdRemainder != bRemainder % modGCD)
return -1;
aMod /= modGCD;
aRemainder /= modGCD;
bMod /= modGCD;
bRemainder /= modGCD;
long aReverse = BigInteger.valueOf(aMod)
.modInverse(BigInteger.valueOf(bMod)).longValue();
long bReverse = BigInteger.valueOf(bMod)
.modInverse(BigInteger.valueOf(aMod)).longValue();
long mod = aMod * bMod;
return BigInteger
.valueOf(bReverse * aRemainder % mod)
.multiply(BigInteger.valueOf(bMod))
.add(BigInteger.valueOf(aReverse * bRemainder % mod).multiply(
BigInteger.valueOf(aMod))).mod(BigInteger.valueOf(mod))
.longValue()
* modGCD + gcdRemainder;
}
public static long[] generatePowers(long base, long maxValue) {
if (maxValue <= 0)
return new long[0];
int size = 1;
long current = 1;
while (maxValue / base >= current) {
current *= base;
size++;
}
return generatePowers(base, size, Long.MAX_VALUE);
}
}
class GraphAlgorithms {
public static int[] topologicalSort(Graph graph) {
int count = graph.vertexCount();
int[] queue = new int[count];
int[] degree = new int[count];
int size = 0;
for (int i = 0; i < graph.edgeCount(); i++) {
if (!graph.isRemoved(i))
degree[graph.destination(i)]++;
}
for (int i = 0; i < count; i++) {
if (degree[i] == 0)
queue[size++] = i;
}
for (int i = 0; i < size; i++) {
int current = queue[i];
for (int j = graph.firstOutbound(current); j != -1; j = graph
.nextOutbound(j)) {
int next = graph.destination(j);
if (--degree[next] == 0)
queue[size++] = next;
}
}
if (size != count)
return null;
return queue;
}
}
class StronglyConnectedComponents {
private final Graph graph;
private int[] order;
private boolean[] visited;
private int index = 0;
private int vertexCount;
private int[] condensed;
private Set<Integer> next;
private StronglyConnectedComponents(Graph graph) {
this.graph = graph;
vertexCount = graph.vertexCount();
order = new int[vertexCount];
visited = new boolean[vertexCount];
condensed = new int[vertexCount];
}
public static Pair<int[], Graph> kosaraju(Graph graph) {
return new StronglyConnectedComponents(graph).kosaraju();
}
private Pair<int[], Graph> kosaraju() {
for (int i = 0; i < vertexCount; i++) {
if (!visited[i])
firstDFS(i);
}
Arrays.fill(visited, false);
Graph result = new Graph(0);
index = 0;
for (int i = vertexCount - 1; i >= 0; i--) {
if (!visited[order[i]]) {
next = new TreeSet<Integer>();
secondDFS(order[i]);
result.addVertices(1);
for (Object set : next.toArray())
result.addSimpleEdge((Integer) set, index);
index++;
}
}
return Pair.makePair(condensed, result);
}
private void secondDFS(int vertexID) {
if (visited[vertexID]) {
if (condensed[vertexID] != index)
next.add(condensed[vertexID]);
return;
}
condensed[vertexID] = index;
visited[vertexID] = true;
int edgeID = graph.firstInbound(vertexID);
while (edgeID != -1) {
secondDFS(graph.source(edgeID));
edgeID = graph.nextInbound(edgeID);
}
}
private void firstDFS(int vertexID) {
if (visited[vertexID])
return;
visited[vertexID] = true;
int edgeID = graph.firstOutbound(vertexID);
while (edgeID != -1) {
firstDFS(graph.destination(edgeID));
edgeID = graph.nextOutbound(edgeID);
}
order[index++] = vertexID;
}
}
class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static <U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
private Pair(U first, V second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> pair = (Pair<U, V>) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null)
&& !(second != null ? !second.equals(pair.second)
: pair.second != null);
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public Pair<V, U> swap() {
return makePair(second, first);
}
@Override
public String toString() {
return "(" + first + "," + second + ")";
}
@SuppressWarnings({ "unchecked" })
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) first).compareTo(o.first);
if (value != 0)
return value;
return ((Comparable<V>) second).compareTo(o.second);
}
} | 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 MXN = 2e3 + 10;
const long long MX5 = 2e5 + 10;
const long long MX6 = 1e6 + 10;
const long long LOG = 20;
const long long INF = 8e18;
const double eps = 1e-9;
const long long MOD = 1e9 + 7;
long long power(long long a, long long b, long long md) {
return (!b ? 1
: (b & 1 ? a * power(a * a % md, b / 2, md) % md
: power(a * a % md, b / 2, md) % md));
}
long long bmm(long long a, long long b) {
return (a % b == 0 ? b : bmm(b, a % b));
}
string base2(long long n) {
string a = "";
while (n >= 2) {
a += (char)(n % 2 + '0');
n /= 2;
}
a += (char)(n + '0');
reverse((a).begin(), (a).end());
return a;
}
long long n, m, ans, cnt, f;
bool mark[MX5], vis[MX5], prio[MX5];
vector<long long> G[MX5], adj[MX5], T, V;
void DFS(long long u) {
vis[u] = 1, V.push_back(u), cnt++;
for (auto v : G[u]) {
if (!vis[v]) DFS(v);
}
}
void dfs(long long u) {
mark[u] = 1;
for (auto v : adj[u]) {
if (!mark[v]) dfs(v);
}
T.push_back(u);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 0; i < m; i++) {
long long u, v;
cin >> u >> v;
adj[u].push_back(v);
G[u].push_back(v), G[v].push_back(u);
}
for (int i = 1; i <= n; i++) {
if (mark[i]) continue;
T.clear(), V.clear(), f = cnt = 0;
DFS(i);
for (auto u : V)
if (!mark[u]) dfs(u);
reverse((T).begin(), (T).end());
for (auto u : T) {
for (auto v : adj[u])
if (prio[v]) f = 1;
prio[u] = 1;
}
ans += cnt - 1 + f;
}
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 | import java.util.List;
import java.util.Arrays;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author mongsiry013
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
int n,m;
List<Integer> G1[], G2[];
List<Integer> Com[];
int C = 0, ans = 0;
int visited[];
public void solve(int testNumber, Scanner in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
visited = new int[n];
G1 = new ArrayList[n];
G2 = new ArrayList[n];
Com = new ArrayList[n];
for(int i=0; i<n; ++i){
G1[i] = new ArrayList<Integer>();
G2[i] = new ArrayList<Integer>();
Com[i] = new ArrayList<Integer>();
}
Arrays.fill(visited, 0);
for(int i=0; i<m; ++i){
int u, v;
u = in.nextInt()-1;
v = in.nextInt()-1;
G1[u].add(v);
G2[u].add(v);
G2[v].add(u);
}
for(int i=0; i<n; ++i){
if(visited[i] == 0) {
dfs(i);
C++;
}
}
ans -= C;
Arrays.fill(visited, 0);
for(int i=0; i<C; ++i){
for(int j : Com[i]){
if(visited[j] == 0) {
if(dfs2(j)){
ans++;
break;
}
}
}
}
out.println(ans);
}
boolean dfs2(int cur){
visited[cur] = 1;
for(int next : G1[cur]){
if(visited[next] == 1) return true;
else if(visited[next] == 0){
if(dfs2(next)) return true;
}
}
visited[cur] = 2;
return false;
}
void dfs(int cur){
visited[cur] = 1;
for(int next : G2[cur]){
if(visited[next] == 0) dfs(next);
}
ans++;
Com[C].add(cur);
}
}
| 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 <typename T1, typename T2>
ostream& operator<<(ostream& out, pair<T1, T2> a) {
return (out << "(" << a.first << "; " << a.second << ")");
}
const int nmax = 1000 * 1000;
const int inf = 1000 * 1000 * 1000;
const int mod = 1000 * 1000 * 1000 + 7;
const long long infl = 1000ll * 1000ll * 1000ll * 1000ll * 1000ll * 1000ll;
int n, m, x, y, used1[nmax], answer = 0;
vector<int> a[nmax], b[nmax], cur;
bool f, used[nmax];
void dfs1(int v) {
used[v] = true;
cur.push_back(v);
for (int i = 0; i < (int)a[v].size(); i++)
if (!used[a[v][i]]) dfs1(a[v][i]);
}
void dfs2(int v) {
used1[v] = 1;
for (int i = 0; i < (int)b[v].size(); i++)
if (used1[b[v][i]] == 0)
dfs2(b[v][i]);
else if (used1[b[v][i]] == 1)
f = true;
used1[v] = 2;
}
int main() {
assert(scanf("%d%d", &n, &m));
for (int i = 0; i < m; i++) {
assert(scanf("%d%d", &x, &y));
x--, y--;
a[x].push_back(y);
a[y].push_back(x);
b[x].push_back(y);
}
for (int i = 0; i < n; i++) {
if (!used[i]) {
cur.clear();
dfs1(i);
f = false;
for (int j = 0; j < (int)cur.size(); j++)
if (used1[cur[j]] == 0) dfs2(cur[j]);
answer += (int)cur.size() - 1;
if (f) answer++;
}
}
printf("%d\n", answer);
}
| 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;
vector<int> nei[maxn], nei2[maxn];
int n, m, cnt;
bool cycle = false;
int col[maxn];
int mark[maxn], ans;
bool cmp[maxn];
void dfs(int v) {
col[v] = ans;
mark[v] = 1;
for (auto u : nei[v]) {
if (!mark[u]) {
dfs(u);
}
}
}
void dfs2(int v) {
mark[v] = 1;
for (auto u : nei2[v]) {
if (!mark[u])
dfs2(u);
else if (mark[u] == 1) {
cmp[col[u]] = true;
}
}
mark[v] = 2;
}
void dfs_all() {
for (int i = 0; i < n; i++) {
if (!mark[i]) {
dfs(i);
ans++;
}
}
memset(mark, 0, sizeof mark);
for (int i = 0; i < n; i++)
if (!mark[i]) {
dfs2(i);
}
for (int i = 0; i < ans; i++)
if (cmp[i]) cnt++;
cout << n - ans + cnt << endl;
}
int main() {
cin >> n >> m;
for (int i = 0, a, b; i < m; i++) {
cin >> a >> b;
a--;
b--;
nei[a].push_back(b), nei[b].push_back(a);
nei2[a].push_back(b);
}
dfs_all();
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
template <class T>
T gcd(T a, T b) {
T r;
while (b != 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
template <class T>
T lcm(T a, T b) {
return a / gcd(a, b) * b;
}
template <class T>
int getbit(T s, int i) {
return (s >> i) & 1;
}
template <class T>
T onbit(T s, int i) {
return s | (T(1) << i);
}
template <class T>
T offbit(T s, int i) {
return s & (~(T(1) << i));
}
const double PI = 2 * acos(0.0);
const long double eps = 1e-12;
const int infi = 1e9;
const long long Linfi = (long long)9e18;
const long long MOD = 1000000007;
int n, m, u, v, dem, cnt = 0;
int List[100005], group[100005], xet[100005], inDFS[100005];
vector<int> adj[100005], adj2[100005], V[100005];
vector<pair<int, int> > GE[100005];
pair<int, int> E[100005];
set<pair<int, int> > S;
void DFS(int u) {
group[u] = cnt;
V[cnt].push_back(u);
xet[u] = 1;
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
if (xet[v] == 0) DFS(v);
}
}
void visit(int u, int &ok) {
xet[u] = 1;
inDFS[u] = 1;
for (int i = 0; i < adj2[u].size(); i++) {
int v = adj2[u][i];
if (xet[v] == 0)
visit(v, ok);
else if (xet[v] == 1 && inDFS[v])
ok = 1;
}
inDFS[u] = 0;
}
void solve() {
for (int i = 1; i <= n; i++)
if (xet[i] == 0) {
cnt++;
DFS(i);
}
for (int i = 1; i <= m; i++) {
int u = E[i].first;
int v = E[i].second;
int g = group[u];
GE[g].push_back(E[i]);
}
int ans = 0;
memset(xet, 0, sizeof(xet));
for (int i = 1; i <= cnt; i++) {
int ok = 0;
for (int j = 0; j < V[i].size(); j++) {
int u = V[i][j];
if (xet[u] == 0) visit(u, ok);
}
if (ok)
ans += V[i].size();
else
ans += V[i].size() - 1;
}
cout << ans << endl;
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> u >> v;
adj2[u].push_back(v);
adj[u].push_back(v);
adj[v].push_back(u);
E[i] = pair<int, int>(u, v);
S.insert(pair<int, int>(u, v));
}
solve();
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200005;
bool visited[MAXN], recStack[MAXN];
vector<int> adj[MAXN], kel[MAXN];
int par[MAXN];
int find(int x) {
if (par[x] == x) return x;
return par[x] = find(par[x]);
}
void join(int a, int b) { par[find(a)] = find(b); }
bool dfs(int now) {
visited[now] = 1;
recStack[now] = true;
for (auto nxt : adj[now]) {
if (!visited[nxt] && dfs(nxt)) {
return true;
} else if (recStack[nxt]) {
return true;
}
}
recStack[now] = false;
return false;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m, u, v;
cin >> n >> m;
for (int i = 1; i <= n; i++) par[i] = i;
for (int i = 1; i <= m; i++) {
cin >> u >> v;
adj[u].push_back(v);
join(u, v);
}
for (int i = 1; i <= n; i++) kel[find(i)].push_back(i);
int ans = 0;
for (int i = 1; i <= n; i++) {
if (kel[i].empty()) continue;
bool cycle = 0;
for (auto isi : kel[i]) {
if (visited[isi]) continue;
if (dfs(isi)) {
cycle = 1;
break;
}
}
ans += kel[i].size();
if (!cycle) ans--;
}
cout << ans << '\n';
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int mx = 1e5 + 10;
vector<int> g[mx];
int cmp[mx], ncc = 0;
stack<int> st;
int color[mx], idx[mx], low[mx], sz[mx], t = 0;
void dfs(int u) {
color[u] = 1;
idx[u] = low[u] = t++;
st.push(u);
for (int i = 0; i < int(g[u].size()); i++) {
int v = g[u][i];
if (color[v] == 0) {
dfs(v);
low[u] = min(low[u], low[v]);
} else if (color[v] == 1) {
low[u] = min(low[u], idx[v]);
}
}
if (idx[u] == low[u]) {
int v;
do {
v = st.top();
cmp[v] = ncc;
sz[ncc]++;
st.pop();
} while (v != u);
ncc++;
}
color[u] = 2;
}
vector<int> us, vs;
vector<int> dag[mx];
bool is1;
int cnt;
vector<int> groups[mx];
int ufp[mx], ufz[mx];
int gp(int u) {
while (ufp[u] != u) u = ufp[u];
return u;
}
void join(int u, int v) {
int pu = gp(u);
int pv = gp(v);
if (pu == pv) return;
if (ufz[pu] < ufz[pv]) swap(pu, pv);
ufp[pv] = pu;
ufz[pu] += ufz[pv];
}
int main() {
int n, m, u, v;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d %d", &u, &v);
g[u].push_back(v);
us.push_back(u);
vs.push_back(v);
}
memset(color, 0, sizeof color);
memset(sz, 0, sizeof sz);
for (int i = 1; i <= n; i++) {
if (color[i] == 0) {
dfs(i);
}
}
for (int i = 0; i < ncc; i++) {
ufp[i] = i;
ufz[i] = 1;
}
for (int i = 0; i < int(us.size()); i++) {
join(cmp[us[i]], cmp[vs[i]]);
}
for (int i = 0; i < ncc; i++) {
groups[gp(i)].push_back(i);
}
int ans = 0;
for (int i = 0; i < ncc; i++) {
bool is1 = true;
int nv = 0;
for (int j = 0; j < int(groups[i].size()); j++) {
if (sz[groups[i][j]] > 1) is1 = false;
nv += sz[groups[i][j]];
}
if (nv > 0) {
if (is1)
ans += nv - 1;
else
ans += nv;
}
}
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 MAX = 1e5 + 7;
int NUMBER_OF_WAYS, n, m, u, vertex, conectivity_marker[MAX + 1], component,
teleport_marker[MAX + 1], components[MAX + 1];
vector<int> conectivity[MAX + 1], teleport[MAX + 1];
void DEE_EF_ES(int source) {
conectivity_marker[source] = component;
for (auto member : conectivity[source]) {
if (!conectivity_marker[member]) {
DEE_EF_ES(member);
}
}
}
void dfs(int leaf) {
teleport_marker[leaf] = 2;
for (auto memser : teleport[leaf]) {
if (teleport_marker[memser] == 2) {
components[conectivity_marker[memser]] = 1;
} else if (teleport_marker[memser] == 0) {
dfs(memser);
}
}
teleport_marker[leaf] = 1;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> u >> vertex;
teleport[u].push_back(vertex);
conectivity[u].push_back(vertex);
conectivity[vertex].push_back(u);
}
for (int i = 1; i <= n; i++) {
if (conectivity_marker[i] == 0) {
component++;
DEE_EF_ES(i);
}
}
for (int i = 1; i <= n; i++) {
if (!teleport_marker[MAX]) {
dfs(i);
}
}
NUMBER_OF_WAYS = n - component;
for (int i = 1; i <= n; i++) {
NUMBER_OF_WAYS += components[i];
}
cout << NUMBER_OF_WAYS << 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_N = 1e5 + 5;
int root[MAX_N];
int find(int u) {
if (root[u] != u) {
root[u] = find(root[u]);
}
return root[u];
}
void merge(int u, int v) {
u = find(u);
v = find(v);
root[u] = v;
}
vector<int> out_adj[MAX_N];
int vis[MAX_N];
int has_cyc[MAX_N];
void find_cyc(int u) {
vis[u] = 1;
for (int nxt : out_adj[u]) {
if (vis[nxt] == 1) {
has_cyc[find(u)] = 1;
} else if (vis[nxt] == 0) {
find_cyc(nxt);
}
}
vis[u] = 2;
}
int main() {
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
root[i] = i;
}
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
out_adj[u].push_back(v);
merge(u, v);
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
find_cyc(i);
}
}
int ans = n;
for (int i = 1; i <= n; i++) {
if (find(i) == i) {
if (!has_cyc[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;
const int MAX_V = 200010;
int V, E;
int C[MAX_V], vis[MAX_V];
bool cir[MAX_V];
vector<int> g[MAX_V], gg[MAX_V];
int cnt;
void color(int u) {
C[u] = cnt;
for (int i = 0; i < gg[u].size(); ++i) {
int vv = gg[u][i];
if (!C[vv]) color(vv);
}
}
void visit(int u) {
vis[u] = -1;
for (int i = 0; i < g[u].size(); ++i) {
int vv = g[u][i];
if (vis[vv] == 0)
visit(vv);
else if (vis[vv] == -1)
cir[C[vv]] = true;
}
vis[u] = 1;
}
int main() {
int x;
cin >> V >> E;
for (int i = 0; i < E; ++i) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
gg[a].push_back(b);
gg[b].push_back(a);
}
for (int i = 1; i <= V; ++i) {
if (!C[i]) {
cnt++;
color(i);
}
}
for (int i = 1; i <= V; ++i) {
if (!vis[i]) visit(i);
}
int ans = V - cnt;
for (int i = 1; i <= cnt; ++i) {
if (cir[i]) ans++;
}
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;
int n, m, used[123456];
vector<long long> g[123456], rg[123456], vs;
int cmp[123456], cmpsize[123456];
void add_edge(int from, int to) {
g[from].push_back(to);
rg[to].push_back(from);
}
void dfs(int v) {
used[v] = 1;
for (int i = 0; i < g[v].size(); i++)
if (!used[g[v][i]]) dfs(g[v][i]);
vs.push_back(v);
}
void rdfs(int v, int k) {
used[v] = 1;
cmp[v] = k;
for (int i = 0; i < rg[v].size(); i++)
if (!used[rg[v][i]]) rdfs(rg[v][i], k);
}
int scc() {
memset(used, 0, sizeof(used));
vs.clear();
for (int v = 0; v < n; v++) {
if (!used[v]) dfs(v);
}
memset(used, 0, sizeof(used));
int k = 0;
for (int i = int(vs.size()) - 1; i >= 0; i--) {
if (!used[vs[i]]) rdfs(vs[i], k++);
}
return k;
}
int dfs2(int v) {
used[v] = 1;
int res = cmpsize[cmp[v]] == 1;
for (int i = 0; i < g[v].size(); i++)
if (!used[g[v][i]]) {
res &= dfs2(g[v][i]);
}
for (int i = 0; i < rg[v].size(); i++)
if (!used[rg[v][i]]) {
res &= dfs2(rg[v][i]);
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
add_edge(a - 1, b - 1);
}
scc();
memset(cmpsize, 0, sizeof(cmpsize));
for (int i = 0; i < n; i++) {
cmpsize[cmp[i]]++;
}
memset(used, 0, sizeof(used));
int ans = n;
for (int i = 0; i < n; i++)
if (!used[i]) {
ans -= dfs2(i);
}
cout << ans;
}
| 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]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b]:
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;
int u[100100], v[100100];
int root[100100], cnt[100100], ord[100100];
int find_root(int u) { return u == root[u] ? u : root[u] = find_root(root[u]); }
void merge(int u, int v) {
u = find_root(u);
v = find_root(v);
if (u != v) root[v] = u;
}
vector<vector<int> > adj[100100];
int indeg[100100];
int q[100100], qf, qb;
int calc(vector<vector<int> > adj, int n) {
memset(indeg, 0, sizeof(int) * n);
for (int i = 0; i < n; i++) {
for (int j = adj[i].size(); j--;) {
indeg[adj[i][j]]++;
}
}
qf = qb = 0;
for (int i = 0; i < n; i++)
if (!indeg[i]) q[qb++] = i;
while (qf < qb) {
int u = q[qf++];
for (int i = adj[u].size(); i--;) {
int v = adj[u][i];
if (!(--indeg[v])) q[qb++] = v;
}
}
return qb == n ? n - 1 : n;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) root[i] = i;
for (int i = 0; i < m; i++) {
cin >> u[i] >> v[i];
merge(u[i], v[i]);
}
for (int i = 1; i <= n; i++) {
ord[i] = cnt[find_root(i)]++;
adj[find_root(i)].push_back(vector<int>(0));
}
for (int i = 0; i < m; i++) {
adj[find_root(u[i])][ord[u[i]]].push_back(ord[v[i]]);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (find_root(i) == i) ans += calc(adj[i], cnt[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;
int f[100005];
int n, m;
vector<int> e[100005];
queue<int> que;
int F(int x) {
if (f[x] == x) return x;
return f[x] = F(f[x]);
}
bool H[100005];
int lt[100005];
bool vis[100005];
int deg[100005];
void func() {
while (!que.empty()) {
int cnt = que.front();
que.pop();
for (int i = 0; i < e[cnt].size(); i++) {
deg[e[cnt][i]]--;
if (deg[e[cnt][i]] == 0) que.push(e[cnt][i]);
}
}
}
int main() {
int x, y;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) f[i] = i;
for (int i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
e[x].push_back(y);
deg[y]++;
f[F(x)] = F(y);
}
for (int i = 1; i <= n; i++) {
lt[F(i)]++;
if (deg[i] == 0) que.push(i);
}
func();
int ans = 0;
for (int i = 1; i <= n; i++) {
if (deg[i] != 0) H[F(i)] = 1;
}
for (int i = 1; i <= n; i++) {
if (f[i] == i) {
if (H[i])
ans += lt[i];
else {
ans += lt[i] - 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>
int n, m;
int edge[100100][2];
int elist[200100];
int es[200100];
int en[100100];
int chk[100100];
int comp[100100];
int pn[100100];
int cn;
int q[100100];
int qs, qe;
int ans;
int flag;
void dfs(int loc) {
int i;
chk[loc] = 1;
comp[cn] = loc;
cn++;
for (i = en[loc]; i < en[loc + 1]; i++) {
if (chk[elist[i]] == 0) {
dfs(elist[i]);
}
}
}
int main() {
int i, j;
scanf("%d%d", &n, &m);
for (i = 0; i < m; i++) {
scanf("%d%d", &edge[i][0], &edge[i][1]);
en[edge[i][0] + 2]++;
en[edge[i][1] + 2]++;
}
for (i = 0; i < n + 10; i++) {
en[i + 1] += en[i];
}
for (i = 0; i < m; i++) {
elist[en[edge[i][0] + 1]] = edge[i][1];
es[en[edge[i][0] + 1]] = 1;
pn[edge[i][0]]++;
en[edge[i][0] + 1]++;
elist[en[edge[i][1] + 1]] = edge[i][0];
en[edge[i][1] + 1]++;
}
ans = n;
for (i = 1; i <= n; i++) {
if (chk[i] == 0) {
flag = 0;
cn = 0;
dfs(i);
qe = 0;
for (j = 0; j < cn; j++) {
if (pn[comp[j]] == 0) {
q[qe] = comp[j];
qe++;
}
}
for (qs = 0; qs < qe; qs++) {
for (j = en[q[qs]]; j < en[q[qs] + 1]; j++) {
if (es[j] == 0) {
pn[elist[j]]--;
if (pn[elist[j]] == 0) {
q[qe] = elist[j];
qe++;
}
}
}
}
for (j = 0; j < cn; j++) {
if (pn[comp[j]] != 0) {
break;
}
}
if (j == cn) {
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;
template <class T>
inline bool ylmin(T &a, T b) {
return a < b ? 0 : (a = b, 1);
}
template <class T>
inline bool ylmax(T &a, T b) {
return a > b ? 0 : (a = b, 1);
}
template <class T>
inline T abs(T x) {
return x < 0 ? -x : x;
}
inline char read() {
static const int IO_LEN = 1024 * 1024;
static char buf[IO_LEN], *ioh, *iot;
if (ioh == iot) {
iot = (ioh = buf) + fread(buf, 1, IO_LEN, stdin);
if (ioh == iot) return -1;
}
return *ioh++;
}
template <class T>
inline void read(T &x) {
static int iosig;
static char ioc;
for (iosig = 0, ioc = read(); !isdigit(ioc); ioc = read())
if (ioc == '-') iosig = 1;
for (x = 0; isdigit(ioc); ioc = read()) x = (x << 1) + (x << 3) + (ioc ^ '0');
if (iosig) x = -x;
}
const int MAXN = 1e5 + 10;
int n, m, u, v, vis[MAXN], du[MAXN];
vector<int> G[MAXN], H[MAXN];
inline void dfs(int u, vector<int> &S) {
S.push_back(u);
vis[u] = 1;
for (auto v : G[u])
if (!vis[v]) dfs(v, S);
}
inline bool topsort(vector<int> S) {
queue<int> Q;
int cnt = 0;
for (auto u : S)
for (auto v : H[u]) du[v]++;
for (auto u : S)
if (!du[u]) Q.push(u);
while (!Q.empty()) {
int u = Q.front();
Q.pop();
cnt++;
for (auto v : H[u])
if (!(--du[v])) Q.push(v);
}
return cnt == ((int)S.size());
}
int main() {
read(n), read(m);
for (int i = (1); i <= (m); i++)
read(u), read(v), G[u].push_back(v), G[v].push_back(u), H[u].push_back(v);
int ans = n;
for (int i = (1); i <= (n); i++) {
if (vis[i]) continue;
vector<int> S;
dfs(i, S);
ans -= topsort(S);
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, m, rt[100100], x[100100], y[100100];
int find_rt(int u) { return rt[u] == u ? u : rt[u] = find_rt(rt[u]); }
void link(int u, int v) {
u = find_rt(u), v = find_rt(v);
if (u != v) rt[u] = v;
}
vector<int> adj[100100], edge[100100], node[100100];
int C, col[100100], ord[100100], ft;
bool vis[100100];
vector<int> v[100100], rv[100100];
void dfs(int x) {
vis[x] = 1;
for (auto y : v[x])
if (!vis[y]) dfs(y);
ord[ft--] = x;
}
void rdfs(int x) {
col[x] = C;
for (auto y : rv[x])
if (!col[y]) rdfs(y);
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) rt[i] = i;
for (int i = 0; i < m; i++) scanf("%d %d", &x[i], &y[i]), link(x[i], y[i]);
for (int i = 0; i < m; i++) edge[find_rt(x[i])].push_back(i);
for (int i = 1; i <= n; i++) node[find_rt(i)].push_back(i);
int rlt = 0;
for (int i = 1; i <= n; i++) {
if (node[i].size()) {
for (auto j : edge[i]) v[x[j]].push_back(y[j]), rv[y[j]].push_back(x[j]);
int sz = node[i].size();
ft = sz;
for (auto u : node[i])
if (!vis[u]) dfs(u);
C = 0;
for (int i = 1; i <= sz; i++)
if (!col[ord[i]]) C++, rdfs(ord[i]);
rlt += C == sz ? sz - 1 : sz;
}
}
printf("%d\n", rlt);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 100;
int n, m, ans, stt, st[N], high[N], h[N];
vector<int> adj1[N], adj2[N], t;
stack<int> s;
bool on[N], mark1[N], mark2[N], flag;
void DFS1(int v) {
t.push_back(v);
mark1[v] = 1;
for (int i = 0; i < adj1[v].size(); i++) {
int u = adj1[v][i];
if (!mark1[u]) DFS1(u);
}
}
void DFS2(int v) {
mark2[v] = on[v] = 1;
st[v] = high[v] = stt++;
s.push(v);
for (int i = 0; i < adj2[v].size(); i++) {
int u = adj2[v][i];
if (!mark2[u]) {
DFS2(u);
high[v] = min(high[v], high[u]);
} else if (on[u])
high[v] = min(high[v], high[u]);
}
if (high[v] == st[v]) {
int u = s.top(), cnt = 0;
while (st[u] >= st[v]) {
cnt++;
on[u] = 0;
s.pop();
if (s.size())
u = s.top();
else
break;
}
if (cnt > 1) flag = 1;
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj2[--u].push_back(--v);
adj1[u].push_back(v);
adj1[v].push_back(u);
}
for (int i = 0; i < n; i++)
if (!mark1[i]) {
DFS1(i);
flag = 0;
for (int j = 0; j < t.size(); j++)
if (!mark2[t[j]]) DFS2(t[j]);
ans += t.size();
if (!flag) ans--;
t.clear();
}
cout << ans << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> edge;
int n, m;
int parent[100000];
int size[100000];
int visited[100000];
int finished[100000];
int has_loop[100000];
int find_root(int v) {
if (parent[v] == -1) {
return v;
}
return parent[v] = find_root(parent[v]);
}
void merge(int u, int v) {
u = find_root(u), v = find_root(v);
if (u == v) {
return;
}
if (size[u] < size[v]) {
merge(v, u);
return;
}
parent[v] = u;
size[u] += size[v];
}
void dfs(int here) {
visited[here] = true;
for (int there : edge[here]) {
if (finished[there]) {
continue;
} else if (visited[there]) {
has_loop[find_root(here)] = 1;
} else {
dfs(there);
}
}
finished[here] = true;
}
void loop_check() {
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i);
}
}
}
int main() {
cin >> n >> m;
edge = vector<vector<int>>(n, vector<int>());
for (int i = 0; i < n; i++) {
parent[i] = -1;
size[i] = 1;
}
for (int i = 0; i < m; i++) {
int from, to;
cin >> from >> to;
edge[from - 1].push_back(to - 1);
merge(from - 1, to - 1);
}
vector<int> wcc_list;
for (int i = 0; i < n; i++) {
if (find_root(i) == i) {
wcc_list.push_back(i);
}
}
loop_check();
int ans = 0;
for (int wcc : wcc_list) {
ans += size[wcc] - 1;
if (has_loop[wcc]) {
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;
const int P = 1e9 + 7;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long qpow(long long a, long long n) {
long long r = 1 % P;
for (a %= P; n; a = a * a % P, n >>= 1)
if (n & 1) r = r * a % P;
return r;
}
long long inv(long long x) { return x <= 1 ? 1 : inv(P % x) * (P - P / x) % P; }
const int N = 1e6 + 10;
int n, m, clk;
int vis[N], vis1[N], ok[N];
vector<int> g[N], g1[N];
int dfs(int x) {
vis[x] = 2;
for (int y : g[x]) {
if (vis[y] == 2 || !vis[y] && dfs(y)) return 1;
}
vis[x] = 1;
return 0;
}
void dfs1(int x, int c) {
vis1[x] = c;
for (int y : g1[x])
if (!vis1[y]) dfs1(y, c);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
g1[u].push_back(v), g1[v].push_back(u);
g[u].push_back(v);
}
for (int i = 1; i <= n; ++i)
if (!vis1[i]) dfs1(i, ++clk);
for (int i = 1; i <= n; ++i)
if (!vis[i]) ok[vis1[i]] |= dfs(i);
int ans = n;
for (int i = 1; i <= clk; ++i) ans -= !ok[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;
stack<int> st;
int cmpcnt, n, m, res;
vector<int> g[(1 << 17)], gt[(1 << 17)], f[(1 << 17)];
int vis[(1 << 17)], comp[(1 << 17)], cmpsize[(1 << 17)], in[(1 << 17)],
out[(1 << 17)];
void dfs(int x) {
vis[x] = 1;
for (int i = 0; i < g[x].size(); i++)
if (!vis[g[x][i]]) dfs(g[x][i]);
st.push(x);
}
void dfs2(int x) {
vis[x] = 1;
comp[x] = cmpcnt, cmpsize[cmpcnt]++;
for (int i = 0; i < gt[x].size(); i++)
if (!vis[gt[x][i]]) dfs2(gt[x][i]);
}
int dfs3(int x) {
vis[x] = 1;
int res = 1;
if (cmpsize[comp[x]] != 1) res = 0;
for (int i = 0; i < g[x].size(); i++)
if (!vis[g[x][i]]) res &= dfs3(g[x][i]);
for (int i = 0; i < gt[x].size(); i++)
if (!vis[gt[x][i]]) res &= dfs3(gt[x][i]);
return res;
}
void Kosaraju() {
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs(i);
memset(vis, 0, sizeof(vis));
for (; !st.empty(); st.pop()) {
int t = st.top();
if (!vis[t]) dfs2(t), cmpcnt++;
}
}
int main() {
int a, b;
cin >> n >> m;
for (int i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
g[a].push_back(b), gt[b].push_back(a);
}
Kosaraju();
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
if (!vis[i] && dfs3(i)) res++;
cout << n - 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;
using LL = long long;
int n, m, iTime;
stack<int> st;
vector<bool> inSt;
vector<int> disc, low, szScc, inScc;
vector<vector<int> > gr, adj;
void dfs(int u) {
disc[u] = low[u] = ++iTime;
st.emplace(u);
inSt[u] = true;
for (int v : gr[u]) {
if (!disc[v]) {
dfs(v);
low[u] = min(low[u], low[v]);
} else if (inSt[v])
low[u] = min(low[u], disc[v]);
}
if (disc[u] == low[u]) {
szScc.emplace_back(0);
while (st.top() != u) {
++szScc.back();
inScc[st.top()] = ((int)(szScc).size()) - 1;
inSt[st.top()] = false;
st.pop();
}
++szScc.back();
inScc[st.top()] = ((int)(szScc).size()) - 1;
inSt[st.top()] = false;
st.pop();
}
}
void dfs2(int u, bool& tmp, int& cnt) {
disc[u] = 1;
++cnt;
if (szScc[inScc[u]] > 1) tmp = false;
for (int v : adj[u])
if (!disc[v]) dfs2(v, tmp, cnt);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
gr.assign(n, {});
adj.assign(n, {});
while (m--) {
int u, v;
cin >> u >> v;
--u;
--v;
gr[u].emplace_back(v);
adj[u].emplace_back(v);
adj[v].emplace_back(u);
}
disc.assign(n, 0);
low.assign(n, 0);
inSt.assign(n, false);
inScc.assign(n, -1);
for (int u = 0; u < n; ++u)
if (!disc[u]) dfs(u);
int ans = 0;
disc.assign(n, 0);
for (int u = 0; u < n; ++u)
if (!disc[u]) {
bool tmp = true;
int nV = 0;
dfs2(u, tmp, nV);
ans += nV - tmp;
}
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;
int f[131072], in[131072], s[131072];
vector<int> adj[131072], c[131072];
int getf(int cur) {
if (f[cur] != cur) f[cur] = getf(f[cur]);
return f[cur];
}
int main() {
int N, M, i, j, a, b, cur, S, E, RES;
cin >> N >> M;
for (i = 1; i <= N; i++) f[i] = i;
for (i = 0; i < M; i++) {
cin >> a >> b;
adj[a].push_back(b);
in[b]++;
f[getf(a)] = getf(b);
}
for (i = 1; i <= N; i++) c[getf(i)].push_back(i);
RES = 0;
for (i = 1; i <= N; i++)
if (c[i].size()) {
S = E = 0;
for (j = 0; j < (int)c[i].size(); j++)
if (!in[c[i][j]]) s[E++] = c[i][j];
while (S < E) {
cur = s[S++];
for (j = 0; j < (int)adj[cur].size(); j++) {
in[adj[cur][j]]--;
if (!in[adj[cur][j]]) s[E++] = adj[cur][j];
}
}
if (E == c[i].size())
RES += (int)c[i].size() - 1;
else
RES += (int)c[i].size();
}
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>
int inp() {
char c = getchar();
while (c < '0' || c > '9') c = getchar();
int sum = 0;
while (c >= '0' && c <= '9') {
sum = sum * 10 + c - '0';
c = getchar();
}
return sum;
}
int head[100010], nxt[200010], end[200010], fa[100010];
int dfn[100010], low[100010], st[100010], cnt = 0, size[100010], bel[100010];
bool ins[100010], flg[100010];
int idx = 0, top = 0;
void tarjan(int cur) {
dfn[cur] = low[cur] = ++idx;
st[++top] = cur;
ins[cur] = true;
for (int x = head[cur]; x != -1; x = nxt[x]) {
if (!dfn[end[x]]) {
tarjan(end[x]);
low[cur] = std::min(low[cur], low[end[x]]);
} else if (ins[end[x]])
low[cur] = std::min(low[cur], dfn[end[x]]);
}
if (dfn[cur] == low[cur]) {
cnt++;
while (st[top] != cur) {
ins[st[top]] = false;
bel[st[top]] = cnt;
size[cnt]++;
top--;
}
ins[cur] = false;
bel[cur] = cnt;
size[cnt]++;
top--;
}
}
int cou = 0;
void link(int a, int b) {
nxt[++cou] = head[a];
head[a] = cou;
end[cou] = b;
}
int find(int x) { return (fa[x] == x) ? x : (fa[x] = find(fa[x])); }
int main() {
memset(head, -1, sizeof(head));
int n = inp();
int m = inp();
for (int i = 1; i <= n; i++) fa[i] = i;
while (m--) {
int u = inp();
int v = inp();
link(u, v);
fa[find(u)] = find(v);
}
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
for (int i = 1; i <= n; i++)
if (size[bel[i]] > 1) {
flg[find(i)] = true;
}
int ans = n;
for (int i = 1; i <= n; i++)
if (fa[i] == i && !flg[i]) ans--;
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 50;
int n, m;
int parent[N];
int vis1[N], vis2[N], tag[N], flag[N];
vector<int> v[N];
int root(int x) {
if (parent[x] == -1 || parent[x] == x)
return x;
else
return parent[x] = root(parent[x]);
}
void merge(int x, int y) {
x = root(x);
y = root(y);
parent[x] = y;
}
void dfs(int x) {
vis1[x] = 1;
for (int i = 0; i < v[x].size(); i++) {
int y = v[x][i];
if (root(x) != root(y)) merge(x, y);
if (vis1[y]) {
if (!vis2[y]) {
tag[y] = 1;
}
} else
dfs(y);
}
vis2[x] = 1;
}
int main() {
int i, j;
cin >> n >> m;
for (i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
v[a].push_back(b);
}
memset(parent, -1, sizeof(parent));
for (i = 1; i <= n; i++) {
if (!vis1[i]) dfs(i);
}
for (i = 1; i <= n; i++) {
if (tag[i] == 1) flag[root(i)] = 1;
}
int ans = n;
for (i = 1; i <= n; i++) {
if (root(i) == i) ans--;
if (flag[i]) ans++;
}
printf("%d\n", ans);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
void fre() {
freopen("c://test//input.in", "r", stdin);
freopen("c://test//output.out", "w", stdout);
}
template <class T>
inline void gmax(T &a, T b) {
if (b > a) a = b;
}
template <class T>
inline void gmin(T &a, T b) {
if (b < a) a = b;
}
using namespace std;
const int N = 1e5 + 10, M = 0, Z = 1e9 + 7, maxint = 2147483647,
ms31 = 522133279, ms63 = 1061109567, ms127 = 2139062143;
const double eps = 1e-8, PI = acos(-1.0);
int n, m;
int x, y;
int ind[N], s[N], num, top;
vector<int> a[N], b[N];
bool e[N];
void dfs(int x) {
e[x] = 1;
num++;
if (ind[x] == 0) s[++top] = x;
for (int i = a[x].size() - 1; i >= 0; i--) {
int y = a[x][i];
if (!e[y]) dfs(y);
}
}
int main() {
while (~scanf("%d%d", &n, &m)) {
memset(ind, 0, sizeof(ind));
for (int i = 1; i <= n; i++) a[i].clear(), b[i].clear();
for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
ind[y]++;
a[x].push_back(y);
a[y].push_back(x);
b[x].push_back(y);
}
int ans = 0;
memset(e, 0, sizeof(e));
for (int i = 1; i <= n; i++)
if (!e[i]) {
num = top = 0;
dfs(i);
int sum = top;
while (top) {
int x = s[top--];
for (int j = b[x].size() - 1; j >= 0; j--) {
int y = b[x][j];
ind[y]--;
if (ind[y] == 0) {
s[++top] = y;
sum++;
}
}
}
if (sum == num)
ans += (num - 1);
else
ans += num;
}
printf("%d\n", ans);
}
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int N, M, C, cycle, stat[100011];
vector<int> id[100011];
vector<int> adj[100011];
vector<int> adj2[100011];
void dfs(int x) {
id[C].push_back(x);
stat[x] = C;
for (int i = 0; i < (int)adj2[x].size(); i++)
if (!stat[adj2[x][i]]) dfs(adj2[x][i]);
}
void dfs2(int x) {
stat[x] = 1;
for (int i = 0; i < (int)adj[x].size(); i++) {
if (!stat[adj[x][i]])
dfs2(adj[x][i]);
else if (stat[adj[x][i]] == 1)
cycle = 1;
}
stat[x] = 2;
}
int main() {
if (fopen("data.in", "r")) freopen("data.in", "r", stdin);
scanf("%d", &N);
scanf("%d", &M);
for (int i = 0; i < M; i++) {
int a, b;
scanf("%d", &a);
scanf("%d", &b);
adj[a].push_back(b);
adj2[a].push_back(b);
adj2[b].push_back(a);
}
for (int i = 1; i <= N; i++)
if (!stat[i]) {
C++;
dfs(i);
}
memset(stat, 0, sizeof(stat));
int ans = 0;
for (int i = 1; i <= C; i++) {
cycle = 0;
for (int j = 0; j < (int)id[i].size(); j++)
if (!stat[id[i][j]]) dfs2(id[i][j]);
ans += id[i].size() - (!cycle);
}
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;
void SieveOfErat() {
bool prime[1000001];
memset(prime, true, sizeof(prime));
for (long long vec = 2; vec * vec <= 1000000; vec++) {
if (prime[vec] == true) {
for (long long dd = vec * 2; dd <= 1000000; dd += vec) prime[dd] = false;
}
}
}
long long gcd(long long aa, long long id2) {
if (aa == 0) {
return id2;
} else
return gcd(aa % id2, id2);
}
struct vect {
struct vect *foll;
long long calc;
struct vect *succ;
};
int in[300000], head[300000];
int to[300000];
int nex[300000];
int tot = 1;
int n, m, ans;
int vis[300000], mk[300000];
queue<int> q;
void add(int u, int v) {
to[tot] = v;
nex[tot] = head[u];
head[u] = tot++;
}
int dfs(int u) {
int ret = 1;
vis[u] = 1;
for (int i = head[u]; i != -1; i = nex[i]) {
int v = to[i];
if (!vis[v]) {
ret += dfs(v);
if (in[v] == 0) q.push(v);
}
}
return ret;
}
bool topo(int u, int c) {
int k = 0;
q.push(u);
mk[u] = 1;
while (!q.empty()) {
int now = q.front();
q.pop();
k++;
for (int i = head[now]; i != -1; i = nex[i]) {
int v = to[i];
in[v]--;
if (!mk[v] && in[v] == 0) {
q.push(v);
mk[v] = 1;
}
}
}
return k == c;
}
int main() {
memset(head, -1, sizeof(head));
cin >> n >> m;
while (m--) {
int u, v;
cin >> u >> v;
add(u, v);
add(v, u);
in[v]++;
}
for (int i = 1; i <= n; i++) {
if (!vis[i] && in[i] == 0) {
int c = dfs(i);
if (topo(i, c))
ans += c - 1;
else
ans += c;
}
}
for (int i = 1; i <= n; i++) {
if (!vis[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>
#pragma GCC optimize("O2")
using namespace std;
const int MAXN = 1e6 + 10;
const long long MOD = 1e9 + 7;
const long long MOD2 = 998244353;
const long long INF = 8e18;
const int LOG = 20;
long long pw(long long a, long long b, long long mod) {
return (!b ? 1
: (b & 1 ? (a * pw(a * a % mod, b / 2, mod)) % mod
: pw(a * a % mod, b / 2, mod)));
}
vector<int> G[MAXN], adj[MAXN];
int mark[MAXN], vis[MAXN], C[MAXN], T[MAXN], is_D[MAXN], cnt;
void DFS(int v) {
mark[v] = 1;
C[v] = cnt;
T[cnt]++;
for (auto u : adj[v]) {
if (!mark[u]) DFS(u);
}
}
void dfs(int v) {
vis[v] = 1;
for (auto u : G[v]) {
if (vis[u] == 2) continue;
if (vis[u] == 1) {
is_D[C[v]] = 1;
} else {
dfs(u);
}
}
vis[v] = 2;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b;
cin >> a >> b;
G[a].push_back(b);
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int i = 1; i <= n; i++) {
if (!mark[i]) {
cnt++;
DFS(i);
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
dfs(i);
}
}
for (int i = 1; i <= cnt; i++) {
ans += T[i] + is_D[i] - 1;
}
cout << ans;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Hamed Valizadeh ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInputReader in = new FastInputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
class Node {
ArrayList<Integer> in = new ArrayList<Integer>();
ArrayList<Integer> out = new ArrayList<Integer>();
}
Node[] graph;
boolean[] visited;
public void solve(int testNumber, FastInputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
graph = new Node[n];
for (int i = 0; i < n; i++)
graph[i] = new Node();
for (int i = 0; i < m; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
graph[x].out.add(y);
graph[y].in.add(x);
}
visited = new boolean[n];
Arrays.fill(visited, false);
inDegree = new int[n];
Arrays.fill(inDegree, 0);
queue = new int[n];
int total = 0;
for (int i = 0; i < n; i++) {
if (visited[i])
continue;
ArrayList<Integer> component = new ArrayList<Integer>();
dfs(i, component);
total += solve(component);
}
out.println(total);
}
int[] inDegree;
int head, tail;
int[] queue;
private int solve(ArrayList<Integer> component) {
head = tail = 0;
for (int i: component) {
inDegree[i] = graph[i].in.size();
if (inDegree[i] == 0)
queue[tail++] = i;
}
while (head < tail) {
int current = queue[head++];
for (int next: graph[current].out)
if (--inDegree[next] == 0)
queue[tail++] = next;
}
return tail == component.size()? component.size() - 1: component.size();
}
private void dfs(int i, ArrayList<Integer> component) {
if (visited[i])
return;
visited[i] = true;
component.add(i);
for (int next: graph[i].in)
dfs(next, component);
for (int next: graph[i].out)
dfs(next, component);
}
}
class FastInputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastInputReader(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 double PI = acos(-1.0);
const long long INF = 1e9 + 47;
const long long LINF = INF * INF;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 1 << 17;
int n, m;
vector<int> g[N];
vector<int> G[N];
char used[N];
vector<int> comp;
void dfs1(int v) {
comp.push_back(v);
used[v] = 1;
for (auto i : G[v])
if (!used[i]) dfs1(i);
}
char u2[N];
bool cycl = false;
void dfs2(int v) {
u2[v] = 1;
for (auto i : g[v]) {
if (u2[i] == 0) dfs2(i);
cycl |= u2[i] == 1;
}
u2[v] = 2;
}
int solve() {
cycl = false;
for (auto i : comp)
if (u2[i] == 0) dfs2(i);
return (int)((comp).size()) + cycl - 1;
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
while (m--) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
G[u].push_back(v);
G[v].push_back(u);
}
int ans = 0;
for (int i = (1); i < (n + 1); ++i) {
if (used[i]) continue;
comp.clear();
dfs1(i);
ans += solve();
}
cout << ans << endl;
cerr << "Time elapsed: " << clock() / (double)CLOCKS_PER_SEC << 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 = 1e5 + 50;
vector<int> g[N], g1[N], vs;
int mark[N];
bool flag = false;
void dfs(int v) {
mark[v] = 1;
for (int i = 0; i < g[v].size(); i++) {
int to = g[v][i];
if (mark[to] == 1) flag = true;
if (mark[to] == 3) dfs(to);
}
mark[v] = 2;
}
void dfs1(int v) {
mark[v] = 3;
vs.push_back(v);
for (int i = 0; i < g1[v].size(); i++) {
int to = g1[v][i];
if (mark[to] == 0) dfs1(to);
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
g[x].push_back(y);
g1[x].push_back(y);
g1[y].push_back(x);
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (mark[i]) continue;
dfs1(i);
flag = false;
for (int i = 0; i < vs.size(); i++) {
if (mark[vs[i]] == 3) dfs(vs[i]);
}
ans += (int)vs.size() - 1 + (int)flag;
vs.clear();
}
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>
#pragma comment(linker, "/STACK:36777216")
using namespace std;
const int N = 2e5 + 7;
const int M = N * N * 2;
const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const double EPS = 1e-8;
struct Edge {
int v, next;
} e[N << 1];
int first[N], ecnt;
void Addedge(int u, int v) {
e[++ecnt].v = v, e[ecnt].next = first[u], first[u] = ecnt;
}
int f[N], deg[N], n, m, u, v, tot;
int getf(int x) { return f[x] == x ? f[x] : f[x] = getf(f[x]); }
queue<int> Q;
vector<int> vec[N];
int main() {
cin >> n >> m;
tot = n;
memset(first, -1, sizeof(first));
ecnt = -1;
for (int i = 1; i <= n; i++) {
f[i] = i;
}
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
Addedge(u, v);
deg[v]++;
int fu = getf(u), fv = getf(v);
if (fu == fv) continue;
f[fu] = fv;
tot--;
}
for (int i = 1; i <= n; i++) {
if (deg[i] == 0) Q.push(i);
}
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (int i = first[u]; i != -1; i = e[i].next) {
int v = e[i].v;
deg[v]--;
if (deg[v] == 0) Q.push(v);
}
}
int ans = n - tot;
for (int i = 1; i <= n; i++) {
int ff = getf(i);
vec[ff].push_back(i);
}
for (int i = 1; i <= n; i++) {
if (vec[i].size() == 0) continue;
for (int j = 0; j < vec[i].size(); j++) {
if (deg[vec[i][j]] != 0) {
ans++;
break;
}
}
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class B {
static class SCC {
private boolean[] used;
private List<Integer> finished;
List<Integer>[] g;
List<Integer>[] rg;
int[] cmp;
int[] cmpSize;
public SCC(List<Integer>[] g, List<Integer>[] rg) {
int n = g.length;
this.g = g;
this.rg = rg;
used = new boolean[n];
finished = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (used[i]) continue;
dfs(i);
}
used = new boolean[n];
int group = 0;
cmp = new int[n];
cmpSize = new int[n];
for (int i = n - 1; i >= 0; i--) {
if (used[finished.get(i)]) continue;
rdfs(finished.get(i), group++);
}
}
void dfs(int u) {
used[u] = true;
for (int v : g[u]) {
if (used[v]) continue;
dfs(v);
}
finished.add(u);
}
void rdfs(int u, int group) {
used[u] = true;
cmp[u] = group;
cmpSize[group]++;
for (int nbr : rg[u]) {
if (used[nbr]) continue;
rdfs(nbr, group);
}
}
}
int dfs(int cur) {
int r = scc.cmpSize[scc.cmp[cur]]==1?1:0;
visited[cur] = true;
for (int nbr:g[cur]) {
if (visited[nbr]) continue;
r &= dfs(nbr);
}
for (int nbr:rg[cur]) {
if (visited[nbr]) continue;
r &= dfs(nbr);
}
return r;
}
List<Integer>[] g;
List<Integer>[] rg;
SCC scc;
boolean[] visited;
public B() throws Exception {
int n = in.nextInt();
int m = in.nextInt();
g = new List[n];
rg = new List[n];
for (int i=0; i<n; i++) g[i] = new ArrayList<>();
for (int i=0; i<n; i++) rg[i] = new ArrayList<>();
for (int i=0; i<m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
g[a].add(b);
rg[b].add(a);
}
scc = new SCC(g, rg);
int ans = n;
visited = new boolean[n];
for (int i=0; i<n; i++) {
if (visited[i]) continue;
ans -= dfs(i);
}
buf.append(ans).append('\n');
}
public static Scanner in = new Scanner(System.in);
public static StringBuilder buf = new StringBuilder();
public static void debug(Object... arr) { // {{{
System.err.println(Arrays.deepToString(arr));
} // }}}
public static void main(String[] args) throws Exception { // {{{
new B();
System.out.print(buf);
} // }}}
public static class Scanner { // {{{
BufferedReader br;
String line;
StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public boolean hasNext() throws IOException {
while ((st==null||!st.hasMoreTokens())&&(line=br.readLine())!=null)
st = new StringTokenizer(line);
return st.hasMoreTokens();
}
public String next() throws IOException {
if (hasNext()) return st.nextToken();
throw new NoSuchElementException();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} // }}}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
int n, m, ans;
int h[100005], nxt[200005], to[200005], tot;
void ins(int x, int y) {
nxt[++tot] = h[x];
to[tot] = y;
h[x] = tot;
}
int vis[100005], cnt;
int stk[100005], top;
int que[100005], l, r;
int in[100005];
void DFS(int u) {
vis[u] = cnt;
stk[++top] = u;
for (int i = h[u]; i; i = nxt[i]) {
if (!vis[to[i]]) DFS(to[i]);
if (i & 1) ++in[to[i]];
}
}
int BFS() {
l = 1, r = 0;
for (int i = (1); i <= (top); ++i)
if (in[stk[i]] == 0) que[++r] = stk[i];
while (l <= r) {
int u = que[l++];
for (int i = h[u]; i; i = nxt[i])
if (i & 1)
if (--in[to[i]] == 0) que[++r] = to[i];
}
return r == top;
}
int main() {
int x, y;
scanf("%d%d", &n, &m);
ans = n;
for (int i = (1); i <= (m); ++i) scanf("%d%d", &x, &y), ins(x, y), ins(y, x);
for (int i = (1); i <= (n); ++i) {
if (!vis[i]) {
top = 0;
++cnt, DFS(i);
ans -= BFS();
}
}
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 |
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static class pair implements Comparable<pair>
{
int a;
int b;
public pair(int pa, int pb)
{
a = pa; b= pb;
}
@Override
public int compareTo(pair o) {
if(this.a < o.a)
return -1;
if(this.a > o.a)
return 1;
return Integer.compare(o.b, this.b);
}
}
public static boolean dag;
public static int v[];
//public static Stack<Integer> sta;
public static ArrayList[] uadj;
public static void main (String[] args) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] r = in.readLine().split(" ");
int n = Integer.parseInt(r[0]);
int m = Integer.parseInt(r[1]);
ArrayList[] adj = new ArrayList[n];
uadj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
uadj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
r = in.readLine().split(" ");
int a = Integer.parseInt(r[0])-1;
int b = Integer.parseInt(r[1])-1;
adj[a].add(b);
adj[b].add(a);
uadj[a].add(b);
}
boolean[] vis = new boolean[n];
v = new int[n];
int ans = 0;
for (int vert = 0; vert < n; vert++) {
if(!vis[vert])
{
Stack<Integer> st = new Stack<Integer>();
ArrayList<Integer> nums = new ArrayList<Integer>();
st.push(vert);
while(!st.isEmpty())
{
int cur = st.pop();
if(!vis[cur])
{
vis[cur]=true;
nums.add(cur);
for (Object veci: adj[cur]) {
if(!vis[(Integer) veci])
st.push((Integer) veci);
}
}
}
int cnt = nums.size();
for(Integer i: nums) v[i]=0; //white
dag=true;
//sta = new Stack<Integer>();
for(Integer i: nums) if(v[i]==0)
DFS(i);
if(!dag)
ans+=cnt;
else ans+=cnt-1;
//System.out.println(vert + " " + cnt+ " "+ans);
}
}
System.out.println(ans);
}
public static void DFS(int a) {
if(v[a]==1)
{
dag = false;
//System.out.println(a);
}
if(v[a]>0) return;
v[a] = 1; // gray
for(Object i: uadj[a]) DFS((Integer) i);
v[a] = 2; // black
//sta.push(a);
}
} | 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 T, n, m, last, d, e, ee;
int l, r, s, t, ll, tot;
int x, y, z, ans, tt, yy;
vector<int> a[100010];
int v[100010], g[100010], k[100010];
int f[100100];
int inf = 1000000001;
void dfs(int ss, int s) {
for (int i = 0; i < a[ss].size(); i++) {
int j = a[ss][i];
if (j == s) {
v[s] = 1;
return;
}
if (v[j] >= inf) {
v[j] = inf - 1;
dfs(j, s);
}
}
}
int went(int s) {
v[s] = 0;
for (int i = 0; i < a[s].size(); i++) {
int j = a[s][i];
if (v[j] >= inf) {
v[j] = inf - 1;
dfs(j, s);
}
if (v[s]) break;
}
return v[s];
}
int fa(int x) {
if (x == f[x])
return x;
else {
f[x] = fa(f[x]);
return f[x];
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i = i + 1) f[i] = i;
for (int i = 1; i <= m; i = i + 1) {
scanf("%d%d", &x, &y);
a[x].push_back(y);
x = fa(x);
y = fa(y);
if (x != y) f[y] = x;
}
for (int i = 1; i <= n; i = i + 1) f[i] = fa(f[i]), v[i] = inf;
for (int i = 1; i <= n; i = i + 1) {
if (f[i] == i) tot++;
if (g[f[i]] == -1) continue;
ans = went(i);
inf--;
if (ans) {
tot--;
g[f[i]] = -1;
}
}
printf("%d\n", n - tot);
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 = 2e5 + 5;
vector<int> edge[maxn], travel[maxn];
int degree[maxn];
int n, m;
queue<int> que;
bool vis[maxn];
int dfs(int x) {
int res = 1;
vis[x] = true;
for (int i = 0; i < edge[x].size(); i++) {
int to = edge[x][i];
if (!vis[to]) res += dfs(to);
}
if (degree[x] == 0) que.push(x);
return res;
}
int getans(int s) {
int nn = 0;
while (!que.empty()) que.pop();
nn = dfs(s);
int cnt = 0;
while (!que.empty()) {
int x = que.front();
que.pop();
cnt++;
for (int i = 0; i < travel[x].size(); i++) {
int to = travel[x][i];
degree[to]--;
if (degree[to] == 0) {
que.push(to);
}
}
}
if (cnt == nn)
return nn - 1;
else
return nn;
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
for (int i = 1; i <= n; i++) edge[i].clear(), travel[i].clear();
memset(degree, 0, sizeof(degree));
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d%d", &a, &b);
edge[a].push_back(b);
edge[b].push_back(a);
travel[a].push_back(b);
degree[b]++;
}
int ans = 0;
memset(vis, false, sizeof(vis));
for (int i = 1; i <= n; i++)
if (!vis[i]) ans += getans(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;
const int MN = 100111;
int V;
vector<int> G[MN];
struct DirectedDfs {
vector<int> num, low, current, S;
int counter;
vector<vector<int> > scc;
DirectedDfs() : num(V, -1), low(V, 0), current(V, 0), counter(0) {
for (int i = 0, _a = (V); i < _a; i++)
if (num[i] == -1) dfs(i);
}
void dfs(int u) {
low[u] = num[u] = counter++;
S.push_back(u);
current[u] = 1;
for (int j = 0, _a = (G[u].size()); j < _a; j++) {
int v = G[u][j];
if (num[v] == -1) dfs(v);
if (current[v]) low[u] = min(low[u], low[v]);
}
if (low[u] == num[u]) {
scc.push_back(vector<int>());
while (1) {
int v = S.back();
S.pop_back();
current[v] = 0;
scc.back().push_back(v);
if (u == v) break;
}
}
}
};
int n, m, id[MN], isLoop[MN], lab[MN];
pair<int, int> e[MN];
int getRoot(int u) {
if (lab[u] < 0) return u;
return lab[u] = getRoot(lab[u]);
}
void merge(int u, int v) {
u = getRoot(u);
v = getRoot(v);
if (u == v) return;
if (lab[u] > lab[v]) swap(u, v);
lab[u] += lab[v];
lab[v] = u;
isLoop[u] += isLoop[v];
}
int main() {
while (scanf("%d%d", &n, &m) == 2) {
V = n;
for (int i = (0), _b = (n); i <= _b; i++) G[i].clear();
for (int i = (1), _b = (m); i <= _b; i++) {
int u, v;
scanf("%d%d", &u, &v);
--u;
--v;
G[u].push_back(v);
e[i] = make_pair(u, v);
}
DirectedDfs tree;
int cur = 0;
memset(lab, -1, sizeof lab);
memset(isLoop, 0, sizeof isLoop);
for (auto scc : tree.scc) {
++cur;
for (int x : scc) {
id[x] = cur;
if (scc.size() > 1) isLoop[cur] = 1;
}
lab[cur] = -scc.size();
}
for (int i = (1), _b = (m); i <= _b; i++) {
int u = id[e[i].first], v = id[e[i].second];
if (u != v) merge(u, v);
}
int res = 0;
for (int i = (1), _b = (cur); i <= _b; i++)
if (lab[i] < 0) {
if (isLoop[i])
res -= lab[i];
else
res -= lab[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 | #include <bits/stdc++.h>
using namespace std;
int const N = 100 * 1000 + 7;
int n, m, a[N], b[N], mark[N], ans, d;
vector<int> adj[N], vec;
void dfs1(int v) {
mark[v] = 1;
vec.push_back(v);
for (auto ed : adj[v]) {
int u = (ed < 0 ? a[-ed] : b[ed]);
if (!mark[u]) {
dfs1(u);
}
}
}
void dfs2(int v) {
mark[v] = 2;
for (auto ed : adj[v]) {
if (ed < 0) continue;
int u = b[ed];
if (mark[u] == 1) {
dfs2(u);
}
if (mark[u] == 2) {
d = 1;
}
}
mark[v] = 3;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> a[i] >> b[i];
a[i]--, b[i]--;
adj[a[i]].push_back(+i);
adj[b[i]].push_back(-i);
}
ans = n;
for (int v = 0; v < n; v++) {
if (!mark[v]) {
vec.clear();
dfs1(v);
d = 0;
for (auto u : vec) {
if (mark[u] == 1) {
dfs2(u);
}
}
ans += d - 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;
int n, m, cnt[100005], mp[100005], par[100005], ans;
bool vis[100005];
vector<int> v[100005];
int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); }
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) par[i] = i;
for (int i = 0; i < m; ++i) {
int a, b;
scanf("%d%d", &a, &b);
v[a].push_back(b);
par[find(a)] = find(b);
mp[b]++;
}
queue<int> q;
for (int i = 1; i <= n; ++i) {
cnt[find(i)]++;
if (!mp[i]) q.push(i);
}
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto &x : v[u])
if (!--mp[x]) q.push(x);
}
for (int i = 1; i <= n; ++i)
if (mp[i]) vis[find(i)] = 1;
for (int i = 1; i <= n; ++i)
if (par[i] == i) ans += cnt[i] - (vis[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;
long long mod = 1e9 + 7;
int main() {
int n, m;
cin >> n >> m;
vector<int> g[n];
vector<int> g2[n];
for (int i = (0); i < (m); i++) {
int a, b;
cin >> a >> b;
a--, b--;
g[a].push_back(b);
g2[b].push_back(a);
}
bool vis[n];
memset(vis, false, sizeof(vis));
stack<int> lis;
for (int i = (0); i < (n); i++) {
if (vis[i]) continue;
stack<int> S;
S.push(i);
vis[i] = true;
while (!S.empty()) {
int c = S.top();
for (auto u : g[c]) {
if (!vis[u]) {
S.push(u);
vis[u] = true;
break;
}
}
if (c == S.top()) {
lis.push(c);
S.pop();
}
}
}
memset(vis, false, sizeof(vis));
vector<vector<int> > scc;
while (!lis.empty()) {
int temp = lis.top();
lis.pop();
if (vis[temp]) continue;
vis[temp] = true;
stack<int> S;
S.push(temp);
vector<int> component;
while (!S.empty()) {
int c = S.top();
S.pop();
component.push_back(c);
for (auto u : g2[c]) {
if (!vis[u]) {
vis[u] = true;
S.push(u);
}
}
}
scc.push_back(component);
}
int id[n];
for (int i = (0); i < (scc.size()); i++) {
for (auto u : scc[i]) id[u] = i;
}
int k = scc.size();
int ok[k];
memset(ok, -1, sizeof(ok));
int ans = 0;
vector<int> cg[n];
vector<int> rcg[n];
for (int i = (0); i < (k); i++) {
for (auto u : scc[i]) {
for (auto e : g[u]) {
if (id[u] == id[e]) continue;
if (ok[id[e]] != i) {
ok[id[e]] = i;
cg[i].push_back(id[e]);
cg[id[e]].push_back(i);
}
}
}
}
memset(vis, false, sizeof(vis));
for (int i = (0); i < (k); i++) {
if (vis[i]) continue;
int cnt = 0;
queue<int> Q;
Q.push(i);
vis[i] = true;
int VER = 0;
bool cyc = false;
while (!Q.empty()) {
int c = Q.front();
VER += scc[c].size();
if (scc[c].size() > 1) cyc = true;
Q.pop();
cnt++;
for (auto u : cg[c]) {
if (!vis[u]) {
vis[u] = true;
Q.push(u);
}
}
}
if (cyc)
ans += VER;
else
ans += VER - 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>
const int maxn = 2e5;
using namespace std;
vector<int> g[maxn], dir[maxn];
int mark[maxn];
int vis[maxn];
bool cycle;
vector<int> an;
void tdfs(int u) {
vis[u] = 1;
an.push_back(u);
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (!vis[v]) tdfs(v);
}
}
void dfs(int u) {
mark[u] = 1;
for (int i = 0; i < dir[u].size(); i++) {
int v = dir[u][i];
if (!mark[v])
dfs(v);
else if (mark[v] == 1)
cycle = true;
}
mark[u] = 2;
}
int main() {
int n, m, ans;
scanf("%d%d", &n, &m);
ans = n;
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d%d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
dir[x].push_back(y);
}
for (int i = 1; i <= n; i++) {
if (!mark[i]) {
an.clear();
tdfs(i);
for (int i = 0; i < an.size(); i++) dfs(an[i]);
if (!cycle) ans--;
cycle = false;
}
}
printf("%d\n", ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class CF286B {
static int[] p;
static ArrayList<Integer>[] g;
static boolean[] v;
static boolean[] v2;
static int find(int i) {
return p[i] = i != p[i] ? find(p[i]) : i;
}
static int[] toposort;
static int top;
static void dfs(int i) {
if (v[i])
return;
v[i] = true;
for (int j : g[i])
dfs(j);
toposort[top++] = i;
}
static int cost() {
if (top == 0)
return 0;
for (int i = top - 1; i >= 0; i--) {
for (int j : g[toposort[i]])
if (v2[j])
return top;
v2[toposort[i]] = true;
}
return top - 1;
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer strtok;
strtok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(strtok.nextToken());
int m = Integer.parseInt(strtok.nextToken());
p = new int[n];
g = new ArrayList[n];
for (int i = 0; i < n; i++) {
p[i] = i;
g[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
strtok = new StringTokenizer(in.readLine());
int u = Integer.parseInt(strtok.nextToken()) - 1;
int v = Integer.parseInt(strtok.nextToken()) - 1;
g[u].add(v);
p[find(u)] = find(v);
}
ArrayList<Integer> sg = new ArrayList<>();
for (int i = 0; i < n; i++)
sg.add(i);
Collections.sort(sg, (a, b) -> Integer.compare(find(a), find(b)));
toposort = new int[n];
v = new boolean[n];
v2 = new boolean[n];
int lastcomp = -1;
int ans = 0;
for (int i : sg) {
if (lastcomp != find(i)) {
ans += cost();
lastcomp = find(i);
top = 0;
}
dfs(i);
}
ans += cost();
System.out.println(ans);
}
}
| JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = (int)1e5 + 100;
int n, m;
vector<int> g[N];
vector<int> gg[N];
vector<int> a[N];
int C;
int ans;
bool used[N];
int u[N];
void read() {
scanf("%d%d", &n, &m);
int v, x;
for (int i = 0; i < m; i++) {
scanf("%d%d", &v, &x);
v--;
x--;
g[v].push_back(x);
gg[v].push_back(x);
gg[x].push_back(v);
}
return;
}
void dfs1(int v) {
used[v] = 1;
a[C].push_back(v);
ans++;
for (int i = 0; i < (int)gg[v].size(); i++) {
int to = gg[v][i];
if (!used[to]) dfs1(to);
}
return;
}
bool dfs2(int v) {
u[v] = 1;
for (int i = 0; i < (int)g[v].size(); i++) {
int to = g[v][i];
if (u[to] != 0) {
if (u[to] == 1) return true;
} else {
if (dfs2(to)) return true;
}
}
u[v] = 2;
return false;
}
void solve() {
for (int i = 0; i < n; i++) {
if (used[i]) continue;
dfs1(i);
C++;
}
ans -= C;
for (int i = 0; i < C; i++) {
for (int j = 0; j < (int)a[i].size(); j++) {
int v = a[i][j];
if (u[v] != 0) continue;
if (dfs2(v)) {
ans++;
break;
}
}
}
printf("%d\n", ans);
return;
}
int main() {
read();
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;
template <typename T, typename U>
inline void smin(T &a, const U &b) {
if (a > b) a = b;
}
template <typename T, typename U>
inline void smax(T &a, const U &b) {
if (a < b) a = b;
}
template <class T>
inline void gn(T &first) {
char c, sg = 0;
while (c = getchar(), (c > '9' || c < '0') && c != '-')
;
for ((c == '-' ? sg = 1, c = getchar() : 0), first = 0; c >= '0' && c <= '9';
c = getchar())
first = (first << 1) + (first << 3) + c - '0';
if (sg) first = -first;
}
template <class T1, class T2>
inline void gn(T1 &x1, T2 &x2) {
gn(x1), gn(x2);
}
template <class T1, class T2, class T3>
inline void gn(T1 &x1, T2 &x2, T3 &x3) {
gn(x1, x2), gn(x3);
}
template <class T1, class T2, class T3, class T4>
inline void gn(T1 &x1, T2 &x2, T3 &x3, T4 &x4) {
gn(x1, x2, x3), gn(x4);
}
template <class T1, class T2, class T3, class T4, class T5>
inline void gn(T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5) {
gn(x1, x2, x3, x4), gn(x5);
}
template <class T>
inline void print(T first) {
if (first < 0) {
putchar('-');
return print(-first);
}
if (first < 10) {
putchar('0' + first);
return;
}
print(first / 10);
putchar(first % 10 + '0');
}
template <class T>
inline void println(T first) {
print(first);
putchar('\n');
}
template <class T>
inline void printsp(T first) {
print(first);
putchar(' ');
}
template <class T1, class T2>
inline void print(T1 x1, T2 x2) {
printsp(x1), println(x2);
}
template <class T1, class T2, class T3>
inline void print(T1 x1, T2 x2, T3 x3) {
printsp(x1), printsp(x2), println(x3);
}
template <class T1, class T2, class T3, class T4>
inline void print(T1 x1, T2 x2, T3 x3, T4 x4) {
printsp(x1), printsp(x2), printsp(x3), println(x4);
}
template <class T1, class T2, class T3, class T4, class T5>
inline void print(T1 x1, T2 x2, T3 x3, T4 x4, T5 x5) {
printsp(x1), printsp(x2), printsp(x3), printsp(x4), println(x5);
}
int power(int a, int b, int m, int ans = 1) {
for (; b; b >>= 1, a = 1LL * a * a % m)
if (b & 1) ans = 1LL * ans * a % m;
return ans;
}
int vst[100010], low[100010], ins[100010], st[100010], bel[100010];
int id, top, cnt;
vector<int> vec[100010], adj[100010];
int val[100010];
map<pair<int, int>, int> mp;
vector<int> num[100010];
void tarjan(int u) {
vst[u] = low[u] = ++id;
ins[u] = 1;
st[++top] = u;
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
if (!vst[v])
tarjan(v), low[u] = min(low[u], low[v]);
else if (ins[v])
low[u] = min(low[u], vst[v]);
}
if (vst[u] == low[u]) {
++cnt;
while (1) {
bel[st[top]] = cnt;
vec[cnt].push_back(st[top]);
ins[st[top]] = 0;
if (st[top--] == u) break;
}
}
}
int flag = 1;
int ans = 0;
void dfs(int u) {
if (val[bel[u]] > 1) flag = 0;
ans++;
for (int i = 0; i < num[u].size(); i++) {
int v = num[u][i];
if (vst[v]) continue;
vst[v] = 1;
dfs(v);
}
}
int main() {
int n, m;
gn(n, m);
for (int i = 1; i <= m; i++) {
int u, v;
gn(u, v);
adj[u].push_back(v);
}
for (int i = 1; i <= n; i++)
if (vst[i] == 0) tarjan(i);
for (int i = 1; i <= n; i++) val[bel[i]]++;
for (int i = 1; i <= n; i++)
for (int j = 0; j < adj[i].size(); j++) {
int u = adj[i][j];
if (!mp.count(pair<int, int>(i, u))) {
num[i].push_back(u);
num[u].push_back(i);
mp[pair<int, int>(i, u)] = 1;
mp[pair<int, int>(u, i)] = 1;
}
}
for (int i = 1; i <= n; i++) vst[i] = 0;
for (int i = 1; i <= n; i++)
if (vst[i] == 0) {
flag = 1;
vst[i] = 1;
dfs(i);
ans -= flag;
}
println(ans);
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100007;
vector<int> e[maxn], e2[maxn];
int n, m;
bool mark[maxn], free1[maxn], inDFS[maxn], foundCir;
vector<int> lst;
void dfs(int u) {
lst.push_back(u);
mark[u] = 1;
for (int i = 0; i < int(e2[u].size()); ++i) {
int v = e2[u][i];
if (!mark[v]) dfs(v);
}
}
void dfs2(int u) {
free1[u] = 0;
inDFS[u] = 1;
for (int i = 0; i < int(e[u].size()); ++i) {
int v = e[u][i];
if (free1[v])
dfs2(v);
else if (inDFS[v])
foundCir = 1;
}
inDFS[u] = 0;
}
int main() {
scanf("%d%d", &n, &m);
int u, v;
for (int i = 0; i < m; ++i) {
scanf("%d%d", &u, &v);
e[u].push_back(v);
e2[u].push_back(v);
e2[v].push_back(u);
}
memset(mark, 0, sizeof(mark));
memset(free1, 1, sizeof(free1));
memset(inDFS, 0, sizeof(inDFS));
int res = 0;
for (int u = 1; u <= n; ++u)
if (!mark[u]) {
lst.clear();
dfs(u);
foundCir = 0;
for (int i = 0; i < int(lst.size()); ++i) {
int x = lst[i];
if (free1[x]) dfs2(x);
}
res += int(lst.size());
if (!foundCir) res--;
}
cout << res << endl;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const long long MX = 1e5 + 9;
long long par[MX];
vector<long long> adj[MX], comp[MX];
bool st[MX], ft[MX], res;
long long FS(long long v) {
if (par[v] < 0) return v;
return par[v] = FS(par[v]);
}
void US(long long a, long long b) {
a = FS(a), b = FS(b);
if (a == b) return;
if (par[a] > par[b]) swap(a, b);
par[a] += par[b];
par[b] = a;
}
void DFS(long long u) {
st[u] = 1;
for (long long v : adj[u]) {
if (!st[v])
DFS(v);
else if (!ft[v])
res = 1;
}
ft[u] = 1;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long n, m;
cin >> n >> m;
fill(par, par + n + 1, -1);
for (long long i = 0; i < m; i++) {
long long u, v;
cin >> u >> v;
US(u, v);
adj[u].push_back(v);
}
for (long long i = 1; i <= n; i++) comp[FS(i)].push_back(i);
long long ans = 0;
for (long long i = 1; i <= n; i++) {
res = 0;
for (long long u : comp[i]) {
if (!st[u]) DFS(u);
}
ans += (comp[i].size() - 1 + res) * (comp[i].size() > 0);
}
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 | def main():
n, m = map(int, raw_input().split())
n += 1
cluster, dest, avail, ab = list(xrange(n)), [0] * n, [True] * n, [[] for _ in xrange(n)]
def root(x):
y = x
while y != cluster[y]:
y = cluster[y]
while x != y:
x, cluster[x] = cluster[x], y
return x
for _ in xrange(m):
a, b = map(int, raw_input().split())
ab[a].append(b)
dest[b] += 1
cluster[root(a)] = root(b)
pool = [a for a in xrange(1, n) if not dest[a]]
while pool:
u = pool.pop()
for v in ab[u]:
dest[v] -= 1
if not dest[v]:
pool.append(v)
for a in xrange(1, n):
avail[root(a)] &= not dest[a]
print(n - sum(f and a == c for a, c, f in zip(xrange(n), cluster, avail)))
if __name__ == '__main__':
main()
| PYTHON |
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.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
IOScanner scanner;
if (new File("data.in").exists()) {
scanner = new IOScanner("data.in", null);
} else {
scanner = new IOScanner();
}
while (scanner.hasNext()) {
new Solver(scanner).solve();
}
scanner.close();
}
}
class IOScanner {
private final BufferedReader reader;
private final PrintWriter writer;
private StringTokenizer stringTokenizer;
public IOScanner() {
this(System.in, System.out);
}
public IOScanner(String input, String output) throws FileNotFoundException {
this(input == null ? null : new File(input), output == null ? null : new File(output));
}
public IOScanner(File input, File output) throws FileNotFoundException {
this(input == null ? System.in : new FileInputStream(input), output == null ? System.out
: new FileOutputStream(output));
}
public IOScanner(InputStream inputStream, OutputStream outputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
writer = new PrintWriter(outputStream);
}
private StringTokenizer read() {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
try {
stringTokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
return null;
}
}
return stringTokenizer;
}
public boolean hasNext() {
StringTokenizer tokenizer = read();
return tokenizer != null && tokenizer.hasMoreTokens();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextInts(int n) {
int[] input = new int[n];
for (int i = 0; i < n; i++) {
input[i] = nextInt();
}
return input;
}
public int[][] nextInts(int n, int m) {
int[][] input = new int[n][];
for (int i = 0; i < n; i++) {
input[i] = nextInts(m);
}
return input;
}
public double[] nextDoubles(int n) {
double[] input = new double[n];
for (int i = 0; i < n; i++) {
input[i] = nextDouble();
}
return input;
}
public String[] nexts(int n) {
String[] input = new String[n];
for (int i = 0; i < n; i++) {
input[i] = next();
}
return input;
}
public char[][] nextCharArrays(int n) {
String[] input = nexts(n);
char[][] result = new char[n][];
for (int i = 0; i < n; i++) {
result[i] = input[i].toCharArray();
}
return result;
}
public String next() {
return read().nextToken();
}
public void println() {
writer.println();
}
public void println(Iterable<?> iterable) {
println(iterable.iterator());
}
public void println(Iterator<?> iterator) {
boolean first = true;
while (iterator.hasNext()) {
if (first) {
first = false;
} else {
print(' ');
}
print(iterator.next());
}
println();
}
public void println(Object token) {
writer.println(token);
}
public void print(Object token) {
writer.print(token);
}
public void printf(String format, Object... args) {
writer.printf(format, args);
}
public void flush() {
writer.flush();
}
public void close() throws IOException {
reader.close();
writer.close();
}
}
class Edge {
final int from, to;
final Edge next;
Edge(int from, int to, Edge next) {
this.from = from;
this.to = to;
this.next = next;
}
}
class Solver {
private final IOScanner scanner;
private Edge[] head;
private int[] visited, stack, low, id;
private int top, curT, curD, res;
private int[] p;
public Solver(IOScanner scanner) {
this.scanner = scanner;
}
public void solve() {
int n = scanner.nextInt();
int m = scanner.nextInt();
head = new Edge[n];
Arrays.fill(head, null);
int[][] edges = scanner.nextInts(m, 2);
for (int i = 0; i < m; i++) {
edges[i][0]--;
edges[i][1]--;
addEdge(edges[i][0], edges[i][1]);
}
visited = new int[n];
stack = new int[n];
low = new int[n];
id = new int[n];
curT = top = curD = 0;
Arrays.fill(visited, 0);
for (int i = 0; i < n; i++) {
if (visited[i] == 0) {
dfs(i);
}
}
p = new int[curD];
for (int i = 0; i < curD; i++) {
p[i] = i;
}
int[] count = new int[curD];
boolean[] has = new boolean[curD];
Arrays.fill(has, false);
for (int i = 0; i < m; i++) {
if (id[edges[i][0]] != id[edges[i][1]]) {
p[find(id[edges[i][0]])] = find(id[edges[i][1]]);
}
}
for (int i = 0; i < n; i++) {
count[find(id[i])]++;
}
for (int i = 0; i < m; i++) {
if (id[edges[i][0]] == id[edges[i][1]]) {
has[find(id[edges[i][0]])] = true;
}
}
res = n;
for (int i = 0; i < curD; i++) {
if (count[i] == 1 || count[i] > 1 && !has[i]) {
res--;
}
}
scanner.println(res);
}
private int find(int x) {
return x == p[x] ? p[x] : (p[x] = find(p[x]));
}
private void dfs(int u) {
int uid = ++curT;
low[u] = curT;
stack[top++] = u;
visited[u] = 1;
for (Edge e = head[u]; e != null; e = e.next) {
int v = e.to;
if (visited[v] == 0) {
dfs(v);
low[u] = Math.min(low[u], low[v]);
} else if (visited[v] != -1) {
low[u] = Math.min(low[u], low[v]);
}
}
if (low[u] == uid) {
int v, count = 0;
do {
v = stack[--top];
visited[v] = -1;
id[v] = curD;
count++;
} while (v != u);
curD++;
if (count > 1) {
res += count;
}
}
}
private void addEdge(int a, int b) {
Edge edge = new Edge(a, b, head[a]);
head[a] = edge;
}
} | JAVA |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 100;
long long n, m, vcmp[maxn], markc[maxn], cntc[maxn], ans, state[maxn];
vector<int> adj[maxn], cadj[maxn];
bool dfs(int x) {
state[x] = 1;
for (int i = 0; i < adj[x].size(); i++) {
int y = adj[x][i];
if (state[y] == 0) {
if (dfs(y)) return true;
} else if (state[y] == 1) {
return true;
}
}
state[x] = 2;
return false;
}
void findcycle() {
for (int i = 0; i < n; i++) {
if (state[i] == 0) {
if (dfs(i) == true) {
markc[vcmp[i]] = true;
}
}
}
for (int c = 1; c < maxn; c++) {
if (cntc[c] > 0) ans += cntc[c] + markc[c] - 1;
}
return;
}
void dfsc(int x, int color) {
vcmp[x] = color;
cntc[color]++;
for (int i = 0; i < cadj[x].size(); i++) {
if (vcmp[cadj[x][i]] == 0) {
dfsc(cadj[x][i], color);
}
}
return;
}
void findcomponents() {
int cmp = 1;
for (int i = 0; i < n; i++) {
if (vcmp[i] == 0) {
dfsc(i, cmp);
cmp++;
}
}
return;
}
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;
u--;
v--;
cadj[v].push_back(u);
cadj[u].push_back(v);
adj[v].push_back(u);
}
findcomponents();
findcycle();
cout << ans;
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
template <class T>
inline bool In(T &n) {
T x = 0, tmp = 1;
char c = getchar();
while ((c < '0' || c > '9') && c != '-' && c != EOF) c = getchar();
if (c == EOF) return false;
if (c == '-') c = getchar(), tmp = -1;
while (c >= '0' && c <= '9') x *= 10, x += (c - '0'), c = getchar();
n = x * tmp;
return true;
}
template <class T>
inline void Out(T n) {
if (n < 0) {
putchar('-');
n = -n;
}
int len = 0, data[20];
while (n) {
data[len++] = n % 10;
n /= 10;
}
if (!len) data[len++] = 0;
while (len--) putchar(data[len] + 48);
}
int n, m;
vector<int> g[100010], rg[100010];
vector<int> vs;
bool vis[100010];
int cmp[100010], cmps[100010];
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);
}
}
void scc() {
memset(vis, false, sizeof(vis));
for (int i = 0; i < n; i++)
if (!vis[i]) dfs(i);
memset(vis, false, sizeof(vis));
int k = 0;
for (int i = vs.size() - 1; i >= 0; i--)
if (!vis[vs[i]]) rdfs(vs[i], k++);
}
int dfs2(int v) {
vis[v] = true;
int ret = (cmps[cmp[v]] == 1);
for (int i = 0; i < g[v].size(); i++)
if (!vis[g[v][i]]) ret &= dfs2(g[v][i]);
for (int i = 0; i < rg[v].size(); i++)
if (!vis[rg[v][i]]) ret &= dfs2(rg[v][i]);
return ret;
}
int main() {
In(n);
In(m);
int a, b;
for (int i = 0; i < m; i++) {
In(a);
In(b);
a--;
b--;
g[a].push_back(b);
rg[b].push_back(a);
}
scc();
for (int i = 0; i < n; i++) cmps[cmp[i]]++;
memset(vis, false, sizeof(vis));
int ans = n;
for (int i = 0; i < n; i++) {
if (!vis[i]) ans -= dfs2(i);
}
Out(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> nve[100005], ve[100005], gr[100005];
bool used[100005];
int nu[100005];
int n, m, k;
bool hc;
void gdfs(int x) {
used[x] = true;
gr[k].push_back(x);
for (int i = 0; i < nve[x].size(); i++) {
if (!used[nve[x][i]]) gdfs(nve[x][i]);
}
}
void dfs(int x) {
nu[x] = 1;
for (int i = 0; i < ve[x].size(); i++) {
if (nu[ve[x][i]] == 1) hc = true;
if (!nu[ve[x][i]]) dfs(ve[x][i]);
}
nu[x] = 2;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
nve[a].push_back(b);
nve[b].push_back(a);
ve[a].push_back(b);
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
gdfs(i);
k++;
}
}
int sum = n;
for (int i = 0; i < k; i++) {
hc = false;
for (int j = 0; j < gr[i].size(); j++) {
if (!nu[gr[i][j]]) dfs(gr[i][j]);
}
if (!hc) sum--;
}
printf("%d", sum);
return 0;
}
| CPP |
506_B. Mr. Kitayuta's Technology | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int f[100001];
vector<int> g[100001];
bool visited[100001];
int t[100001], c = 0;
bool cyc[100001];
int find(int x) {
if (f[x] != x) f[x] = find(f[x]);
return f[x];
}
void u(int x, int y) {
x = find(x);
y = find(y);
f[x] = y;
}
void dfs(int x) {
visited[x] = true;
c++;
for (int i = 0; i < g[x].size(); i++)
if (!visited[g[x][i]]) dfs(g[x][i]);
c++;
t[x] = c;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
int i, a, b, j;
for (i = 0; i < n; i++) f[i] = i;
for (i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
a--;
b--;
u(a, b);
g[a].push_back(b);
}
memset(visited, false, sizeof(visited));
memset(cyc, false, sizeof(false));
for (i = 0; i < n; i++)
if (!visited[i]) dfs(i);
for (i = 0; i < n; i++)
for (j = 0; j < g[i].size(); j++)
if (t[i] < t[g[i][j]]) cyc[find(i)] = true;
set<int> s;
for (i = 0; i < n; i++)
if (!cyc[find(i)]) s.insert(find(i));
printf("%d\n", n - s.size());
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 fa[100005];
vector<int> g[100005];
bool vis[100005];
bool hh[100005];
int getf(int v) { return fa[v] == v ? v : fa[v] = getf(fa[v]); }
int dfn[100005];
int low[100005];
int belong[100005];
int nn[100005];
int ind;
bool v[100005];
bool sta[100005];
stack<int> ss;
int num = 0;
void tarjan(int u) {
dfn[u] = low[u] = ++ind;
ss.push(u);
sta[u] = true;
v[u] = true;
for (int i = 0; i < g[u].size(); i++) {
if (!v[g[u][i]]) {
tarjan(g[u][i]);
low[u] = min(low[u], low[g[u][i]]);
} else if (sta[g[u][i]]) {
low[u] = min(low[u], dfn[g[u][i]]);
}
}
if (dfn[u] == low[u]) {
int p, k = 0;
num++;
do {
k++;
p = ss.top();
ss.pop();
belong[p] = num;
sta[p] = false;
} while (p != u);
nn[num] = k;
}
}
int main(int argc, const char* argv[]) {
int n, m;
int u, v;
memset(vis, false, sizeof(vis));
memset(hh, false, sizeof(hh));
cin >> n >> m;
for (int i = 0; i <= n; i++) {
fa[i] = i;
}
for (int i = 0; i < m; i++) {
cin >> u >> v;
g[u].push_back(v);
if (getf(u) != getf(v)) {
fa[getf(u)] = getf(v);
}
}
for (int i = 1; i <= n; i++) {
getf(i);
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
ind = 0;
num = 0;
tarjan(i);
if (ind != num) {
hh[fa[i]] = true;
}
}
}
int tot = 0, block = 0;
for (int i = 1; i <= n; i++) {
if (fa[i] == i) {
if (hh[i]) {
tot++;
}
block++;
}
}
cout << n + tot - block << 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 max_N = 100000 + 10;
bool mark[max_N], on[max_N], cycle[max_N], flag;
int n, cnt, ans;
vector<int> adj[max_N], g[max_N];
void dfs1(int v) {
mark[v] = on[v] = true;
for (int u : adj[v]) {
if (!mark[u])
dfs1(u);
else if (on[u])
cycle[u] = true;
}
on[v] = false;
}
void dfs2(int v) {
cnt++;
mark[v] = true;
if (cycle[v]) flag = true;
for (int u : g[v])
if (!mark[u]) dfs2(u);
}
void dfs_all() {
for (int i = 0; i < n; i++)
if (!mark[i]) dfs1(i);
fill(mark, mark + n, 0);
for (int i = 0; i < n; i++) {
if (!mark[i]) {
cnt = 0, flag = 0;
dfs2(i);
if (flag)
ans += cnt;
else
ans += cnt - 1;
}
}
}
int main() {
int m, a, b;
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> a >> b;
adj[--a].push_back(--b);
g[a].push_back(b), g[b].push_back(a);
}
dfs_all();
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 = 2e5;
bool truth[MAXN];
int nvar;
int neg(int x) { return MAXN - 1 - x; }
vector<int> g[MAXN];
int n, m, lw[MAXN], idx[MAXN], qidx, cmp[MAXN], qcmp;
stack<int> st;
void tjn(int u) {
lw[u] = idx[u] = ++qidx;
st.push(u);
cmp[u] = -2;
for (int v : g[u]) {
if (!idx[v] || cmp[v] == -2) {
if (!idx[v]) tjn(v);
lw[u] = min(lw[u], lw[v]);
}
}
if (lw[u] == idx[u]) {
int x, l = -1;
do {
x = st.top();
st.pop();
cmp[x] = qcmp;
if (min(x, neg(x)) < nvar) l = x;
} while (x != u);
if (l != -1) truth[qcmp] = (cmp[neg(l)] < 0);
qcmp++;
}
}
void scc() {
memset(idx, 0, sizeof(idx));
qidx = 0;
memset(cmp, -1, sizeof(cmp));
qcmp = 0;
for (int i = 0; i < n; i++)
if (!idx[i]) tjn(i);
}
set<int> gn[MAXN];
bool vis[MAXN];
bool f = true;
map<int, int> q;
void dfs(int x) {
vis[x] = true;
f = f && q[x] == 1;
for (auto v : gn[x])
if (!vis[v]) dfs(v);
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--, b--;
g[a].push_back(b);
}
scc();
for (int i = 0; i < n; i++) {
q[cmp[i]]++;
}
long long res = n;
for (int i = 0; i < n; i++) {
for (auto x : g[i])
if (cmp[x] != cmp[i])
gn[cmp[i]].insert(cmp[x]), gn[cmp[x]].insert(cmp[i]);
}
for (int i = 0; i < qcmp; i++)
if (!vis[i]) dfs(i), res -= f, f = true;
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>
struct neighlist_t {
int neighbour;
char forward;
struct neighlist_t *next;
} * neighlist[100000];
int N, M;
int incoming[100000];
int outcoming[100000];
int processed[100000];
int fifo_start, fifo_end;
int fifo[100000];
int size;
void fifo_init() { fifo_start = fifo_end = 0; }
void fifo_push(int a) {
fifo[fifo_end] = a;
fifo_end++;
}
int fifo_pull() {
if (fifo_start == fifo_end) return -1;
return fifo[fifo_start++];
}
void dfs(int a) {
struct neighlist_t *n;
if (processed[a]) return;
processed[a] = 1;
size++;
if (!incoming[a]) fifo_push(a);
for (n = neighlist[a]; n; n = n->next) dfs(n->neighbour);
}
void add_edge(int a, int b) {
struct neighlist_t *n;
outcoming[a]++;
incoming[b]++;
n = (struct neighlist_t *)malloc(sizeof(struct neighlist_t));
n->next = neighlist[a];
n->neighbour = b;
n->forward = 1;
neighlist[a] = n;
n = (struct neighlist_t *)malloc(sizeof(struct neighlist_t));
n->next = neighlist[b];
n->neighbour = a;
n->forward = 1;
neighlist[b] = n;
}
void graph_init() {
int i;
for (i = 0; i < N; i++) neighlist[i] = NULL;
}
int main() {
int a, b, i, j;
struct neighlist_t *n;
int remain, result;
scanf("%d %d\n", &N, &M);
for (i = 0; i < M; i++) {
scanf("%d %d\n", &a, &b);
a--;
b--;
add_edge(a, b);
}
for (i = 0; i < N; i++) processed[i] = 0;
result = 0;
for (i = 0; i < N; i++) {
if (processed[i]) continue;
fifo_init();
size = 0;
dfs(i);
remain = size;
while ((j = fifo_pull()) >= 0) {
for (n = neighlist[j]; n; n = n->next)
if (n->forward) {
incoming[n->neighbour]--;
if (!incoming[n->neighbour]) fifo_push(n->neighbour);
}
remain--;
}
if (remain)
result += size;
else
result += size - 1;
}
printf("%d\n", result);
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;
int tot, n, m, head[maxn], sta[maxn];
int dfn[maxn], low[maxn], tt, top, las, f;
bool instack[maxn], cir[maxn];
struct edge {
int next, to;
} ji[maxn];
vector<int> v[maxn];
void add(int x, int y) {
v[x].push_back(y);
v[y].push_back(x);
ji[tot].next = head[x];
ji[tot].to = y;
head[x] = tot++;
}
void tarjan(int x) {
dfn[x] = low[x] = ++tt;
instack[x] = 1;
sta[++top] = x;
for (int k = head[x]; k != -1; k = ji[k].next) {
int toit = ji[k].to;
if (!dfn[toit]) {
tarjan(toit);
low[x] = min(low[x], low[toit]);
} else if (instack[toit])
low[x] = min(low[x], dfn[toit]);
}
if (dfn[x] == low[x]) {
for (int st;;) {
st = sta[top--];
instack[st] = 0;
cir[st] = (st != x);
if (st == x) break;
}
}
}
void dfs(int x) {
dfn[x] = ++tt;
if (cir[x]) f = 1;
for (int i = 0; i < v[x].size(); i++)
if (!dfn[v[x][i]]) dfs(v[x][i]);
}
int main() {
int a, b;
memset(head, -1, sizeof(head));
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
add(a, b);
}
int r = 0;
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
for (int i = 1; i <= n; i++) dfn[i] = 0;
tt = 0;
for (int i = 1; i <= n; i++) {
if (!dfn[i]) {
f = 0;
las = tt;
dfs(i);
r += tt - las - (f == 0);
}
}
printf("%d\n", r);
}
| 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 cmp = 0;
int mark[200005], sizes[200005], belongs[200005];
vector<int> adj[200005], radj[200005], grph[200005];
stack<int> st;
void dfs(int k) {
mark[k] = 1;
belongs[k] = cmp;
sizes[cmp]++;
for (int i = 0; i < grph[k].size(); i++) {
if (!mark[grph[k][i]]) {
dfs(grph[k][i]);
}
}
}
void dfs2(int k) {
mark[k] = 1;
for (int i = 0; i < adj[k].size(); i++) {
if (!mark[adj[k][i]]) {
dfs2(adj[k][i]);
}
}
st.push(k);
}
int cnt;
void dfs3(int k) {
mark[k] = 1;
cnt++;
for (int i = 0; i < radj[k].size(); i++) {
if (!mark[radj[k][i]]) {
dfs3(radj[k][i]);
}
}
}
int main() {
int n, m, i, j, x, y;
scanf("%d %d", &n, &m);
for (i = 0; i < m; i++) {
scanf("%d %d", &x, &y);
adj[x].push_back(y);
radj[y].push_back(x);
grph[x].push_back(y);
grph[y].push_back(x);
}
for (i = 1; i <= n; i++) {
if (!mark[i]) {
cmp++;
dfs(i);
}
}
for (i = 0; i <= n; i++) {
mark[i] = 0;
}
for (i = 1; i <= n; i++) {
if (!mark[i]) {
dfs2(i);
}
}
for (i = 1; i <= n; i++) {
mark[i] = 0;
}
int ans = 0;
while (!st.empty()) {
int p = st.top();
st.pop();
cnt = 0;
if (!mark[p]) {
dfs3(p);
if (cnt != 1 && sizes[belongs[p]] > 0)
sizes[belongs[p]] = -sizes[belongs[p]];
}
}
for (i = 1; i <= cmp; i++) {
if (sizes[i] < 0) {
ans += (-sizes[i]);
} else {
ans += (sizes[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;
template <class T>
T abs(T x) {
return x > 0 ? x : -x;
}
int n;
int m;
int was[100000];
int was2[100000];
int use[100000];
vector<int> v[100000];
vector<int> rv[100000];
vector<int> u[100000];
vector<int> q, w;
int go(int x) {
if (was[x]) return 0;
was[x] = 1;
for (int i = 0; i < ((int)(v[x]).size()); i++) go(v[x][i]);
q.push_back(x);
return 0;
}
int go2(int x) {
if (use[x]) return 0;
w.push_back(x);
use[x] = 1;
for (int i = 0; i < ((int)(u[x]).size()); i++) go2(u[x][i]);
return 0;
}
int go3(int x) {
if (was2[x]) return 0;
int cur = 1;
was2[x] = 1;
for (int i = 0; i < ((int)(rv[x]).size()); i++) cur += go3(rv[x][i]);
return cur;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
a--;
b--;
v[a].push_back(b);
rv[b].push_back(a);
u[a].push_back(b);
u[b].push_back(a);
}
int ans = n;
for (int i = 0; i < n; i++)
if (!use[i]) {
w.clear();
go2(i);
q.clear();
for (int j = 0; j < ((int)(w).size()); j++)
if (!was[w[j]]) go(w[j]);
reverse((q).begin(), (q).end());
int ok = 1;
for (int j = 0; j < ((int)(q).size()); j++)
if (go3(q[j]) > 1) {
ok = 0;
break;
}
ans -= ok;
}
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;
using LL = int64_t;
const int INF = 0x3fffffff;
const double EPS = 1e-9;
const double PI = 2 * asin(1);
bool g_f;
int g_n, g_m;
vector<bool> vb_mark;
vector<int> vi_mark, vi_num;
vector<vector<int>> vvi_e, vvi_ue;
void pretreat() {}
bool input() {
cin >> g_n >> g_m;
if (cin.eof()) return false;
vb_mark.clear(), vb_mark.resize(g_n + 1), vi_mark.clear();
vi_mark.resize(g_n + 1), vi_num.clear(), vvi_e.clear();
vvi_e.resize(g_n + 1), vvi_ue.clear(), vvi_ue.resize(g_n + 1);
for (int i = 0, u, v; i < g_m; ++i) {
scanf("%d%d", &u, &v);
vvi_e[u].emplace_back(v);
vvi_ue[u].emplace_back(v);
vvi_ue[v].emplace_back(u);
}
return true;
}
void dfs(int u) {
vi_mark[u] = 1;
for (auto &v : vvi_e[u]) {
if (vi_mark[v] == 0)
dfs(v);
else if (vi_mark[v] == 1)
g_f = true;
}
vi_mark[u] = 2;
}
void dfs_(int u) {
vb_mark[u] = true;
vi_num.emplace_back(u);
for (auto &v : vvi_ue[u]) {
if (!vb_mark[v]) dfs_(v);
}
}
void solve() {
int ans = 0;
for (int i = 1; i <= g_n; ++i) {
if (!vb_mark[i]) {
vi_num.clear();
g_f = false;
dfs_(i);
for (auto u : vi_num) dfs(u);
ans += vi_num.size() - 1;
if (g_f) ++ans;
}
}
cout << ans << endl;
}
int main() {
pretreat();
while (input()) {
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 |
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.contains(cmp[u])) {
loopExist = true;
} else {
hash.add(cmp[u]);
}
for (int v : g[u]) {
if (!visited[v]) dfs(v, cmp);
}
}
boolean loopExist;
boolean[] visited;
HashSet<Integer> hash = new HashSet<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>();
for (int i = 0; i < m; i++) {
a[i] = in.nextInt() - 1;
b[i] = in.nextInt() - 1;
g[a[i]].add(b[i]);
}
SCC scc = new SCC(g);
int[] cmp = scc.doit();
for (int i = 0; i < n; i++) g[i].clear();
for (int i = 0; i < m; i++) {
g[a[i]].add(b[i]);
g[b[i]].add(a[i]);
}
int res = n;
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();
loopExist = false;
dfs(next, cmp);
if (!loopExist) res--;
}
}
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 | import java.util.*;
import java.lang.*;
import java.io.*;
public class D
{
private static ArrayList<Integer> order;
private static ArrayList<Integer> component;
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int m = Integer.parseInt(tokenizer.nextToken());
ArrayList<Integer> [] graph = new ArrayList[n];
for(int i = 0 ; i < n ; i++)
graph[i] = new ArrayList<Integer>();
ArrayList<Integer> [] transpose = new ArrayList[n];
for(int i = 0 ; i < n ; i++)
transpose[i] = new ArrayList<Integer>();
ArrayList<Integer> [] all = new ArrayList[n];
for(int i = 0 ; i < n ; i++)
all[i] = new ArrayList<Integer>();
for(int i = 0 ; i < m ; i++)
{
tokenizer = new StringTokenizer(reader.readLine());
int a = Integer.parseInt(tokenizer.nextToken()) - 1;
int b = Integer.parseInt(tokenizer.nextToken()) - 1;
graph[a].add(b);
transpose[b].add(a);
all[a].add(b);
all[b].add(a);
}
boolean [] visited = new boolean[n];
order = new ArrayList<Integer>();
component = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i++)
if(!visited[i])
dfs(i, graph, visited);
boolean [] alone = new boolean[n];
Arrays.fill(visited, false);
for(int i = order.size()-1 ; i >= 0 ; i--)
if(!visited[order.get(i)])
{
component.clear();
dfs(order.get(i), transpose, visited);
if(component.size() == 1)
alone[order.get(i)] = true;
}
int res = 0;
Arrays.fill(visited, false);
for(int i = 0 ; i < n ; i++)
if(!visited[i])
{
component.clear();
dfs(i, all, visited);
boolean cycle = false;
for(int c : component)
if(!alone[c])
cycle = true;
if(cycle)
res += component.size();
else
res += component.size()-1;
}
System.out.println(res);
}
private static void dfs(int at, ArrayList<Integer>[] graph, boolean[] visited)
{
if(visited[at])
return;
visited[at] = true;
component.add(at);
for(int to : graph[at])
dfs(to, graph, visited);
order.add(at);
}
} | JAVA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.