Description
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.
Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.
Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input
The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row.
The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.
Output
On the first line print integer k — the maximal number of segments in a partition of the row.
Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment.
Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type.
If there are several optimal solutions print any of them. You can print the segments in any order.
If there are no correct partitions of the row print the number "-1".
Sample Input
5 1 2 3 4 1
1 1 5
5 1 2 3 4 5
-1
7 1 2 1 3 1 2 1
2 1 3 4 7
解题思路:
codeforce的一道题,这题题意挺好理解,要细心一些,由于漏掉了一些条件我也错了很多次。。
1,珍珠的种类数目太大了,需要进行映射。
2,使用计数的数组(这题可以简化为一个bool数组),发现出现一样的种类,就确定了一个线段,这个线段要左边进行扩展,最后一个线段要右边进行扩展。
3,memset函数是线性的复杂度,在循环里面尽量的不要用,如果要进行数组值的清除,知道要清零的位置吗最好写一个专门清零的循环。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<vector>
using namespace std;
const int maxn = 3000005 ;
int n ;
int arry[maxn];
bool num[maxn];
int sg[maxn][2];
map<int,int>qq;
int main(){
while(~scanf("%d",&n)){
qq.clear();
int c = 1 ;
for(int i=0;i<n;i++){
scanf("%d",&arry[i]);
}
for(int i=0;i<n;i++){
if(!qq.count(arry[i]))qq[arry[i]] = c++ ;
}
memset(num,false,sizeof(num));
int cnt = 0 ;
int l = 1 ;
for(int i=0;i<n;i++){
int x = qq[arry[i]];
if(!num[x]){
num[x]=true;
continue ;
}else{
//memset(num,false,sizeof(num));
for(int j=i;j>=l-1;j--)num[qq[arry[j]]]=false;
sg[cnt][0]=l;
sg[cnt][1]=i+1;
cnt++;
l=i+2;
}
}
if(cnt==0){
printf("-1\n");
}else {
printf("%d\n",cnt);
for(int i=0;i<cnt;i++){
if(i==cnt-1){
printf("%d %d\n",sg[i][0],n);
}
else printf("%d %d\n",sg[i][0],sg[i][1]);
}
}
}
return 0;
}