P1966 [NOIP2013 提高组] 火柴排队(树状数组求逆序对)

P1966 [NOIP2013 提高组] 火柴排队icon-default.png?t=M276https://www.luogu.com.cn/problem/P1966在学完树状数组之后写这一题还是感悟很多的,首先根据题意我们可以想到要想两列相对火柴距离最短就必须a序列中第k大元素与b序列中第k大元素一一对应,但我们一开始得到的序列就是题目给出的顺序,不能保证第k大元素一一对应,所以我们就需要交换相邻元素让它一一对应,当然我就只需要交换一个序列的元素就够了 。

在第一次写这道题的时候war了,在翻看题解的时候离散化a与b的映射这一点我很难理解,但我思索后可以发现我们只需要直接找到我们目标所需的映射,不用从最开始的序列逐步交换得出,离散化后直接将a,b数组一一对应即可得出目标的映射关系,就转变成逆过来求将目标序列变成升序序列的问题,这个时候我们就可以用树状数组求逆序对来计算最小交换次数,本人文笔不好可能词不达意,但希望大家能理解到我的意思。

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
#include <cstdlib>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000010;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))

int tree[MAXN];
int n;
const int mod = 99999997;
struct node {
	int id, val;
};
node a[MAXN];
node b[MAXN];
int e[MAXN];

inline bool cmp(node a, node b) {
	if (a.val == b.val) {
		return a.id < b.id;
	}
	return a.val < b.val;
}

inline void update(int pos, int x) {
	for (; pos <= n; pos += lowbit(pos)) {
		tree[pos] += x;
	}
}

inline int query(int pos) {
	int rec = 0;
	for (; pos; pos -= lowbit(pos)) {
		rec += tree[pos];
	}
	return rec;
}


int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i].val);
		a[i].id = i;
	}
	for (int i = 1; i <= n; i++) {
		scanf("%d", &b[i].val);
		b[i].id = i;
	}
	sort(a + 1, a + n + 1, cmp);
	sort(b + 1, b + n + 1, cmp);
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		e[a[i].id] = b[i].id;
	}
	for (int i = 1; i <= n; i++) {
		update(e[i], 1);
		ans = (ans + i - query(e[i])) % mod;
	}
	printf("%d", ans);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值