在这里插入图片描述
UVA1218
定义Son[i]Son[i]为第ii个节点的子节点集
dp[i]dp[i]为以ii为根节点的最少服务器需求量

  1. dp[i][0]dp[i][0]为将第ii个节点作为服务器的时的情况,即它的子节点既可以是服务器,又可以是客户端。
  2. dp[i][1]dp[i][1]为第ii个节点为客户端且它的父节点为服务器的情况,即它的子节点只能是客户端。(一个客户端只能且必须能和一个服务器直接相连)
  3. dp[i][2]dp[i][2]为第ii个节点为客户端且它的父节点也为客户端的情况,即i有且只有一个子节点是服务器。

转移方程
VVii的子节点集合

  1. dp[i][0]=(vVmin(dp[v][0],dp[v][1]))+1dp[i][0]=(\sum\limits_{v\in V}{min(dp[v][0],dp[v][1])})+1
  2. dp[i][1]=vVdp[v][2]dp[i][1]=\sum\limits_{v\in V}{dp[v][2]}
  3. dp[i][2]=min(dp[vk][0]+vVvkdp[v][2])=min(dp[vk][0]+dp[i][1]dp[vk][2]dp[i][2]=min(dp[v_k][0]+\sum\limits_{v\in {V-v_k}}{dp[v][2]})=min(dp[v_k][0]+dp[i][1]-dp[v_k][2]
    即枚举ii的每一个子节点作为服务器的情况。

AC代码

#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
#include<map>
using namespace std;
int N, Status;
vector<int> Son[10001];
int dp[10001][3];
void Clear() {
	for (int i = 1; i <= N; ++i) {
		Son[i].clear();
	}
}
void Input() {	
	cin >> N;
	Clear();
	for (int i = 1; i < N; ++i) {
		int x, y;
		cin >> x >> y;
		Son[x].push_back(y);
		Son[y].push_back(x);
	}
}
void DP(int Root,int Father) {
	dp[Root][0] = 1;
	dp[Root][1] = 0;
	dp[Root][2] = 10000;//inf
	for (auto SonIt = Son[Root].cbegin(); SonIt != Son[Root].cend(); ++SonIt) {
		if (*SonIt == Father) {
			continue;
		}
		DP(*SonIt, Root);
		dp[Root][0] += min(dp[*SonIt][0], dp[*SonIt][1]);
		dp[Root][1] += dp[*SonIt][2];
	}
	for (auto SonIt = Son[Root].cbegin(); SonIt != Son[Root].cend(); ++SonIt) {
		if (*SonIt == Father) {
			continue;
		}
		dp[Root][2] = min(dp[Root][2], dp[Root][1] - dp[*SonIt][2] + dp[*SonIt][0]);
	}
}
int main() {
	while (true) {
		Input();
		DP(1, -1);
		cout <<min(dp[1][0],dp[1][2]) << endl;
		cin >> Status;
		if (Status == -1) {
			break;
		}
	}
	return 0;
}
posted on 2020-01-19 17:00  SCU_GoodGuy  阅读(288)  评论(0)    收藏  举报