此处给大家分享俩题目!让你知道效率高的程序是怎样的,对你绝对有用!
Chef and Digits
初看题,觉得很水,但是提交后会发现不断地TLE
怎么去优化呢?预处理,记录每个数出现的次数
Yesterday Chef had a great party and doesn't remember the way he celebreated it. But he found a strange paper in his kitchen containing n digits (lets give them indices from 1 to n and name them a1, a2 ... aN).
Chef remembers that he played such game:
- On each step he choose an index x from 1 to n.
- For all indices y (y < x) he calculated the difference by = ax - ay.
- Then he calculated B1 - sum of all by which are greater than 0 and B2 - sum of all by which are less than 0.
- The answer for this step is B1 - B2.
Chef remembers the game, but forgot the answer. Please, help him!
Input
- The first line contains two integers n, m denoting the number of digits and number of steps. The second line contains n digits (without spaces) a1, a2, ..., an.
- Each of next m lines contains single integer x denoting the index for current step.
Output
- For each of m steps print single number in a line - answer of the step.
Constraints
- 1 ≤ n, m ≤ 10^5
- 0 ≤ ai ≤ 9
- 1 ≤ x ≤ n
Example
Input: 10 3 0324152397 1 4 7 Output: 0 7 9
#include<stdio.h>
#include<string.h>
const int N=100005;
char str[N];
int num[N][10];
int main()
{
int n,m,x,b,i;
scanf("%d %d %s",&n,&m,str+1);
for(i=1;str[i];i++)
{
str[i]-='0';
memcpy(num[i],num[i-1],sizeof num[i]);
num[i][str[i]]++;
}
while(m--)
{
scanf("%d",&x);
int ans=0;
for(int i=0;i<10;i++)
{
b=str[x]-i;
if(b<0) b=-b;
ans+=b*num[x-1][i];
}
printf("%d\n",ans);
}
}