# 題目 所謂「B2數列」係指一正整數數列 1<= b1 < b2 < b3 ...,其中所有的 bi + bj (i <= j)皆不相等。 您的任務是判別某一數列是否為「B2數列」。 >[>>更多細節請點此](https://zerojudge.tw/ShowProblem?problemid=d123) # 思路 1. 先判斷輸入的測資為 *遞增數列* 2. 如果是遞增數列在計算任兩數和是否皆不相等 3. 運用bool值的判斷找出解 ### 使用工具: 1. *unordered_set* 2. *vector* (也可以改用陣列) ### 理由: 1. 判斷遞增數列我們需要一個容器存下所有數據,並利用一個compare()判斷是否遞增。 (調用compare()函式用意是使的整體架構更清晰) 2. unordered_set 採用hash的算法優化,所以特別適合快速搜尋。 # Code (建議自己嘗試多次後在看!!) ```c++=1 //header.h // // Created by rissun on 2024/9/8. // #ifndef B2_sequence #define B2_sequence #include <iostream> #include <vector> #include <unordered_set> using vec= std::vector<int>; class __Problem{ vec vc; bool compare() { int n; for(int i=1;i<vc.size();++i) if(vc[i-1]>vc[i]) return false; return true; } bool Is_B2() { if(!compare()) return false; using um=std::unordered_set<int>; um ub; for(int i=0;i<vc.size();++i) for(int j=i;j<vc.size();++j){ int sum=vc[i]+vc[j]; if(ub.find(sum)!=ub.end()) return false; ub.insert(sum); } return true; } public:void inputAndSort(int n) { for(int i=0, a;i<n;++i) { std::cin>>a; vc.push_back(a); } } void showAnswer() { static int Case=0; printf("Case #%d: %s",++Case, (Is_B2()?"It is a B2-Sequence.\n" :"It is not a B2-Sequence.\n") ); } }; #endif //B2_sequence ``` ```c++=1 //main.cpp #include "1861 . B2-sequence.h" int main() { int n; while(std::cin>>n) { __Problem _B2_; _B2_.inputAndSort(n); _B2_.showAnswer(); } return 0; } ```