Frosh Week (hdu 3743 树状数组)

Frosh Week

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)

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
 

//题意:把一群人排成一队(无序),每个人都有个学号,现在相邻两个学生可以交换,问最少要交换多少次,这个队伍可以变成按学号从小到大排列的。

//思路:用一个结构体,记录每个人一开始的位置和学号。然后按学号顺序排序,得到每个人排序好后的位置。然后用树状数组求逆序数。


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
using namespace std;

typedef struct {
	int id;
	int num;
}Peo;

const int MAX = 1000100;

int n;
int c[MAX];
Peo s[MAX];

bool cmp(Peo p, Peo q)
{
	return p.num < q.num;
}

int lowbit(int x)
{
	return x&(-x);
}

void add(int k, int x)
{
	while (k <= n)
	{
		c[k] += x;
		k += lowbit(k);
	}
}

int sum(int x)
{
	int sum = 0;
	while (x > 0)
	{
		sum += c[x];
		x -= lowbit(x);
	}
	return sum;
}

int main()
{
	int i;
	while (scanf("%d", &n) != EOF)
	{
		memset(s, 0, sizeof(s));
		memset(c, 0, sizeof(c));
		for (i = 1; i <= n; i++)
		{
			scanf("%I64d", &s[i].num);
			//用id标记这个人原来的位置
			s[i].id = i;
		}

		//根据学号从小到大排序
		sort(s + 1, s + n + 1, cmp);

		//ans值会大于int,要用__int64或long long 
		__int64 ans = 0;
		for (i = 1; i <= n; i++)
		{
			//每次只能和相邻的人交换,只能移动一格
			add(s[i].id, 1);
			ans += i - sum(s[i].id);
		}
		printf("%I64d\n", ans);
	}
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值