西南交通大学第十三届ACM决赛-重现赛-E(DFS)

题目描述

The term of this problem is the same as the problem "Maximize The Beautiful Value", the only exception — The sequence may not necessary to to non-decreasing.

输入描述:

 The first line contains an positive integer T(1≤T≤10), represents there are T test cases. 
 For each test case: 
 The first line contains two positive integers n,k(1≤n≤105,1≤k<n),the length of the sequence ,the least steps you need to move. 
 The second line contains n integers a1,a2…an(1≤ai≤108) - the sequence.

输出描述:

For each test case, you should output the max F(n).

示例1



题意:给你n个城市,n-1条边,这n个城市可相互到达,现在要求将这n个城市分成n/2对,

问你这n/2对城市之间的距离之和最小是多少。

题解:考虑贪心,每个点和相邻的点之间的距离一定是最小,呢找完所有相邻点后剩下的点怎么办?

还是一样的,一定是尽量走尽可能少的边,假如说两个点不是相邻的,但是这两个点到他们共同的

父亲的距离之和一定是最优解,因此可以考虑异或模拟这个过程即可。

#include<set> 
#include<map>    
#include<stack>           
#include<queue>           
#include<vector>   
#include<string>
#include<time.h>
#include<math.h>           
#include<stdio.h>           
#include<iostream>           
#include<string.h>           
#include<stdlib.h>   
#include<algorithm>  
#include<functional>   
using namespace std;           
#define ll long long      
#define inf  1000000000      
#define mod 1000000007            
#define maxn  100100
#define lowbit(x) (x&-x)           
#define eps 1e-9
struct node
{
    ll x,y;
};
vector<node>q[maxn];
bool flag[maxn];
ll ans;
void dfs(int u,int p)
{
    int i;
    for(i=0;i<q[u].size();i++)
    {
        node v=q[u][i];
        if(v.x==p)
            continue;
        dfs(v.x,u);
        if(flag[v.x]==1)
            continue;
        ans+=v.y;
        flag[u]^=1;
        flag[v.x]^=1;
    }
}
int main(void)
{
    ll T,n,i,x,y,z;
    scanf("%lld",&T);
    while(T--)
    {
        ans=0;
        scanf("%lld",&n);
        memset(flag,0,sizeof(flag));
        for(i=1;i<n;i++)
        {
            scanf("%lld%lld%lld",&x,&y,&z);
            node tmp;
            tmp.x=y;tmp.y=z;
            q[x].push_back(tmp);
            tmp.x=x;tmp.y=z;
            q[y].push_back(tmp);
        }
        dfs(1,0);
        printf("%lld\n",ans);
        for(i=1;i<=n;i++)
            q[i].clear();
    }
    return 0;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值