Description
Input
第一行是两个整数N(3 < N < 200000)和M,分别表示居住点总数和街道总数。以下M行,每行给出一条街道的信息。第i+1行包含整数Ui、Vi、Ti(1 < Ui, Vi < N,1 < Ti < 1000000000),表示街道i连接居住点Ui和Vi,并且经过街道i需花费Ti分钟。街道信息不会重复给出。
Output
仅包含整数T,即最坏情况下Chris的父母需要花费T分钟才能找到Chris。
Sample Input
4 3
1 2 1
2 3 1
3 4 1
Sample Output
4
打完代码,感觉身体被掏空,不多说了,直接上图。
大概就是这个感觉,恩恩。
代码如下
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int sz = 2001000;
int head[sz],nxt[sz];
ll dis_s[sz],dis_t[sz];
int tot = 1;
int n,m;
struct gtnd
{
int t;
ll d;
}l[sz];
void build_edge(int f,int t,ll d)
{
l[tot].t = t;
l[tot].d = d;
nxt[tot] = head[f];
head[f] = tot ++;
}
int read_int()
{
int x = 0 , f = 1;
char in = getchar();
while(in < '0' || in > '9')
{
if(in == '-')
f = -1;
in = getchar();
}
while('0' <= in && in <= '9')
{
x = (x << 3) + (x << 1) + in - '0';
in = getchar();
}
return x * f;
}
ll read_ll()
{
ll x = 0 , f = 1;
char in = getchar();
while(in < '0' || in > '9')
{
if(in == '-')
f = -1;
in = getchar();
}
while('0' <= in && in <= '9')
{
x = x * 10 + in - '0';
in = getchar();
}
return x * f;
}
void start_work()
{
n = read_int() , m = read_int();
for(int i = 1 ; i <= m ; i ++)
{
int f = read_int() , t = read_int();
ll d = read_ll();
build_edge(f,t,d);
build_edge(t,f,d);
}
}
int pos;
ll dist;
void dfs_first(int u,int fa,ll d)
{
if(d > dist)
dist = d , pos = u;
for(int i = head[u] ; i ; i = nxt[i])
if(l[i].t != fa)
dfs_first(l[i].t,u,d+l[i].d);
}
void dfs_s(int u,int fa,ll d)
{
dis_s[u] = d;
for(int i = head[u] ; i ; i = nxt[i])
if(l[i].t != fa)
dfs_s(l[i].t,u,d+l[i].d);
}
void dfs_t(int u,int fa,ll d)
{
dis_t[u] = d;
for(int i = head[u] ; i ; i = nxt[i])
if(l[i].t != fa)
dfs_t(l[i].t,u,d+l[i].d);
}
int main()
{
start_work();
dfs_first(1,0,0);
int s = pos;
dist = 0;
dfs_first(pos,0,0);
int t = pos;
dfs_s(s,0,0);
dfs_t(t,0,0);
ll ans = 0;
for(int i = 1 ; i <= n ; i ++)
if(i != s && i != t)
ans = max(ans,min(dis_s[i],dis_t[i]));
printf("%lld\n",ans+dist);
return 0;
}