1021. Couples

首先原题是这样的
Description
N couples are standing in a circle, numbered consecutively clockwise from 1 to 2N. Husband and wife do not always stand together. We remove the couples who stand together until the circle is empty or we can’t remove a couple any more.
Can we remove all the couples out of the circle?

Input
There may be several test cases in the input file. In each case, the first line is an integer N(1 <= N <= 100000)—-the number of couples. In the following N lines, each line contains two integers —- the numbers of each couple.
N = 0 indicates the end of the input.

Output
Output “Yes” if we can remove all the couples out of the circle. Otherwise, output “No”.

Sample Input
4
1 4
2 3
5 6
7 8

2
1 3
2 4

0
Sample Output
Yes
No

题目意思很简单,给你一个数N,还有一个1~2N的圆圈,然后给出N对数字,表示他们是夫妻,当某一对数字在圆圈中相邻的时候,将这两个移走,我们要做到的就是判断根据所给出的夫妻判断是否能将圈中的所有夫妻移走。

看着挺复杂,但是其实挺简单。我的做法就是利用一个栈的结构和数组。数组用于储存夫妻,用第一个样例说明一下。需要先定义一个数组arr,大小为2*N+1;然后输入第一对夫妻2,3时,使得arr[2] = arr[3] = 1;
以此类推,然后定义一个栈的结构,当栈不为空,并且arr[i] = 栈顶元素时,将其pop出来,否则数组元素入栈。最后我们只需要判断栈是否为空就好

代码如下

#include<iostream>
#include<stack> 
using namespace std;


int main()
{
    int n;
    int a,b;
    while(cin >> n&& n!= 0)
    {
        int arr[2*n+1];
        for(int i =1;i<=n;i++)
        {
            cin>>a>>b;
            arr[a] = arr[b] = i;
        }
        stack<int> s;
        for(int i = 1;i<=n*2;i++)
        {
            if(!s.empty() && s.top() == arr[i])
            {
                s.pop();
            }
            else
            {
                s.push(arr[i]);
            }
        }
        if(s.empty())
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl; 
    }
 }                 

最后附上题目地址:http://soj.sysu.edu.cn/1021

你可能感兴趣的:(西西里)