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; bool used[200005]; vector<int> r; int n, m, x, y; int u[200005]; bool cycle; vector<int> G[200005]; vector<int> g[200005]; void dfs(int v) { r.push_back(v); used[v] = true; for (int i = 0; i < (int)G[v].size(); ++i) { int to = G[v][i]; if (!used[to]) dfs(to); } } void dfs2(int v) { u[v] = 1; for (int i = 0; i < g[v].size(); ++i) { int to = g[v][i]; if (u[to] == 0) dfs2(to); else { if (u[to] == 1) { cycle = true; break; } } } u[v] = 2; } void solve() { scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) { scanf("%d%d", &x, &y); x--; y--; G[x].push_back(y); G[y].push_back(x); g[x].push_back(y); } memset(used, false, sizeof(used)); int ans = n; for (int i = 0; i < n; ++i) { if (!used[i]) { dfs(i); cycle = false; for (int j = 0; j < r.size(); ++j) u[r[j]] = 0; for (int j = 0; j < r.size(); ++j) { int to = r[j]; if (u[to] == 0) dfs2(to); } ans -= !cycle; r.clear(); } } cout << ans << endl; } int main() { solve(); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int N = 100500; vector<int> g[N], f[N], vc; int us[N], vis[N], cyc; void dfs(int x) { us[x] = 1; for (int i = 0; i < g[x].size(); i++) { int y = g[x][i]; if (us[y] == 1) cyc = 1; if (!us[y]) dfs(y); } us[x] = 2; } void dfsu(int x) { if (vis[x]) return; vis[x] = 1; vc.push_back(x); for (int i = 0; i < f[x].size(); i++) dfsu(f[x][i]); } int main() { int n, m, a, b; cin >> n >> m; for (int i = 0; i < m; i++) { cin >> a >> b; a--; b--; g[a].push_back(b); f[a].push_back(b); f[b].push_back(a); } int res = 0; memset(us, 0, sizeof us); memset(vis, 0, sizeof vis); for (int i = 0; i < n; i++) if (!vis[i]) { cyc = 0; vc.clear(); dfsu(i); for (int j = 0; j < vc.size(); j++) if (!us[vc[j]]) dfs(vc[j]); res += vc.size() - 1 + cyc; } cout << res; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, m; queue<int> q; int vis[N]; vector<int> no[N]; vector<int> v[N]; int in[N], p[N]; long long ans = 0; int find(int u) { if (u == p[u]) return u; return p[u] = find(p[u]); } void add(int id) { q.empty(); for (int i = 0; i < no[id].size(); i++) if (!in[no[id][i]]) q.push(no[id][i]); int x = 0; while (q.size()) { int u = q.front(); q.pop(); x++; for (int i = 0; i < v[u].size(); i++) { if (!--in[v[u][i]]) q.push(v[u][i]); } } if (x == no[id].size()) ans += no[id].size() - 1; else ans += no[id].size(); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) p[i] = i; for (int a, b, i = 0; i < m; i++) { scanf("%d%d", &a, &b); v[a].push_back(b); in[b]++; p[find(a)] = find(b); } for (int i = 1; i <= n; i++) { no[find(i)].push_back(i); } for (int i = 1; i <= n; i++) { if (p[i] == i) add(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
import java.io.IOException; import java.util.HashSet; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.LinkedList; public class MrKitayutasTechnology { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int M = sc.nextInt(); InOutNode[] nodes = new InOutNode[N + 1]; for (int i = 1; i <= N; i++){ nodes[i] = new InOutNode(); } for (int i = 0; i < M; i++) { int a = sc.nextInt(); int b = sc.nextInt(); nodes[a].nexts.add(nodes[b]); nodes[b].prevs.add(nodes[a]); } int cnt = 0; HashSet<InOutNode> visited = new HashSet<InOutNode>(); for (int i = 1; i <= N; i++) { if (!visited.contains(nodes[i])) { HashSet<InOutNode> comp = getComponent(nodes[i]); if (toplogicalSort(comp) == null) { cnt += comp.size(); } else { cnt += comp.size() - 1; } for (InOutNode n : comp) { visited.add(n); } } } System.out.println(cnt); } public static HashSet<InOutNode> getComponent(InOutNode seed) { HashSet<InOutNode> visited = new HashSet<InOutNode>(); LinkedList<InOutNode> q = new LinkedList<InOutNode>(); q.addLast(seed); while (!q.isEmpty()) { InOutNode curr = q.removeFirst(); if (visited.contains(curr)) { continue; } visited.add(curr); for (InOutNode n : curr.nexts) { q.addLast(n); } for (InOutNode n : curr.prevs) { q.addLast(n); } } return visited; } // NOTE: destructively modifies the input nodes public static ArrayList<InOutNode> toplogicalSort(HashSet<InOutNode> nodes) { ArrayList<InOutNode> lst = new ArrayList<InOutNode>(); HashSet<InOutNode> starts = new HashSet<InOutNode>(); LinkedList<InOutNode> q = new LinkedList<InOutNode>(); for (InOutNode n : nodes) { if (n.prevs.size() == 0) { starts.add(n); q.addLast(n); } } while (!q.isEmpty()) { InOutNode n = q.removeFirst(); if (!starts.contains(n)) { continue; } lst.add(n); for (InOutNode m : n.nexts) { m.prevs.remove(n); if (m.prevs.size() == 0) { starts.add(m); q.addLast(m); } } n.nexts.clear(); } for (InOutNode n : nodes) { if ((n.prevs.size() > 0) || (n.nexts.size() > 0)) { return null; } } return lst; } public static class InOutNode { public HashSet<InOutNode> nexts; public HashSet<InOutNode> prevs; public InOutNode() { this.nexts = new HashSet<InOutNode>(); this.prevs = new HashSet<InOutNode>(); } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { 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 int nextInt() { 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 int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> #pragma optimization_level 3 #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") using namespace std; const int N = 3e5 + 5; const long long mod = 1e9 + 7; const long long INF = 1e18; const int INFi = 0x7f7f7f7f; long long test = 1, n, m, vis[N], rec[N], cyc[N], p[N], sz[N]; vector<long long> adj[N]; stack<long long> Stack; void make(long long n) { for (int i = 1; i <= n; i++) { p[i] = i; sz[i] = 1; } } int find(long long x) { return (p[x] == x) ? x : p[x] = find(p[x]); } void merge(long long x, long long y) { long long a = find(x); long long b = find(y); if (a != b) { if (sz[a] >= sz[b]) swap(a, b); p[a] = b; sz[b] += sz[a]; } } void TSUtil(int v) { vis[v] = 1; for (auto it : adj[v]) if (!vis[it]) TSUtil(it); Stack.push(v); } void TS() { for (int i = 1; i <= n; i++) if (!vis[i]) TSUtil(i); while (Stack.empty() == 0) { cout << Stack.top() << " "; Stack.pop(); } } bool CycleUtil(int v) { if (vis[v] == 0) { vis[v] = 1, rec[v] = 1; for (auto it : adj[v]) { if (!vis[it] && CycleUtil(it)) return 1; else if (rec[it]) return 1; } } rec[v] = 0; return 0; } void Cycle() { for (int i = 1; i <= n; i++) if (CycleUtil(i)) cyc[find(i)] = 1; } void solve() { cin >> n >> m; make(n); for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); merge(u, v); } Cycle(); long long ans = 0; for (int i = 1; i <= n; i++) { if (find(i) == i) { if (cyc[i] == 1) ans += sz[i]; else ans += sz[i] - 1; } } cout << ans << " " << "\n"; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed; cout << setprecision(10); ; for (int i = 1; i <= test; i++) { 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> #pragma optimization_level 3 #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") using namespace std; const long double PI = 3.14159265358979323846; const long long MOD = 1e+9 + 7; const long long INF = LLONG_MAX; const int INFi = INT_MAX; const long long N = 2e+5 + 8; vector<long long> adj[N], adju[N]; long long vis[N]; long long dx4[] = {0, 1, 0, -1}, dy4[] = {1, 0, -1, 0}; long long test_cases = 1; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); ; long long n, m, u, v, ok, grp[N]; vector<long long> pt; void isCycle(long long v, long long p) { vis[v] = 1; for (auto to : adj[v]) { if (vis[to] == 1) ok = 1; if (vis[to] == 0) isCycle(to, v); } vis[v] = 2; } void dfs(long long v, long long p) { vis[v] = 1; for (auto to : adju[v]) { if (vis[to] == 0) dfs(to, v); } pt.push_back(v); } void MAIN(long long tc) { cin >> n >> m; for (long long i = 1; i <= m; i++) { cin >> u >> v; adj[u].push_back(v); adju[u].push_back(v); adju[v].push_back(u); } long long ct = 1, res = 0; for (long long i = (0); i <= n + 5; i++) vis[i] = 0; ; for (long long i = 1; i <= n; i++) { if (vis[i] == 0) { pt.clear(); dfs(i, 0); for (auto it : pt) grp[it] = ct; res += pt.size() - 1; ct++; } } set<long long> k; for (long long i = (0); i <= n + 5; i++) vis[i] = 0; ; for (long long i = 1; i <= n; i++) { if (vis[i] == 0) { ok = 0; isCycle(i, 0); if (ok) k.insert(grp[i]); } } res += k.size(); cout << res; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed; cout << setprecision(10); ; for (long long i = (1); i <= test_cases; i++) { MAIN(i); } }
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; struct edge { int to, next; } e[maxn]; int fa[maxn], siz[maxn], n, m, last[maxn], cnt; inline void add(int u, int v) { cnt++; e[cnt].to = v; e[cnt].next = last[u]; last[u] = cnt; } int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void unionn(int x, int y) { int na = find(x), nb = find(y); if (na == nb) return; siz[nb] += siz[na]; fa[na] = nb; } int dfn[maxn], huan[maxn]; void dfs(int u) { dfn[u] = 1; for (int i = last[u]; i; i = e[i].next) { int v = e[i].to; if (!dfn[v]) dfs(v); else if (dfn[v] == 1) huan[find(v)] = 1; } dfn[u] = 2; } int ans = 0; int main() { cin >> n >> m; for (int i = 1; i <= n; i++) siz[i] = 1, fa[i] = i; for (int i = 1, u, v; i <= m; i++) { scanf("%d %d", &u, &v); add(u, v); unionn(v, u); } for (int i = 1; i <= n; i++) { if (!dfn[i]) dfs(i); } for (int i = 1; i <= n; i++) { if (find(i) == i) { ans += siz[i] - 1; } ans += huan[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; int n, m; int E[200010], X[200010], H[100010], co = 1; int rd[100010]; inline void addEdge(int x, int y) { E[++co] = y, X[co] = H[x], H[x] = co; E[++co] = x, X[co] = H[y], H[y] = co; ++rd[y]; } bool v[100010]; int g[100010], tt; void dfs(int x) { v[x] = true; g[++tt] = x; for (int p = H[x]; p; p = X[p]) if (!v[E[p]]) dfs(E[p]); } queue<int> Q; bool calc() { for (int i = 1; i <= tt; ++i) if (!rd[g[i]]) Q.push(g[i]); int tp; while (!Q.empty()) { tp = Q.front(); Q.pop(); for (int p = H[tp]; p; p = X[p]) { if (p % 2 == 0 && --rd[E[p]] == 0) Q.push(E[p]); } } for (int i = 1; i <= tt; ++i) if (rd[g[i]] > 0) return false; return true; } int getNum() { int ret = 0; memset(v, false, sizeof v); for (int i = 1; i <= n; ++i) if (!v[i]) { tt = 0; dfs(i); if (calc()) ++ret; } return ret; } int main() { scanf("%d %d", &n, &m); int x, y; for (int i = 1; i <= m; ++i) { scanf("%d %d", &x, &y); addEdge(x, y); } printf("%d\n", n - getNum()); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<vector<int> > gu(n); vector<vector<int> > gd(n); vector<int> dg(n); for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; a--; b--; gu[a].push_back(b); gd[a].push_back(b); gd[b].push_back(a); dg[b]++; } queue<int> q; for (int i = 0; i < n; i++) if (dg[i] == 0) q.push(i); vector<int> lib(n, false); while (not q.empty()) { int a = q.front(); q.pop(); lib[a] = true; for (int i = 0; i < gu[a].size(); i++) { int b = gu[a][i]; if (--dg[b] == 0) q.push(b); } } q = queue<int>(); for (int i = 0; i < n; i++) if (not lib[i]) q.push(i); while (not q.empty()) { int a = q.front(); q.pop(); for (int i = 0; i < gd[a].size(); i++) { int b = gd[a][i]; if (not lib[b]) continue; lib[b] = false; q.push(b); } } int ans = n; for (int i = 0; i < n; i++) { if (not lib[i]) continue; ans--; q = queue<int>(); q.push(i); while (not q.empty()) { int a = q.front(); q.pop(); for (int i = 0; i < gd[a].size(); i++) { int b = gd[a][i]; if (not lib[b]) continue; lib[b] = false; q.push(b); } } } cout << ans << endl; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; vector<int> adj[100010], radj[100010]; bool vis[100010]; int N, M; vector<int> order; int grp[100010], gz, grp_size[100010]; int wcc_size[100010], wcc_cnt; bool wcc_cyclic[100010]; void dfs(int u) { vis[u] = true; for (const int v : adj[u]) { if (!vis[v]) { dfs(v); } } order.push_back(u); } void rdfs(int u, int g) { vis[u] = true; grp[u] = g; grp_size[g]++; for (const int v : radj[u]) { if (!vis[v]) { rdfs(v, g); } } } void udfs(int u, int w) { vis[u] = true; wcc_size[w]++; if (grp_size[grp[u]] > 1) { wcc_cyclic[w] = true; } for (const int v : adj[u]) { if (!vis[v]) { udfs(v, w); } } for (const int v : radj[u]) { if (!vis[v]) { udfs(v, w); } } } int main(int argc, char **argv) { int N, M; cin >> N >> M; for (int i = (0); i < (M); i++) { int x, y; cin >> x >> y; --x, --y; adj[x].push_back(y); radj[y].push_back(x); } memset(vis, 0, sizeof(vis)); for (int i = (0); i < (N); i++) { if (!vis[i]) { dfs(i); } } memset(vis, 0, sizeof(vis)); for (int i = (N)-1; i >= (0); i--) { if (!vis[order[i]]) { rdfs(order[i], gz); gz++; } } memset(vis, 0, sizeof(vis)); for (int i = (0); i < (N); i++) { if (!vis[i]) { udfs(i, wcc_cnt); wcc_cnt++; } } int res = 0; for (int i = (0); i < (wcc_cnt); i++) { res += wcc_size[i] - !wcc_cyclic[i]; } printf("%d\n", res); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int dfsnum = 0, dfn[110000], low[110000], n, m, sta[110000], top = 0, sccnum = 0, scc[110000], sc[110000], insta[110000]; vector<int> g[110000], rg[110000]; bool bo[110000]; void tarjan(int x) { int i, j, k; bo[x] = true; dfn[x] = low[x] = ++dfsnum; sta[++top] = x; insta[x] = true; for (k = 0; k < g[x].size(); k++) { int y = g[x][k]; if (dfn[y] == -1) { tarjan(y); low[x] = min(low[x], low[y]); } else if (insta[y]) low[x] = min(low[x], dfn[y]); } if (dfn[x] == low[x]) { ++sccnum; do { k = sta[top--]; insta[k] = false; scc[k] = sccnum; } while (k != x); } } int dfs(int x) { bo[x] = true; int ret = (sc[scc[x]] == 1), i, j, k; for (i = 0; i < g[x].size(); i++) if (!bo[g[x][i]]) ret &= dfs(g[x][i]); for (i = 0; i < rg[x].size(); i++) if (!bo[rg[x][i]]) ret &= dfs(rg[x][i]); return ret; } int main() { int i, j, k; scanf("%d%d", &n, &m); for (i = 1; i <= m; i++) { int x, y; scanf("%d%d", &x, &y); g[x].push_back(y); rg[y].push_back(x); } memset(bo, false, sizeof(bo)); memset(dfn, -1, sizeof(dfn)); memset(insta, false, sizeof(insta)); for (i = 1; i <= n; i++) if (!bo[i]) tarjan(i); memset(sc, 0, sizeof(sc)); for (i = 1; i <= n; i++) sc[scc[i]]++; int ans = n; memset(bo, false, sizeof(bo)); for (i = 1; i <= n; i++) if (!bo[i]) ans -= dfs(i); printf("%d\n", ans); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; vector<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 maxn = 2000011, maxm = 2000011; int tot = 0, v[maxm], son[maxm], pre[maxm], now[maxn]; void add(int a, int b) { pre[++tot] = now[a]; now[a] = tot; son[tot] = b; } int fa[maxn], n, m; bool Vis[maxn]; int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } void init() { scanf("%d%d", &n, &m); memset(Vis, 0, sizeof(Vis)); for (int i = 1; i <= n; ++i) fa[i] = i; for (int i = 1, a, b; i <= m; ++i) { scanf("%d%d", &a, &b); Vis[a] = 1; Vis[b] = 1; add(a, b); fa[find(a)] = find(b); } } int dfn[maxn], low[maxn], Stack[maxn], stot = 0, sign = 0, ans; bool b[maxn], B[maxn]; void tarjan(int x) { dfn[x] = low[x] = ++sign; Stack[++stot] = x; b[x] = 1; for (int p = now[x]; p; p = pre[p]) if (!dfn[son[p]]) { tarjan(son[p]); low[x] = min(low[x], low[son[p]]); } else if (b[son[p]]) low[x] = min(low[x], dfn[son[p]]); if (dfn[x] == low[x]) { bool ok = 0; if (Stack[stot] != x) ok = 1; while (Stack[stot + 1] != x) { if (ok) B[find(Stack[stot])] = 1; b[Stack[stot--]] = 0; } } } void work() { ans = 0; memset(B, 0, sizeof(B)); for (int i = 1; i <= n; ++i) if (Vis[i]) ++ans; for (int i = 1; i <= n; ++i) if (Vis[i] && !dfn[i]) tarjan(i); for (int i = 1; i <= n; ++i) if (Vis[i] && find(i) == i && !B[i]) --ans; cout << ans << endl; } int main() { init(); work(); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int n, m, ans, cnt, ind, top, scc; int low[100005], dfn[100005], q[100005], bl[100005], num[100005]; int fa[100005], last[100005]; bool inq[100005], mark[100005]; struct edge { int to, next, v; } e[100005]; void insert(int u, int v) { e[++cnt].to = v; e[cnt].next = last[u]; last[u] = cnt; } int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void tarjan(int x) { low[x] = dfn[x] = ++ind; inq[x] = 1; q[++top] = x; for (int i = last[x]; i; i = e[i].next) if (!dfn[e[i].to]) { tarjan(e[i].to); low[x] = min(low[x], low[e[i].to]); } else if (inq[e[i].to]) low[x] = min(low[x], dfn[e[i].to]); if (low[x] == dfn[x]) { int now = 0; scc++; while (x != now) { now = q[top]; top--; bl[now] = scc; inq[now] = 0; num[scc]++; if (num[scc] != 1) mark[scc] = 1; } } } void rebuild() { cnt = 0; for (int x = 1; x <= n; x++) { for (int i = last[x]; i; i = e[i].next) { int u = bl[x], v = bl[e[i].to]; int p = find(u), q = find(v); if (p != q) { fa[p] = q; num[q] += num[p]; mark[q] |= mark[p]; } } } } int main() { n = read(); m = read(); for (int i = 1; i <= m; i++) { int u = read(), v = read(); insert(u, v); } for (int i = 1; i <= n; i++) if (!dfn[i]) tarjan(i); for (int i = 1; i <= scc; i++) fa[i] = i; rebuild(); for (int i = 1; i <= scc; i++) if (fa[i] == i) { if (!mark[i]) ans += num[i] - 1; else ans += num[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 N = 100100; int n, m, ans = 0; int fa[N], u[N], v[N], cnt[N], ord[N], deg[N]; vector<pair<int, int> > edge[N]; vector<int> a[N]; int Root(int x) { return (fa[x] == x) ? x : (fa[x] = Root(fa[x])); } int Get(int x) { for (int i = 1; i <= cnt[x]; i++) { deg[i] = 0; a[i].clear(); } for (int i = 0; i < edge[x].size(); i++) { a[edge[x][i].first].push_back(edge[x][i].second); deg[edge[x][i].second]++; } int dem = 0; queue<int> q; for (int i = 1; i <= cnt[x]; i++) { if (!deg[i]) { q.push(i); } } while (!q.empty()) { int foo = q.front(); q.pop(); dem++; for (int i = 0; i < a[foo].size(); i++) { int foo2 = a[foo][i]; if (--deg[foo2] == 0) { q.push(foo2); } } } return cnt[x] == dem ? cnt[x] - 1 : cnt[x]; } int main() { ios_base::sync_with_stdio(0); cin >> n >> m; for (int i = 1; i <= n; i++) { fa[i] = i; } for (int i = 1; i <= m; i++) { cin >> u[i] >> v[i]; int xx = Root(u[i]); int yy = Root(v[i]); if (Root(xx) != Root(yy)) { fa[xx] = yy; } } for (int i = 1; i <= n; i++) { ord[i] = ++cnt[Root(i)]; } for (int i = 1; i <= m; i++) { edge[Root(u[i])].push_back(make_pair(ord[u[i]], ord[v[i]])); } for (int i = 1; i <= n; i++) { if (!edge[i].size()) { continue; } ans += Get(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; struct UF { int par[100005]; void init(int n) { for (int i = 0; i < n; i++) { par[i] = i; } } int find(int x) { if (par[x] == x) return x; return par[x] = find(par[x]); } void unite(int x, int y) { x = find(x); y = find(y); par[y] = x; } }; UF uf; vector<int> vec[100005]; vector<int> rvec[100005]; vector<int> dag[100005]; vector<int> vs; int cmb[100005], nd[100005], deg[100005]; int ord[100005], id[100005]; bool use[100005], ok[100005]; int n, m, bef; void dfs(int v) { use[v] = true; for (int i = 0; i < vec[v].size(); i++) if (!use[vec[v][i]]) dfs(vec[v][i]); vs.push_back(v); } void rdfs(int v, int k) { use[v] = true; cmb[v] = k; nd[k]++; for (int i = 0; i < rvec[v].size(); i++) if (!use[rvec[v][i]]) rdfs(rvec[v][i], k); } int scc() { memset(use, false, sizeof(use)); for (int i = 0; i < n; i++) if (!use[i]) dfs(i); memset(use, false, sizeof(use)); int k = 0; for (int i = n - 1; i >= 0; i--) if (!use[vs[i]]) rdfs(vs[i], k++); int now = 0; bef = -1; for (int i = 0; i < k; i++) { if (nd[i] > 1) { if (bef == -1) bef = now++; id[i] = bef; } else id[i] = now++; } uf.init(n + 2); for (int i = 0; i < n; i++) { for (int j = 0; j < vec[i].size(); j++) { int to = vec[i][j]; if (id[cmb[to]] != id[cmb[i]]) uf.unite(id[cmb[to]], id[cmb[i]]); } } int ret = 0; for (int i = 0; i < now; i++) if (uf.find(i) == i) ret++; return n - (ret - (bef == -1 ? 0 : 1)); } int main() { scanf("%d %d", &n, &m); for (int i = 0; i < m; i++) { int a, b; scanf("%d %d", &a, &b); a--; b--; vec[a].push_back(b); rvec[b].push_back(a); } printf("%d\n", scc()); 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; bool used[100001]; int cmp[100001]; vector<int> g[100001], gr[100001]; vector<int> vs; void add(int x, int y) { g[x].push_back(y); gr[y].push_back(x); } vector<int> v[100001]; int ct; void dfs0(int x) { used[x] = 1; v[ct].push_back(x); for (auto y : g[x]) { if (!used[y]) dfs0(y); } for (auto y : gr[x]) { if (!used[y]) dfs0(y); } } void dfs(int x) { used[x] = 1; for (auto y : g[x]) { if (!used[y]) dfs(y); } vs.push_back(x); } void rdfs(int v, int k) { used[v] = 1; cmp[v] = k; for (auto y : gr[v]) { if (!used[y]) rdfs(y, k); } } int scc() { fill(used, used + n, 0); vs.clear(); for (int i = 0; i < n; i++) { if (!used[i]) dfs(i); } fill(used, used + n, 0); int k = 0; for (int i = vs.size() - 1; i >= 0; i--) { if (!used[vs[i]]) rdfs(vs[i], k++); } return k; } int main() { cin >> n >> m; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; a--; b--; add(a, b); } for (int i = 0; i < n; i++) { if (!used[i]) { dfs0(i); ct++; } } int ans = n - ct; fill(used, used + n, 0); scc(); for (int i = 0; i < ct; i++) { bool nuee = 0; unordered_set<int> st; for (auto x : v[i]) { if (st.find(cmp[x]) != st.end()) { nuee = 1; break; } st.insert(cmp[x]); } if (nuee) ans++; } cout << ans << endl; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int maxn = 1000 * 100 + 10; vector<int> v[3][maxn], e[maxn]; int mark[maxn]; int w[maxn]; vector<int> q; int flag[maxn]; vector<pair<int, int> > edge; inline void dfs(int x, int t, int l) { mark[x] = l; for (int i = 0; i < v[t][x].size(); ++i) { int u = v[t][x][i]; if (mark[u] == 0) dfs(u, t, l); } if (t == 1) q.push_back(x); else { w[l]++; } } inline int first(int x) { flag[x] = 1; int ret = 0; if (w[x] > 1) ret = 1; for (int i = 0; i < e[x].size(); ++i) { int u = e[x][i]; if (flag[u] == 0) ret |= first(u); } return ret; } int main() { ios_base::sync_with_stdio(false); int n, m; cin >> n >> m; while (m-- > 0) { int fi, se; cin >> fi >> se; v[1][fi].push_back(se); v[2][se].push_back(fi); edge.push_back(pair<int, int>(fi, se)); } for (int i = 1; i <= n; ++i) if (mark[i] == 0) dfs(i, 1, 1); memset(mark, 0, sizeof mark); int cnt = 1; for (int i = n - 1; i >= 0; --i) { if (mark[q[i]] == 0) dfs(q[i], 2, cnt++); } for (int i = 0; i < edge.size(); ++i) { int fi = edge[i].first, se = edge[i].second; if (mark[fi] != mark[se]) e[mark[fi]].push_back(mark[se]); e[mark[se]].push_back(mark[fi]); } int set_number = 0, ans = n; for (int i = 1; i < cnt; ++i) { if (flag[i] == 0) { ans += first(i); set_number++; } } cout << ans - set_number << 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; long long int mod = 1e10; int a[100100], t1[100100], t2[100100], t, f[100100], p[100100], c[100100]; vector<int> v[100100]; int find(int x) { if (x == p[x]) return x; return (p[x] = find(p[x])); } void un(int x1, int x2) { x1 = find(x1); x2 = find(x2); if (x1 != x2) { p[x1] = x2; c[x2] += c[x1]; } } void dfs(int x, int p) { int i; t1[x] = t; t2[x] = 0; t++; a[x] = p; for (i = 0; i < v[x].size(); i++) if (a[v[x][i]] == -1) dfs(v[x][i], x); else if (t2[v[x][i]] == 0) f[x] = 1; t2[x] = t; t++; } void solve(int n, int m) { int j, i, l = 0, w, k, ans = m; for (i = 0; i < n; i++) { a[i] = -1; v[i].clear(); f[i] = 0; t2[i] = 0; p[i] = i; c[i] = 1; } for (i = 0; i < m; i++) { scanf("%d%d", &l, &k); v[l - 1].push_back(k - 1); un(l - 1, k - 1); } t = 0; for (i = 0; i < n; i++) if (a[i] == -1) dfs(i, 1e5); ans = 0; for (i = 0; i < n; i++) if (f[i] == 1) f[find(i)] = 1; for (i = 0; i < n; i++) if (find(i) == i && c[i] > 1) { if (f[i] == 0) ans += c[i] - 1; else ans += c[i]; } printf("%d\n", ans); } int main() { #pragma comment(linker, "/STACK:1073741824") int n, m; while (scanf("%d%d", &n, &m) != EOF) solve(n, m); 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 mxn = 100 * 1000 + 5; int n, m, ans; vector<int> g[mxn], rg[mxn], topol; bool been[mxn], cycle[mxn]; void topol_sort(int u) { been[u] = true; for (int v : g[u]) if (!been[v]) topol_sort(v); topol.push_back(u); } void scc(int u, bool q) { been[u] = true; cycle[u] = q; for (int v : rg[u]) if (!been[v]) cycle[u] = true, scc(v, true); } bool wcc(int u) { been[u] = true; bool res = cycle[u]; for (int v : g[u]) if (!been[v]) res |= wcc(v); for (int v : rg[u]) if (!been[v]) res |= wcc(v); return res; } int main() { ios::sync_with_stdio(false), cin.tie(0); cin >> n >> m; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; g[a].push_back(b); rg[b].push_back(a); } for (int i = 1; i <= n; i++) if (!been[i]) topol_sort(i); reverse(topol.begin(), topol.end()); fill(been, been + n + 3, false); for (int v : topol) if (!been[v]) scc(v, false); fill(been, been + n + 3, false); int DAGCOMP = 0, CYCLE = 0; for (int v : topol) if (!been[v]) { if (wcc(v)) CYCLE++; DAGCOMP++; } ans += n - DAGCOMP; ans += CYCLE; cout << ans; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Main main = new Main(); main.read(); } /* IO */ private StringBuilder ans; private BufferedReader in; private StringTokenizer tok; /* fields */ private int nNodes; private Node[] nodes; private int nEdges; private boolean[] found; private int[] visited; private int currDfs; private boolean containsCycle; private ArrayList<Node> currComponent; private int currTag; private void read() throws IOException { // streams boolean file = false; if (file) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); ans = new StringBuilder(); // make nodes tok = new StringTokenizer(in.readLine()); nNodes = Integer.parseInt(tok.nextToken()); nodes = new Node[nNodes + 1]; found = new boolean[nNodes + 1]; for (int i = 0; i <= nNodes; i++) nodes[i] = new Node(i); // make edges nEdges = Integer.parseInt(tok.nextToken()); for (int i = 0; i < nEdges; i++) { tok = new StringTokenizer(in.readLine()); int s = Integer.parseInt(tok.nextToken()); int t = Integer.parseInt(tok.nextToken()); found[s] = true; found[t] = true; nodes[s].next.add(nodes[t]); nodes[t].prev.add(nodes[s]); } // answer System.out.println(solve()); } private int solve() { // put the nodes to groups ArrayList<ArrayList<Node>> components = new ArrayList<>(); visited = new int[nNodes + 1]; currTag = 1; for (int i = 0; i <= nNodes; i++) if (found[i]) if (visited[i] == 0) { currComponent = new ArrayList<Node>(); visited[i] = 1; dfsBoth(nodes[i]); components.add(currComponent); } // solve each group int answer = 0; for (ArrayList<Node> component : components) { // get scc currDfs = 1; currTag++; for (Node node :component) if (visited[node.id] != currTag) { visited[node.id] = currTag; dfsRev(node); } // dfs on scc to check cycles Collections.sort(component, new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { return Integer.compare(o2.rank, o1.rank); } }); currTag++; containsCycle = false; for (Node node :component) if (visited[node.id] != currTag) { visited[node.id] = currTag; dfs(node); } // add to answer if (containsCycle) answer += component.size(); else answer += component.size() - 1; } return answer; } private void dfsBoth(Node node) { currComponent.add(node); for (Node next : node.next) if (visited[next.id] != currTag) { visited[next.id] = currTag; dfsBoth(next); } for (Node prev : node.prev) if (visited[prev.id] != currTag) { visited[prev.id] = currTag; dfsBoth(prev); } } private void dfs(Node node) { for (Node next : node.next) if (visited[next.id] != currTag) { containsCycle = true; visited[next.id] = currTag; dfs(next); } } private void dfsRev(Node node) { for (Node prev : node.prev) if (visited[prev.id] != currTag) { visited[prev.id] = currTag; dfsRev(prev); } node.rank = currDfs++; } } class Node { int id; LinkedList<Node> next; LinkedList<Node> prev; int rank; public Node(int id) { this.id = id; this.next = new LinkedList<>(); this.prev = new LinkedList<>(); this.rank = -1; } public String toString() { return id + ""; } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; vector<long long> graph[100005], dg[100005]; long long vis[100005]; long long vis2[100005]; stack<long long> st; long long cycle; void dfs(long long src) { vis[src] = 1; for (long long i = 0; i < graph[src].size(); i++) { long long v = graph[src][i]; if (!vis[v]) dfs(v); } st.push(src); } void dfs2(long long src) { vis2[src] = 1; for (long long i = 0; i < dg[src].size(); i++) { long long v = dg[src][i]; if (vis2[v] == 0) { dfs2(v); } else if (vis2[v] == 1) { cycle = 0; } } vis2[src] = -1; } int main() { long long n, m; scanf("%lld", &n); scanf("%lld", &m); for (long long i = 1; i <= m; i++) { long long u, v; scanf("%lld", &u); scanf("%lld", &v); graph[u].push_back(v); graph[v].push_back(u); dg[u].push_back(v); } long long ans = 0; for (long long i = 1; i <= n; i++) { if (!vis[i]) { while (!st.empty()) st.pop(); dfs(i); long long sz = st.size(); cycle = 1; while (!st.empty()) { long long adj = st.top(); st.pop(); if (vis2[adj] == 0) { dfs2(adj); } } ans += (sz - cycle); } } printf("%lld\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; #pragma comment(linker, "/STACK:26777216") const int mod = 2e9 + 7; const double eps = 1e-8; const int N = 803; const double pi = acos(-1.0); const long long inf = 1ll << 50; int gcd(int a, int b) { return !b ? a : gcd(b, a % b); } struct union_set { int fa[103]; void init(int n) { for (int i = 0; i <= n; i++) fa[i] = i; return; } int getroot(int i) { if (fa[i] != i) fa[i] = getroot(fa[i]); return fa[i]; } void _union(int i, int j) { fa[i] = j; } }; int pow_mod(int a, int b, int c) { long long ans = 1; while (b) { if (b & 1) ans = ans * a % c; a = 1ll * a * a % c; b >>= 1; } return ans % c; } const int MN = 100003; vector<int> edge[MN]; vector<int> SCC[MN]; stack<int> s; int low[MN], dfn[MN]; int instack[MN], stap[MN]; int belong[MN]; int num[MN]; int ind[MN]; int tp, p; int bcnt; void tarjan(int x) { low[x] = dfn[x] = ++tp; stap[++p] = x; instack[x] = 1; for (int i = 0; i < edge[x].size(); i++) { int v = edge[x][i]; if (dfn[v] == -1) { tarjan(v); if (low[x] > low[v]) low[x] = low[v]; } else if (instack[v] && dfn[v] < low[x]) low[x] = dfn[v]; } if (low[x] == dfn[x]) { int top; do { top = stap[p]; belong[top] = bcnt; instack[top] = 0; p--; } while (x != top); bcnt++; } } int hsize[MN] = {0}; int have[MN]; int rhave[MN]; int id[MN], top = 1; void dfs(int u, int l) { if (id[u] == l) return; id[u] = l; have[l]++; rhave[l] += hsize[u]; for (int v = 0; v < SCC[u].size(); v++) dfs(SCC[u][v], l); return; } int main() { int n, m, i, a, b, j; bcnt = tp = p = 0; scanf("%d%d", &n, &m); memset(dfn, -1, sizeof(dfn)); memset(low, 0, sizeof(low)); memset(instack, 0, sizeof(instack)); memset(belong, 0, sizeof(belong)); memset(ind, 0, sizeof(ind)); for (i = 1; i <= n; i++) { edge[i].clear(); SCC[i].clear(); } for (i = 0; i < m; i++) { scanf("%d%d", &a, &b); edge[a].push_back(b); } for (i = 1; i <= n; i++) { if (dfn[i] == -1) tarjan(i); } for (i = 1; i <= n; i++) { hsize[belong[i]]++; for (j = 0; j < edge[i].size(); j++) { int x = belong[i]; int y = belong[edge[i][j]]; if (x != y) { SCC[x].push_back(y); SCC[y].push_back(x); } } } for (int i = 0; i < bcnt; i++) if (id[i] == 0) dfs(i, top++); int ans = 0; for (int i = 1; i <= bcnt; i++) if (have[i]) ans += (have[i] == rhave[i]) ? rhave[i] - 1 : rhave[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 = 100000 + 10; const int maxm = 100000 + 10; struct edge { int x, y, next; }; edge gr[maxm], gd[maxm]; int tot, n, m, fir[maxn], fid[maxn]; int L[maxn], col[maxn], totcol; int fa[maxn], sumc[maxn]; bool mark[maxn]; void dfs_d(int u) { mark[u] = true; for (int t = fir[u]; t > 0; t = gr[t].next) if (!mark[gr[t].y]) { dfs_d(gr[t].y); } L[++L[0]] = u; } void dfs_c(int u, int c) { col[u] = c; for (int t = fid[u]; t > 0; t = gd[t].next) if (col[gd[t].y] == 0) { dfs_c(gd[t].y, c); } } void add(int x, int y) { ++tot; gr[tot].x = x, gr[tot].y = y, gr[tot].next = fir[x]; gd[tot].x = y, gd[tot].y = x, gd[tot].next = fid[y]; fir[x] = tot; fid[y] = tot; } int find(int u) { if (fa[u] == u) return u; fa[u] = find(fa[u]); return fa[u]; } int main() { int x, y; while (scanf("%d%d", &n, &m) != EOF) { memset(fir, 0, sizeof(fir)); memset(fid, 0, sizeof(fid)); tot = 0; for (int i = 1; i <= n; i++) fa[i] = i; for (int i = 0; i != m; i++) { scanf("%d%d", &x, &y); add(x, y); if (find(x) != find(y)) { fa[fa[x]] = fa[y]; } } memset(mark, 0, sizeof(mark)); L[0] = 0; for (int i = 1; i <= n; i++) { if (!mark[i]) dfs_d(i); } memset(col, 0, sizeof(col)); totcol = 0; for (int i = n; i >= 1; i--) { if (col[L[i]] == 0) { dfs_c(L[i], ++totcol); } } memset(sumc, 0, sizeof(sumc)); for (int i = 1; i <= n; i++) ++sumc[col[i]]; int ans = n; memset(mark, 0, sizeof(mark)); for (int i = 1; i <= n; i++) { if (sumc[col[i]] > 1) mark[find(i)] = true; } for (int i = 1; i <= n; i++) { if (find(i) == i) ans = ans - 1 + mark[i]; } printf("%d\n", ans); } return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int N, M; vector<int> V2[101101]; vector<int> V[101101]; vector<int> VV[101101]; int Gp = 0; vector<int> G[101101]; bool Check[101101]; void Make_Group(int now) { Check[now] = true; G[Gp].push_back(now); for (int i = 0; i < V2[now].size(); i++) { int next = V2[now][i]; if (Check[next] == true) continue; Make_Group(next); } } bool Check2[101101]; int Clock[101101], CC; void F_DFS(int now) { Check2[now] = true; for (int i = 0; i < V[now].size(); i++) { int next = V[now][i]; if (Check2[next] == true) continue; F_DFS(next); } Clock[++CC] = now; } bool Check3[101101]; int S_DFS(int now) { int result = 1; Check3[now] = true; for (int i = 0; i < VV[now].size(); i++) { int next = VV[now][i]; if (Check3[next] == true) continue; result += S_DFS(next); } return result; } bool Have_Cy(int nowg) { CC = 0; for (int i = 0; i < G[nowg].size(); i++) { int now = G[nowg][i]; if (Check2[now] == true) continue; F_DFS(now); } for (int i = CC; i >= 1; i--) { int now = Clock[i]; if (Check3[now] == true) continue; if (S_DFS(now) >= 2) return true; } return false; } int main() { scanf("%d%d", &N, &M); for (int i = 1; i <= M; i++) { int x, y; scanf("%d%d", &x, &y); V[x].push_back(y); V2[x].push_back(y); V2[y].push_back(x); VV[y].push_back(x); } for (int i = 1; i <= N; i++) { if (Check[i] == false) { ++Gp; Make_Group(i); } } int Ans = 0; for (int i = 1; i <= Gp; i++) { Ans += G[i].size(); Ans -= 1; if (Have_Cy(i)) Ans += 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
//package round286; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.BitSet; import java.util.InputMismatchException; import java.util.Queue; public class B { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] from = new int[m]; int[] to = new int[m]; for(int i = 0;i < m;i++){ from[i] = ni()-1; to[i] = ni()-1; } int[][] g = packD(n, from, to); int[][] ig = packD(n, to, from); int[] clus = decomposeToSCC(g, ig); int[] fc = new int[n]; for(int i = 0;i < n;i++)fc[clus[i]]++; int mc = -1; for(int v : clus)mc = Math.max(mc, v); mc++; DJSet ds = new DJSet(mc); for(int i = 0;i < m;i++){ ds.union(clus[from[i]], clus[to[i]]); } boolean[] cy = new boolean[n]; for(int i = 0;i < n;i++){ if(fc[i] > 1){ cy[ds.root(i)] = true; } } int count = n; for(int i = 0;i < mc;i++){ if(ds.upper[i] < 0){ if(!cy[i])count--; } } out.println(count); } public static class DJSet { public int[] upper; public DJSet(int n) { upper = new int[n]; Arrays.fill(upper, -1); } public int root(int x) { return upper[x] < 0 ? x : (upper[x] = root(upper[x])); } public boolean equiv(int x, int y) { return root(x) == root(y); } public boolean union(int x, int y) { x = root(x); y = root(y); if (x != y) { if (upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x; } return x == y; } public int count() { int ct = 0; for (int u : upper) if (u < 0) ct++; return ct; } } public static int[] decomposeToSCC(int[][] g, int[][] ig) { int n = g.length; BitSet visited = new BitSet(); int[] po = new int[n]; int pop = 0; for (int i = visited.nextClearBit(0); i < n; i = visited .nextClearBit(i + 1)) { pop = dfsPostOrder(i, g, visited, po, pop); } int[] ret = new int[n]; visited.clear(); int clus = 0; for (int i = n - 1; i >= 0; i--) { if (!visited.get(po[i])) { Queue<Integer> q = new ArrayDeque<Integer>(); q.add(po[i]); visited.set(po[i]); while (!q.isEmpty()) { int cur = q.poll(); ret[cur] = clus; for (int k : ig[cur]) { if (!visited.get(k)) { q.add(k); visited.set(k); } } } clus++; } } return ret; } public static int dfsPostOrder(int cur, int[][] g, BitSet visited, int[] po, int pop) { visited.set(cur); for (int i : g[cur]) { if (!visited.get(i)) { pop = dfsPostOrder(i, g, visited, po, pop); } } po[pop++] = cur; return pop; } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; } return g; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.io.*; import java.util.*; public class CFB { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; // StrongConnectedComponents: int n; int m; List<List<Integer>> graph = new ArrayList<>(); List<List<Integer>> revGraph = new ArrayList<>(); int[] from; int[] to; void solve() throws IOException { n = nextInt(); m = nextInt(); from = new int[m]; to = new int[m]; for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); revGraph.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { //an edge from u to v int u = nextInt() - 1; int v = nextInt() - 1; from[i] = u; to[i] = v; graph.get(u).add(v); revGraph.get(v).add(u); } List<List<Integer>> comps = connectedComp(); int sz = comps.size(); int[] toId = new int[n]; for (int i = 0; i < sz; i++) { for (int v : comps.get(i)) { toId[v] = i; } } List<List<Integer>> conn = new ArrayList<>(); for (int i = 0; i < sz; i++) { conn.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = from[i]; int v = to[i]; int id1 = toId[u]; int id2 = toId[v]; if (id1 == id2) { continue; } conn.get(id1).add(id2); conn.get(id2).add(id1); } boolean[] vis = new boolean[sz]; int res = 0; for (int i = 0; i < sz; i++) { if (vis[i]) { continue; } List<Integer> ls = new ArrayList<>(); dfs(i, vis, conn, ls); int total = 0; for (int v : ls) { total += comps.get(v).size(); } if (total > ls.size()) { res += total; } else { res += ls.size() - 1; } } outln(res); } void dfs(int cur, boolean[] vis, List<List<Integer>> conn, List<Integer> ls) { if (vis[cur]) { return; } vis[cur] = true; ls.add(cur); for (int nxt : conn.get(cur)) { dfs(nxt, vis, conn, ls); } } List<List<Integer>> connectedComp(){ Stack<Integer> st = new Stack<>(); boolean[] visited = new boolean[n]; for (int i = 0; i < n; i++) { if (!visited[i]) { helper(st, graph, visited, i); } } Arrays.fill(visited, false); List<List<Integer>> res = new ArrayList<>(); while(!st.isEmpty()) { int v = st.pop(); if(!visited[v]) { Stack<Integer> temp = new Stack<>(); List<Integer> ls = new ArrayList<>(); temp.push(v); ls.add(v); visited[v] = true; while(!temp.isEmpty()){ int u = temp.pop(); for (int nxt : revGraph.get(u)) { if (!visited[nxt]) { visited[nxt] = true; temp.push(nxt); ls.add(nxt); } } } res.add(ls); } } return res; } void helper(Stack<Integer> st, List<List<Integer>> graph, boolean[] visited, int cur){ if(!visited[cur]) { visited[cur] = true; for (int nxt : graph.get(cur)) { helper(st, graph, visited, nxt); } st.push(cur); } } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFB() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFB(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int MAXN = 100001; int n; vector<int> g[MAXN]; int dfn[MAXN]; int low[MAXN]; int vis[MAXN]; int ins[MAXN]; int ind = 1; stack<int> st; int cyc[MAXN]; int ans1 = 0, ans2 = 0; void dfs(int u) { dfn[u] = low[u] = ind++; st.push(u); ins[u] = vis[u] = 1; for (auto v : g[u]) { if (!vis[v]) { dfs(v); low[u] = min(low[u], low[v]); } else if (ins[v]) { low[u] = min(low[u], dfn[v]); } } if (dfn[u] == low[u]) { int t = 0; int v; do { v = st.top(); st.pop(); t++; ins[v] = 0; } while (u != v); if (t > 1) cyc[u] = 1; } } void get_scc() { for (int i = 1; i <= n; i++) { if (!vis[i]) { dfs(i); } } } int p[MAXN]; int cnt[MAXN]; void init() { for (int i = 1; i <= n; i++) { cnt[i] = 1; p[i] = i; } } int query(int x) { return p[x] == x ? x : p[x] = query(p[x]); } void merge(int x, int y) { x = query(x); y = query(y); if (x == y) { return; } p[x] = y; cyc[y] |= cyc[x]; cnt[y] += cnt[x]; } int main() { int m; scanf("%d%d", &n, &m); while (m--) { int u, v; scanf("%d%d", &u, &v); g[u].push_back(v); } init(); get_scc(); for (int u = 1; u <= n; u++) { for (auto v : g[u]) { merge(u, v); } } int ans = 0; for (int u = 1; u <= n; u++) if (p[u] == u) { ans += cnt[u] - 1 + cyc[u]; } 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> void pr(const string& name, T t) { cerr << name << ": " << t << endl; } template <typename T, typename... Types> void pr(const string& names, T t, Types... rest) { auto comma_pos = names.find(','); cerr << names.substr(0, comma_pos) << ": " << t << ", "; auto next_name_pos = names.find_first_not_of(" \t\n", comma_pos + 1); pr(string(names, next_name_pos), rest...); } template <class T, class U> ostream& operator<<(ostream& o, const pair<T, U>& v) { return o << "(" << v.first << ", " << v.second << ")"; } template <class T> ostream& operator<<(ostream& o, const vector<T>& v) { o << "{"; for (int i = 0; i < (int)((int)((v).size())); ++i) o << (i ? ", " : "") << v[i]; return o << "}"; } const int dx[] = {0, 1, 0, -1}; const int dy[] = {-1, 0, 1, 0}; const int MAX_N = 2e5 + 10; vector<int> G[MAX_N]; vector<int> rG[MAX_N]; int cmp[MAX_N]; bool vis[MAX_N]; int V; vector<int> vs; void dfs(int v) { vis[v] = true; for (auto e : G[v]) if (!vis[e]) dfs(e); vs.push_back(v); } void rdfs(int v, int k) { vis[v] = true; cmp[v] = k; for (auto e : rG[v]) if (!vis[e]) rdfs(e, k); } int scc() { vs.clear(); memset(vis, 0, sizeof(vis)); for (int i = 0; i < (int)(V); ++i) if (!vis[i]) dfs(i); memset(vis, 0, sizeof(vis)); int k = 0; reverse((vs).begin(), (vs).end()); for (auto e : vs) if (!vis[e]) rdfs(e, k++); return k; } int un[MAX_N]; int find(int x) { if (un[x] == x) return x; return un[x] = find(un[x]); } void unit(int a, int b) { un[find(a)] = find(b); } int main(int argc, char* argv[]) { ios::sync_with_stdio(0); cin.tie(0); memset(un, -1, sizeof(un)); int n, m; cin >> n >> m; for (int i = 0; i < (int)(n); ++i) un[i] = i; for (int i = 0; i < (int)(m); ++i) { int a, b; cin >> a >> b; --a, --b; G[a].push_back(b); rG[b].push_back(a); unit(a, b); } V = n; scc(); map<int, set<int> > app; for (int i = 0; i < (int)(n); ++i) app[find(i)].insert(i); int ans = 0; for (auto& e : app) { if ((int)((e.second).size()) == 1) continue; set<int> cnum; for (auto v : e.second) cnum.insert(cmp[v]); if ((int)((cnum).size()) != (int)((e.second).size())) ans += (int)((e.second).size()); else ans += (int)((e.second).size()) - 1; } cout << ans << '\n'; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int head[100005], dfn[100005], low[100005], z[100005], fa[100005], size[100005], si[100005], belong[100005], num[100005]; struct ff { int to, nxt; } e[100005]; bool vis[100005], init[100005], pd; int i, u, v, n, m, fx, fy, ans, cnt, Time, top, tmp; void add(int u, int v) { e[++cnt] = (ff){v, head[u]}; head[u] = cnt; } void Tarjan(int now) { dfn[now] = low[now] = ++Time; z[++top] = now; int k = top; vis[now] = init[now] = 1; for (int i = head[now]; i; i = e[i].nxt) { int v = e[i].to; if (!vis[v]) { Tarjan(v); low[now] = min(low[now], low[v]); } else if (init[v]) low[now] = min(low[now], dfn[v]); } if (dfn[now] == low[now]) { size[++tmp] = top - k + 1; for (int i = k; i <= top; i++) init[z[i]] = 0, belong[z[i]] = tmp; top = k - 1; } } int get(int x) { return x == fa[x] ? x : fa[x] = get(fa[x]); } int main() { scanf("%d%d", &n, &m); for (i = 1; i <= n; i++) fa[i] = i, si[i] = 1; for (i = 1; i <= m; i++) { scanf("%d%d", &u, &v); add(u, v); fx = get(u), fy = get(v); if (fx != fy) fa[fx] = fy, si[fy] += si[fx]; } for (i = 1; i <= n; i++) if (!vis[i]) Tarjan(i); for (i = 1; i <= n; i++) num[get(i)] = 1; for (i = 1; i <= n; i++) if (size[belong[i]] > 1) num[get(i)] = 0; for (i = 1; i <= n; i++) if (get(i) == i) ans += si[i] - num[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 long long N = 1e5 + 10, MOD = 1e9 + 7; vector<vector<int> > E, F; vector<int> D; vector<bool> V; int dfs(int u) { if (V[u]) return 0; V[u] = 1; int r = 1; for (int v : E[u]) r += dfs(v); for (int v : F[u]) r += dfs(v); return r; } int main() { int n, m; cin >> n >> m; E = vector<vector<int> >(n); F = vector<vector<int> >(n); V = vector<bool>(n); D = vector<int>(n); for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; E[u - 1].push_back(v - 1); F[v - 1].push_back(u - 1); D[v - 1]++; } vector<int> Q; for (int i = 0; i < n; i++) if (D[i] == 0) Q.push_back(i); for (int q = 0; q < Q.size(); q++) for (int v : E[Q[q]]) if (!--D[v]) Q.push_back(v); int ans = 0; for (int i = 0; i < n; i++) if (D[i]) ans += dfs(i); for (int i = 0; i < n; i++) if (!D[i]) ans += max(0, dfs(i) - 1); cout << ans << '\n'; cin >> n; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int N = 100007; int in[N], n, m, st[N], p, visit[N], loop[N], num[N], u[N], v[N]; vector<int> child[N]; int Arr[N], sizee[N]; void initialize_dsu(int a, int b) { for (int i = a; i <= b; ++i) Arr[i] = i, sizee[i] = 1; } int root(int a) { if (a == Arr[a]) return a; return Arr[a] = root(Arr[a]); } bool find(int a, int b) { return (root(a) == root(b)); } void union_set(int a, int b) { int u = root(a), v = root(b); if (find(u, v)) return; if (sizee[u] < sizee[v]) swap(u, v); Arr[v] = Arr[u], sizee[u] += sizee[v]; } void dfs(int u) { visit[u] = 1; for (int v : child[u]) { if (visit[v]) continue; dfs(v); } st[++p] = u; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; initialize_dsu(1, n); for (int i = 1; i <= m; ++i) { cin >> u[i] >> v[i]; child[u[i]].push_back(v[i]); in[v[i]] = 1; union_set(u[i], v[i]); } int ans = 0; for (int i = 1; i <= n; ++i) if (in[i] == 0) dfs(i); for (int i = 1; i <= n; ++i) if (visit[i] == 0) dfs(i); reverse(st + 1, st + n + 1); for (int i = 1; i <= n; ++i) num[st[i]] = i; for (int i = 1; i <= m; ++i) if (num[u[i]] > num[v[i]]) { if (loop[root(u[i])]) continue; loop[root(u[i])] = 1, ++ans; } set<int> s; for (int i = 1; i <= n; ++i) s.insert(root(st[i])); for (auto k : s) ans += sizee[k] - 1; cout << ans << endl; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const double EPS = 0.000000001; const double PI = 3.141592653589793; const long long LLINF = 99999999999999999LL; const int MAX_N = 100005; const int MOD = 1000000007; int N, M, n, cnt, ans; vector<int> v[MAX_N], w[MAX_N], SCC[MAX_N], a; bool cycle; bool hasCycle[MAX_N], vis[MAX_N]; void DFS1(int x) { vis[x] = 1; for (int i = 0; i < (int)v[x].size(); ++i) { int y = v[x][i]; if (vis[y] == 0) DFS1(y); } a.push_back(x); } void DFS2(int x) { vis[x] = 1; SCC[n].push_back(x); for (int i = 0; i < (int)w[x].size(); ++i) { int y = w[x][i]; if (vis[y] == 0) DFS2(y); } } void DFS(int x) { ++cnt; vis[x] = 1; if (hasCycle[x]) cycle = 1; for (int i = 0; i < (int)v[x].size(); ++i) { int y = v[x][i]; if (vis[y] == 0) DFS(y); } for (int i = 0; i < (int)w[x].size(); ++i) { int y = w[x][i]; if (vis[y] == 0) DFS(y); } } int main() { cin >> N >> M; for (int i = 1; i <= M; ++i) { int x, y; cin >> x >> y; v[x].push_back(y); w[y].push_back(x); } for (int i = 1; i <= N; ++i) if (!vis[i]) DFS1(i); memset(vis, 0, sizeof(vis)); for (int i = a.size() - 1; i >= 0; --i) if (!vis[a[i]]) { ++n; DFS2(a[i]); } for (int i = 1; i <= n; ++i) if (SCC[i].size() > 1) for (int j = 0; j < (int)SCC[i].size(); ++j) hasCycle[SCC[i][j]] = 1; memset(vis, 0, sizeof(vis)); for (int i = 1; i <= N; ++i) { if (vis[i]) continue; cnt = 0; cycle = 0; DFS(i); if (cycle) ans += cnt; else ans += cnt - 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; int Set(int N, int pos) { return N = N | (1 << pos); } int reset(int N, int pos) { return N = N & ~(1 << pos); } bool check(int N, int pos) { return (bool)(N & (1 << pos)); } inline int addmod(int x, int y) { return (x % 1000000007 + y % 1000000007) % 1000000007; } inline int submod(int x, int y) { return (x % 1000000007 - y % 1000000007 + 1000000007) % 1000000007; } inline int mulmod(int x, int y) { return (x % 1000000007 * 1LL * y % 1000000007) % 1000000007; } inline int nextSubMask(int i, int mask) { return (i - 1) & mask; } template <typename T> void we_r_done(T mssg) { cout << mssg; exit(0); } const int N = 1e5 + 5; vector<int> v[N], comp[N]; int n, m, parent[N], color[N]; int Find(int x) { if (x == parent[x]) return x; return parent[x] = Find(parent[x]); } bool cycle; void dfs(int x) { color[x] = 1; for (int u : v[x]) { if (color[u] == 1) { cycle = true; return; } if (color[u] == 0) dfs(u); } color[x] = 2; } int main() { while (scanf("%d%d", &n, &m) == 2) { for (int i = 1; i <= n; i++) { v[i].clear(); parent[i] = i; comp[i].clear(); color[i] = 0; } vector<int> son(n + 2, 0); for (int i = 1; i <= m; i++) { int a, b; scanf("%d%d", &a, &b); v[a].push_back(b); if (Find(a) != Find(b)) { parent[parent[a]] = parent[b]; } } set<int> dads; for (int i = 1; i <= n; i++) { int p = Find(i); comp[p].push_back(i); dads.insert(p); } int ans = 0; for (auto d : dads) { if (comp[d].size() < 2) continue; cycle = false; for (int u : comp[d]) { if (color[u] == 0) dfs(u); } ans += comp[d].size(); if (cycle == false) ans--; } cout << min(ans, min(n, m)) << 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 static java.lang.Math.*; import static java.lang.Integer.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; public class round286B { static int n; static ArrayList <Integer> [] graph; static ArrayList<Integer> [] graph2; static ArrayList<ArrayList<Integer>> comps = new ArrayList<ArrayList<Integer>>(); static int idx = -1; static boolean cycle = false; static boolean [] vis; static boolean [] vis2; static boolean [] inStack; public static int dfs(int cur){ inStack[cur] = true; vis[cur] = true; int ans = 1; for(int nxt : graph[cur]){ if(inStack[nxt]) cycle = true; if(!vis[nxt] && !inStack[nxt]) ans += dfs(nxt); } inStack[cur] = false; return ans; } public static void dfs2(int cur){ vis2[cur] = true; if(comps.size() < idx + 1){ ArrayList<Integer> x = new ArrayList<Integer>(); x.add(cur); comps.add(x); }else{ ArrayList<Integer> x = comps.get(idx); x.add(cur); } for(int nxt : graph2[cur]){ if(!vis2[nxt]) dfs2(nxt); } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String [] use = br.readLine().split(" "); n = parseInt(use[0]); int m = parseInt(use[1]); graph = new ArrayList [n + 1]; graph2 = new ArrayList [n + 1]; for(int i = 0 ; i < n + 1 ; ++i) graph[i] = new ArrayList<Integer>(); for(int i = 0 ; i < n + 1 ; ++i) graph2[i] = new ArrayList<Integer>(); for(int i = 0 ; i < m ; ++i){ use = br.readLine().split(" "); int a = parseInt(use[0]); int b = parseInt(use[1]); graph[a].add(b); graph2[a].add(b); graph2[b].add(a); } vis = new boolean [n + 1]; vis2 = new boolean [n + 1]; for(int i = 1 ; i <= n ; ++i){ if(!vis2[i]){ ++idx; dfs2(i); } } int ans = 0; inStack = new boolean [n + 1]; for(int i = 0 ; i < comps.size() ; ++i){ cycle = false; for(int x : comps.get(i)){ if(!vis[x]){ dfs(x); } } ans += comps.get(i).size(); if(!cycle) ans--; } System.out.println(ans); } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> G[100005]; int low[100005], num[100005], _time; bool del[100005]; stack<int> st; int tplt_cnt, tplt_size[100005], tplt_type[100005]; int ans; vector<int> Gvh[100005]; int vo_huong_cnt, vo_huong_type[100005], vo_huong_size[100005]; bool visited[100005]; void dfs_vo_huong(int u) { if (visited[u]) return; visited[u] = 1; vo_huong_type[u] = vo_huong_cnt; vo_huong_size[vo_huong_cnt]++; for (int i = 0; i < Gvh[u].size(); i++) { int v = Gvh[u][i]; dfs_vo_huong(v); } } bool used_tplt[100005]; bool check[100005]; void dfs(int u) { low[u] = num[u] = ++_time; st.push(u); for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if (!num[v]) dfs(v), low[u] = min(low[u], low[v]); else if (!del[v]) low[u] = min(low[u], num[v]); } if (num[u] == low[u]) { ++tplt_cnt; int x; do { x = st.top(); tplt_size[tplt_cnt]++; tplt_type[x] = tplt_cnt; del[x] = 1; st.pop(); } while (x != u); } } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= m; i++) { int x, y; scanf("%d %d", &x, &y); G[x].push_back(y); Gvh[x].push_back(y); Gvh[y].push_back(x); } for (int i = 1; i <= n; i++) if (!visited[i] && Gvh[i].size()) { vo_huong_cnt++; dfs_vo_huong(i); } for (int i = 1; i <= n; i++) if (!num[i] && G[i].size()) dfs(i); for (int i = 1; i <= n; i++) { if (!used_tplt[tplt_type[i]] && G[i].size()) { used_tplt[tplt_type[i]] = 1; if (tplt_size[tplt_type[i]] >= 2) check[vo_huong_type[i]] = 1; } } for (int i = 1; i <= vo_huong_cnt; i++) ans += vo_huong_size[i] - (1 - check[i]); 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 <typename T, typename S> inline bool REMIN(T& a, const S& b) { return a > b ? a = b, 1 : 0; } template <typename T, typename S> inline bool REMAX(T& a, const S& b) { return a < b ? a = b, 1 : 0; } int bit(long long x, int pos) { return (x >> pos) & 1; } long long power(long long base, long long exp, long long c = 1e9 + 7) { if (!exp) return 1; long long r = power(base, exp >> 1, c); r = (r * r) % c; if (exp & 1) r = (r * base) % c; return r; } long long T, N, M, K; int a, b, c; string s1, s2; const long double PI = 2 * acos(0); const long long INF = 1e9 + 4; const int NMAX = 1e5 + 5; const long long MOD = 1000000007; int vis[NMAX]; int yay[NMAX]; vector<int> eds[NMAX]; vector<int> act[NMAX]; map<pair<int, int>, int> exi; vector<int> chek; void roam(int x) { if (vis[x]) return; vis[x] = 1; chek.emplace_back(x); for (int v : eds[x]) roam(v); } int low[NMAX], disc[NMAX], ver[NMAX]; bool dfs(int x) { low[x] = 1; for (int v : act[x]) { if (low[v]) { if (low[v] == 1) return 1; } else { if (dfs(v)) return 1; } } low[x] = 2; return 0; } int inc[NMAX]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> N >> M; for (int(i) = int(1); (i) <= int(M); ++(i)) { cin >> a >> b; if (!exi[{a, b}]) { eds[a].emplace_back(b); eds[b].emplace_back(a); exi[{a, b}] = 1; } act[a].emplace_back(b); inc[b]++; } long long ans = 0; for (int(i) = int(1); (i) <= int(N); ++(i)) { if (!vis[i]) { chek.clear(); roam(i); int tot = 0, root = 0; for (int x : chek) if (!inc[x]) root = x; if (!root) { ans += ((int)(chek.size())); } else { int flag = 0; for (int gofor : chek) if (!disc[gofor]) { if (dfs(gofor)) { flag = 1; } } if (flag) ans += ((int)(chek.size())); else ans += ((int)(chek.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; vector<int> graph[100001], rev_graph[100001]; vector<int> order; int visited[100001], comp[100001], comp_size[100001], n, m, a, b, no_of_comp = 0, res; void dfs(int v) { visited[v] = 1; for (int i = 0; i < graph[v].size(); i++) { if (visited[graph[v][i]] != 1) dfs(graph[v][i]); } order.push_back(v); } void rev_dfs(int v, int k) { visited[v] = 1; comp[v] = k; for (int i = 0; i < rev_graph[v].size(); i++) { if (visited[rev_graph[v][i]] != 1) rev_dfs(rev_graph[v][i], k); } return; } void strongy_connected_components() { for (int i = 1; i <= n; i++) { if (visited[i] != 1) dfs(i); } for (int i = 1; i <= n; i++) visited[i] = 0; for (int i = order.size() - 1; i >= 0; i--) { if (visited[order[i]] != 1) rev_dfs(order[i], no_of_comp++); } return; } int solve(int v) { visited[v] = 1; int ret = (comp_size[comp[v]] == 1); for (int i = 0; i < graph[v].size(); i++) { if (visited[graph[v][i]] != 1) ret &= solve(graph[v][i]); } for (int i = 0; i < rev_graph[v].size(); i++) { if (visited[rev_graph[v][i]] != 1) ret &= solve(rev_graph[v][i]); } return ret; } int main() { scanf("%d%d", &n, &m); ; for (int i = 0; i < m; i++) { scanf("%d%d", &a, &b); ; graph[a].push_back(b); rev_graph[b].push_back(a); } strongy_connected_components(); for (int i = 1; i <= n; i++) { comp_size[comp[i]]++; } for (int i = 1; i <= n; i++) visited[i] = 0; res = n; for (int i = 1; i <= n; i++) { if (visited[i] != 1) res -= solve(i); } printf("%d\n", res); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int n, m, x, y; bool circle = true; int vis[100010], vis2[100010]; vector<int> neg[100010], adj[100010]; vector<int> dot; void ndfs(int start) { dot.push_back(start); vis[start] = 1; for (int i = 0; i <= int(neg[start].size()) - 1; i++) { if (!vis[neg[start][i]]) ndfs(neg[start][i]); } return; } void adfs(int start) { vis2[start] = 1; for (int i = 0; i <= int(adj[start].size()) - 1; i++) { if (!vis2[adj[start][i]]) adfs(adj[start][i]); else if (vis2[adj[start][i]] == 1) circle = false; } vis2[start] = 2; return; } int main() { cin >> n >> m; for (int i = 1; i <= m; i++) { cin >> x >> y; neg[x].push_back(y); neg[y].push_back(x); adj[x].push_back(y); } int ans = n; for (int i = 1; i <= n; i++) { circle = 1; if (!vis[i]) { dot.clear(); ndfs(i); for (int i = 0; i <= int(dot.size()) - 1; i++) if (!vis2[dot[i]]) adfs(dot[i]); ans -= circle; } } 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.*; import java.io.*; public class b { static ArrayList<Integer>[] g; public static void main(String[] args) throws IOException { input.init(System.in); int n = input.nextInt(), m = input.nextInt(); g = new ArrayList[n]; for(int i = 0; i<n; i++) g[i] = new ArrayList<Integer>(); for(int i = 0; i<m; i++) { int a = input.nextInt()-1, b = input.nextInt()-1; g[a].add(b); } scc(); //System.out.println(Arrays.toString(id)); HashSet<Integer>[] dag = dag(); int res = 0; int[] sizes = new int[count]; for(int i = 0; i<n; i++) sizes[id[i]]++; //for(int i = 0; i<count; i++) if(sizes[i] > 1) res += sizes[i]; //System.out.println(res); boolean[] vis = new boolean[count]; for(int i = 0; i<count; i++) { if(vis[i]) continue; int size = 0; vis[i] = true; Queue<Integer> q = new LinkedList<Integer>(); q.add(i); boolean flag = false; while(!q.isEmpty()) { int at = q.poll(); if(sizes[at] > 1) flag = true; size+= sizes[at]; for(int e : dag[at]) { if(vis[e]) continue; vis[e] = true; q.add(e); } } //System.out.println(flag+" "+size); res += flag ? size : size - 1; } System.out.println(res); } static HashSet<Integer>[] dag() { HashSet<Integer>[] res = new HashSet[count]; for(int i = 0; i<count; i++) res[i] = new HashSet<Integer>(); for(int i = 0; i<g.length; i++) { for(int x : g[i]) if(id[i] != id[x]) { res[id[i]].add(id[x]); res[id[x]].add(id[i]); } } return res; } static boolean[] marked; static int[] id, low, stk; static int pre, count; static void scc() { id = new int[g.length]; low = new int[g.length]; stk = new int[g.length+1]; pre = count = 0; marked = new boolean[g.length]; for(int i =0; i<g.length; i++) if(!marked[i]) dfs(i); } static void dfs(int i) { marked[stk[++stk[0]]=i] = true; int min = low[i] = pre++; for(int j: g[i]) { if(!marked[j]) dfs(j); if(low[j] < min) min = low[j]; } if(min < low[i]) low[i] = min; else { while(stk[stk[0]] != i) { int j =stk[stk[0]--]; id[j] = count; low[j] = g.length; } id[stk[stk[0]--]] = count++; low[i] = g.length; } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> G[100005]; vector<int> gt[100005]; vector<int> tab; vector<vector<int> > SCC; bool looped[100005]; bool was[100005]; bool in[100005]; void dfs(int v, bool yes, int id) { was[v] = 1; for (int i = 0; i < G[v].size(); i++) if (!was[G[v][i]]) dfs(G[v][i], yes, id); for (int i = 0; i < gt[v].size(); i++) if (!was[gt[v][i]]) dfs(gt[v][i], yes, id); if (!yes) { tab.push_back(v); } else { SCC[id].push_back(v); } } bool dfs2(int v) { was[v] = 1; in[v] = 1; for (int i = 0; i < G[v].size(); i++) if (in[G[v][i]]) return true; else if (!was[G[v][i]]) if (dfs2(G[v][i])) return true; in[v] = 0; return false; } bool use[100005]; int main() { scanf("%d %d", &n, &m); for (int i = 0; i < m; i++) { int a, b; scanf("%d %d", &a, &b); G[a].push_back(b); gt[b].push_back(a); use[a] = use[b] = 1; } for (int i = 1; i <= n; i++) if (!was[i] && use[i]) dfs(i, false, 0); memset(was, 0, sizeof(was)); int idx = 0; for (int i = tab.size() - 1; i >= 0; i--) if (!was[tab[i]]) { SCC.push_back(vector<int>()); dfs(tab[i], true, idx); idx++; } memset(was, 0, sizeof(was)); for (int i = 0; i < SCC.size(); i++) { for (int j = 0; j < SCC[i].size(); j++) if (!was[SCC[i][j]]) if (dfs2(SCC[i][j])) { looped[i] = true; break; } } int result = 0; for (int i = 0; i < SCC.size(); i++) { if (looped[i]) result += SCC[i].size(); else result += SCC[i].size() - 1; } printf("%d\n", result); }
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> vis; vector<vector<int> > adj, adj2; long long ans; int wcc[(long long)3e5 + 100], scc[(long long)3e5 + 100], ssz[(long long)3e5 + 100], dfs_low[(long long)3e5 + 100], dfs_num[(long long)3e5 + 100], wccsz[(long long)3e5 + 100]; int scnum; stack<int> s; void opt() { ios_base::sync_with_stdio(false); cin.tie(NULL); } int cnt = 0; int cnt2 = 0; void dfs(int u) { vis[u] = 1; wcc[u] = cnt; cnt2++; for (int i = 0; i < adj2[u].size(); i++) { int v = adj2[u][i]; if (!vis[v]) dfs(v); } } int ds; void tarjan(int u) { dfs_low[u] = dfs_num[u] = ds++; s.push(u); vis[u] = 1; for (int i = 0; i < adj[u].size(); i++) { int v = adj[u][i]; if (dfs_num[v] == 0) { tarjan(v); } if (vis[v]) dfs_low[u] = min(dfs_low[u], dfs_low[v]); } if (dfs_low[u] == dfs_num[u]) { int sz = 0; while (1) { int v = s.top(); s.pop(); vis[v] = 0; scc[v] = scnum; sz++; if (u == v) break; } ssz[scnum++] = sz; } } bool taken[(long long)3e5 + 100]; int main() { opt(); int m, n; cin >> n >> m; adj.assign(n + 3, vector<int>()); adj2.assign(n + 3, vector<int>()); vis.assign(n + 3, 0); for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; x--, y--; adj[x].push_back(y); if (!binary_search(adj2[x].begin(), adj2[x].end(), y)) adj2[x].push_back(y); if (!binary_search(adj2[y].begin(), adj2[y].end(), x)) adj2[y].push_back(x); } for (int i = 0; i < n; i++) if (!vis[i]) { dfs(i); wccsz[cnt++] = cnt2; cnt2 = 0; } vis.clear(); vis.assign(n + 3, 0); for (int i = 0; i < n; i++) { if (dfs_num[i] == 0) tarjan(i); } int ans = 0; for (int i = 0; i < n; i++) { if (!taken[wcc[i]]) { ans += wccsz[wcc[i]] - 1; taken[wcc[i]] = 1; } } for (int i = 0; i <= n; i++) taken[i] = 0; for (int i = 0; i < n; i++) { if (ssz[scc[i]] > 1 && !taken[wcc[i]]) { ans++; taken[wcc[i]] = 1; } } cout << ans; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int MN = 1e5 + 100; vector<int> v1[MN]; vector<int> v2[MN]; vector<int> group; bool used1[MN]; bool used2[MN]; bool used3[MN]; void findGroup(int x) { used1[x] = 1; group.push_back(x); for (auto y : v1[x]) { if (!used1[y]) { findGroup(y); } } } int findCycle(int x) { used2[x] = 1; used3[x] = 1; for (auto y : v2[x]) { if (used3[y]) return 1; if (!used2[y]) { if (findCycle(y)) return 1; } } used3[x] = 0; return 0; } int main() { int n, m; cin >> n >> m; for (int i = 0; i < m; ++i) { int q, w; cin >> q >> w; --q, --w; v1[q].push_back(w); v1[w].push_back(q); v2[q].push_back(w); } int ans = 0; for (int i = 0; i < n; ++i) { if (!used1[i]) { group.clear(); findGroup(i); if (group.size() == 1) continue; for (int j = 0; j < group.size(); ++j) { if (!used2[group[j]]) { if (findCycle(group[j])) goto lol; } } ans += group.size() - 1; continue; lol:; ans += group.size(); } } cout << ans << '\n'; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; struct node { vector<int> adj; vector<int> bak; int comp; int indeg; }; int n, m; node g[100005]; int cnt[100005]; int currComp = 1; int ret; vector<int> cMembers[100005]; void DFS(int curr) { g[curr].comp = currComp; cnt[currComp]++; cMembers[currComp].push_back(curr); int limit = g[curr].adj.size(); for (int i = 0; i <= limit - 1; i++) { int nxt = g[curr].adj[i]; if (g[nxt].comp == 0) DFS(nxt); } limit = g[curr].bak.size(); for (int i = 0; i <= limit - 1; i++) { int nxt = g[curr].bak[i]; if (g[nxt].comp == 0) DFS(nxt); } } bool toposort(int cmp) { int topit = 1; queue<int> q; for (int i = 0; i <= (int)(cMembers[cmp].size()) - 1; i++) { int curr = cMembers[cmp][i]; if (g[curr].indeg == 0) { q.push(curr); topit++; } } while (!q.empty()) { int curr = q.front(); q.pop(); int limit = g[curr].adj.size(); for (int i = 0; i <= limit - 1; i++) { int nxt = g[curr].adj[i]; g[nxt].indeg--; if (g[nxt].indeg == 0) { topit++; q.push(nxt); } } } if (topit < cnt[cmp] + 1) { return false; } return true; } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= m; i++) { int u, v; scanf("%d %d", &u, &v); g[u].adj.push_back(v); g[v].bak.push_back(u); g[v].indeg++; } for (int i = 1; i <= n; i++) { if (g[i].comp == 0) { DFS(i); currComp++; } } currComp--; for (int i = 1; i <= currComp; i++) { bool top = toposort(i); if (top) ret += cnt[i] - 1; else ret += cnt[i]; } cout << ret << 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 n, m, cnt, head[100100], fa[100100], sccno[100100], lowlink[100100], pre[100100]; int stack[100100], top, scc_cnt, dfs_clock, size[100100], vis[100100], ans; struct data { int to, next; } edge[100100]; inline void Add_Edge(int u, int v) { edge[++cnt] = (data){v, head[u]}; head[u] = cnt; } inline int find(int k) { return fa[k] == k ? k : fa[k] = find(fa[k]); } inline void Tarjan(int u) { pre[u] = lowlink[u] = ++dfs_clock; stack[++top] = u; for (int i = head[u]; i; i = edge[i].next) { int v = edge[i].to; if (!pre[v]) { Tarjan(v); lowlink[u] = (lowlink[u]) < (lowlink[v]) ? (lowlink[u]) : (lowlink[v]); } else if (!sccno[v]) lowlink[u] = (lowlink[u]) < (pre[v]) ? (lowlink[u]) : (pre[v]); } if (lowlink[u] == pre[u]) for (scc_cnt++;;) { int x = stack[top--]; sccno[x] = scc_cnt; size[scc_cnt]++; if (x == u) break; } } inline void ReBuild() { for (int u = 1; u <= n; u++) { for (int i = head[u]; i; i = edge[i].next) { int fx = find(sccno[u]), fy = find(sccno[edge[i].to]); if (fx != fy) { fa[fy] = fx; size[fx] += size[fy]; vis[fx] |= vis[fy]; } } } } int main() { scanf("%d%d", &n, &m); for (int i = 1, u, v; i <= m; i++) { scanf("%d%d", &u, &v); Add_Edge(u, v); } for (int i = 1; i <= n; i++) if (!pre[i]) Tarjan(i); for (int i = 1; i <= scc_cnt; i++) { fa[i] = i; if (size[i] > 1) vis[i] = 1; } ReBuild(); for (int i = 1; i <= scc_cnt; i++) if (fa[i] == i) if (vis[i]) ans += size[i]; else ans += size[i] - 1; printf("%d\n", ans); }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> const long long N = 1000006; using namespace std; const long long MOD = 1000000007LL; template <typename T> T gcd(T a, T b) { if (a == 0) return b; return gcd(b % a, a); } template <typename T> T power(T x, T y, long long m = MOD) { T ans = 1; while (y > 0) { if (y & 1LL) ans = (ans * x) % m; y >>= 1LL; x = (x * x) % m; } return ans % m; } vector<vector<long long> > g; vector<vector<long long> > ac; long long vis[N], vis2[N], in[N]; vector<long long> lt; bool f; vector<long long> topo; void dfs(long long n) { if (vis[n]) return; lt.emplace_back(n); vis[n] = 1; for (auto i : g[n]) if (!vis[i]) dfs(i); } void ch(long long n) { vis2[n] = 1; for (auto i : ac[n]) { if (!vis2[i]) ch(i); } topo.emplace_back(n); } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n, m; cin >> n >> m; g.resize(n); ac.resize(n); for (long long(i) = (0); i < (m); i++) { long long a, b; cin >> a >> b; --a; --b; g[a].emplace_back(b); g[b].emplace_back(a); ac[a].emplace_back(b); } long long ans = 0; for (long long(i) = (0); i < (n); i++) { if (vis[i]) continue; lt.clear(); f = 0; topo.clear(); dfs(i); for (auto ver : lt) ch(ver); set<long long> s; for (auto x : topo) { if (f) break; for (auto u : ac[x]) { if (f) break; if (s.find(u) == s.end()) { f = 1; break; } } s.insert(x); } if (f) ans += (long long)lt.size(); else ans += (long long)lt.size() - 1; } cout << ans; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int cycle[100010]; int sz[100010]; int parent[100010]; int Rank[100010]; vector<int> v[100010]; int mark[100010], use[100010]; int find(int cur) { if (parent[cur] == cur) return cur; return parent[cur] = find(parent[cur]); } void Union(int x, int y) { int xroot = find(x); int yroot = find(y); if (xroot == yroot) return; if (Rank[xroot] < Rank[yroot]) swap(xroot, yroot); sz[xroot] += sz[yroot]; sz[yroot] = 0; parent[yroot] = xroot; if (Rank[xroot] == Rank[yroot]) { Rank[xroot]++; } } void init(int n) { int i; for (i = 0; i <= n; ++i) { cycle[i] = 0; sz[i] = 1; Rank[i] = 0; parent[i] = i; } } void go(int cur) { mark[cur] = use[cur] = 1; for (int u : v[cur]) { if (!mark[u]) go(u); else if (use[u]) cycle[find(cur)] = 1; } use[cur] = 0; } int main() { memset(mark, 0, sizeof(mark)); memset(use, 0, sizeof(use)); int n, m, i; scanf("%d", &n); scanf("%d", &m); init(n); for (i = 0; i < m; ++i) { int x, y; scanf("%d", &x); scanf("%d", &y); v[x].push_back(y); Union(x, y); } for (i = 1; i <= n; ++i) if (!mark[i]) go(i); int ans = 0; for (i = 1; i <= n; ++i) if (sz[i]) ans = ans + sz[i] - 1 + cycle[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; const int N = 100010; int n, m; vector<long long> g[N]; vector<long long> rg[N]; vector<long long> vs; bool used[N]; int cmp[N], cmpsize[N]; void add_edge(int from, int to) { g[from].push_back(to); rg[to].push_back(from); } void dfs(int v) { used[v] = 1; for (int i = 0; i < (((int)(g[v]).size())); i++) { if (!used[g[v][i]]) dfs(g[v][i]); } vs.push_back(v); } void rdfs(int v, int k) { used[v] = 1; cmp[v] = k; for (int i = 0; i < (((int)(rg[v]).size())); i++) { if (!used[rg[v][i]]) rdfs(rg[v][i], k); } } int scc() { memset(used, 0, sizeof(used)); vs.clear(); for (int v = 0; v < (n); v++) { if (!used[v]) dfs(v); } memset(used, 0, sizeof(used)); int k = 0; for (int i = ((int)(vs).size()) - 1; i >= 0; i--) { if (!used[vs[i]]) rdfs(vs[i], k++); } return k; } int dfs2(int v) { used[v] = 1; int res = cmpsize[cmp[v]] == 1; for (int i = 0; i < (((int)(g[v]).size())); i++) if (!used[g[v][i]]) { res &= dfs2(g[v][i]); } for (int i = 0; i < (((int)(rg[v]).size())); i++) if (!used[rg[v][i]]) { res &= dfs2(rg[v][i]); } return res; } int main() { cin.tie(0); ios_base::sync_with_stdio(0); cin >> n >> m; for (int i = 0; i < (m); i++) { int a, b; cin >> a >> b; add_edge(a - 1, b - 1); } scc(); memset(cmpsize, 0, sizeof(cmpsize)); for (int i = 0; i < (n); i++) { cmpsize[cmp[i]]++; } memset(used, 0, sizeof(used)); int ans = n; for (int i = 0; i < (n); i++) if (!used[i]) { ans -= dfs2(i); } cout << ans << endl; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> const int MAXN = 1e5 + 5; std::vector<int> G[MAXN], GG[MAXN]; int n, m; bool vis[MAXN]; std::vector<int> S; inline void dfs(int v) { vis[v] = 1; S.push_back(v); for (auto x : GG[v]) { if (vis[x]) continue; dfs(x); } for (auto x : G[v]) { if (vis[x]) continue; dfs(x); } } int deg[MAXN]; inline int work() { if (S.size() == 1) return 0; std::queue<int> q; for (auto x : S) if (!deg[x]) q.push(x); int c = 0; while (!q.empty()) { int v = q.front(); q.pop(); ++c; for (auto x : G[v]) { if (!--deg[x]) q.push(x); } } int ans = S.size(); if (c == S.size()) { ans = (int)S.size() - 1; } return ans; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; ++i) { int u, v; scanf("%d%d", &u, &v); G[u].push_back(v); GG[v].push_back(u); ++deg[v]; } int ans = 0; for (int i = 1; i <= n; ++i) if (!vis[i]) { S.clear(); dfs(i); ans += work(); } 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 M, A[100100], B[100100]; int C, N; int scc[100100]; vector<int> graph[100100], rev[100100], st; int cnt[100100]; void visit0(int p) { scc[p] = -1; for (auto q : graph[p]) if (!scc[q]) visit0(q); st.push_back(p); } void visit1(int p) { scc[p] = C; for (auto q : rev[p]) if (!~scc[q]) visit1(q); } void scc_go() { memset(scc, 0, N * 4); C = 0; for (int i = 0; i < N; ++i) if (!scc[i]) visit0(i); for (int i = N - 1; i >= 0; --i) if (!~scc[st[i]]) ++C, visit1(st[i]); } bool vis[100100]; pair<int, int> visit(int p) { if (vis[p]) return make_pair(0, 0); vis[p] = true; int ret = 1, flg = 0; for (auto x : graph[p]) { auto tmp = visit(x); ret += tmp.first; flg |= tmp.second; } for (auto x : rev[p]) { auto tmp = visit(x); ret += tmp.first; flg |= tmp.second; } if (cnt[scc[p]] >= 2) flg = 1; return make_pair(ret, flg); } int main() { scanf("%d%d", &N, &M); for (int i = 0; i < M; ++i) { scanf("%d%d", A + i, B + i); --A[i]; --B[i]; graph[A[i]].push_back(B[i]); rev[B[i]].push_back(A[i]); } scc_go(); for (int i = 0; i <= N; ++i) { vis[i] = false; cnt[i] = 0; } for (int i = 0; i < N; ++i) { ++cnt[scc[i]]; } int ret = 0; for (int i = 0; i < N; ++i) { if (!vis[i]) { auto x = visit(i); ret += x.first + x.second - 1; } } printf("%d\n", ret); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const long long N = 1e5 + 5; long long n, m; vector<long long> undirG[N]; long long grp = 0; vector<long long> g[N], newg[N], rg[N], todo; long long comp[N], indeg[N], sz[N]; bool vis[N]; set<long long> gr[N]; void dfs(long long u) { vis[u] = 1; for (auto &it : g[u]) { if (!vis[it]) dfs(it); } todo.push_back(u); } void dfs2(long long u, long long val) { comp[u] = val; sz[val]++; for (auto &it : rg[u]) { if (comp[it] == -1) dfs2(it, val); } } void sccAddEdge(long long from, long long to) { g[from].push_back(to); rg[to].push_back(from); } void scc() { for (long long i = 1; i <= n; i++) comp[i] = -1; for (long long i = 1; i <= n; i++) { if (!vis[i]) dfs(i); } reverse(todo.begin(), todo.end()); for (auto &it : todo) { if (comp[it] == -1) dfs2(it, ++grp); } } long long vertices = 0, check = 0; void dfs0(long long u) { if (vis[u]) return; vis[u] = 1; check |= (sz[comp[u]] > 1); vertices++; for (auto &it : undirG[u]) dfs0(it); } int32_t main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; cin >> n >> m; for (long long i = 1; i <= m; i++) { long long u, v; cin >> u >> v; sccAddEdge(u, v); undirG[u].push_back(v); undirG[v].push_back(u); } scc(); memset(vis, 0, sizeof(vis)); long long ans = 0; for (long long i = 1; i <= n; i++) { if (vis[i]) continue; check = 0; vertices = 0; dfs0(i); if (check) ans += vertices; else ans += vertices - 1; } cout << ans; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 10; int n, m, pre[N], cnt[N], ans = 0, sz[N], du[N], u, v; int find(int x) { return x == pre[x] ? x : pre[x] = find(pre[x]); } vector<int> g[N]; queue<int> q; int main() { cin >> n >> m; for (int i = 1; i <= n; i++) pre[i] = i; for (int i = 1; i <= m; i++) { scanf("%d%d", &u, &v); g[u].push_back(v); pre[find(u)] = find(v); du[v]++; } for (int i = 1; i <= n; i++) { sz[find(i)]++; if (!du[i]) q.push(i); } while (!q.empty()) { u = q.front(); q.pop(); for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; du[v]--; if (!du[v]) q.push(v); } } for (int i = 1; i <= n; i++) if (du[i]) cnt[find(i)] = 1; for (int i = 1; i <= n; i++) if (pre[i] == i) ans += sz[i] - (cnt[i] ^ 1); cout << ans << "\n"; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,ssse3,sse3,sse4,popcnt,avx,mmx,abm,tune=native") using namespace std; namespace output { void __(short x) { cout << x; } void __(unsigned x) { cout << x; } void __(int x) { cout << x; } void __(long long x) { cout << x; } void __(unsigned long long x) { cout << x; } void __(double x) { cout << x; } void __(long double x) { cout << x; } void __(char x) { cout << x; } void __(const char* x) { cout << x; } void __(const string& x) { cout << x; } void __(bool x) { cout << (x ? "true" : "false"); } template <class S, class T> void __(const pair<S, T>& x) { __(1 ? "(" : ""), __(x.first), __(1 ? ", " : " "), __(x.second), __(1 ? ")" : ""); } template <class T> void __(const vector<T>& x) { __(1 ? "{" : ""); bool _ = 0; for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1; __(1 ? "}" : ""); } template <class T> void __(const set<T>& x) { __(1 ? "{" : ""); bool _ = 0; for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1; __(1 ? "}" : ""); } template <class T> void __(const multiset<T>& x) { __(1 ? "{" : ""); bool _ = 0; for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1; __(1 ? "}" : ""); } template <class S, class T> void __(const map<S, T>& x) { __(1 ? "{" : ""); bool _ = 0; for (const auto& v : x) __(_ ? 1 ? ", " : " " : ""), __(v), _ = 1; __(1 ? "}" : ""); } void pr() { cout << "\n"; } template <class S, class... T> void pr(const S& a, const T&... b) { __(a); if (sizeof...(b)) __(' '); pr(b...); } } // namespace output using namespace output; const int MN = 1e5 + 5; int N, M, i, x, y, vis[MN][2], nxt, st[MN], cmp[MN], id, vs[MN], f, cnt; set<int> hm, cc; vector<int> adj[MN], wat[MN]; stack<int> s; void dfs(int n) { vis[n][0] = vis[n][1] = ++nxt; st[n] = 1; s.push(n); for (auto v : adj[n]) { if (!vis[v][0]) dfs(v), vis[n][1] = min(vis[n][1], vis[v][1]); else if (st[v]) vis[n][1] = min(vis[n][1], vis[v][0]); } if (vis[n][0] == vis[n][1]) { while (s.size() && s.top() != n) { cmp[s.top()] = id + 1; st[s.top()] = 0; s.pop(); } cmp[s.top()] = ++id; st[s.top()] = 0; s.pop(); } } void ddfs(int n) { vs[n] = 1; cnt++; if (cc.count(cmp[n])) f = 1; cc.insert(cmp[n]); for (auto v : wat[n]) { if (!vs[v]) ddfs(v); } } int main() { scanf("%d%d", &N, &M); for (i = 1; i <= M; i++) { scanf("%d%d", &x, &y); hm.insert(x), hm.insert(y); adj[x].push_back(y); wat[x].push_back(y); wat[y].push_back(x); } for (i = 1; i <= N; i++) { if (!vis[i][0]) dfs(i); } int ans = 0; for (i = 1; i <= N; i++) { if (!vs[i]) { f = cnt = 0; ddfs(i); if (f) ans += cnt; else ans += cnt - 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 = 100010; vector<int> adj_dir[MAXN], adj[MAXN]; int visited[MAXN]; vector<int> comp; bool has_cycle; void dfs(int u) { visited[u] = 1; comp.push_back(u); for (int i = 0; i < adj[u].size(); i++) { int v = adj[u][i]; if (!visited[v]) { dfs(v); } } } void dfs_dir(int u) { visited[u] = 1; for (int i = 0; i < adj_dir[u].size(); i++) { int v = adj_dir[u][i]; if (visited[v] == 0) { dfs_dir(v); } else if (visited[v] == 1) { has_cycle = true; } } visited[u] = 2; } int main() { int n, m; while (scanf("%d%d", &n, &m) > 0) { while (m--) { int a, b; scanf("%d%d", &a, &b); adj_dir[a].push_back(b); adj[a].push_back(b); adj[b].push_back(a); } memset(visited, 0, sizeof visited); int ans = 0; for (int u = 1; u <= n; u++) { if (!visited[u]) { comp.clear(); dfs(u); for (int i = 0; i < comp.size(); i++) { visited[comp[i]] = false; } has_cycle = false; for (int i = 0; i < comp.size(); i++) { if (!visited[comp[i]]) { dfs_dir(comp[i]); } } ans += comp.size(); if (!has_cycle) ans--; } } printf("%d\n", ans); for (int i = 1; i <= n; i++) { adj[i].clear(); adj_dir[i].clear(); } } }
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 setIO() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); } const long double PI = 4 * atan((long double)1); const int INF = 1e9 + 7; const long long _INF = 1e18; vector<vector<int> > med, ed; vector<bool> vs; vector<int> wut, in, low, stc; vector<vector<int> > cmp; stack<int> st; int ct = 1; void dfs1(int u, int p = -1) { vs[u] = 1; wut.push_back(u); for (int x : med[u]) if (!vs[x]) { dfs1(x, u); } } bool dfs2(int u, int p = -1) { bool ret = 0; in[u] = low[u] = ct++; st.push(u); stc[u] = 1; for (int v : ed[u]) { if (!in[v]) { ret |= dfs2(v, u); low[u] = min(low[u], low[v]); } else if (stc[v]) { low[u] = min(low[u], in[v]); } } if (low[u] == in[u]) { vector<int> scc; int v; do { v = st.top(); st.pop(); scc.push_back(v); stc[v] = 0; } while (u != v); if ((int)scc.size() > 1) ret = 1; } return ret; } int main() { setIO(); int n, m; cin >> n >> m; in.resize(n + 1); stc.resize(n + 1); low.resize(n + 1); med.assign(n + 1, vector<int>()); ed.assign(n + 1, vector<int>()); vs.resize(n + 1); for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; med[a].push_back(b); med[b].push_back(a); ed[a].push_back(b); } for (int i = 1; i <= n; i++) { if (!vs[i]) { dfs1(i); cmp.push_back(wut); wut.clear(); } } int ans = 0; for (vector<int> x : cmp) { bool cy = 0; for (int u : x) { if (!in[u]) cy |= dfs2(u); } ans += (int)x.size(); if (!cy) 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; vector<int> v[100001]; int c[100001]; int n; int m; int dsu[100001]; int F(int x) { if (dsu[x] < 0) return x; else { dsu[x] = F(dsu[x]); return dsu[x]; } } void U(int x, int y) { x = F(x); y = F(y); if (x == y) return; if (dsu[x] < dsu[y]) swap(x, y); dsu[x] += dsu[y]; dsu[y] = x; } bool as = false; void topo(int q) { c[q] = 1; for (int i = 0; i < v[q].size(); ++i) { if (!c[v[q][i]]) { topo(v[q][i]); } else if (c[v[q][i]] == 1) { as = true; } } c[q] = -1; } vector<int> be[100001]; int main() { ios_base::sync_with_stdio(false); cin >> n >> m; for (int i = 1; i <= n; ++i) dsu[i] = -1; for (int i = 1; i <= m; ++i) { int x, y; cin >> x >> y; U(x, y); v[x].push_back(y); } int cur = 0; for (int i = 1; i <= n; ++i) { be[F(i)].push_back(i); } for (int j = 1; j <= n; ++j) { if (!be[j].size()) continue; for (int i = 0; i < be[j].size(); ++i) { if (!c[be[j][i]]) topo(be[j][i]); } cur += (-dsu[F(be[j][0])]); if (!as) --cur; as = false; } cout << cur; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashSet; import java.util.ArrayList; import java.util.LinkedList; import java.util.StringTokenizer; public class MrKitayutasTechnology { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int M = sc.nextInt(); Node[] nodes = new Node[N + 1]; for (int i = 1; i <= N; i++){ nodes[i] = new Node(); } for (int i = 0; i < M; i++) { int a = sc.nextInt(); int b = sc.nextInt(); nodes[a].nexts.add(nodes[b]); nodes[b].prevs.add(nodes[a]); } int cnt = 0; HashSet<Node> visited = new HashSet<Node>(); for (int i = 1; i <= N; i++) { if (!visited.contains(nodes[i])) { HashSet<Node> comp = getComponent(nodes[i]); if (toplogicalSort(comp) == null) { cnt += comp.size(); } else { cnt += comp.size() - 1; } for (Node n : comp) { visited.add(n); } } } System.out.println(cnt); } public static HashSet<Node> getComponent(Node seed) { HashSet<Node> visited = new HashSet<Node>(); LinkedList<Node> q = new LinkedList<Node>(); q.addLast(seed); while (!q.isEmpty()) { Node curr = q.removeFirst(); if (visited.contains(curr)) { continue; } visited.add(curr); for (Node n : curr.nexts) { q.addLast(n); } for (Node n : curr.prevs) { q.addLast(n); } } return visited; } // NOTE: destructively modifies the input nodes public static ArrayList<Node> toplogicalSort(HashSet<Node> nodes) { ArrayList<Node> lst = new ArrayList<Node>(); HashSet<Node> starts = new HashSet<Node>(); LinkedList<Node> q = new LinkedList<Node>(); for (Node n : nodes) { if (n.prevs.size() == 0) { starts.add(n); q.addLast(n); } } while (!q.isEmpty()) { Node n = q.removeFirst(); if (!starts.contains(n)) { continue; } lst.add(n); for (Node m : n.nexts) { m.prevs.remove(n); if (m.prevs.size() == 0) { starts.add(m); q.addLast(m); } } n.nexts.clear(); } for (Node n : nodes) { if ((n.prevs.size() > 0) || (n.nexts.size() > 0)) { return null; } } return lst; } public static class Node { public HashSet<Node> nexts; public HashSet<Node> prevs; public Node() { this.nexts = new HashSet<Node>(); this.prevs = new HashSet<Node>(); } } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; struct Union { int par[100001], val[100001], cnt[100001], loop[100001]; Union() { for (int j = 0; j < 100001; j++) par[j] = j, val[j] = 0, cnt[j] = 1, loop[j] = 0; } int parent(int x) { if (x == par[x]) return x; return par[x] = parent(par[x]); } void add(int x, int y) { int p1 = parent(x); int p2 = parent(y); if (p1 == p2) return; if (cnt[p1] > cnt[p2]) { par[p2] = p1; cnt[p1] += cnt[p2]; } else { par[p1] = p2; cnt[p2] += cnt[p1]; } } void update(int x, int v, int l) { int p = parent(x); val[p] = v; loop[p] = l; } pair<int, int> value(int x) { return make_pair(val[parent(x)], loop[parent(x)]); } }; Union u; vector<int> g[100001]; int mark[100001] = {0}, dfsNo[100001] = {0}; set<int> otherTree[100001]; void dfs(int src, int par, const int num, int& cycle, vector<int>& nodes) { if (mark[src] == 1) { cycle = 1; return; } if (mark[src]) { if (dfsNo[src] == dfsNo[par]) return; else otherTree[num].insert(dfsNo[src]); return; } nodes.push_back(src); dfsNo[src] = num; mark[src] = 1; for (auto i : g[src]) dfs(i, src, num, cycle, nodes); mark[src] = 2; } int main() { ios_base ::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; for (int j = 0; j < m; j++) { int u, v; cin >> u >> v; g[u].push_back(v); } int num = 1; for (int j = 1; j <= n; j++) { int cyc = 0; if (!mark[j]) { vector<int> nodes; dfs(j, 0, num, cyc, nodes); int cnts = (cyc == 0) ? (int)nodes.size() - 1 : (int)nodes.size(); u.update(num, cnts, cyc); for (auto it : otherTree[num]) { if (u.parent(it) == u.parent(num)) continue; cyc = u.value(num).second, cnts = u.value(num).first; if (cyc) { int l = u.value(it).second, v = u.value(it).first; u.add(it, num); if (l) u.update(it, v + cnts, 1); else u.update(it, v + cnts + 1, 1); } else { int l = u.value(it).second, v = u.value(it).first; u.add(num, it); if (l) u.update(it, v + cnts + 1, 1); else u.update(it, v + cnts + 1, 0); } } num++; } } int ans = 0; set<int> s; for (int j = 1; j < num; j++) { if (s.count(u.parent(j))) continue; s.insert(u.parent(j)); ans += u.value(j).first; } 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 target("avx,avx2,fma") #pragma GCC optimization("O2") #pragma GCC optimization("unroll-loops") using namespace std; const long long int N = 2e5 + 10, mod = 1e9 + 7, inf = 1e18, dlt = 12251; int poww(int n, int k) { if (!k) return 1; if (k == 1) return n; long long r = poww(n, k / 2); return (((r * r) % mod) * poww(n, k & 1)) % mod; } int vis[N], comp[N], sz[N]; bool dg[N]; vector<int> adj[N], out[N]; void pre(int v, int c) { comp[v] = c; sz[c]++; for (int u : adj[v]) if (!comp[u]) pre(u, c); } bool dfs(int v) { vis[v] = 1; for (int u : out[v]) { if (vis[u] == 1) return 0; if (vis[u] == 2) continue; if (!dfs(u)) return 0; } vis[v] = 2; return 1; } int main() { int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); out[u].push_back(v); } int c = 0; for (int i = 1; i < n + 1; i++) { if (!comp[i]) { c++; dg[c] = 1; pre(i, c); } } for (int i = 1; i < n + 1; i++) { if (vis[i]) continue; if (!dfs(i)) dg[comp[i]] = 0; } int ans = 0; for (int i = 1; i < c + 1; i++) { if (dg[i]) ans += sz[i] - 1; else ans += sz[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; int n; int edge; int head[300001]; int scc, cnt; bool v[300001]; int s[400001], top; int dfn[400001], low[400001], belong[400001]; int indeg[400001], outdeg[400001], sdeg[400001]; struct map { int s, t; int next; } a[300001]; inline void add(int s, int t) { a[edge].next = head[s]; head[s] = edge; a[edge].s = s; a[edge].t = t; } inline void tarjan(int d) { int i, x; cnt++; dfn[d] = cnt; low[d] = cnt; top++; s[top] = d; v[d] = true; for (i = head[d]; i != 0; i = a[i].next) { x = a[i].t; if (dfn[x] == 0) { tarjan(x); low[d] = min(low[d], low[x]); } else if (v[x] && low[d] > dfn[x]) low[d] = dfn[x]; } if (dfn[d] == low[d]) { scc++; x = s[top]; top--; while (x != d) { v[x] = false; belong[x] = scc; x = s[top]; top--; } v[x] = false; belong[x] = scc; } } inline void count_edge() { int i, j, d; for (i = 1; i <= n; i++) sdeg[belong[i]]++; } int father[400001]; int sx[400001]; inline int find(int x) { if (father[x] != x) father[x] = find(father[x]); return father[x]; } inline int count_edgeex() { int i, j, d; int fx, fy; int s = 0; for (i = 1; i <= n; i++) { for (j = head[i]; j != 0; j = a[j].next) { d = a[j].t; fx = find(belong[i]); fy = find(belong[d]); if (fx != fy) { if (sx[fx] == 1 || sx[fy] == 1) s++; father[fx] = fy; if (sx[fx] != 1 || sx[fy] != 1) { sx[fx] += sx[fy]; sx[fy] = sx[fx]; } } } } return s; } int main() { int m; scanf("%d%d", &n, &m); int i; int s, t; for (i = 1; i <= m; i++) { scanf("%d%d", &s, &t); edge++; add(s, t); } for (i = 1; i <= n; i++) if (!belong[i]) tarjan(i); count_edge(); for (i = 1; i <= scc; i++) { father[i] = i; sx[i] = sdeg[i]; } int ans = 0; for (i = 1; i <= scc; i++) if (sdeg[i] != 1) ans += sdeg[i]; ans += count_edgeex(); printf("%d\n", ans); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; vector<int> g[100010]; int dfn[100010], v[100010], w[100010], be[100010], fa[100010], low[100010], st[100010], s, h, t, n, m, ti; bool f[100010]; int getf(int x) { if (fa[x] != x) fa[x] = getf(fa[x]); return fa[x]; } void tarjan(int x) { dfn[x] = low[x] = ++h; st[++t] = x; f[x] = 1; for (int i = 0; i < g[x].size(); i++) { int y = g[x][i]; if (!dfn[y]) { tarjan(y); low[x] = min(low[x], low[y]); } else if (f[y]) low[x] = min(low[x], low[y]); } if (dfn[x] == low[x]) { s++; while (st[t + 1] != x) { int y = st[t--]; f[y] = 0; be[y] = s; w[s]++; } } } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) fa[i] = i; for (int i = 1; i <= m; i++) { int x, y; scanf("%d%d", &x, &y); g[x].push_back(y); int u = getf(x), v = getf(y); if (u != v) fa[u] = v; } int ans = n; for (int i = 1; i <= n; i++) if (!dfn[i]) { h = t = 0; tarjan(i); } for (int i = 1; i <= n; i++) if (w[be[i]] > 1) v[getf(i)] = 1; for (int i = 1; i <= n; i++) if (getf(i) == i && !v[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 cmx = 1e5 + 5; vector<int> adj[cmx], und[cmx]; int mark1[cmx], mark2[cmx]; vector<int> v; int n, m; bool cycle; void dfs2(int x) { mark2[x] = 1; for (int i = 0; i < adj[x].size(); i++) { int u = adj[x][i]; if (mark2[u] == 1) cycle = true; if (!mark2[u]) dfs2(u); } mark2[x] = 2; } void dfs1(int x) { mark1[x] = 1; v.push_back(x); for (int i = 0; i < und[x].size(); i++) if (!mark1[und[x][i]]) dfs1(und[x][i]); } int main() { cin >> n >> m; for (int i = 0; i < m; i++) { int u, v; scanf("%d %d", &u, &v); u--, v--; adj[u].push_back(v); und[u].push_back(v); und[v].push_back(u); } int ans = n; for (int i = 0; i < n; i++) { if (!mark1[i]) { v.clear(); dfs1(i); cycle = false; for (int j = 0; j < v.size(); j++) if (!mark2[v[j]]) dfs2(v[j]); 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; bool vis1[100011]; long long int vis2[100011]; vector<long long int> second; vector<long long int> g[100011], gd[100011]; void dfs1(long long int v) { vis1[v] = 1; second.emplace_back(v); for (auto x : g[v]) { if (!vis1[x]) dfs1(x); } } long long int dfs2(long long int v) { vis2[v] = 1; for (auto x : gd[v]) { if (vis2[x] == 0) { if (dfs2(x)) return 1; } if (vis2[x] == 1) return 1; } vis2[v] = 2; return 0; } long long int func(vector<long long int>& w) { long long int p = 0; for (auto x : w) { if (vis2[x] == 0) p += dfs2(x); } if (!p) return 1; return 0; } int main() { long long int n, m; cin >> n >> m; long long int u, v; for (int i = 1; i <= m; i++) { cin >> u >> v; g[u].emplace_back(v); g[v].emplace_back(u); gd[u].emplace_back(v); } long long int ans = 0; for (int i = 1; i <= n; i++) { if (!vis1[i]) { second.clear(); dfs1(i); ans = ans + second.size() - func(second); } } cout << ans; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int arr[4]; int main() { int n, a; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a); arr[a]++; } return printf("%d\n", n - max(max(arr[1], arr[2]), arr[3])), 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
from collections import deque from math import ceil,floor,sqrt,gcd def ii(): return int(input()) def mi(): return map(int,input().split()) def li(): return list(mi()) def si():return input() n=ii() a=li() m={} for i in a: if i not in m: m[i]=1 else: m[i]+=1 b=[] for i in m.keys(): b.append(m[i]) b.sort() if(len(b)==3): print(b[0]+b[1]) elif(len(b)==2): print(b[0]) else: print('0')
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long n; cin >> n; vector<long long> v(n); long long a1 = 0, a2 = 0, a3 = 0; for (long long i = 0; i < n; i++) { cin >> v[i]; if (v[i] == 1) a1++; else if (v[i] == 2) a2++; else a3++; } long long a = max(a1, max(a2, a3)); cout << (a1 + a2 + a3) - a; return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class sequence { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader str = new BufferedReader( new InputStreamReader(System.in)); int n = Integer.parseInt(str.readLine()); PrintWriter out = new PrintWriter(System.out); int[] arr = new int[3]; StringTokenizer input = new StringTokenizer(str.readLine()); for (int i = 0; i < n; i++) { int x = Integer.parseInt(input.nextToken()); arr[(x - 1)]++; } int max = 0; max = Math.max(arr[0], Math.max(arr[1], arr[2])); out.println(n - max); out.close(); } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n = int(input()) s = list(map(int, input().split())) print(n-max(s.count(x) for x in [1, 2, 3]))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
/* * Hello! You are trying to hack my solution, are you? =) * Don't be afraid of the size, it's just a dump of useful methods like gcd, or n-th Fib number. * And I'm just too lazy to create a new .java for every task. * And if you were successful to hack my solution, please, send me this test as a message or to [email protected]. * It can help me improve my skills and i'd be very grateful for that. * Sorry for time you spent reading this message. =) * Good luck, unknown rival. =) * */ import java.io.*; import java.math.*; import java.util.*; public class Abra { void solve() throws IOException { int n = nextInt(); int[] a = new int[3]; for (int i = 0; i < n; i++) a[nextInt() - 1]++; out.println(lib.min(a[0] + a[1], a[0] + a[2], a[2] + a[1])); } public static void main(String[] args) throws IOException { new Abra().run(); } StreamTokenizer in; PrintWriter out; boolean oj; BufferedReader br; void init() throws IOException { oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); br = new BufferedReader(reader); in = new StreamTokenizer(br); out = new PrintWriter(writer); } long selectionTime = 0; void startSelection() { selectionTime -= System.currentTimeMillis(); } void stopSelection() { selectionTime += System.currentTimeMillis(); } void run() throws IOException { long beginTime = System.currentTimeMillis(); long beginMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); init(); solve(); long endMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long endTime = System.currentTimeMillis(); if (!oj) { System.out.println("Memory used = " + (endMem - beginMem)); System.out.println("Total memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Running time = " + (endTime - beginTime)); } out.flush(); } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } int fastNextInt() throws IOException { int r = 0, d = 1; char c = (char) br.read(); while (!lib.isDigitChar(c) && c != '-') c = (char) br.read(); while (true) { if (c == '-') { d = -1; } else { r += (c - '0') * d; d *= 10; } c = (char) br.read(); if (!lib.isDigitChar(c) && c != '-') break; } return r; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } String nextString() throws IOException { in.nextToken(); return in.sval; } double nextDouble() throws IOException { in.nextToken(); return in.nval; } myLib lib = new myLib(); static class myLib { long fact(long x) { long a = 1; for (long i = 2; i <= x; i++) { a *= i; } return a; } long digitSum(String x) { long a = 0; for (int i = 0; i < x.length(); i++) { a += x.charAt(i) - '0'; } return a; } long digitSum(long x) { long a = 0; while (x > 0) { a += x % 10; x /= 10; } return a; } long digitMul(long x) { long a = 1; while (x > 0) { a *= x % 10; x /= 10; } return a; } int digitCubesSum(int x) { int a = 0; while (x > 0) { a += (x % 10) * (x % 10) * (x % 10); x /= 10; } return a; } double pif(double ax, double ay, double bx, double by) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); } double pif3D(double ax, double ay, double az, double bx, double by, double bz) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by) + (az - bz) * (az - bz)); } double pif3D(double[] a, double[] b) { return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2])); } long gcd(long a, long b) { if (a == 0 || b == 0) return 1; if (a < b) { long c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { long c = b; b = a; a = c; } } return b; } int gcd(int a, int b) { if (a == 0 || b == 0) return 1; if (a < b) { int c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { int c = b; b = a; a = c; } } return b; } long lcm(long a, long b) { return a * b / gcd(a, b); } int lcm(int a, int b) { return a * b / gcd(a, b); } int countOccurences(String x, String y) { int a = 0, i = 0; while (true) { i = y.indexOf(x); if (i == -1) break; a++; y = y.substring(i + 1); } return a; } int[] findPrimes(int x) { boolean[] forErato = new boolean[x - 1]; List<Integer> t = new Vector<Integer>(); int l = 0, j = 0; for (int i = 2; i < x; i++) { if (forErato[i - 2]) continue; t.add(i); l++; j = i * 2; while (j < x) { forErato[j - 2] = true; j += i; } } int[] primes = new int[l]; Iterator<Integer> iterator = t.iterator(); for (int i = 0; iterator.hasNext(); i++) { primes[i] = iterator.next().intValue(); } return primes; } int rev(int x) { int a = 0; while (x > 0) { a = a * 10 + x % 10; x /= 10; } return a; } class myDate { int d, m, y; int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; public myDate(int da, int ma, int ya) { d = da; m = ma; y = ya; if ((ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) && !(d == 29 && m == 2 && y % 4 == 0)) { d = 1; m = 1; y = 9999999; } } void incYear(int x) { for (int i = 0; i < x; i++) { y++; if (m == 2 && d == 29) { m = 3; d = 1; return; } if (m == 3 && d == 1) { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { m = 2; d = 29; } return; } } } boolean less(myDate x) { if (y < x.y) return true; if (y > x.y) return false; if (m < x.m) return true; if (m > x.m) return false; if (d < x.d) return true; if (d > x.d) return false; return true; } void inc() { if ((d == 31) && (m == 12)) { y++; d = 1; m = 1; } else { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { ml[1] = 29; } if (d == ml[m - 1]) { m++; d = 1; } else d++; } } } int partition(int n, int l, int m) {// n - sum, l - length, m - every // part // <= m if (n < l) return 0; if (n < l + 2) return 1; if (l == 1) return 1; int c = 0; for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) { c += partition(n - i, l - 1, i); } return c; } int rifmQuality(String a, String b) { if (a.length() > b.length()) { String c = a; a = b; b = c; } int c = 0, d = b.length() - a.length(); for (int i = a.length() - 1; i >= 0; i--) { if (a.charAt(i) == b.charAt(i + d)) c++; else break; } return c; } String numSym = "0123456789ABCDEF"; String ZFromXToYNotation(int x, int y, String z) { if (z.equals("0")) return "0"; String a = ""; // long q = 0, t = 1; BigInteger q = BigInteger.ZERO, t = BigInteger.ONE; for (int i = z.length() - 1; i >= 0; i--) { q = q.add(t.multiply(BigInteger.valueOf(z.charAt(i) - 48))); t = t.multiply(BigInteger.valueOf(x)); } while (q.compareTo(BigInteger.ZERO) == 1) { a = numSym.charAt((int) (q.mod(BigInteger.valueOf(y)).intValue())) + a; q = q.divide(BigInteger.valueOf(y)); } return a; } double angleFromXY(int x, int y) { if ((x == 0) && (y > 0)) return Math.PI / 2; if ((x == 0) && (y < 0)) return -Math.PI / 2; if ((y == 0) && (x > 0)) return 0; if ((y == 0) && (x < 0)) return Math.PI; if (x > 0) return Math.atan((double) y / x); else { if (y > 0) return Math.atan((double) y / x) + Math.PI; else return Math.atan((double) y / x) - Math.PI; } } static boolean isNumber(String x) { try { Integer.parseInt(x); } catch (NumberFormatException ex) { return false; } return true; } static boolean stringContainsOf(String x, String c) { for (int i = 0; i < x.length(); i++) { if (c.indexOf(x.charAt(i)) == -1) return false; } return true; } long pow(long a, long n) { // b > 0 if (n == 0) return 1; long k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } int pow(int a, int n) { // b > 0 if (n == 0) return 1; int k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } double pow(double a, int n) { // b > 0 if (n == 0) return 1; double k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } double log2(double x) { return Math.log(x) / Math.log(2); } int lpd(int[] primes, int x) {// least prime divisor int i; for (i = 0; primes[i] <= x / 2; i++) { if (x % primes[i] == 0) { return primes[i]; } } ; return x; } int np(int[] primes, int x) {// number of prime number for (int i = 0; true; i++) { if (primes[i] == x) return i; } } int[] dijkstra(int[][] map, int n, int s) { int[] p = new int[n]; boolean[] b = new boolean[n]; Arrays.fill(p, Integer.MAX_VALUE); p[s] = 0; b[s] = true; for (int i = 0; i < n; i++) { if (i != s) p[i] = map[s][i]; } while (true) { int m = Integer.MAX_VALUE, mi = -1; for (int i = 0; i < n; i++) { if (!b[i] && (p[i] < m)) { mi = i; m = p[i]; } } if (mi == -1) break; b[mi] = true; for (int i = 0; i < n; i++) if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i]; } return p; } boolean isLatinChar(char x) { if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true; else return false; } boolean isBigLatinChar(char x) { if (x >= 'A' && x <= 'Z') return true; else return false; } boolean isSmallLatinChar(char x) { if (x >= 'a' && x <= 'z') return true; else return false; } boolean isDigitChar(char x) { if (x >= '0' && x <= '9') return true; else return false; } class NotANumberException extends Exception { private static final long serialVersionUID = 1L; String mistake; NotANumberException() { mistake = "Unknown."; } NotANumberException(String message) { mistake = message; } } class Real { String num = "0"; long exp = 0; boolean pos = true; long length() { return num.length(); } void check(String x) throws NotANumberException { if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character."); long j = 0; for (long i = 0; i < x.length(); i++) { if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) { if (j == 0) j = 1; else if (j == 5) j = 6; else throw new NotANumberException("Unexpected sign."); } else if ("0123456789".indexOf(x.charAt((int) i)) != -1) { if (j == 0) j = 2; else if (j == 1) j = 2; else if (j == 2) ; else if (j == 3) j = 4; else if (j == 4) ; else if (j == 5) j = 6; else if (j == 6) ; else throw new NotANumberException("Unexpected digit."); } else if (x.charAt((int) i) == '.') { if (j == 0) j = 3; else if (j == 1) j = 3; else if (j == 2) j = 3; else throw new NotANumberException("Unexpected dot."); } else if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) { if (j == 2) j = 5; else if (j == 4) j = 5; else throw new NotANumberException("Unexpected exponent."); } else throw new NotANumberException("O_o."); } if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end."); } public Real(String x) throws NotANumberException { check(x); if (x.charAt(0) == '-') pos = false; long j = 0; String e = ""; boolean epos = true; for (long i = 0; i < x.length(); i++) { if ("0123456789".indexOf(x.charAt((int) i)) != -1) { if (j == 0) num += x.charAt((int) i); if (j == 1) { num += x.charAt((int) i); exp--; } if (j == 2) e += x.charAt((int) i); } if (x.charAt((int) i) == '.') { if (j == 0) j = 1; } if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) { j = 2; if (x.charAt((int) (i + 1)) == '-') epos = false; } } while ((num.length() > 1) && (num.charAt(0) == '0')) num = num.substring(1); while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) { num = num.substring(0, num.length() - 1); exp++; } if (num.equals("0")) { exp = 0; pos = true; return; } while ((e.length() > 1) && (e.charAt(0) == '0')) e = e.substring(1); try { if (e != "") if (epos) exp += Long.parseLong(e); else exp -= Long.parseLong(e); } catch (NumberFormatException exc) { if (!epos) { num = "0"; exp = 0; pos = true; } else { throw new NotANumberException("Too long exponent"); } } } public Real() { } String toString(long mantissa) { String a = "", b = ""; if (exp >= 0) { a = num; if (!pos) a = '-' + a; for (long i = 0; i < exp; i++) a += '0'; for (long i = 0; i < mantissa; i++) b += '0'; if (mantissa == 0) return a; else return a + "." + b; } else { if (exp + length() <= 0) { a = "0"; if (mantissa == 0) { return a; } if (mantissa < -(exp + length() - 1)) { for (long i = 0; i < mantissa; i++) b += '0'; return a + "." + b; } else { if (!pos) a = '-' + a; for (long i = 0; i < mantissa; i++) if (i < -(exp + length())) b += '0'; else if (i + exp >= 0) b += '0'; else b += num.charAt((int) (i + exp + length())); return a + "." + b; } } else { if (!pos) a = "-"; for (long i = 0; i < exp + length(); i++) a += num.charAt((int) i); if (mantissa == 0) return a; for (long i = exp + length(); i < exp + length() + mantissa; i++) if (i < length()) b += num.charAt((int) i); else b += '0'; return a + "." + b; } } } } boolean containsRepeats(int... num) { Set<Integer> s = new TreeSet<Integer>(); for (int d : num) if (!s.contains(d)) s.add(d); else return true; return false; } int[] rotateDice(int[] a, int n) { int[] c = new int[6]; if (n == 0) { c[0] = a[1]; c[1] = a[5]; c[2] = a[2]; c[3] = a[0]; c[4] = a[4]; c[5] = a[3]; } if (n == 1) { c[0] = a[2]; c[1] = a[1]; c[2] = a[5]; c[3] = a[3]; c[4] = a[0]; c[5] = a[4]; } if (n == 2) { c[0] = a[3]; c[1] = a[0]; c[2] = a[2]; c[3] = a[5]; c[4] = a[4]; c[5] = a[1]; } if (n == 3) { c[0] = a[4]; c[1] = a[1]; c[2] = a[0]; c[3] = a[3]; c[4] = a[5]; c[5] = a[2]; } if (n == 4) { c[0] = a[0]; c[1] = a[2]; c[2] = a[3]; c[3] = a[4]; c[4] = a[1]; c[5] = a[5]; } if (n == 5) { c[0] = a[0]; c[1] = a[4]; c[2] = a[1]; c[3] = a[2]; c[4] = a[3]; c[5] = a[5]; } return c; } int min(int... a) { int c = Integer.MAX_VALUE; for (int d : a) if (d < c) c = d; return c; } int max(int... a) { int c = Integer.MIN_VALUE; for (int d : a) if (d > c) c = d; return c; } double maxD(double... a) { double c = Double.MIN_VALUE; for (double d : a) if (d > c) c = d; return c; } double minD(double... a) { double c = Double.MAX_VALUE; for (double d : a) if (d < c) c = d; return c; } int[] normalizeDice(int[] a) { int[] c = a.clone(); if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0); else if (c[2] == 0) c = rotateDice(c, 1); else if (c[3] == 0) c = rotateDice(c, 2); else if (c[4] == 0) c = rotateDice(c, 3); else if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0); while (c[1] != min(c[1], c[2], c[3], c[4])) c = rotateDice(c, 4); return c; } boolean sameDice(int[] a, int[] b) { for (int i = 0; i < 6; i++) if (a[i] != b[i]) return false; return true; } final double goldenRatio = (1 + Math.sqrt(5)) / 2; final double aGoldenRatio = (1 - Math.sqrt(5)) / 2; long Fib(int n) { if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5)); else return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5)); return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5)); } class japaneeseComparator implements Comparator<String> { @Override public int compare(String a, String b) { int ai = 0, bi = 0; boolean m = false, ns = false; if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') { if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true; else return -1; } if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') { if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true; else return 1; } a += "!"; b += "!"; int na = 0, nb = 0; while (true) { if (a.charAt(ai) == '!') { if (b.charAt(bi) == '!') break; return -1; } if (b.charAt(bi) == '!') { return 1; } if (m) { int ab = -1, bb = -1; while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') { if (ab == -1) ab = ai; ai++; } while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') { if (bb == -1) bb = bi; bi++; } m = !m; if (ab == -1) { if (bb == -1) continue; else return 1; } if (bb == -1) return -1; while (a.charAt(ab) == '0' && ab + 1 != ai) { ab++; if (!ns) na++; } while (b.charAt(bb) == '0' && bb + 1 != bi) { bb++; if (!ns) nb++; } if (na != nb) ns = true; if (ai - ab < bi - bb) return -1; if (ai - ab > bi - bb) return 1; for (int i = 0; i < ai - ab; i++) { if (a.charAt(ab + i) < b.charAt(bb + i)) return -1; if (a.charAt(ab + i) > b.charAt(bb + i)) return 1; } } else { m = !m; while (true) { if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') { if (a.charAt(ai) < b.charAt(bi)) return -1; if (a.charAt(ai) > b.charAt(bi)) return 1; ai++; bi++; } else if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1; else if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1; else break; } } } if (na < nb) return 1; if (na > nb) return -1; return 0; } } Random random = new Random(); } void readIntArray(int[] a) throws IOException { for (int i = 0; i < a.length; i++) a[i] = nextInt(); } String readChars(int l) throws IOException { String r = ""; for (int i = 0; i < l; i++) r += (char) br.read(); return r; } class fraction{ long num = 0, den = 1; void reduce(){ long d = lib.gcd(num, den); num /= d; den /= d; } fraction(long ch, long zn) { num = ch; den = zn; reduce(); } fraction add(fraction t) { long nd = lib.lcm(den, t.den); fraction r = new fraction(nd / den * num + nd / t.den * t.num, nd); r.reduce(); return r; } public String toString(){ return num + "/" + den; } } /* * class cubeWithLetters { String consts = "ЧКТФЭЦ"; char[][] letters = { { * 'А', 'Б', 'Г', 'В' }, { 'Д', 'Е', 'З', 'Ж' }, { 'И', 'Л', 'Н', 'М' }, { * 'О', 'П', 'С', 'Р' }, { 'У', 'Х', 'Щ', 'Ш' }, { 'Ы', 'Ь', 'Я', 'Ю' } }; * * char get(char x) { if (consts.indexOf(x) != -1) return x; for (int i = 0; * i < 7; i++) { for (int j = 0; j < 4; j++) { if (letters[i][j] == x) { if * (j == 0) return letters[i][3]; else return letters[i][j - 1]; } } } * return '!'; } * * void subrotate(int x) { char t = letters[x][0]; letters[x][0] = * letters[x][3]; letters[x][3] = letters[x][2]; letters[x][2] = * letters[x][1]; letters[x][1] = t; } * * void rotate(int x) { subrotate(x); char t; if (x == 0) { t = * letters[1][0]; letters[1][0] = letters[2][0]; letters[2][0] = * letters[3][0]; letters[3][0] = letters[5][2]; letters[5][2] = t; * * t = letters[1][1]; letters[1][1] = letters[2][1]; letters[2][1] = * letters[3][1]; letters[3][1] = letters[5][3]; letters[5][3] = t; } if (x * == 1) { t = letters[2][0]; letters[2][0] = letters[0][0]; letters[0][0] = * letters[5][0]; letters[5][0] = letters[4][0]; letters[4][0] = t; * * t = letters[2][3]; letters[2][3] = letters[0][3]; letters[0][3] = * letters[5][3]; letters[5][3] = letters[4][3]; letters[4][3] = t; } if (x * == 2) { t = letters[0][3]; letters[0][3] = letters[1][2]; letters[1][2] = * letters[4][1]; letters[4][1] = letters[3][0]; letters[3][0] = t; * * t = letters[0][2]; letters[0][2] = letters[1][1]; letters[1][1] = * letters[4][0]; letters[4][0] = letters[3][3]; letters[3][3] = t; } if (x * == 3) { t = letters[2][1]; letters[2][1] = letters[4][1]; letters[4][1] = * letters[5][1]; letters[5][1] = letters[0][1]; letters[0][1] = t; * * t = letters[2][2]; letters[2][2] = letters[4][2]; letters[4][2] = * letters[5][2]; letters[5][2] = letters[0][2]; letters[0][2] = t; } if (x * == 4) { t = letters[2][3]; letters[2][3] = letters[1][3]; letters[1][3] = * letters[5][1]; letters[5][1] = letters[3][3]; letters[3][3] = t; * * t = letters[2][2]; letters[2][2] = letters[1][2]; letters[1][2] = * letters[5][0]; letters[5][0] = letters[3][2]; letters[3][2] = t; } if (x * == 5) { t = letters[4][3]; letters[4][3] = letters[1][0]; letters[1][0] = * letters[0][1]; letters[0][1] = letters[3][2]; letters[3][2] = t; * * t = letters[4][2]; letters[4][2] = letters[1][3]; letters[1][3] = * letters[0][0]; letters[0][0] = letters[3][1]; letters[3][1] = t; } } * * public String toString(){ return " " + letters[0][0] + letters[0][1] + * "\n" + " " + letters[0][3] + letters[0][2] + "\n" + letters[1][0] + * letters[1][1] + letters[2][0] + letters[2][1] + letters[3][0] + * letters[3][1] + "\n" + letters[1][3] + letters[1][2] + letters[2][3] + * letters[2][2] + letters[3][3] + letters[3][2] + "\n" + " " + * letters[4][0] + letters[4][1] + "\n" + " " + letters[4][3] + * letters[4][2] + "\n" + " " + letters[5][0] + letters[5][1] + "\n" + " " * + letters[5][3] + letters[5][2] + "\n"; } } * * * Vector<Integer>[] a; int n, mc, c1, c2; int[] col; * * void wave(int x, int p) { for (Iterator<Integer> i = a[x].iterator(); * i.hasNext(); ) { int t = i.next(); if (t == x || t == p) continue; if * (col[t] == 0) { col[t] = mc; wave(t, x); } else { c1 = x; c2 = t; } } } * * void solve() throws IOException { * * String s = "ЕПОЕЬРИТСГХЖЗТЯПСТАПДСБИСТЧК"; //String s = * "ЗЬУОЫТВЗТЯПУБОЫТЕАЫШХЯАТЧК"; cubeWithLetters cube = new * cubeWithLetters(); for (int x = 0; x < 4; x++) { for (int y = x + 1; y < * 5; y++) { for (int z = y + 1; z < 6; z++) { cube = new cubeWithLetters(); * out.println(cube.toString()); cube.rotate(x); * out.println(cube.toString()); cube.rotate(y); * out.println(cube.toString()); cube.rotate(z); * out.println(cube.toString()); out.print(x + " " + y + " " + z + " = "); * for (int i = 0; i < s.length(); i++) { out.print(cube.get(s.charAt(i))); * } out.println(); } } } * * int a = nextInt(), b = nextInt(), x = nextInt(), y = nextInt(); * out.print((lib.min(a / (x / lib.gcd(x, y)), b / (y / lib.gcd(x, y))) * (x * / lib.gcd(x, y))) + " " + (lib.min(a / (x / lib.gcd(x, y)), b / (y / * lib.gcd(x, y))) * (y / lib.gcd(x, y)))); } */ }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n=int(input()) a=list(map(int,input().split())) count1,count2,count3=0,0,0 for x in a: if x==1: count1+=1 elif x==2: count2+=1 else: count3+=1 print(min(count1+count2,count2+count3,count3+count1))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
a=int(input());b=list(map(int,input().split()));print(a-max(b.count(i) for i in [1,2,3]))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[n]; int one = 0, two = 0, three = 0; for (int i = 0; i < n; i++) { cin >> arr[i]; int k = arr[i]; if (k == 1) { one++; } else if (k == 2) { two++; } else if (k == 3) { three++; } } int maxm = max(one, max(two, three)); cout << n - maxm << endl; return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n = input() i1 = 0 i2 = 0 i3 = 0 s = list(map(int,input().split())) for j in s: if(j==1): i1 = i1+1 if(j==2): i2 = i2+1 if(j==3): i3=i3+1 if(i2>=i3 and i2>=i1): print(i3+i1) elif(i3>=i2 and i3>=i1): print(i2+i1) elif(i1>=i3 and i1>=i2): print(i3+i2) else: exit()
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n=int(raw_input()) l=raw_input() print n-max(l.count('1'),l.count('2'),l.count('3'))
PYTHON
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n = int(input()) a = list(map(int,input().split())) ones = a.count(1) twos = a.count(2) threes = a.count(3) print(min(ones + twos, ones + threes, twos + threes))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
# cook your dish here n=int(input()) l=input().split() c1=0 c2=0 c3=0 #print(l) c1=l.count("1") c2=l.count("2") c3=l.count("3") li=[c1,c2,c3] #print(li) s=max(li) #print(s) print(n-s)
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.util.*; import java.io.*; public class a { static long mod = 1000000007; static boolean[][] blacks; public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(new PrintStream(System.out)); //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); int n = input.nextInt(); int[] freq = new int[3]; for(int i = 0; i<n; i++) freq[input.nextInt()-1]++; Arrays.sort(freq); out.println(n-freq[2]); out.close(); } static long pow(long a, long p) { if(p==0) return 1; if((p&1) == 0) { long sqrt = pow(a, p/2); return (sqrt*sqrt)%mod; } else return (a*pow(a,p-1))%mod; } static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static String nextLine() throws IOException { return reader.readLine(); } } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n=int(input()) a=list(map(int,input().split())) x=a.count(1) y=a.count(2) z=n-(x+y) print(min(x+y,y+z,z+x))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int n, s1 = 0, s2 = 0, s3 = 0; cin >> n; for (int i = 0; i < n; i++) { int a; cin >> a; if (a == 1) s1++; if (a == 2) s2++; if (a == 3) s3++; } int k = max(max(s1, s2), s3); cout << n - k; return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.io.*; import java.util.*; public class A { PrintWriter out; BufferedReader in; StringTokenizer ss; static void dbg(String s){System.out.println(s);}; String next_token() throws IOException {while (!ss.hasMoreTokens())ss=new StringTokenizer(in.readLine()); return ss.nextToken();} Double _double() throws IOException {return Double.parseDouble (next_token());} int _int() throws IOException {return Integer.parseInt (next_token());} long _long() throws IOException {return Long.parseLong (next_token());} void run()throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out= new PrintWriter(System.out); String name=""; /*in = new BufferedReader(new FileReader(name+".in")); out = new PrintWriter(new File(name+".out")); */ ss = new StringTokenizer(" "); int a[]=new int[3]; int m=_int(); int ans=m; for(int i=0;i<m;i++){ int b=_int(); a[b-1]++; } for(int i=0;i<3;i++)ans=Math.min(ans,m-a[i]); out.println(ans); out.close(); } public static void main(String[] args)throws Exception { try{new A().run();}catch (Exception e){int Ar[]=new int[2];Ar[1+2]=2;}; } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int n, a[1000001]; int cont1, cont2, cont3; int s1, s2, s3; int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= n; i++) { if (a[i] == 1) cont1++; else if (a[i] == 2) cont2++; else cont3++; } s1 = cont1 + cont2; s2 = cont2 + cont3; s3 = cont1 + cont3; if (s1 <= s2 && s1 <= s3) cout << s1; else if (s2 <= s1 && s2 <= s3) cout << s2; else if (s3 <= s1 && s3 <= s2) cout << s3; else cout << "0"; return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
i = int(input()) l = list(map(int, input().split())) g = max(l.count(1), l.count(2), l.count(3)) print(i - g)
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int arr[4]; int main() { int n; cin >> n; int inp; for (int i = 0; i < n; i++) { cin >> inp; arr[inp]++; } cout << n - *max_element(arr, arr + 4) << endl; return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.io.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class A1008 { public static void main(String [] args) /*throws Exception*/ { InputStream inputReader = System.in; OutputStream outputReader = System.out; InputReader in = new InputReader(inputReader);//new InputReader(new FileInputStream(new File("input.txt")));new InputReader(inputReader); PrintWriter out = new PrintWriter(outputReader);//new PrintWriter(new FileOutputStream(new File("output.txt"))); Algorithm solver = new Algorithm(); solver.solve(in, out); out.close(); } } class Algorithm { void solve(InputReader ir, PrintWriter pw) { int n = ir.nextInt(); int [] a = new int[4]; for (int i = 0; i < n; i++) a[ir.nextInt()]++; if (a[1] >= a[2] && a[1] >= a[3]) pw.print(a[2] + a[3]); else if (a[2] >= a[1] && a[2] >= a[3]) pw.print(a[1] + a[3]); else pw.print(a[1] + a[2]); } private static void mergeSort(int[] array) { if(array.length == 1) return; int[] first = new int[array.length / 2]; int[] second = new int[array.length - first.length]; System.arraycopy(array, 0, first, 0, first.length); System.arraycopy(array, first.length, second, 0, second.length); mergeSort(first); mergeSort(second); merge(first, second, array); } private static void merge(int[] first, int[] second, int[] result) { int iFirst = 0; int iSecond = 0; int j = 0; while (iFirst < first.length && iSecond < second.length) { if (first[iFirst] < second[iSecond]) { result[j] = first[iFirst]; iFirst++; } else { result[j] = second[iSecond]; iSecond++; } j++; } System.arraycopy(first, iFirst, result, j, first.length - iFirst); System.arraycopy(second, iSecond, result, j, second.length - iSecond); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine(){ String fullLine; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return null; } String [] toArray() { return nextLine().split(" "); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
def sequence(lst): a = [0, 0, 0] for elem in lst: if elem == 1: a[0] += 1 elif elem == 2: a[1] += 1 else: a[2] += 1 return len(lst) - max(a) n = int(input()) b = [int(i) for i in input().split()] print(sequence(b))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int a; int num[3] = {0}; int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a; num[a - 1]++; } printf("%d\n", n - max(num[0], max(num[1], num[2]))); return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; int n, I = 0, II = 0, III = 0; cin >> n; for (int i = 0; i < n; i++) { int a; cin >> a; if (a == 1) { I++; } else if (a == 2) { II++; } else { III++; } } int ans = n - max(I, max(II, III)); cout << ans << endl; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.util.*; import java.io.*; public class Main{ int a; public static void main(String args[]) { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); int a[]=new int[t]; int temp[]=new int[4]; TreeMap<Integer,Integer>T=new TreeMap<>(); for(int i=0;i<t;++i) { a[i]=scan.nextInt(); temp[a[i]]++; } Arrays.sort(temp); System.out.print(temp[1]+temp[2]); } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int a = 0; int b = 0; int c = 0; for (int i = 0; i < n; i++) { int m; cin >> m; if (m == 1) { a++; } if (m == 2) { b++; } if (m == 3) { c++; } } int max = a; if (b > max) { max = b; } if (c > max) { max = c; } cout << n - max << endl; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; inline int read() { char ch = getchar(); if (!(~ch)) return 0; int f = 1; while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } int x = 0; while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); } return x * f; } int a[4]; int main() { int n = read(); for (register int i = 0; i < n; ++i) a[read()]++; printf("%d\n", n - *max_element(a + 1, a + 4)); return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n = int(input()) arr = list(map(int,input().split())) one = arr.count(1) two = arr.count(2) three = arr.count(3) print( min(n-one,n-two,n-three))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; template <typename T> void Print(const vector<T> &v) { for (int i = 0; i + 1 < v.size(); i++) cout << v[i] << " "; cout << v.back() << "\n"; } void solve() { int n; cin >> n; int one, two, three; one = two = three = 0; int temp; for (int i = 0; i < n; i++) { cin >> temp; if (temp == 1) one++; else if (temp == 2) two++; else three++; } int maxx = -1; maxx = max(one, two); maxx = max(maxx, three); printf("%d\n", n - maxx); } int main() { int tc = 1; for (int t = 1; t <= tc; t++) { solve(); } return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
#include <bits/stdc++.h> using namespace std; int n, num[4]; int main() { scanf("%d", &n); int i; for (i = 1; i <= n; i++) { int x; scanf("%d", &x); num[x]++; } int maxn = num[1], sum = num[1] + num[2] + num[3]; if (num[2] > maxn) maxn = num[2]; if (num[3] > maxn) maxn = num[3]; printf("%d", sum - maxn); return 0; }
CPP
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.util.*; public class Solution_1 { public static void main(String[] args) { // solution start :-) Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; int c1 = 0; int c2 = 0; int c3 = 0; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); if(a[i]==1) c1++; else if(a[i]==2) c2++; else c3++; } int ar[] = new int[3]; ar[0] = c1; ar[1] = c2; ar[2] = c3; Arrays.sort(ar); System.out.println(ar[0]+ar[1]); // solution end \(^-^)/ // | // / \ } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n=int(input()) s=[int(i) for i in input().split()] a=s.count(1) b=s.count(2) c=s.count(3) r=min(a+b,a+c,b+c) print(r)
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n = int(input()) a = list(map(int, input().split())) ans = n - max([a.count(x) for x in [1, 2, 3]]) print(ans)
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.util.Scanner; import java.io.*; public class p52a { public static void main(String[] args) throws Exception { p52aa in = new p52aa(System.in); int n = in.nextLong(); int[] all = new int[n]; for (int i = 0; i < all.length; i++) { all[i] = in.nextLong(); } int min = n; int c = 0; for (int i = 0; i < all.length; i++) { if(all[i] != 1) c++; } min = Math.min(c, min); c = 0; for (int i = 0; i < all.length; i++) { if(all[i] != 2) c++; } min = Math.min(c, min); c = 0; for (int i = 0; i < all.length; i++) { if(all[i] != 3) c++; } min = Math.min(c, min); System.out.println(min); } } //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); class p52aa { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public p52aa(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextLong() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public char nextChar() throws Exception { char ret = ' '; byte c = read(); while (c <= ' ') c = read(); ret = (char)c; return ret; } public String nextString() throws Exception { StringBuffer ret = new StringBuffer(); byte c = read(); while (c <= ' ') c = read(); do { ret = ret.append((char)c); c = read(); } while (c > ' '); return ret.toString(); } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
n=int(input()) ar=list(map(int,input().split())) print(n-max([ar.count(i) for i in range(1,4)]))
PYTHON3
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.util.*; import java.io.*; public class testa { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] tot = new int[4]; for(int i=0; i<n; i++) tot[Integer.parseInt(st.nextToken())]++; int res = n-Math.max(tot[1], Math.max(tot[2],tot[3])); System.out.printf("%d%n", res); } }
JAVA
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3). Output Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Examples Input 9 1 3 2 2 2 1 1 2 3 Output 5 Note In the example all the numbers equal to 1 and 3 should be replaced by 2.
2
7
import java.io.*; import java.io.ObjectInputStream.GetField; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; public class _A_ { public static void main(String[] args) throws IOException{ BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); int m = Integer.parseInt(stdin.readLine()); String s = stdin.readLine(); String [] f = s.split(" "); int [] a = new int[3]; int max = 0,d = 0; for (int i = 0; i < f.length; i++) { int y = Integer.parseInt(f[i]); a[y-1]++; } for (int i = 0; i < a.length; i++) { d += a[i]; max = Math.max(max, a[i]); } System.out.println(d - max); } }
JAVA