1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Zadanie: Dostawa Żwiru (DOS)
// runda 2
// Marcin Machura <marcin.machura@hotmail.com>

use std::io;
use std::collections::BinaryHeap;


fn main() {
    let mut input = String::new();
    
    // Wczytywanie n i k
    io::stdin()
        .read_line(&mut input)
        .expect("Błąd danych!");
    
    let nums: Vec<i64> = input
        .split_whitespace()
        .filter_map(|s| s.parse::<i64>().ok()) 
        .collect();
    
    let n = nums[0] as usize; // Konwersja na usize do indeksowania
    let k = nums[1]; 
    
    input.clear();
    
    // Wczytywanie wysokości ścieżki
    io::stdin()
        .read_line(&mut input)
        .expect("Błąd danych #2");
        
    // stan fragmentów scieżki
    let mut steps: Vec<i64> = input
        .split_whitespace()
        .filter_map(|s| s.parse::<i64>().ok()) 
        .collect();

    let mut trucks: i64 = 0;

    // skopcowane fragmenty scieżki by wybierac najwyższy
    let mut heap: BinaryHeap<(i64, usize)> = BinaryHeap::new(); 
    
    for i in 0..n {
        heap.push((steps[i], i));
    }
    
    while let Some((h, i)) = heap.pop() {
        // zamiast upheap: jeśli wartość w tablicy jest już większa -> ten wpis w kopcu jest nieaktualny
        if h < steps[i] {
            continue;
        }

        // Lewy sąsiad
        if i > 0 {
            let left = i - 1;
            if steps[left] + k < steps[i] {
                let diff = (steps[i] - k) - steps[left];
                trucks += diff;
                steps[left] = steps[i] - k;
                heap.push((steps[left], left));
            }
        }

        // Prawy sąsiad
        if i + 1 < n {
            let right = i + 1;
            if steps[right] + k < steps[i] {
                let diff = (steps[i] - k) - steps[right];
                trucks += diff;
                steps[right] = steps[i] - k;
                heap.push((steps[right], right));
            }
        }
    }
    
    println!("{}", trucks);
}