POJ1208地址:http://poj.org/problem?id=1208
move
a
onto
b
:
先将
a
和
b
上的其他木块移回到它们的初始位置,然后将木块
a
摞在木块
b
上
.
move
a
over
b
:
先将木块
a
上的其他木块移到它们的初始位置后,然后将木块
a
摞到包含了木块
b
的那一堆木块上面
pile
a
onto
b
:
先将木块
b
上的所有木块移回到它们的初始位置,然后将木块
a
及其上的木块移到木块
b
上
.
pile
a
over
b
:
将包含木块
a
的那一摞木块移到包含了木块
b
的那一堆木块上面
.
#include <iostream>
using namespace std;
struct Node{
int no;
struct Node *next;
};
struct Node *station[25];
int Bplace[25];
void Init(int n){
for(int i=0;i<n;i++){
station[i]=(struct Node*)malloc(sizeof(struct Node));
station[i]->no=i;
Bplace[i]=i;
station[i]->next=NULL;
}
}
struct Node *Find(int a,bool setNULL){
int b;
struct Node *p,*q;
b=Bplace[a];
if(station[b]->no==a)
{
p=station[b];
if(setNULL){
station[b]=NULL;
}
return p;
}
else{
q=station[b];
p=q->next;
while(p->no!=a){
q=p;
p=p->next;
}
if(setNULL)
q->next=NULL;
return p;
}
}
void f(int a){
struct Node *p;
p=Find(a,false); //constant point to the station[a->no]
if(p->next==NULL)
return;
int j;
while(p->next!=NULL){
j=p->next->no;
station[j]=p->next;
Bplace[j]=j;
p->next=NULL;
p=station[j];
}
}
void move(int a,int b){
if(a==b || Bplace[a]==Bplace[b])
return;
struct Node *pa,*pb;
pa=Find(a,true);
pb=Find(b,false);
while(pb->next){
pb=pb->next;
}
pb->next=pa;
while(pa!=NULL){
Bplace[pa->no]=Bplace[pb->no];
pa=pa->next;
}
}
void monto(int a,int b)
{
f(a);
f(b);
move(a,b);
}
void mover(int a,int b){
f(a);
move(a,b);
}
void ponto(int a,int b){
f(b);
move(a,b);
}
void pover(int a,int b){
move(a,b);
}
int main(){
int n,a,b;
struct Node *p;
char ch1[5],ch2[5];
//freopen("acm.txt","r",stdin);
cin>>n;
Init(n);
while(cin>>ch1 && strcmp(ch1,"quit")!=0){
cin>>a;
cin>>ch2;
cin>>b;
if(strcmp(ch1,"move")==0){
if(strcmp(ch2,"onto")==0)
monto(a,b);
else
mover(a,b);
}
else{
if(strcmp(ch2,"onto")==0)
ponto(a,b);
else
pover(a,b);
}
}//while
for(int i=0;i<n;i++)
{
cout<<i<<": ";
p=station[i];
while(p!=NULL)
{
cout<<p->no<<"";
p=p->next;
}
cout<<endl;
}
return 0;
}