HDU 4455 Substrings(DP)

101 篇文章 0 订阅
86 篇文章 0 订阅

题目链接:点击打开链接

思路:

我们用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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值