码迷,mamicode.com
首页 > 其他好文 > 详细

1072 Gas Station (30point(s)) 需要二刷 *多源最短路径问题

时间:2020-03-26 19:59:10      阅读:17      评论:0      收藏:0      [点我收藏+]

标签:include   print   加油站   flag   需要   ble   结果   main   ons   

基本思想:

迪杰斯特拉得翻版,循环求各个节点,最后求最小结果;

 

关键点:

注意题目要求;

 

#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\n", amin, aavg);
	}
}

  

1072 Gas Station (30point(s)) 需要二刷 *多源最短路径问题

标签:include   print   加油站   flag   需要   ble   结果   main   ons   

原文地址:https://www.cnblogs.com/songlinxuan/p/12576390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!