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

题意分析:
给定一个整数n,代表原始珠串的长度,接下来一行给出每种珠子的价值,再接着一行给出原始珠串的排列,要求找出一串序列没有重复的珠子并且价值最大。这个题是真的不难,读懂题意花了我不少时间,一开始一直在找eva要的原始珠串,是包含所有颜色的珠串

Eva needs your help to tell her how to obtain the longest piece of string that contains beads with all different colors.

感觉题目翻译的不是很准确,eva要的珠串其实只是没有重复珠串且拥有最大价值的片段,并没有包含全部颜色。

算法:
滑动窗口/双指针 一个右指针一直往右移动,增加窗口内的珠串数量和价值,然后判断窗口内的珠串是否重复,如果重复,左指针向右移动收缩窗口。移动完成就是一个满足条件的窗口,再与最大价值比较,更新最大价值和左右端点。

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n, a,max_=INT_MIN,sum=0;
	pair<int, int>ret;
	cin >> n;
	vector<int>value(n), original(n), table(n+1);
	for (int i = 0; i < n; i++)
		cin >> value[i];
	for (int i = 0; i < n; i++)
		cin >> original[i];
	for (int l = 0, r = 0; r < original.size(); r++){
		table[original[r]]++;
		sum += value[original[r] - 1];
		while (table[original[r]] > 1){
			table[original[l]]--;
			sum -= value[original[l++] - 1];
		}
		if (sum > max_){
			max_ = sum;
			ret = { l,r };
		}
	}
	cout << max_ << " " << ret.first << " " << ret.second;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值