zoj 1067 Color Me Less

正确代码:

#include <iostream>
#include<vector>
#include<math.h>
using namespace std; 

int main() {
	int tar[16][3];
	for(int i=0;i<16;i++)
		for(int j=0;j<3;j++)
			cin >> tar[i][j];
	int color[100][3]={0};
	int m=0,n=0,count=0;
	while(cin >> color[m][n]){
		if(color[m][0]==-1&&color[m][1]==-1&&color[m][2]==-1)
			break;
		n++;
		if(n==3){
			n=0;
			m++;
			count++;
		}
	}
	
	vector<int>D(count);
	vector<int>m_num(count);
	int temp;
	for(int i=0;i<count;i++){
		D[i]=10000; //max
		for(int p=0;p<16;p++){
			temp=sqrt(
				 pow(color[i][0]-tar[p][0],2)+
				 pow(color[i][1]-tar[p][1],2)+
				 pow(color[i][2]-tar[p][2],2));
			if(temp<D[i]){
				D[i]=temp;
				m_num[i]=p;
			} 
		}
	} 
	
	for(int i=0;i<count;i++) 
			cout << "(" << color[i][0] << "," 
				 << color[i][1] << "," 
				 << color[i][2] << ") maps to ("
				 << tar[m_num[i]][0] << ","
				 << tar[m_num[i]][1] << ","
				 << tar[m_num[i]][2] << ")" <<endl;

	return 0;
}

分析:

每次都在输出格式上磕绊,这次又是少一个空格...

简单题,mark一下是因为我才发现acm在线检查的时候每输入一次输出一次这样写也是可以的。如此一来可以极大地简化代码,至少使得数据处理的部分数组少用一维,for循环少嵌套一次。

同时在一维二维多维数组初始化的问题上还是有些模糊,主要在于“menset”,“mencpy”,“={0}”这三者之间的区别。

首先要知道一个变量被创建时,全局变量通常为0,局部变量的值是不确定的。

“={0}”与“menset”的效果是一样的,“={0}”还稍微快一些,但”={N}“并不是将数组所有元素置为N,而是仅仅将第一个元素置为N,而”menset“可以实现将所有元素置为N。

”menset“与”mencpy“的效果相同,区别在于前者是赋值操作,后者是复制操作。

此程序可提高的地方还有以下几点:

1、更好的可读性

typedef struct
{
	int r;
	int g;
	int b;
} Color;
2、可放到一起的放到一起

while(std::cin>>r>>g>>b&&r!=-1&&g!=-1&&b!=-1)  

3、可以不使用math.h就别用

temp=(map[i].r-r)*(map[i].r-r)+
     (map[i].g-g)*(map[i].g-g)+
     (map[i].b-b)*(map[i].b-b);


附:

#include <iostream>

typedef struct
{
	int r;
	int g;
	int b;
} Color;

int main(int argc, char* argv[])  
{  
	int min,i,j,temp;
	int r,g,b;
	Color map[16];
	for(i=0;i<16;++i)
		std::cin>>map[i].r>>map[i].g>>map[i].b;
	while(std::cin>>r>>g>>b&&r!=-1&&g!=-1&&b!=-1)
	{
		min=-1;
		j=-1;
		for(i=0;i<16;++i)
		{
			temp=(map[i].r-r)*(map[i].r-r)+
				(map[i].g-g)*(map[i].g-g)+
				(map[i].b-b)*(map[i].b-b);
			if(min<0||min>temp)
			{
				min=temp;
				j=i;
			}
		}
		std::cout<<"("<<r<<","<<g<<","<<b<<") maps to ("
			<<map[j].r<<","<<map[j].g<<","<<map[j].b<<")"<<std::endl;
	}
	
	return 0;
}  



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值