codechef April challenge (1)(学习去优化时间效率???)

此处给大家分享俩题目!让你知道效率高的程序是怎样的,对你绝对有用!

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

  • 1n, m10^5
  • 0ai9
  • 1xn

 

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);
    }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值