PAT 1030. Travel Plan (30)
来源:互联网 发布:apache ab测试 linux 编辑:程序博客网 时间:2024/05/16 09:15
题目:http://www.patest.cn/contests/pat-a-practise/1030
考察最短路径问题,复习了一下dijkstra算法。
http://www.2cto.com/kf/201311/257005.html
题目不仅要求最短路径还需要加权值
#include<iostream>#include<cstdio>#include<cstring>using namespace std;int n,m,s,d;int highway[502][502];int cost[502][502];int INF = 10000000;bool flag[502];int dis[502];int c[502];int pre[502];int dijkstra()//dijkstra算法{ for(int i = 0; i < n; i++) { flag[i] = false; dis[i] = highway[s][i]; c[i] = cost[s][i]; if(dis[i] == INF) pre[i] = -1; else pre[i] = s; } dis[s] = 0; flag[s] = true; c[s] = 0; for(int i = 0; i < n-1; i++) { int min = INF; int pos; for(int j = 0; j < n; j++) { if(!flag[j] && min >dis[j]) { pos = j; min = dis[j]; } } flag[pos] = true; for(int j = 0; j < n; j++) { if(!flag[j]) { if(dis[j] > (dis[pos]+ highway[pos][j])) { dis[j] = dis[pos] + highway[pos][j]; c[j] = c[pos] + cost[pos][j]; pre[j] = pos; }else if(dis[j] == (dis[pos]+ highway[pos][j])) { if(c[j] > c[pos] + cost[pos][j]) { c[j] = c[pos] + cost[pos][j]; pre[j] = pos; } } } } } return dis[d];}void searchPath()//打印路径{ int c = 0; int path[502]; int x = 0; path[x++] = d; int temp = pre[d]; while(temp != s) { path[x++] = temp; temp = pre[temp]; } path[x] = s; for(int i = x; i >= 0; i--) printf("%d ",path[i]);}int main(){ while(scanf("%d%d%d%d",&n,&m,&s,&d) != EOF) { for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { highway[i][j] = INF; cost[i][j] = INF; } for(int i = 0; i < m; i++) { int a,b; scanf("%d%d",&a,&b); scanf("%d%d",&highway[a][b],&cost[a][b]); highway[b][a] = highway[a][b]; cost[b][a] = cost[a][b]; } int ans = dijkstra(); searchPath(); printf("%d %d\n",ans,c[d]); } return 0;}
0 0
- 1030. Travel Plan (30)-PAT
- 1030. Travel Plan (30) PAT
- PAT 1030. Travel Plan (30)
- PAT 1030. Travel Plan (30)
- PAT 1030. Travel Plan (30)
- 【PAT】1030. Travel Plan (30)
- pat 1030. Travel Plan (30)
- PAT 1030. Travel Plan (30)
- PAT 1030. Travel Plan
- 【PAT】1030. Travel Plan
- 【PAT Advanced Level】1030. Travel Plan (30)
- PAT 1030. Travel Plan (30) 图论
- PAT A 1030. Travel Plan (30)
- PAT (Advanced) 1030. Travel Plan (30)
- PAT(A) - 1030. Travel Plan (30)
- 【PAT甲级】1030. Travel Plan (30)
- PAT甲级练习1030. Travel Plan (30)
- PAT甲级1030. Travel Plan (30)
- EQueue - 一个纯C#写的分布式消息队列介绍2
- 1001 二分查找
- JavaScript快速入门(一)(2015.8.3)
- 对高价流量说不 高性价比流量王——亿富流量银行
- Mono for Unreal Engine发布,C#进入虚幻引擎(Unreal Engine)
- PAT 1030. Travel Plan (30)
- Memory barrier(内存屏障)
- 1009:FatMouse' Trade
- Word Break
- 3件Unreal Engine 3不得不说的故事
- 同步和条件变量
- poj 2631 Roads in the North 【树的直径裸题】
- IBInspectable 和IB_DESIGNABLE动态刷新IB
- 关于二分查找, 关注细节