# Color Space Conversion# Basic Arithmetic# Input/Output

b056 - 1. 影像像素轉換問題

🔗 前往 ZeroJudge 原題

題目描述

題目要求讀取一個 n x n 的影像,每個像素包含紅(R)、綠(G)、藍(B)三個顏色值。根據給定的公式將 RGB 轉換為 XYZ 色彩空間,並輸出每個像素的 X、Y、Z 值。最後計算並輸出所有像素 Y 值的平均值。

解題思路

程式首先讀取影像大小 n。然後,對於每個像素,讀取 R、G、B 值,並使用提供的公式計算 X、Y、Z 值。計算出的 X、Y、Z 值會立即輸出。同時,將所有 Y 值累加起來。在處理完所有像素後,計算 Y 值的平均值,並按照題目要求的格式輸出。程式使用了優化標誌以提高效能。

複雜度分析

  • 時間複雜度: O(n^2),因為需要遍歷 n x n 的影像像素。
  • 空間複雜度: O(1),程式只使用了固定數量的變數,不隨輸入大小變化。

程式碼

#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <iostream>
#include <iomanip>
using namespace std;
inline double read(){
	int a(0);
	char c('0');
	while(c>='0'){
		a=(a<<3)+(a<<1)+c-'0';
		c=getchar_unlocked();
	}
	return a;
}
int main(){
	cin.tie(0); ios::sync_with_stdio(false);
	int t;
	while(t=read()){
		double y,R,G,B,ans(0);
		t*=t;
		for(int i(0);i<t;++i){
			R=read();
			G=read();
			B=read();
			y = 0.2654 * R + 0.6704 * G + 0.0642 * B;
			ans+=y;
			cout  <<  fixed <<  setprecision(4) << 0.5149 * R + 0.3244 * G + 0.1607 * B << " " << y << " " << 0.0248 * R + 0.1248 * G + 0.8504 * B << "\n"; 
		}
		double tt(t);
		ans/=tt;
		cout  <<  fixed <<  setprecision(4) << "The average of Y is " << ans << "\n";
		t=read();
	}
}

Discussion