解题思路:先循环找一次最大的a_ib_i,然后循环把所有等于该最大值的菜品标记售罄。然后在剩下的菜里找最大的a_ib_i,如果等大,找最小的|a_i-b_i|。只要是顺着遍历的,找到的一定是编号最小的。
注意10^9是会爆int的,所以建议使用long long;另外,本题如果用冒泡排序等一般的排序来做,会超时。(快速排序等\Omicron(n\log n)的排序不会超时,有兴趣可以自行了解)
参考代码:
C语言:
#include <stdio.h>
#include <math.h>
long long n, a[100010], b[100010], max_ab = -1, min_d = 1e10, k, v[100010];
int main()
{
scanf("%lld", &n);
for (int i = 1; i <= n; ++i) //为让下标与编号对应,从下标1开始使用数组
{
scanf("%lld", &a[i]);
}
for (int i = 1; i <= n; ++i)
{
scanf("%lld", &b[i]);
}
for (int i = 1; i <= n; ++i)
{
if (a[i] * b[i] > max_ab)
{
max_ab = a[i] * b[i];
}
}
for (int i = 1; i <= n; ++i)
{
if (a[i] * b[i] == max_ab)
{
v[i] = 1; //表示售罄
}
}
max_ab = -1; //重新初始化
for (int i = 1; i <= n; ++i)
{
if (v[i] == 0 && (a[i] * b[i] > max_ab || a[i] * b[i] == max_ab && fabs(a[i] - b[i]) < min_d))
{
max_ab = a[i] * b[i]; //除去售罄菜外当前最美味的值
min_d = fabs(a[i] - b[i]); //在最美味的值里,最小|a_i-b_i|的差值
k = i;
}
}
if (k == 0) //全局变量初始值为0
{
printf("sold out");
}
else
{
printf("%lld %lld", k, a[k] * b[k]);
}
return 0;
}
Python:
n = int(input())
a = [int(i) for i in input().strip().split(' ')]
b = [int(i) for i in input().strip().split(' ')]
max_ab = -1
min_d = 1e10
ans = -1
for i in range(n):
if a[i]*b[i] > max_ab:
max_ab = a[i]*b[i]
v = [a[i]*b[i] == max_ab for i in range(n)]
max_ab = -1
for i in range(n):
if not v[i] and (a[i]*b[i] > max_ab or a[i]*b[i] == max_ab and abs(a[i]-b[i]) < min_d):
ans = i
max_ab = a[i]*b[i]
min_d = abs(a[i]-b[i])
if ans == -1:
print('sold out')
else:
print('%d %d'%(ans+1, a[ans]*b[ans]))