题目描述
A color reduction is a mapping from a set of discrete colors to a smaller one.The solution to this problem requires that you perform just such a mapping in a standard twenty-four bit RGB color space. The input consists of a target set of sixteen RGB color values, and a collection of arbitrary RGB colors to be mapped to their closest color in the target set. For our purposes, an RGB color is defined as an ordered triple (R, G, B) where each value of the triple is an integer from 0 to 255. The distance between two colors is defined as the Euclidean distance between two three-dimensional points. That is, given two colors ( R1, G1, B1) and ( R2, G2, B2), their distance D is given by the equation.
输入
The input file is a list of RGB colors, one color per line, specified as three integers from 0 to 255 delimited by a single space. The first sixteen colors form the target set of colors to which the remaining colors will be mapped. The input is terminated by a line containing three `-1' values.
输出
For each color to be mapped, output the color and its nearest color from the target set.
题目解说:
输入16组三维坐标,再输入一点坐标,请输出这一点和16个点的中距离最近的点;输入的数据以-1,-1,-1为输入结束标志。解题思路:
这题宏观来看的话,我们只是在找16个结果中的最小值。因为开方后有误差,所以我们不必开方。
在找最短距离的时候,我们选择的是交换法:先将第一个结果作为最小值,一旦发现以后的结果比自己小,就交换。这样我们对于每组数据都要进行16次操作。
这道题有一个隐藏的bug就是没考虑一旦存在两个距离最近数据的时候要怎么处理,这种情况题目并没有完全说明。代码:
#include <iostream>
#include <cstdio>
#define N 16
using namespace std;
int a[N][3]; //存16个三位数组
void panduan(int x,int y,int z){ //判断是否为最短距离点
long min=-1,sum2;
int t=0;
for(int j=0;j<N;j++){
sum2=(x-a[j][0])*(x-a[j][0])+(y-a[j][1])*(y-a[j][1])+(z-a[j][2])*(z-a[j][2]);
if(min<0||sum2<min){
min=sum2;
t=j;
}
}
printf("(%d,%d,%d) maps to (%d,%d,%d)\n",x,y,z,a[t][0],a[t][1],a[t][2]);
}
int main(){
for(int i=0;i<N;i++){
scanf("%d %d %d",&a[i][0],&a[i][1],&a[i][2]);
}
int m,n,l;
int t;
cin>>m>>n>>l;
while(m!=-1&&n!=-1&&l!=-1){ //判断是否为文件结束的标志
panduan(m,n,l);
cin>>m>>n>>l;
}
return 0;
}
代码改善:
为了处理那个隐藏的bug,我们做了如下改善:
#include <iostream>
#include <cstdio>
#define N 16
const int maxn=255*255*255;
using namespace std;
int a[N][3]; //存16个三位数组
int f[maxn][N]={0};
void panduan(int x,int y,int z){ //判断是否为最短距离点
long min=-1,sum2;
int t=0;
for(int j=0;j<N;j++){
sum2=(x-a[j][0])*(x-a[j][0])+(y-a[j][1])*(y-a[j][1])+(z-a[j][2])*(z-a[j][2]);
f[sum2][j]++;
if(min<0||sum2<min){
min=sum2;
t=j;
}
}
for(int j=0;j<N;j++){
if(f[][t]!=0){
printf("(%d,%d,%d) maps to (%d,%d,%d)\n",x,y,z,a[t][0],a[t][1],a[t][2]);
}
}
}
int main(){
for(int i=0;i<N;i++){
scanf("%d %d %d",&a[i][0],&a[i][1],&a[i][2]);
}
int m,n,l;
int t;
cin>>m>>n>>l;
while(m!=-1&&n!=-1&&l!=-1){ //判断是否为文件结束的标志
panduan(m,n,l);
cin>>m>>n>>l;
}
return 0;
}
小提醒:
1.大家在存三位坐标的时候不一定要开创三个数组来存,一个二维数组就解决了。
2.一般在交换法中找最小的时候,也不一定要令第一个数据为最小值,我们可以使用上述的方法。
3.大家以后在处理距离问题时,可以不用开方,一般我们开方后都会选择以double的类型来存储,这会使得比较过程中有误差,最好不要选择这种方法。