hdu3743(线段树+离散化)

Frosh Week

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1388    Accepted Submission(s): 441


Problem Description
During Frosh Week, students play various fun games to get to know each other and compete against other teams. In one such game, all the frosh on a team stand in a line, and are then asked to arrange themselves according to some criterion, such as their height, their birth date, or their student number. This rearrangement of the line must be accomplished only by successively swapping pairs of consecutive students. The team that finishes fastest wins. Thus, in order to win, you would like to minimize the number of swaps required.
 

Input
The first line of input contains one positive integer n, the number of students on the team, which will be no more than one million. The following n lines each contain one integer, the student number of each student on the team. No student number will appear more than once.
 

Output
Output a line containing the minimum number of swaps required to arrange the students in increasing order by student number.
 

Sample Input
  
  
3 3 1 2
 

Sample Output
  
  
2
 

Source
 

Recommend
lcy
         本题给定一个数n,然后给出n个数的序列,要求最少交换多少次可使原序列变成递增的。根据以往的经验,也就是求序列的逆序数的和。可用线段树破之。但本题有个陷阱,即原序列中的n个数并没说是从1到n的某个排列。对此我们可以先进行离散化。离散化在本题很简单,只需记录数在原序列中的下标,然后按数值从小到大排序。排序后的下表id对应该数在原数组中的相对大小,然后我们按从小到大的顺序插入,查询。
         线段树+离散化
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int MAXN=1000000+100;
struct node
{
	int num,id;
}Per[MAXN];
int C[MAXN];
int Lowbit[MAXN];
//C[i] = a[i-lowbit(i)+1] + …+ a[i],下表从1开始
//Lowbit[i]=i&(i^(i-1));或Lowbit[i]=i&(-i); 
//1.查询
int QuerySum(int p)
//查询原数组中下标1-p的元素的和 
{ 
   int nSum=0; 
   while(p>0) 
   {  
      nSum+=C[p]; 
      p-=Lowbit[p]; 
   } 
    return nSum; 
} 

//2.修改+初始化
void Modify(int p,int val) 
//原数组中下表为p的元素+val,导致C[]数组中部分元素值的改变
{ 
    while(p<=MAXN-10) 
   { 
      C[p]+=val; 
      p+=Lowbit[p]; 
    } 
} 
//************************************************************

bool cmp(node a,node b)
{
	return a.num<b.num;
}

int main()
{
	int n,i;
	__int64 ans;
	for(i=1;i<MAXN;i++)
		Lowbit[i]=i&(-i);
	while(~scanf("%d",&n))
	{
		for(i=1;i<=n;i++)
			//scanf("%d",&da[i]);
		{
			scanf("%d",&Per[i].num);
			Per[i].id=i;
		}
		memset(C,0,sizeof(C));
		ans=0;
		sort(Per+1,Per+n+1,cmp);
		for(i=1;i<=n;i++)
		{
			ans+=(__int64)QuerySum(n)-(__int64)QuerySum(Per[i].id);
			Modify(Per[i].id,1);
		}
		printf("%I64d\n",ans);
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值