cf1042F. Leaf Sets(贪心)
程序员文章站
2022-09-14 18:30:07
题意 题目链接 给出一棵树,删除一些边,使得任意联通块内的任意点距离不超过$k$ sol 考场上想的贪心是对的:考虑一棵子树,如果该子树内最深的两个节点的距离相加$>k$就删掉最深的那个点,向上update的时候只返回最深的点的深度 然而却苦于写不出代码。。。 ......
题意
给出一棵树,删除一些边,使得任意联通块内的任意点距离不超过$k$
sol
考场上想的贪心是对的:考虑一棵子树,如果该子树内最深的两个节点的距离相加$>k$就删掉最深的那个点,向上update的时候只返回最深的点的深度
然而却苦于写不出代码。。。
/* */ #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<map> #include<vector> #include<set> #include<queue> #include<cmath> //#include<ext/pb_ds/assoc_container.hpp> //#include<ext/pb_ds/hash_policy.hpp> #define pair pair<int, int> #define mp(x, y) make_pair(x, y) #define fi first #define se second #define int long long #define ll long long #define ull unsigned long long #define rg register #define pt(x) printf("%d ", x); //#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? eof : *p1++) //char buf[(1 << 22)], *p1 = buf, *p2 = buf; //char obuf[1<<24], *o = obuf; //void print(int x) {if(x > 9) print(x / 10); *o++ = x % 10 + '0';} //#define os *o++ = ' '; using namespace std; //using namespace __gnu_pbds; const int maxn = 1e6 + 10, inf = 1e9 + 10, mod = 1e9 + 7; const double eps = 1e-9; inline int read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } int n, k, ans = 0; vector<int> v[maxn]; int dfs(int x, int fa) { if(v[x].size() == 1) return 0; vector<int> dis; for(int i = 0; i < v[x].size(); i++) { int to = v[x][i]; if(to == fa) continue; dis.push_back(dfs(to, x) + 1); } sort(dis.begin(), dis.end()); while(dis.size() >= 2) { int x = dis[dis.size() - 1], y = dis[dis.size() - 2]; if(x + y > k) ans++, dis.pop_back(); else break; } return dis.back(); } main() { n = read(); k = read(); for(int i = 1; i <= n - 1; i++) { int x = read(), y = read(); v[x].push_back(y); v[y].push_back(x); } for(int i = 1; i <= n; i++) if(v[i].size() > 1) {dfs(i, 0); break;} printf("%d", ans + 1); return 0; } /* 2 2 1 1 1 2 1 1 */
上一篇: unexpected reloc type问题分析
下一篇: python学习之基础语法