題意:2011北京網賽題目。輸出遍曆的路徑。
#include <stack>#include <queue>#include <cstring>#include <iostream>using namespace std;#define N 1000010#define M 50010struct 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;}