题目大意:
N个顶点的有向图(1 ≤ N ≤ 500)编号为1 ~ N,有M条双向边(1 ≤ M ≤ 2500)和W条负权边(1 ≤ W ≤ 200),边的形式为"u v c",当表示双向边时表示从u到v和从v到u有一条权值为c的边,当表示负权边时表示从u到v的单向边的权值为-c,其中0 < c ≤ 10,000。
现有t个测例,每个测例中给出以上信息,要求判断是否有负环,如果有则输出"YES",否则输出"NO"。
注释代码:
/*
* Problem ID : POJ 3259 Wormholes
* Author : Lirx.t.Una
* Language : C
* Run Time : 79 ms
* Run Memory : 216 KB
*/
#include <stdio.h>
#define INF 1000000
//最大定点数
#define MAXN 500
//最大边数,2500 × 2 + 200
#define MAXM 5200
typedef struct { int u, v, c; } Arc;//有向边u->v,权值为c
Arc arc[MAXM];//有向边
int dis[MAXN + 1];//各个顶点到源点的当前最短路径长度
int e;//边数
void
addarc( int u, int v, int c ) {//添加有向边
arc[e].u = u;
arc[e].v = v;
arc[e].c = c;
e++;
}
int
belf(int n) {//Bellman-Ford单源最短路径
int cont;//continue,是否可以再继续
int i, k;
int tmp;
cont = 1;//初始化
for ( k = 1; cont && k <= n; k++ )//总共松弛k - 1轮,第k轮检查是否存在负边权
for ( cont = 0, i = 0; i < e; i++ )//每一轮中对每条边都检查是否可以松弛
if ( ( tmp = dis[ arc[i].u ] + arc[i].c ) < dis[ arc[i].v ] ) {
if ( k == n ) return 1;//如果是第k轮还有边可以松弛就代表存在负边权
dis[ arc[i].v ] = tmp;//进行松弛
cont = 1;//有松弛就可以继续,如果每条边都已经不能松弛了也就不用再检查了,已经求出最短路径了
}
return 0;
}
int
main() {
int t;
int n, m, w;//点数、双向边数、负边数
int u, v, c;
int i;
scanf("%d", &t);
while ( t-- ) {
e = 0;
scanf("%d%d%d", &n, &m, &w);
for ( i = 1; i <= n; i++ ) dis[i] = INF;
while ( m-- ) {
scanf("%d%d%d", &u, &v, &c);
addarc( u, v, c );
addarc( v, u, c );
}
while ( w-- ) {
scanf("%d%d%d", &u, &v, &c);
addarc( u, v, -c );
}
if ( belf(n) ) puts("YES");
else puts("NO");
}
return 0;
}
无注释代码:
#include <stdio.h>
#define INF 1000000
#define MAXN 500
#define MAXM 5200
typedef struct { int u, v, c; } Arc;
Arc arc[MAXM];
int dis[MAXN + 1];
int e;
void
addarc( int u, int v, int c ) {
arc[e].u = u;
arc[e].v = v;
arc[e].c = c;
e++;
}
int
belf(int n) {
int cont;
int i, k;
int tmp;
cont = 1;
for ( k = 1; cont && k <= n; k++ )
for ( cont = 0, i = 0; i < e; i++ )
if ( ( tmp = dis[ arc[i].u ] + arc[i].c ) < dis[ arc[i].v ] ) {
if ( k == n ) return 1;
dis[ arc[i].v ] = tmp;
cont = 1;
}
return 0;
}
int
main() {
int t;
int n, m, w;
int u, v, c;
int i;
scanf("%d", &t);
while ( t-- ) {
e = 0;
scanf("%d%d%d", &n, &m, &w);
for ( i = 1; i <= n; i++ ) dis[i] = INF;
while ( m-- ) {
scanf("%d%d%d", &u, &v, &c);
addarc( u, v, c );
addarc( v, u, c );
}
while ( w-- ) {
scanf("%d%d%d", &u, &v, &c);
addarc( u, v, -c );
}
if ( belf(n) ) puts("YES");
else puts("NO");
}
return 0;
}