您的位置:首页 > 其它

BZOJ1907 树的路径覆盖

2015-02-23 19:27 411 查看
ydc题解上写着贪心,后来又说是树形dp。。。可惜看不懂(顺便骗三连)

其实就是每个叶子开始拉一条链,从下面一路走上来,遇到能把两条链合起来的就合起来就好了。

/**************************************************************
Problem: 1907
User: rausen
Language: C++
Result: Accepted
Time:112 ms
Memory:1396 kb
****************************************************************/

#include <cstdio>
#include <cstring>

using namespace std;
const int N = 1e4 + 5;

struct edge {
int next, to;
edge() {}
edge(int _n, int _t) : next(_n), to(_t) {}
} e[N << 1];

struct tree_node {
int fa, ans, used;
} tr
;

int n;
int first
, tot;

inline int read() {
int x = 0;
char ch = getchar();
while (ch < '0' || '9' < ch)
ch = getchar();
while ('0' <= ch && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x;
}

void Add_Edges(int x, int y) {
e[++tot] = edge(first[x], y), first[x] = tot;
e[++tot] = edge(first[y], x), first[y] = tot;
}

#define y e[x].to
int dfs(int p) {
int x, cnt = 0;
tr[p].ans = 1, tr[p].used = 0;
for (x = first[p]; x; x = e[x].next)
if (y != tr[p].fa) {
tr[y].fa = p;
dfs(y);
tr[p].ans += tr[y].ans;
if (!tr[y].used) ++cnt;
}
if (cnt >= 2) tr[p].ans -= 2, tr[p].used = 1;
else if (cnt == 1) --tr[p].ans;
}
#undef y

int main() {
int i, T;
T = read();
while (T--) {
n = read(), tot = 0;
memset(first, 0, sizeof(first));
for (i = 1; i < n; ++i)
Add_Edges(read(), read());
dfs(1);
printf("%d\n", tr[1].ans);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: