重建道路:树形DP

传送门

题目描述

重建道路:树形DP

分析

去年写的题,今天看猫猫博客的时候又想起来了这道题,回顾一些细节
f [ i ] [ j ] f[i][j] f[i][j]表示以 i i i为根节点保留 j j j个节点所要砍掉的道路数量,然后跑一下树形背包即可

代码

#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 200;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
	char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
	while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int h[N],ne[N],e[N],idx;
int in[N];
int f[N][N];
int sz[N];
int n,p;

void add(int x,int y){
	ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}

void dfs(int u){
	sz[u] = 1;
	for(int i = h[u];~i;i = ne[i]){
		int j = e[i];
		dfs(j);
		sz[u] += sz[j];
		for(int k = sz[u];k;k--)
			for(int l = 1;l < k;l++)
				f[u][k] = min(f[u][k],f[u][k - l] + f[j][l] - 1);
	}
}

int main() {
	memset(h,-1,sizeof h);
	read(n),read(p);
	for(int i = 1;i < n;i++){
		int x,y;
		read(x),read(y);
		add(x,y);
		in[x]++;
	}
	memset(f,0x3f,sizeof f);
	for(int i = 1;i <= n;i++) f[i][1] = in[i];
	dfs(1);
	int ans = f[1][p];
	for(int i = 2;i <= n;i++) ans = min(ans,f[i][p] + 1);
	di(ans);
	return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/


上一篇:编程练习


下一篇:【树形dp】洛谷 P2014 [CTSC1997]选课