問題描述
很久以前,T王國空前繁榮。爲了更好地管理國家,王國修建了大量的快速路,用於連接首都和王國內的各大城市。
爲節省經費,T國的大臣們經過思考,制定了一套優秀的修建方案,使得任何一個大城市都能從首都直接或者通過其他大城市間接到達。同時,如果不重複經過大城市,從首都到達每個大城市的方案都是唯一的。
J是T國重要大臣,他巡查於各大城市之間,體察民情。所以,從一個城市馬不停蹄地到另一個城市成了J最常做的事情。他有一個錢袋,用於存放往來城市間的路費。
聰明的J發現,如果不在某個城市停下來修整,在連續行進過程中,他所花的路費與他已走過的距離有關,在走第x千米到第x+1千米這一千米中(x是整數),他花費的路費是x+10這麼多。也就是說走1千米花費11,走2千米要花費23。
J大臣想知道:他從某一個城市出發,中間不休息,到達另一個城市,所有可能花費的路費中最多是多少呢?輸入格式
輸入的第一行包含一個整數n,表示包括首都在內的T王國的城市數
城市從1開始依次編號,1號城市爲首都。
接下來n-1行,描述T國的高速路(T國的高速路一定是n-1條)
每行三個整數Pi, Qi, Di,表示城市Pi和城市Qi之間有一條高速路,長度爲Di千米。輸出格式
輸出一個整數,表示大臣J最多花費的路費是多少。樣例輸入1
5
1 2 2
1 3 1
2 4 5
2 5 4
樣例輸出1
135
輸出格式
大臣J從城市4到城市5要花費135的路費。
題解:
這道題很容易,利用dfs求出某個城市到另一個城市的最大路徑即可,然後利用路費的計算方法,算出路費輸出即可。
代碼:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 7010+5;
int n;
int p,q,d;
int maxV = -inf;
// 鄰接矩陣
int flag[MAX];
int g[MAX][MAX];
void dfs(int s,int sum)
{
//cout << "當前點:" << s << " " << "當前路徑值:" << sum << endl;
if(sum > maxV)
{
maxV = sum;
}
for(int j = 1; j <= n; j++)
{
if(g[s][j] != -1 && !flag[j])
{
flag[j] = 1;
dfs(j,sum+g[s][j]);
flag[j] = 0;
}
}
}
int main()
{
/*
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
*/
cin >> n;
memset(g,-1,sizeof(g));
for(int i = 1; i <= n-1; i++)
{
cin >> p >> q >> d;
g[p][q] = g[q][p] = d;
}
for(int i = 1; i <= n; i++)
{
memset(flag,0,sizeof(flag));
flag[i] = 1;
//cout << "起點:" << i << endl;
dfs(i,0);
//cout << endl;
}
//cout << maxV << endl;
int sum = 0;
for(int x = 1; x <= maxV; x++)
{
sum += 10+x;
}
cout << sum << endl;
return 0;
}