CF 1029E Tree with Small Distances
生活随笔
收集整理的這篇文章主要介紹了
CF 1029E Tree with Small Distances
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
昨晚隨便玩玩搞個div3結果浪翻了……
強烈譴責D題hack數據卡常
考慮到本題中所要求的最短距離不會大于2,所以我們可以把所有結點到$1$的距離通過對$3$取模分類,考慮到直接自頂向下貪心不滿足局部最優解可以推出全局最優解,所以我們可以自下向上這樣可以考慮到所有條件。我們處理出一個結點$x$所有兒子$y$的取模后的距離的最小值$dis$,那么一個結點向$1$連一條邊的充要條件就是:
$dis == 0 && x != 1 && fa != 1$
時間復雜度$O(n)$。
Code:
#include <cstdio> #include <cstring> 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; }View Code
?
轉載于:https://www.cnblogs.com/CzxingcHen/p/9532801.html
總結
以上是生活随笔為你收集整理的CF 1029E Tree with Small Distances的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [USACO08NOV]lites
- 下一篇: 求一个电影中好听的英文名字