2018.1.30【 CodeForces - 620C 】解题报告(STL,set容器)

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

Examples
input
5
1 2 3 4 1
output
1
1 5
input
5
1 2 3 4 5
output
-1
input
7
1 2 1 3 1 2 1
output
2
1 3
4 7

【题目大意】

给定一个数列,若子序列中包含至少一对相同数(ai与aj相同)则为good,问最多能划分为多少个good(要求每一个数都要再一个序列中),并输出每一段的开头index和结尾index。

【解题思路】

由于不限定开头和结尾必须就是相同的数,所以每一次出现相同数就划分一次即可。

利用set容器(set容器元素唯一),可以通过std::set::count方法来查询之前是否出现该数,是的话count++,然后清空set。

注意头尾的格式输出即可。

【解题代码】

#include 
#include 
#include 
#include 
using namespace std;
const int maxn=3e5+5;
typedef long long ll;
set s;
int x[maxn];
int n,k;
int main()
{
	while(~scanf("%d",&n))
	{
		k=0;
		if(!s.empty()) s.clear();
		for(int i=1;i<=n;i++)
		{
			int p;
			scanf("%d",&p);
			if(s.count(p)==0) s.insert(p);
			else
			{
				x[k++]=i;
				s.clear();
			}
		}
		if(k==0) printf("-1\n");
//		else if(!s.empty()) printf("-1\n");
		else
		{
			if(x[k-1]!=n) x[k-1]=n;
			printf("%d\n",k);
			printf("1 %d\n",x[0]);
			for(int i=0;i

【总结与反思】

1.开始由于读错题,错认为结尾必须也得找到相同的数字对应,不然就没有符合条件的输出-1,果然就WA了,还要再返工读题。

2.利用x[k++]来记录每一次生成相同数时的坐标,便于后来再遍历。

3.补充set容器相关内容,同样搬运一下学长分享的。方便以后查看。

2018.1.30【 CodeForces - 620C 】解题报告(STL,set容器)_第1张图片

2018.1.30【 CodeForces - 620C 】解题报告(STL,set容器)_第2张图片

2018.1.30【 CodeForces - 620C 】解题报告(STL,set容器)_第3张图片



你可能感兴趣的:(CodeForces,STL)