题目:
In this winter holiday, Bob has a plan for skiing at the mountain resort.
This ski resort has MM different ski paths and NNdifferent flags situated at those turning points.
The ii-th path from the S_iSi-th flag to the T_iTi-th flag has length L_iLi.
Each path must follow the principal of reduction of heights and the start point must be higher than the end point strictly.
An available ski trail would start from a flag, passing through several flags along the paths, and end at another flag.
Now, you should help Bob find the longest available ski trail in the ski resort.
Input Format
The first line contains an integer TT, indicating that there are TT cases.
In each test case, the first line contains two integers NN and MM where 0 < N \leq 100000<N≤10000and 0 < M \leq 1000000<M≤100000 as described above.
Each of the following MM lines contains three integers S_iSi, T_iTi, and L_i~(0 < L_i < 1000)Li (0<Li<1000)describing a path in the ski resort.
Output Format
For each test case, ouput one integer representing the length of the longest ski trail.
题意:给定一个DAG,求最长路径的长度。
思路:拓扑排序。用一个数组记录一下到达每个点的路径长度。队列每次pop出一个入度为0的点时,都用到达它的最长路径更新与它相邻的点,最终结果是所有点结果的最大值。
代码:拓扑排序
#include<bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define ss(x) scanf("%s",x)
#define sc(x) scanf("%c",&x)
#define sf(x) scanf("%f",&x)
#define slf(x) scanf("%lf",&x)
#define slld(x) scanf("%lld",&x)
#define me(x,b) memset(x,b,sizeof(x))
#define pd(d) printf("%d\n",d);
#define plld(d) printf("%lld\n",d);
#define eps 1.0E-8
// #define Reast1nPeace
typedef long long ll;
using namespace std;
const int maxn = 1e5+10;
int n,m;
vector<pair<int,int> > G[maxn];
int maxlen[maxn];
int in[maxn];
void topsort(){
queue<int> q;
for(int i = 1 ; i<=n ; i++){
if(!in[i]) q.push(i);
}
while(!q.empty()){
int now = q.front() ; q.pop();
for(int i = 0 ; i<G[now].size() ; i++){
int to = G[now][i].first;
int len = G[now][i].second;
maxlen[to] = max(maxlen[to] , maxlen[now]+len);
in[to]--;
if(!in[to]) q.push(to);
}
}
}
int main(){
#ifdef Reast1nPeace
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
int T;
cin>>T;
while(T--){
memset(maxlen,0,sizeof(maxlen));
memset(in,0,sizeof(in));
for(int i = 1 ; i<=n ; i++) G[i].clear();
cin>>n>>m;
int s,t,l;
for(int i = 1 ; i<=m ; i++){
cin>>s>>t>>l;
G[s].push_back(make_pair(t,l));
in[t]++;
}
topsort();
int maxn = 0;
for(int i = 1 ; i<=n ; i++){
maxn = max(maxn,maxlen[i]);
}
cout<<maxn<<endl;
}
return 0;
}