HDU1874-畅通工程续
来源:互联网 发布:活动报名网站源码 编辑:程序博客网 时间:2024/06/08 04:48
畅通工程续 Time Limit: 1000 MS Memory Limit: 32768 KProblem Description 某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。Input 本题目包含多组数据,请处理到文件结束。每组数据第一行包含两个正整数N和M(0<N<200,0<M<1000),分别代表现有城镇的数目和已修建的道路的数目。城镇分别以0~N-1编号。接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。Output 对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.
Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1
题解
最短路裸题,没有负权边,所以Dij和SPFA都可过。
代码
#include<iostream>#include<cstdio>#include<queue>#include<cstring>#include<algorithm>using namespace std;struct edge{int from,to,next,v;}e[1010];int n,m,dis[250],cnt,head[250],b,d;bool vis[250],flag=false;void add(int u,int v,int w){ e[cnt++].from=u; e[cnt].to=v; e[cnt].v=w; e[cnt].next=head[u]; head[u]=cnt;}void spfa(int s){ queue<int>q; memset(vis,0,sizeof(vis)); memset(dis,63,sizeof(dis)); while(!q.empty()) q.pop(); vis[s]=true; dis[s]=0; q.push(s); while(!q.empty()) { int temp=q.front(); q.pop(); vis[temp]=false; if(temp==d) {flag=1;} for(int i=head[temp];i!=-1;i=e[i].next) { int t=e[i].to; if(dis[t]>dis[temp]+e[i].v) { dis[t]=dis[temp]+e[i].v; if(!vis[t]) { vis[t]=true; q.push(t); } } } }}int main(){ while(~scanf("%d%d",&n,&m)) { flag=false; memset(head,-1,sizeof(head)); memset(e,0,sizeof(e)); cnt=0; for(int i=0;i<m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); add(u,v,w); add(v,u,w); } scanf("%d%d",&b,&d); spfa(b); if(flag==false) printf("-1\n"); else printf("%d\n",dis[d]); } return 0;}
OI蒟蒻,欢迎批评指正。
0 0
- hdu1874畅通工程续
- hdu1874 畅通工程续
- HDU1874 畅通工程续
- HDU1874 畅通工程续
- hdu1874 畅通工程续
- HDU1874:畅通工程续
- hdu1874畅通工程续
- hdu1874畅通工程续
- hdu1874畅通工程续
- HDU1874 畅通工程续
- hdu1874 畅通工程续
- HDU1874畅通工程续
- HDU1874 畅通工程续
- HDU1874-畅通工程续
- HDU1874----畅通工程续
- HDU1874畅通工程续
- HDU1874 畅通工程续
- hdu1874-畅通工程续
- /bin、/sbin、/usr/bin和/usr/sbin的简单区别
- n!末尾的0的个数
- 游戏开发常用字符串函数整理【C++版】
- Http异步client
- postgresql启动1053错误
- HDU1874-畅通工程续
- codeforces500A New Year Transportation (水题 模拟)
- Android复习-Java基础(1)
- HDU5900-QSC and Master
- MyBatis获取插入记录的自增长字段值
- hdu 5886 Tower Defence 2016ACM/ICPC青岛赛区网络赛1009
- 决策树与随机森林相关概念
- Leetcode 57 Insert Interval
- 保存Word