2016大連區域賽 現場賽 F—Detachment【貪心+逆元】
Detachment
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total Submission(s): 346 Accepted Submission(s): 97Problem Description
In a highly developed alien society, the habitats are almost infinite dimensional space. In the history of this planet,there is an old puzzle. You have a line segment with x units’ length representing one dimension.The line segment can be split into a number of small line segments: a1,a2a1+a2 ai≠aj a1∗a2*...).Note that it allows to keep one dimension.That's to say, the number of ai can be only one. Now can you solve this question and find the maximum size of the space?(For the final number is too large,your answer will be modulo 10^9+7)
Input
The first line is an integer T,meaning the number of test cases. Then T lines follow. Each line contains one integer x. 1≤T≤10^6, 1≤x≤10^9
Output
Maximum s you can get modulo 10^9+7. Note that we wants to be greatest product before modulo 10^9+7.
Sample Input
1 4
Sample Output
4
題意:
給你一個數n(n<=1e9),讓你把n拆成若干個不相同的數的和,且這些數的積是所有拆分方法中最大的。輸出這些數的最大積對1e9+7取模。
分析:
要取乘積的最大,要把數儘量分成多個【貪心】,例如2+3+4+。。。。+ans,如果和為n,那就輸出ans的階乘;
如果比n大1,輸出3*4*....*(ans-1)*(ans+1)
其他情況差為x輸出2*....*(x-1)*(x+1)*......*ans
程式碼:
#include<bits/stdc++.h> #define ll long long #define mod 1000000007 using namespace std; ll a[100055]; ll n,ans; bool ok(ll mid) { return (mid+1)*mid/2-1>=n; } ll power(ll aa,ll n) //a的n次方mod { ll ans=1; aa=aa%mod; while (n) { if(n&1) ans=(ans*aa)%mod; n>>=1; aa=(aa*aa)%mod; } return ans; } int main() { ll t,i,j,l,r,pos,mid; ll tt; a[0]=1; for(i=1;i<=100005;i++) a[i]=(a[i-1]*i)%mod; scanf("%lld",&t); while(t--) { scanf("%lld",&n); l=1; r=n; if(n<=4) { printf("%lld\n",n); continue; } while(l<=r) { mid=(l+r)>>1; if(ok(mid)) { r=mid-1; ans=mid; } else l=mid+1; } pos=ans; ans=ans*(ans+1)/2-1-n; if(ans==0) { printf("%lld\n",a[pos]); continue; } if(ans==1) { tt=a[pos-1]*(pos+1)%mod; tt=tt*power(2,mod-2)%mod; printf("%lld\n",tt); continue; } else { tt=a[pos]; tt=tt*power(ans,mod-2)%mod; printf("%lld\n",tt); } } }