其他分享
首页 > 其他分享> > PAT2021年春季3月份备考_经验分享和心路历程(10-4)

PAT2021年春季3月份备考_经验分享和心路历程(10-4)

作者:互联网

题干:1087 All Roads Lead to Rome (30 分)

// A1087.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <bits/stdc++.h>
using namespace std;
struct info {
    string name;
    int cost;
};
unordered_map<string, int> happy;
unordered_map<string, vector<info>> gn;
unordered_map<string, bool> visit;

int max_cost = INT_MAX;
int max_happy = INT_MIN;
int avg_happy = INT_MIN;
int cur_count;
int avg = -1;
vector<string> temp_path;
vector<string> final_path;
vector<int> an;
void DFS(string start,int cost,int happiness,int count) {//count计算的是节点的,happiness是在节点上的
    if (count != 0) {
        avg = happiness / (count);
    }
    if (start == "ROM" && 
        (cost < max_cost|| 
            (cost == max_cost&& happiness> max_happy)||
            (happiness == max_happy && avg> avg_happy)
            )
        ) {
        max_cost = cost;
        max_happy = happiness;
        avg_happy = avg;
        cur_count = count;
        final_path = temp_path;
    }
    if (start == "ROM") {
        an.push_back(cost);
        return;
    }
    for (int i = 0; i < gn[start].size(); i++) {
        if (visit[gn[start][i].name] != true) {
            visit[gn[start][i].name] = true;
            temp_path.push_back(gn[start][i].name);
            DFS(gn[start][i].name,cost+ gn[start][i].cost, happiness +happy[gn[start][i].name], count+1);
            visit[gn[start][i].name] = false;
            temp_path.pop_back();
        }
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    FILE* s;
    freopen_s(&s, "in.txt", "r", stdin);
#endif // !ONLINE_JUDGE

    int n, k;
    string start;
    cin >> n >> k >> start;
    string a; int b; string c;
    for (int i = 0; i < n-1; i++) {
        cin >> a >> b;
        happy[a] = b;
    }
    for (int i = 0; i < k; i++) {
        cin >> a >> c >> b;
        gn[a].push_back({ c,b });
        gn[c].push_back({ a,b });
    }
    visit[start] = true;
    temp_path.push_back(start);
    DFS(start,0,0,0);
    int match = 0;
    for (int i = 0; i < an.size(); i++) {
        if (an[i] == max_cost) {
            match++;
        }
    }
    printf("%d %d %d %d\n", match, max_cost, max_happy, avg_happy);
    cout << final_path[0];
    for (int i = 1; i < final_path.size(); i++) {
        cout << "->" << final_path[i];
    }
    return 0;
}

 

标签:PAT2021,cost,10,int,max,start,心路历程,gn,happy
来源: https://blog.csdn.net/qq_30753921/article/details/113961882