ZCMU—1798

来源:互联网 发布:数控车床编程实例 编辑:程序博客网 时间:2024/06/05 09:06

Problem B: Problem B: Language Cardinality

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 6  Solved: 2
[Submit][Status][Web Board]

Description

Problem B: Language Cardinality

A (formal) language is a set of strings. One way to define a particular langauge is using ordinary set notation. Alternatively, some form of grammar may be more convenient for representing large sets. The UW grammar in which we are interested has two parts:

  • An initial string
  • A set of replacement rules of the form s1 -> s2 where s1 and s2 are strings

The language defined by this grammar is the set of all strings that can be generated by repeatedly replacing s1 by s2 within the initial string. For example, consider the grammar G consisting of the initial string

"AyB"

and the replacement rules

{"A"->"ab", "Ay"->"cdy", "B"->"w", "B"->"x"} .

G generates the language

L = {"AyB", "Ayw", "Ayx", "abyB", "abyw", "abyx", "cdyB", "cdyw", "cdyx"}

Given a UW grammar G, compute how many different strings there are in the language generated by G.

The first line of input contains the initial string. The second and subsequent lines contain the replacement rules, one per line, terminated by end-of-file. There are at most 100 replacement rules. Each input string contains between 0 and 10 upper and lower case letters, and is enclosed in quotes. There are no spaces in the input.

Output consists of a single integer, the number of distinct strings in the language generated by G. If there are more than 1000 distinct strings, print "Too many." instead.

Input

Output

Sample Input

"AyB"
"A"->"ab"
"Ay"->"cdy"
"B"->"w"
"B"->"x"

Sample Output

9

【分析】

最多只需要运行1000次的模拟....看起来貌似很简单然而...debug快哭了...我真是菜..
set判重+string直接模拟...这里用到了.replace替换函数..
模拟过程没什么好说的...各有各的模拟方法,要说的只有几点坑,首先一点就是出现环的时候,也就是"a"->"ab"这种情况出现的时候就是Too many,就因为这个判断我wa了不知道多少次...有一点没有考虑就是"a"->"a"是不影响答案的..因为会判重...
其他的就是自己模拟的细节处理了~
【代码】
#include <iostream>#include <set>#include <cstdio>#include <cstring>#include <vector>using namespace std;string x,s;set <string> a;vector <string> f;string ma[10000][3];int len,i,t,tt;int main(){cin>>x;x.erase(x.begin());x.erase(x.end()-1);a.insert(x);f.push_back(x);len=0;int flag=0;while (cin>>x){for (i=1;!(x[i+1]=='-'&& x[i+2]=='>');i++) ma[len][0]+=x[i];for (i+=4;i<x.length()-1;i++) ma[len][1]+=x[i];if (ma[len][1].find(ma[len][0])!=string::npos&& ma[len][1]!=ma[len][0]) flag=1;len++;}while (!flag){x=f.front();f.erase(f.begin());for (i=0;i<len;i++){t=x.find(ma[i][0]);while (t!=string::npos&&a.size()<=1000){s=x;s.replace(t,ma[i][0].length(),ma[i][1]);tt=a.size();a.insert(s);if (tt<a.size()) f.push_back(s);t=x.find(ma[i][0],t+1);}}if (f.empty()||a.size()>1000) break;}if (a.size()>1000||flag) printf("Too many.\n");else printf("%d\n",a.size());}


0 0