UVA 558 Wormholes 【SPFA 判負環】
阿新 • • 發佈:2018-02-02
math.h struct possible sta clas ack names dsm 推斷
題目鏈接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=499
題意:就是推斷圖中有無負環
SPFA,某個節點入隊次數大於n就是有負環。
代碼:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <malloc.h>
using namespace std;
const int MAXN = 41000;
const int INF = 0x3f3f3f3f;
struct Edge
{
int v;
int cost;
Edge(int _v = 0, int _cost = 0)
{
v = _v;
cost = _cost;
}
};
vector<Edge> E[MAXN];
void addedge(int u, int v, int cost)
{
E[u].push_back(Edge(v, cost));
}
bool vis[MAXN];
int cnt[MAXN];//記錄入隊列的次數
int dist[MAXN];
////////////////
bool SPFA(int start, int n)
{
memset(vis, false, sizeof(vis));
memset (cnt, 0, sizeof(cnt));
for (int i = 0; i <= n; i++) dist[i] = INF;
vis[start] = true;
dist[start] = 0;
queue<int> que;
while (!que.empty()) que.pop();
que.push(start);
cnt[start] = 1;
while (!que.empty())
{
int u = que.front(); que.pop();
vis[u] = false;
for (int i = 0; i<E[u].size(); i++)
{
int v = E[u][i].v;
if (dist[v]>dist[u] + E[u][i].cost)
{
dist[v] = dist[u] + E[u][i].cost;
if (!vis[v])
{
vis[v] = true;
que.push(v);
cnt[v]++;
if (cnt[v] > n) return false;
}
}
}
}
return true;
}
int n, m;
int a, b, c;
int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d%d",&n,&m);
for (int i = 0; i <= n; i++) E[i].clear();
while (m--)
{
scanf("%d%d%d", &a, &b, &c);
addedge(a, b, c);
//addedge(b, a, c);
}
if (!SPFA(0, n)) puts("possible");
else puts("not possible");
}
return 0;
}
UVA 558 Wormholes 【SPFA 判負環】