1117 Eddington Numbers
分数 25
British astronomer Eddington liked to ride a bike. It is said that in order to show off his skill, he has even defined an “Eddington number”, E – that is, the maximum integer E such that it is for E days that one rides more than E miles. Eddington’s own E was 87.
Now given everyday’s distances that one rides for N days, you are supposed to find the corresponding E (≤N).
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤105), the days of continuous riding. Then N non-negative integers are given in the next line, being the riding distances of everyday.
Output Specification:
For each case, print in a line the Eddington number for these N days.
Sample Input:
10
6 7 6 9 3 10 8 2 7 8
Sample Output:
6
AC Code
法一
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i)
cin >> a[i];
sort(a, a + n);
for (int i = n; i; --i) // 如果i符合的条件的话,需要有i天的距离大于i
{
if (a[n - i] > i) // a[n-i]是倒数第i个数//i>0
{
cout << i << endl;
return 0;
}
}
// 如果最小1都不满足条件,则E=0
puts("0");
return 0;
}
法二
#include <bits/stdc++.h>
using namespace std;
vector<int> a;
bool chk(int n)
{
int res = 0;
for (auto x : a)
{
if (x > n)
++res;
}
if (res < n)
return false;
return true;
}
int main()
{
int n;
cin >> n;
while (n--)
{
int x;
cin >> x;
a.push_back(x);
}
int l = 0, r = 1e9;//从0开始,不要从1开始
while (l < r)
{
int mid = l + r + 1 >> 1;
if (chk(mid))
l = mid;
else
r = mid - 1;
}
cout << l << endl;
return 0;
}
Review
- 题解
- 题意:找到最大的 $E$,满足有 $E$ 个数 $>E$
- 法一
对所有的数排序(升序),要满足有 $E$ 个数>$E$,也就是倒数第 $E$ 个数 $>E$
对于i>0
,数组a[0]~a[n-1]
的倒数第 $i$ 数是a[n-i]
特殊情况,所有的数都 $<1$,需要特判 - 法二
二分查找最大的 $E$,需要注意左边界 $l=0$ 而不是 $l=1$,因为有可能所有的数都 $<1$