【拓扑排序专题】计蒜客 16957 Skiing (求DAG的最长路)

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

题目来源

2017 ACM-ICPC 亚洲区(乌鲁木齐赛区)网络赛

思路

题目大意:给你一个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;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值