首页 > 其他分享 >洛谷 P8509 题解(待完善)

洛谷 P8509 题解(待完善)

时间:2022-11-16 07:22:22浏览次数:78  
标签:ch 洛谷 int 题解 ll tot nex P8509 now

题面

要求所有点到关键点的距离和最小。

首先要确定这个点去哪个关键点最短。

树上两点间路径与距离是唯一的,所以

我们从两个关键点分别跑dfs。

第一遍求出每个点到s的最短距离。

然后再从t点出发,如果这个点到t点的距离更短,那么这个点就应该去t点。

定向的工作也可以在dfs的时候做。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int h=600010;
int head[h],last[h],to[h],tot=1;
ll len[h];
void add_edge(int x,int y,ll w){
    tot++;
    last[tot]=head[x];
    head[x]=tot;
    to[tot]=y;
    len[tot]=w;
}
void add(int x,int y,ll w){
    add_edge(x,y,w);
    add_edge(y,x,w);
}
int n,s,t;
ll dis[h];
bool ch[h];
void clear(int now){
    for(int i=head[now];i;i=last[i])
        ch[i]=0,ch[i^1]=0;
}
void dfs(int now,int fa){
    for(int i=head[now];i;i=last[i]){
        int nex=to[i];
        if(nex^fa)
            if(dis[nex]>dis[now]+len[i])
                clear(nex),dis[nex]=dis[now]+len[i],ch[i]=0,ch[i^1]=1,dfs(nex,now);
    }
}
ll d;
int main(){
    scanf("%d%d%d",&n,&s,&t);
    for(int i=1,u,v;i<n;i++)
        scanf("%d%d%lld",&u,&v,&d),add(u,v,d);
    memset(dis,0x3f,sizeof(dis));
    dis[s]=0,dis[t]=0;
    dfs(s,0),dfs(t,0);
    ll ans=0;
    for(int i=1;i<=n;i++)
        ans+=dis[i];
    printf("%lld\n",ans);
    for(int i=1;i<n;i++)
        if(ch[i*2])
            putchar('1');
        else
            if(ch[i*2+1])
                putchar('2');
            else
                putchar('0');
    return 0;
}
完整代码

 

标签:ch,洛谷,int,题解,ll,tot,nex,P8509,now
From: https://www.cnblogs.com/12103h/p/16894668.html

相关文章

  • 神奇脑洞题解——USACO追查坏牛奶(CSGO894)
    COGS的这一题是超级满配版本比洛谷的要强力的多:894.追查坏牛奶-COGS额外要求是:求出最小割流量,同时求出割边最小,同时字典序最小的方案输出割掉的边最小割流量好求,最......
  • 【题解】[模拟赛20221115] Tree
    模拟赛20221115Tree|CQNK\(O(m*n*2^n)\)很好做,但是本题有更优秀的做法:在此记录复杂度\(O(n*2^n)\)的做法。考虑从后往前dp,设dp状态\(f_{s,0/1}\)分别表示在填......
  • 洛谷 P8097
    考虑时光倒流。由于A操作只会给两个活跃的点连边,所以可以忽略,倒过来相当于没有删边操作。然后只剩下加边,加活跃点,两种操作。每次暴力DFS即可。时间复杂度\(\mathca......
  • 题解 ARC001C【パズルのお手伝い】
    postedon2021-01-1118:20:37|under题解|source前言这道题与八皇后很像,可以做完八皇后再来做这道题。如果你\(\color{white}\colorbox{red}{WA}\)了,请检查你有......
  • 题解 UVA12265【贩卖土地 Selling Land】
    postedon2022-09-2414:33:29|under题解|sourceproblem一个黑白矩阵,求以每个点为右下角,能围出的周长最大的全白矩形的周长。\(n\leq2000\)。solution试图进行......
  • 焦点科技编程挑战赛2022题解
    比赛说明:比赛在四个学校开展,南理南航南农和矿大。题目查找文本差异要求origin和dest中分别包含1000w+条数据dest对数据进行了打乱操作,即origin和dest中相同数据行的......
  • CF1598F RBS 题解
    题意给\(n\)个串,求将这\(n\)个串以任意顺序接起来的最大的是合法括号序列的前缀数。分析\(n\)很小,考虑状压dp。有一个很典的转化是将(看成\(+1\),将)看成\(-......
  • 洛谷-5175
    洛谷-5175思路这里面的第一篇题解根据需要啥就加啥的想法!(妙啊)Code#include<bits/stdc++.h>usingnamespacestd;#define_u_u_ios::sync_with_stdio(false),ci......
  • CF 1743 题解
    比赛链接:https://codeforces.com/contest/1743题解:AB水题//bySkyRainWind#include<cstdio>#include<vector>#include<cstring>#include<iostream>#include......
  • week3题解
    1.寄包柜   看到题目最容易想到开二位数组但数据量过大,因此需要map#include<bits/stdc++.h>usingnamespacestd;map<int,map<int,int>>a;这里开了一个map......