poj2003 Hire and Fire
题意:按题目要求实现hire,fire,print的三种操作
解法:以结构体为节点,用map来建立成员姓名与节点一 一映射的关系,链表list表示儿子节点,构造树形结构
#include<iostream>
#include<cstring>
#include<map>
#include<list>
using namespace std;
struct node{
string name;
node *f;
list<node*> kid;
node() {f=NULL;}
};
map<string,node*> member;
void hire(string a,string b){
node *root=new node();
root->name=b;
root->f=member[a];
member[b]=root;
member[a]->kid.push_back(root);
}
void fire(string a){
node* squid=member[a];
member.erase(squid->name);
while(!squid->kid.empty()){
squid->name=squid->kid.front()->name;
member[squid->name]=squid;
squid=squid->kid.front();
}
node *root=squid->f;
root->kid.remove(squid);
delete squid;
}
void prin(node* root,int dep){
if(root==NULL) return;
for(int i=0;i<dep;i++) cout<<'+';
cout<<root->name<<endl;
for(list<node*>::iterator it=root->kid.begin();it!=root->kid.end();it++)
prin(*it,dep+1);
}
int main(){
node *root=new node;
string a,b,c;
cin>>a;
root->name=a;
member[a]=root;
while(cin>>a){
if(a=="print"){
prin(root,0);
for(int i=0;i<60;i++) cout<<'-';
cout<<endl;
}
else if(a=="fire"){
cin>>b;
fire(b);
}
else{
cin>>b>>c;
hire(a,c);
}
}
return 0;
}

浙公网安备 33010602011771号