Official

B - Booby Prize Editorial by en_translator


Sort \(A_i\) in the decreasing order, and the original position of its second value is the answer. In order to obtain the original position of an element of a sorted array, we can sort \((A_i,i)\) instead of \(A_i\).

Sample code (C++)

#include<bits/stdc++.h>
using namespace std;

int main(){
	int n;
	cin >> n;
	vector<pair<int,int>>v;
	for(int i=0;i<n;i++){
		int a;
		cin >> a;
		v.push_back(make_pair(a,i+1));
	}
	sort(v.begin(),v.end(),greater<pair<int,int>>());
	
	cout << v[1].second << endl;
}

Sample code (Python)

N=int(input())
A=list(map(int,input().split()))
v=[]

for i in range(N):
	v.append((A[i],i+1))

v.sort()
v.reverse()
print(v[1][1])

As an another solution, we can store only the two largest values while inspecting each element in the original order, so that the problem is solved in a total of \(O(N)\) time without sorting. (It is like holding the first two values of insertion sort)

Sample code (Python)

N=int(input())
A=list(map(int,input().split()))

M1,M2=(0,0),(0,0)
for i in range(N):
	X=(A[i],i+1)
	if X>M1:
		M2=M1
		M1=X
	elif X>M2:
		M2=X

print(M2[1])

posted:
last update: