题意:2011北京网赛题目。输出遍历的路径。
#include <stack>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
#define N 1000010
#define M 50010
struct Item
{
int flag, id; /* flag=1表示为数字,flag=0表示非数字。 id表示房间的编号。 */
char ch;
};
queue<Item> que; /* 将给出的字符串转化为 1(2(3)) 类型来储存 */
stack<Item> node; /* 用来存储节点,(叶子节点不储存) */
char str[N];
char name[M][12];
int cnt;
void solve ()
{
printf("%d\n",cnt);
for ( int i = 1; i <= cnt; i++ )
printf("%s\n",name[i]);
Item cell, temp;
while ( ! que.empty() )
{
cell = que.front();
que.pop();
if ( cell.flag == 1 )
{
temp = que.front(); /* cell 为数字, 那么依据它的下一个字符来决定它的操作 */
que.pop();
if ( temp.ch == '(' )
{
if ( ! node.empty() )
printf("%d %d\n", (node.top()).id, cell.id );
node.push(cell);
}
else if ( temp.ch == ',' )
{
printf("%d %d\n", node.top().id, cell.id );
printf("%d %d\n", cell.id, node.top().id );
}
else if ( temp.ch == ')' )
{
printf("%d %d\n", node.top().id, cell.id );
printf("%d %d\n", cell.id, node.top().id );
Item ttem = node.top();
node.pop();
if ( ! node.empty() )
printf("%d %d\n", ttem.id, node.top().id );
}
}
else if ( cell.ch == ')' && node.size() >= 2 ) /* 若cell不是数字,那么若它是'('则处理,其他都不做处理 */
{
temp = node.top();
node.pop();
printf("%d %d\n", temp.id, node.top().id );
}
}
putchar('\n');
}
int main()
{
int t, len;
scanf("%d",&t);
while ( t-- )
{
scanf("%s",str);
len = strlen(str);
cnt = 0;
while ( !node.empty () ) node.pop();
while ( !que.empty () ) que.pop ();
Item cell;
for ( int i = 0; i < len; i++ )
{
int j = 0;
while ( islower(str[i]) && i < len )
{
if ( 0 == j ) cnt++;
name[cnt][j++] = str[i++];
}
if ( j != 0 )
{
name[cnt][j] = '\0';
cell.flag = 1;
cell.id = cnt;
que.push(cell);
}
cell.flag = 0;
cell.ch = str[i];
que.push(cell);
}
solve();
}
return 0;
}
#include <stack>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
stack<int> father; /* 储存双亲节点 */
queue<int> que; /* 按顺序储存遍历的点 */
char str[1000010];
char name[50010][12];
int main()
{
int t;
scanf("%d",&t);
while ( t-- )
{
scanf("%s",str);
int len = strlen(str);
while ( !father.empty () ) father.pop();
while ( !que.empty () ) que.pop ();
int i, j, cnt = 0;
for ( i = 0; i < len; i++ )
{
j = 0;
while ( islower(str[i]) && i < len )
{
if ( 0 == j ) cnt++;
name[cnt][j++] = str[i++];
}
if ( j != 0 )
name[cnt][j] = '\0';
if ( str[i] == '(' )
{
que.push(cnt);
father.push(cnt);
}
else if ( str[i] == ')' )
{
if ( str[i-1] != ')' )
que.push ( cnt );
que.push ( father.top() );
father.pop();
}
else if ( str[i] == ',' )
{
if ( str[i-1] != ')' )
que.push(cnt);
que.push(father.top());
}
}
printf("%d\n",cnt);
for ( i = 1; i <= cnt; i++ )
printf("%s\n",name[i]);
while ( que.size() > 1 )
{
printf("%d ",que.front());
que.pop();
printf("%d\n",que.front());
}
putchar('\n');
}
return 0;
}