题目链接
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
思路:一开始也愣是没有读懂样例,来解释一下样例,找出最长的含有不重复元素的序列,头为4,尾为7(ans=a【8】+a【1】+a【5】+a【2】),感觉这是pat的套路啊。所以最后就变成了求最长的含有不重复元素的序列,我们其实可以求解出1-i的字符串的最长连续的含有不重复元素序列的长度,至于最大值的和可以通过前缀和很快判断出来,那么怎么求最长长度呢,我们记录一个变量last表示上一个变化的位置,如果数字i上一次出现的位置小于last,那么last就要更新为当前的位置,否则的话dp【i】都为i-last+1。
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e4+1;
vector<int>v[maxn];
int n,last,a[maxn],dp[maxn],num[maxn],now[maxn],sum[maxn];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%d",&a[i]);
for(int i=1;i<=n;++i)
{
scanf("%d",&num[i]);
}
for(int i=1;i<=n;++i) v[i].push_back(0);
for(int i=1;i<=n;++i)
v[num[i]].push_back(i),now[num[i]]=1;
dp[1]=last=1;now[num[1]]++;
for(int i=2;i<=n;++i)
{
if(i==v[num[i]][now[num[i]]]&&last>v[num[i]][now[num[i]]-1]) dp[i]=i-last+1;
else if(i==v[num[i]][now[num[i]]]) dp[i]=i-v[num[i]][now[num[i]]-1],last=v[num[i]][now[num[i]]-1]+1;
else dp[i]=i-last+1;
now[num[i]]++;
}
int ans=0,maxx=0,k1,k2;
for(int i=1;i<=n;++i)
sum[i]=sum[i-1]+a[num[i]],maxx=max(maxx,dp[i]);
for(int i=1;i<=n;++i)
{
if(dp[i]==maxx)
{
if(sum[i]-sum[i-dp[i]]>ans) ans=sum[i]-sum[i-dp[i]],k1=i-dp[i]+1,k2=i;
}
}
printf("%d %d %d\n",ans,k1-1,k2-1);
}