HDU 5875 Function (思路题目)

本文介绍了一种针对特定自定义函数F(l,r)的优化算法,该函数在给定数组A上计算从l到r的元素按顺序取模的结果。通过对原始函数进行转换并利用特殊性质,文章提供了一个高效解决方案来避免不必要的计算。

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

大体题意:

告诉你一个自定义的F函数求解方法,给你q个自变量(区间),求解答案!

思路:

分析自定义的函数可以知道,我们可以变换一下这个函数,变换之后也就是F(l,r) = a[l] % a[l+1] %..... % a[r];

如果这样纯粹的求解的话,肯定会超时的,不说有多少个操作,就是这个取模就慢的不行!

我们知道,一个数对比他大的数取模的话,那么这个数取模后是不变的,我们可以利用这一个性质进行优化!

我们定义nest[i] 表示在i位置以后 第一个不比a[i]大的数,这样我们不断的跳位置即可!因为之间的没必要进行枚举,因为取模了值也不变!这样就可以通过了!


坑:

注意,输入的n 个数会有0存在,因此不能直接取模,如果发现是0的话,就没意义了, 直接break 即可!(continue就超时)反正有0就很恶心了,不该有0 的数据的 = = !

详细见代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int n;
int nest[maxn];
int a[maxn];
void get_next(){
	for (int i = 1; i <= n; ++i){
		for (int j = i+1; j <= n; ++j){
			nest[i] = n+1;
			if (a[j] <= a[i]){
				nest[i] = j;
				break;
			}
		}
	}
}
int main(){
	int T;
	scanf("%d",&T);
	while(T--){	
		scanf("%d",&n);
		for (int i = 1; i <= n; ++i){
			scanf("%d",&a[i]);
		}
		get_next();
		int q;
		scanf("%d",&q);
		while(q--){
			int l,r;
			scanf("%d %d",&l,&r);
			int ans = a[l];
			for (int i = nest[l]; i <= r; i = nest[i]){
				if (a[i] == 0)break;
				ans %= a[i];
				if (ans == 0)break;
			}
			printf("%d\n",ans);
		}	
	}
	return 0;
}

Function

Time Limit: 7000/3500 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1548    Accepted Submission(s): 567


Problem Description
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) (1lrN)  is defined as:
F(l,r)={AlF(l,r1) modArl=r;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(1N100000) .
  The second line contains  N  space-separated positive integers:  A1,,AN (0Ai109) .
  The third line contains an integer  M  denoting the number of queries. 
  The following  M  lines each contain two integers  l,r (1lrN) , 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
 

Source

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值