bzoj4778[Usaco2017 Open]COWBASIC 矩阵乘法

博客介绍了如何解析COWBASIC程序,特别是处理循环嵌套和简单的表达式运算,通过矩阵乘法来模拟多次循环后的变量值。主要难点在于输入的解析和处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

高冷的po姐不愿意说题意,这个。。我就说一下吧。。
题意就是要求你写一个parser,MOO是循环次数,你把给你的哪一段程序循环MOO次,然后输出那个要输出的变量就好了。
由于MOO可以多次循环而且可以循环套循环,再加上expression只有赋值和加,所以只能用矩阵乘法模拟。。
难点主要在读入上吧,,我是这么觉得的。

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<sstream>
#include<map>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=105;
const int mo=1e9+7;
map<string,int> var_map;
int sta[N],n;
int top,tot,cnt;
int hash(string s)
{
    int &re=var_map[s];
    if (!re)re=++tot;
    return re;
} 
struct matrix
{
    int a[N][N];
    matrix(){}
    matrix(int v)
    {
        memset(a,0,sizeof(a));
        fo(i,0,tot)a[i][i]=v;
    } 
    int* operator [] (int i)
    {
        return a[i];
    } 
    friend matrix operator *(matrix x,matrix y)
    {
        matrix c(0);
         fo(i,0,tot)
         fo(j,0,tot)
         fo(k,0,tot)
         c[i][j]=(c[i][j]+1ll*x[i][k]*y[k][j]%mo)%mo; 
        return c;
    }
    friend matrix pow(matrix a,int b)
    {
        matrix r(1);
        while (b)
        {
            if (b&1)r=r*a;
            a=a*a;
            b>>=1;
        }
        return r;
    }
}mat[N];
int main()
{
    string buffer;
    new(&mat[0])matrix(1);
    while (1)
    {
        static char s[N*5];
        gets(s);
        istringstream stream(s);
        stream>>s;
        if (s[0]>='a'&&s[0]<='z')
        {
            static int b[N];
            int left=hash(s);
            memset(b,0,sizeof(b));
            while (stream>>s)
            {
                if (s[0]>='a'&&s[0]<='z')
                {
                    int right=hash(s);
                    fo(i,0,tot)
                    b[i]=(b[i]+mat[top][right][i])%mo;
                }
                else if (s[0]>='0'&&s[0]<='9')
                {
                    int right=atoi(s);
                    b[0]=(b[0]+right)%mo;
                }
            }
            fo(i,0,tot)mat[top][left][i]=b[i];
        }
        else if (s[0]>='0'&&s[0]<='9')
        {
            sta[++top]=atoi(s);
            new (&mat[top])matrix(1);
        }
        else if (s[0]=='}')
        {
            mat[top-1]=pow(mat[top],sta[top])*mat[top-1];
            top--;
        }
        else if (s[0]=='R')
        {
            stream>>s;
            int val=hash(s);
            int ans=0;
            fo(i,0,tot)ans=(ans+mat[0][val][i])%mo;
            printf("%d\n",ans);
            break;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值