1087 All Roads Lead to Rome

可真是神奇,希望机试遇到迪杰斯特拉能够很快很好地写出来
为什么别人的代码是有颜色的呢

#include<iostream>
#include<cstring>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=1100;
const int INF=0x3fffffff;
int n,k;//n个点k条路
int d[maxn],w[maxn],weight[maxn],num[maxn],pre[maxn];//从起点到各点的最小距离 
int G[maxn][maxn];
vector<int> route;
map<string,int> toInt;
map<int,string> toStr; 
bool vis[maxn];//是否访问过,最短路径条数 
void Dijkstra(int st){
	fill(d,d+maxn,INF);
	memset(vis,0,sizeof(vis));
	memset(num,0,sizeof(num));
	memset(w,0,sizeof(w));
	pre[st]=0;
	num[st]=1;
	w[st]=weight[st];
	d[st]=0;
	for(int i=0;i<n;i++){
		int u=-1,min=INF;
		for(int j=0;j<n;j++){
			if(!vis[j]&&d[j]<min){
				u=j;
				min=d[j];
			}
		}
		if(u==-1) return;
		vis[u]=true;
		for(int j=0;j<n;j++){
			if(!vis[j]&&G[u][j]!=INF){
				if(d[u]+G[u][j]<d[j]){
					pre[j]=u;
					d[j]=d[u]+G[u][j];
					w[j]=w[u]+weight[j];
					num[j]=num[u];
				}else if(d[u]+G[u][j]==d[j]){
					if(w[j]<w[u]+weight[j]){
						w[j]=w[u]+weight[j];
						pre[j]=u;
					}
					num[j]+=num[u];
				}
			} 
		} 
	}
}
void DFS(int ed){
	if(ed==0){
		route.push_back(ed);
		return;
	} 
	DFS(pre[ed]);
	route.push_back(ed);
}
int main(){
	fill(G[0],G[0]+maxn*maxn,INF);
	string s;
	cin>>n>>k>>s;
	toInt[s]=0;
	for(int i=1;i<n;i++){
		cin>>s;
		toInt[s]=i;
		cin>>weight[i];
	}
	for(int i=0;i<k;i++){
		string s1,s2;
		int d1,d2;
		cin>>s1>>s2;
		d1=toInt[s1];
		d2=toInt[s2];
		cin>>G[d1][d2];
		G[d2][d1]=G[d1][d2];
	}
	for(map<string,int>::iterator mp=toInt.begin();mp!=toInt.end();mp++){
		toStr[mp->second]=mp->first;
	} 
	Dijkstra(0);
	int ed=toInt["ROM"];
	DFS(ed);
	printf("%d %d %d %d\n",num[ed],d[ed],w[ed],w[ed]/(route.size()-1));
	for(int i=0;i<route.size();i++){
		int m=route[i];
		cout<<toStr[m];
		if(i<route.size()-1) printf("->");
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_32719923/article/details/88572174