UVA1145 War 题解
解题思路
一道简单的模拟题。步骤如下:
- 循坏读入 A、B 的牌;
- 将两人的牌转化为数字,并插入到一个双向队列中;
- 进行循环,进行游戏,直到平局、有一方赢了、一直玩下去。
对于循环内部,我们分为两个部分:
- 判断游戏结果并输出;
- 进行游戏。
其中的进行游戏部分,我们每次获取两人牌堆的头牌,并进行比较,如果一样,就一直比较下去,直到有一人或两人牌堆为空或出现牌不一样的情况。对于每次的两张牌,我们都把它们插入一个栈中,这样就可以方便地实现按照从上到下地顺序放回自己的牌堆中。显然,出现不同的两张牌一定是栈顶的两张牌,进行比较放回就可以了。
注意事项
在每一次游戏结束后,一定要记得对两人的排队清空,并循环弹出栈中剩余的元素。
AC 代码
进行游戏部分代码如下,其中
check()) break;
int nowa=A.front();
int nowb=B.front();
A.pop_front();
B.pop_front();
sta.push(nowa);
sta.push(nowb);
while(nowa==nowb){
if(check()){
A.clear();
B.clear();
while(!sta.empty())
sta.pop();
return;
}
nowa=A.front();
nowb=B.front();
A.pop_front();
B.pop_front();
sta.push(nowa);
sta.push(nowb);
}if(nowa>nowb){
int now=sta.top();
sta.pop();
A.push_back(sta.top());
sta.pop();
A.push_back(now);
while(!sta.empty()){
A.push_back(sta.top());
sta.pop();
A.push_back(sta.top());
sta.pop();
}
}else{
while(!sta.empty()){
B.push_back(sta.top());
sta.pop();
B.push_back(sta.top());
sta.pop();
}
}cnt++;
完整代码:
#include<string>
#include<iostream>
#include<deque>
#include<stack>
using namespace std;
string a,b;int cnt;
deque<int> A,B;
inline int Get(char c){
if(c=='7') return 1;
else if(c=='8') return 2;
else if(c=='9') return 3;
else if(c=='T') return 4;
else if(c=='J') return 5;
else if(c=='Q') return 6;
else if(c=='K') return 7;
else return 8;
}stack<int> sta;
inline bool check(){
if(cnt>=16*16*16){
puts("play forever");
return true;
}else if(A.empty()&&B.empty()){
puts("draw game");
return true;
}else if(B.empty()&&!A.empty()){
puts("A wins");
return true;
}else if(A.empty()&&!B.empty()){
puts("B wins");
return true;
}return false;
}
inline void work(){
int lena=a.length();
int lenb=b.length();
for(register int i=0;i<lena;++i)
A.push_back(Get(a[i]));
for(register int i=0;i<lenb;++i)
B.push_back(Get(b[i]));
bool is=false;cnt=0;
while(true){
if(check()) break;
int nowa=A.front();
int nowb=B.front();
A.pop_front();
B.pop_front();
sta.push(nowa);
sta.push(nowb);
while(nowa==nowb){
if(check()){
A.clear();
B.clear();
while(!sta.empty())
sta.pop();
return;
}
nowa=A.front();
nowb=B.front();
A.pop_front();
B.pop_front();
sta.push(nowa);
sta.push(nowb);
}if(nowa>nowb){
int now=sta.top();
sta.pop();
A.push_back(sta.top());
sta.pop();
A.push_back(now);
while(!sta.empty()){
A.push_back(sta.top());
sta.pop();
A.push_back(sta.top());
sta.pop();
}
}else{
while(!sta.empty()){
B.push_back(sta.top());
sta.pop();
B.push_back(sta.top());
sta.pop();
}
}cnt++;
}A.clear();B.clear();
while(!sta.empty())
sta.pop();
}
signed main(){
while(cin>>a>>b)
work();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下