传送门:http://acm.split.hdu.edu.cn/showproblem.php?pid=4455
Substrings
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3426 Accepted Submission(s): 1050
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 a
1,a
2…a
n, 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<=10
6, 0<=Q<=10
4, 0<= a
1,a
2…a
n <=10
6
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
7 1 1 2 3 4 4 5 3 1 2 3 0
Sample Output
7 10 12
Source
思路:
i+1的答案是i的答案减去最后一段,加上前面各段增长1增加的情况数。统计与前面相同数字的距离大于等于i的即为增加的情况数。
#include <cstdio>
#include <cstring>
using namespace std;
const int N=1000005;
int a[N];
int dist[N];///与前一个相同数字距离为i的个数
int distsum[N];///距离大于等于i的个数
long long dp[N];///用int会爆
int ls[N];
int last[N];
int main()
{
int n;
while (scanf("%d",&n)!=EOF)
{
if (n==0)
break;
memset(dist,0,sizeof(dist));
memset(last,0,sizeof(last));
memset(ls,0,sizeof(ls));
for (int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
dist[i-last[a[i]]]++;
last[a[i]]=i;
}
memset(last,0,sizeof(last));
last[a[n]]=1;
ls[n]=1;
for (int i=n-1;i>=1;i--)
{
if (last[a[i]])
ls[i]=ls[i+1];
else
{
ls[i]=ls[i+1]+1;
last[a[i]]=1;
}
}
memset(distsum,0,sizeof(distsum));
for (int i=n;i>=1;i--)
distsum[i]=distsum[i+1]+dist[i];
dp[1]=n;
for (int i=2;i<=n;i++)
{
dp[i]=dp[i-1]+distsum[i]-ls[n+2-i];
}
int w;
scanf("%d",&w);
while (w--)
{
int x;
scanf("%d",&x);
printf("%lld\n",dp[x]);
}
}
return 0;
}