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;
}

猜你喜欢

转载自blog.csdn.net/baidu_37550206/article/details/85537846