【dfs】(样题,熟悉邻接表写法vector) 单源最大权路径 CSU - 1960 【从起点走,找一条路径,使权和最大】
有一棵由N个结点构成的树,每一条边上都有其对应的权值。现在给定起点,求从该点出发的一条路径(至少有一条边)使得这条路径上的权值之和最大,并输出这个最大值。
Input
第一行一个正整数T,代表数据组数。每组数据第一行两个正整数n(2<=n<=10^5),s(1<=s<=n),分别表示树结点数目以及给定的起点,点的编号从1至N。接下来M行,每行三个整数x,y,z,(1<=x,y<=n,|z|<=1000),代表编号为x和y的点之间有一条权值为z的双向边。
Output
每组数据输出一行,即所找到路径的最大权值(格式参见样例)。
Sample Input
2
3 1
1 2 10
1 3 5
5 5
1 5 70
4 3 100
5 3 -10
2 5 60
Sample Output
Case #1: 10
Case #2: 90
题意:
给一棵树和起点,求从该点出发的一条路径, 使权值之和最大,输出最大值。
思路:
dfs,记录路径权值和,不断更新最大值。
PS:
这里点比较多,不能用数组记录边,可以用vector实现邻接表。注意每一次清理邻接表。
AC代码:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 100005;
int vis[maxn];
int n, st, ans, sum;
struct edge
{
int v, w;
edge(int vv, int ww): v(vv), w(ww) {}
};
vector<edge> G[maxn];
void dfs(int s)
{
vis[s] = 1;
for(int i = 0; i < G[s].size(); i++)
{
int next = G[s][i].v;
int val = G[s][i].w;
if(!vis[next])
{
sum += val;
ans = max(ans, sum);
dfs(next);
vis[next] = 0;
sum -= val;
}
}
}
int main()
{
int t;
scanf("%d", &t);
for(int k = 1; k <= t; k++)
{
scanf("%d%d", &n, &st);
ans = -INF;
sum = 0;
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n; i++)
G[i].clear();
int v, u, w;
for(int i = 0; i < n - 1; i++)
{
scanf("%d%d%d", &v, &u, &w);
G[v].push_back(edge(u, w));
G[u].push_back(edge(v, w));
}
dfs(st);
printf("Case #%d: %d\n", k, ans);
}
return 0;
}