TOJ 2596: Music Notes

本文介绍了一个算法问题,涉及歌曲由多个音符组成,每个音符持续一定拍数。任务是根据给定的时间点,确定正在播放的是哪个音符。文章提供了两种解决方法,一种使用二分查找,另一种利用标准库函数upper_bound简化实现。

2596: Music Notes 分享至QQ空间

Time Limit(Common/Java):1000MS/10000MS     Memory Limit:65536KByte
Total Submit: 3            Accepted:3

Description

 

FJ is going to teach his cows how to play a song. The song consists of N (1 ≤ N ≤ 100) notes, and the i-th note lasts for B_i (1 ≤ B_i ≤ 100) beats. The cows will begin playing the song at time 0; thus, they will play note 1 from time 0 to time B_1 - 1, note 2 fromtime B_1 to time B_1 + B_2 - 1, etc.

The cows have lost interest in the song, as they feel that it is long and boring. Thus, to make sure his cows are paying attention, FJ asks them Q (1 ≤ Q ≤ 1,000) questions of the form, "During the beat at time T_i (0 ≤ T_i < length of song), which note should you be playing?" The cows need your help to answer these questions.

By way of example, consider a song with these specifications: note 1 for length 2, note 2 for length 1, and note 3 for length 3:

 

NOTES    1   1   2   3   3   3
       +---+---+---+---+---+---+
TIME     0   1   2   3   4   5

 

Input

 

* Line 1: Two space-separated integers: N and Q
* Lines 2..N+1: Line i+1 contains a single integer: B_i
* Lines N+2..N+Q+1: Line N+i+1 contains a single integer: T_i

 

Output

 

* Lines 1..Q: Line i contains the a single integer that is the note the cows should be playing at time T_i

 

Sample Input

 3 5 







1

Sample Output

 2 



 这么简单的题怎么没有人写题解,你有n首歌,问你可以听到第几首,前缀和处理下,然后二分直接输出啊

#include<stdio.h>
int a[105],n,q;
int BS(int x)
{
    int l=1,r=n;
    while(l<=r)
    {
        int mi=(l+r)/2;
        if(a[mi]>x)r=mi-1;
        else l=mi+1;
    }
    return l;
}
int main()
{
    while(~scanf("%d%d",&n,&q))
    {
        scanf("%d",&a[1]);
        for(int i=2;i<=n;i++)
        {
            scanf("%d",&a[i]);
            a[i]+=a[i-1];
        }
        while(q--)
        {
            int x;scanf("%d",&x);
            printf("%d\n",BS(x));
        }
    }
    return 0;
}

 原题数据范围应该很大,这个暴力复杂度都还正常

#include<stdio.h>
#include<algorithm>
using namespace std;
int a[105],n,q;
int main()
{
    while(~scanf("%d%d",&n,&q))
    {
        scanf("%d",&a[1]);
        for(int i=2;i<=n;i++)
        {
            scanf("%d",&a[i]);
            a[i]+=a[i-1];
        }
        while(q--)
        {
            int x;scanf("%d",&x);
            printf("%d\n",(int)(upper_bound(a+1,a+n+1,x)-a));
        }
    }
    return 0;
}

 

 

转载于:https://www.cnblogs.com/BobHuang/p/7529934.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值