展开字符串(dfs)

展开字符串

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 2123    Accepted Submission(s): 1019

Problem Description
在纺织CAD系统开发过程中,经常会遇到纱线排列的问题。 该问题的描述是这样的:常用纱线的品种一般不会超过25种,所以分别可以用小写字母表示不同的纱线,例如:abc表示三根纱线的排列;重复可以用数字和括号表示,例如:2(abc)表示abcabc;1(a)=1a表示a;2ab表示aab;如果括号前面没有表示重复的数字出现,则就可认为是1被省略了,如:cd(abc)=cd1(abc)=cdabc;这种表示方法非常简单紧凑,也易于理解;但是计算机却不能理解。为了使计算机接受,就必须将简单紧凑的表达方式展开。某ACM队接受了此项任务。现在你就是该ACM队的一员,请你把这个程序编写完成。 已知条件:输入的简单紧凑表达方式的长度不超过250个字符;括号前表示重复的数不超过1000;不会出现除了数字、括号、小写字母以外的任何其他字符;不会出现括号不配对等错误的情况(错误处理已由ACM其他队员完成了)。
 
Input
本题有多个测试数据组,第一行输入的就是数据组数N,接着就是N行表达式,表达式是按照前面介绍的意义书写的。
 
Output
输出时含有N行,每行对应一个输入的表达式。
 
Sample Input
2 1(1a2b1(ab)1c) 3(ab2(4ab))
 
Sample Output
abbabc abaaaabaaaababaaaabaaaababaaaabaaaab
 

题解:没写出来,看了人家的修改了自己的,然而wawawa;

我的:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<string>
using namespace std;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define SL(x) scanf("%lld",&x)
#define PI(x) printf("%d",x)
#define PL(x) printf("%lld",x)
#define P_ printf(" ")
#define T_T while(T--)
typedef long long LL;
const int MAXN=250010;
char s[MAXN];
int k;
int len;
//int i;
int dfs(int x){
	int temp,e;
	for(int i=x;i<len;i++){
		//temp=1;
		if(s[i]==')')return i+1;
		/*if(s[i]>='0'&&s[i]<='9'){
			temp=s[i]-'0';
			i++;
			while(s[i]>='0'&&s[i]<='9'){
				temp=temp*10+s[i]-'0';i++;
			}
		}*/
		for(temp=0;isdigit(s[i]);i++)
              temp=temp*10+s[i]-'0';
          if(!temp) temp=1;
		if(s[i]=='('){
			while(temp--){
				e=dfs(i+1);
			}
			i=e;
		}
		else{
			while(temp--)printf("%c",s[i]);
		}
	}
}
int main(){
	int T;
	SI(T);
	T_T{
		memset(s,0,sizeof(s));
		scanf("%s",s);
		len=strlen(s);
		dfs(0);puts("");
	}
	return 0;
}

  大神ac;

#include <iostream>
#include <cctype>
#include <cstring>
#include <string>
using namespace std;

string s;
int fun(int ith)
{
     int k,e;
     char c;
     for(c=s[ith++];ith<s.size()&&c!=')';c=s[ith++])//递归结束的条件是字符串结束或遇到右括号 
     {
          for(k=0;isdigit(c);c=s[ith++])
              k=k*10+c-'0';
          if(!k) k=1;
          if(c=='('){
              while(k--)
                  e=fun(ith);
              ith=e;//重置ith的值,到下层递归结束的位置 
     }
     else
     {
         while(k--)
             putchar(c);
     }
 }
 if(c==')') return ith;//返回本次读到结尾的位置 
}
int main()
{
     int i,j,k,T;
     cin>>T;
     while(T--)
     {
          s.clear();
          cin>>s;
          fun(0);//进入递归 
          cout<<endl;
     }
     return 0;
}

  

原文地址:https://www.cnblogs.com/handsomecui/p/5087251.html