TJU1173

北城以北 提交于 2019-11-27 01:43:18
在思考这题的时候想到了一个很好的解法。
建立一棵用数组模拟的树,每个结点的值类型是一个char,内容是ABC中的一个。先把原01串处理为AB串并作为叶子结点,然后两个两个合并。合并的时候,两结点全A或全B时,父结点值为A或B,否则为C。树建立起来以后,先序遍历即可。注意只有在一个结点的值为C的时候才访问左右孩子。
None.gif#include<iostream>
None.gif#include
<cstring>
None.gif
using namespace std;
None.gif
None.gif
const int K = 0x20000;
None.gif
void PrintTree(char s[2*K],int current);
None.gif
int length;
None.gif
int main()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
char s[2*K];
InBlock.gif    
int ptEnd,ptStart;
InBlock.gif    
while(cin>>s)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        ptStart 
= 0;
InBlock.gif        ptEnd 
= strlen(s);
InBlock.gif        length 
= ptEnd * 2 - 1;
InBlock.gif        
for(int i=0;i<ptEnd;i++) s[i] = s[i] - '0' + 'A';
InBlock.gif        
while(ptStart + 2 <= ptEnd)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if(s[ptStart] != 'C' && s[ptStart] == s[ptStart+1])
InBlock.gif                s[ptEnd
++= s[ptStart];
InBlock.gif            
else
InBlock.gif                s[ptEnd
++= 'C';
InBlock.gif            ptStart 
+= 2;
ExpandedSubBlockEnd.gif        }

InBlock.gif        PrintTree(s,
1);
InBlock.gif        cout
<<endl;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
return 0;
ExpandedBlockEnd.gif}

None.gif
void PrintTree(char s[2*K],int current)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    cout
<<s[length-current];
InBlock.gif    
if(s[length-current] == 'C')
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        current 
<<= 1;
InBlock.gif        PrintTree(s,current
+1);
InBlock.gif        PrintTree(s,current);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/FancyMouse/articles/263943.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!