Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unordered_map>
- #include <optional>
- #include <iostream>
- #include <vector>
- using SegmentT = std::pair<size_t, size_t>;
- using AnswerT = std::optional<SegmentT>;
- // Найти непрерывный отрезок массива с заданной суммой
- AnswerT getSegment(const std::vector<int> & input, int value) {
- // Получаем массив частных сумм
- std::vector<int> prepare;
- size_t sum = 0U;
- for (auto elem : input) {
- sum += elem;
- prepare.push_back(sum);
- }
- // @first - частная сумма
- // @second - позиция элемента
- std::unordered_map<int, size_t> pos;
- for (size_t index = 0U; index < prepare.size(); index++) {
- // Важно перезаписать!
- pos[prepare[index]] = index;
- }
- for (size_t index = 0U; index < input.size(); index++) {
- auto it = pos.find(value - input[index]);
- if (it == pos.end()) continue;
- if (it->second < index) {
- return {{ it->second + 1, index }};
- }
- }
- return std::nullopt;
- }
- int main() {
- std::vector<int> input = {1, 2, 3, 5, -3, 5};
- int value = 8;
- auto result = getSegment(input, value);
- if (result) {
- for (size_t index = result->first; index <= result->second; index++) {
- std::cout << input[index] << " ";
- }
- }else {
- std::cout << "Не найдено" << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement