hdu5875 Function 模运算 + 单调栈
来源:互联网 发布:固定资产投资的算法 编辑:程序博客网 时间:2024/05/21 06:28
题目描述:给定数组A,数组中元素的个数不多于1e5个,现给出函数F(l , r)的定义
给出m( m <= 1e5)次询问,每次询问给出l、r的值,每次输出F(l,r)
思路:首先观察模的三个性质:
①一个数模比它大的数大小不变
②一个数先模a,再模b,如果 a>b,那么模b这一步没什么效果
③a % b <= a/2
证明:若b >= a / 2 , 则 a % b = a - b <= a - a / 2 = a / 2 ;
若b< a / 2 , 假设 a % b = x > a / 2 ; 则有x % b = y < x ,故a % b = y != x 矛盾
综上,a% b <= a / 2 ;
所以,对于任意一次询问,让A[i]只对其后面的第一个比自己小的数k取模,然后再对k后面比k小的第一个数取模,这样最多取模31次,复杂度O(logA[i] * m)不会超时
那么,怎么维护比A[i]小的第一个数k呢?我们开一个数组nt,nt[i]表示第i个后面小于等于A[i]的第一个数的位置,使用单调栈构造nt数组。
首先将a[n]入栈,然后i从n-1到1循环,每次如果a[i]大于等于栈顶的数,就把nt[i]赋值为栈顶数的位置;否则让栈顶的数出栈,考虑下一个栈顶。 最后,让a[i]入栈
实现代码如下:
#pragma warning(disable:4786)#pragma comment(linker, "/STACK:102400000,102400000")#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<stack>#include<queue>#include<map>#include<set>#include<vector>#include<cmath>#include<string>#include<sstream>#define LL long long#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)#define mem(a,x) memset(a,x,sizeof(a))#define lson l,m,x<<1#define rson m+1,r,x<<1|1using namespace std;const int INF = 0x3f3f3f3f;const double PI = acos(-1.0);const int maxn = 1e5 + 5;const double eps=1e-6;struct node{ int val , pos ;}st[maxn];int top , a[maxn] , nt[maxn] ;int main(){ int T , l , r , n , m ; scanf("%d",&T) ; while(T--){ mem(st,0); mem(nt , 0); top = 0; scanf("%d",&n); for(int i = 1 ; i<= n ; i++){ scanf("%d",&a[i]); } node x = { a[n] , n } ; st[++top] = x ; nt[n] = -1 ; for(int i = n - 1 ; i>= 1 ; i--){ int flag = 0; while(top > 0) { if(st[top].val <= a[i]){ nt[i] = st[top].pos ; flag = 1 ; break; } else{ --top; } } if(!flag) nt[i] = -1 ; node x = {a[i] , i } ; st[++top] = x; } scanf("%d",&m); for(int i = 1 ; i<= m ; i++){ scanf("%d %d",&l , &r); int cur = nt[l] , ans = a[l] ; while(cur != -1 && cur <= r && ans){ int mod = a[cur] ; ans %= mod ; cur = nt[cur] ; } printf("%d\n",ans); } } return 0 ;}
0 0
- hdu5875 Function 模运算 + 单调栈
- hdu5875 Function (预处理+单调性质)
- hdu5875 Function
- HDU5875-Function
- hdu5875 Function
- HDU5875 - 大连网赛1008(单调栈)
- Function(HDU5875)
- hdu5875 Function(暴力)
- 【HDU5875】Function(RMQ)
- hdu5875 Function (离线处理)
- HDU5875-Function(RMQ + 二分)
- hdu5662 YJQQQAQ and the function (单调栈)
- hdu 5875 Function 单调栈 + 暴力
- HDU 5875 Function (单调栈+暴力)
- HDU-5662 YJQQQAQ and the function (枚举&&单调栈)
- [HDU 5875] Function (单调栈/(RMQ+二分))
- HDU 5875 Function(单调栈+在线倍增法)
- hdu5875(取模的性质,线段树,二分)
- DIY一个具有远程控制功能的智能家居原型系统
- springmvc4+hibernate4整合框架的搭建,超详细哦
- IP、TCP、UDP首部详解
- mvn tomcat:run启动tomcat插件一直停在Starting Coyote HTTP/1.1 on http-8080
- hdu 5493线段树+模拟
- hdu5875 Function 模运算 + 单调栈
- 高级软件工程师(面试题)
- bzoj 3226: [Sdoi2008]校门外的区间(线段树)
- Java中级开发工程师知识点归纳
- C#Windows窗体组成基本思路和控件使用
- 系统软件的质量属性
- 24. Swap Nodes in Pairs
- ASP.NET MVC中 使用邮件模板的两种方式
- POJ【数论/组合/博弈论】题目列表