poj2387 Til the Cows Come Home
来源:互联网 发布:mac icloud备份 编辑:程序博客网 时间:2024/05/17 21:40
题意:有n个点,求从1到n的最短路径。
这里使用了Dijkstra算法,使用邻接矩阵来实现的复杂度是O(n^2)。主要思想是通过不断寻找与起点距离最小的点,然后更新与该点所相连的点的值,直到所有点都访问完了以后结束。
代码
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define MAXN 1005#define INF 1000000int t,n;int cost[1005][1005];int vis[1005];int d[1005];void init(){ memset(vis,0,sizeof(vis)); fill(d,d+1003,INF); for(int i=0;i<=1003;i++) fill(cost[i],cost[i]+1003,INF); d[1]=0;}void dijkstra(){ while(1) { int v=-1; for(int i=1;i<=n;i++) //寻找未被访问的 if(!vis[i]&&(v==-1||d[i]<d[v]))v=i; if(v==-1)break; vis[v]=1; //printf("%d %dcc ",v,d[v]); for(int i=1;i<=n;i++) d[i]=min(d[i],d[v]+cost[v][i]); }}int main(){ init(); scanf("%d%d",&t,&n); for(int i=0;i<t;i++) { int u,v,a; scanf("%d%d%d",&u,&v,&a); if(a<cost[u][v]) { cost[u][v]=a; cost[v][u]=a; } } // printf("%d\n",cost[4][7]); dijkstra(); printf("%d\n",d[n]);}
0 0
- poj2387- Til the Cows Come Home
- poj2387- Til the Cows Come Home
- POJ2387 Til the Cows Come Home
- POJ2387 Til the Cows Come Home【Dijkstra】
- POJ2387----Til the Cows Come Home(dijkstra)
- POJ2387---Til the Cows Come Home
- POJ2387 Til the Cows Come Home
- [poj2387] Til the Cows Come Home
- poj2387 Til the Cows Come Home
- poj2387 Til the Cows Come Home
- poj2387 Til the Cows Come Home
- POJ2387 Til the Cows Come Home
- POJ2387 Til the Cows Come Home
- Poj2387- Til the Cows Come Home
- POJ2387 Til the Cows Come Home
- POJ2387 Til the Cows Come Home
- POJ2387-Til the Cows Come Home
- POJ2387 Til the Cows Come Home
- 二叉树判定树结构是否相同,值是否相同
- Maven的Setting.xml文件模板
- HashMap实现原理分析
- 【目标检测:Hough Forest】霍夫森林(Hough Forest)目标检测算法及其原理(二)
- HDU-2032 杨辉三角
- poj2387 Til the Cows Come Home
- 关于函数参数入栈顺序(完善中)
- 设计第二个弹出窗口(MessageBox)
- Boost智能指针shared_ptr、weak_ptr
- java中volatile关键字的含义
- 正则表达式实现(Linux C语言版本)
- 触摸事件(touchstart、touchmove和touchend)
- ExecutorService的十个使用技巧
- cxf隐藏service列表