# Array# String# Iteration

d710 - parking lot

🔗 前往 ZeroJudge 原題

題目描述

題目要求模擬一個停車場,停車場中有若干輛車,每輛車都有廠牌和顏色。程式需要讀取車輛的廠牌和顏色,然後根據輸入的查詢條件(廠牌或顏色)輸出符合條件的車輛資訊。

解題思路

這題的核心是根據查詢條件在車輛資料中進行搜尋。程式首先讀取車輛的數量和查詢次數,然後讀取每輛車的廠牌和顏色,儲存在一個車輛陣列中。接著,程式迴圈讀取查詢條件,判斷查詢條件是根據廠牌還是顏色進行查詢,然後遍歷車輛陣列,找出符合條件的車輛,並輸出其廠牌和顏色。

複雜度分析

  • 時間複雜度: O(n*m),其中 n 是車輛數量,m 是查詢次數。因為對於每次查詢,都需要遍歷整個車輛陣列。
  • 空間複雜度: O(n),因為需要儲存所有車輛的資訊。

程式碼

#include <iostream>
#include <string>
using namespace std;
struct car{
	string brand;
	string color;
};
int main(){
	int a,b;
	while(cin >> a >> b){
		car c[a];
		string cc,d;
		for(int i=0;i<a;i++)
			cin >> c[i].brand >> c[i].color;
		while(b--){
			cin >> cc >> d;
			if(cc=="brand")
				for(int i=0;i<a;i++)
					if(c[i].brand==d)
						cout << c[i].brand << " " << c[i].color << "\n";
			else
				for(int i=0;i<a;i++)
					if(c[i].color==d)
						cout << c[i].brand << " " << c[i].color << "\n";
		}
	}
}

Discussion