即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

POJ – 3259 Wormholes解题报告(SPFA判断负权环)

编程语言 Anna__1997 21℃ 0评论
#include 
#include 
#include 
#include 
#include 
#define INF 0x3f3f3f3f
using namespace std;
struct Edge
{
    int from, to, dist;
    Edge(int u, int v, int d): from(u), to(v), dist(d) {}
};

vector edges;
vector G[501];
bool SPFA(int n)
{
    queue Q;
    int d[501];
    memset(d, 0x3f, sizeof(d));
    d[1] = 0;
    bool v[501];
    int cnt[501];
    memset(cnt, 0, sizeof(cnt));
    memset(v, 0, sizeof(v));
    v[1] = true;
    Q.push(1);
    while (!Q.empty())
    {
        int temp = Q.front();
        Q.pop();
        v[temp] = false;
        for (int k = 0; k < G[temp].size(); k++)
        {

            Edge& e = edges[G[temp][k]];
            if (d[temp] < INF && d[e.to] > d[temp] + e.dist)
            {
                d[e.to] = d[temp] + e.dist;
                if (!v[e.to])
                {
                    Q.push(e.to);
                    v[e.to] = true;
                    if (++cnt[e.to] > n)
                        return false;
                }

            }

        }

    }
    return true;
}
int main()
{
    freopen("aa.txt", "r", stdin);
    int F, n, m, w; //fields path wormhole
    scanf("%d", &F);
    int a, b, t;


    while (F--)
    {
        edges.clear();
        for (int i = 0; i < 501; i++)
            G[i].clear();
        cin >> n >> m >> w;
        while (m--)
        {
            scanf("%d %d %d", &a, &b, &t);
            //cin >> a >> b >> t;
            edges.push_back(Edge(a, b, t));
            int k = edges.size();
            G[a].push_back(k - 1);
            edges.push_back(Edge(b, a, t));
            k = edges.size();
            G[b].push_back(k - 1);


        }
        while (w--)
        {
            scanf("%d %d %d", &a, &b, &t);
            //cin >> a >> b >> t;
            edges.push_back(Edge(a, b, -t));
            int k = edges.size();
            G[a].push_back(k - 1);

        }

        if (!SPFA(n))
            printf("YES\n");

        else
            printf("NO\n");
            //cout << "NO" << endl;



    }
}


转载请注明:CodingBlog » POJ – 3259 Wormholes解题报告(SPFA判断负权环)

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情