Va 558 Wormholes

Source: Internet
Author: User

UVA_558

This question is actually asking us to determine whether there is a negative circle in the source image. If SPFA is used, when the number of times a point is entered is greater than N, it can indicate that there is a negative circle in the source image.

#include<stdio.h>
#include<string.h>
#define MAXD 1010
#define MAXM 2010
#define INF 1000000000
int d[MAXD], q[MAXD], inq[MAXD], inedq[MAXD];
int N, M, first[MAXD], e, next[MAXM], v[MAXM], w[MAXM];
void add(int a, int b, int c)
{
v[e] = b;
w[e] = c;
next[e] = first[a];
first[a] = e;
e ++;
}
void init()
{
int i, a, b, c;
scanf("%d%d", &N, &M);
memset(first, -1, sizeof(first));
e = 0;
for(i = 0; i < M; i ++)
{
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
}
int SPFA()
{
int i, u, front, rear;
front = rear = 0;
for(i = 0; i < N; i ++)
d[i] = INF;
d[0] = 0;
memset(inq, 0, sizeof(inq));
memset(inedq, 0, sizeof(inedq));
q[rear ++] = 0;
while(front != rear)
{
u = q[front ++];
if(front > N)
front = 0;
inq[u] = 0;
for(i = first[u]; i != -1; i = next[i])
if(d[u] + w[i] < d[v[i]])
{
d[v[i]] = d[u] + w[i];
if(!inq[v[i]])
{
q[rear ++] = v[i];
if(rear > N)
rear = 0;
inq[v[i]] = 1;
if(inedq[v[i]] ++ > N)
return 1;
}
}
}
return 0;
}
int main()
{
int t;
scanf("%d", &t);
while(t --)
{
init();
if(SPFA())
printf("possible\n");
else
printf("not possible\n");
}
return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.