Sicily 1021. Couples (栈)

题目:http://soj.me/1021

  很好的启蒙题

  n对夫妇站成一个圈将相邻的夫妇取出 若全部夫妇均能取出 输出Yes 否则输出No

思路:将夫妇从编号1到2n的夫妇分别压入栈,如果栈顶的夫妇和即将压入的夫妇相同,则退栈。若最后全部夫妇退栈 输出Yes

   其中用了一个 arr[a] = b;arr[b] = a;的方法来记录夫妇的状态

   还不会用c++的stack,就用数组模拟了一个

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int arr[200000];
int stack[200000];

int main()
{
    while(1)
    {
        int n;
        cin>>n;
        if(n==0) break;
        for (int i = 0; i < n; i++)
        {
            int a,b;
            cin >> a >> b;
            arr[a] = b;
            arr[b] = a;
        }
        int c=1;
        stack[c++]=arr[1];
         for (int i = 2; i <=2*n; i++)
        {
            if(stack[c-1]==i) stack[--c]=-1;
            else
            {
                stack[c++]=arr[i];
            }
        }
        if(stack[1]==-1) cout<<"Yes"<<endl;
        else cout << "No"<<endl;
    }

    return 0;

}

转载于:https://www.cnblogs.com/danielqiu/archive/2013/01/23/2874071.html

猜你喜欢

转载自blog.csdn.net/weixin_33957648/article/details/93795282