Codeforces 645B Mischievous Mess Makers【逆序数】

题目链接:

http://codeforces.com/problemset/problem/645/B

题意:

给定步数和排列,每步可以交换两个数,问最后逆序数最多是多少对?

分析:

看例子就能看出来肯定是不断往中间逼近,然后交换头尾两个,给定交换的对数,直接算就好了,复杂度O(1)

代码:

#include<iostream>
using namespace std;
typedef long long ll;
int main (void)
{
    ll n, m;
    cin>>n>>m;

    ll res = 0;
    ll ans = min(n/2, m);
    res = (n  - 1+ (n - ans + 1))/ 2 * ans + (n - 2 * ans + n - ans - 1)/2 * ans;
    cout<<res<<endl;

    return 0;
}

智商压制
直接用所有对数减去为改变的对数就好了嘛

#include<iostream>
using namespace std;
int main (void)
{
    long long n, m;
    cin>>n>>m;
    long long res = max(n - 2 * m, 0ll);
    long long ans = n * (n - 1)/2 - res * (res - 1) / 2;
    cout<<ans<<endl;

    return 0;
}

然后求逆序数的经典方法就是树状数组了,这里写下,时间复杂度O(nlogn)

#include<iostream>
using namespace std;
typedef long long ll;
const int maxn = 400020;
int bit[maxn], a[maxn];
int n, m;
int sum(int i)
{
    int s = 0;
    while(i){
        s += bit[i];
        i -= i & -i;
    }
    return s;
}
void add(int i, int x)
{
    while(i <= n){
        bit[i] += x;
        i += i & -i;
    }
}
int main (void)
{
    cin>>n>>m;
    if(m >= n / 2){
        cout<<(ll) n * (n - 1)/2<<endl;
        return 0;
    }
    for(int i = 1; i <= n; i++) a[i] = i;
    for(int i = 1; i <= m; i++) swap(a[i], a[n - i + 1]);
    ll res = 0;
    for(int i = 1; i <= n; i++){
        add(a[i], 1);
        res +=i - sum(a[i]);

    }
    cout<<res<<endl;
}

转载于:https://www.cnblogs.com/Tuesdayzz/p/5758724.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值