A-取石子
从四个石子堆堆顶取石子,问有多少种取法,结果对1e9+7取模。
组合数问题
C(a+b+c+d,a)⋅C(b+c+d,b)⋅C(c+d,c)
C
(
a
+
b
+
c
+
d
,
a
)
⋅
C
(
b
+
c
+
d
,
b
)
⋅
C
(
c
+
d
,
c
)
(补充一下,这里无论先拿a还是b,c,d,最后化简后都是一样的)可能有人不太理解这个组合数怎么来的,如果将从堆顶拿石子看成序列的话,那么序列长度是a+b+c+d,
C(a+b+c+d,a)
C
(
a
+
b
+
c
+
d
,
a
)
就是指a+b+c+d中有a个都来自于数量为a的那一堆石子,
C(b+c+d,b)
C
(
b
+
c
+
d
,
b
)
是指剩下的b+c+d中有b个来自数量为b的石子堆,
C(c+d,c)
C
(
c
+
d
,
c
)
是剩下的c+d中有c个来自数量为c的石子堆,最后
C(d,d)=1
C
(
d
,
d
)
=
1
就不用说了吧。。
化简一下就是
(a+b+c+d)!a!(b+c+d)!
(
a
+
b
+
c
+
d
)
!
a
!
(
b
+
c
+
d
)
!
⋅
⋅
(b+c+d)!b!(c+d)!
(
b
+
c
+
d
)
!
b
!
(
c
+
d
)
!
⋅
⋅
(c+d)!c!d!
(
c
+
d
)
!
c
!
d
!
=>
(a+b+c+d)!a!b!c!d!
(
a
+
b
+
c
+
d
)
!
a
!
b
!
c
!
d
!
然后费马小定理求
a!b!c!d!
a
!
b
!
c
!
d
!
的逆元就好了。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod = 1e9+7;
inline ll Pow(int a,int p)
{
ll res = a,ans = 1;
while(p){
if(p&1) ans = res%mod*ans%mod;
res = res%mod*res%mod;
p >>= 1;
}
return ans%mod;
}
int main()
{
int a,b,c,d;
while(cin>>a>>b>>c>>d){
ll sum = 1;
for(int i = 1; i <= a+b+c+d; ++i)
sum = sum*i%mod;
for(int i = 1; i <= a; ++i)
sum = sum*Pow(i,mod-2)%mod;
for(int i = 1; i <= b; ++i)
sum = sum*Pow(i,mod-2)%mod;
for(int i = 1; i <= c; ++i)
sum = sum*Pow(i,mod-2)%mod;
for(int i = 1; i <= d; ++i)
sum = sum*Pow(i,mod-2)%mod;
cout<<sum%mod<<endl;
}
return 0;
}
不会费马小定理用Java,或者Python也可过。
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
public static BigInteger factorial(BigInteger x){
BigInteger tmp = BigInteger.ONE;
for(BigInteger i = BigInteger.ONE; i.compareTo(x)<=0; i=i.add(BigInteger.ONE))
tmp = tmp.multiply(i);
return tmp;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
BigInteger a[] = new BigInteger[4];
while (in.hasNext()) {
int sum = 0;
for (int i = 0; i < 4; ++i) {
int x = in.nextInt();
a[i] = factorial(BigInteger.valueOf(x));
sum += x;
}
BigInteger ans = factorial(BigInteger.valueOf(sum)).divide(a[0].multiply(a[1].multiply(a[2].multiply(a[3])))).mod(BigInteger.valueOf(1000000007));
System.out.println(ans);
}
in.close();
}
}
除此Java大数还可以用现成的求逆元的方法modInverse
BigInteger ans = factorial(BigInteger.valueOf(sum)).multiply(a[0].multiply(a[1].multiply(a[2].multiply(a[3]))).modInverse(BigInteger.valueOf(1000000007))).mod(BigInteger.valueOf(1000000007));
B-AB序列
题中的原式
∑(|Ai+x|)+∑(|BI+x|)+|x|
∑
(
|
A
i
+
x
|
)
+
∑
(
|
B
I
+
x
|
)
+
|
x
|
可以写成
∑(|x−(−Ai)|)+∑(|x−Bi|)+|x−0|
∑
(
|
x
−
(
−
A
i
)
|
)
+
∑
(
|
x
−
B
i
|
)
+
|
x
−
0
|
,所以说这是一个关于
x
x
的凹函数,最小值在组成的集合的中位数取到,如果中位数有两个则最小值在两个中位数之间取到。方法的话题解给了三个,线性时间求中位数,排序,二分或三分。这里蒻用的比较简单的排序。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5+7;
int a[N];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i = 0; i < n; ++i)
scanf("%d",&a[i]),a[i] = -a[i];
for(int i = n; i < n+m; ++i)
scanf("%d",&a[i]);
a[n+m] = 0;
sort(a,a+n+m+1);
long long sum = 0;
for(int i = 0; i <= n+m; ++i)
sum += abs(a[i]-a[n+m>>1]);
printf("%lld\n",sum);
return 0;
}