灵神的每日一题(难度:1500)
题目描述
原题链接 https://codeforces.com/problemset/problem/1436/C
C. Binary Search
time limit per test 1 second
memory limit per test 256 megabytes
inputstandard input
outputstandard output
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 1e9+7.
Input
The only line of input contains integers n, x and pos (1≤x≤n≤1000, 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 1e9+7.
样例1
input
4 1 2
output
6
样例2
input
123 42 24
output
824071958
Note
All possible permutations in the first test case: (2,3,1,4), (2,4,1,3), (3,2,1,4), (3,4,1,2), (4,2,1,3), (4,3,1,2).
做法(排列组合)
如果要取到这个数,即二分后的结果要时刻保证包含位置pos,如果mid大于pos,就要让当前的值大于x,即在大于x的数中任意取一个,mid小于pos,就在小于x的数中取一个,如果mid等于pos,需要让mid取到pos(即只有一种取法),最后二分结束后,剩下的数全排列即可
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MOD = 1000000000 + 7;
int n,x,p;
LL cal(int n)
{
LL res = 1;
for (LL i = 1; i <= n; i ++ )
{
res *= i;
res = res % MOD;
}
return res;
}
int main()
{
cin >> n >> x >> p;
long long ans = 1;
int dn = n - x,xn = x - 1;
int l = 0,r = n;
while(l < r)
{
int mid = (l + r) / 2;
if(mid > p){
ans *= dn;
dn -- ;
r = mid;
}
else{
if(mid != p){
ans *= xn;
xn -- ;
}
l = mid + 1;
}
ans = ans % MOD;
}
ans = (ans * cal(dn + xn)) % MOD;
cout<<ans<<endl;
return 0;
}