PAT A1072 Gas Station (30 points)

Insert picture description here

#include <cstdio>
#include <string>
#include <algorithm>
#include <iostream>

using namespace std;
const int MAXV = 1020;
const int INF = 1e9;

int d[MAXV];
int n, m, k, ds;
bool vis[MAXV];
int G[MAXV][MAXV];

int getID(string s){
    
    
	int num;
	if(s[0] == 'G'){
    
    
		s = s.substr(1, s.size()-1);
		num = stoi(s);
		num += n;
	}else{
    
    
		num = stoi(s);
	}
	return num;
}

void Dijkstral(int s){
    
    
	fill(vis, vis+MAXV, false);
	fill(d, d+MAXV, INF);
	d[s] = 0;
	for(int i=0; i<n+m; i++){
    
    
		int u = -1, MIN = INF;
		for(int j=1; j<=n+m; j++){
    
    
			if(vis[j]==false && d[j]<MIN){
    
    
				u = j;
				MIN = d[j];
			}
		}
		if(u == -1) return;
		vis[u] = true;
		for(int v=1; v<=n+m; v++){
    
    
			if(vis[v]==false && G[u][v]!=INF){
    
    
				if(d[v] > d[u] + G[u][v]){
    
    
					d[v] = d[u] + G[u][v];
				}
			}
		}
	}
}

double getavg(){
    
    
	double res = 0;
	for(int i=1; i<=n; i++){
    
    
		res += 1.0*d[i]/n;
	}
	return res;
}

int main(){
    
    
	fill(G[0], G[0]+MAXV*MAXV, INF);
	scanf("%d %d %d %d", &n, &m, &k, &ds);
	
	string s1, s2;
	int u, v, w;
	for(int i=0; i<k; i++){
    
    
		cin >> s1 >> s2 >> w;
		u = getID(s1);
		v = getID(s2);
		G[u][v] = w;
		G[v][u] = w;
	}
	
	double maxdis = -1, minavg = INF;
	int index;
	for(int i=n+1; i<=n+m; i++){
    
    
		Dijkstral(i);
		int mindis = INF;
		int flag = 0;
		for(int j=1; j<=n; j++){
    
    
			if(d[j] > ds){
    
    
				flag = 1;
				break;
			}
			if(d[j] < mindis){
    
    
				mindis = d[j];
			}
		}
		if(flag) continue;
		if(mindis > maxdis){
    
    
			maxdis = mindis;
			index = i - n;
			minavg = getavg();
		}else if(mindis == maxdis){
    
    
			if(getavg() < minavg){
    
    
				index = i - n;
				minavg = getavg();
			}
		}
	}
	if(maxdis == -1){
    
    
		printf("No Solution");
	}else{
    
    
		printf("G%d\n%.1f %.1f", index, maxdis, minavg);
	}
	
	return 0;
} 

Guess you like

Origin blog.csdn.net/weixin_45964844/article/details/113843515