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

PAT顶级题解目录​​​​​​​

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值