PAT A1087 All Roads Lead to Rome (30 分)

在这里插入图片描述
Djikstral+DFS

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
const int MAXV = 220;
const int INF = 1e9;

int n, k;
string st;
map<string,int> stoint;
map<int,string> inttos; 
int happy[MAXV] = {
    
    0};
int d[MAXV];
int G[MAXV][MAXV];
int num = 0;
vector<int> pre[MAXV];
vector<int> path, tempPath;
int maxhappy = -1;
double avghappy;
bool vis[MAXV] = {
    
    false};

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

void DFS(int v){
    
    
	if(v == 0){
    
    
		tempPath.push_back(v);
		num++;
		int currenth = 0;
		for(int i=0; i<tempPath.size()-1; i++){
    
    
			int index = tempPath[i];
			currenth += happy[index];
		}
		if(currenth > maxhappy){
    
    
			path = tempPath;
			maxhappy = currenth;
			avghappy = 1.0 * currenth / (tempPath.size()-1); 
		}else if(currenth == maxhappy){
    
    
			double avg = 1.0 * currenth / (tempPath.size()-1);
			if(avg > avghappy){
    
    
				avghappy = avg;
				path = tempPath;
			}
		}
		tempPath.pop_back();
		return;
	}
	tempPath.push_back(v);
	for(int i=pre[v].size()-1; i>=0; i--){
    
    
		DFS(pre[v][i]);
	}
	tempPath.pop_back();
}

int main(){
    
    
	fill(G[0], G[0]+MAXV*MAXV, INF);
	cin >> n >> k >> st;
	stoint[st] = 0;
	inttos[0] = st;
	
	int t = 1;
	for(int i=0; i<n-1; i++){
    
    
		string s;
		int h;
		cin >> s >> h;
		stoint[s] = t;
		inttos[t] = s;
		happy[t] = h;
		t++;
	}
	int u, v, w;
	for(int i=0; i<k; i++){
    
    
		string s1, s2;
		cin >> s1 >> s2 >> w;
		u = stoint[s1];
		v = stoint[s2];
		G[u][v] = G[v][u] = w;
	}
	int end = stoint["ROM"];
	
	Dijkstral(0);
	DFS(end);
	printf("%d %d %d %d\n", num, d[end], maxhappy, (int)avghappy);
	for(int i=path.size()-1; i>=0; i--){
    
    
		cout << inttos[path[i]];
		if(i != 0) printf("->");
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45964844/article/details/113844926
今日推荐