1021. Couples
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
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
Problem Source
ZSUACM Team Member
题意类似于祖玛游戏,相邻的人若属于一对夫妻,则将他们两人撤出,若最后全部撤出则输出YES。利用栈这种数据结构,将同一对夫妻的序号分别设为i和-i存入数组中,然后按顺序将其压入栈内,若栈为空,则直接压入,若栈顶人的序号加上即将压入栈的人的序号和为0,则为一对夫妻,所以将两人都从栈内撤出,若不为0则直接压入栈。等到将数组内的数据全部都尝试压入后,若栈内为空则说明能全部撤出,若不为空则撤出失败。整道题的逻辑和代码都比较简单。
// Problem#: 1021
// Submission#: 5045794
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
int n;
int coup[200000];//第i对夫妻分别位于第j个位置和第k个位置,则coup[j-1]=i,coup[k-1]=-i
bool isempty()
{
stack<int> couple;//一个栈
int couple1,couple2;
for(int i=0;i<n;++i)
{
cin>>couple1>>couple2;//将夫妻对的序号和对应的位置存入数组
coup[couple1-1]=i+1;
coup[couple2-1]=-i-1;
}
for(int i=0;i<2*n;++i)
{
if(couple.empty())//若栈为空,则将这个人的序号压入栈
{
couple.push(coup[i]);
}
else if(couple.top()+coup[i]==0) couple.pop();//等于0则说明要放入栈的和栈顶的是一对夫妻,所以将他们两个撤出栈
else couple.push(coup[i]);//否则则放入栈
}
if(couple.empty()) return true;//若栈最后为空则所有夫妻全部撤出,返回true
else return false;//否则返回false
}
int main()
{
while(cin>>n&&n)
{
if(isempty()) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}