计蒜客 Skiing 2017乌鲁木齐网络赛 拓扑排序

题目:

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<N10000and 0 < M \leq 1000000<M100000 as described above.

Each of the following MM lines contains three integers S_iSiT_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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值