【PAT甲级】1072. Gas Station (30)
来源:互联网 发布:专业校色软件 编辑:程序博客网 时间:2024/06/05 07:23
此题用Dijkstra计算;如果用Floyd最后一个测试用例会超时
#include <stdio.h>#include <iostream> #include <vector>#include <string>#include <algorithm>#include <stdlib.h>#define INF 1<<29using namespace std;struct T { int min; int sum; int index;};int min(int a, int b); T dij(int start);bool cmp(T a, T b);int n, m, k, ds;int N;int cost[1100][1100];int main() { cin >> n >> m >> k >> ds; N = m + n; int p1, p2, d; string p1str, p2str; vector<T> v; for (int i = 0; i <= N; i++) { for (int j = 0; j <= N; j++) { if (i == j) cost[i][j] = 0; else cost[i][j] = INF; } } for (int i = 0; i < k; i++) { cin >> p1str >> p2str >> d; if (p1str[0] == 'G') p1 = n + atoi(p1str.substr(1).c_str()); else p1 = atoi(p1str.c_str()); if (p2str[0] == 'G') p2 = n + atoi(p2str.substr(1).c_str()); else p2 = atoi(p2str.c_str()); cost[p1][p2] = cost[p2][p1] = d; } for (int i = n + 1; i <= N; i++) { T t = dij(i); if (t.min != -1) v.push_back(t); } sort(v.begin(), v.end(), cmp); if (v.size()) printf("G%d\n%.1f %.1f\n", v[0].index - n, float(v[0].min), float(v[0].sum)/n); else printf("No Solution"); return 0;}int min(int a, int b) { return (a < b ? a : b);}bool cmp(T a, T b) { if (a.min > b.min) return true; else if (a.min == b.min && a.sum < b.sum) return true; else if (a.min == b.min && a.sum == b.sum && a.index < b.index) return true; else return false;}T dij(int start) { int *d = new int[N+1]; int *used = new int[N+1]; fill(d, d + N + 1, INF); fill(used, used + N + 1, 0); d[start] = 0; while (true) { int v = -1; for (int u = 1; u <= N; u++) { if (!used[u] && (v == -1 || d[u] < d[v])) v = u; } if (v == -1) break; used[v] = 1; for (int u = 1; u <= N; u++) { d[u] = min(d[u], d[v] + cost[v][u]); } } int min = INF; int sum = 0; for (int i = 1; i <= n; i++) { if (d[i] < min) min = d[i]; sum += d[i]; } for (int i = 1; i <= n; i++) { if (d[i] > ds) min = -1; } T t; t.min = min; t.sum = sum; t.index = start; return t;}
阅读全文
0 0
- PAT甲级练习1072. Gas Station (30)
- 1072. Gas Station (30) PAT 甲级
- PAT甲级1072. Gas Station (30)
- 【PAT甲级】1072. Gas Station (30)
- PAT 甲级 1072. Gas Station (30)
- 1072. Gas Station (30)-PAT甲级真题(Dijkstra)
- PAT 1072. Gas Station (30)
- PAT 1072. Gas Station (30)
- 【PAT】1072. Gas Station (30)
- PAT 1072. Gas Station (30)
- PAT 1072. Gas Station
- PAT 1072. Gas Station
- PAT 1072. Gas Station
- 【PAT】1072. Gas Station
- pat 1072. Gas Station
- PAT A 1072. Gas Station (30)
- PAT-A-1072. Gas Station (30)
- 【PAT】【Advanced Level】1072. Gas Station (30)
- JVM基础知识(转)
- unity对象池
- RTMP vs. WebRTC 视频直播技术合集
- Android 禁止ViewPager左右滑动
- 程序设计入门—Python 第一周作业
- 【PAT甲级】1072. Gas Station (30)
- 通过url下载图片 并保存到服务器
- 使用Django实现分页功能
- 为什么需要短信验证码平台
- InnoDB存储引擎
- 关于url提交请求时传递数组参数的用法
- 在本地环境搭建maven的nexus私服,但是有些jar下载不了或下载很慢,解决办法
- MongoDB-配置翻译
- 中小企业云化转型解经营之困 中企动力三大利好引潮流之风