题目描述
There is a magic maze that its roads is unidirectional and you will not arrive the same resting area if you walk alongthe road (the maze is acyclic). There are n resting areas and m roads in themaze. Some roads make you get treasure, while others make you lost treasure. You should pick the place to set out and get treasure as much as possible.
Note that for each road you can go through only once.
输入描述:
The first line: the number of case T (1≤T≤110 ) In each test case: The first line is two integers: the number of resting area n, the number of roads m(1≤n≤1000, 0≤m≤n×(n−1)÷2) m lines follow, each with three integers: the beginning u, the end v, treasure w(0≤u<n,0≤v<n,−1000≤w≤1000)
输出描述:
T lines, each with an integer what is the maximum treasure
示例1
输入
复制
2 5 4 0 1 -10 1 2 10 2 3 10 3 4 -10 4 4 0 1 4 0 2 5 2 3 -2 3 1 4
输出
复制
20 7
说明
In the first example, you can go 1 ->2 >3, then the ans is 10+10=20 In the second example, you can go 0 ->2 ->3>-1, then the ans is 5−2+4=7
思路:
首先看到这个问题肯定会想到用dfs加动态规划来做(因为有不同的路径,又要求最大值) 但最开始我就根据自己想的 先用start数组找到起点 再从起点依次使用dfs找到路径再找到最大值。
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int dp[N];
typedef pair<int,int> pii;
vector<pii> v[N];
int dfs(int op){
int res=0;
if(dp[op]) return dp[op];
for(int i=0;i<v[op].size();i++){
int x=v[op][i].first;
int y=v[op][i].second;
res=max(res,dfs(x)+y);
}
dp[op]=res;
return res;
}
void solve(){
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++){
int x,y,z;
cin>>x>>y>>z;
v[x].push_back({y,z});
}
int maxl=0;
for(int i=0;i<n;i++){
if(dp[i]) continue;
maxl=max(maxl,dfs(i));
}
for(int i=0;i<n;i++){
maxl=max(maxl,dp[i]);
dp[i]=0;
v[i].clear();
}
cout<<maxl<<"\n";
}
signed main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int t=1;
cin>>t;
while(t--){
solve();
}
}