DFS - spfa 判负环 ( L - The Shortest Path )

L - The Shortest Path ( DFS - spfa 判负环 )

题目链接:http://codeforces.com/gym/101498/problem/L

Input

3
3 3
1 2 -1
2 3 -3
3 1 -5
4 5
1 3 0
1 2 -2
2 3 3
3 4 1
4 1 -1
4 4
1 2 5
2 3 -3
3 4 -3
1 4 2

Output

-inf
-3
-6

题意:n个点m条边的有向图,任选两点的最短距离的最小值是多少,如果有负回路输出-inf。

思路:定义一个源点s和一个汇点t,都和1~n个点相连,权值为0,从s点跑spfa后得到的dis[t] 就是中间部分能产生的最小值。

注意:这个题可能存在非常多的负回路,但用bfs写的普通spfa找负回路太慢了,因为它要有边松弛n+次才能确定有负回路。所以这个题用DFS写的spfa来做,dfs找负回路就很简单了( 见代码 ),只需要某个点又 松弛 回来了,就肯定又负回路了。

代码:

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <queue>
#define inf 0x3f3f3f3f

using namespace std;

const int maxn = 1e4+10;
int head[maxn];
int dis[maxn];
int via[maxn];
int num[maxn];
int cnt,n,m,mm,flag;
int ans;

struct node {
    int to,w,next;
} e[maxn];

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

void spfa( int node )
{
    if ( flag==1 ) return ;
    via[ node ] = 1;
    for ( int i=head[node]; i!=-1; i=e[i].next ) {
        int to = e[i].to, w=e[i].w;
        if ( dis[to]>dis[node]+w ) {
            dis[to] = dis[node] + w;
            if ( flag==0 && via[to]==1 ) { // 形成了负环
                flag = 1;
                break;
            }
            else spfa(to);
        }
    }
    via[ node ] = 0;
}

int main()
{
    int listt,i,j,x,y,z;
    cin >> listt;
    while ( listt-- ) {
        memset(via,0,sizeof(via));
        memset(dis,0x3f,sizeof(dis)); // 最短路设成inf,最长路设成0
        flag = 0;
        scanf("%d %d",&n,&m);
        n += 2;
        memset(head,-1,sizeof(head));
        cnt = 0; ans=0x3f3f3f3f;
        for ( i=0; i<m; i++ ) {
            scanf("%d %d %d",&x,&y,&z);
            addage(x,y,z);
            ans = min(ans,z);
        }
        if ( ans>=0 ) {printf("%d\n",ans);continue;}
        for ( int i=1; i<=n; i++ ) {
            addage(0,i,0);
            addage(i,n+1,0);
        }
        dis[0] = 0; // 非常重要!!记得从哪个点出发就把他设成0
        spfa(0);
        if ( flag==1 ) printf("-inf\n");
        else printf("%d\n",dis[n+1]);
    }

    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值