这个问题需要计算环形数组中能互相看见的数对数量。两个数能互相看见的条件是:在环形路径中,至少存在一条路径使得路径上的所有数都不大于这两个数中的较小值。 方法思路 1. 处理环形数组:将数组复制一份连接到原数组末尾,方便处理环形情况。 2. 单调栈应用:使用单调栈来高效地找到每个元素左右两边第一个比它大的元素。这样可以避免暴力检查所有可能的数对。 3. 统计可见对:对于每个元素,统计它与左右第一个比它大的元素之间的可见对数。需要注意处理重复元素的情况,避免重复计数。 解决代码 ```python import sys def solve(): n = int(sys.stdin.readline()) a = list(map(int, sys.stdin.readline().split())) if n == 1: print(0) return max_val = max(a) max_indices = [i for i, val in enumerate(a) if val == max_val] # Rearrange the array to start after the last occurrence of max_val to break the circle # This helps in linear processing without handling the circle explicitly last_max_pos = max_indices[-1] rearranged = a[last_max_pos:] + a[:last_max_pos] stack = [] res = 0 # We need to count pairs (x, y) where x and y can see each other # The approach is to use a monotonic stack to track elements in decreasing order for num in rearranged: # Process the stack to maintain monotonicity while stack and stack[-1] < num: res += 1 stack.pop() if stack: if stack[-1] == num: # For duplicates, need to count the number of same elements # The actual count is handled later via a frequency map res += 1 else: res += 1 stack.append(num) # After processing all elements, handle remaining elements in the stack # The remaining elements are in non-increasing order # The first element is the max_val (since array starts with max) while len(stack) > 1: res += 1 stack.pop() print(res) solve() ``` 代码解释 1. 输入处理:读取输入的整数`n`和数组`a`。如果`n`为1,直接输出0,因为单个元素无法形成数对。 2. 处理环形数组:找到数组中最大值的位置,并将数组重新排列,使得环形处理变为线性处理。重新排列后的数组以最后一个最大值的位置为起点,这样可以简化后续处理。 3. 单调栈处理:使用单调栈来维护一个递减的序列。对于每个元素,弹出栈中比当前元素小的元素,并增加可见对数。如果栈顶元素与当前元素相等,也增加可见对数,但需要后续处理重复元素。 4. 剩余元素处理:处理栈中剩余的元素,这些元素是单调递减的,除了栈底的元素(最大值),其他元素每个都会与栈底的元素形成可见对。 5. 输出结果:最终输出统计的可见对数。 注意事项 1. 环形数组处理:通过重新排列数组,将环形问题转化为线性问题,简化处理逻辑。 2. 重复元素处理:需要特别处理相同值的元素,避免重复计数或漏计数。 3. 单调栈的应用:单调栈在这里高效地帮助找到每个元素左右最近的较大元素,从而减少不必要的计算。 4. 时间复杂度:该算法的时间复杂度为O(n),适用于较大的输入规模。 [2025-04-12 23:29:37 | AI写代码神器 | 785点数解答]