【51nod 1737 配对】+ 链式前向星 + dfs + 输入外挂

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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值