M¹nh D¬ng Biªn So¹nBé M«n CÊu Tróc D÷ LiÖu Gi¶i ThuËt 2012 §ª Sè 6 Trong Bé §Ò ¤n TËp #include #include #include #include ifstream tepvao"C:/cau truc du lieu/dethi/trungto.in.txt"; ofstr
Trang 1M¹nh D¬ng Biªn So¹n
Bé M«n CÊu Tróc D÷ LiÖu
Gi¶i ThuËt 2012
§ª Sè 6 Trong Bé §Ò ¤n TËp
#include<iostream.h>
#include<malloc.h>
#include<fstream.h>
#include<string.h>
ifstream tepvao("C:/cau truc du lieu/dethi/trungto.in.txt");
ofstream tepra("C:/cau truc du lieu/dethi/hauto.out.txt");
/*
Chuyen tu trung to sang hau to
*/
struct node
{
char conyeu;
struct node *next;
};
typedef struct node *stacknode;
typedef struct
{
stacknode top;
}Stack;
Stack dau;
void KhoiTaoStack(Stack *S)
{
S->top=NULL;
return ;
}
int StackRong(Stack S)
{
return (S.top==NULL);
}
void PUSHStack(Stack *S,char x)
{
stacknode p;
p=(stacknode)malloc(sizeof(struct node));
p->conyeu=x;
p->next=S->top;
S->top=p;
return ;
Trang 2char POPStack(Stack *S)
{
stacknode p;
if(StackRong(*S))
{
return -1;
}else
{
p=S->top;
S->top=S->top->next;
return p->conyeu;
}
}
char xemdinh(Stack *S)
{ stacknode p;
if(StackRong(*S)){return '\0';}
p=S->top;
return p->conyeu;
}
int pri(char x)
{
if(x=='^')return 3;
if(x=='*'||x=='/')return 2;
if(x=='+'||x=='-')return 1;
return 0;
}
void hauto(char S[])
{
int n=strlen(S);
Stack cun; KhoiTaoStack(&cun);
for(int i=0;i<n;i++)
{
if(S[i]=='(')PUSHStack(&cun,S[i]);
else if(S[i]==')') {
while(1) {
if(xemdinh(&cun)=='('){POPStack(&cun);break;} else
if(pri(xemdinh(&cun))>=1)tepra<<POPStack(&cun)<<" ";
else if(StackRong(cun))break;
} if(xemdinh(&cun)=='(')POPStack(&cun);
} else if(pri(S[i])>=1) {
while(1)
Trang 3if(StackRong(cun)||xemdinh(&cun)=='(') {
PUSHStack(&cun,S[i]);
break;
} else if(pri(xemdinh(&cun))<pri(S[i])) {
PUSHStack(&cun,S[i]);
break;
} else tepra<<POPStack(&cun)<<" "; }
} else tepra<<S[i]<<" ";
}
while(StackRong(cun)!=1)tepra<<POPStack(&cun)<<" ";
tepra<<endl;
}
void NhapDL(char S[][600],int &n)
{
tepvao>>n;
for(int i=1;i<=n;i++)
tepvao>>S[i];
}
void InKetQua(char S[][600],int n)
{
tepra<<n<<endl;
for(int i=1;i<=n;i++)
hauto(S[i]);
}
main()
{
char S[1000][600];
int n;
NhapDL(S,n);
InKetQua(S,n);
}