PAT甲级 1087 All Roads Lead to Rome

#include<iostream>
#include<map>
#include<vector>
#include<string>
#include<limits.h>
#include<algorithm>
using namespace std;
struct city{
    string name;
    int happiness;
};
struct road{
    vector<int>cc;
    int total;
    int happiness;
    int average_happiness;
};
bool comp(road x,road y){
      if(x.total!=y.total) return x.total<y.total;
     if(x.happiness!=y.happiness) return x.happiness>y.happiness;
   if(x.average_happiness!=y.average_happiness) return x.average_happiness>y.average_happiness;
}

map<string,int>m;
 int visited[300];
 vector<road>v;//存储最小cost的路径
vector<int>lingju[300];//存储邻节点
int roads[300][300];//存储cost
int mubiao;

city c[300];
vector <int>ans;
void dfs(int cur,int cost,int happiness){
    //ans.push_back();
    if(visited[cur]<cost) return;
    if(cur!=0){
           ans.push_back(cur);
    }
    if(cur==mubiao){
           if(cost==visited[mubiao]){
                road r;
                r.cc=ans;
                r.total=cost;
                r.happiness=happiness;
                r.average_happiness=happiness/ans.size();
                v.push_back(r);
           }
        else if(cost<visited[mubiao]){
                v.clear();
                road r;
                r.cc=ans;
                r.total=cost;
                r.happiness=happiness;
                r.average_happiness=happiness/ans.size();
                v.push_back(r);
                visited[mubiao]=cost;
        }
    }
    else {
        visited[cur]=cost;
            for(int i=0;i<lingju[cur].size();i++){
                int temp=lingju[cur][i];
                  dfs(temp,cost+roads[cur][temp],happiness+c[temp].happiness);
            }
        }
    if(ans.size()>0)
     ans.pop_back();
}
int main(){
    int n,k;string str;
    cin>>n>>k;
    cin>>str;
    
    c[0].name=str;
    for(int i=1;i<n;i++){
         cin>>c[i].name;
        cin>>c[i].happiness;
        m[c[i].name]=i;
        if(c[i].name=="ROM") mubiao=i;
}
for(int i=0;i<k;i++){
int j,k,cost;
    string s1,s2;
    cin>>s1>>s2>>cost;
    j=m[s1];
    k=m[s2];
    lingju[j].push_back(k);
    lingju[k].push_back(j);
    roads[j][k]=roads[k][j]=cost;
}
   
    for(int i=0;i<n;i++){ visited[i]=INT_MAX;}
    dfs(0,0,0);
   
    sort(v.begin(),v.end(),comp);
    if(!v.empty()){
    cout<<v.size()<<" "<<v[0].total<<" "<<v[0].happiness<<" "<<v[0].average_happiness<<endl;
 
    cout<<str;
    for(int i=0;i<v[0].cc.size();i++){
       cout<<"->"<<c[v[0].cc[i]].name;
}
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值