在C++
中,有可能从文件中读取NxN
矩阵样式输入并将其分配给二维数组,其时间渐近复杂度优于O(n^2)
,假设N
在第一行中给出,而其他行在整数之间有空格?我可以逐个填充我的数组遍历输入整数,其成本为O(n^2)
。
#define MAX_SIZE 1000
std::string row,temp;
std::ifstream inpfile("input.txt");
inpfile>>row;
int size=std::stoi(row);
static int M[MAX_SIZE][MAX_SIZE];
for(int i=0;i<size;++i){
for(int j=0;j<size;++j){
inpfile>>temp;
A[i][j]=std::stoi(temp);
}
}
我只是想像读取nth line
并创建数组(或某个容器)的nth row
,这将减少linear time
的时间复杂度。是否有任何实现比迭代给定矩阵的所有元素更好?
循环通过O(N)的答案,其中N是一个int,但是就线而言,无论如何,你总是有O(N ^ 2)。也许这是您可以拥有的最接近的解决方案。
int temp;
int countX = 0;
while(inFile >> temp)
{
A[countX/size][countX % size] = std::stoi(temp);
countX++;
}
我希望这有帮助。