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;
const int N = 30000 * 20 + 1;
void solve() {
int n, k;
cin >> n >> k;
vector<int> l(2 * n), r(2 * n), s(2 * n);
vector idx(2, vector<set<int>>(n));
vector cnt(2, vector<int>(n));
for (int i = 0; i < 2 * n; i++) {
cin >> l[i] >> r[i] >> s[i];
l[i]--, r[i]--;
idx[0][l[i]].insert(i);
idx[1][r[i]].insert(i);
cnt[0][l[i]]++, cnt[1][r[i]]++;
}
queue<pair<int, int>> q;
for (int i = 0; i < n; i++) {
if (cnt[0][i] <= 1) {
q.push({i, 0});
}
if (cnt[1][i] <= 1) {
q.push({i, 1});
}
}
vector<bool> deleted(2 * n, false);
vector used(2, vector<bool>(n, false));
vector g(2, vector<vector<int>>(2 * n));
int diff = 0;
while (!q.empty()) {
auto [i, t] = q.front();
q.pop();
if (cnt[t][i] == 0) {
cout << "NO\n";
return;
}
int j = *idx[t][i].begin();
if (t == 0) {
diff += s[j];
} else {
diff -= s[j];
}
used[t][i] = true;
deleted[j] = true;
cnt[0][l[j]]--;
cnt[1][r[j]]--;
idx[0][l[j]].erase(j);
idx[1][r[j]].erase(j);
if (cnt[0][l[j]] == 1) {
q.push({l[j], 0});
}
if (cnt[1][r[j]] == 1) {
q.push({r[j], 1});
}
}
for (int i = 0; i < 2 * n; i++) {
if (!deleted[i]) {
if (!used[0][l[i]]) {
g[0][i].push_back(l[i]);
g[1][l[i]].push_back(i);
}
if (!used[1][r[i]]) {
g[0][i].push_back(r[i] + n);
g[1][r[i] + n].push_back(i);
}
}
}
int cost0 = 0;
vector<int> d;
int sum = 0;
for (int i = 0; i < 2 * n; i++) {
if (!deleted[i]) {
sum += s[i];
}
}
for (int i = 0; i < 2 * n; i++) {
if (deleted[i]) {
continue;
}
int j = i, par = -1, step = 0, ss = 0, c0 = 0, c1 = 0;
bool first = true;
while (first || j != i || step != 0) {
if (step == 0) {
deleted[j] = true;
if (ss == 0) {
c0 += s[j];
} else {
c1 += s[j];
}
ss ^= 1;
}
first = false;
if (g[step][j][0] == par) {
par = j;
j = g[step][j][1];
} else {
par = j;
j = g[step][j][0];
}
step ^= 1;
}
cost0 += c0;
d.push_back(c1 - c0);
}
bitset<N> b;
b[cost0] = 1;
for (int v : d) {
if (v < 0) {
b |= b >> (-v);
} else {
b |= b << v;
}
}
for (int i = 0; i <= sum; i++) {
int j = sum - i;
if (b[i] && abs(i - j + diff) <= k) {
cout << "YES\n";
return;
}
}
cout << "NO\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
}
# | 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... |