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
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <vector>

using namespace std;

struct Node {
    unsigned long value;
    bool isLeaf;
    Node *leftChild;
    Node *rightChild;
};

struct Answer {
    unsigned long innerShift;
    unsigned long outerShift;

    Answer(unsigned long innerShift, unsigned long outerShift) : innerShift(innerShift), outerShift(outerShift) {}
};

Node *createTree(vector<unsigned long> &values, unsigned long from, unsigned long to) {
    auto *node = new Node();

    node->isLeaf = to - from == 1;

    if (node->isLeaf) {
        node->value = values[from];
    } else {
        node->leftChild = createTree(values, from, (from + to) / 2);
        node->rightChild = createTree(values, (from + to) / 2, to);
        node->value = min(node->leftChild->value, node->rightChild->value);
    }

    return node;
}

void deleteTree(Node *tree) {
    if (!tree->isLeaf) {
        deleteTree(tree->leftChild);
        deleteTree(tree->rightChild);
    }
    delete tree;
}

Answer query(Node *node, int value, unsigned long shift) {
    if (node->value >= value + shift) {
        return {0, 0};
    }

    if (node->isLeaf) {
        unsigned long outerShift = value + shift - node->value;
        return {outerShift, outerShift};
    }

    Answer answerFromLeft = query(node->leftChild, value, shift);
    Answer answerFromRight = query(node->rightChild, value, answerFromLeft.outerShift);
    return {answerFromLeft.innerShift + answerFromRight.innerShift, answerFromRight.outerShift};
}

void readInput(vector<unsigned long> &values, vector<int> &queries) {
    int valuesCount, queriesCount;
    cin >> valuesCount >> queriesCount;
    unsigned long previousValue = 0;
    for (int i = 0; i < valuesCount; i++) {
        unsigned long value;
        cin >> value;
        values.push_back(value - previousValue);
        previousValue = value;
    }
    for (int i = 0; i < queriesCount; i++) {
        int query;
        cin >> query;
        queries.push_back(query);
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    vector<unsigned long> values;
    vector<int> queries;
    readInput(values, queries);
    Node *tree = createTree(values, 0, values.size());
    for (int q : queries) {
        Answer answer = query(tree, q, 0);
        cout << answer.innerShift << endl;
    }
    deleteTree(tree);
    return 0;
}