Educational Codeforces Round 6(C)尺取法+贪心

来源:互联网 发布:光网络计划 verizon 编辑:程序博客网 时间:2024/04/29 03:50

C. Pearls in a Row
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

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 test(s)
input
51 2 3 4 1
output
11 5
input
51 2 3 4 5
output
-1
input
71 2 1 3 1 2 1
output
21 34 7






题意:给你n个数字,问 最多有多少个区间满足区间内恰好有2个相同的数字,将这些区间的下标输出。



题解:很明显,使用尺取法枚举区间,;这里使用SET去维护区间的个数,如果一个区间的数字出出现2次,那么这个区间就是符合题意的。这里其实有一个很坑的地方,举个例子

4

1 1 3 2

这组的样例应该输出

1

 1 4

很多同学错应该是输出

1

1 2

那么我们可以稍微处理一下,我们只要稍微思考一下就知道,只有最后一个区间的数字有可能会扫描不到所有的数字,根据题意最后一个区间的右区间一定是n。所以输出的时候将最后的数字特殊处理一下




#include<iostream>#include<cstdio>#include<algorithm>#include<cmath>#include<cstring>#include<map>#include<set>#include<vector>#define N 3000000using namespace std;#define LL unsigned long longLL a[N];struct point{int x,y;point(int _x,int _y):x(_x),y(_y){}point(){}};map<unsigned long long,LL>q;vector<point>eg;int main(){#ifdef CDZSCfreopen("i.txt","r",stdin);#endifint n;while(~scanf("%d",&n)){   eg.clear();q.clear();for(int i=0;i<n;i++){scanf("%lld",&a[i]);}int L=0,R=0;while(R<n){if(!q.count(a[R])){q[a[R++]]++;}else{eg.push_back(point(L+1,R+1));L=++R;q.clear();}}if(eg.size()<=0){puts("-1");}else{printf("%d\n",eg.size());for(int i=0;i<eg.size();i++){if(i==eg.size()-1){eg[i].y=n;}printf("%d %d\n",eg[i].x,eg[i].y);}}}return 0;}
















0 0
原创粉丝点击