UVALive 6800 THE MOUNTAIN OF GOLD?

题目PDF链接
题意:有一些时光隧道连接两个Mountain,问能否从 0号点 (Ledang Mountain in Malaysia) 穿越到 0号点的过去。
题解:其实就是SPFA判负环,这个负环包含 0号点。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define prt(k) cout<<#k" = "<<k<<endl;
const int inf = 0x3f3f3f3f;
int n, m;
#include <vector>
const int N = 1222;
const int M = 3333;
vector<pair<int,int> > g[N];
#define pb push_back
#define MP make_pair
#include <queue>
struct EE
{
    int to, next, w;
}e[M*2];
int head[N];
int L = 0;

void add(int u,int v,int w) {
    e[L].to = v;
    e[L].w = w;
    e[L].next = head[u];
    head[u] = L++;
}
bool spfa()
{
    queue<int> q;
    int d[N];
    bool inq[N];
    memset(inq, false, sizeof inq);
    memset(d, 63, sizeof d);
    d[0] = 0;
    int use[N];
    memset(use, 0 , sizeof use);
    use[0] = 1;
    inq[0] = true;
    q.push(0);
    while (!q.empty())
    {
        int u = q.front(); q.pop();
        inq[u]=false;
        if (u==n && d[n]<0) return true;
        for(int i=head[u];~i;i=e[i].next)
        {
            int v = e[i].to;
            int w = e[i].w;
            if (d[v] > d[u] + w)
            {

                d[v] = d[u] + w;
                if (!inq[v] && use[v]<=n)
                {
                    q.push(v);
                    inq[v] = true;
                    if (use[v]==n) d[v] = -inf;
                    use[v] ++;
                }
            }
        }
    }
    return (d[0] < 0);
}
int main()
{
    int re; cin>>re;
    int ca = 1;
    char yes[] = "possible", no[] = "not possible";
    while (re--)
    {
        for(int i=0;i<N;i++) g[i].clear();
        L = 0;
        memset(head, -1, sizeof head);
        cin >> n >> m;
        for(int i=0;i<m;i++)
        {
            int a,b,c;
            cin>>a>>b>>c;
            add(a, b, c);
        }
        printf("Case #%d: ", ca++);
        if (spfa())
        {
            puts(yes);
        }
        else puts(no);
    }
    return 0;
}
/** 2 2 2 0 1 15 1 0 -20 4 4 0 1 10 1 2 20 2 3 30 3 0 -60 */

你可能感兴趣的:(using,pdf,图论,SPFA,bfs)