// 完美的服务.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
const int maxn = 50000;
struct edge {
int to;
int next;
};
edge edges[maxn];//前向星存图
int h[maxn];
int tot = 0;
int d[maxn][3];
//dp[x][0]dp[x][0]:x是服务器,孩子是不是服务器均可
//dp[x][1]dp[x][1]:x不是服务器,x的父亲是服务器,x的孩子不能是服务器
//dp[x][2]dp[x][2]:x不是服务器且x的父亲不是服务器,x的孩子必须有且仅有一个是服务器。
void addedge(int x, int y)
{
edges[++tot].next = h[x];
edges[tot].to = y;
h[x] = tot;
}
void dfs(int root,int father)
{
d[root][0] = 1;
d[root][1] = 0;
d[root][2] = 123154;
for (int i = h[root];i;i = edges[i].next)
{
int v = edges[i].to;
if (v == father)continue;
dfs(v, root);
d[root][0] += min(d[v][0], d[v][1]);
d[root][1] += d[v][2];
}
for (int i = h[root];i;i = edges[i].next)
{
int v = edges[i].to;
if (v == father)continue;
d[root][2] = min(d[root][2], d[root][1] - d[v][2] + d[v][0]);
}
}
int main()
{
int n;
while (cin >> n)
{
memset(h, 0, sizeof(h));
for (int i = 1;i < n;i++)
{
int a, b;
cin >> a >> b;
addedge(a, b);
addedge(b, a);
}
dfs(1, 0);
cout << min(d[1][0], d[1][2]) << endl;
int opt;
cin >> opt;
if (opt == -1)
{
break;
}
}
}
完美的服务
最新推荐文章于 2024-01-27 00:57:51 发布