題目地址:1021. Couples
思路:
想清楚了這道題其實很簡單。利用夫妻出現的位置作為下標,並設為同一值,第一對夫妻值為1,第二對為2,以此類推,存儲完畢即可進入下一步。
利用棧這個數據結構:遍歷這個數組,當棧不為空且棧頂元素等於數組出現的元素時,pop掉棧頂元素,其余情況則入棧。循環完畢,若棧為空則為Yes,否則為No。
具體代碼如下:
1 #include <iostream>
2 #include <stack>
3 using namespace std;
4
5 int main() {
6 int num;
7 while (cin >> num && num) {
8 int *store = new int[num*2+1];
9 for (int i = 1; i <= num; i++) {
10 int a, b;
11 cin >> a >> b;
12 store[a] = store[b] = i;
13 }
14 stack<int> st;
15 for (int i = 1; i <= num*2; i++) {
16 if (!st.empty() && st.top() == store[i]) {
17 st.pop();
18 }
19 else {
20 st.push(store[i]);
21 }
22 }
23 st.empty() ? cout << "Yes\n" : cout << "No\n";
24 }
25
26 return 0;
27 }