hdu 4455 Substrings(樹狀數組+遞推),hdusubstrings

來源:互聯網
上載者:User

hdu 4455 Substrings(樹狀數組+遞推),hdusubstrings

題目連結:hdu 4455 Substrings

題目大意:給定一個長度為N的序列,現在有Q次詢問,每次給定一個w,表示長度,輸出序列中長度為w的連續子序列

的權值和。序列的權值表示序列中不同元素的個數。

解題思路:遞推,先預先處理處每個位置和前面相同的資料的最短距離P。dp[i]表示說長度為i子序列的權值和,dp[i+1] = 

dp[i] + v - c。v為[i+1~N]中P值大於i的個數,我們可以看作將長度為i的子序列長度向後增加1,那麼v則為增加長度帶來

的權值增加值,c則是最後一個長度為i的序列,因為它不能再增加長度,可是長度又不夠,所以只能扣除掉。在遞推的

過程中維護c即可,對於P可以用樹狀數組最佳化。

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 1e6;int N, A[maxn + 5], P[maxn + 5], T[maxn + 5], fenw[maxn + 5];ll dp[maxn + 5];#define lowbit(x) ((x)&(-x))void add (int x, int d) {    while (x <= maxn) {        fenw[x] += d;        x += lowbit(x);    }}int sum(int x) {    int ret = 0;    while (x) {        ret += fenw[x];        x -= lowbit(x);    }    return ret;}void init () {    int x;    memset(T, -1, sizeof(T));    memset(fenw, 0, sizeof(fenw));    for (int i = 1; i <= N; i++) {        scanf("%d", &x);        A[i] = x;        if (T[x] == -1)            P[i] = N;        else            P[i] = i - T[x];        T[x] = i;        add(P[i], 1);    }}void solve() {    memset(T, 0, sizeof(T));    int c = 1;    dp[1] = N;    T[A[N]] = 1;    for (int i = 2; i <= N; i++) {        add(P[i-1], -1);        int v = sum(maxn) - sum(i-1);        dp[i] = dp[i-1] + v - c;        if (T[A[N-i+1]] == 0) {            T[A[N-i+1]] = 1;            c++;        }    }}int main () {    while (scanf("%d", &N) == 1 && N) {        init();        solve();        int Q, x;        scanf("%d", &Q);        while (Q--) {            scanf("%d", &x);            printf("%I64d\n", dp[x]);        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.