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.
InputThe 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.
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".
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
题意:要找最多数量的包含2个相同元素的数列,输出最大的“好“数列的个数,并给出两个相同元素的位置,如果找不到就输出-1.
思路:考虑到用集合,运用插入和查找函数。第一个数的位置为第一个”好“数列的起始(能找到的前提下),清空集合,逐个插入,碰上已有的则跳到下一个”好“数列(因为要满足最大数量,则需要尽可能短的遇到前后满足相同就作为一个满足条件的数列。
#include<iostream>
#include<cmath>
#include<algorithm>
#include<set>
using namespace std;
set<int>s;
int main()
{
int i,n,t=0,x,z=1,sum=0;
scanf("%d",&n);
int a[n];
s.clear(); //清空集合
for(i=0;i<n;i++)
{
scanf("%d",&x);
if(!s.count(x)) s.insert(x); //集合中没有当前扫描的元素则插入
else {
a[t++]=z; //记录一个满足条件数列的起始
a[t++]=i+1; //记录一个满足条件的数列的末端,i+1由于i从0开始,记录位置从1开始
s.clear(); //找到一个则清空集合
z=i+2; //从当前数列的尾端再往后推一个指向下一个满足条件数列的开始
sum++; //数量+1
}
}
if(!s.empty()){
if(t!=0)
{
t--; //之前t++越界了1个位置
a[t]=n;}
else {printf("-1");return 0;} //t=0 说明没有找到重复的,一直都在插入,即找不到满足条件的数列
}
printf("%d\n",sum); //输出数据
for(i=0;i<t;i=i+2)
{
printf("%d %d\n",a[i],a[i+1]);
}
return 0;
}