find the mincost rout
来源:互联网 发布:软件使用说明怎么写 编辑:程序博客网 时间:2024/06/06 01:39
杭州有N个景区,景区之间有一些双向的路来连接,现在8600想找一条旅游路线,这个路线从A点出发并且最后回到A点,假设经过的路线为V1,V2,....VK,V1,那么必须满足K>2,就是说至除了出发点以外至少要经过2个其他不同的景区,而且不能重复经过同一个景区。现在8600需要你帮他找一条这样的路线,并且花费越少越好。
接下来的M行里,每行包括3个整数a,b,c.代表a和b之间有一条通路,并且需要花费c元(c <= 100)。
3 3
1 2 1
2 3 1
1 3 1
3 3
1 2 1
1 2 3
2 3 1
Sample Output
3
It's impossible.
题解:本题使用floyd求最小环问题,一个环至少有3个顶点,设某环编号最大的顶点为 L ,在环中直接与之相连的两个顶点编号分别为 M 和 N (M,N < L),则最大编号为 L的最小环长度即为 Graph(M,L) + Graph(N,L) + Dist(M,N) ,其中 Dist(M,N) 表示以 0…L-1 号顶点为中间点时的最短路径,刚好符合 Floyd 算法最外层循环到 k=L 时的情况,则此时对 M 和 N 循环所有编号小于 L的顶点组合即可找到最大编号为 L 的最小环。再经过最外层 k 的循环,即可找到整个图的最小环。
#include<stdio.h>#include<math.h>#define INF 0x3f3f3f//不能为0x3f3f3f3f,否则可能会溢出int N,M;int lu[105][105],dis[105][105];int floyd(){ int mincircle; int i,j,k; mincircle=INF;//先将最小环初始化为很大的数 for(i=1;i<=N;i++) { for(j=1;j<=N;j++) { lu[i][j]=dis[i][j]; //用一个中间数组存输入的全部路径花费,因为后面可能会改变 } } //核心代码部分如下 for(k=1;k<=N;k++) { for(i=1;i<k;i++) { for(j=i+1;j<k;j++) { if(mincircle>dis[i][j]+lu[i][k]+lu[k][j]) mincircle=dis[i][j]+lu[i][k]+lu[k][j]; } } //更新借助k时,i到j的路径花费 for(i=1;i<=N;i++) { for(j=1;j<=N;j++) { if(dis[i][j]>dis[i][k]+dis[k][j]) dis[i][j]=dis[i][k]+dis[k][j]; } } } return mincircle;}int main(){ int a,b,c,ans; while(~scanf("%d %d",&N,&M)) { for(int i=1;i<=N;i++) { for(int j=1;j<=N;j++) { dis[i][j]=INF; } } while(M--) { scanf("%d %d %d",&a,&b,&c); if(dis[a][b]>c) { dis[a][b]=dis[b][a]=c; } } ans=floyd(); if(ans!=INF) { printf("%d\n",ans); } else printf("It's impossible.\n"); } return 0;}
阅读全文
0 0
- find the mincost rout
- find the mincost route
- find the mincost route
- find the mincost route
- find the mincost route
- find the mincost route
- find the mincost route
- find the mincost route
- HDU1599 find the mincost route
- hdu1599 find the mincost route
- hdu1599 find the mincost route
- hdu1599 find the mincost route
- Hdoj find the mincost route
- find the mincost route hdoj1599
- HDU1599:find the mincost route
- HDU_1599 find the mincost route
- find the mincost route HDU
- hdu1599 find the mincost route
- 实现了一个AOI模块
- 剑指offer 39---求二叉树的深度 && 输入一颗二叉树的根节点,判断该树是不是平衡二叉树
- 648. Replace Words
- CodeForces
- 39. Combination Sum I && II
- find the mincost rout
- HDU 4960 Another OCD Patient (dp)
- Echarts学习之路 —— echarts介绍
- trait特性
- std::priority_queue 优先队列
- Android高级控件之ListView的优化以及下拉刷新页面
- 组合查询和存储过程
- 从对象和函数(或称构造函数)两个维度理解js中的函数
- 单例模式