1072 Gas Station (30point(s)) 需要二刷 *多源最短路径问题
Posted songlinxuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1072 Gas Station (30point(s)) 需要二刷 *多源最短路径问题相关的知识,希望对你有一定的参考价值。
基本思想:
迪杰斯特拉得翻版,循环求各个节点,最后求最小结果;
关键点:
注意题目要求;
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; const int maxn = 1020; const int INF = 100000000; const double DINF = 100000000.0; int n, m, k, ds; int num; int ma[maxn][maxn]; int dis[maxn]; int vis[maxn]; double aavg = DINF; double amin = 0.0; int aindex = -1; int trans(string s) { if (s[0] == ‘G‘) { s = s.substr(1, s.size() - 1); return stoi(s) + n; } else { return stoi(s); } } void dij(int st) { fill(vis, vis + maxn, false); fill(dis, dis + maxn, INF); dis[st] = 0; for (int u = 0; u < num; u++) { int index = -1; int mnum = INF; for (int i = 1; i <= num; i++) { if (!vis[i] && dis[i] < mnum) { mnum = dis[i]; index = i; } } if (index == -1) return; vis[index] = true; for (int i = 1; i <= num; i++) { if (!vis[i] && ma[index][i] != INF) { if (dis[i] > dis[index] + ma[index][i]) { dis[i] = dis[index] + ma[index][i]; } } } } } int main() { fill(ma[0], ma[0] + maxn * maxn, INF); cin >> n >> m >> k >> ds; num = n + m; string a, b; int d; for (int i = 0; i < k; i++) { cin >> a >> b >> d; int aa = trans(a); int bb = trans(b); ma[aa][bb] = ma[bb][aa] = d; } for (int i = 1; i <= m; i++) { //寻找每个加油站的最短路径 double avg = 0; double mnum = 0; bool flag = false; dij(n + i); sort(dis + 1, dis + n + 1); if (dis[n] > ds) continue; for (int j = 1; j <= n; j++) { avg += double(dis[j]) / double(n); } if (amin < dis[1]) { amin = dis[1]; aindex = i; aavg = avg; } else if (amin == dis[1]&&avg<aavg) { amin = dis[1]; aindex = i; aavg = avg; } } if (aindex == -1) cout << "No Solution" << endl; else { cout << "G" << aindex << endl; printf("%.1lf %.1lf ", amin, aavg); } }
以上是关于1072 Gas Station (30point(s)) 需要二刷 *多源最短路径问题的主要内容,如果未能解决你的问题,请参考以下文章
PAT (Advanced Level) 1072. Gas Station (30)
1072 Gas Station (30 分)难度: 中 / 知识点: Dijkstra + 枚举