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
41 42 35 67 821 32 40
Sample Output
YesNo
題目分析:
這個題的意思很明顯,筆者思路就是用一個數組來儲存資訊,數組下標就表示圈中的夫婦編號,數組的內容就是判別是否是夫妻倆,比如第一組資料就是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轉換成listlist<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 forif(!flag)break;}if(coupleFlag2.empty())cout<<"Yes"<<endl;else cout<<"No"<<endl;}//end while}