题目大意: 有两种语句,一种定义 a[size] 另外一种赋值 a[id] = b[id] / a[id] = value; 类似这种
主要思路:
用map<string,int> 存放变量名和变量名对应的size
map<string,map<int,int> > 来存放哪几个id是被初始化过的了,只有这里面的值可以出现在[]里面。
check() 递归检查类似a[b[c[id]]] 这种类型。
递归到最里面,然后返回到上一层来检查这个值是否存在和是否被初始化过。
记得清空map, 以及substr(id,len)是从下标id开始,截取长度为len的串...而不是开始下标和结束下标。
#include <bits/stdc++.h>
using namespace std;
#define Pair pair<int,int>
map<string,int > df; //名字是否定义过
map<string,map<int,int> > dy; //定义过的名字,对int下标是否初始化过
int judge = 0;
int check(string temp) //检查
{
if(temp[0] <= '9' && temp[0] >= '0')
{
int res;
stringstream ss;
ss << temp; ss >> res;
return res;
}
else
{
string na = temp.substr(0,temp.find_first_of('['));
string li = temp.substr(temp.find_first_of('[')+1,temp.find_last_of(']') -temp.find_first_of('[')-1);
int i = check(li);
//下面都是判断 na[i] 是否是定义过的。
if(df.count(na) == 0)
judge = 1;
else
{
if(i < 0 || i >= df[na])
judge = 1;
if(dy.count(na) == 0)
judge = 1;
else if(dy[na].count(i) == 0)
judge = 1;
}
if(judge == 0)
return dy[na][i];
else return -1;
}
}
int readdata()
{
string temp;
int num = 0;
df.clear(); dy.clear();
int flag = 0;
judge = 0;
while(getline(cin,temp))
{
if(temp == "." && num == 0) return 0;
if(temp == "." && num > 0)
{
if(!flag)
printf("0\n");
return 1;
}
num++;
if(flag == 0)
{
if(temp.find('=') != string::npos)
{
string arr = temp.substr(0,temp.find_first_of('='));
string brr = temp.substr(temp.find_first_of('=')+1);
string namea = arr.substr(0,arr.find_first_of('['));
string nameb = brr.substr(0,brr.find_first_of('['));
string ina = arr.substr(arr.find_first_of('[')+1,arr.find_last_of(']') - arr.find_first_of('[')-1);
int i = check(ina);
int j = check(brr);
if(judge == 1)
flag = 1;
else
{
map<int,int> com;
if(df.count(namea) == 0)
flag = 1;
else
{
if(i >= df[namea] || i < 0)
flag = 1;
else
{
if(dy.count(namea) == 0)
{
com[i] = j;
dy[namea] = com;
}
else dy[namea][i] = j;
}
}
}
if(flag) printf("%d\n",num);
}
else
{
string name = temp.substr(0,temp.find_first_of('['));
string nu = temp.substr(temp.find_first_of('[')+1,temp.find_last_of(']')-1);
stringstream ss;
ss << nu;
int len;
ss >> len;
df[name] = len;
}
}
}
}
int main()
{
//freopen("D://in.txt","r",stdin);
while(readdata() != 0)
{ }
return 0;
}