Largest Point
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1365 Accepted Submission(s): 535
Problem Description
Given the sequence
A
with
n
integers
t1,t2,⋯,tn
. Given the integral coefficients
a
and
b
. The fact that select two elements
ti
and
tj
of
A
and
i≠j
to maximize the value of
at2i+btj
, becomes the largest point.
Input
An positive integer
T
, indicating there are
T
test cases.
For each test case, the first line contains three integers corresponding to n (2≤n≤5×106), a (0≤|a|≤106) and b (0≤|b|≤106) . The second line contains n integers t1,t2,⋯,tn where 0≤|ti|≤106 for 1≤i≤n .
The sum of n for all cases would not be larger than 5×106 .
For each test case, the first line contains three integers corresponding to n (2≤n≤5×106), a (0≤|a|≤106) and b (0≤|b|≤106) . The second line contains n integers t1,t2,⋯,tn where 0≤|ti|≤106 for 1≤i≤n .
The sum of n for all cases would not be larger than 5×106 .
Output
The output contains exactly
T
lines.
For each test case, you should output the maximum value of at2i+btj .
For each test case, you should output the maximum value of at2i+btj .
Sample Input
2 3 2 1 1 2 3 5 -1 0 -3 -3 0 3 3
Sample Output
Case #1: 20 Case #2: 0
贪心类型题目要注意这样的一点:贪心就要贪到位。一开始做这个题目的时候想的是对t【】排序,然后对a,b的状态分类讨论,分>0 <0 =0一共九种去讨论,讨论讨论就发现问题了,很多地方不能贪到位,需要很多复杂的步骤,虽然超时的问题避免了,但是WA的问题却是很难避免。这里欠缺了思考,自愧不如。
这里正确简洁的贪心思想是这样的:
用两个结构体来分别记录 a*t^2和b*t的值,然后对每一个值都赋予一个num表示下标,然后对两个结构体排序。如果两者的最大值num下标不同,那么加一起就是结果、否则要比较a次大和b最大加和以及a最大和b次大加和、选择大的输出。
这里思路清晰了直接上代码:
注意这里数据比较大,用long long,杭电应用I64输入。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define ll long long int
struct date
{
ll date,num;
}aa[1000005],bb[1000005];
ll t[1000005];
int cmp(date a,date b)
{
return a.date<b.date;
}
int main()
{
int T;
int kase=0;
scanf("%d",&T);
while(T--)
{
ll n,a,b;
scanf("%I64d%I64d%I64d",&n,&a,&b);
for(int i=0;i<n;i++)
{
scanf("%I64d",&t[i]);
aa[i].date=a*t[i]*t[i];
bb[i].date=b*t[i];
aa[i].num=i;bb[i].num=i;
}
sort(aa,aa+n,cmp);
sort(bb,bb+n,cmp);
if(aa[n-1].num!=bb[n-1].num)
{
printf("Case #%d: %I64d\n",++kase,aa[n-1].date+bb[n-1].date);
}
else
{
ll output=max(aa[n-2].date+bb[n-1].date,aa[n-1].date+bb[n-2].date);
printf("Case #%d: %I64d\n",++kase,output);
}
}
}