大体题意:

告诉你一个自定义的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) (1≤l≤r≤N) is defined as:
F(l,r)={AlF(l,r−1) 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(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


(l,r), output  F(l,r)


 



Sample Input


1 3 2 3 3 1 1 3


 



Sample Output


2


 



Source


2016 ACM/ICPC Asia Regional Dalian Online