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

暴力法解决,这道题题目难读懂,看了半个小时才明白什么意思。。就是求最大连续子串和,不能有重复的。

例如样例最大不重复和8152,left=3,right=6 。max ans=v[8]+v[1]+v[5]+v[2]=66

拿了29分,希望有同学可以指出如何AC。

#include <iostream>
#include <algorithm>
#include <string.h>
#include <map>
#include <vector>
using namespace std;
int ans,temp;
int l,r;


int main(){
	int n,left,right,j;
	cin>>n;
	
	int v[n],t[n];
	for(int i=1;i<=n;i++){
		cin>>v[i];	
	}
	for(int i=0;i<n;i++){
		cin>>t[i];
	}
	
	for(int i=0;i<n;i++){
		bool b[n+1] = {false};
		b[t[i]] = true;
		 temp = v[t[i]];
		
		for( j=i+1;j<n;j++){
			if(b[t[j]]==true) {
				j--;
				break;
			}
			b[t[j]]=true;
			 temp+=v[t[j]];	
		}
		if(temp>ans){
			ans = temp;
			left = i;
			right=j;
		}
	}
cout<<ans<<" "<<left<<" "<<right;
	return 0;
	
}

猜你喜欢

转载自blog.csdn.net/qq_36671300/article/details/85524891