BZOJ 4778 Usaco2017 Open COWBASIC 矩陣乘法

題目大意:自己看= =

容易發現所有的變換都是線性變換,用矩乘模擬

循環那個用個棧來模擬嵌套關係就行了

#include <map>
#include <string>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#define M 110
#define MOD 1000000007
using namespace std;

map<string,int> var_map;

int stack[M],top;

int tot;

int Hash(string s)
{
    int &re=var_map[s];
    if(!re) re=++tot;
    return re;
}

struct Matrix
{
    int a[M][M];
    Matrix() {}
    Matrix(int val)
    {
        memset(a,0,sizeof a);
        for(int i=0;i<=tot;i++)
            a[i][i]=val;
    }
    int* operator [] (int i)
    {
        return a[i];
    }
    friend Matrix operator * (Matrix x,Matrix y)
    {
        Matrix z(0);
        for(int i=0;i<=tot;i++)
            for(int j=0;j<=tot;j++)
                for(int k=0;k<=tot;k++)
                    (z[i][j]+=(long long)x[i][k]*y[k][j]%MOD)%=MOD;
        return z;
    }
    friend Matrix Quick_Power(Matrix x,int y)
    {
        Matrix re(1);
        while(y)
        {
            if(y&1) re=re*x;
            x=x*x; y>>=1;
        }
        return re;
    }
}matrix[M];

int main()
{
    string buffer;
    new (&matrix[0])Matrix(1);
    while(1)
    {
        static char s[360];
        gets(s);
        istringstream stream(s);
        stream>>s;
        if(s[0]>='a'&&s[0]<='z')
        {
            static int b[M];
            int left=Hash(s);
            memset(b,0,sizeof b);
            while(stream>>s)
            {
                if(s[0]>='a'&&s[0]<='z')
                {
                    int right=Hash(s);
                    for(int i=0;i<=tot;i++)
                        (b[i]+=matrix[top][right][i])%=MOD;
                }
                else if(s[0]>='0'&&s[0]<='9')
                {
                    int right=atoi(s);
                    (b[0]+=right)%=MOD;
                }
            }
            for(int i=0;i<=tot;i++)
                matrix[top][left][i]=b[i];
        }
        else if(s[0]>='0'&&s[0]<='9')
        {
            stack[++top]=atoi(s);
            new (&matrix[top])Matrix(1);
        }
        else if(s[0]=='}')
        {
            matrix[top-1]=Quick_Power(matrix[top],stack[top])*matrix[top-1];
            top--;
        }
        else if(s[0]=='R')
        {
            stream>>s;
            int val=Hash(s);
            int ans=0;
            for(int i=0;i<=tot;i++)
                (ans+=matrix[0][val][i])%=MOD;
            cout<<ans<<endl;
            break;
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章