This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
int h, w;
const int MAXN = 1.1e6;
int parent[MAXN];
int sz[MAXN];
int highest[MAXN];
vector<vector<bool>> aa, bb;
int get(int i, int j) {
return w * i + j;
}
void init() {
for (int i = 0; i < h; i ++)
for (int j = 0; j < w; j ++) {
int xx = get(i, j);
parent[xx] = xx;
sz[xx] = 1;
highest[xx] = i;
}
}
int find(int u) {
if (parent[u] == u)
return u;
return parent[u] = find(parent[u]);
}
int find(int i, int j) {
return find(get(i, j));
}
void unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return;
if (sz[a] > sz[b])
swap(a, b);
highest[b] = max(highest[b], highest[a]);
sz[b] += sz[a];
parent[a] = b;
}
void solve() {
// set up components
init();
for (int i = 0; i < h; i ++)
for (int j = 0; j < w - 1; j ++)
if (aa[i][j])
unite(get(i, j), get(i, j + 1));
for (int i = 0; i < h - 1; i ++)
for (int j = 0; j < w; j ++)
if (bb[i][j])
unite(get(i, j), get(i + 1, j));
int t; cin >> t;
set<pair<int, int>> components;
for (int i = 0; i < t; i ++) {
int x, y; cin >> x >> y;
x --; y --;
int xx = find(x, y);
components.insert({highest[xx], xx});
}
// while not all together, merge components
int cost = 0;
int last = -1;
while (components.size() > 1) {
pair<int, int> cur = *components.begin();
components.erase(cur);
int i = cur.first;
for (int j = 0; j < w; j ++) {
int xx = find(i, j);
int curheight = highest[xx];
components.erase({curheight, xx});
}
// merge the top row
for (int j = 0; j < w - 1; j ++)
unite(find(i, j), find(i, j + 1));
// now add back
cost ++;
components.insert({highest[find(i, 0)], find(i, 0)});
if (last == i) {
cost = -1;
break;
}
last = i;
}
cout << cost << endl;
}
int main() {
cin >> h >> w;
int q; cin >> q;
aa.resize(h);
for (int i = 0; i < h; i ++) {
aa[i].resize(w - 1);
string s; cin >> s;
for (int j = 0; j < w - 1; j ++)
aa[i][j] = (s[j] == '1') ? 1 : 0;
}
bb.resize(h - 1);
for (int i = 0; i < h - 1; i ++) {
bb[i].resize(w);
string s; cin >> s;
for (int j = 0; j < w; j ++)
bb[i][j] = (s[j] == '1') ? 1 : 0;
}
for (int i = 0; i < h; i ++) {
int cc; cin >> cc;
}
while (q --)
solve();
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |