Codeforces Round #462 (Div. 2) A. A Compatible Pair

A. A Compatible Pair
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.

Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a1, a2, ..., an, and Banban's have brightness b1, b2, ..., bm respectively.

Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.

Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.

You are asked to find the brightness of the chosen pair if both of them choose optimally.

Input

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50).

The second line contains n space-separated integers a1, a2, ..., an.

The third line contains m space-separated integers b1, b2, ..., bm.

All the integers range from  - 109 to 109.

Output

Print a single integer — the brightness of the chosen pair.

Examples
input
Copy
2 2
20 18
2 14
output
252
input
Copy
5 3
-1 0 1 2 3
-1 0 1
output
2
Note

In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.

In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.

刚开始的想法有错误,认为就两组灯笼sort排序一下。然后最大的就是第一组最大乘第二组最大或第一组最小乘第二组最小。后来发现问题。比如第一组 1 2 3,第二组 -3 -2  那按照我的想法得到的是-6,其实是-4,因为这组要交叉相乘才会最大。实际上是去个头部的,考虑剩下最大的可能性(匹配方式为交叉或平行),再考虑去个尾部的,考虑可能性(匹配方式为交叉或平行)复杂度 O(nlogn+mlogm)


#include <iostream>
#include <algorithm>
using namespace std;
long long a[55],b[55];
int main() {
    int n,m;
    cin>>n>>m;
    for (int i=1; i<=n; i++) {
        cin>>a[i];
    }
    for (int i=1; i<=m;i++) {
        cin>>b[i];
    }
    sort(a+1, a+1+n);
    sort(b+1, b+1+m);
        cout<<min(max(max(a[1]*b[1], a[n-1]*b[m]),max(a[1]*b[m], a[n-1]*b[1])), max(max(a[2]*b[1], a[n]*b[m]), max(a[2]*b[m], a[n]*b[1])))<<endl;
    return 0;
}



第二总做法是记录一下最大值,第二次找的时候不要去管产生最大的那个第一组有关的乘积就可以了 复杂度O(2*n*m)



n,m=raw_input().split()
n=int(n);m=int(m)
a=raw_input().split()
b=raw_input().split()
a=[int(x)for x in a]
b=[int(x)for x in b]
a.sort();b.sort()
mmax=-1e19;t=0
for i in range(n):
    for j in range(m):
        if a[i]*b[j]>mmax:
            mmax=a[i]*b[j]
            t=i
mmax=-1e19
for i in range(n):
    for j in range(m):
        if (a[i]*b[j]>mmax)&(i!=t):
            mmax=a[i]*b[j]
print mmax


猜你喜欢

转载自blog.csdn.net/aaakirito/article/details/79333084