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 integerN(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
题目分析:
这个题的意思很明显,笔者思路就是用一个数组来存储信息,数组下标就表示圈中的夫妇编号,数组的内容就是判别是否是夫妻俩,比如第一组数据就是1 2 2 1 3 3 4 4,这样遍历数组然后前后相等剔除,就可以满足了。首先我是用vector来实现,但是总是超时,原来vector随机删除数据的时间复杂度较高,然后就想到list代替,但是在输入数据时还要随机访问,所以笔者做法是输入时用vector来输入,然后转换成list,用list来删除节点,这样最后终于AC了
但是,但是,网上的大神说用栈来做,想一想,果然,完美,看来数据结构的选择还是很重要的。
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<list>
#include<string.h>
using namespace std;
int main()
{
int n;
while(cin>>n&&n!=0)
{
vector<int>coupleFlag(2*n);
for(int i=0;i<2*n;i++)
{
int x;
cin>>x;
coupleFlag[x-1]=i/2;
}
//把vector转换成list
list<int>coupleFlag2(coupleFlag.begin(),coupleFlag.end());
int flag=false;
while(true)
{
flag=false;
for(list<int>::iterator ite=coupleFlag2.begin();!coupleFlag2.empty()&&ite!=coupleFlag2.end();ite++)
{
list<int>::iterator itej;
list<int>::iterator iteEnd=coupleFlag2.end();
list<int>::iterator iteiTmp=ite;
ite!=--iteEnd?itej=++iteiTmp:itej=coupleFlag2.begin();
if(ite==coupleFlag2.begin()&&*ite==*iteEnd)
{
flag=true;
coupleFlag2.erase(iteEnd);
coupleFlag2.erase(ite);
break;
}
if(*ite==*itej)
{
flag=true;
coupleFlag2.erase(itej);
ite=coupleFlag2.erase(ite);
break;
}
}
//for(int i=0;!coupleFlag.empty()&&i<coupleFlag2.size()-1;i++)
//{
// if(i==0&&coupleFlag[0]==coupleFlag[coupleFlag.size()-1])
// {
// coupleFlag.erase(coupleFlag.begin()+coupleFlag.size()-1);
// coupleFlag.erase(coupleFlag.begin());
// i--;
// continue;
// }
// int j;
// i!=coupleFlag.size()-1?j=i+1:j=0;
// if(coupleFlag[i]==coupleFlag[i+1])
// {
// flag=true;
// coupleFlag.erase(coupleFlag.begin()+i+1);
// coupleFlag.erase(coupleFlag.begin()+i);
// i--;;
// }//end if
//
//}//end for
if(!flag)break;
}
if(coupleFlag2.empty())
cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}//end while
}