本文共 1609 字,大约阅读时间需要 5 分钟。
大意: 给定树, 求叶子的最小划分, 使得每个划分内任意两个叶子距离不超过k.
任选一个非叶结点, 贪心合并.
#include #include #include #include #include #include #include #include #include #include #include #define REP(i,a,n) for(int i=a;i<=n;++i)#define PER(i,a,n) for(int i=n;i>=a;--i)#define hr putchar(10)#define pb push_back#define lc (o<<1)#define rc (lc|1)#define mid ((l+r)>>1)#define ls lc,l,mid#define rs rc,mid+1,r#define x first#define y second#define io std::ios::sync_with_stdio(false)#define endl '\n'#define DB(a) ({REP(__i,1,n) cout< <<' ';hr;})using namespace std;typedef long long ll;typedef pair pii;const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f;ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;}//head#ifdef ONLINE_JUDGEconst int N = 1e6+10;#elseconst int N = 111;#endifint n, k, ans;vector g[N];int dfs(int x, int f) { if (g[x].size()==1) return 0; vector v; for (int y:g[x]) if (y!=f) v.pb(dfs(y,x)+1); sort(v.begin(),v.end()); int sz = v.size()-1; for (; sz>=1; --sz) { if (v[sz]+v[sz-1]<=k) break; ++ans; } return v[sz];}int main() { scanf("%d%d", &n, &k); REP(i,2,n) { int u, v; scanf("%d%d", &u, &v); g[u].pb(v),g[v].pb(u); } int rt = 1; PER(i,1,n) if (g[i].size()>1) rt=i; dfs(rt,0); printf("%d\n",ans+1);}
转载于:https://www.cnblogs.com/uid001/p/10913197.html