3 3 5 5 6 7node
題意:找出每組連續的k個數的最大值最小值。ios
能夠用線段樹,也能夠優先隊列。ui
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<map> #include<vector> #include<queue> #include<stack> #include<set> #include<cmath> #define ll long long #define mem(a,b) memset(a,b,sizeof(a)) using namespace std; const int MAXN=1000000+10; const int inf=0x3f3f3f; int n,m; struct node1 { ll x; int y; friend bool operator < (node1 a,node1 b) { return a.x>b.x; } }z1; struct node2 { ll x; int y; friend bool operator<(node2 a,node2 b) { return a.x<b.x; } }z2; priority_queue<node1>q1; priority_queue<node2>q2; ll z[MAXN]; ll minn[MAXN]; ll maxn[MAXN]; int main() { scanf("%d%d",&n,&m); while(!q1.empty()) q1.pop(); while(!q2.empty()) q2.pop(); for(int i=1;i<=n;i++) { scanf("%lld",&z[i]); z1.y=z2.y=i; z2.x=z1.x=z[i]; if(i<=m) { q1.push(z1); q2.push(z2); } } int ans=0; minn[ans]=q1.top().x; maxn[ans++]=q2.top().x; int left=2; for(int i=m+1;i<=n;i++) { z1.x=z[i];z1.y=i; z2.x=z[i];z2.y=i; q1.push(z1); q2.push(z2); while(q1.top().y<left) { q1.pop(); } while(q2.top().y<left) { q2.pop(); } left++; minn[ans]=q1.top().x; maxn[ans++]=q2.top().x; } printf("%lld",minn[0]); for(int i=1;i<ans;i++) printf(" %lld",minn[i]); printf("\n"); printf("%lld",maxn[0]); for(int i=1;i<ans;i++) printf(" %lld",maxn[i]); printf("\n"); }
線段樹spa
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<map> #include<vector> #include<queue> #include<stack> #include<set> #include<cmath> #define ll long long #define mem(a,b) memset(a,b,sizeof(a)) #define inf 0x3f3f3f3f #define maxn 1000009 #define root 1,n,1 #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 using namespace std; struct node{ int l,r,rt; int mid(){ return (l+r)/2; } }tree[maxn*4]; int n,k; int sum1[maxn<<2],sum2[maxn<<2]; void pushup(int rt){ sum1[rt]=min(sum1[rt<<1],sum1[rt<<1|1]); sum2[rt]=max(sum2[rt<<1],sum2[rt<<1|1]); } void build(int l,int r,int rt){ tree[rt].l=l;tree[rt].r=r; if(l==r){ tree[rt].l=tree[rt].r=l; scanf("%d",&sum1[rt]); sum2[rt]=sum1[rt];return ; } int mid=tree[rt].mid(); build(lson); build(rson); pushup(rt); } int query1(int a,int b,int l,int r,int rt){ if(a==l&&b==r){ return sum1[rt]; } int mid=tree[rt].mid(); if(a>mid){ return query1(a,b,mid+1,r,rt*2+1); } else if(b<=mid){ return query1(a,b,l,mid,rt*2); } else return min(query1(a,mid,lson),query1(mid+1,b,rson)); } int query2(int a,int b,int l,int r,int rt){ if(a==l&&b==r){ return sum2[rt]; } int mid=tree[rt].mid(); if(a>mid){ return query2(a,b,mid+1,r,rt*2+1); } else if(b<=mid){ return query2(a,b,l,mid,rt*2); } else return max(query2(a,mid,lson),query2(mid+1,b,rson)); } int main(){ mem(sum1,inf);mem(sum2,-inf); scanf("%d%d",&n,&k); build(root); for(int i=1;i<=n-k+1;i++){ if(i!=1)printf(" "); printf("%d",query1(i,i+k-1,root)); } printf("\n"); for(int i=1;i<=n-k+1;i++){ if(i!=1)printf(" "); printf("%d",query2(i,i+k-1,root)); } printf("\n"); }