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
University of Waterloo Local Contest 2010.10.02
 

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;
}

你可能感兴趣的:(数据结构,线段树)