1737 配对
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
收藏
关注
给出一棵n个点的树,将这n个点两两配对,求所有可行的方案中配对两点间的距离的总和最大为多少。
Input
一个数n(1<=n<=100,000,n保证为偶数)
接下来n-1行每行三个数x,y,z表示有一条长度为z的边连接x和y(0<=z<=1,000,000,000)
Output
一个数表示答案
Input示例
6
1 2 1
1 3 1
1 4 1
3 5 1
4 6 1
Output示例
7
//配对方案为(1,2)(3,4)(5,6)
一条边的贡献 = 点较少的一边的点的个数 * 这条边的权值
AC代码: (453 ms)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int K = 1e5 + 10;
typedef long long LL;
LL n,head[K],s[K],num,ans;
struct node{
LL to,vl,next;
}st[K * 2];
void add(LL a,LL b,LL c){
st[num] = node{b,c,head[a]}; head[a] = num++;
st[num] = node{a,c,head[b]}; head[b] = num++;
}
void dfs(LL x,LL f){
s[x] = 1;
for(int i = head[x]; i != -1; i = st[i].next)
if(st[i].to != f)
dfs(st[i].to,x),s[x] += s[st[i].to],ans += min(s[st[i].to],n - s[st[i].to]) * st[i].vl;
}
int main()
{
LL a,b,c;
num = 0;
memset(head,-1,sizeof(head));
scanf("%d",&n);
for(int i = 1; i < n; i++)
scanf("%lld %lld %lld",&a,&b,&c),add(a,b,c);
ans = 0;
dfs(1,0);
printf("%lld\n",ans);
return 0;
}
AC代码 + 输入外挂 (171ms):
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int K = 1e5 + 10;
typedef long long LL;
LL n,head[K],s[K],num,ans;
struct node{
LL to,vl,next;
}st[K * 2];
LL read(){
LL x = 0, y = 1;
char s = getchar();
while(s < '0' || s > '9') { if(s == '-') y = -1;s = getchar();}
while(s >= '0' && s <= '9') x = x * 10 + s - '0',s = getchar();
return x * y;
}
void add(LL a,LL b,LL c){
st[num] = node{b,c,head[a]}; head[a] = num++;
st[num] = node{a,c,head[b]}; head[b] = num++;
}
void dfs(LL x,LL f){
s[x] = 1;
for(int i = head[x]; i != -1; i = st[i].next)
if(st[i].to != f)
dfs(st[i].to,x),s[x] += s[st[i].to],ans += min(s[st[i].to],n - s[st[i].to]) * st[i].vl;
}
void out(LL a){
if(a < 0) putchar('-'), a = -a;
if(a >= 10) out(a / 10); putchar(a % 10 + '0');
}
int main()
{
LL a,b,c;
num = 0;
memset(head,-1,sizeof(head));
scanf("%d",&n);
for(int i = 1; i < n; i++)
a = read(),b = read(),c = read(),add(a,b,c);
ans = 0;
dfs(1,0);
out(ans);
return 0;
}