[蓝桥杯 2014 省 B] 小朋友排队
题目描述
n n n 个小朋友站成一排。现在要把他们按身高从低到高的顺序排列,但是每次只能交换位置相邻的两个小朋友。
每个小朋友都有一个不高兴的程度。开始的时候,所有小朋友的不高兴程度都是 0 0 0。
如果某个小朋友第一次被要求交换,则他的不高兴程度增加 1 1 1,如果第二次要求他交换,则他的不高兴程度增加 2 2 2(即不高兴程度为 3 3 3),依次类推。当要求某个小朋友第 k k k 次交换时,他的不高兴程度增加 k k k。
请问,要让所有小朋友按从低到高排队,他们的不高兴程度之和最小是多少。
如果有两个小朋友身高一样,则他们谁站在谁前面是没有关系的。
输入格式
输入的第一行包含一个整数 n n n,表示小朋友的个数。
第二行包含 n n n 个整数 H 1 , H 2 ⋯ H n H_1,H_2 \cdots H_n H1,H2⋯Hn,分别表示每个小朋友的身高。
输出格式
输出一行,包含一个整数,表示小朋友的不高兴程度和的最小值。
样例 #1
样例输入 #1
3
3 2 1
样例输出 #1
9
提示
【样例说明】
首先交换身高为 3 3 3 和 2 2 2 的小朋友,再交换身高为 3 3 3 和 1 1 1 的小朋友,再交换身高为 2 2 2 和 1 1 1 的小朋友,每个小朋友的不高兴程度都是 3 3 3,总和为 9 9 9。
【数据规模与约定】
对于 10 % 10\% 10% 的数据, 1 ≤ n ≤ 10 1 \le n \le 10 1≤n≤10;
对于 30 % 30\% 30% 的数据, 1 ≤ n ≤ 1000 1 \le n \le 1000 1≤n≤1000;
对于 50 % 50\% 50% 的数据, 1 ≤ n ≤ 10000 1 \le n \le 10000 1≤n≤10000;
对于 100 % 100\% 100% 的数据, 1 ≤ n ≤ 100000 1 \le n \le 100000 1≤n≤100000, 0 ≤ H i ≤ 1000000 0 \le H_i \le 1000000 0≤Hi≤1000000。
时限 1 秒, 256M。蓝桥杯 2014 年第五届省赛
AC代码:
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<queue>
#include<string>
#include<bitset>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<numeric>
#include<iomanip>
#define endl '\n'
//#define x first
//#define y second
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
const int N=3e5+10;
const int MOD=1e9 + 7;
const int INF=0X3F3F3F3F;
const int dx[]={-1,1,0,0,-1,-1,+1,+1};
const int dy[]={0,0,-1,1,-1,+1,-1,+1};
const int M = 1e6 + 10;
int a[M];
int tree[M];
int n;
int b[M];
int bit(int x)
{
return x & -x;
}
void add(int x, int y)
{
while(x < M)//因为x代表的为a[i]值, 因此这里应该小于M
{
tree[x] += y;
x += bit(x);
}
}
int q(int x)
{
int res = 0;
while(x){
res += tree[x];
x -= bit(x);
}
return res;
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++)
{
cin >> a[i];
a[i] ++;// 消除0
}
for(int i = 1; i <= n; i ++)
{
add(a[i], 1);
b[i] = i - q(a[i]);//找到左边比那个人大的数个数
}
memset(tree, 0, sizeof tree);
for(int i = n; i >= 1; i --)
{
add(a[i], 1);
b[i] += q(a[i] - 1);//找到右边比那个人小的数的个数
}
// for(int i = 1; i <= n; i ++)
// {
// cout << tree[i] << endl;
// }
ll res = 0;
for(int i = 1; i <= n; i ++)
{
res += (ll)(b[i] + 1) * b[i] / 2;
}
cout << res << endl;
return 0;
}