UVA1596 Bug Hunt

     这个题竟然卡了我一整天,最开始的思路是把每个数组元素都替换成数字并依次判断,果断写乱了,改了大半天都没改对。

     今天换了个思路,把每一行代码的括号都去掉,仅保留字母和数字,这样进行判断会方便一些。同时,把每一行的字母(即数组名称提取出来),用循环过一遍,跟相应的数字对应,判断越界等的情况。

    

#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<sstream>
using namespace std;
typedef long long ll;
pair<char,ll>ha;  //记录数组的下标及名称
map<char,ll>Count; //记录每个数组名的最大值
map<pair<char,ll>,ll>num; //记录每个数组单元的值
string trans(string s){   //把中括号去掉
   char ss[10000];
   memset(ss,0,sizeof(ss));
   int i, j = 0, len = s.length();
   for(i = 0; i < s.length(); i++)
      if(s[i] != '[' && s[i] != ']') ss[j++] = s[i];
   ss[j] = 0;
   string s1 = ss;
   return s1;
}
ll get_count(string s){      //得到数组元素的值并判断
   int len = s.length(), temp = 0;
   string s1 = s;
   for(int i = 0; i < len; i++){
      char c = s[i];
      if(isalpha(c)) if(!Count.count(c)) return -1;   //没有定义的数组,直接返回
      if(isalpha(c)) s[i] = ' ';
      if(isdigit(c)) {temp = i;break;}
   }
   stringstream ss(s);
   ll x;
   ss >> x;
   for(int i = temp-1; i >= 0; i--){
      char c = s1[i];
      ha.first = c; ha.second = x;
      if(!num.count(ha)) return -1;
      x = num[ha];
   }
   return x;
}
int main()
{
    string s;
    int i,j,k;
    vector<string>code;
    while(cin >> s && s[0] != '.'){
        Count.clear();
        num.clear();
        code.clear();
        code.push_back(trans(s));
        int yes = 1;
        while(cin >> s && s[0] != '.')
            code.push_back(trans(s));
        int len = code.size();
        for(i = 0; i < len; i++){
            k = code[i].find('=');
            if(k == std::string::npos){
               string s1 = code[i].substr(1);
               char c = code[i][0];
               ll x = get_count(s1);
               if(x == -1) {cout << i+1 << endl;yes = 0;break;}
               Count[c] = x;
            }
            else{
               string s1 = code[i].substr(1,k-1);
               string s2 = code[i].substr(k+1);
               char c = code[i][0];
               ll x = get_count(s1), y = get_count(s2);
               if(!Count.count(c) || x == -1 || y == -1 || x >= Count[c]){cout << i+1 << endl; yes = 0; break;}
               ha.first = c; ha.second = x;
               num[ha] = y;
            }
        }if(yes == 1)cout << "0\n";
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值