HDU - 5854 K-th value 二分 + dp (看题解)

HDU - 5854

二分答案之后, 设答案值为v,    x为小于等于v的边的数量, y为大于v的边的数量,

列出方程 x > (x + y) / k    ==  (k - 1) * x - y > 0, 感觉有点像线性规划的样子。

然后用树形dp去check, 判合不合法的时候可以优化成一个R, 但是不优化也能过。

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)
#include<bits/stdc++.h>
#define LL long long
#define LD long double
#define ull unsigned long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ALL(x) (x).begin(), (x).end()
#define fio ios::sync_with_stdio(false); cin.tie(0);

using namespace std;

const int N = 1e5 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = (int)1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1);

template<class T, class S> inline void add(T &a, S b) {a += b; if(a >= mod) a -= mod;}
template<class T, class S> inline void sub(T &a, S b) {a -= b; if(a < 0) a += mod;}
template<class T, class S> inline bool chkmax(T &a, S b) {return a < b ? a = b, true : false;}
template<class T, class S> inline bool chkmin(T &a, S b) {return a > b ? a = b, true : false;}

//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int n;
int L, R, K;
int dp[N][51];

vector<PII> G[N];

struct Edge {
    int u, v, w;
    void read() {
        scanf("%d%d%d", &u, &v, &w);
    }
} e[N];

bool dfs(int u, int fa) {
    for(int i = 1; i <= R; i++) {
        dp[u][i] = -inf;
    }
    dp[u][0] = 0;
    for(auto &e : G[u]) {
        int v = e.se, w = e.fi;
        if(v == fa) continue;
        if(dfs(v, u)) return true;
        for(int i = 0; i < R; i++) {
            for(int j = max(0, L - i - 1); i + j + 1 <= R; j++) {
                if(dp[u][i] + dp[v][j] + w > 0) {
                    return true;
                }
            }
        }
        for(int i = 1; i <= R; i++) {
            chkmax(dp[u][i], dp[v][i - 1] + w);
        }
    }
    return false;
}

bool check(int val) {
    for(int i = 1; i <= n; i++) {
        G[i].clear();
    }
    for(int i = 1; i < n; i++) {
        if(e[i].w <= val) {
            G[e[i].u].push_back(mk(K - 1, e[i].v));
            G[e[i].v].push_back(mk(K - 1, e[i].u));
        }
        else {
            G[e[i].u].push_back(mk(-1, e[i].v));
            G[e[i].v].push_back(mk(-1, e[i].u));
        }
    }
    return dfs(1, 0);
}

int main() {
    int T; scanf("%d", &T);
    while(T--) {
        scanf("%d", &n);
        for(int i = 1; i < n; i++) {
            e[i].read();
        }
        scanf("%d%d%d", &K, &L, &R);
        int low = 1, high = 1000000000, mid, ans = -1;
        while(low <= high) {
            mid = low + high >> 1;
            if(check(mid)) ans = mid, high = mid - 1;
            else low = mid + 1;
        }
        printf("%d\n", ans);
    }
    return 0;
}

/*
(k - 1) * x - y > 0
*/

猜你喜欢

转载自www.cnblogs.com/CJLHY/p/11437381.html