zoukankan      html  css  js  c++  java
  • AtCoder Grand Contest 018 D

    题目传送门:https://agc018.contest.atcoder.jp/tasks/agc018_d

    题目大意:

    给定一棵(N)个点的带权树,求最长哈密顿路径(不重不漏经过每个点一次,两点之间转移可以看做瞬移,对答案贡献为两点之间的距离)


    这道题直接计算不好算,我们考虑每条边的贡献,基于一种贪心的思想,我们发现只要围着树的重心跑,就可以使每条边得到充分利用

    考虑边i的贡献,我们假定边i割掉后分成两个大小为x,y的联通块,那么贡献则为(2*v[i]*min(x,y))

    因为我们走的不是回路,因此有一条边不会被算两次。如果树的重心只有一个,那么必然减去与重心相连的边权最小的边;如果树的重心有两个,减去两重心相连的边即可

    /*program from Wolfycz*/
    #include<cmath>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    #define inf 0x7f7f7f7f
    using namespace std;
    typedef long long ll;
    typedef unsigned int ui;
    typedef unsigned long long ull;
    inline char gc(){
    	static char buf[1000000],*p1=buf,*p2=buf;
    	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
    }
    inline int frd(){
    	int x=0,f=1;char ch=gc();
    	for (;ch<'0'||ch>'9';ch=gc())	if (ch=='-')    f=-1;
    	for (;ch>='0'&&ch<='9';ch=gc())	x=(x<<1)+(x<<3)+ch-'0';
    	return x*f;
    }
    inline int read(){
    	int x=0,f=1;char ch=getchar();
    	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
    	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
    	return x*f;
    }
    inline void print(int x){
    	if (x<0)    putchar('-'),x=-x;
    	if (x>9)	print(x/10);
    	putchar(x%10+'0');
    }
    const int N=2e5;
    int pre[(N<<1)+10],now[N+10],child[(N<<1)+10],val[(N<<1)+10];
    int size[N+10],Msize[N+10];
    int n,tot,rize,root;
    ll Ans;
    void join(int x,int y,int z){pre[++tot]=now[x],now[x]=tot,child[tot]=y,val[tot]=z;}
    void insert(int x,int y,int z){join(x,y,z),join(y,x,z);}
    void dfs(int x,int fa,int v){
    	int Max=0; size[x]=1;
    	for (int p=now[x],son=child[p];p;p=pre[p],son=child[p]){
    		if (son==fa)	continue;
    		dfs(son,x,val[p]),size[x]+=size[son];
    		Max=max(Max,size[son]);
    	}
    	Ans+=1ll*min(size[x],n-size[x])*v*2;
    	Max=max(Max,n-size[x]);
    	Msize[x]=Max;
    	if (Max<rize){
    		rize=Max;
    		root=x;
    	}
    }
    int main(){
    	n=read(),rize=inf;
    	for (int i=1;i<n;i++){
    		int x=read(),y=read(),z=read();
    		insert(x,y,z);
    	}
    	dfs(1,0,0);
    	int tmp=inf;
    	for (int p=now[root],son=child[p];p;p=pre[p],son=child[p]){
    		tmp=min(tmp,val[p]);
    		if (Msize[root]==Msize[son]){
    			Ans-=val[p];
    			printf("%lld
    ",Ans);
    			return 0;
    		}
    	}
    	printf("%lld
    ",Ans-tmp);
    	return 0;
    }
    
  • 相关阅读:
    Storm 第一章 核心组件及编程模型
    四 Hive整合HBase
    Hbase第五章 MapReduce操作HBase
    swift 附属脚本
    swift 方法
    swift 属性
    swift 类和结构体
    swift 枚举类型
    swift 闭包
    Swift 函数
  • 原文地址:https://www.cnblogs.com/Wolfycz/p/10117684.html
Copyright © 2011-2022 走看看