题意简述
给出一个长度为 的序列, 次操作,每次操作给出一整数 ,把该序列分成连续的长度均为 的 段后,把每段反转,并查询反转后整体的逆序对数。
题解
考虑一次反转后对整个序列造成的影响。
每次操作相当于把整个序列分成了 个块,我们只需要考虑块内和块外。
考虑一个块对其他块的情况。
嗯。
没有影响,完。
那么我们只需要考虑如何快速计算出每个块内的变化即可。
像归并排序一样考虑问题,把序列分成 层(把二叉树画出来)。
要反转区间 就要翻转 ,以此类推。
然后就预处理出每一层顺序对逆序对即可。
#include <cstdio>
#define LL long long
const int MAXN = ( 1 << 20 ) + 5, MAXM = 1e6 + 5;
LL rint () {
LL x = 0, f = 1; char c = getchar ();
for ( ; c < '0' || c > '9'; c = getchar () ) f = c == '-' ? -1 : f;
for ( ; c >= '0' && c <= '9'; c = getchar () ) x = ( x << 3 ) + ( x << 1 ) + ( c & 15 );
return x * f;
}
template<typename _T>
void wint ( _T x ) {
if ( x < 0 ) putchar ( '-' ), x = ~ x + 1;
if ( x > 9 ) wint ( x / 10 );
putchar ( x % 10 ^ '0' );
}
template<typename _T> void swapp ( _T &x, _T &y ) { _T w = x; x = y; y = w; }
int n, m, ts, a[MAXN], fm[MAXN];
LL cnt[25][2];
void Merge ( const int l, const int r, const int x ) {
if ( l >= r ) return;
int mid = ( l + r ) >> 1;
Merge ( l, mid, x - 1 ), Merge ( mid + 1, r, x - 1 );
int i = l, j = mid + 1;
for ( ; i <= mid && j <= r; ) {
if ( a[i] < a[j] ) cnt[x][1] += r - j + 1, ++ i;
else ++ j;
}
i = l, j = mid + 1;
int s = 0;
for ( ; i <= mid && j <= r; ) {
if ( a[i] > a[j] ) cnt[x][0] += mid - i + 1, fm[s ++] = a[j ++];
else fm[s ++] = a[i ++];
}
for ( ; i <= mid; fm[s ++] = a[i ++] ) ;
for ( ; j <= r; fm[s ++] = a[j ++] ) ;
for ( int i = l; i <= r; ++ i ) a[i] = fm[i - l];
}
int main () {
n = rint ();
for ( int i = 1; i <= ( 1 << n ); ++ i ) a[i] = rint ();
Merge ( 1, 1 << n, n );
m = rint ();
for ( int _ = 1; _ <= m; ++ _ ) {
int x = rint ();
LL res = 0;
while ( x -- > 0 ) swapp ( cnt[x + 1][0], cnt[x + 1][1] );
for ( int i = 1; i <= n; ++ i ) res += cnt[i][0];
wint ( res ), putchar ( '\n' );
}
return 0;
}