NOI模拟(5.8) HNOID2T3 道路 (bzoj5290)

道路

题目背景:

5.8 模拟 HNOI2018D2T3

分析:记忆化搜索

 

没什么难度的裸DP,直接定义dp[i][j][k]表示以i为根的子树中,i到跟有j条没有修过的公路,k条没有修过的铁路,然后如果是乡村则直接返回计算过的答案,否则

dp[i][j][k] = std::min(dp[lc[i]][j][k] + dp[rc[i]][j][k + 1]

            , dp[lc[i]][j+ 1][k], dp[rc[i]][j][k])

(lc[i]表示i的公路下的儿子,rc[i]是铁路下的)

直接记忆化搜索就好了,注意要开long long

时间复杂度O(n * 40 * 40)

 

Source:

 

/*
    created by scarlyw
*/
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <cctype>
#include <vector>
#include <set>
#include <queue>
#include <ctime>
#include <bitset>
 
inline char read() {
    static const int IN_LEN = 1024 * 1024;
    static char buf[IN_LEN], *s, *t;
    if (s == t) {
        t = (s = buf) + fread(buf, 1, IN_LEN, stdin);
        if (s == t) return -1;
    }
    return *s++;
}
 
///*
template<class T>
inline void R(T &x) {
    static char c;
    static bool iosig;
    for (c = read(), iosig = false; !isdigit(c); c = read()) {
        if (c == -1) return ;
        if (c == '-') iosig = true; 
    }
    for (x = 0; isdigit(c); c = read()) 
        x = ((x << 2) + x << 1) + (c ^ '0');
    if (iosig) x = -x;
}
//*/

const int OUT_LEN = 1024 * 1024;
char obuf[OUT_LEN];
char *oh = obuf;
inline void write_char(char c) {
	if (oh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf;
	*oh++ = c;
}


template<class T>
inline void W(T x) {
	static int buf[30], cnt;
	if (x == 0) write_char('0');
	else {
		if (x < 0) write_char('-'), x = -x;
		for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;
		while (cnt) write_char(buf[cnt--]);
	}
}

inline void flush() {
	fwrite(obuf, 1, oh - obuf, stdout), oh = obuf;
}
 
/*
template<class T>
inline void R(T &x) {
    static char c;
    static bool iosig;
    for (c = getchar(), iosig = false; !isdigit(c); c = getchar())
        if (c == '-') iosig = true; 
    for (x = 0; isdigit(c); c = getchar()) 
        x = ((x << 2) + x << 1) + (c ^ '0');
    if (iosig) x = -x;
}
//*/

const int MAXN = 20000 + 10;
const int MAXX = 40 + 2;

int n;
long long dp[MAXN][MAXX][MAXX];
int a[MAXN], b[MAXN], c[MAXN], lc[MAXN], rc[MAXN];

inline long long calc(int id, int x, int y) {
    return (long long)c[id] * (a[id] + x) * (b[id] + y);
}

inline long long dfs(int cur, int x, int y) {
    if (cur < 0) return calc(-cur, x, y);
    if (dp[cur][x][y] != -1) return dp[cur][x][y];
    dp[cur][x][y] = std::min(dfs(lc[cur], x, y) + dfs(rc[cur], x, y + 1)
        , dfs(lc[cur], x + 1, y) + dfs(rc[cur], x, y));
    return dp[cur][x][y];
}

inline void read_in() {
    R(n), memset(dp, -1, sizeof(dp));
    for (int i = 1; i < n; ++i) R(lc[i]), R(rc[i]);
    for (int i = 1; i <= n; ++i) R(a[i]), R(b[i]), R(c[i]);
}

int main() {
    freopen("road.in", "r", stdin);
    freopen("road.out", "w", stdout);
    read_in();
    std::cout << dfs(1, 0, 0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/scar_lyw/article/details/80259180