该编程题主要考察的是数据结构的使用,一个好的数据结构处理问题来得心应手
我是通过利用C++中原有的list数据结构(大体上相当于一个双向链表)解决该问题的,其中list的每个元素需保存角色和随从的position、attack、health。
#include<iostream>
#include<string>
#include<list>
using namespace std;
class AI{
public:
int position;
int attack;
int health;
AI(int p,int a,int h){
position=p;
attack=a;
health=h;
}
};
typedef list<AI> LISTAI;
int main()
{
int n;
cin>>n;
LISTAI pet_one,pet_two;
pet_one.push_front(AI(0,0,30));
pet_two.push_front(AI(0,0,30));
LISTAI::iterator ite;
string action;
LISTAI *pet_att=&pet_one;
LISTAI *pet_def=&pet_two;
for(int i=0;i<n;i++){
cin>>action;
if(action=="summon"){
int p,a,h,tag=0;
cin>>p>>a>>h;
AI temp(p,a,h);
for(ite=pet_att->begin();ite!=pet_att->end();++ite){
if(ite->position==p){
pet_att->insert(ite,temp);
tag=1;
while(ite!=pet_att->end()){
ite->position++;
ite++;
}
break;
}
}
if(tag!=1) pet_att->push_back(temp);
}
else if(action=="attack"){
int att,def;
cin>>att>>def;
LISTAI::iterator ite_att,ite_def;
for(ite_att=pet_att->begin();ite_att!=pet_att->end();++ite_att)
if(ite_att->position==att) break;
for(ite_def=pet_def->begin();ite_def!=pet_def->end();++ite_def)
if(ite_def->position==def) break;
ite_att->health-=ite_def->attack;
ite_def->health-=ite_att->attack;
if(ite_att->health<=0){
ite_att=pet_att->erase(ite_att);
for(;ite_att!=pet_att->end();++ite_att)
ite_att->position--;
}
if(ite_def->position!=0&&ite_def->health<=0){
ite_def=pet_def->erase(ite_def);
for(;ite_def!=pet_def->end();++ite_def)
ite_def->position--;
}
else if(ite_def->position==0&&ite_def->health<=0){
break;
}
}
else if(action=="end"){
LISTAI *pp=pet_att;
pet_att=pet_def;
pet_def=pp;
}
}
if(pet_one.begin()->health<=0) cout<<-1<<endl;
else if(pet_two.begin()->health<=0) cout<<1<<endl;
else cout<<0<<endl;
ite=pet_one.begin();
cout<<ite->health<<endl;
ite++;
cout<<pet_one.size()-1;
for(;ite!=pet_one.end();++ite){
cout<<" "<<ite->health;
}
cout<<endl;
ite=pet_two.begin();
cout<<ite->health<<endl;
ite++;
cout<<pet_two.size()-1;
for(;ite!=pet_two.end();++ite){
cout<<" "<<ite->health;
}
cout<<endl;
return 0;
}