2017 ACM-ICPC网络赛 H.Skiing 有向图最长路

H.Skiing

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<N10000 and 0 < M \leq 1000000<M100000 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.

样例输入

1
5 4
1 3 3
2 3 4
3 4 1
3 5 2

样例输出

6





代码:
#include<bits/stdc++.h>
//#include<regex>
#define db double
#define ll long long
#define vec vector<ll>
#define Mt  vector<vec>
#define ci(x) scanf("%d",&x)
#define cd(x) scanf("%lf",&x)
#define cl(x) scanf("%lld",&x)
#define pi(x) printf("%d\n",x)
#define pd(x) printf("%f\n",x)
#define pl(x) printf("%lld\n",x)
#define MP make_pair
#define PB push_back
#define fr(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int N=1e6+5;
const int mod=1e9+7;
const int MOD=mod-1;
const db  eps=1e-18;
const db  pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
typedef pair<int,int> P;
vector<P>g[N];
int a[N],f[N];
queue<int> q;
bool vis[N];
int main()
{
    int t;
    ci(t);
    while(t--)
    {
        int n,m;
        memset(f,0, sizeof(f));
        memset(a,0, sizeof(a));
        ci(n),ci(m);
        for(int i=1;i<=n;i++) g[i].clear();
        for(int i=0;i<m;i++){
            int x,y,z;
            ci(x),ci(y),ci(z);
            g[x].push_back(P(y,z));
            a[y]++;// 入度
        }
        for(int i=1;i<=n;i++){
            if(!a[i]) q.push(i); //入度点
        }
        int ma=0;
        while(q.size())//按拓扑序来找最长路
        {
            int u=q.front();
            q.pop();
            for(int i=0;i<g[u].size();i++){
                int v=g[u][i].first;
                int d=g[u][i].second;
                f[v]=max(f[v],f[u]+d);
                ma=max(ma,f[v]);
                a[v]--;
                if(!a[v]) q.push(v);
            }
        }
        pi(ma);
    }

}

 

 
posted @ 2017-09-13 23:48  thges  阅读(499)  评论(0编辑  收藏  举报