Luo Valley P2136 negative draw closer bidirectional ring spfa take min

Topic links:

https://www.luogu.org/problem/P2136

Ideas tips blog: https://www.luogu.org/blog/user27165/solution-p2136

Ideas:

1: Key: "closer together" is not necessarily Xiaoming, it may be red, the subject did not give a specific source sink, when to do so in spfa, respectively, n is 1 and each source do it again, taking min

    spfa(1);
    int mi=d[n];
    spfa(n);
    cout<<min(mi,d[1])<<endl;

2: negative determination method rings, cnt array, a stored node number into the team, if more than n indicates the presence of a negative ring

#include <bits/stdc++.h>

using namespace std;
const int maxn=1e3+1;
vector<pair<int,int> >e[maxn];
int n,m,ing[maxn],a,b,c,d[maxn],cnt[maxn];

inline void spfa(int s)
{
    memset(ing,0,sizeof(ing));
    memset(d,0x7f,sizeof(d));
    queue<int>q;
    q.push(s);
    cnt[s]++;
    d[s]=0;
    ing[s]=1;
    while(!q.empty())
    {
        int now=q.front();
        q.pop();
        ing[now]=0;
        if(cnt[now]>n)
        {
            cout<<"Forever love"<<endl;
            exit(0);
        }
        for(int i=0;i<e[now].size();i++)
        {
            int v=e[now][i].first;
            if(d[v]>d[now]+e[now][i].second)
            {
                d[v]=d[now]+e[now][i].second;
                if(ing[v])
                    continue;
                q.push(v);
                cnt[v]++;
                ing[v]=1;
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(0);
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>a>>b>>c;
        e[a].push_back(make_pair(b,-c));
    }
    spfa(1);
    int mi=d[n];
    spfa(n);
    cout<<min(mi,d[1])<<endl;
    return 0;
}

 

Published 117 original articles · won praise 37 · views 6610

Guess you like

Origin blog.csdn.net/aiwo1376301646/article/details/100584669