TOJ-5480: Lonely and Warm

Keywords: Programming

Topic link: http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=5480

This problem is similar to POJ 3735, which is a fast power of matrices.

Just construct the matrix according to the requirement of the title, and then repeat the number of times only need a quick power.

For the three operations required by the title, the matrix can be constructed in the following way

The first requirement is get x, which means that the X cat gets one.

That is, the position of x + 1

The second requirement is eat x, which means that the cat eats all its fish.

That is, x goes to zero.

The third requirement is exchange x y, meaning that cats X and Y exchange their fish.

That is swap(x,y).

#include <bits/stdc++.h>
using namespace std;
#define LL __int64
#define EPS 1e-6
#define PI (acos(-1))
#define E exp(1.0)
struct A{
	LL data[111][111];
	int n;
	void ini(int nn){
		n=nn;
		memset(data,0,sizeof(data));
	}
	void dw(int nn){
		ini(nn);
		for(int i=0;i<=n;i++)data[i][i]=1;
	}
	A(){
		n=2;
		memset(data,0,sizeof(data));
	}
};
int n;
A operator* (A a,A b)
{
	A ans;
	for(int i=0;i<=n;i++)
    {
        for(int j=0;j<=n;j++)
        {
            if(a.data[i][j]==0)continue;
            for(int k=0;k<=n;k++)
            {
                ans.data[i][k]+=a.data[i][j]*b.data[j][k];

            }
        }
    }
	return ans;
}
A operator^ (A a,int k)
{
	A ans;
	ans.dw(n);
	while(k)
	{
		if(k&1)ans=ans*a;
		a=a*a;
		k>>=1;
	}
	return ans;
}
int main(){
	int m,k,x,y;
	A T;
	char ch[15];
	while(~scanf("%d%d%d",&n,&m,&k)){
		T.dw(n);
		while(k--){
			scanf("%s",ch);
			if(ch[0]=='g'){
				scanf("%d",&x);
				T.data[0][x]++;
			}
			else if(ch[0]=='e'){
				if(ch[1]=='x'){
					scanf("%d %d",&x,&y);
					for(int i=0;i<=n;i++){
						swap(T.data[i][x],T.data[i][y]); 
					}
				}else {	
					scanf("%d",&x);
					for(int i=0;i<=n;i++){
						T.data[i][x]=0;
					}
				}
			}
		}
		T=T^m;
		printf("%I64d",T.data[0][1]);
		if(T.data[0][1]>(1LL<<32))while(1);
		for(int i=2;i<=n;i++){
			printf(" %I64d",T.data[0][i]);
		}
		puts("");
	}
}

 

Posted by root on Fri, 25 Jan 2019 14:42:14 -0800