题意:

(2)嵌套数组表达式:利用栈进行计算,由里向外逐层计算得出值!
1 #include<iostream>
2 #include<cstdio>
3 #include<map>
4 #include<vector>
5 #include<string>
6 #include<cstring>
7 #include<stack>
8 using namespace std;
9 typedef pair<char, int> position;//数组名+下标
10 map<position, int>arr;//存放数组的值
11 map<char, int>arrSize;//存放数组的大小
12
13 bool isDefine(string str)//是否是定义
14 {
15 if (str.find("=") == string::npos)//没有找到,返回string::npos
16 return true;
17 return false;
18 }
19
20 int arrLen(string str)//计算数组的长度或下标值
21 {
22 int len = 0;
23 for (int i = 0; i < str.length(); i++)
24 {
25 if (str[i] == ']')
26 break;
27 if (str[i] >= '0'&&str[i] <= '9')
28 {
29 len = len * 10;
30 len += str[i] - '0';
31 }
32 }
33 return len;
34 }
35
36 stack<char>sac;//用于计算嵌套数组
37
38 bool findValue(string str, int &index, int start)
39 {
40 while (!sac.empty())//清空栈
41 {
42 sac.pop();
43 }
44 //=后面是数字
45 if (str[start] >= '0'&&str[start] <= '9')
46 {
47 index = arrLen(str);//求值
48 return true;
49 }
50 else//嵌套的
51 {
52 int index2 = 0;
53 char name;
54 for (int i = start; i < str.length();)//遍历拆解
55 {
56 if (str[i] == '[' || str[i] == ']')
57 i++;
58 else if (str[i] <= '9'&&str[i] >= '0')//遇到数字,算值
59 {
60 while (str[i] >= '0'&&str[i] <= '9')
61 {
62 index2 *= 10;
63 index2 += str[i] - '0';
64 i++;
65 }
66 break;//找到数字就出来不需要管后面的]]]]
67 }
68 else//数组名入栈
69 sac.push(str[i++]);
70 }
71 //拆解完,由内向外计算
72 while (!sac.empty())
73 {
74 name = sac.top();
75 sac.pop();
76 if (arrSize[name] > index2)//没有越界
77 {
78 //被初始化过
79 if (arr.count(position(name, index2)) != 0)
80 index2 = arr[position(name, index2)];
81 else
82 return false;//没有被初始化
83 }
84 else
85 return false;//越界
86 }
87 index = index2;//把求得的值传回
88 }
89 return true;
90 }
91
92 bool solve(string str)
93 {
94 if (isDefine(str))//定义还是赋值
95 {
96 arrSize[str[0]] = arrLen(str);//存放数组的大小
97 }
98 else//赋值
99 {
100 char arrName = str[0];
101 int arrIndex;
102 findValue(str, arrIndex, 2);//计算下标,a[3],下标2就是3
103 if (arrIndex >= arrSize[arrName])
104 return false;//越界
105 int start = str.find("=") + 1;
106 int values;
107 string tempStr = str.substr(start, str.length() - start);
108 if (str[start] >= '0'&&str[start] <= '9')//=后面直接是数字
109 values = arrLen(tempStr);
110 else//等于后面是嵌套数组的
111 {
112 values = 0;
113 if (!findValue(str, values, start))
114 return false;
115 }
116 arr[position(arrName, arrIndex)] = values;//数组赋值
117 }
118 return true;
119 }
120
121 int main()
122 {
123 string str;
124 bool noBug;
125 int res;
126 while (cin>>str&&str!=".")
127 {
128 noBug = true;
129 int cnt = 1;
130 if (!solve(str))//第一行
131 {
132 noBug = false;
133 res = cnt;
134 }
135 while (cin>>str&&str!=".")
136 {
137 cnt++;
138 if (noBug)
139 {
140 if (!solve(str))
141 {
142 noBug = false;
143 res = cnt;
144 }
145 }
146 }
147 if (noBug)
148 cout << "0\n";
149 else
150 cout << res << endl;
151 arr.clear();
152 arrSize.clear();
153 }
154 return 0;
155 }