Sicily 1021. Couples

题目地址: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 }

 

posted @ 2014-11-19 23:49  winray  阅读(249)  评论(0编辑  收藏  举报