Skip to content

Commit 283b253

Browse files
Merge pull request #3168 from cpinitiative/ryanchou-dev-patch-2
c++ -> closing the farm (gold)
2 parents be25050 + 804fc85 commit 283b253

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

solutions/usaco-646.mdx

+82
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,89 @@ Note: The video solution might not be the same as other solutions. Code in C++.
2626
**Time Complexity:** $\mathcal{O}(V \cdot E \cdot \alpha(n)))$
2727

2828
<LanguageSection>
29+
<CPPSection>
2930

31+
```cpp
32+
#include <bits/stdc++.h>
33+
using namespace std;
34+
35+
//BeginCodeSnip{DSU}
36+
struct DSU {
37+
vector<int> e;
38+
DSU(int N): e(N, -1) { }
39+
40+
// get representive component (uses path compression)
41+
int get(int x) { return e[x] < 0 ? x : e[x] = get(e[x]); }
42+
43+
bool same_set(int a, int b) { return get(a) == get(b); }
44+
45+
int size(int x) { return -e[get(x)]; }
46+
47+
// union by size
48+
bool unite(int x, int y) {
49+
x = get(x), y = get(y);
50+
if (x == y) return false;
51+
if (e[x] > e[y]) swap(x, y);
52+
e[x] += e[y];
53+
e[y] = x;
54+
return true;
55+
}
56+
};
57+
//EndCodeSnip
58+
59+
int main() {
60+
freopen("closing.in", "r", stdin);
61+
int n, m;
62+
cin >> n >> m;
63+
64+
vector<vector<int>> adj(n);
65+
for (int i = 0; i < m; i++) {
66+
int u, v;
67+
cin >> u >> v;
68+
u--;
69+
v--;
70+
adj[u].push_back(v);
71+
adj[v].push_back(u);
72+
}
73+
74+
// conn[i] = whether the ith farm is closed
75+
vector<bool> conn(n);
76+
vector<int> rev(n);
77+
for (int i = 0; i < n; i++) {
78+
cin >> rev[i];
79+
rev[i]--;
80+
}
81+
82+
DSU dsu(n);
83+
reverse(rev.begin(), rev.end());
84+
85+
conn[rev[0]] = 1;
86+
// one node is always connected
87+
vector<string> ans = {"YES"};
88+
89+
// connected components
90+
int cc = 1;
91+
for (int i = 1; i < n; i++) {
92+
cc++;
93+
conn[rev[i]] = 1;
94+
for (int j : adj[rev[i]]) {
95+
if (conn[j]) {
96+
if (dsu.unite(j, rev[i])) {
97+
cc--;
98+
}
99+
}
100+
}
101+
ans.push_back(cc == 1 ? "YES" : "NO");
102+
}
103+
reverse(ans.begin(), ans.end());
104+
105+
freopen("closing.out", "w", stdout);
106+
for (const string& i : ans) {
107+
cout << i << '\n';
108+
}
109+
}
110+
```
111+
</CPPSection>
30112
<PySection>
31113
32114
```py

0 commit comments

Comments
 (0)