D - 最大值
Problem Description
There are n integers a[0], a[1], ..., a[n-1], your task is to find two integers L, R(0 <= L < R <= n-1) that make the
value (a[L] - a[R])^2 maximized(最大化).
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases.
Each case starts with a line containing a integer n(2 <= n <= 100,000).
The next line contains n space-separated elements ai (0 <= i <= n-1), and the absolute value(绝对值) of ai is not exceed 1,000,000.
Output
For each case, you need to print 3 space-separated number L, R and the value (a[L] - a[R])^2 in a single line. And the problem ensure that the solution is unique.
Sample Input
3 5 1 8 -5 1 74 7 21 41 -66 13 999 -50 1111 9 20 12 12 22 18 29 30 -42 -999999
Sample Output
2 4 6241 2 6 1385329 6 8 1000058000841
需要注意的就是数据的存储问题,需要考虑溢出的可能,当初我就是没有考虑的全面,计算时有 sum=(min-max)*(min-max)(long long sum; int min,max;) 结果计算后就会有溢出的情况,因为是想计算出(min-max)*(min-max)类型还是int,然后再把值赋给long long类型的sum,所以sum存储的是溢出后的值
有的计算机不能接受long long,可以试着把long long 改成 _int64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
/*
* this code is made by 1406100108
* Problem: 1355
* Verdict: Accepted
* Submission Date: 2015-04-14 20:53:42
* Time: 372 MS
* Memory: 1916 KB
*/
#include<iostream>
#include<cstring>
using
namespace
std;
int
main()
{
unsigned
int
T,n;
int
i;
int
minp,maxp;
long
long
sum,max,min; //注意类型是long long
cin>>T;
if
(T>0&&T<=20)
while
(T--)
{
int
*p;
cin>>n;
min=1000000; //由于知道数据的范围,可赋予min,max一个极限的值
max=-1000000;
if
(n<2||n>1000000)
break
;
p=
new
int
[n]; //动态分配长度为n的空间
for
(i=0;i<n;++i)
{
cin>>p[i];
if
(p[i]<-1000000||p[i]>1000000)
break
;
}
for
(i=0;i<n;++i)
{
if
(min>=p[i]) //寻找并记录记录最小值和对应下标
{
min=p[i];
minp=i;
}
if
(max<=p[i]) //寻找并记录记录最大值和对应下标
{
max=p[i];
maxp=i;
}
}
// cout<<minp<<'\t'<<maxp<<endl;
// cout<<min<<'\t'<<max<<endl;
sum=(min-max)*(min-max);
if
(minp<maxp)
{
cout<<minp<<
" "
<<maxp<<
" "
<<sum<<endl;
}
if
(minp>maxp)
{
cout<<maxp<<
" "
<<minp<<
" "
<<sum<<endl;
}
delete
[]p;
}
return
0;
}
|