CodeForces 1883F You Are So Beautiful

题目链接:CodeForces 1883F【You Are So Beautiful】



思路

       要找出一个子数组使得在数组中只能找出一个子序列和当前子数组相等,则只需要找出首元素的数字必须为当前元素值第一次出现,尾元素的数字必须为当前元素值最后一次出现,则只能找出唯一的子序列和当前子数组相等。所以从前往后遍历,记录每个元素值第一次出现和最后一次出现的位置,然后逐个遍历遇到第一次出现的元素值时可以找出的子数组又多了一个,所以计数变量加1,直到遍历至最后一次出现的元素就将前面的第一次出现的元素个数加到结果上,此时这些加到结果上的子数组都满足首元素值是第一次出现,尾元素值是最后一次出现。


代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;

const int N = 1e6 + 10;
const double eps = 1e-8;

int n,k;
int  a[N];

void solve() {
  cin >> n;
  for (int i = 0; i < n; i++)
    cin >> a[i];

  ll ans = 0;
  map<int, int> first, end, cnt;

  for (int i = 0; i < n; i++) {
    if (cnt[a[i]] == 0) {
      cnt[a[i]]++;
      first[a[i]] = i;
      end[a[i]] = i;
    } else {
      end[a[i]] = i;
    }
  }

  int sum = 0;

  for (int i = 0; i < n; i++) {
    if (first[a[i]] == i)
      sum++;
    if (end[a[i]] == i)
      ans += sum;
  }

  cout << ans << endl;
}

int main() {
  int t;
  cin >> t;
  while (t--)
    solve();
  return 0;
}
posted @ 2024-07-28 16:44  薛定谔的AC  阅读(11)  评论(0编辑  收藏  举报