E. Jeff and Permutation

这篇博客探讨了一种优化策略,针对给定序列,通过将元素按绝对值排序并应用贪心策略来确定最小逆序数。博主分析了问题的性质,指出绝对值大的元素对结果的影响仅取决于绝对值较小的元素。通过实现和优化算法,最终求得了序列的最小逆序数。代码示例中展示了如何利用位操作和前缀和技巧提高效率。

题意:
市赛的题的弱化版,给定一个序列,你可以把任何数取-要么取+,问最小逆序数。
思路:
发现到这个题的性质,绝对值大的贡献只决定于绝对值小的,那么按照绝对值排序贪心即可,取左边贡献和右边贡献的min就行了。
代码:

// Problem: E. Jeff and Permutation
// Contest: Codeforces - Codeforces Round #204 (Div. 1)
// URL: https://codeforces.com/contest/351/problem/E
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
#define IL inline
#define x first
#define y second
typedef long long ll;
using namespace std;
const int N=1000010;
int tr[N];
	int n;
int lowbit(int x)
{
	return x&-x;
}A
void add(int a,int b)
{
	for(int i=a;i<=n;i+=lowbit(i))
		tr[i]+=b;
}
int a[N];
int query(int x)
{
	int res=0;
	for(int i=x;i;i-=lowbit(i))
		res+=tr[i];
		return res;
}
struct node{
	int x;
	int pos;
	bool operator<(const node&w)const
	{
		if(x!=w.x)
		return x<w.x;
		return pos<w.pos;
	}
};
vector<node>v;
int cnt[N];
int main()
{

	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		a[i]=abs(a[i]);
		v.push_back({a[i],i});
	}
	sort(v.begin(),v.end());
	long long res=0;
	for(int i=0;i<v.size();i++)
	{
		int x=v[i].x;
		int pos=v[i].pos;
		int l=query(pos-1);
		int r=query(n)-query(pos);
		l-=cnt[x];
		cnt[x]++;
		//cout<<l<<" "<<r<<endl;
		res+=min(l,r);
		add(pos,1);
	}
	cout<<res<<endl;
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值