Skip to content

Commit c947ab6

Browse files
committed
Creating Hashing Directory with one problem
1 parent 193ac59 commit c947ab6

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Hashing/sequence_pair_weight.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Problem Link - https://codeforces.com/contest/1527/problem/C
3+
4+
Problem Statement - The weight of a sequence is defined as the number of unordered pairs of indexes (i,j)
5+
(here i<j) with same value (ai=aj). For example, the weight of sequence a=[1,1,2,2,1] is 4. The set of unordered pairs of indexes with same value are (1,2), (1,5), (2,5), and (3,4).
6+
7+
You are given a sequence a of n integers. Print the sum of the weight of all subsegments of a.
8+
A sequence b is a subsegment of a sequence a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
9+
10+
*/
11+
12+
#include<bits/stdc++.h>
13+
#define int long long
14+
15+
using namespace std;
16+
17+
void solve(int n, vector<int> v){
18+
int ans = 0;
19+
map<int, int> toLeft;
20+
for(int i=1; i<=n; i++){
21+
if(toLeft[v[i]] != 0){
22+
int toRight = n-i+1;
23+
ans += toRight*toLeft[v[i]];
24+
}
25+
toLeft[v[i]] += i;
26+
}
27+
cout<<ans<<"\n";
28+
}
29+
30+
signed main(){
31+
ios::sync_with_stdio(false);cin.tie(0);
32+
int t = 1;
33+
cin >> t;
34+
for(int i=1; i<=t; i++){
35+
int n;
36+
cin>>n;
37+
vector<int> v(n+1);
38+
for(int j=1; j<=n; j++){
39+
cin>>v[j];
40+
}
41+
solve(n,v);
42+
}
43+
return 0;
44+
}
45+
46+
// Tutorial Link to understand the solution - https://codeforces.com/blog/entry/90939

0 commit comments

Comments
 (0)