平均池化問題

題目描述

給定一個 n×n 的整數矩陣,其中 n 為偶數且介於4到20之間。你的任務是對這個矩陣進行 2x2 的平均池化操作。

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

輸入格式

第一行包含一個整數 n,表示矩陣的大小。
接下來的 n 行,每行包含 n 個整數,代表矩陣中的元素。

輸出格式

對於每個 2x2 的子矩陣,輸出其元素的平均值,結果保留兩位小數。每個平均值後跟一個空格,每行輸出的平均值數量應與輸入矩陣的列數 n/2 相匹配。

範例輸入1

4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

範例輸出1

3.50 5.50 
11.50 13.50 

範例輸入2

4
12 20 30 0
8 12 2 0
34 70 37 4
112 100 25 12

範例輸出2

13.00 8.00 
79.00 19.50 

範例輸入3

6
10 2 0 12 1 3
21 0 13 2 2 0
0 0 0 10 0 0
19 2 0 13 61 1
0 1 32 3 0 2
9 2 0 31 11 0

範例輸出3

8.25 6.75 1.50 
5.25 5.75 15.50 
3.00 16.50 3.25 

解答

#include <iostream> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<vector<int>> matrix(n, vector<int>(n)); // 讀取矩陣 for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) cin >> matrix[i][j]; // 進行平均池化 for (int i = 0; i < n; i += 2) { for (int j = 0; j < n; j += 2) { double avg = (matrix[i][j] + matrix[i][j+1] + matrix[i+1][j] + matrix[i+1][j+1]) / 4.0; printf("%.2f ",avg); } printf("\n"); } return 0; }