POJ 3259 Wormholes(Bellman-Ford判负环)
2015-07-13 09:58
441 查看
Description
判断一个图中是否存在负环
Input
第一行为用例组数t,每组用例第一行为三个整数n,m,w分别表示顶点数,双向边个数,单向边个数,之后m行每行三个整数a,b,d表示a和之间有一条权值为d的双向边,最后w行每行三个整数a,b,d表示a和b之间有一条权值为-d的单向边
Output
若图中存在负环则输出YES,否则输出NO
Sample Input
2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8
Sample Output
NO
YES
Solution
Bellman-Ford
Code
判断一个图中是否存在负环
Input
第一行为用例组数t,每组用例第一行为三个整数n,m,w分别表示顶点数,双向边个数,单向边个数,之后m行每行三个整数a,b,d表示a和之间有一条权值为d的双向边,最后w行每行三个整数a,b,d表示a和b之间有一条权值为-d的单向边
Output
若图中存在负环则输出YES,否则输出NO
Sample Input
2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8
Sample Output
NO
YES
Solution
Bellman-Ford
Code
#include<cstdio> #include<iostream> using namespace std; #define INF (1<<29) #define maxm 2710 #define maxv 505 struct node { int x,y,t; }edge[maxm]; int T,n,m,w; int Bellman_Ford() { int i,j,d[maxv],res=1; for(i=1;i<=n;i++)//初始化 d[i]=INF; int flag=1; while(flag) { flag=0; if(res++>n) return 1; for(i=1;i<=m;i++)//双向边 { if(d[edge[i].x]>d[edge[i].y]+edge[i].t) { d[edge[i].x]=d[edge[i].y]+edge[i].t; flag=1; } if(d[edge[i].y]>d[edge[i].x]+edge[i].t) { d[edge[i].y]=d[edge[i].x]+edge[i].t; flag=1; } } for(;i<=m+w;i++)//单向边 if(d[edge[i].y]>d[edge[i].x]-edge[i].t) { d[edge[i].y]=d[edge[i].x]-edge[i].t; flag=1; } } return 0; } int main() { scanf("%d",&T); while(T--) { scanf("%d%d%d",&n,&m,&w); for(int i=1;i<=m+w;i++) scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].t); if(Bellman_Ford())//存在负环 printf("YES\n"); else//不存在负环 printf("NO\n"); } return 0; }
相关文章推荐
- sweet alert
- jQuery中extend函数详解
- tomcat配置去端口和项目名称访问
- shell
- 牛人博客汇总之摘抄(Talk is cheap, show me the code.)
- 2014 多校赛 第一场
- 概率随机物品
- Eworkpal-ESN(企业社交网络)功能
- 匿名内部类
- Android线程的创建与销毁
- 网络爬虫(三) Java实现简单的网络爬虫
- 经管学习笔记(2)
- 用C++操作文件
- android 动画效果
- Myeclipse快捷键大全
- [floyd]poj3660 Cow Contest
- spring mvc 异常统一处理方式
- 用cmd如何打包.jar文件
- uva 111 History Grading
- HTML5 Web Workers