题意:一个树形网络,叶子是客户端,其他的是服务器。现在只有一台服务器提供服务,使得不超k的客户端流畅,但是其他的就不行了,
现在要在其他结点上安装服务器,使得所有的客户端都能流畅,问最少要几台。
析:首先这是一棵无根树,我们可以转成有根树,正好可以用原来的那台服务器当根,然后在不超过 k 的叶子结点,就可以不用考虑,
然后要想最少,那么就尽量让服务器覆盖尽量多的叶子,我们可以从最低的叶子结点开始向上查找最长的距离当服务器,这样是最优的。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <unordered_map> #include <unordered_set> #define debug() puts("++++"); #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1e3 + 5; const int mod = 2000; const int dr[] = {-1, 1, 0, 0}; const int dc[] = {0, 0, 1, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } vector<int> G[maxn], node[maxn]; int f[maxn]; bool cover[maxn]; void dfs(int u, int fa, int cnt){ f[u] = fa; if(1 == G[u].size() && cnt > m) node[cnt].push_back(u); for(int i = 0; i < G[u].size(); ++i) if(G[u][i] != fa) dfs(G[u][i], u, cnt+1); } void dfs2(int u, int fa, int cnt){ cover[u] = true; if(cnt >= m) return ; for(int i = 0; i < G[u].size(); ++i){ int v = G[u][i]; if(v == fa) continue; dfs2(v, u, cnt+1); } } int solve(){ memset(cover, false, sizeof cover); int ans = 0; for(int j = n-1; j > m; --j) for(int i = 0; i < node[j].size(); ++i){ int v = node[j][i]; if(cover[v]) continue; for(int k = 0; k < m; ++k) v = f[v]; dfs2(v, -1, 0); ++ans; } return ans; } int main(){ int T; cin >> T; while(T--){ int s; scanf("%d %d %d", &n, &s, &m); for(int i = 1; i <= n; ++i) G[i].clear(), node[i].clear(); for(int i = 1; i < n; ++i){ int u, v; scanf("%d %d", &u, &v); G[u].push_back(v); G[v].push_back(u); } dfs(s, -1, 0); printf("%d ", solve()); } return 0; }