题面
解法
给个链接,贪心和树形dp讲得挺到位的
反正我觉得贪心比较好写,也挺好理解的
时间复杂度:\(O(Tn)\)
代码
#include <bits/stdc++.h>
#define N 10010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == ‘-‘) f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - ‘0‘, c = getchar(); x *= f;
}
struct Edge {
int next, num;
} e[N * 3];
int cnt, vis[N], ans[N];
void add(int x, int y) {
e[++cnt] = (Edge) {e[x].next, y};
e[x].next = cnt;
}
void dfs(int x, int fa) {
ans[x] = 1; int tot = 0;
for (int p = e[x].next; p; p = e[p].next) {
int k = e[p].num;
if (k == fa) continue; dfs(k, x);
ans[x] += ans[k];
if (!vis[k]) tot++;
}
if (tot >= 2) ans[x] -= 2, vis[x] = 1;
if (tot == 1) ans[x]--;
}
int main() {
int T; read(T);
while (T--) {
int n; read(n); cnt = n;
for (int i = 1; i <= n; i++)
e[i].next = 0, vis[i] = 0, ans[i] = 0;
for (int i = 1; i < n; i++) {
int x, y; read(x), read(y);
add(x, y), add(y, x);
}
dfs(1, 0); cout << ans[1] << "\n";
}
return 0;
}
原文地址:https://www.cnblogs.com/copperoxide/p/9477047.html
时间: 2024-10-13 09:52:34