EOJ 1418/POJ 2566 Bound Found

题目简介


给定一个数列和t,求总和最接近t的一段连续子序列及其和。

说明


由于n达到了1e5不能采用n^2算法,因此考虑用前缀和+尺取法(滑动窗口法/two pointers)降低复杂度。

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e5+5;
const int INF = 0x3f3f3f3f;
struct node
{
    int id, sum;
    bool operator < (const node& rhs) const
    {
        if (sum == rhs.sum) return id < rhs.id;
        return sum < rhs.sum;
    }
}a[maxn];
int n, q, ans, lans, rans;

int main()
{
    int x;
    while (cin >> n >> q && n+q)
    {
        a[0].id = a[0].sum = 0;
        for (int i = 1; i <= n; ++i)
        {
            scanf("%d", &x);
            a[i].id = i;
            a[i].sum = a[i-1].sum + x;
        }
        sort(a, a+1+n);
        while (q--)
        {
            scanf("%d", &x);
            int l = 0, r = 1, minx = INF;
            while (l <= r && r <= n)
            {
                int now = a[r].sum - a[l].sum;
                if (abs(now-x) < minx)
                {
                    minx = abs(now-x);
                    ans = now;
                    lans = a[l].id;
                    rans = a[r].id;
                }
                if (now < x) ++r;
                else if (now > x) ++l;
                else break;
                if (l == r) ++r;
            }
            if (lans > rans) swap(lans, rans);
            printf("%d %d %d\n", ans, lans+1, rans);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值