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

 

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