您的位置:首页 > 产品设计 > UI/UE

UVA 11235 Frequent values

2015-12-13 17:15 405 查看
求区间最多相同数的数量是多少,因为数列是排序好的,所以直接离散了用线段树求比如样例

-1 -1 1 1 1 1 3 10 10 10 离散后就是(1,2)(2,4)(3,1)(4,3)标号为1的数有2个,标号为2的数有4个.....再用Left[i]Right[i]数组记录标号为i的左边界和右边界,方便查询。

查询时就是线段树求最大值了

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<queue>
#include<algorithm>
#include<set>
#include<string>
#include<iostream>
using namespace std;
typedef long long LL;
#define N 100005
#define inf 1999999999
#define mod 1000000007
int num
,Left
,Right
,coun
;
int n,q,tot;
struct node
{
int l,r,mx;
}tree[N<<2];
void build(int l,int r,int rt)
{
tree[rt].l=l;
tree[rt].r=r;
tree[rt].mx=0;
if(l==r)
{
tree[rt].mx=coun[l];
return ;
}
int mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
tree[rt].mx=max(tree[rt<<1].mx,tree[rt<<1|1].mx);
}
int query(int l,int r,int rt)//求最大值
{
if(tree[rt].l==l&&tree[rt].r==r)
return tree[rt].mx;
int mid=(tree[rt].l+tree[rt].r)>>1;
if(r<=mid) return query(l,r,rt<<1);
else if(l>mid) return query(l,r,rt<<1|1);
else return max(query(l,mid,rt<<1),query(mid+1,r,rt<<1|1));
}
int main()
{
while(scanf("%d",&n),n)
{
scanf("%d",&q);
tot=0;
memset(coun,0,sizeof(coun));
int pre,x;
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
if(i==1)
{
pre=x;
Left[++tot]=1;
}
if(x==pre)
coun[tot]++;
else
{
Right[tot]=i-1;
pre=x;
Left[++tot]=i;
coun[tot]=1;
}
num[i]=tot;//记录第i个数属于哪个标号
}
Right[tot]=n;
build(1,tot,1);
int l,r;
for(int i=0;i<q;i++)
{
scanf("%d%d",&l,&r);
if(num[l]==num[r]) printf("%d\n",r-l+1);
else
{
int ans=max(Right[num[l]]-l+1,r-Left[num[r]]+1);
if(num[l]+1<=num[r]-1)
printf("%d\n",max(ans,query(num[l]+1,num[r]-1,1)));
else printf("%d\n",ans);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: