I was writing a program for homework.
It's about simulating two people playing a card game.
At first, Mr.Y has n
cards while Mr.P has m
cards and the cards they have are unique.
Mr.Y plays first, and here's how you play the game:
- First, you pick a number
x
, if the number is among the cards of your competitor, you take it. - Then, if you already have the card you got, you throw both the card on your hand and the card you just got.
- Then, your competitor does the same thing (he picks a number
w
).
That's the end of the first round.
The game ends when one of the people ran out of cards.
Also, if the game doesn't end in k
rounds, it automatically ends.
The program has to output:
A number l
, which represents in how many rounds will the game end.
The cards Mr.Y and Mr.P have when a round ends.
I have tried to simulate the game using vector but the code raises a segmentation fault when I tried to execute it.
Here's my code:
#include<bits/stdc++.h>
using namespace std;
int n,m,k,w,x,a;
vector<int> y,p;
vector<vector<int>> ymoves;
vector<vector<int>> pmoves;
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>a;
y.push_back(a);
}
for(int i=0;i<m;i++){
cin>>a;
y.push_back(a);
}
cin>>k;
bool b=1;
for(int i=0;i<k;i++){
cin>>x>>w;
for(int j=0;j<p.size();j++){
if(p[j]==x){
y.push_back(x);
p.erase(p.begin()+j);
break;
}
}
for(int j=0;j<y.size()-1;j++){
if(y[j]==x){
y.erase(y.begin()+j);
y.pop_back();
break;
}
}
for(int j=0;j<y.size();j++){
if(y[j]==w){
p.push_back(w);
y.erase(y.begin()+j);
break;
}
}
for(int j=0;j<p.size()-1;j++){
if(p[j]==w){
p.erase(p.begin()+j);
p.pop_back();
break;
}
}
copy(y.begin(),y.end(),ymoves[i].begin());
copy(p.begin(),p.end(),pmoves[i].begin());
if(y.empty()||p.empty()){
b=0;
cout<<i<<'\n';
for(int j=0;j<i;j++){
cout<<ymoves[j].size()<<' ';
for(int l=0;l<ymoves[j].size();l++)cout<<ymoves[j].at(l)<<' ';
cout<<'\n';
cout<<pmoves[j].size()<<' ';
for(int l=0;l<pmoves[j].size();l++)cout<<pmoves[j].at(l)<<' ';
cout<<'\n';
}
break;
}
}
if(b){
cout<<k<<'\n';
for(int j=0;j<k;j++){
cout<<ymoves[j].size()<<' ';
for(int l=0;l<ymoves[j].size();l++)cout<<ymoves[j].at(l)<<' ';
cout<<'\n';
cout<<pmoves[j].size()<<' ';
for(int l=0;l<pmoves[j].size();l++)cout<<pmoves[j].at(l)<<' ';
cout<<'\n';
}
}
}