题目
Andrey thinks he is truly a successful developer, but in reality he didn’t know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows:
Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down).
Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x!
Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order.
Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7.
Input
The only line of input contains integers n,x and pos(
1
≤
x
≤
n
≤
1000
1 \le x \le n \le 1000
1≤x≤n≤1000,
0
≤
p
o
s
≤
n
−
1
0 \le pos \le n - 1
0≤pos≤n−1) — the required length of the permutation, the number to search, and the required position of that number, respectively.
Output
Print a single number — the remainder of the division of the number of valid permutations by 10^9+7.
样例
输入:
4 1 2
输出:
6
输入:
123 42 24
输出:
824071958
题意
有一个含有n个数的序列,如果序列有序,则按照如下代码可以找到 pos 位置上的数字 x ,现在,如果序列无序,而且仍然可以用下面这段代码找到位于pos 位置上的数字 x ,请问这样的序列有多少种,答案对1e9+7取模。
思路
发现题目给出的代码是二分
如果序列无序,可是二分的前提是单调,所以仔细想想,发现下标是单调的
因此:使用二分算法进行查找计数,找出哪些位置的数值是大于x的,哪些位置的数值是小于x的,
然后进行全排列即可找出答案。
AC代码
#include<iostream>
using namespace std;
#define ll long long
ll mod = 1e9 + 7;
const int N = 1e3;
ll jie(int n, int m) {
ll res = 1;
for (ll i = n; i >= (n - m + 1); i--)
res = (res * i) % mod;
return res;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n, x, pos;
cin >> n >> x >> pos;
int l = 0, r = n;
ll nums = 0, numb = 0;
while (l - r < 0) {
int mid = (l + r) / 2;
//特别注意这一步,大数和小数都不算内,只进行二分
if (mid == pos)
l = mid + 1;
else if (mid > pos) {
r = mid;
numb += 1;
}
else {
l = mid + 1;
nums += 1;
}
}
if (numb > n - x || nums > x - 1) {
cout << 0 << endl;
return 0;
}
ll ans = 1;
ans = (ans * jie(n - x, numb)) % mod;
ans = (ans * jie(x - 1, nums)) % mod;
ans = (ans * jie(n - numb - nums - 1, n - numb - nums - 1)) % mod;
cout << ans << endl;
return 0;
}