Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 1232 | Accepted: 619 |
Description
Input
Output
Sample Input
5 2
1 2 1
2 3 2
3 4 2
4 5 1
Sample Output
6
Source
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <queue> using namespace std; int const MAX = 100005; int n, s, cnt; int dis[MAX], head[MAX]; struct EGDE { int v, w, next; }e[MAX]; void Add(int u, int v, int w) { e[cnt].v = v; e[cnt].w = w; e[cnt].next = head[u]; head[u] = cnt++; } void DFS(int u, int fa, int d) { for(int i = head[u]; i != -1; i = e[i].next) { int v = e[i].v; int w = e[i].w; if(v != fa) { dis[v] = w + d; DFS(v, u, w + d); } } return; } int main() { cnt = 0; int sum = 0; scanf("%d %d", &n, &s); memset(head, -1, sizeof(head)); memset(dis, 0, sizeof(dis)); for(int i = 0; i < n - 1; i++) { int u, v, w; scanf("%d %d %d", &u, &v, &w); Add(u, v, w); Add(v, u, w); sum += 2 * w; } dis[s] = 0; DFS(s, -1, 0); int o, ma = -1; for(int i = 1; i <= n; i++) { if(dis[i] > ma) { ma = dis[i]; o = i; } } dis[o] = 0; DFS(o, -1, 0); ma = -1; for(int i = 1; i <= n; i++) if(dis[i] > ma) ma = dis[i]; printf("%d\n", sum - ma); }
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int const MAX = 100005; int head[MAX], dp[MAX][2]; int n, s, cnt, ans; struct EDGE { int v, w, next; }e[MAX]; void Add(int u, int v, int w) { e[cnt].v = v; e[cnt].w = w; e[cnt].next = head[u]; head[u] = cnt ++; } void DFS(int u, int fa) { dp[u][0] = dp[u][1] = 0; for(int i = head[u]; i != -1; i = e[i].next) { int v = e[i].v; int w = e[i].w; if(v != fa) { DFS(v, u); if(dp[u][0] < dp[v][0] + w) { int tmp = dp[u][0]; dp[u][0] = dp[v][0] + w; dp[u][1] = tmp; } else if(dp[u][1] < dp[v][0] + w) dp[u][1] = dp[v][0] + w; } } ans = max(ans, dp[u][1] + dp[u][0]); return; } int main() { cnt = 0; ans = 0; memset(head, -1, sizeof(head)); scanf("%d %d", &n, &s); int sum = 0; for(int i = 0; i < n - 1; i++) { int u, v, w; scanf("%d %d %d", &u, &v, &w); Add(u, v, w); Add(v, u, w); sum += 2 * w; } DFS(s, -1); printf("%d\n", sum - ans); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/tc_to_top/article/details/47002255