码迷,mamicode.com
首页 > 编程语言 > 详细

codeforce div2 C 树状数组

时间:2016-09-21 22:53:49      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

http://codeforces.com/contest/362

题目大意:给你一个序列,用冒泡排序法让他变为非递减的序列最少需要几次。在冒泡交换之间,你有一个swap操作,该swap操作是交换任意两个数组元素的位置,问在该操作后,所再需要的冒泡交换次数是多少,并输出方案数

思路:树状数组维护一下区间序列,知道该区间内比他大的有几个就行了。然后暴力。

 

技术分享
//看看会不会爆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;
}
View Code

 

codeforce div2 C 树状数组

标签:

原文地址:http://www.cnblogs.com/heimao5027/p/5894343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!