http://codeforces.com/contest/362
题目大意:给你一个序列,用冒泡排序法让他变为非递减的序列最少需要几次。在冒泡交换之间,你有一个swap操作,该swap操作是交换任意两个数组元素的位置,问在该操作后,所再需要的冒泡交换次数是多少,并输出方案数
思路:树状数组维护一下区间序列,知道该区间内比他大的有几个就行了。然后暴力。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
//看看会不会爆int!数组会不会少了一维! //取物问题一定要小心先手胜利的条件 #include <bits/stdc++.h> using namespace std; #define LL long long #define ALL(a) a.begin(), a.end() #define pb push_back #define mk make_pair #define fi first #define se second const int maxn = 5000 + 5; int tree[maxn], a[maxn]; int big[maxn][maxn], big2[maxn][maxn]; int n; int lowbit(int x) {return x & -x;} int sum(int x){ int ans = 0; for (int i = x; i > 0; i -= lowbit(i)){ ans += tree[i]; } return ans; } void add(int x, int val){ for (int i = x; i <= n; i += lowbit(i)){ tree[i] += val; } } int main(){ scanf("%d", &n); for (int i = 1; i <= n; i++) { int u; scanf("%d", &u); u++; a[i] = u; } int tot = 0; for (int i = n; i >= 1; i--){ tot += sum(a[i]); add(a[i], 1); } ///l->r的区间 ///区间内比他大的 for (int i = n; i > 0; i--){ memset(tree, 0, sizeof(tree)); for (int j = n; j >= i;j--){///都取不到边界 if (a[j] > a[i]) add(a[j], 1); big[i][j] = sum(n) - sum(a[i] - 1); } } ///r->l的区间 ///区间内比他大的 for (int i = 1; i <= n; i++){ memset(tree, 0, sizeof(tree)); for (int j = 1; j <= i; j++){ if (a[j] > a[i]) add(a[j], 1); big2[i][j] = sum(n) - sum(a[i] - 1); } } int mintot = tot; int cnt = 0; for (int i = 1; i <= n; i++){///left for (int j = i + 1; j <= n; j++){///right if (a[i] < a[j]) continue; int t1 = 2 * (big[i][i + 1] - big[i][j]) - (j - (i + 1)); int t2 = j - (i + 1) - 2 * (big2[j][j - 1] - big2[j][i]); int tmp = tot + t1 + t2 - 1; if (tmp < mintot) cnt = 1, mintot = tmp; else if (tmp == mintot) cnt++; } } printf("%d %d\n", mintot, cnt); return 0; }