1. 程式人生 > >codeforces 1029E Tree with Small Distances【思維+貪心】 【非原創】

codeforces 1029E Tree with Small Distances【思維+貪心】 【非原創】

close hide 就是 set running += int sed pro

題目:戳這裏

學習博客:戳這裏

題意:給一個樹加最少的邊,使得1到所有點的距離小於等於2.

解題思路:分析樣例3可以看出,如果一個點到1的距離大於2,那麽建立1到該點的父親節點的邊將比直接與該點建邊更優。官方題解的做法是把所有與1距離大於2的點放到大頂堆裏維護,每次取出最遠的點,染色與該點父節點以及與父節點相接的所有點。也就是相當於與父節點建邊,距離為1,與父節點的子節點的距離就為2了,於是把這些點彈出。從大佬博客中學到一個很妙的寫法,是用dfs實現這個思路,具體看代碼。

附ac代碼:

技術分享圖片
 1 #include <bits/stdc++.h>
 2 using namespace
std; 3 const int maxn = 2e5 + 10; 4 int dis[maxn]; 5 vector<int>nu[maxn]; 6 int ans = 0; 7 void dfs(int now, int pre, int cnt) 8 { 9 10 dis[now] = cnt; 11 int flag = 0; 12 for(int y : nu[now]) 13 { 14 // printf("%d\n", y); 15 if(y == pre) continue; 16 17 dfs(y, now, cnt + 1
); 18 if(dis[y] > 2) 19 { 20 flag = 1; 21 dis[now] = 1; 22 dis[pre] = 2; 23 } 24 } 25 ans += flag; 26 27 } 28 int main() 29 { 30 int n; 31 int u, v; 32 scanf("%d", &n); 33 for(int i = 1; i < n; ++i) 34 {
35 scanf("%d %d", &u, &v); 36 nu[u].push_back(v); 37 nu[v].push_back(u); 38 } 39 dfs(1, 1, 0); 40 printf("%d\n", ans); 41 }
View Code

codeforces 1029E Tree with Small Distances【思維+貪心】 【非原創】