HDU 4455 Substrings

来源:互联网 发布:借钱软件哪个能借到钱 编辑:程序博客网 时间:2024/05/16 04:12

首先,我们来看:

{1}   {2}  {3}

{1, 2} {2, 3}

{1,  2,  3}

后面一个可以看成把前面一个的最后一个子串去掉, 然后在每第 i 个子串里面添加第 i + w - 1 个数

[w, n]区间内的数都按顺序添加到了第1...n-w+1个子串后面。

对第 i  个数,他被添加到了以 a[ i - w +1 ]开始的子串中,如果 l[i] < i - w + 1  , 其中 l[i] 是他左边第一个和他相同的数,那么他会使答案 + 1 。

记 cnt[i] = i - l[i] ,

dp[i] = dp[i - 1] + ( [ i, n] 中多少 cnt[i]>=w ) - [n-w+2, n] 区间中多少不同的数

Substrings

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1875    Accepted Submission(s): 575


Problem Description
XXX has an array of length n. XXX wants to know that, for a given w, what is the sum of the distinct elements’ number in all substrings of length w. For example, the array is { 1 1 2 3 4 4 5 } When w = 3, there are five substrings of length 3. They are (1,1,2),(1,2,3),(2,3,4),(3,4,4),(4,4,5)
The distinct elements’ number of those five substrings are 2,3,3,2,2.
So the sum of the distinct elements’ number should be 2+3+3+2+2 = 12
 

Input
There are several test cases.
Each test case starts with a positive integer n, the array length. The next line consists of n integers a1,a2…an, representing the elements of the array.
Then there is a line with an integer Q, the number of queries. At last Q lines follow, each contains one integer w, the substring length of query. The input data ends with n = 0 For all cases, 0<w<=n<=106, 0<=Q<=104, 0<= a1,a2…an <=106
 

Output
For each test case, your program should output exactly Q lines, the sum of the distinct number in all substrings of length w for each query.
 

Sample Input
71 1 2 3 4 4 531230
 

Sample Output
71012
 

Source
2012 Asia Hangzhou Regional Contest
 

int low(int i) { return  i&-i; }int get(int i){    int ret = 0;    for(;i>0;i-=low(i)) ret += tree[i];    return ret;}void add(int i, int x){    for(;i<N;i+=low(i)) tree[i] += x;}int main(){    while(scanf("%d", &n)==1 && n)    {        memset(last, 0, sizeof last);        memset(tree, 0 , sizeof tree);        for(int i=1;i<=n;i++)        {            scanf("%d", a+i);            cnt[i] = i - last[a[i]];            add(cnt[i], 1);            last[a[i]] = i;                 }            dp[1] = n;        memset(vis, 0, sizeof vis);        int sz = 0;        for(int i=2;i<=n;i++)        {            if(!vis[a[n-i+2]]) sz++;            vis[a[n-i+2]] = true;            add(cnt[i-1], -1);            dp[i] = dp[i-1] + (n - i + 1 - get(i-1) ) - sz;        }        scanf("%d", &Q);        for(int i=0;i<Q;i++)        {            int w; scanf("%d", &w);            printf("%I64d\n", dp[w]);        }    }}


0 0
原创粉丝点击