蓝桥杯训练之大臣的旅费

Description

很久以前,T王国空前繁荣。为了更好地管理国家,王国修建了大量的快速路,用于连接首都和王国内的各大城市。

为节省经费,T国的大臣们经过思考,制定了一套优秀的修建方案,使得任何一个大城市都能从首都直接或者通过其他大城市间接到达。同时,如果不重复经过大城市,从首都到达每个大城市的方案都是唯一的。

J是T国重要大臣,他巡查于各大城市之间,体察民情。所以,从一个城市马不停蹄地到另一个城市成了J最常做的事情。他有一个钱袋,用于存放往来城市间的路费。

聪明的J发现,如果不在某个城市停下来修整,在连续行进过程中,他所花的路费与他已走过的距离有关,在走第x千米到第x+1千米这一千米中(x是整数),他花费的路费是x+10这么多。也就是说走1千米花费11,走2千米要花费23。

J大臣想知道:他从某一个城市出发,中间不休息,到达另一个城市,所有可能花费的路费中最多是多少呢?

Input

输入的第一行包含一个整数n,表示包括首都在内的T王国的城市数

城市从1开始依次编号,1号城市为首都。

接下来n-1行,描述T国的高速路(T国的高速路一定是n-1条)

每行三个整数Pi, Qi, Di,表示城市Pi和城市Qi之间有一条高速路,长度为Di千米。

Output

输出一个整数,表示大臣J最多花费的路费是多少。

Sample Input

样例输入1
5
1 2 2
1 3 1
2 4 5
2 5 4

Sample Output

样例输出1
135

第一反应就是最短路,因为不知道数据的大小,而且感觉似乎需要求任意两点之间最短路,果断写了一个Floyd。时间超限。。

后来一想,其实没有必要求任意两点之间的距离,其实找出距离最大的那一条路,然后直接求这条路连通的路的距离就好~

//Asimple
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <cmath>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <limits.h>
#include <time.h>
#define INF 0xfffffff
#define mod 999101
#define PI 3.14159265358979323
#define swap(a,b,t) t = a, a = b, b = t
#define CLS(a, v) memset(a, v, sizeof(a))
#define debug(a)  cout << #a << " = "  << a <<endl
#define srd(a) scanf("%d", &a)
#define src(a) scanf("%c", &a)
#define srs(a) scanf("%s", a)
#define srdd(a,b) scanf("%d %d",&a, &b)
#define srddd(a,b,c) scanf("%d %d %d",&a, &b, &c)
#define prd(a) printf("%d
", a)
#define prdd(a,b) printf("%d %d
",a, b)
#define prs(a) printf("%s
", a)
#define prc(a) printf("%c", a)
using namespace std;
inline int abs(int x){return x<0?-x:x;}
typedef long long ll;
const int maxn = 1000010;
int n, m, num, T, k, len, ans, sum, x, y;
int dis[maxn];
bool vis[maxn];
int a[maxn];

struct node{
    int x;
    int y;
    int w;
    node(int x, int y) : x(x), y(y), w(w){
    }
    node (){
    } 
}e[maxn];
void init() {
    len = 0;
    for(int i=1; i<=n; i++) {
        a[i] = -1;
    }
}

void add_e(int x, int y, int w) {
    e[len].x = y;
    e[len].w = w;
    e[len].y = a[x];
    a[x] = len++;
}

void solve(int x) { queue<int> q; CLS(vis, false); CLS(dis, 0); vis[x] = true; q.push(x); ans = 0; dis[x] = 0; while( !q.empty() ) { int xx = q.front(); q.pop(); for(int i=a[xx]; i!=-1; i=e[i].y) { int v = e[i].x; if( !vis[v] ) { vis[v] = true; dis[v] = e[i].w + dis[xx]; if( ans < dis[v] ) { sum = v; ans = dis[v]; } q.push(v); } } } } void input() { srd(n); init(); for(int i=1; i<n; i++) { srddd(x, y, num); add_e(x, y, num); add_e(y, x, num); } solve(1); solve(sum); cout << ans*10+(1+ans)*ans/2 << endl; } int main(){ input(); return 0; }
低调做人,高调做事。
原文地址:https://www.cnblogs.com/Asimple/p/6393040.html