【題解】ZeroJudge d908: 4. 最佳路徑

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=d908
【解題想法】DFS

  • func( ):以遞迴方式實現DFS
  • map <char, vector<pair<char, int> > > mp; 紀錄每一點可以通往的鄰接點及其權重。
  • (Line-13):紀錄路徑的最大權重總和。
#include <iostream>
#include <map>
#include <vector>
using namespace std;

map <char, vector<pair<char, int> > > mp;
char start;

int func(int start, int total){
    if (!mp.count(start)) return total;
    int maxi = 0;
    for (pair<char, int> p: mp[start]){
        maxi = max(func(p.first, total+p.second), maxi);
    }
    return maxi;
}

int main() {
    int num;
    while (cin >> start >> num){
        mp.clear();
        char a, b;
        int n;
        for (int i = 0; i < num; i++){
            cin >> a >> b >> n;
            mp[a].push_back({b, n});
        }
        cout << func(start, 0) << "\n";
    }
}

Python code (credit: Amy Chou)

def dfs(start, total):
    if start not in G:
        return total
    mx = 0
    for nxt, w in G[start]:
        mx = max(mx, dfs(nxt, total + w))
    return mx
    
# main program 
src = input()
n = int(input())
G = {}
for _ in range(n):
    tmp = input().split()
    if tmp[0] in G:
        G[tmp[0]].append((tmp[1], int(tmp[2])))
    else:
        G[tmp[0]] = [(tmp[1], int(tmp[2]))]
        
print(dfs(src, 0))
分享本文 Share with friends