UVA 1596 Bug Hunt

来源:互联网 发布:传智播客python就业班 编辑:程序博客网 时间:2024/05/14 14:56

题意:给出一段程序,输出第一个出现bug的位置。

程序有两个格式:一种是定义一个数组,并规定数组大小;一种是对数组元素进行赋值。 

Bug有两种:一种是数组越界,一种是使用未初始化的变量。

思路:模拟判断

如果是第一种语句,就给丢进map给个编号并记录数组大小。

第二种语句用递归判断一下,因为可以嵌套类似这样a[a[1]]。

#include <cstdio>#include <cmath>#include <cstring>#include <string>#include <cstdlib>#include <iostream>#include <algorithm>#include <stack>#include <map>#include <set>#include <vector>#include <sstream>#include <queue>#include <utility>using namespace std;#define rep(i,j,k) for (int i=j;i<=k;i++)#define Rrep(i,j,k) for (int i=j;i>=k;i--)#define Clean(x,y) memset(x,y,sizeof(x))const int maxn = 1001;char temp[100];string str;int ans;int arraynum;map<string,int> pos;      //为数组名编号map<int,int> value[maxn]; //每个数组的值是多少map<int,bool> flag[maxn]; //每个数组的值是否被初始化int ind[maxn]; // 最大下标int getnum(char* st,char *ed){    int ans = 0;    for(char *i = st;i<=ed;i++)        if ( isdigit( *i ) ) ans = ans * 10 + *i - '0';        else break;    return ans;}int getvalue(char *st,char *ed,bool& f){    if ( !f ) return 0;    char *s = st;    int ans;    if ( isdigit( *s ) )        ans = getnum(st,ed);    else    {        int k = strchr(st,'[') - st;        string arrayname = string(st,st+k);        int Ind = getvalue( st+k+1,ed,f );        k = pos[arrayname];        if( Ind< ind[ k ] && flag[ k ][Ind]  )            ans = value[k][Ind];        else        {            f = false;            ans = 0;        }    }    return ans;}bool init(){    gets(temp);    if ( temp[0] == '.' ) return false;    arraynum = 0;    ans = 0;    bool ok = true;    while( temp[0]!='.' )    {        if ( ok )        {            if ( strchr(temp,'=') == NULL )            {                arraynum++;                flag[arraynum].clear();                value[arraynum].clear();                int k = strchr(temp,'[') - temp;                str = string(&temp[0],&temp[k]);                pos[str] = arraynum;                ind[arraynum] = getnum(temp+k+1,temp+strlen(temp)-1);            }            else            {                string arrayname;                int Ind;                int Val;                bool vaild = true;                int k = strchr(temp,'[') - temp;                arrayname = string(&temp[0],&temp[k]);                int p = strchr(temp,'=') - temp;                Ind = getvalue(temp+k+1,temp+p,vaild);                Val = getvalue(temp+p+1,temp+strlen(temp)-1,vaild);                k = pos[arrayname];                if ( !vaild || Ind>=ind[k] ) ok = false;                else                {                    flag[k][Ind] = true;                    value[k][Ind] = Val;                }            }            ans++;        }        gets(temp);    }    if ( ok ) ans = 0;    return true;}int main(){    while( init() )    {        cout<<ans<<endl;    }    return 0;}


0 0
原创粉丝点击