首页 > 试题广场 >

Magic Maze

[编程题]Magic Maze
  • 热度指数:4 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 128M,其他语言256M
  • 算法知识视频讲解
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
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1005,INF=999999999;
int G[maxn][maxn],dp[maxn];
int d(int);
int T,i,j,n,m,a,b,c;
int main(){
    //freopen("input.txt","r",stdin);
    for(scanf("%d",&T);T--;){
        for(i=0;i<maxn;i++)
            for(j=0;j<maxn;j++) G[i][j]=INF;
        for(i=0;i<maxn;i++) dp[i]=INF;
        for(scanf("%d%d",&n,&m),i=0;i<m;i++){
            scanf("%d%d%d",&a,&b,&c);
            G[a][b]=c;
        }
        int Max=-INF;
        for(i=0;i<n;i++) Max=max(Max,d(i));
        printf("%d\n",Max);
    }
}
int d(int x){
    if(dp[x]!=INF) return dp[x];
    dp[x]=0;
    for(int i=0;i<n;i++)
        if(G[x][i]!=INF)
            dp[x]=max(dp[x],d(i)+G[x][i]);
    return dp[x];
}//记忆搜索

发表于 2017-10-26 16:40:45 回复(0)

问题信息

上传者:牛客301599号
难度:
1条回答 1956浏览

热门推荐

通过挑战的用户