zoj 3659 Conquer a New Region

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4882


题目大意:

有一棵树,每条边有权值,从树上一点到另一点的路径权值为该条路径上的最小权边,选一个点使得该点到其余所有点的路径权值和最大.


题目思路:

看一下规模,可能是贪心,dp,线段树之类的,线段树明显没想法,dp嘛,状态太多了,那就想想贪心,不过不管是什么方法,最终的目的就是要得到一个有根树,这里我们可以用并查集+路径压缩来做.

贪心我们只要考虑构树是按边的权值降序还是升序,如果选用升序的话,当前边要到前面加入的边的限制,所以就麻烦了,而降序呢,前面加入的边是受当前边的限制,所以相对容易多了.

对与每个父亲还要保存到其子孙的路径权值和以及子孙数量,这在合并两棵树是要用到.

1)两个点均无父亲,任选一个作为父亲.

2)其中一个无父亲,把有父亲的父亲作为无父亲的父亲(很绕口= =...将就一下).

3)均有父亲,那么就要判断一下到底谁做父亲可以使构成的树路径权值更大,在这边就要用到路径权值和以及子孙数量了(我是用到了,大牛可能不需要...).


代码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

#define ll long long
#define ls rt<<1
#define rs ls|1
#define lson l,mid,ls
#define rson mid+1,r,rs
#define middle (l+r)>>1
#define eps (1e-9)
#define type int
#define clr_all(x,c) memset(x,c,sizeof(x))
#define clr(x,c,n) memset(x,c,sizeof(x[0])*(n+1))
#define MOD 1000000007
#define inf 0x3f3f3f3f
#define pi acos(-1.0)
#define M 200000 +5

template <class T> void _swap(T &x,T &y){T t=x;x=y;y=t;}
template <class T> T _max(T x,T y){return x>y? x:y;}
template <class T> T _min(T x,T y){return x<y? x:y;}
int test,cas;

int n,m;
struct node{
	int u,v;
	ll c;
	void read(){
		scanf("%d%d%lld",&u,&v,&c);
	}
	bool operator < (const node &t) const{
		return c > t.c;
	}
}p[M];
ll sum[M],cnt[M];
int fa[M];

int Find(int x){
	for(;x!=-1 && x!=fa[x];x=fa[x]);
	return x;
}

void Union(int u,int v,ll val){
	int uf=Find(u),vf=Find(v);
	if(uf==-1 && vf==-1)
		fa[u]=v,sum[v]+=val,cnt[v]++,fa[v]=v;
	else if(uf==-1)
		fa[u]=vf,sum[vf]+=val,cnt[vf]++;
	else if(vf==-1)
		fa[v]=uf,sum[uf]+=val,cnt[uf]++;
	else{
		ll tu=sum[uf]+(cnt[vf]+1)*val;
		ll tv=sum[vf]+(cnt[uf]+1)*val;
		if(tu > tv) fa[vf]=uf,sum[uf]=tu,cnt[uf]+=cnt[vf]+1;
		else fa[uf]=vf,sum[vf]=tv,cnt[vf]+=cnt[uf]+1;
	}
}

void run(){
	int i,j;
	clr(sum,0,n),clr(cnt,0,n);
	clr(fa,-1,n);
	m=n-1;
	for(i=0;i<m;i++)
		p[i].read();
	sort(p,p+m);
	for(i=0;i<m;i++)
		Union(p[i].u,p[i].v,p[i].c);
	for(i=1;i<=n;i++) if(cnt[i]+1==n){
		printf("%lld\n",sum[i]);
		return;
	}
}

void preSof(){
}

int main(){
	//freopen("1.in","r",stdin);
	//freopen("1.out","w",stdout);
	preSof();
	//run();
	while(~scanf("%d",&n)) run();
	//for(scanf("%d",&test),cas=1;cas<=test;cas++) run();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值