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 <cstdio>
#include <cstring>
#include <stack>
#include <set>
using namespace std;
const int maxn=3e5+5;
typedef long long ll;
set<int> 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<k-1;i++)
				printf("%d %d\n",x[i]+1,x[i+1]); 
		}
	}
		return 0;
} 

【總結與反思】

1.開始由於讀錯題,錯認爲結尾必須也得找到相同的數字對應,不然就沒有符合條件的輸出-1,果然就WA了,還要再返工讀題。

2.利用x[k++]來記錄每一次生成相同數時的座標,便於後來再遍歷。

3.補充set容器相關內容,同樣搬運一下學長分享的。方便以後查看。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章