Codeforces Round #312 (Div. 2) B. Amr and The Large Array (构造)
Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.
Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.
Help Amr by choosing the smallest subsegment possible.
The first line contains one number n (1 ≤ n ≤ 105), the size of the array.
The second line contains n integers ai (1 ≤ ai ≤ 106), representing elements of the array.
Output two integers l, r (1 ≤ l ≤ r ≤ n), the beginning and the end of the subsegment chosen respectively.
If there are several possible answers you may output any of them.
5
1 1 2 2 1
1 5
5
1 2 2 3 1
2 3
6
1 2 2 1 1 2
1 5
A subsegment B of an array A from l to r is an array of size r - l + 1 where Bi = Al + i - 1 for all 1 ≤ i ≤ r - l + 1
题意:
一个序列的美丽程度与其中某个数重复次数的最大值有关。求最短的子序列(连续的一段)使得其美丽程度与原序列相等。
分析:
开始就想到暴力,但是wa在第7组上,而且跑得很慢,估计不wa也会在后面超时。
于是休息了下,想到一个比较好处理的方法。
就是把他们的值和位置用结构体记录,然后按照值从小到大,值相等时按位置从小到大排列。这样,就能方便的比较每个数出现了
多少次,最左和最右的位置分别在哪。
实现时,记录出现次数的变量忘记更新了,而且由于是根据后一个数与前一个数是否相等来判断数的分界线,所以处理的时候忘了最后一段是
结果的情况,漏处理了,wa4。。。然后总算= =
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<cstdlib> #include<cmath> #include<vector> #include<queue> #include<map> #include<set> using namespace std; typedef long long ll; struct node { int v,pos; }a[100010]; bool cmp(node x,node y) { if(x.v == y.v) return x.pos<y.pos; return x.v<y.v; } int main() { int n,x; while(~scanf("%d",&n)) { for(int i=1;i<=n;i++) { scanf("%d",&a[i].v); a[i].pos = i; } sort(a+1,a+n+1,cmp); int st = 1,len=0,cnt = 1; int ansl,ansr; for(int i=2;i<=n;i++) { if(a[i].v==a[i-1].v) cnt++; else { if(cnt>len) { ansl = a[st].pos; ansr = a[i-1].pos; len = cnt; } else if(cnt==len) { if(a[i-1].pos-a[st].pos+1<ansr-ansl+1) { ansl = a[st].pos; ansr = a[i-1].pos; } } st = i; cnt = 1; } } if(cnt>len) { ansl = a[st].pos; ansr = a[n].pos; cnt = len; } else if(cnt==len) { if(a[n].pos-a[st].pos+1<ansr-ansl+1) { ansl = a[st].pos; ansr = a[n].pos; } } printf("%d %d\n",ansl,ansr); } return 0; }