Usaco 2010 Dec Gold Exercise(奶牛健美操)

时间:2022-04-19 16:12:14
/*codevs 3279 二分+dfs贪心检验 堆版本 re一个 爆栈了*/
#include<cstdio>
#include<queue>
#include<cstring>
#define pa pair<int,int>
#define mk make_pair
#define X first
#define Y second
#define maxn 100010
using namespace std;
int n,S,num,head[maxn],ans,f[maxn],mid,sum;
struct node{
int v,pre;
}e[maxn*];
priority_queue<pa>q;
int init(){
int x=,f=;char s=getchar();
while(s<''||s>''){if(s=='-')f=-;s=getchar();}
while(s>=''&&s<=''){x=x*+s-'';s=getchar();}
return x*f;
}
void Add(int from,int to){
num++;e[num].v=to;
e[num].pre=head[from];
head[from]=num;
}
void Dfs(int u,int from){
int cnt=;
for(int i=head[u];i;i=e[i].pre){
int v=e[i].v;if(v==from)continue;
Dfs(v,u);cnt++;
}
if(cnt==)return;
while(!q.empty())q.pop();
for(int i=head[u];i;i=e[i].pre){
int v=e[i].v;if(v==from)continue;
q.push(mk(f[v],v));
}
while(q.size()>=){
int x=q.top().X,xi=q.top().Y;q.pop();
int y=q.top().X,yi=q.top().Y;q.pop();
if(x+y+>mid){
f[xi]=;q.push(mk(y,yi));sum++;
}
else {
q.push(mk(x,xi));q.push(mk(y,yi));break;
}
}
if(q.size()==&&q.top().X+>mid){
f[q.top().Y]=;sum++;q.pop();
}
int mx=;
if(q.size())mx=q.top().X+;
f[u]=mx;
}
bool Judge(){
memset(f,,sizeof(f));
sum=;Dfs(,);
return sum<=S;
}
int main()
{
n=init();S=init();int u,v;
for(int i=;i<n;i++){
u=init();v=init();
Add(u,v);Add(v,u);
}
int l=,r=0x3f3f3f3f;
while(l<=r){
mid=l+r>>;
if(Judge()){
r=mid-;ans=mid;
}
else l=mid+;
}
printf("%d\n",ans);
return ;
}
/*codevs 3279 二分+dfs贪心检验 数组版本*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 100010
using namespace std;
int n,S,num,head[maxn],ans,f[maxn],mid,sum;
struct node{
int v,pre;
}e[maxn*];
struct C{
int o,val;
bool operator < (const C &x)const{
return val>x.val;
}
}p[maxn];
int init(){
int x=,f=;char s=getchar();
while(s<''||s>''){if(s=='-')f=-;s=getchar();}
while(s>=''&&s<=''){x=x*+s-'';s=getchar();}
return x*f;
}
void Add(int from,int to){
num++;e[num].v=to;
e[num].pre=head[from];
head[from]=num;
}
void Dfs(int u,int from){
int cnt=;
for(int i=head[u];i;i=e[i].pre){
int v=e[i].v;if(v==from)continue;
Dfs(v,u);cnt++;
}
if(cnt==)return;cnt=;
for(int i=head[u];i;i=e[i].pre){
int v=e[i].v;if(v==from)continue;
p[++cnt]=(C){v,f[v]};
}
sort(p+,p++cnt);int p1=,p2=;
while(p2<=cnt){
int x=p[p1].val,xi=p[p1].o;
int y=p[p2].val,yi=p[p2].o;
if(x+y+>mid){
f[xi]=;sum++;p1++;p2++;
}
else break;
}
if(p1==cnt&&p[p1].val+>mid){
f[p[p1++].o]=;sum++;
}
int mx=;
if(p1<=cnt)mx=p[p1].val+;
f[u]=mx;
}
bool Judge(){
memset(f,,sizeof(f));
sum=;Dfs(,);
return sum<=S;
}
int main()
{
n=init();S=init();int u,v;
for(int i=;i<n;i++){
u=init();v=init();
Add(u,v);Add(v,u);
}
int l=,r=0x3f3f3f3f;
while(l<=r){
mid=l+r>>;
if(Judge()){
r=mid-;ans=mid;
}
else l=mid+;
}
printf("%d\n",ans);
return ;
}