hdu 7108 Command Sequence 分析: 前缀和维护两个方向上的的坐标考虑能回到同一个点,则两个方向上的前缀和的值是相同的哈希一下,判断有多少相同的前缀和,再计算相加即可 #include <bits/stdc++.h> #define int long long using namespace std; const int N=1e6+5; char s[N]; int g[N][3]; pair <int,int> P; map <pair <int,int>,int> mp; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T; cin>>T; while(T--) { int n; cin>>n; cin>>s+1; mp.clear(); P=make_pair(0,0); // 初始位置 mp[P]++; for(int i=1;i<=n;i++) { g[i][0]=g[i-1][0]; g[i][1]=g[i-1][1]; if(s[i]=='U') g[i][0]++; if(s[i]=='D') g[i][0]--; if(s[i]=='L') g[i][1]--; if(s[i]=='R') g[i][1]++; P=make_pair(g[i][0],g[i][1]); mp[P]++; } int ans=0; for(int i=1;i<=n;i++) { P=make_pair(g[i][0],g[i][1]); int t=mp[P]; mp[P]=0; ans+=t*(t-1)/2; } cout<<ans<<endl; } return 0; }