Algorithms
- Greedy Algorithm
- Prefix Sum
The Problem
Given the sequence of length ,how many distinct triplets exist in such that , and forms a (not necessarily contiguous) subsequence of ?
Two triplets are considered different if any one of their elements differs.
Analysis
Since , only the numbers that appear at least twice in the sequence can be candidates for and in a valid triplet. We can identify such numbers by counting the frequency of each number in , and collect all numbers with frequency into a set .
Now, consider a greedy approach: For any , we can fix the last two occurrences of in as and . Then, any element before the second-to-last occurrence of can be used as (as long as it is different from ). Since we are forming a subsequence (not necessarily contiguous), this greedy choice ensures we account for all valid triplets involving . Therefore, this approach is correct.
Let be the index of the second-to-last occurrence of in , and be the index of the last occurrence. To compute the number of valid choices for , we need to know how many distinct elements occur in the range . This will give the number of valid satisfying .
To achieve this efficiently, we use a prefix sum array , where for each position , records the number of unique elements seen in . When we process the sequence from the beginning, for each number’s first occurrence, we increment the corresponding by . Then we can compute prefix sums cumulatively.
The contribution of each (labeled ) to the final answer is:
The part is designed to prevent that the occurrence of makes contribution to the result by mistake. For the instance below, if we do not minus , the value of will be wrong:
Eventually, for the answer (labeled ),we get:
Just output the with print statement.
Code
//C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int total;
cin >> total;
//Input the length of the sequence
vector<int> count (total, 0);
//Record the occurrence
vector<int> posiA (total, -1);
vector<int> posiB (total, -1);
//Record the indices of last two occurrence of a specific number
vector<int> a;
int prefixSum[1000020];
memset(prefixSum, 0, sizeof(prefixSum));
//Prefix Sum
for (int i = 0; i < total; i++) {
int input;
cin >> input;
count[input]++;
if (count[input] == 1) {
posiA[input] = i;
prefixSum[i] = 1;
} else if (count[input] == 2) {
posiB[input] = i;
a.push_back(input);
} else if (count[input] >= 3) {
posiA[input] = posiB[input];
posiB[input] = i;
}
}
for (int i = 1; i < total; i++) {
prefixSum[i] = prefixSum[i - 1] + prefixSum[i];
}
//Calculate for the Prefix Sum array
int ans(0);
for (int i : a) {
ans += prefixSum[posiA[i]] - 1;
}
//Solve for answer
cout << ans;
//Output
return 0;
}