1. 程式人生 > >PAT TOP 1026 String of Colorful Beads (35)

PAT TOP 1026 String of Colorful Beads (35)

問題描述:

1026 String of Colorful Beads (35 分)

Eva would like to buy a string of beads with no repeated colors so she went to a small shop of which the owner had a very long string of beads. However the owner would only like to cut one piece at a time for his customer. With as many as ten thousand beads in the string, Eva needs your help to tell her how to obtain the longest piece of string that contains beads with all different colors. And more, each kind of these beads has a different value. If there are more than one way to get the longest piece, Eva would like to take the most valuable one. It is guaranteed that such a solution is unique.

Input Specification:

Each input file contains one test case. Each case first gives in a line a positive integer N (≤ 10,000) which is the length of the original string in the shop. Then N positive numbers (≤ 100) are given in the next line, which are the values of the beads -- here we assume that the types of the beads are numbered from 1 to N, and the i-th number is the value of the i-th type of beads. Finally the last line describes the original string by giving the types of the beads from left to right. All the numbers in a line are separated by spaces.

Output Specification:

For each test case, print in a line the total value of the piece of string that Eva wants, together with the beginning and the ending indices of the piece (start from 0). All the numbers must be separated by a space and there must be no extra spaces at the beginning or the end of the line.

Sample Input:

8
18 20 2 97 23 12 8 5
3 3 5 8 1 5 2 1

Sample Output:

66 3 6

 

這一題總覺得之前好像寫過類似的,好像叫做 最長不重複子串 問題。。。

顯然,這一類題和 最長不下降子序列 一樣,求解都應該用我們最喜歡的雙下標法。。。

雙下標法就是設定串的兩個下標b,e(b<=e)(對應begin和end)。在每一個以b為起始,e為結束的子串中,記錄下題目所要求的s值(在本題中s值是最長不重複子串的value),當b=e=n時就遍歷了整個串。。。

對於本題所要求的 不重複子串,可以設定一個vi[]陣列。它的下標是串內所有單個元素的type值,它的值是上一次相同type值的元素在串中出現的位置。這樣每次檢測到元素重複時,都把下標b重新設定成vi[]陣列中的值。

比如,對於串 1 1 3 1 1 3 2 ,它的vi[]陣列的變化過程應該是{-1 1 -1 -1 -1 -1 -1 -1},{-1 1 -1 2 -1 -1 -1 -1},{-1 3 -1 2 -1 -1 -1 -1},{-1 4 -1 2 -1 -1 -1 -1},{-1 4 -1 5 -1 -1 -1 -1},{-1 4 6 5 -1 -1 -1 -1}

(有機會的話,博主可以考慮在bilibili上發一個關於這一題的視訊,博主的bilibili ID就是kircher)【(ಡωಡ)】

 

AC程式碼:

#include<bits/stdc++.h>
using namespace std;
int main()
{
//	freopen("data.txt","r",stdin);
	int n,k;
	scanf("%d",&n);
	vector<int> v,vl;
	vector<int> vi(n+1,-1);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&k);
		v.emplace_back(k);
	}
	int vls=0,b=-1,e=-1,s=0,mb=0,ms=0;
	for(int i=0;i<n;i++)
	{
		scanf("%d",&k);
		vls+=v[k-1];
		vl.emplace_back(vls);
		if(vi[k]>=mb)
		{
			if(s<ms)
			{
				b=mb;
				e=i-1;
				s=ms;
			}
			ms=vls-vl[vi[k]];
			mb=vi[k]+1;
		}
		else
		ms+=v[k-1];
		vi[k]=i;
	}
	if(s<ms)
	{
		b=mb;
		e=n-1;
		s=ms;
	}
	printf("%d %d %d",s,b,e);
    return 0;
}