题目链接:http://poj.org/problem?id=2926
这个题目是看算法合集之《浅谈信息学竞赛中的“0”和“1”》后做的,二进制思想的经典应用
具体如下
(x1-x2) + (y1-y2), (x1-x2) + (y2-y1), (x2-x1) + (y1-y2), (x2-x1) + (y2-y1)
变形下:
(x1+y1) - (x2+y2), (x1-y1) - (x2-y2), (-x1+y1) - (-x2+y2), (-x1-y1) - (-x2-y2)
上面是二维的情况,多维也一样,我们只要枚举符号,一共5维就32种情况,选取
每种情况的最大值和最小值,最终就能求出最优解,复杂度接近O(n)
#include <string.h>
#include <algorithm>
#include <iostream>
#include <stdio.h>
using namespace std;
const double eps=1e12;
const int maxn = 101000;
double rec[maxn][5];
int n;
int main(){
int i,j,k;
double ans,now,MIN,MAX;
while(scanf("%d",&n)!=EOF){
for(i=0;i<n;i++)
for(j=0;j<5;j++){
scanf("%lf",&rec[i][j]);
}
ans=-eps;
for(i=0;i<32;i++){
MIN=eps,MAX=-eps;
for(j=0;j<n;j++){
now=0;
for(k=0;k<5;k++){
if(i&(1<<k)) now+=rec[j][k];
else now-=rec[j][k];
}
MIN=min(MIN,now);
MAX=max(MAX,now);
}
ans=max(ans,MAX-MIN);
}
printf("%.2lf\n",ans);
}
return 0;
}