C - Swaps 2(树状数组,思维)
生活随笔
收集整理的這篇文章主要介紹了
C - Swaps 2(树状数组,思维)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C - Swaps 2
給定兩個長度為nnn的數組A,BA, BA,B,我們可以進行若干次如下操作,使AAA變成BBB,
- 選定i<ni < ni<n,將aia_iai?減小111,將ai+1a_{i + 1}ai+1?增加111。
- 交換ai,ai+1a_i, a_{i + 1}ai?,ai+1?。
問我們進行多少次操作,可以將AAA變成BBB,如果無解則輸出?1-1?1,否則輸出最小操作次數。
容易發現,不管怎么交換ai+ia_i + iai?+i的值都是不變的,當我們要得到bib_ibi?的時候,我們一定是去找一個aj+j=bi+ia_j + j = b_i + iaj?+j=bi?+i,且jjj最小的那個點,這樣可以減小操作次數,
所以可以考慮先離散化,然后用vectorvectorvector存下ai+ia_i + iai?+i的所有下標。因為每個數的下標都是會變化的,所以我們要知道AAA中每個點的真實下標。
容易發現只有原始數組中的某個數下標大于當前下標,如果這個數向前移動了,這個時候才會使得我們得數組下標變大,所以只要用數組數組存一下即可。
#include <bits/stdc++.h>using namespace std;const int N = 2e5 + 10;int a[N], b[N], c[N], sum[N], n, m;vector<int> vt[N];inline int lowbit(int x) {return x & (-x); }void update(int x, int v) {while (x <= n) {sum[x] += v;x += lowbit(x);} }int query(int x) {int ans = 0;while (x) {ans += sum[x];x -= lowbit(x);}return ans; }int query(int l, int r) {return query(r) - query(l - 1); }int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);scanf("%d", &n);for (int i = 1; i <= n; i++) {scanf("%d", &a[i]);c[i] = a[i] + i;}sort(c + 1, c + 1 + n);m = unique(c + 1, c + 1 + n) - (c + 1);for (int i = 1; i <= n; i++) {scanf("%d", &b[i]);int pos = lower_bound(c + 1, c + 1 + m, b[i] + i) - c;if (c[pos] != b[i] + i) {puts("-1");return 0;}b[i] = pos;vt[lower_bound(c + 1, c + 1 + m, a[i] + i) - c].push_back(i);}long long ans = 0;for (int i = 1; i <= n; i++) {if (!vt[b[i]].size()) {puts("-1");return 0;}int cur = vt[b[i]].back();ans += cur + query(cur + 1, n) - i;vt[b[i]].pop_back();update(cur, 1);}printf("%lld\n", ans);return 0; }總結
以上是生活随笔為你收集整理的C - Swaps 2(树状数组,思维)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宝宝36度正常吗
- 下一篇: F. Strange Array(Cod