Magic Maze(dp+dfs)

14 篇文章 0 订阅
2 篇文章 0 订阅

传送门

题目描述

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();
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值