题目描述
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
题意:给你n个点,m条边,这m条边是单向边,让你规定一个起点和终点,
使得走过的路的权值之和最小。题目保证不会有环,并且一个点只会经过一次。
题解:我们可以考虑按照最大字段和的dp方式搞这道题,当然,起点一定是入度为0
的点,类似于拓扑排序,每次加入队列的点一定是当前入度为0的点。然后广搜DP即可。
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<string>
#include<time.h>
#include<math.h>
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<functional>
using namespace std;
#define ll long long
#define inf 1000000000
#define mod 1000000007
#define maxn 100100
#define lowbit(x) (x&-x)
#define eps 1e-9
struct node
{
int x,y;
};
vector<node>q[1005];
queue<int>t;
int ans,in[1005],flag[1005],dp[1005];
int main(void)
{
int T,n,m,i,x,y,z,j;
scanf("%d",&T);
while(T--)
{
ans=0;
while(t.empty()==0)
t.pop();
memset(in,0,sizeof(in));
memset(dp,0,sizeof(dp));
memset(flag,0,sizeof(flag));
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
node tmp;
tmp.x=y;tmp.y=z;
q[x].push_back(tmp);
in[y]++;
}
for(i=0;i<n;i++)
if(in[i]==0)
t.push(i);
while(t.empty()==0)
{
int now=t.front();
t.pop();
flag[now]=1;
for(i=0;i<q[now].size();i++)
{
node v=q[now][i];
if(flag[v.x]==1)
continue;
dp[v.x]=max(dp[v.x],dp[now]+v.y);
in[v.x]--;
if(in[v.x]==0)
t.push(v.x);
}
}
for(i=0;i<n;i++)
ans=max(ans,dp[i]);
printf("%d\n",ans);
for(i=0;i<n;i++)
q[i].clear();
}
return 0;
}