結果
| 問題 |
No.271 next_permutation (2)
|
| コンテスト | |
| ユーザー |
kmjp
|
| 提出日時 | 2015-08-22 00:34:51 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
RE
|
| 実行時間 | - |
| コード長 | 2,196 bytes |
| コンパイル時間 | 1,196 ms |
| コンパイル使用メモリ | 166,828 KB |
| 実行使用メモリ | 6,948 KB |
| 最終ジャッジ日時 | 2024-07-18 12:28:04 |
| 合計ジャッジ時間 | 4,220 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| 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:34:27: required from here
main.cpp:19:64: warning: no return statement in function returning non-void [-Wreturn-type]
19 | V add(int e,V 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];
V operator()(int e) {V s=0;e++;while(e) s+=bit[e-1],e-=e&-e; return s;}
V add(int e,V v) { while(e<=1<<ME) bit[e-1]+=v,e+=e&-e;}
};
ll mo=1000000007;
int N;
ll K;
vector<ll> P;
ll fact[101010], totinv[101010];
ll ret;
ll getsmaller(int n) {
static BIT<int,18> bt;
ZERO(bt.bit);
int i;
ll tot=0;
for(i=n+1;i<N;i++) bt.add(P[i],1);
FOR(i,n+1) tot+=bt(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:
ll smaller=getsmaller(i);
ret += factinv(K)+(smaller*K)%mo;
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++;
swap(P[i],P[x]);
}
}
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;
}
kmjp