EOJ2183. Minimum Scalar Product

该博客讨论了EOJ2183问题,涉及如何找到两个向量在允许坐标排列变化情况下的最小标量积。通过递增排序一个向量和递减排序另一个向量来简化计算,以降低时间复杂度到O(n log n),并避免整数溢出。内容包含了输入输出格式说明及样例解析。
摘要由CSDN通过智能技术生成

单点时限: 2.0 sec

内存限制: 256 MB

You are given two vectors v1=(x1,x2,…,xn) and v2=(y1,y2,…,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+…+xnyn.

Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.

输入格式

The first line of the input file contains integer number T - the number of test cases. For each test case, the first line contains integer number n. The next two lines contain n integers each, giving the coordinates of v1 and v2 respectively.

T = 10

100 ≤ n ≤ 800

-100000 ≤ xi, yi ≤ 100000

输出格式

For each test case, output a line

Case #X: Y

where X is the test case number, starting from 1, and Y is the minimum scalar product of all permutations of the two given vectors.

样例

input

2
3
1 3 -5
-2 4 1
5
1 2 3 4 5
1 0 1 0 1

output

Case #1: -25
Case #2: 6
#include <iostream>
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
class SingleJob{
public:
	int dim;
	vector<long long> vecA; 
	vector<long long> vecB;
};
int main() {
    int jobs, temp;
    SingleJob J[10];
    // 输入
    cin >> jobs;
	for(int i=0;i<jobs;i++){
		cin >> J[i].dim;
		for(int j=0;j<J[i].dim;j++){
			cin >> temp;
			J[i].vecA.insert(J[i].vecA.end(), temp);
		}
		for(int j=0;j<J[i].dim;j++){
			cin >> temp;
			J[i].vecB.insert(J[i].vecB.end(), temp);
		}
	}
	// 输出。注意结果dotpdt是两个int型相乘,需要用longlong定义
	long long dotpdt=0;
	for(int i=0;i<jobs;i++){
		sort(J[i].vecA.begin() , J[i].vecA.end());
		sort(J[i].vecB.rbegin(), J[i].vecB.rend());
		
		for(int j=0;j<J[i].dim;j++){
			dotpdt += J[i].vecA[j] * J[i].vecB[j];
		}
		cout << "Case #" << i+1 << ": " << dotpdt << endl;
		dotpdt = 0;
	}
	return 0;
} 

ps:假设维度是n,让A、B生成全排列然后暴力解的时间复杂度是O(n^2)。注意到最小点积可以是 “让每个vecA最大的数 × vecB最小的数” 从而简化运算。

因此本例将vecA递增排序、vecB递减排序,最后求出每个job对应的点积 dotpdt 并输出。

另外,本题与 EOJ3003. 最小向量点积 的不同之处在于vectorA和vectorB 的范围扩大了,导致的点积结果可能超过int所表示的范畴

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值