C. Valera and Elections
dp + dfs
题意
一棵树, 树边有的有标记有的没标记, 如果选择一个点, 能将点到根最短路径上的边全部打上标记, 问最少选几个点, 使所有的边都被打上标记.
思路
\(f[i]:表示最少需要选择的点数使以i为根的子树都被标记.\)
因此如果u
的邻结点j
, 且f[j]==0 && i, j 之间的边未被标记
, j
应该被放入答案中.
代码
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 2e5 + 10, M = N;
int h[N], ne[M], e[M], w[M], idx;
int ans[N], cnt;
int f[N];
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
void dfs(int u, int fa) {
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
dfs(j, u);
if (f[j] == 0) {
if (w[i]) {
ans[++cnt] = j;
f[u]++;
}
} else {
f[u]++;
}
}
}
int main() {
memset(h, -1, sizeof h);
IO;
//freopen("in.txt", "r", stdin);
int n;
cin >> n;
for (int i = 0; i < n - 1; ++i) {
int a, b, c;
cin >> a >> b >> c;
if (c == 1) {
add(a, b, 0);
add(b, a, 0);
} else {
add(a, b, 1);
add(b, a, 1);
}
}
dfs(1, -1);
cout << cnt << '\n';
for (int i = 1; i <= cnt; ++i) cout << ans[i] << ' ';
cout << '\n';
return 0;
}