Codeforces 1039D You Are Given a Tree (看题解)
Posted cjlhy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces 1039D You Are Given a Tree (看题解)相关的知识,希望对你有一定的参考价值。
感觉是个套路。。 怎么好像我没怎么见过啊。
k * t <= n 类似于这种, 对所有 k 求满足条件 t 的最大值, 那么答案不同的数量只有根号个。
如果随 k 的变化单调的话就可以二分优化啦。
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 1e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) a += b; if(a >= mod) a -= mod; template<class T, class S> inline void sub(T& a, S b) a -= b; if(a < 0) a += mod; template<class T, class S> inline bool chkmax(T& a, S b) return a < b ? a = b, true : false; template<class T, class S> inline bool chkmin(T& a, S b) return a > b ? a = b, true : false; const int B = 1000; int n, k, cur, ans[N], fa[N]; vector<int> G[N]; int id[N], nid; int dp[N]; int mx[N][2]; int calc(int k) if(~ans[k]) return ans[k]; for(int o = 1; o <= n; o++) int u = id[o]; dp[u] = mx[u][0] = mx[u][1] = 0; for (auto& v : G[u]) if(v == fa[u]) continue; dp[u] += dp[v]; if(mx[v][0] >= mx[u][0]) mx[u][1] = mx[u][0], mx[u][0] = mx[v][0]; else if(mx[v][0] > mx[u][1]) mx[u][1] = mx[v][0]; if(mx[u][0] + mx[u][1] + 1 >= k) dp[u]++; mx[u][0] = mx[u][1] = 0; else mx[u][0]++; mx[u][1]++; return ans[k] = dp[1]; void dfs(int u, int f) fa[u] = f; for(auto& v : G[u]) if(v == f) continue; dfs(v, u); id[++nid] = u; void solve(int l, int r) if(l > r) return; if(calc(l) == calc(r)) for(int i = l + 1; i < r; i++) ans[i] = ans[l]; return; int mid = l + r >> 1; solve(l, mid); solve(mid + 1, r); int main() memset(ans, -1, sizeof(ans)); scanf("%d", &n); for(int i = 1; i < n; i++) int u, v; scanf("%d%d", &u, &v); G[u].push_back(v); G[v].push_back(u); dfs(1, 0); solve(1, n); for(int i = 1; i <= n; i++) printf("%d\n", ans[i]); return 0; /* */
以上是关于Codeforces 1039D You Are Given a Tree (看题解)的主要内容,如果未能解决你的问题,请参考以下文章
CF1039D You Are Given a Tree [根号分治]
[CF1039D]You Are Given a Tree[贪心+根号分治]
CF 1039D You Are Given a Tree && CF1059E Split the Tree 的贪心解法