https://nanti.jisuanke.com/t/16957
Skiing
Description
In this winter holiday, Bob has a plan for skiing at the mountain resort.
This ski resort has MM different ski paths and NN different 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≤10000 and 0 < M \leq 1000000<M≤100000as 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.
样例输入
1
5 4
1 3 3
2 3 4
3 4 1
3 5 2
样例输出
6
题目来源
思路
题目大意:给你一个n个点m条边的DAG(有向无环图),求最长路
题目思路:DAG上的最长路,直接拓扑排序。dp记录到第i个节点的最长路径和。最后遍历dp数组找到DAG的最长路。
AC Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int nmax=1e5+10;
int inDegree[nmax];//存每个节点的入度
vector<pair<int,int>>G[nmax];//邻接表 1st存节点,2nd存边权
int dp[nmax];//从初始节点到第i个节点的最长路径和
int n,m;//点数,边数
void toposort(){
queue<int>q;
while(!q.empty()) q.pop();//清空队列
for(int i=1;i<=n;i++){//顶点编号:1~N
if(inDegree[i]==0){
q.push(i);//把入度为0的顶点扔进队列
}
}
while(!q.empty()){
int u=q.front();
q.pop();//删除该点
for(int i=0;i<G[u].size();i++){//遍历与点u相邻的所有边,删除之。
int v=G[u][i].first;
inDegree[v]--;
if(inDegree[v]==0){
q.push(v);//队列里放点
}
dp[v]=max(dp[v],dp[u]+G[u][i].second);
}
//G[u].clear();
}
}
int main(int argc, char** argv) {
int t;
scanf("%d",&t);
while(t--){
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){//初始化清空邻接表
G[i].clear();
}
memset(inDegree,0,sizeof(inDegree));
memset(dp,0,sizeof(dp));
int u,v,w;
for(int i=0;i<m;i++){
scanf("%d %d %d",&u,&v,&w);
G[u].push_back(make_pair(v,w));
inDegree[v]++;
}
toposort();
int maxx=-1;
for(int i=1;i<=n;i++){
maxx=max(maxx,dp[i]);//找到这些路径和中最大的
}
printf("%d\n",maxx);
}
return 0;
}