SPFA判环。
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
#define MAXN 1100
#define INF 0X3F3F3F3F
struct Edge
{
int u, v, w;
int next;
}edge[MAXN*4];
int first[MAXN], d[MAXN];
int n, m, cnt;
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
int spfa(int src)
{
queue<int> q;
bool inq[MAXN] = {0};
int count[MAXN] = {0};
for(int i = 0; i < n; i++) d[i] = (i == src)?0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0;
for(int e = first[x]; e != -1; e = edge[e].next)
{
int v = edge[e].v, w = edge[e].w;
if(d[v] > d[x] + w)
{
d[v] = d[x] + w;
if(!inq[v])
{
inq[v] = 1;
if(++count[v] > n) return 0; //判环
q.push(v);
}
}
}
}
return 1;
}
void read_graph(int u, int v, int w)
{
edge[cnt].v = v, edge[cnt].w = w;
edge[cnt].next = first[u], first[u] = cnt++;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d%d", &n, &m);
while(m--)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
read_graph(u, v, w);
}
if(!spfa(0))
{
printf("possible\n");
}
else
{
printf("not possible\n");
}
}
}
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
#define MAXN 1100
#define INF 0X3F3F3F3F
struct Edge
{
int u, v, w;
int next;
}edge[MAXN*4];
int first[MAXN], d[MAXN];
int n, m, cnt;
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
int spfa(int src)
{
queue<int> q;
bool inq[MAXN] = {0};
int count[MAXN] = {0};
for(int i = 0; i < n; i++) d[i] = (i == src)?0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0;
for(int e = first[x]; e != -1; e = edge[e].next)
{
int v = edge[e].v, w = edge[e].w;
if(d[v] > d[x] + w)
{
d[v] = d[x] + w;
if(!inq[v])
{
inq[v] = 1;
if(++count[v] > n) return 0; //判环
q.push(v);
}
}
}
}
return 1;
}
void read_graph(int u, int v, int w)
{
edge[cnt].v = v, edge[cnt].w = w;
edge[cnt].next = first[u], first[u] = cnt++;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d%d", &n, &m);
while(m--)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
read_graph(u, v, w);
}
if(!spfa(0))
{
printf("possible\n");
}
else
{
printf("not possible\n");
}
}
}