http://codeforces.com/contest/747/problem/E
首先,把字符串变成这个样子。
hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0
hello 2 1
ok 0 2
bye 0 3
test 0 4
one 1 5
two 2 6
a 0 7
b 0 8
然后就可以按着每一位来dfs,第二个参数表示他有2个儿子,dfs的时候开个string ans[maxn]来保存每一层的字符串就可以了,
比赛的时候,傻傻逼逼地dfs构图,建好图后,又bfs,然后发现是头插法,又要reveser,很麻烦。不过幸好过了。
赛后补上这个方法。

#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <assert.h> #define IOS ios::sync_with_stdio(false) using namespace std; #define inf (0x3f3f3f3f) typedef long long int LL; #include <iostream> #include <sstream> #include <vector> #include <set> #include <map> #include <queue> #include <string> #define root 1 const int maxn = 1e6 + 20; struct node { string s; int ti; int id; }a[maxn]; int lena; char str[maxn]; string out[maxn]; string ans[maxn]; int up; int mxdeep; void dfs(int cur, int deep) { up = max(up, cur); mxdeep = max(mxdeep, deep); ans[deep] += out[cur]; ans[deep] += " "; for (int i = 1; i <= a[cur].ti; ++i) { dfs(up + 1, deep + 1); } } void work() { scanf("%s", str + 1); int lenstr = strlen(str + 1); int now = 0; string ts; int di = 0; int to = 0; lenstr += 1; str[lenstr] = ','; lena = 0; for (int i = 1; i <= lenstr; ++i) { if (now == 0) { if (str[i] == ',') { now = 1; } else ts += str[i]; } else { if (str[i] == ',') { ++lena; a[lena].s = ts; a[lena].ti = di; a[lena].id = ++to; out[to] = ts; di = 0; ts.clear(); now = 0; } else di = di * 10 + str[i] - '0'; } } // for (int i = 1; i <= lena; ++i) { //// printf("%d %d %d") // cout << a[i].s << " " << a[i].ti << " " << a[i].id << endl; // } up = 1; while (up <= lena) { dfs(up, 1); up++; } printf("%d ", mxdeep); for (int i = 1; i <= mxdeep; ++i) { cout << ans[i] << endl; } } int main() { #ifdef local freopen("data.txt", "r", stdin); // freopen("data.txt", "w", stdout); #endif work(); return 0; }