有多少个3*3的矩阵的每一行之和每一列之和等于k,t次询问,用c++代码实现
时间: 2024-06-01 11:12:16 浏览: 14
题目描述
有多少个3*3的矩阵的每一行之和每一列之和等于k,t次询问。
输入格式
第一行一个整数t,表示询问次数。
接下来t行,每行一个整数k,表示询问矩阵每行每列之和的值。
输出格式
对于每个询问,输出一个整数,表示满足条件的3*3矩阵的数量。
数据范围
1≤t≤100
−1000≤k≤1000
样例
输入样例:
3
0
4
-4
输出样例:
1
20
20
C++ 代码
相关问题
C++代码实现,有多少个3x3矩阵的每一行之和、每一列之和都等于R?C++代码实现
以下是C语言代码实现:
```c
#include <stdio.h>
#define N 3 //矩阵的大小
#define R 15 //要求每行、每列之和等于R
int main(){
int matrix[N][N]; //定义矩阵
int count = 0; //计数器,记录符合要求的矩阵数量
//生成所有可能的矩阵
for(int i=1; i<=9; i++){
for(int j=1; j<=9; j++){
for(int k=1; k<=9; k++){
for(int l=1; l<=9; l++){
for(int m=1; m<=9; m++){
for(int n=1; n<=9; n++){
for(int o=1; o<=9; o++){
for(int p=1; p<=9; p++){
for(int q=1; q<=9; q++){
matrix[0][0] = i; //填充矩阵
matrix[0][1] = j;
matrix[0][2] = k;
matrix[1][0] = l;
matrix[1][1] = m;
matrix[1][2] = n;
matrix[2][0] = o;
matrix[2][1] = p;
matrix[2][2] = q;
//检查每行、每列之和是否等于R
int flag = 1; //标志位,表示符合要求
for(int x=0; x<N; x++){
int sum_row = 0; //每行之和
int sum_col = 0; //每列之和
for(int y=0; y<N; y++){
sum_row += matrix[x][y]; //计算每行之和
sum_col += matrix[y][x]; //计算每列之和
}
if(sum_row != R || sum_col != R){ //如果有行或列之和不等于R
flag = 0; //标志位置为0
break; //跳出循环
}
}
if(flag == 1){ //如果符合要求
count++; //计数器加1
}
}
}
}
}
}
}
}
}
}
printf("符合要求的矩阵数量为:%d\n", count);
return 0;
}
```
该代码使用了6层嵌套循环来生成所有可能的3x3矩阵,然后检查每个矩阵的每行、每列之和是否等于R,如果符合要求,计数器加1。最后输出符合要求的矩阵数量。由于嵌套循环层数较多,时间复杂度较高,不适用于大规模的矩阵计算。
题目描述 有多少个3*3的矩阵的每一行之和每一列之和等于k,t次询问。 输入格式 第一行一个整数t,表示询问次数。 接下来t行,每行一个整数k,表示询问矩阵每行每列之和的值。 输出格式 对于每个询问,输出一个整数,表示满足条件的3*3矩阵的数量。用c++代码编写出代码
#include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int k;
cin >> k;
int ans = 0;
for (int i = 1; i <= min(k, 9); i++)
{
for (int j = 1; j <= min(k, 9); j++)
{
int x = k - i - j;
if (x <= 0 || x > 9) continue;
ans += 1;
}
}
cout << ans << endl;
}
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)