题解 P3385 【【模板】负环】

Solution

这题有毒!!!!!
spfa判负环常用的有两种,一种是判断松弛次数,但它会绕环好多次,另一种是判断最短路径的长度,只要绕环一次,前一种本题过不了。

判断最短路径的长度的意思就是用一个len数组记录从源点到当前节点的最短路径经过的边数,并在松弛时令len[v]=len[u]+1。若len[v]>=n则必然存在负环。

为了解决图不联通的问题,引入一个新的数组searched,searched[v]表示是否从v出发搜索过,每一次找一个searched值为false的点开始搜。同时,还可以用searched数组进行一些剪枝....(不过本题的鬼畜数据不需要)

有意思的是,第55行的check()换成spfa(1)也能过....... UPD:是我没看题目.jpg

正解:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=2005;
const int maxm=6005;
struct Edge { int v,w; Edge *next; };
Edge *G[maxn],mem[maxm],*ecnt;
inline void AddEdge(int u,int v,int w) { ecnt->v=v; ecnt->w=w; ecnt->next=G[u]; G[u]=ecnt++; }
int T,n,m;
int dis[maxn],len[maxn];
bool inq[maxn],searched[maxn];
bool spfa(int s)
{
    queue<int> que;
    memset(inq,false,sizeof(inq));
    memset(dis,0x3F,sizeof(dis));
    que.push(s);
    dis[s]=0; inq[s]=true; len[s]=0; searched[s]=true;
    while(que.size())
    {
        int u=que.front(); que.pop(); inq[u]=false;
        for(Edge *it=G[u];it;it=it->next)
            if(dis[it->v]>dis[u]+it->w)
            {
                dis[it->v]=dis[u]+it->w;
                len[it->v]=len[u]+1;
                searched[it->v]=true;
                if(len[it->v]>=n) return true;
                if(!inq[it->v]) { inq[it->v]=true; que.push(it->v); }
            }
    }
    return false;
}
bool check()
{
    memset(searched,0,sizeof(searched));
    // for(int i=1;i<=n;i++) if(!searched[i]&&spfa(i)) return true;
    return spfa(1);
}
int main()
{
    scanf("%d",&T);
    while(T-->0)
    {
        memset(G,0,sizeof(G)); ecnt=mem;
        scanf("%d%d",&n,&m);
        for(int i=0;i<m;i++)
        {
            int a,b,w; scanf("%d%d%d",&a,&b,&w);
            AddEdge(a,b,w);
            if(w>=0) AddEdge(b,a,w);
        }
        puts(check()?"YE5":"N0");
    }
    return 0;
}

转载于:https://www.cnblogs.com/happyZYM/p/11379559.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值