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/printfinstead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
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.
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
题意:
把一个序列分成最多份,使得每份都有两个数相同,且每份的左最小右最大
思路:
用set储存已经遍历的节点,结构体储存分成的每份的左右
一旦遇到有两个数相同,就记录并重置
最后把最后一个结构体的右节点设为序列长
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <set>
#define ll long long
using namespace std;
set<int>s;
int n;
struct node
{
int l,r;
};
struct node num[150100];
int main()
{
scanf("%d",&n);
int f=0,cnt=1;
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
if(f==0)
{
num[cnt].l=i;
f=1;
}
if(s.find(x)==s.end())
{
s.insert(x);
}
else
{
num[cnt].r=i;
cnt++;
s.clear();
f=0;
}
}
if(cnt-1==0)
{
printf("-1\n");
return 0;
}
if(f)
{
num[cnt].r=n;
}
if(num[cnt-1].r!=n)
num[cnt-1].r=n;
printf("%d\n",cnt-1);
for(int i=1;i<cnt;i++)
{
printf("%d %d\n",num[i].l,num[i].r);
}
}