1. 程式人生 > >PAT-BASIC1090——危險品裝箱

PAT-BASIC1090——危險品裝箱

我的PAT-BASIC程式碼倉:https://github.com/617076674/PAT-BASIC

原題連結:https://pintia.cn/problem-sets/994805260223102976/problems/1038429484026175488

題目描述:

知識點:map集合的應用

思路:按題述程式設計即可

時間複雜度和錄入的資料關係很大,不好分析。空間複雜度是O(N)。

注意點:

在有讀入資料的迴圈中謹慎使用break跳出迴圈,會使後續讀入的資料全部錯位。

C++程式碼:

#include<iostream>
#include<map>
#include<vector>
#include<algorithm>

using namespace std;

int main(){
	int N, M;
	cin >> N >> M;
	
	map<int, vector<int> > incompatibleMap;
	map<int, vector<int> >::iterator it;

	int tempNum1;
	int tempNum2;
	
	for(int i = 0; i < N; i++){
		cin >> tempNum1 >> tempNum2;
		incompatibleMap[tempNum1].push_back(tempNum2);
		incompatibleMap[tempNum2].push_back(tempNum1);
	}
	
	int K;
	int tempNum;
	
	bool flag;
	for(int i = 0; i < M; i++){
		cin >> K;
		vector<int> flagVector;
		flag = true; 
		for(int j = 0; j < K; j++){
			cin >> tempNum;	//If you break from line 43, the remain numbers in this line will be read by next circle.
			if(find(flagVector.begin(), flagVector.end(), tempNum) == flagVector.end()){
				it = incompatibleMap.find(tempNum);
				if(it != incompatibleMap.end()){
					for(int k = 0; k < it->second.size(); k++){
						flagVector.push_back(it->second[k]);
					}
				}
			}else{
				flag = false;
				//break; You can not break from here. 
			}
		}
		if(!flag){
			printf("No\n");
		}else{
			printf("Yes\n");
		}
	}
	
	return 0;
}

C++解題報告: