现在的位置: 首页 > 综合 > 正文

POJ 3735 Training little cats

2014年02月15日 ⁄ 综合 ⁄ 共 1868字 ⁄ 字号 评论关闭

很神奇的一道矩阵题,这也说明了矩阵的神奇之处。  构造矩阵的方法,我是想不出来了,只能从网上找了找思路。

因m的数据范围较大,用矩阵连乘。

构建矩阵模型,peanut[N] = {0,0,。。。。0,1}:即前n个数为0,最后一个数取1

matrix[N][N],初始化条件下为单位矩阵,。。。

对猫咪进行操作转化为在对矩阵peanut进行操作,一组操作过程转化为矩阵matrix,那么m次操作,即对peanut*(matrix^m)

然后 对题中样例就是

初始化下matrix为单位矩阵
1 0 0 0

0 1 0 0
0 0 1 0
0 0 0 1

输入g
1, 就应该在第1列最后一个加1

1
0 0 0

0
1 0 0

0
0 1 0

1
0 0 1

输入s x y就是把x, y列的值都互换

输入e x,就是把x 列的值都清零

然后用矩阵快速幂就OK了。注意要用__int64 

/*
ID: sdj22251
PROG: subset
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define LOCA
#define MAXN 500005
#define INF 100000000
#define eps 1e-7
#define L(x) x<<1
#define R(x) x<<1|1
using namespace std;
int n, m;
struct wwj
{
    int r, c;
    __int64 mat[105][105];
}need, pea;
void init()
{
    memset(pea.mat, 0, sizeof(pea.mat));
    memset(need.mat, 0, sizeof(need.mat));
    pea.r = 1;
    pea.c = n;
    need.r = n;
    need.c = n;
    for(int i = 1; i <= n; i++)
    {
        pea.mat[1][i] = 0;
        need.mat[i][i] = 1;
    }
    pea.mat[1][n] = 1;
}
wwj multi(wwj x, wwj y)
{
    wwj t;
    int i, j, k;
    memset(t.mat, 0, sizeof(t.mat));
    t.r = x.r;
    t.c = y.c;
    for(i = 1; i <= x.r; i++)
    {
        for(k = 1; k <= x.c; k++)
        if(x.mat[i][k])
        {
            for(j = 1; j <= y.c; j++)
            t.mat[i][j] += x.mat[i][k] * y.mat[k][j];
        }
    }
    return t;
}
int main()
{
#ifdef LOCAL
    freopen("d:/data.in","r",stdin);
    freopen("d:/data.out","w",stdout);
#endif
    int i, j, p, x, y, k;
    char s[5];
    while(scanf("%d%d%d", &n, &m, &k) != EOF)
    {
        if(n == 0 && m == 0 && k == 0) break;
        n++;
        init();
        while(k--)
        {
            scanf("%s", s);
            if(s[0] == 'g')
            {
                scanf("%d", &x);
                need.mat[n][x]++;
            }
            else if(s[0] == 'e')
            {
                scanf("%d", &x);
                for(i = 1; i <= n; i++)
                need.mat[i][x] = 0;
            }
            else if(s[0] == 's')
            {
                scanf("%d%d", &x, &y);
                for(i = 1; i <= n; i++)
                swap(need.mat[i][x], need.mat[i][y]);
            }
        }
        while(m)
        {
            if(m & 1)
            {
                pea = multi(pea, need);
            }
            need = multi(need, need);
            m = m >> 1;
        }
        for(i = 1; i < n; i++)
        printf("%I64d ", pea.mat[1][i]);
        puts("");
    }
    return 0;
}

抱歉!评论已关闭.