题目链接:点击打开链接
思路:
我们用d[i]表示长度为i的答案。 那么我们可以把样例数据写出来看看是否能够递推。 可以发现, d[i] = d[i-1] - last[i-1] + (n-i+1) - dist[i]。
last[i]表示从后往前i长度时不同数字的个数, 也就是说, d[i-1]的最后一个子序列被扔了, 然后d[i]比d[i-1]还可能多加了( n - i + 1), 然后我们把不符合要求的减掉。 比赛时自己推出来的, 说不很清楚, 建议自己推一下。
细节参见代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 1e6+5;
int T,n,m,R,a[maxn],last[maxn],dist[maxn], q, x, p[maxn];
ll d[maxn];
bool hehe[maxn];
int main() {
while(~scanf("%d", &n) && n) {
memset(d, 0, sizeof(d));
memset(hehe, 0, sizeof(hehe));
memset(dist, 0, sizeof(dist));
d[1] = n;
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
int cnt = 1;
memset(p, 0, sizeof(p));
for(int i = n; i >= 1; i--) {
if(p[a[i]]) last[cnt] = last[cnt-1];
else {
p[a[i]] = 1;
last[cnt] = last[cnt-1] + 1;
}
cnt++;
}
memset(p, 0, sizeof(p));
for(int i = 1; i <= n; i++) {
if(p[a[i]]) {
dist[i-p[a[i]]+1]++;
hehe[i] = 1;
p[a[i]] = i;
}
else p[a[i]] = i;
}
for(int i = 1; i <= n; i++) {
if(hehe[i-1]) dist[i] += dist[i-1] - 1;
else dist[i] += dist[i-1];
}
for(int i = 2; i <= n; i++) {
d[i] = d[i-1] - (ll)last[i-1] + (ll)(n - i + 1) - (ll)dist[i];
}
scanf("%d", &q);
while(q--) {
scanf("%d", &x);
printf("%I64d\n", d[x]);
}
}
return 0;
}