POJ

来源:互联网 发布:云数据库 编辑:程序博客网 时间:2024/06/03 13:37
#include<iostream>#include<math.h>#include<cstdio>#include<stdlib.h>#include<string.h>#include<vector>#include<algorithm>#include<queue>using namespace std;int dp[50009][30]={0},dp1[50009][30]={1000009};int a[50009],n;void init(){    for(int j=0;(1<<j)<=n;j++)        for(int i=1;i+(1<<j)<=n+1;i++)    {        if(j)        {            dp[i][j]=max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);            dp1[i][j]=min(dp1[i][j-1],dp1[i+(1<<(j-1))][j-1]);        }        else {dp[i][j]=a[i];        dp1[i][j]=a[i];        }    }}int main(){int m;scanf("%d%d",&n,&m);for(int i=1;i<=n;i++)    scanf("%d",&a[i]);init();int x,y;for(int i=1;i<=m;i++){scanf("%d%d",&x,&y);if(x>y)swap(x,y);int k=floor(log10(double(y-x+1))/log10(double(2)));int min1,max1;max1=max(dp[x][k],dp[y-(1<<k)+1][k]);min1=min(dp1[x][k],dp1[y-(1<<k)+1][k]);printf("%d\n",max1-min1);}    return 0;}

#include <stdio.h>#include <iostream>#include <string.h>#include <algorithm>#include <map>using namespace std;struct node{    int min1,max1,l,r;}tree[200100];int a[60000],n;void build(int l,int r,int root){     tree[root].l=l;     tree[root].r=r;    if(l==r)    {        if(l<=n)        tree[root].min1=a[l];        tree[root].max1=a[l];        return ;    }    int mid=(l+r)/2;   build(l,mid,root*2);   build(mid+1,r,root*2+1);   tree[root].min1=min(tree[root*2].min1,tree[root*2+1].min1);   tree[root].max1=max(tree[root*2].max1,tree[root*2+1].max1);}int find_min(int l,int r,int root){    if(tree[root].l>=l&&tree[root].r<=r)    {return tree[root].min1;}    int mid=(tree[root].l+tree[root].r)/2;    int t1=2000000,t2=2000000;    if(mid>=l)    t1=find_min(l,r,root*2);    if(mid<r)t2=find_min(l,r,root*2+1);    return min(t1,t2);}int find_max(int l,int r,int root ){    if(tree[root].l>=l&&tree[root].r<=r)    {return tree[root].max1;}    int mid=(tree[root].l+tree[root].r)/2;    int t1=0,t2=0;    if(mid>=l)    t1=find_max(l,r,root*2);    if(mid<r)t2=find_max(l,r,root*2+1);    return max(t1,t2);}int main(){int m;scanf("%d%d",&n,&m);for(int i=1;i<=n;i++)    scanf("%d",&a[i]);build(1,n,1);int x,y;for(int i=1;i<=m;i++){    scanf("%d%d",&x,&y);    printf("%d\n",find_max(x,y,1)-find_min(x,y,1));}    return 0;}


0 0
原创粉丝点击