UVa 558 - Wormholes(SPFA)

来源:互联网 发布:魅可mac什么档次 编辑:程序博客网 时间:2024/04/30 13:03

题目链接:UVa 558 - Wormholes

SPFA。

肿么图论都忘了。。复习一下。。

#include <iostream>#include <cstring>#include <queue>using namespace std;const int MAX_N = 2000 + 100;const int MAX_M = 1000 + 50;const int INF = (1 << 30);int next[MAX_N],head[MAX_M],u[MAX_N],v[MAX_N],w[MAX_N],d[MAX_M],cnt[MAX_M],vis[MAX_M];int n,m,T;void read_graph(){    cin >> n >> m;    memset(head,-1,sizeof(head));    for(int e = 1;e <= m;e++)    {        cin >> u[e] >> v[e] >> w[e];        next[e] = head[u[e]];        head[u[e]] = e;    }}bool SPFA(int src){    memset(vis,0,sizeof(vis));    memset(cnt,0,sizeof(cnt));    for(int i = 0;i < n;i++)        d[i] = INF;    d[src] = 0;    queue<int> Q;    Q.push(src);    cnt[src]++;    while(!Q.empty())    {        int u = Q.front();        Q.pop();        vis[u] = false;        for(int e = head[u];e != -1;e = next[e])        {            if(d[v[e]] > d[u] + w[e])            {                d[v[e]] = d[u] + w[e];                if(!vis[v[e]])                {                    Q.push(v[e]);                    vis[v[e]] = true;                    cnt[v[e]]++;                    if(cnt[v[e]] >= n)                        return true;                }            }        }    }    return false;}int main(){    cin >> T;    while(T--)    {        read_graph();        if(SPFA(0))            cout << "possible" << endl;        else            cout << "not possible" << endl;    }    return 0;}


0 0
原创粉丝点击