Реши на с++ задачу с фото

생성일: 2026년 4월 22일

답변에 사용된 모델 GPT-5.3 by Chat01

질문

20260422_161306.jpg

Реши на с++ задачу с фото

사고

Solving maximum distance of equal elements efficiently

I need to solve the problem of finding the maximum distance between equal elements in a sequence. We can use an unordered map to track first positions and calculate the maximum difference in indices between repeated values. The algorithm should be efficient, ideally O(n), but handling large values requires careful memory management, especially since N can go up to 1e6. Sorting seems too slow, so a more efficient approach is needed.

Exploring memory-efficient approaches for solving the problem

I'm considering using an unordered_map for faster access, but with N as large as 1e6, the memory could exceed 32MB. A more memory-efficient alternative could be sorting the elements by value, storing only the first occurrence, and calculating the max difference between indices. This approach uses sorting with minimal memory and might fit within the time limit.

Thought for 24s

답변

Вот решение на C++.

Идея простая: для каждого числа надо знать самую левую и самую правую позицию. Тогда расстояние между одинаковыми элементами равно right - left, а ответ — максимум по всем значениям.

Чтобы уложиться в память при N до 1000000, удобно сохранить пары
(значение, позиция), отсортировать их по значению и пройти по группам одинаковых чисел.

cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Item { long long value; int pos; }; bool cmp(const Item& a, const Item& b) { if (a.value != b.value) return a.value < b.value; return a.pos < b.pos; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<Item> a(N); for (int i = 0; i < N; ++i) { cin >> a[i].value; a[i].pos = i; } sort(a.begin(), a.end(), cmp); int ans = 0; int i = 0; while (i < N) { int j = i; int firstPos = a[i].pos; int lastPos = a[i].pos; while (j < N && a[j].value == a[i].value) { lastPos = a[j].pos; ++j; } ans = max(ans, lastPos - firstPos); i = j; } cout << ans << '\n'; return 0; }

Как это работает на примере:

1 2 3 1 2 2 4 5 6 7

  • для 1: позиции 0 и 3, расстояние 3
  • для 2: позиции 1, 4, 5, максимальное расстояние 5 - 1 = 4

Ответ: 4.

Если хочешь, я могу сразу дать и более короткую версию, а также объяснение построчно для сдачи.

이 Q&A 공유하기