CodeForces - 620C (贪心)详解

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".

直接讲贪心的思路。

由于每个元素最大可以是1e9所以要用map来记录每个元素出现的次数,每当某个元素出现两次时,就截成一段,然后清空map,用L,R分别记录当前段的左端和右端。用一个结构体数组来保存答案。特别注意,若遍历完后最后一个元素未被放入某一段中,则需要将结构体数组最后一个的 r 改为 n;

下面上代码

#include <vector>
#include <stdio.h>
#include <map>
#include <stdlib.h>
#include<ctype.h>
#define LL long long
using namespace std;

const int MAX = 3e5 + 50;
map<int, int> mp;
int a[MAX];
struct date
{
	int l, r;
} ans[MAX];
int main(int argc, char const *argv[]){
	int n;
	scanf("%d", &n);
	int L = 1, R = 0; // 注意,R需要从0开始
	int fg = 0; //用来判断for一遍后最后一个元素是否被放入最后一段中
	int k = 0;
	for(int i = 1; i <= n; i++){
		scanf("%d", &a[i]);
		int x = a[i];
		mp[x]++; // 记录该元素出现了几次
		R++; //每次进入时R++
		if(mp[x] == 2){
			if(i == n){ 
				fg = 1;
			}
			mp.clear();
			ans[k].l = L;
			ans[k++].r = R;
			L = R + 1; // 截取一段后,更新左端点
		}
	}
	if(k == 0){
		printf("-1\n");
	} else{
		if(fg == 0){ // 如果最后一个元素未被放入,则将最后一个r改为n
			ans[k - 1].r = n;
		}
		printf("%d\n", k);
		for(int i = 0; i < k; i++){
			printf("%d %d\n", ans[i].l, ans[i].r);
		}
	}
	return 0;
}


 

猜你喜欢

转载自blog.csdn.net/weixin_43737952/article/details/88985446