【2017新疆网络赛】H Skiing 最短路径spfa 模版

37 篇文章 0 订阅
20 篇文章 0 订阅

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 SiSi-th flag to the TiTi-th flag has length LiLi.

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≤100000<N10000 and 0<M≤1000000<M100000 as described above.

Each of the following MM lines contains three integers SiSiTiTi, and Li (0<Li<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条边,求最长路径。


思路:

spfa模版题,设置超级源点到每个点一条权为0的边,图上以权值的相反值建边,求最短路径

//
//  main.cpp
//  H
//
//  Created by zc on 2017/9/15.
//  Copyright © 2017年 zc. All rights reserved.
//
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=11000;
const int M=110000;
const int INF=0x3f3f3f3f;
int head[N],cnt;

struct node
{
    int next,v,w;
}e[M];

void init()
{
    memset(head,-1,sizeof(head));
    cnt=0;
}

void add(int u,int v,int w)
{
    e[cnt].v=v;
    e[cnt].w=w;
    e[cnt].next=head[u];
    head[u]=cnt++;
}

int d[N],v[N],n,m;

void spfa(int u)
{
    for(int i=0;i<=n;i++)   d[i]=INF,v[i]=0;
    queue<int>q;
    q.push(u);v[u]=1;d[u]=0;
    while(!q.empty())
    {
        int c=q.front();
        q.pop();
        v[c]=0;
        for(int i=head[c];i+1;i=e[i].next)
        {
            int t=e[i].v;
            if(d[t]>d[c]+e[i].w)
            {
                d[t]=d[c]+e[i].w;
                if(!v[t])   q.push(t);
            }
        }
    }
}


int main(int argc, const char * argv[]) {
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        init();
        for(int i=0;i<m;i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            add(u, v, -w);
        }
        for(int i=1;i<=n;i++)   add(0, i, 0);
        spfa(0);
        int ans=0;
        for(int i=1;i<=n;i++)   ans=max(ans,-d[i]);
        printf("%d\n",ans);
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值