九度 OJ 题目1008:最短路径问题 (Dijstra 算法)
2017-03-14 13:31
549 查看
题目描述:
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
输入:
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
输出:
输出 一行有两个数, 最短距离及其花费。
样例输入:
样例输出:
该题与 九度OJ题目1447:最短路 使用相同思想,只是多了一个cost变量
九度OJ题目1447:最短路 我的解法:http://blog.csdn.net/qq_31820885/article/details/61925864
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
输入:
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
输出:
输出 一行有两个数, 最短距离及其花费。
样例输入:
3 2 1 2 5 6 2 3 4 5 1 3 0 0
样例输出:
9 11
该题与 九度OJ题目1447:最短路 使用相同思想,只是多了一个cost变量
九度OJ题目1447:最短路 我的解法:http://blog.csdn.net/qq_31820885/article/details/61925864
#include <stdio.h> #include<vector> using namespace std; struct E{ int next; int weight; int cost; }; vector<E> edge[1001]; bool mark[1001]; int dis[1001]; int costs[1001]; int main() { int n,m; while(scanf("%d%d", &n,&m)!=EOF) { if(n == 0 && m == 0) break; for(int i=1;i<=n;i++) edge[i].clear(); //初始化 int p1,p2,weight,cost; //录入 while(m--) { scanf("%d%d%d%d",&p1,&p2,&weight,&cost); E tmp; tmp.weight = weight; tmp.cost = cost; tmp.next = p1; edge[p2].push_back(tmp); //p2与p1的连线放到p2的vector中 tmp.next = p2; edge[p1].push_back(tmp); //该图是无向图,所有要两个节点的vector都要存彼此 } int s,t; scanf("%d%d", &s,&t); //初始化 for(int i=1;i<=n;i++) { mark[i] = false; dis[i] = -1; // costs[i] = 0; } //从s节点为初始K集合 mark[s] = true; dis[s] = 0; int newP = s; //新加入K集合的节点 //循环找到特定节点到其他n-1个节点的最短路径 for(int i=1;i<n;i++) { for(int j=0;j<edge[newP].size();j++) { int next = edge[newP][j].next; //新加入节点的相邻节点 int weight = edge[newP][j].weight; int cost = edge[newP][j].cost; if(mark[next] == true) continue; //若next节点已经是集合K的成员 //(dis[next]==dis[newP]+c) && (costs[next]>costs[newP]+cost)该句体现距离相等时取花费少的 if(dis[next] == -1 || dis[next] > dis[newP] + weight || ((dis[next] == dis[newP] + weight) && (costs[next] > costs[newP] + cost))) { dis[next] = dis[newP] + weight; //更新距离 costs[next] = costs[newP] + cost; //更新花费 } } int min = 9999999; //循环查找K集合与U集合之间已经计算出dis值得边的最小边,另其为新加入点 for(int j=1;j<=n;j++) { if(mark[j] == true) continue; if(dis[j] == -1) continue; if(dis[j] < min){ min = dis[j]; newP = j; } } mark[newP] = true; //将新加入点列入K集合 } printf("%d %d\n", dis[t], costs[t]); } return 0; }
相关文章推荐
- 九度OJ-题目1008 最短路径问题
- 九度 oj 题目1008:最短路径问题
- 九度OJ题目1447:最短路径(Dijstra 算法)
- 九度oj 题目1008:最短路径问题 【ZJU2010考研机试题4】【dij+dfs】
- 九度:题目1008:最短路径问题
- 九度OJ-1008:最短路径问题
- 九度题目1008:最短路径问题
- 九度 题目1008:最短路径问题
- 九度oj-1008-最短路径问题
- 九度OJ 1447 最短路 1008 最短路径问题
- 九度OJ 1008:最短路径问题 (最短路)
- [九度OJ]1008.最短路径问题
- 九度题目1008:最短路径问题
- 九度 OJ 1447 题 最短路径问题 Dijkstra(迪杰斯特拉)算法实现,使用vector模板模拟邻接链表
- 九度 OJ 题目1447:最短路径(Floyd 算法)
- 最短路径问题—九度OJ1008 (2010年浙江大学研究生机试真题)
- 九度 题目1008:最短路径问题
- 九度OJ 1008:最短路径问题 (最短路)
- 九度 OJ 1008 最短路径问题
- 题目1008:最短路径问题