#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define out(a) copy(a.begin(),a.end(),ostream_iterator<int>(cout," "))
class Sortish {
public :
int sum;
vector< int > arr;
vector< int > pos, want, have;
int n;
int inter[ 2002 ] ;
int val[ 15 ] [ 15 ] ;
map< int , ll> dp[ ( 1 << 14 ) ] ;
int ls( int indx) {
return indx & ( - indx) ;
}
int get( int indx) {
int res = 0 ;
for ( ; indx > 0 ; indx - = ls( indx) )
res + = inter[ indx] ;
return res;
}
void update( int indx, int val) {
for ( ; indx <= n; indx + = ls( indx) )
inter[ indx] + = val;
}
ll solve( int indx, int mask, int need) {
if ( need < 0 )
return 0 ;
if ( indx == ( int ) want.size ( ) )
return need == 0 ;
if ( dp[ mask] .find ( need) ! = dp[ mask] .end ( ) )
return dp[ mask] [ need] ;
ll res = 0 ;
for ( size_t i = 0 ; i < want.size ( ) ; ++ i) {
if ( mask & ( 1 << i) )
continue ;
int tmp = val[ indx] [ i] ;
for ( size_t j = 0 ; j < i; ++ j) {
if ( mask & ( 1 << j) )
++ tmp;
}
res + = solve( indx + 1 , mask | ( 1 << i) , need - tmp) ;
}
return dp[ mask] [ need] = res;
}
long long ways( int sortedness, vector< int > seq) {
n = seq.size ( ) ;
arr = seq;
map< int , int > cnt;
for ( int i = 0 ; i < n; ++ i)
if ( arr[ i] )
cnt[ arr[ i] ] ++ ;
else
pos.push_back ( i) ;
for ( int i = 1 ; i <= n; ++ i)
if ( cnt.find ( i) ! = cnt.end ( ) )
have.push_back ( i) ;
else
want.push_back ( i) ;
int ps= 0 ;
for ( int i = 0 ; i < n; ++ i) {
if ( arr[ i] ) {
sum + = get( arr[ i] - 1 ) ;
update( arr[ i] , 1 ) ;
} else {
for ( size_t j = 0 ; j < want.size ( ) ; ++ j) {
val[ ps] [ j] + = get( want[ j] - 1 ) ;
for ( int k = i + 1 ; k < n; ++ k) {
if ( arr[ k] > want[ j] )
++ val[ ps] [ j] ;
}
}
++ ps;
}
}
return solve( 0 , 0 , sortedness - s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