原题地址:http://codeforces.com/contest/1004/problem/C
题意:给你n个数字,询问你有多少对
<ai,aj>(i<j)
<
a
i
,
a
j
>
(
i
<
j
)
<script type="math/tex" id="MathJax-Element-70">
(i
思路:我自己写了一个特别烦的方法,我是从前往后计数,然后发现更快的方法是从后往前计数的。
我的代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
ll a[maxn], n;
ll Count[maxn], ans, num, first[maxn];
vector<int>V[maxn];
int main() {
scanf("%I64d", &n);
memset(first, -1, sizeof(first));
for(int i = 1; i <= n; i++) {
scanf("%I64d", &a[i]);
V[a[i]].push_back(i);
if(first[a[i]] == -1) {
first[a[i]] = i;
Count[i] = num;
num++;
} else {
Count[i] = num;
}
}
vector<int>::iterator it;
for(int i = 1; i <= (int)1e5; i++) {
if(V[i].size() == 0) continue;
else {
ans += Count[V[i][0]];
for(it = V[i].begin() + 1; it != V[i].end(); it++) {
ans += Count[*it] - Count[*(it - 1)];
}
}
}
printf("%I64d\n", ans);
return 0;
}
正解:
#include <bits/stdc++.h>
using namespace std;
int a[100007],b[100007]; set<int> s;
int main() {
int n;cin>>n;
int i;
for(i=0;i<n;i++) cin>>a[i];
for(i=0;i<n;i++)
{
b[a[i]]=s.size();
s.insert(a[i]);
}
long long int sum=0;
for(i=0;i<100001;i++)
sum+=b[i];
cout<<sum;
return 0;
}