POJ2566-Bound Found

来源:互联网 发布:九龙医院网络预约 编辑:程序博客网 时间:2024/05/17 07:40

给定一串数组和一个值,找出一段连续的子列使它们和的绝对值离这个值最近。

#include <cstdio>#include <cstdlib>#include <algorithm>using namespace std;const int maxn = 100000 + 10;typedef pair<int, int> P;int a[maxn];P sum[maxn];int main(int argc, char const *argv[]) {    int n, k;    while (scanf("%d%d", &n, &k) == 2 && n + k) {        for (int i = 0; i < n; i++) {            scanf("%d", &a[i]);        }        sum[0] = P(0, 0);        for (int i = 0; i < n; i++) {            sum[i+1] = P(sum[i].first + a[i], i+1);        }        sort(sum, sum + n + 1);        for (int i = 0; i < k; i++) {            int x;            scanf("%d", &x);            int s = 0, t = 1;            int l, u, ans, eps = 1 << 30;            while (s <= n && t <= n) {                int y = sum[t].first - sum[s].first;                if (abs(y - x) < eps) {                    l = sum[s].second;                    u = sum[t].second;                    ans = y;                    eps = abs(y - x);                }                if (y == x) {                    break;                } else if (y > x) {                    s++;                } else {                    t++;                }                if (s == t) {                    t++;                }            }            if (u < l) {                swap(u, l);            }            printf("%d %d %d\n", ans, l+1, u);        }    }    return 0;}
0 0