hdu 3743 Frosh Week(离散化+树状数组)
Frosh Week
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 289 Accepted Submission(s): 72
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
此题大意:与上题一样,求逆序数,不要给英文骗到。我想练下写离散化,所以再写一次,印象更深刻。
代码:
Cpp代码
#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <algorithm>
using namespace std;
int n, a[1000005];
struct node
{
int num, id;
}ch[1000005];
bool cmp1(node a, node b)
{
return a.num < b.num;
}
bool cmp2(node a, node b)
{
return a.id < b.id;
}
int lowbit(int i)
{
return i&(-i);
}
void update(int i, int x)
{
while(i <= n)
{
a[i] += x;
i += lowbit(i);
}
}
int sum(int i)
{
int sum = 0;
while(i > 0)
{
sum += a[i];
i -= lowbit(i);
}
return sum;
}
int main()
{
int i;
long long ans; //注意要long long!!!
while(scanf("%d", &n) != EOF)
{
ans = 0;
memset(a, 0, sizeof(a));
for(i = 1; i <= n; i++)
{
scanf("%d", &ch[i].num);
ch[i].id = i;
}
///离散化
sort(ch+1, ch+n+1, cmp1); //按值排序
ch[1].num = 1; //直接把他的值改变离散化
for(i = 2; i <= n; i++)
{
if(ch[i].num != ch[i-1].num)
ch[i].num = i;
else ch[i].num = ch[i-1].num;
}
sort(ch+1, ch+n+1, cmp2); //再按id排序
///离散化完毕
for(i = 1; i <= n; i++)
{
update(ch[i].num, 1);
ans += (sum(n) - sum(ch[i].num));
}
printf("%I64d\n", ans);
}
return 0;
}
补充:软件开发 , C语言 ,