隨着杭州西湖的知名度的進一步提升,園林規划專家湫湫希望設計出一條新的經典觀光線路,根據老板馬小騰的指示,新的風景線最好能建成環形,如果沒有條件建成環形,那就建的越長越好。
現在已經勘探確定了n個位置可以用來建設,在它們之間也勘探確定了m條可以設計的路線以及他們的長度。請問是否能夠建成環形的風景線?如果不能,風景線最長能夠達到多少?
其中,可以興建的路線均是雙向的,他們之間的長度均大於0。
Input 測試數據有多組,每組測試數據的第一行有兩個數字n, m,其含義參見題目描述;
接下去m行,每行3個數字u v w,分別代表這條線路的起點,終點和長度。
[Technical Specification]
1. n<=100000
2. m <= 1000000
3. 1<= u, v <= n
4. w <= 1000
Output 對於每組測試數據,如果能夠建成環形(並不需要連接上去全部的風景點),那么輸出YES,否則輸出最長的長度,每組數據輸出一行。
Sample Input
3 3 1 2 1 2 3 1 3 1 1Sample Output
YES
題意 : 先判斷一下圖中是否有環,有就直接輸出YES,否則在輸出這個無環圖中的最長鏈
思路分析:判斷一個圖中是否有環,采用並查集即可,找樹上的最長鏈,也就是樹的直徑,有兩種方法,一種是用采用樹形dp,那么樹上最長的鏈就是當前結點最遠和次遠的兒子加起來的和。
dp[x][0] 表示樹上次遠的距離是多少, dp[x][1]表示樹上最遠的距離是多少。
代碼示例:
const int maxn = 1e5+5;
int n, m;
struct node
{
int to, cost;
node(int _to=0, int _cost=0):to(_to), cost(_cost){}
};
vector<node>ve[maxn];
int f[maxn];
int fid(int x){
if (x != f[x]) f[x] = fid(f[x]);
return f[x];
}
bool pt[maxn];
int dp[maxn][2];
int ans;
void dfs(int x, int fa){
pt[x] = true;
for(int i = 0; i < ve[x].size(); i++){
int to = ve[x][i].to;
int cost = ve[x][i].cost;
if (to == fa) continue;
dfs(to, x);
if (dp[x][1] < dp[to][1]+cost){
dp[x][0] = dp[x][1];
dp[x][1] = dp[to][1]+cost;
}
else if (dp[x][0] < dp[to][1]+cost){
dp[x][0] = dp[to][1]+cost;
}
}
ans = max(ans, dp[x][1]+dp[x][0]);
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int x, y, z;
while(~scanf("%d%d", &n, &m)){
for(int i = 1; i <= n; i++) f[i]=i, ve[i].clear();
int flag = 0;
for(int i = 1; i <= m; i++){
scanf("%d%d%d", &x, &y, &z);
ve[x].push_back(node(y, z));
ve[y].push_back(node(x, z));
int x1 = fid(x), x2 = fid(y);
if (x1 == x2) flag = 1;
else f[x1] = x2;
}
if (flag) {printf("YES\n"); continue;}
memset(pt, false, sizeof(pt));
memset(dp, 0, sizeof(dp));
ans = 0;
for(int i = 1; i <= n; i++){
if (!pt[i]) dfs(i, 0);
}
printf("%d\n", ans);
}
return 0;
}
