1026 String of Colorful Beads (35 分)(C )

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

题目大意:给出n,第二行给出颜色1-n的价值,第三行给出原有序列。求原序列的最长不重复序列,如果有两个不重复子序列一样长,则取总价值最大的那个。

解题思路:双指针法,用pos数组记录当前指针p, q之间出现的颜色对应的位置。当q到达pos已有记录的颜色,则移动p至上一次出现该颜色的地方,在移动过程中要将p经过的位置的颜色的对应pos改为-1。

代码:

#include <bits/stdc++.h>
using namespace std;
int main(){
	int n;
	scanf("%d", &n);
	vector<int>value(n+1), bead(n), pos(n+1, -1);
	for(int i = 1; i <= n; ++ i)
		scanf("%d", &value[i]);
	for(int i = 0; i < n; ++ i)
		scanf("%d", &bead[i]);
	int p = 0, q = 0, ans = 0, ans_p, ans_q, temp = 0;
	while(q < n){
		while(q < n && pos[bead[q]] == -1){
			temp += value[bead[q]];
			pos[bead[q]] = q;
			++ q;
		}
		if(temp > ans){
			ans = temp;
			ans_p = p;
			ans_q = q - 1;
		}
		while(q < n && p <= pos[bead[q]]){
			pos[bead[p]] = -1;
			temp -= value[bead[p]];
			++ p;
		}
	}
	printf("%d %d %d", ans, ans_p, ans_q);
}

 

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