Link: Click to open link
The main idea:
The subject test instructions to see most of the day is also not understand-_-| | |, and then go to poj the original topic discussion area to see, finally understand the topic. Test instructions is: Enter an F first, the Representative has the F Group test data, each group of test data entered first N, M, W, indicating that there are n points, M no edge, W has a forward edge, and that the weighted value of the edge should be negative (the input is a positive number), then enter the M+w bar, each edge is two vertices + weights And then let the judge can produce the ring, if so, output yes, otherwise output No.
Problem Solving Ideas:
Determine the negative weight of the edge can not use the Dijkstra algorithm and prim algorithm, the subject can use the SPFA algorithm, first use the linked list to build, use mark[] array marker point use, use used[] array record points in the queue number, SPFA algorithm roughly similar to the BFS search, Just mark the points that have been placed in the queue, and when you remove the first, you want to unmark them. Each time the team, the queue of points corresponding to the used value from the addition of one, to determine the condition of the ring is a bit more than or equal to the total number of points n, that is, a bit corresponding to the used value >= N; This situation indicates that a ring has occurred. Please refer to the code for details:
#include <stdio.h> #include <string.h> #include <queue> #define INF 0x3f3f3f3f#define MAXN 550#define Maxm 5050using namespace Std;int head[maxn];int dis[maxn];int mark[maxn];int used[maxn];struct node{int from,to,val, Next;}; Node Edge[maxm];int num,n,m,w;void getmap (int u,int v,int W) {node e={u,v,w,head[u]};edge[num]=e;head[u]=num++;} BOOL SPFA (int s) {Queue<int>q;memset (mark,0,sizeof (Mark)); memset (dis,inf,sizeof (dis)); memset (Used,0,sizeof ( used)); Q.push (s); Mark[s]=1;dis[s]=0;used[s]++;while (!q.empty ()) {int Top=q.front (); Q.pop (); mark[top]=0;for (int i= Head[top];i!=-1;i=edge[i].next) {int u=edge[i].to;if (dis[u]>dis[top]+edge[i].val) {Dis[u]=dis[top]+edge[i].val ; if (!mark[u]) {mark[u]=1;q.push (U); used[u]++;if (used[u]>=n) return True;}}} return false;} int main () {int f;int s,e,t;scanf ("%d", &f), while (f--) {scanf ("%d%d%d", &n,&m,&w); Memset (Head,-1, sizeof (head)), num=0;for (int i=0;i<m;i++) {scanf ("%d%d%d", &s,&e,&t), Getmap (s,e,t); Getmap (e,s,t);} for (int i=0;i<w;i++) {scanf ("%d%d%d", &s,&e,&t); Getmap (S,E,-T);} if (SPFA (1)) printf ("yes\n"); elseprintf ("no\n");} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ 3259 wormholes