# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
956560 | KK_1729 | Connecting Supertrees (IOI20_supertrees) | C++17 | 0 ms | 0 KiB |
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 "supertrees.h"
#include <vector>
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
struct UFDS {
vector<int> link, siz;
UFDS(int n) : link(n), siz(n, 1) { iota(link.begin(), link.end(), 0); } //each element as its own subset, with size 1
int findRoot(int x) {
if(x == link[x]) return x;
return link[x] = findRoot(link[x]);
/*
A shorter way of writing the following is:
return x == link[x] ? x : link[x] = findRoot(link[x]);
*/
}
bool same(int x, int y) { return findRoot(x) == findRoot(y); }
bool unite(int x, int y) {
x = findRoot(x);
y = findRoot(y);
if (x == y)
return false;
if (siz[x] < siz[y]) swap(x, y);
siz[x] += siz[y];
link[y] = x;
return true;
}
int size(int x) { return siz[findRoot(x)]; }
};
int construct(std::vector<std::vector<int>> p) {
int n = p.size();
std::vector<std::vector<int>> answer;
for (int i = 0; i < n; i++) {
std::vector<int> row;
row.resize(n);
answer.push_back(row);
}
UFDS ds(n);
vector<int> cycle(n);
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j){
if (i == j) continue;
if (p[i][j] == 2){
ds.unite(i, j);
cyc[i] = 1;
}
if (p[i][j] == 1) cycle[i] = 0;
if (p[i][j] == 0){
if (ds.same(i, j)) return 0;
}
}
}
vector<vector<int>> parents(n);
for (int i = 0; i < n; ++i) parents[ds.findRoot(i)].push_back(i);
for (auto item: parents){
int u = item.size();
vector<int> cyc;
vector<int> normal;
for (auto x: item){
if (cycle[x]) cyc.pb(x);
else normal.pb(x);
}
int v = normal.size();
FOR(i,0,v-1){
answer[normal[i]][normal[i+1]] = 1;
answer[normal[i+1]][normal[i]] = 1;
}
if (cyc.size() <= 2) return 0;
v = cyc.size();
FOR(i,0,v-1){
answer[cyc[i]][cyc[i+1]] = 1;
answer[cyc[i+1]][cyc[i]] = 1;
}
answer[cyc[0]][cyc[v-1]] = 1;
answer[cyc[v-1]][cyc[0]] = 1;
answer[normal[0]][cyc[0]] = 1;
answer[cyc[0]][normal[0]] = 1;
}
build(answer);
return 1;
}