*【HDU - 6333】Problem B. Harvest of Apples (莫队,逆元,组合数学)(这样预处理正确吗?)
題干:
There are?nn?apples on a tree, numbered from?11?to?nn.?
Count the number of ways to pick?at most?mm?apples.?
Input
The first line of the input contains an integer?TT?(1≤T≤105)(1≤T≤105)?denoting the number of test cases.?
Each test case consists of one line with two integers?n,mn,m?(1≤m≤n≤105)(1≤m≤n≤105).?
Output
For each test case, print an integer representing the number of ways modulo?109+7109+7.
Sample Input
2 5 2 1000 500Sample Output
16 924129523解題報告:
? ?不得不說,一道好題。
? ?會者不難,難者不會。
? ?剛開始想到離線了。這么想的:想著組合數(shù)公式打表,但是空間復雜度不容許,然后像滾動數(shù)組優(yōu)化,自然而然就想到離線了,這樣跑下來就相當于是求了一遍1e5的組合數(shù)。(相當于n^2了)然而超時了。
? ?正解是這樣的,(鏈接)首先我們要知道組合數(shù)和楊輝三角存在著密切的關系?(貌似是高中講二項式定理的時候提到的)
令表示n個蘋果最多取m個的方案數(shù),很容易想到
根據(jù)楊輝三角也很容易推出
我們將m~n當作一條線段,那么就是這條線段的函數(shù)值,而根據(jù)上面的兩個公式,又可以在O(1)的時間內(nèi)實現(xiàn)到、、、的轉(zhuǎn)移。利用莫隊算法離線處理即可。
AC代碼:
#include<bits/stdc++.h> #define ll long long using namespace std; const int MAX = 1e5 + 5; const ll mod = 1000000007; ll jie[MAX],inv[MAX],q[MAX]; struct Node {int l , r,block,id; } node[MAX]; //bool cmp(Node a,Node b) { // if(a.block == b.block) return a.r < b.r; // else return a.l < b.l; //} //這樣分塊貌似會快不少? bool cmp(Node a,Node b) {if (a.block!=b.block) return a.l<b.l;if (a.block&1) return a.r>b.r;return a.r<b.r; } //這個c函數(shù)是錯的。。。貌似就是因為沒有判斷r<l的情況? //ll c(ll n,ll m) { // return jie[n]*(jie[m]%mod*jie[n-m]%mod); //} ll c(int r,int l) {if (r<l) return 0;return jie[r]*inv[l]%mod*inv[r-l]%mod; } int main() {jie[1] = 1;jie[0] = 1;inv[1] = 1;inv[0] = 1;for(int i = 2; i<=MAX-1; i++) jie[i] = (jie[i-1] * i)%mod;for(int i = 2; i<=MAX-1; i++) {inv[i] = (mod - mod/i*inv[mod%i]%mod)%mod;} //這兩個求逆元的公式都可以使用 // for (int i=2; i<MAX; i++) { // inv[i]=inv[mod%i]*(mod-mod/i)%mod; // } //預處理逆元的前綴積for (int i=2; i<MAX; i++) inv[i]=inv[i-1]*inv[i]% mod;int t;cin>>t;int blk = sqrt(100000);for(int i = 1; i<=t; i++) {scanf("%d%d",&node[i].r,&node[i].l);node[i].id = i;node[i].block = node[i].l/blk;}int l=1,r=1;ll ans = 2;sort(node+1,node+t+1,cmp);for(int i = 1; i<=t; i++) {while(l < node[i].l) l++,ans = (ans + c(r,l))%mod;while(l > node[i].l) ans = (ans - c(r,l) + mod) % mod,l--;while(r < node[i].r) r++,ans = (2*ans-c(r-1,l) + mod )%mod;while(r > node[i].r) ans = (ans + c(r-1,l)) * inv[2] % mod,r--;q[node[i].id] = ans;} for(int i = 1; i<=t; i++) printf("%lld\n",q[i]);return 0 ; }?
總結
以上是生活随笔為你收集整理的*【HDU - 6333】Problem B. Harvest of Apples (莫队,逆元,组合数学)(这样预处理正确吗?)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 券商公司太疯狂!为研究比亚迪 拆了一台元
- 下一篇: 【CH - 1401】 兔子与兔子(字符