POJ-3259(最短路+Bellman-Ford算法判负圈)
Wormholes
POJ-3259
- 这题是最短路问题中判断是否存在负圈的模板题。
- 判断负圈的一个关键就是理解:如果在图中不存在从s可达的负圈,最短路径不会经过一个顶点两次。while循环最多执行v-1次。
- 这题还需要注意的是输入的w条边的权值是负值,因为这是虫洞边。
package POJ;
import java.util.*;
public class POJ_3259 {
static int f,n,m,w;
public int from,to;
public double rate,commisions;
static int edges;//边数
static class edge{
public int from,to,se;
edge(){}
edge(int from,int to,int se){
this.from=from;this.to=to;this.se=se;
}
};
static edge []es;
static int []d;//distance数组
static boolean BellmanFord() {
Arrays.fill(d, 0);
for(int i=0;i<n;i++) {//下标从1开始
for(int j=0;j<edges;j++) {
edge e=es[j];
if(d[e.to]>d[e.from]+e.se) {
d[e.to]=d[e.from]+e.se;
if(i==n-1)
return true;
}
}
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin=new Scanner(System.in);
f=cin.nextInt();
while(f!=0) {
n=cin.nextInt();
m=cin.nextInt();
w=cin.nextInt();
es=new edge[2*m+w];
d=new int[n+1];
int k=0;
int from,to,se;
for(int j=0;j<m;j++) {
from=cin.nextInt();
to=cin.nextInt();
se=cin.nextInt();
es[k++]=new edge(from,to,se);
es[k++]=new edge(to,from,se);
}
for(int j=0;j<w;j++) {
from=cin.nextInt();
to=cin.nextInt();
se=cin.nextInt();
es[k++]=new edge(from,to,-se);
}
edges=k;
if(BellmanFord())
System.out.println("YES");
else System.out.println("NO");
f--;
}
}
}
Either Excellent or Rusty
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了