AtCoder Regular Contest 146 D >=<
考虑直接增量构造。
把条件拆成形如 \(a_u \ge x\) 时 \(a_v \gets \max(a_v, y)\),连边,跑类似一个 spfa 的东西,就行了。
这样一定能构造出一组和最小的解。
启示:二元关系,一般考虑建图。
code
// Problem: D - >=<
// Contest: AtCoder - AtCoder Regular Contest 146
// URL: https://atcoder.jp/contests/arc146/tasks/arc146_d
// Memory Limit: 1024 MB
// Time Limit: 4000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef pair<ll, ll> pii;
const int maxn = 1000100;
ll n, m, q, a[maxn], head[maxn], len;
bool vis[maxn];
struct E {
ll v, x, y;
E(ll a = 0, ll b = 0, ll c = 0) : v(a), x(b), y(c) {}
};
vector<E> G[maxn];
void solve() {
scanf("%lld%lld%lld", &n, &m, &q);
while (q--) {
ll u, v, x, y;
scanf("%lld%lld%lld%lld", &u, &x, &v, &y);
G[u].pb(v, x, y);
G[v].pb(u, y, x);
G[u].pb(v, x + 1, y + 1);
G[v].pb(u, y + 1, x + 1);
}
queue<int> q;
for (int i = 1; i <= n; ++i) {
a[i] = 1;
q.push(i);
vis[i] = 1;
sort(G[i].begin(), G[i].end(), [&](E a, E b) {
return a.x > b.x;
});
}
while (q.size()) {
int u = q.front();
q.pop();
vis[u] = 0;
while (G[u].size() && a[u] >= G[u].back().x) {
E e = G[u].back();
G[u].pop_back();
ll v = e.v, y = e.y;
if (a[v] < y) {
a[v] = y;
if (!vis[v]) {
vis[v] = 1;
q.push(v);
}
}
}
}
ll ans = 0;
for (int i = 1; i <= n; ++i) {
if (a[i] > m) {
puts("-1");
return;
}
ans += a[i];
}
printf("%lld\n", ans);
}
int main() {
int T = 1;
// scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}