CF1223F. Stack Exterminable Arrays
Solution
奇怪的套路增加了。
大概就是 [ l , r ] [l,r] [l,r]能匹配完可以转化为 [ 1 , l − 1 ] [1,l-1] [1,l−1]匹配后的状态和 [ 1 , r ] [1,r] [1,r]匹配后的状态相同,因此 h a s h hash hash判断即可。
Code
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <cassert>
#include <string.h>
//#include <unordered_set>
//#include <unordered_map>
//#include <bits/stdc++.h>
#define MP(A,B) make_pair(A,B)
#define PB(A) push_back(A)
#define SIZE(A) ((int)A.size())
#define LEN(A) ((int)A.length())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define fi first
#define se second
using namespace std;
template<typename T>inline bool upmin(T &x,T y) { return y<x?x=y,1:0; }
template<typename T>inline bool upmax(T &x,T y) { return x<y?x=y,1:0; }
typedef long long ll;
typedef unsigned long long ull;
typedef long double lod;
typedef pair<int,int> PR;
typedef vector<int> VI;
const lod eps=1e-11;
const lod pi=acos(-1);
const int oo=1<<30;
const ll loo=1ll<<62;
const int mods=1e9+9;
const int MAXN=1000005;
const int INF=0x3f3f3f3f;//1061109567
/*--------------------------------------------------------------------*/
inline int read()
{
int f=1,x=0; char c=getchar();
while (c<'0'||c>'9') { if (c=='-') f=-1; c=getchar(); }
while (c>='0'&&c<='9') { x=(x<<3)+(x<<1)+(c^48); c=getchar(); }
return x*f;
}
ull h[MAXN];
map<ull,int> Map;
int a[MAXN],f[MAXN],stk[MAXN],SZ=1e9+7;
signed main()
{
int Case=read();
while (Case--)
{
ll ans=0;
int n=read(),top=0;
for (int i=1;i<=n;i++) a[i]=read(),f[i]=0;
Map.clear(),Map[0]=n+1,f[n+1]=0;
for (int i=n;i>=1;i--)
{
if (top&&stk[top]==a[i]) top--;
else stk[++top]=a[i],h[top]=h[top-1]*SZ+a[i];
if (Map[h[top]]) f[i]=f[Map[h[top]]]+1;
Map[h[top]]=i;
ans+=f[i];
}
printf("%lld\n",ans);
}
return 0;
}