题目链接:hdu Minimum Inversion Number
题目大意:给定一个序列,求该序列所有的循环序列中,逆序对数的最小值。
解题思路:先预处理出原先序列的逆序对数,然后后面的循环序列都可以用o(1)的复杂度递推得到。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 5005;
#define lowbit(x) ((x)&(-x))
int N, arr[maxn], fenw[maxn];
void add (int x, int v) {
while (x <= N) {
fenw[x] += v;
x += lowbit(x);
}
}
int sum(int x) {
int ret = 0;
while (x) {
ret += fenw[x];
x -= lowbit(x);
}
return ret;
}
int main () {
while (scanf("%d", &N) == 1) {
for (int i = 0; i < N; i++)
scanf("%d", &arr[i]);
memset(fenw, 0, sizeof(fenw));
int s = 0;
for (int i = N - 1; i >= 0; i--) {
s += sum(arr[i] + 1);
add(arr[i] + 1, 1);
}
int ans = s;
for (int i = 0; i < N; i++) {
s = s + N - arr[i] * 2 - 1;
ans = min(s, ans);
}
printf("%d\n", ans);
}
return 0;
}
分享到:
相关推荐
next[i]的含义是在str[i]之前的字符串str[0...i]中,必须以str[i-1]结尾的后缀子串(不能包含str[0])与必须以str[0]开头的前
HDU-1711 Number Sequence(KMP算法)For each test case, you should output one line wh
HDU的1250,主要是利用高精度加法,但是代码有点繁琐,效率不是很高
HDU1059的代码
杭电ACMhdu1163
hdu1001解题报告
hdu 1574 passed sorce
HDU的一题........HDU DP动态规
hdu acm 教案 搜索入门 hdu acm 教案 搜索入门
hdu2101AC代码
搜索 dfs 解题代码 hdu1241
hdu acm 教案 动态规划(1) hdu acm 教案 动态规划(1)
hdu 5007 Post Robot 字符串枚举。 暴力一下就可以了。
ACM HDU题目分类,我自己总结的大概只有十来个吧
HDU最全ac代码
hdu 1166线段树代码
hdu动态规划算法集锦
hdu题目分类
自己做的HDU ACM已经AC的题目
hdu-acm源代码(上百题)hdu-acm源代码、hdu-acm源代码hdu-acm源代码