E. Comments dfs模拟

时间:2023-03-10 01:43:46
E. Comments  dfs模拟

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 + ;
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 = ; i <= a[cur].ti; ++i) {
dfs(up + , deep + );
}
}
void work() {
scanf("%s", str + );
int lenstr = strlen(str + );
int now = ;
string ts;
int di = ;
int to = ;
lenstr += ;
str[lenstr] = ',';
lena = ;
for (int i = ; i <= lenstr; ++i) {
if (now == ) {
if (str[i] == ',') {
now = ;
} 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 = ;
ts.clear();
now = ;
} else di = di * + str[i] - '';
}
}
// for (int i = 1; i <= lena; ++i) {
//// printf("%d %d %d")
// cout << a[i].s << " " << a[i].ti << " " << a[i].id << endl;
// }
up = ;
while (up <= lena) {
dfs(up, );
up++;
}
printf("%d\n", mxdeep);
for (int i = ; i <= mxdeep; ++i) {
cout << ans[i] << endl;
}
} int main() {
#ifdef local
freopen("data.txt", "r", stdin);
// freopen("data.txt", "w", stdout);
#endif
work();
return ;
}