码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4041 Eliminate Witches! --模拟

时间:2014-11-16 01:48:42      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   sp   for   

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

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

代码:

bubuko.com,布布扣
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
using namespace std;
#define N 50017

string 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 = 1;
                for(j=i+1;j<v;j++)
                {
                    if(ss[j] == () cnt++;
                    else if(ss[j] == ))
                    {
                        cnt--;
                        if(cnt == 0) break;
                    }
                }
                Go(i+1,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=0;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=0;i<=50000;i++)
            G[i].clear();
        cin>>ss;
        len = ss.length();
        father = 0;
        ind = 0;
        Go(0,len,0);
        printf("%d\n",ind);
        for(i=1;i<=ind;i++)
            cout<<np[i]<<endl;
        dfs(1);
        puts("");
    }
    return 0;
}
View Code

 

HDU 4041 Eliminate Witches! --模拟

标签:style   blog   http   io   color   ar   os   sp   for   

原文地址:http://www.cnblogs.com/whatbeg/p/4100874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!