kuangbin topic 19 uva111551 basic matrix

Posted by topsub on Thu, 30 Apr 2020 23:58:42 +0200

Title:
Given a sequence of numbers, each number corresponds to a transformation, which is the sum of some positions of the original sequence, and the sequence after r-th transformation is asked.
Explanation:
I really didn't expect to construct 01 matrix to express power. Their methods are all water problems. It's related, that is, the position of addition is + 1 in 01 matrix, and then fast power can be used. But how can I not expect to get the result after matrix transformation? Why? Is it really because I failed to study linear algebra? Oh. The big guy explained to me.... ORZ

#include<stdio.h>
#include<string.h>
#define LL long long int 
const int MOD=1000;
struct node
{
    int m[55][55];
    node()
    {
        memset(m,0,sizeof(m));
    }
};
int n,m;
int s[55],s2[55];
node cla(node a,node b){
    node c;
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            for(int k=0;k<n;k++) 
            if(a.m[i][k]&&b.m[k][j])//Prune (add conditions, set threshold), improve efficiency, one is 0, multiplication must be 0
            {
                c.m[i][j]+=a.m[i][k]*b.m[k][j];
                c.m[i][j]%=MOD;
            }
    return c;
}
node POW(node a)
{
    node c;
    for(int i=0;i<n;i++) c.m[i][i]=1;
    while(m)
    {
        if(m%2) c=cla(c,a);
        a=cla(a,a);
        m/=2;
    }
    return c; 
} 
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        node a;
        memset(s,0,sizeof(s));
        memset(s2,0,sizeof(s2));
        for(int i=0;i<n;i++)
        scanf("%d",&s[i]);
        for(int i=0;i<n;i++)
        {
            int x;
            scanf("%d",&x);
            for(int j=0;j<x;j++)
            {
                int v;
                scanf("%d",&v);
                a.m[i][v]++;
            }
        }
        a=POW(a);

        for(int i=0;i<n;i++)
        for(int k=0;k<n;k++)
        if(a.m[i][k]&&s[k])//Prune (add conditions, set threshold), improve efficiency, there is a 0, multiply must be 0
        {
            s2[i]+=a.m[i][k]*s[k];
            s2[i]%=MOD;
        }

        for(int i=0;i<n-1;i++)
        printf("%d ",s2[i]);
        printf("%d\n",s2[n-1]);     
    }
}