P9310
zhongpeilin · · 题解
题目大意:
有
1.消除两个相邻且相同的数。
2.交换两个相邻的数。
问最小操作数?
解题思路:
首先一定是先让他们互相靠近,然后才能消。
然后通过分析不难发现:最小的操作一定是将互相包含的几对数中先将被包含的两个数先消掉,然后再消掉外面的,因为这样就可以让外面的少移动两步。
那么我们可以将两个相同的数看作一段区间,然后再按左端点从大到小排序,然后一个一个区间处理即可。
但是怎么维护一个数前面有多少个还未删除的数来确定现在的位置?
这里可以拿个树状数组来维护,类似后缀加。
至于区间嘛,我们可以不用离线下来,直接从前往后扫,遇到一个之前没有遇到的
时间复杂度:
#include <bits/stdc++.h>
using namespace std;
int read(){
int x = 0;
char op = getchar();
while(op < '0' || op > '9') op = getchar();
while(op >= '0'&& op <= '9'){
x = x * 10 + (op - '0');
op = getchar();
}
return x;
}
int C[1000005], cnt;
int pre[1000005], suf[1000005];
int n, a[1000005], b[1000005];
int ask(int x){
int ans = 0;
for(int i = x; i > 0; i -= (i & (-i))) ans += C[i];
return ans;
}
void add(int x, int c){//树状数组
for(int i = x; i <= n; i += (i & (-i))) C[i] += c;
}
int main() {
n = read();
n *= 2;
for(int i = 1; i <= n; i++) a[i] = read();
for(int i = 1; i <= n; i++){
if(b[a[i]] == 0) b[a[i]] = ++cnt; //之前没遇到,给a[i]的值标个号
a[i] = b[a[i]]; //更新一下
if(pre[a[i]] == 0) pre[a[i]] = i; //表示值为a[i]的第一个数位置在哪
else suf[a[i]] = i;//表示值为a[i]的第二个数位置在哪
}
for(int i = 1; i <= n; i++) add(i, 1); //树状数组初始化一下
long long ans = 0;
for(int i = n / 2; i >= 1; i--){ //从大到小枚举
ans += ask(suf[i]) - ask(pre[i]); //算距离,表示将他俩扔出最小代价。
add(pre[i], -1), add(suf[i], -1); //少了pre[i]和suf[i]
}
cout << ans << endl; //答案
return 0;
}
创作不易,给个赞吧 QWQ!