昨晚随便玩玩搞个div3结果浪翻了……
强烈谴责D题hack数据卡常
考虑到本题中所要求的最短距离不会大于2,所以我们可以把所有结点到$1$的距离通过对$3$取模分类,考虑到直接自顶向下贪心不满足局部最优解可以推出全局最优解,所以我们可以自下向上这样可以考虑到所有条件。我们处理出一个结点$x$所有儿子$y$的取模后的距离的最小值$dis$,那么一个结点向$1$连一条边的充要条件就是:
$dis == 0 && x != 1 && fa != 1$
时间复杂度$O(n)$。
Code:
#include#include using namespace std;const int N = 2e5 + 5;int n, ans = 0, tot = 0, head[N];struct Edge { int to, nxt;} e[N << 1];inline void add(int from, int to) { e[++tot].to = to; e[tot].nxt = head[from]; head[from] = tot;}inline void read(int &X) { X = 0; char ch = 0; int op = 1; for(; ch > '9'|| ch < '0'; ch = getchar()) if(ch == '-') op = -1; for(; ch >= '0' && ch <= '9'; ch = getchar()) X = (X << 3) + (X << 1) + ch - 48; X *= op;}inline void chkMin(int &x, int y) { if(y < x) x = y;}int dfs(int x, int fat) { int dis = 2; for(int i = head[x]; i; i = e[i].nxt) { int y = e[i].to; if(y == fat) continue; chkMin(dis, dfs(y, x)); } if(dis == 0 && x != 1 && fat != 1) ans++; return (dis + 1) % 3;}int main() { read(n); for(int x, y, i = 1; i < n; i++) { read(x), read(y); add(x, y), add(y, x); } dfs(1, 0); printf("%d\n", ans); return 0;}