J - Pashmak and Parmida's problem CodeForces - 459D(思维优化+树状数组)

J - Pashmak and Parmida’s problem CodeForces - 459D
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he’s not)! Parmida has prepared the following test problem for Pashmak.

There is a sequence a that consists of n integers a1, a2, …, an. Let’s denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, ai) > f(j, n, aj).

Help Pashmak with the test.

Input
The first line of the input contains an integer n (1 ≤ n ≤ 106). The second line contains n space-separated integers a1, a2, …, an (1 ≤ ai ≤ 109).

Output
Print a single integer — the answer to the problem.

Example
Input
7
1 2 1 1 2 2 1
Output
8
Input
3
1 1 1
Output
1
Input
5
1 2 3 4 5
Output
0
题目大意:定义一个函数f(n,m,a【m】)返回值为下标从n-m的数组a中与a【m】值相同的数的个数题目中是要找出 f(1, i, ai) > f(j, n, aj)的i,j的对数
解题思路:n<=1e6很明显直接暴力会超时,这时想到用树状数组来存后缀既f(j,n,aj)这样算出前缀和后缀后前缀f(1,i,ai)与后缀比较为o(1)然后当前i,j对数的计算为o(logn)然后这样还是会超时=-=
需要对找f(1,i,ai)的过程进行优化想到可以借用前面的结果来优化
直接开下标为a【i】的数组会造成空间的巨大浪费所以想到借助c++stl中的map来存储。
ac代码

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int N=1e6+5;
int arr[N],fi[N],fj[N];
int n;
void add(int x)
{
    while(x<=n)
    {
        arr[x]++;
        x+=x&(-x);
    }
}
int sum(int x)
{
    int s=0;
    while(x>0)
    {
        s+=arr[x];
        x-=x&(-x);
    }
    return s;
}
int main()
{
    int i;
    map<int,int>mp;
    scanf("%d",&n);
    for(i=1;i<=n;i++)scanf("%d",&arr[i]);
    for(i=1;i<=n;i++)
    {
        fi[i]=++mp[arr[i]];
    }
    mp.clear();
    for(i=n;i>=1;i--)
    {
        fj[i]=++mp[arr[i]];
    }
        memset(arr,0,sizeof(arr));
    LL ans=0;
    for(i=n-1;i>=2;i--)
    {
        add(fj[i+1]);
        ans+=sum(fi[i]-1);
    }
    cout<<ans<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值