Function HDU - 5875(暴力+思维)

博客围绕HDU - 5875的Function问题展开,给定含N个正整数的数组A及M个(l,r)形式的查询,定义了函数F(l,r)。需根据输入的N、数组A、查询数M及具体查询(l,r)输出F(l,r)。分析指出预处理右边首个比它小的数,询问时跳着向后找,可直接暴力求解。

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

Function HDU - 5875

The shorter, the simpler. With this problem, you should be convinced of this truth.

You are given an array A of N postive integers, and M queries in the form (l,r). A function F(l,r) (1≤l≤r≤N) is defined as:

F(l,r)={ Al       l=r; F(l,r1) mod Ar        l<rF(l,r)={ Al       l=r; F(l,r−1) mod Ar        l<r

You job is to calculate F(l,r), for each query (l,r)
.
Input
There are multiple test cases.
  The first line of input contains a integer T, indicating number of test cases, and T test cases follow.

For each test case, the first line contains an integer N(1≤N≤100000).
The second line contains N space-separated positive integers: A1,…,AN (0≤Ai≤109).
The third line contains an integer M denoting the number of queries.
The following M lines each contain two integers l,r (1≤l≤r≤N)
, representing a query.
Output
For each query(l,r), output F(l,r)
on one line.
Sample Input

1
3
2 3 3
1
1 3

Sample Output

2
题意:

给定区间l,r求上述公式

分析:

预处理出右边第一个比它小的数,然后询问的话就可以跳着向后找,直接暴力就可以

code:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000+7;
int pos[maxn];
int a[maxn],n,m;
void init(){
    memset(pos,-1,sizeof(pos));
    for(int i = n-1; i >= 1; i--){
        int p = i + 1;
        for(;;){
            if(a[i] > a[p]){
                pos[i] = p;
                break;
            }
            if(pos[p] == -1){
                pos[i] = -1;
                break;
            }
            p = pos[p];
        }
    }
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        for(int i = 1; i <= n; i++){
            scanf("%d",&a[i]);
        }
        init();
        scanf("%d",&m);
        for(int i = 1; i <= m; i++){
            int l,r;
            scanf("%d%d",&l,&r);
            int ans = a[l];
            l = pos[l];
            while(l <= r && l != -1){
                ans %= a[l];
                l = pos[l];
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值