【其他形式的双指针】poj - 2566

题目链接

题意:求一个区间使得其和的绝对值与输入的 t 差值最小。

题解

  • 尺取法需要区间具有某种单调性质
  • 例如,右指针从左边界向右枚举,而左边界到某边界点,和此边界点到右指针之间具有不同的性质(二分思想)
  • 有时,左指针移动到此边界处时,只需要判断一个方向上的情况。(套用y总模板)
  • 而像这道题,需要判断两个方向上的情况,所以使用较灵活的双指针更合适。

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=1e5+10;
typedef long long ll;
struct node{
	ll sum,id;
}blo[N];
bool cmp(const node& x,const node& y)
{
	return x.sum<y.sum;
}
ll abs_(ll k) { if(k<0) return -k; return k; }
int main()
{
	ll n,k;
	while(scanf("%lld %lld",&n,&k))
	{
		if(n==0 && k==0) break;
		blo[0]={0,0};
		for(int i=1;i<=n;i++)
		{
			scanf("%lld",&blo[i].sum);
			blo[i].sum+=blo[i-1].sum;
			blo[i].id=i;
		}
		sort(blo,blo+1+n,cmp);
		
		while(k--)
		{
			ll t; scanf("%lld",&t);
			//del表示区间和与t的绝对差值,ans,ansl,ansr记录三个答案
			ll del=9e18,ans,sum,ansl,ansr;
			ll l=0,r=1;
			while(r<=n && del)
			{
				sum=blo[r].sum-blo[l].sum;
				if(abs_(sum-t)<del)
				{
					del=abs_(sum-t);
					
					ans=sum;
					ansl=blo[l].id,ansr=blo[r].id;
				}
				
				if(sum<t) r++;
				else if(sum>t) l++;
				
				//在这道题中不能碰到一起
				if(r==l) r++;
			}
			//排完序后ansl,ansr前后顺序被打乱,需要重新调整
			if(ansl>ansr) swap(ansl,ansr);
			printf("%lld %lld %lld\n",ans,ansl+1,ansr);
		}
	}
	return 0;
}

  • 2021.10.19又写了一遍。第四十行加了个=号就过了,不知道为什么,感觉是spj的问题

AC代码:

#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

typedef long long LL;
const int N=1e5+10;

struct node{
    LL sum;
    int id;
    bool operator < (const node a) const{
        return sum < a.sum;
    }
}blo[N];

int main()
{
    LL n, k, x;
    while(scanf("%lld %lld", &n, &k))
    {
        if(n == 0 && k == 0) break;
        blo[0] = {0, 0};
        for(int i=1; i<=n; i++){
            scanf("%lld", &x);
            blo[i].sum = blo[i - 1].sum + x;
            blo[i].id = i;
        }
        sort(blo, blo + n + 1);

        while(k--)
        {
            LL t; scanf("%lld", &t);
            int ansl, ansr;
            LL mi = 9e18, ans;
            for(int i=1, j=0; i<=n; i++)
            {
                while(j < i - 1 && llabs(blo[i].sum - blo[j].sum - t) >= llabs(blo[i].sum - blo[j + 1].sum - t)) j++;
                if(llabs(blo[i].sum - blo[j].sum - t) < mi){
                    mi = llabs(blo[i].sum - blo[j].sum - t);
                    ans = blo[i].sum - blo[j].sum;
                    ansl = blo[j].id, ansr = blo[i].id;
                }
            }
            if(ansl > ansr) swap(ansl, ansr);
            ansl ++;
            printf("%lld %d %d\n", ans, ansl, ansr);
        }
    }

    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值