結果
問題 | No.271 next_permutation (2) |
ユーザー |
![]() |
提出日時 | 2015-08-22 00:16:01 |
言語 | C++11 (gcc 13.3.0) |
結果 |
RE
|
実行時間 | - |
コード長 | 2,361 bytes |
コンパイル時間 | 1,199 ms |
コンパイル使用メモリ | 166,908 KB |
実行使用メモリ | 7,648 KB |
最終ジャッジ日時 | 2024-07-18 12:26:53 |
合計ジャッジ時間 | 4,816 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 3 WA * 2 RE * 16 |
コンパイルメッセージ
main.cpp: In instantiation of ‘V BIT<V, ME>::add(int, V) [with V = int; int ME = 18]’: main.cpp:41:27: required from here main.cpp:19:77: warning: no return statement in function returning non-void [-Wreturn-type] 19 | V add(int e,V v) { val[e++]+=v; while(e<=1<<ME) bit[e-1]+=v,e+=e&-e;} | ^
ソースコード
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<to;x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- template<class V, int ME> class BIT { public: V bit[1<<ME],val[1<<ME]; V total(int e) {V s=0;e++;while(e) s+=bit[e-1],e-=e&-e; return s;} V add(int e,V v) { val[e++]+=v; while(e<=1<<ME) bit[e-1]+=v,e+=e&-e;} V set(int e,V v) { add(e,v-val[e]);} int lower_bound(V val) { V tv=0; int i,ent=0; for(i=ME-1;i>=0;i--) if(tv+bit[ent+(1<<i)-1]<val) tv+=bit[ent+(1<<i)-1],ent+=(1<<i); return ent; } }; int N; ll K; vector<ll> P; ll fact[101010], totinv[101010]; ll ret; ll mo=1000000007; ll getsmaller(int n) { static BIT<int,18> bt; ZERO(bt.bit); ZERO(bt.val); int i; ll tot=0; for(i=n+1;i<N;i++) bt.add(P[i],1); FOR(i,n+1) tot+=bt.total(P[i]); return tot%mo; } ll factinv(ll k) { ll r=0; for(int i=N-1;i>=0;i--) { int j=0; if(k==0) break; while(k>=fact[i]) { r+=(totinv[i]+j*(fact[i]%mo))%mo; k-=fact[i]; j++; } } return r%mo; } void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>K; if(K==0) return _P("0\n"); P.push_back(0); FOR(i,N) cin>>x, P.push_back(x); N++; fact[0]=1; totinv[0]=0; for(i=1;i<=N+5;i++) { fact[i]=fact[i-1]*i; if(fact[i]<fact[i-1]) fact[i]=1LL<<62; totinv[i]=fact[i]%mo*i%mo; (totinv[i]*=i-1)%=mo; (totinv[i]*=(mo+1)/2)%=mo; (totinv[i]*=(mo+1)/2)%=mo; } ret=(K/fact[N-1])%mo*totinv[N-1]%mo; K%=fact[N-1]; for(i=N-2;i>=0;i--) { if(fact[N-1-i]>=K) { out: ret += factinv(K); break; } if(P[i]>P[i+1]) { ll smaller=getsmaller(i); for(x=i;x<N;x++) { if(P[i]<=P[x]) { ll smaller2=fact[N-1-i]%mo*smaller%mo; (ret += totinv[N-1-i]+smaller2)%=mo; K -= fact[N-1-i]; if(K<=fact[N-1-i]) goto out; smaller++; } } sort(P.begin()+i,P.end()); } } cout<<ret%mo<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); solve(); return 0; }