結果
問題 | No.271 next_permutation (2) |
ユーザー |
![]() |
提出日時 | 2015-08-21 23:31:17 |
言語 | C++11 (gcc 13.3.0) |
結果 |
RE
|
実行時間 | - |
コード長 | 2,464 bytes |
コンパイル時間 | 1,727 ms |
コンパイル使用メモリ | 175,612 KB |
実行使用メモリ | 7,788 KB |
最終ジャッジ日時 | 2024-07-18 12:15:18 |
合計ジャッジ時間 | 5,016 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 2 RE * 19 |
コンパイルメッセージ
main.cpp: In instantiation of ‘V BIT<V, ME>::add(int, V) [with V = int; int ME = 18]’: main.cpp:43:9: 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; } }; ll array_inv(vector<ll> V) { static BIT<int,18> bt; ZERO(bt.bit); ZERO(bt.val); int x=0,i; map<ll,int> M; vector<int> V2; M[-1LL<<60]=0; FORR(r,V) M[r]=0; FORR(r,M) r.second=x++; ll ret=0; for(i=V.size()-1;i>=0;i--) { ret += bt.total(M[V[i]]); bt.add(M[V[i]],1); } return ret; } int N; ll K; vector<ll> P; ll fact[101010], totinv[101010]; ll ret; ll mo=1000000007; ll factinv(int n,ll k) { vector<ll> v; ll r=0; int i; FOR(i,n) v.push_back(i); while(k--) { r+=array_inv(v)%mo; next_permutation(v.begin(),v.end()); } 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"); FOR(i,30) P.push_back(i+1); FOR(i,N) cin>>x, P.push_back(x+30); N+=30; fact[0]=1; totinv[0]=0; for(i=1;i<=N;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; } for(i=N-2;i>=0;i--) { if(fact[N-1-i]>=K) { out: ret += factinv(N-1-i,K); break; } if(P[i]>P[i+1]) { ll smaller=0; for(x=i;x<N;x++) smaller+=P[i]>P[x]; for(x=i;x<N;x++) { if(P[i]<=P[x]) { ll smaller2=fact[N-1-i]%mo*smaller%mo; K -= fact[N-1-i]; (ret += totinv[N-1-i]+smaller2)%=mo; 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; }