【发布时间】:2019-10-30 15:08:03
【问题描述】:
我编写了一个程序来打印棋盘图案。 它是这样的: (cmets解释逻辑和变量)
#include<iostream>
#include<vector>
#include<string>
#include<fstream>
#include<cstdlib>
using namespace std;
int block_size = 8; //block_size * block_size is the size of each block on the board
int dim = 8; //8 blocks on every row or column, each block containing block_size * block_size pixels
int res = dim * block_size; //total number of pixels is res * res (resolution)
int main(){
int size = 8;
vector<vector<int> > vec(res);
for (int i = 0; i < res; i++) {
vec[i] = vector<int>(res);
for (int j = 0; j < res; j++) {
vec[i][j] = 0;
}
}//initialize all pixels to 0
//int count=0;
/*
allocate black or white pixels based on odd/even status of array indices which are picked
based on multiples of block_size
ex. i,j = 0,4,8,16...
pixels are allocated from the starting point of a particular coordinate like so: two for loops for i,j + d
where 0<=d<block_size
*/
for (int i = 0; i < res; i=i+block_size) {
for (int j = 0; j < res; j=j+block_size) {
//cout<<count<<" ";
//count++;
//cout<<i/block_size;
if (int ((i/block_size)%2 == 0)){
if(int ((j/block_size)%2 == 0)){
for(int k=i;k<i+block_size;k++){
for (int l=j;l<j+block_size;l++){
vec[k][l]=0;
}
}
}
else{
for(int k=i;k<i+block_size;k++){
for (int l=j;l<j+block_size;l++){
vec[k][l]=255;
}
}
}
}
else{
if(int ((j/block_size)%2 == 0)){
for(int k=i;k<i+block_size;k++){
for (int l=j;l<j+block_size;l++){
vec[k][l]=255;
}
}
}
else{
for(int k=i;k<i+block_size;k++){
for (int l=j;l<j+block_size;l++){
vec[k][l]=0;
}
}
}
}
}
}
cout<<endl;
/*
for (int i = 0; i < size; i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
*/
string filename = "chessboard.pgm";
ofstream pgmFile(filename);
pgmFile << "P2" << endl;
pgmFile << res << " " << res << endl;
pgmFile << 255 << endl;
for(int i=0;i<res;i++){
for(int j=0;j<res;j++){
pgmFile << vec[i][j] << " ";
}
pgmFile << endl;
}
pgmFile.close();
return 0;
}
程序的输出被输入到一个pgm图像中,然后写入一个文件中查看,(Irfanview可以用来查看pgm图像)。
算法如下:
--根据选取的数组索引的奇/偶状态分配黑色或白色像素
基于 block_size 的倍数
前任。 i,j = 0,4,8,16...
--pixels 从特定坐标的起点分配:2 for 循环 for i,j + d 其中 d 范围从 0 到 block_size,不包括 block_size
现在,看起来复杂度是 O(n^4)。关于我可以采取哪些步骤来降低复杂性的任何想法?
【问题讨论】:
-
欢迎来到 SO!我不太明白这是 O(n^4)。这里是什么?如果您访问每个像素一次或两次,那么我看不出您如何期望对此有任何复杂性改进。
-
嗨,我的意思是输入的大小。是的,这是真的,每个像素只被访问一次或两次,但我想也许有一种比我使用的算法更有效的算法。
-
不,不是 O(N^4)。由于您必须访问每个像素固定的次数,并且您已经访问了每个像素固定的次数,因此您无法提高复杂度。不过,您也许可以提高效率。效率不等于复杂性。
标签: c++ algorithm optimization time-complexity