πŸ“ Algorithm/λ°±μ€€

[Swift] λ°±μ€€ 14938번 μ„œκ°• κ·ΈλΌμš΄λ“œ

JINiOS 2024. 10. 30. 18:53
728x90

 

μ„œκ°• κ·ΈλΌμš΄λ“œ

https://www.acmicpc.net/problem/14938

 

 

 

 

풀이

λ‹€μ΅μŠ€νŠΈλΌ

 

1. 1λΆ€ν„° NκΉŒμ§€ BFS λ°˜λ³΅ν•˜λ©΄μ„œ μ΅œλŒ“κ°’ μ—…λ°μ΄νŠΈ

2. λ‹€μŒ 큐의 cost λ”ν–ˆμ„ λ•Œ μˆ˜μƒ‰λ²”μœ„ μ•ˆμ΄κ³ , λ‹€μŒ 큐의 갯수λ₯Ό λ”ν–ˆμ„ λ•Œ ν˜„μž¬ μ•„μ΄ν…œ κ°―μˆ˜λ³΄λ‹€ 크닀면 큐에 μΆ”κ°€ν•˜κΈ°

3. 큐에 λ“€μ–΄κ°„ μ•„μ΄ν…œλ“€μ€ μ „λΆ€ 갈 수 μžˆμœΌλ―€λ‘œ Set둜 관리. bfs λλ‚œ ν›„ Set에 λ“€μ–΄μžˆλŠ” μ•„μ΄ν…œμ— ν•΄λ‹Ήν•˜λŠ” λΉ„μš© μΆ”κ°€ν•΄μ„œ bfs λ°˜ν™˜

 

 

μ†ŒμŠ€μ½”λ“œ

let NMR = readLine()!.split(separator: " ").map { Int($0)! }
let N = NMR[0], M = NMR[1], R = NMR[2]

var items: [Int] = [0]
items += (readLine()!.split(separator: " ").map { Int($0)! })

var roads: [Int :[(ed: Int, cost: Int)]] = [:]

for _ in 0..<R {
    let tmp = readLine()!.split(separator: " ").map { Int($0)! }
    roads[tmp[0], default: []].append((tmp[1], tmp[2]))
    roads[tmp[1], default: []].append((tmp[0], tmp[2]))
}

func bfs(_ st: Int) -> Int {
    var curItem: [Int] = Array(repeating: 0, count: N+1)
    var que: [(Int, Int)] = [(st, 0)] // λ‹€μŒ μ§€μ—­, ν˜„μž¬ μˆ˜μƒ‰λ²”μœ„
    var vis = Set<Int>()
    vis.insert(st)
    
    var idx = 0
    var res = 0
    while que.count > idx {
        let (q, qLimit) = que[idx]
        
        for (nq, ncost) in roads[q, default: []] {
            if nq == st { continue } // λ‹€μŒ 큐가 μ‹œμž‘ 지역이라면 λ„˜μ–΄κ°€κΈ°
            if qLimit + ncost > M { continue } // λ‹€μŒ 큐λ₯Ό μΆ”κ°€ν–ˆμ„ λ•Œ μˆ˜μƒ‰λ²”μœ„ 보닀 컀지면 λ„˜μ–΄κ°€κΈ°
            
            // ν˜„μž¬ μ•„μ΄ν…œκ°’μ— λ‹€μŒ μ•„μ΄ν…œ 값을 ν¬ν•¨ν•œκ²Œ, ν˜„μž¬λ³΄λ‹€ 크면
            if items[nq] + curItem[q] > curItem[nq] {
                que.append((nq, ncost + qLimit))
                curItem[nq] = items[nq] + curItem[q]
                vis.insert(nq)
            }
        }
        
        idx += 1
    }
    for vi in vis {
        res += items[vi]
    }
    return res
}


var maxRes = 0

for i in 1...N {
    let res = bfs(i)
    maxRes = max(res, maxRes)
}

print(maxRes)

 

 

λ°˜λ‘€ λͺ¨μŒ

λ°˜λ‘€ 1

5 5 4

5 7 8 2 3

1 4 1

5 2 4

3 2 3

1 2 3

μ •λ‹΅: 25

 

λ°˜λ‘€ 2

5 5 5

1 2 3 4 5

1 2 2

1 3 4

1 4 2

2 3 4

4 5 2

μ •λ‹΅: 15

728x90