暑假集训(2)第六弹 ----- Frosh Week(UVA11858)

时间:2024-11-23 15:33:38
H - Frosh Week

Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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 "cstdio"

 int num[];
int T[];
__int64 sum;
void mset(int n)
{
for (int i=;i<=n;i++)
scanf ("%d",&num[i]);
}
void px(int x,int y)
{
if (y-x > )
{
int m = x + (y-x)/;
int p = x,q = m,i = x;
px(x,m);
px(m,y);
while (p < m || q < y)
{
if (q >= y || (p < m && num[p] <= num[q]))
T[i++] = num[p++];
else
{
T[i++] = num[q++];
sum += m-p;
}
}
for (i=x;i<y;i++)
num[i] = T[i];
}
}
int main()
{
int n;
while (~scanf ("%d",&n))
{
sum=;
mset(n);
px(,n+);
for (int i=;i<=n;i++)
printf ("%d ",num[i]);
printf ("%I64d\n",sum);
} return ;
}