ICPC2017网络赛(乌鲁木齐)H: Skiing (SPFA最长路)


H: Skiing

 time limit 1000ms memory limit 131072KB
 
i i
In this winter holiday, Bob has a plan for skiing at the mountain resort. This ski resort has M different ski paths and N different flags situated at those turning points. The i-th path from the S -th flag to the T -th flag has length L . 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 T, indicating that there are T cases. In each test case, the first line contains two integers N and M where 0 < N ≤ 10000 and 0 < M ≤ 100000 as described above. Each of the following M lines contains three integers S , T , and L  (0 < L < 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. Sample Input
1 5 4 1 3 3 2 3 4 3 4 1 3 5 2
Sample Output
6
 

【题意】:

给出一个有向无环图,找一条最长路,输出长度

【解析】:

统计入度为0的点,然后对这些点为起点,跑SPFA,同时记忆化搜索记录每个点的最优值。

【代码】:

#include <stdio.h>
#include <stdlib.h>  
#include <string.h>  
#include <iostream>  
#include <algorithm> 
#include <queue>  
#define mset(a,i) memset(a,i,sizeof(a))
using namespace std;
typedef long long ll;
struct node{
    int to,val,next; 
}e[101010];
int n,m,x,y,val,cnt ; 
int IN[10101],head[10101] ;
ll dis[10101];
queue <int> Q ;
void add(int x,int y,int v)
{
    e[cnt] = (node){ y,v,head[x] } ; 
    head[x] = cnt++; 
}
void SPFA(int s)
{
    int u,v;
    while(!Q.empty())Q.pop();
    Q.push(s);
    while(!Q.empty())  
     {
        u=Q.front() ; 
        Q.pop() ;
        for(int i=head[u];~i;i=e[i].next)
        {
            v=e[i].to;
            if(dis[v]<dis[u]+e[i].val)
            {
                dis[v]=dis[u]+e[i].val;
                Q.push(v);
           }
        }
   }
}
int main() 
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		mset(IN,0);
		mset(head,-1);
		mset(dis,0);
		cnt=0;
		scanf("%d%d",&n,&m) ; 
	    for(int i=1;i<=m;i++)
	    {
	    	scanf("%d%d%d",&x,&y,&val);
			add(x,y,val);
	    	IN[y]++;
		}
	     if(n==1)
	     {
	        printf("0\n");
	        continue;
	    }
	    for(int i=1;i<=n;i++)
	    {
	    	if(IN[i]==0)
	  			SPFA(i);
		}
		ll ans=0;
		for(int i=1;i<=n;i++)
		{
			ans=max(ans,dis[i]);
		}
		printf("%lld\n",ans);
	}
    return 0 ;  
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/winter2121/article/details/77916499
文章标签: icpc spfa最长路
个人分类: ACM**图论*******
所属专栏: ACM荣耀之路
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭