Bound Found POJ - 2566 (尺取)

本文介绍了一种用于解析可能源自外星的信号的算法。该算法接收一系列整数及目标值,通过查找连续子序列来确定其绝对和最接近目标值的范围。文章提供了输入输出示例,并附带了实现这一功能的C++代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Signals of most probably extra-terrestrial origin have been received and digitalized by The Aeronautic and Space Administration (that must be going through a defiant phase: "But I want to use feet, not meters!"). Each signal seems to come in two parts: a sequence of n integer values and a non-negative integer t. We'll not go into details, but researchers found out that a signal encodes two integer values. These can be found as the lower and upper bound of a subrange of the sequence whose absolute value of its sum is closest to t. 

You are given the sequence of n integers and the non-negative target t. You are to find a non-empty range of the sequence (i.e. a continuous subsequence) and output its lower index l and its upper index u. The absolute value of the sum of the values of the sequence from the l-th to the u-th element (inclusive) must be at least as close to t as the absolute value of the sum of any other non-empty range.
Input
The input file contains several test cases. Each test case starts with two numbers n and k. Input is terminated by n=k=0. Otherwise, 1<=n<=100000 and there follow n integers with absolute values <=10000 which constitute the sequence. Then follow k queries for this sequence. Each query is a target t with 0<=t<=1000000000.
Output
For each query output 3 numbers on a line: some closest absolute sum and the lower and upper indices of some range where this absolute sum is achieved. Possible indices start with 1 and go up to n.
Sample Input
5 1
-10 -5 0 5 10
3
10 2
-9 8 -7 6 -5 4 -3 2 -1 0
5 11
15 2
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
15 100
0 0
Sample Output
5 4 4
5 2 8
9 1 1
15 1 15
15 1 15

#include<stdio.h>
#include<string.h>
#include<map>
#include<vector>
#include<iostream>
#include<algorithm>
#include<queue>
#include<deque>
#include<math.h>
#define ll long long
const int inf=2e9;
using namespace std;
int a[100005];
struct node
{
    int x,sum;
}e[100005];
int k,n;
int cmp(node n1,node n2)
{
    return n1.sum<n2.sum;
}
void aa(int u)
{
    int l=0,r=1,l1,r1,ans=inf,kk;
    while(r<=n&&ans)
    {
        int dd=e[r].sum-e[l].sum;
        if(abs(dd-u)<=ans)
        {
            ans=abs(dd-u);
            kk=dd;
            l1=e[l].x,r1=e[r].x;
        }
        if(dd>u)
            l++;
        if(dd<u)
            r++;
        if(l==r) r++;
    }
    if(l1>r1) swap(l1,r1);
    printf("%d %d %d\n",kk,l1+1,r1);
}
int main()
{
    while(~scanf("%d%d",&n,&k)&&n+k)
    {
        int b;
        e[0].x=0;e[0].sum=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            e[i].x=i;
            e[i].sum=e[i-1].sum+a[i];
        }
        sort(e,e+n+1,cmp);
        while(k--)
        {
            scanf("%d",&b);
            aa(b);
        }
    }
}




### 解决方案分析 `No thread-bound request found` 错误通常发生在尝试通过 `RequestContextHolder` 获当前线程绑定的请求对象时失败的情况下。这可能是因为当前线程并未关联到任何 HTTP 请求上下文,或者该上下文已被销毁。 #### 原因解析 1. **异步处理**:如果应用程序涉及异步任务(如 `@Async` 或者自定义线程池),主线程中的请求上下文不会自动传递给子线程[^1]。 2. **非 Web 线程访问**:某些情况下,代码运行在非 Web 环境中(例如定时任务、消息队列消费者等),此时无法找到绑定的请求上下文。 3. **过滤器或拦截器配置不当**:某些过滤器可能会提前结束请求生命周期,导致后续逻辑找不到有效的请求上下文。 --- ### 解决方法 以下是几种常见的解决方案: #### 方法一:手动设置 Request Attributes 可以通过显式创建并绑定 `ServletRequestAttributes` 来解决此问题。以下是一个示例实现: ```java import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; public class RequestContextUtil { public static void bindRequest(HttpServletRequest servletRequest) { ServletRequestAttributes attributes = new ServletRequestAttributes(servletRequest); RequestContextHolder.setRequestAttributes(attributes); } } ``` 在实际应用中,在启动新线程之前调用上述工具类的方法来绑定请求属性即可[^1]。 #### 方法二:使用 AsyncContext 进行异步处理 当需要执行异步操作时,可以利用 Servlet 的 `AsyncContext` 功能保持请求上下文存活直到异步任务完成为止。如下所示: ```java @WebServlet(urlPatterns = "/async", asyncSupported = true) public class AsyncServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final AsyncContext ctx = req.startAsync(); Executors.newSingleThreadExecutor().submit(() -> { try { Thread.sleep(5000); // Simulate long-running task HttpServletRequest currentReq = (HttpServletRequest) ctx.getRequest(); // Process with the original request object System.out.println(currentReq.getParameter("param")); ctx.getResponse().getWriter().println("Done!"); } catch (Exception e) { e.printStackTrace(); } finally { ctx.complete(); } }); } } ``` 这种方式能够确保即使是在延迟响应期间也能维持原始请求的信息可用性。 #### 方法三:避免依赖于 RequestContextHolder 如果确实不需要直接访问具体的 `HttpServletRequest` 对象,则应考虑重构代码以减少对此模式的依赖。例如改用更高级别的抽象框架来进行 RESTful 调用而不是手工构建 HTTP 客户端实例[^3]。 --- ### 示例代码片段 这里提供一段基于 RestTemplate 实现的替代方案用于发起远程服务调用: ```java import org.springframework.web.client.RestTemplate; public class RestClientExample { private final RestTemplate restTemplate = new RestTemplate(); public String createBooking(String url, Object requestBody){ ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class); if(response.getStatusCodeValue() == 201 && response.getHeaders().containsKey("Location")){ return response.getHeaders().getLocation().toString(); } throw new RuntimeException("Failed to create booking"); } } ``` 相比传统的 HttpClient 方式更加简洁明了,并且天然集成了 Spring 上下文中的一些便利特性[^3]。 --- ### 总结 针对 `No thread-bound request found` 错误,推荐优先评估是否真的有必要频繁借助 `RequestContextHolder` 访问当前请求数据;如果不是绝对必要的话则尽量采用其他设计思路规避潜在风险。另外需要注意的是,在多线程环境下务必妥善管理好各线程间共享状态的数据一致性问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值