首页 技术 正文
技术 2022年11月7日
0 收藏 482 点赞 868 浏览 1230 个字

题意: 给一个字符串,表示一颗树,要求你把它整理出来,节点从1开始编号,还要输出树边。

解法: 模拟即可。因为由括号,所以可以递归地求,用map存对应关系,np存ind->name的映射,每进入一层括号,使father = now, 遇到右括号’)’,则father = fa[father],用vector存每个节点的子节点,然后最后dfs输出即可。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
using namespace std;
#define N 50017string ss,tmp,S;
string np[N];
map<string,int> mp;
int fa[N],father,ind;
vector<int> G[N];void Go(int u,int v,int father)
{
tmp = "";
int j;
for(int i=u;i<v;i++)
{
if(ss[i] >= 'a' && ss[i] <= 'z')
tmp += ss[i];
else if(ss[i] == '(' || ss[i] == ',' || ss[i] == ')')
{
if(tmp == "") continue;
mp[tmp] = ++ind;
np[ind] = tmp;
tmp = "";
fa[ind] = father;
G[father].push_back(ind);
if(ss[i] == '(')
{
int cnt = ;
for(j=i+;j<v;j++)
{
if(ss[j] == '(') cnt++;
else if(ss[j] == ')')
{
cnt--;
if(cnt == ) break;
}
}
Go(i+,j,ind);
i = j;
}
else if(ss[i] == ')')
father = fa[father];
}
}
if(tmp != "")
{
mp[tmp] = ++ind;
np[ind] = tmp;
tmp = "";
fa[ind] = father;
G[father].push_back(ind);
}
}void dfs(int u)
{
for(int i=;i<G[u].size();i++)
{
int v = G[u][i];
printf("%d %d\n",u,v);
dfs(v);
printf("%d %d\n",v,u);
}
}int main()
{
int t,i,j,len;
scanf("%d",&t);
while(t--)
{
mp.clear();
for(i=;i<=;i++)
G[i].clear();
cin>>ss;
len = ss.length();
father = ;
ind = ;
Go(,len,);
printf("%d\n",ind);
for(i=;i<=ind;i++)
cout<<np[i]<<endl;
dfs();
puts("");
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919