题目描述

There is a sequence with n integers, your task is finding there are how many consecutive subsequences have two characters:
1.The length of the subsequence is k.
2.Every number in this subsequence is different.

输入

The input contains multiple test cases.
The first line of each case contains two integers n and k (1≤k≤n≤200000). Then second line contains n positive integers a[i](1≤a[i]≤1000000000).

输出

For each case ,print the number of consecutive subsequences in the only line.

样例输入

10 3
1 2 3 4 3 2 1 1 2 2

样例输出

4

动态规划

设dp[i]是以第i个数字结尾的满足不重复数字的最长长度,则dp[i] = dp[i-1] + 1(a[i]未出现过),dp[i] = i - m[a[i]] (a[i]出现过,使用map容器储存上个a[i]的下标)

#include <cstdio>
#include <cctype>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <cmath>
using namespace std;
typedef long long LL;

LL n,k;
LL a[200005];
LL dp[200005] = {0};
map<LL,LL> m;

int main(){
  //freopen("test.in","r",stdin);
  while (scanf("%lld %lld",&n,&k) != EOF){
    m.clear();
    memset(dp,0,sizeof(dp));
    LL i,total = 0;
    for (i=1;i<=n;i++){
      scanf("%lld",&a[i]);
    }
    dp[1] = 1; m[a[1]] = 1;
    for (i=2;i<=n;i++){
      if (m[a[i]] == 0){
        dp[i] = dp[i-1]+1; m[a[i]] = i;
      }
      else {
        dp[i] = i - m[a[i]];
        // printf("%lld %lld\n",i,dp[i]);
        m.clear();
        for (int j=i,k=0;k<dp[i];k++){
          m[a[j-k]] = j-k;
        }
        if (i == 5){
          //printf("%lld\n",m[a[2]]);
        }
      }
    }
    //printf("%lld = k\n",k);
    for (i=k;i<=n;i++){
      if (dp[i] >= k) {
      //  printf("%lld\n",i);
        total ++;
      }
    }
    printf("%lld\n",total);
  }
  return 0;
}
View Code

 

posted on 2017-04-19 21:31  Crutain  阅读(202)  评论(0编辑  收藏  举报