Description
Facer's pet cat just gave birth to a brood of little cats. Having considered the health of those lovely cats, Facer decides to make the cats to do some exercises. Facer has well designed a set of moves for his cats.
He is now asking you to supervise the cats to do his exercises. Facer's great exercise for cats contains three different moves:
- g i : Let the ith cat take a peanut.
- e i : Let the ith cat eat all peanuts it have.
- s i j : Let the ith cat and jth cat exchange their peanuts.
All the cats perform a sequence of these moves and must repeat it m times! Poor cats! Only Facer can come up with such embarrassing idea.
You have to determine the final number of peanuts each cat have, and directly give them the exact quantity in order to save them.
Analysis
矩阵应用里最难的一题???
难点在于利用矩阵实现对原数的加法,怎么在不影响其他数的基础上变出一个加数呢?在数学课上..我想出了这个算法。
其实对原数的加法处理,不就是加上在原数上加上若干个1吗,这个1可以放在原矩阵的末尾,1的权值在乘矩阵中,最后只要少输出一个不就行了。
另外..写矩阵的时候疯狂出错,我也不知道为什么。到现在这个对拍正确无数次的程序依然WA...
Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int N=110;
char read(){
char i=getchar();
while(i<'a'||i>'z')i=getchar();
return i;
}
struct Matrix{
int h,l,s[N][N];
void clear(){
memset(s,0,sizeof(s));
}
void output(){
for(int i=0;i<h;i++){
for(int j=0;j<l-2;j++)
printf("%d ",s[i][j]);
printf("%d \n",s[i][l-2]);
}
}
Matrix operator * (Matrix x){
Matrix y;
y.clear();
y.h=h,y.l=x.l;
for(int i=0;i<h;i++)
for(int j=0;j<x.l;j++)
for(int k=0;k<l;k++)
y.s[i][j]+=s[i][k]*x.s[k][j];
return y;
}
Matrix operator *= (Matrix x){
return *this=*this*x;
}
}A,C,E;
void Cnit(int row){
C.clear();
C.h=1,C.l=row,C.s[0][row-1]=1;
}
void Enit(int row){
E.clear();
E.h=row,E.l=row;
for(int i=0;i<row;i++)
E.s[i][i]=1;
}
Matrix Fast_pow(int i){
Matrix a,b;
a=A,b=E;
while(i){
if(i&1)b*=a;
i>>=1;
a*=a;
}
return b;
}
void take(int i){
A.s[A.h-1][i]++;
}
void eatup(int i){
for(int j=0;j<A.h;j++)
A.s[j][i]=0;
}
void exchange(int x,int y){
for(int i=0;i<A.h;i++)
std::swap(A.s[i][x],A.s[i][y]);
}
int main(){
int n,m,k;
while(scanf("%d%d%d",&n,&k,&m)){
if(!(n+m+k))break;
Cnit(n+1);
Enit(n+1);
A=E;
while(m--){
int i,j;
char act=read();
scanf("%d",&i);
if(act=='g')take(i-1);
else if(act=='e')eatup(i-1);
else{
scanf("%d",&j);
exchange(i-1,j-1);
}
}
C*=Fast_pow(k);
C.output();
}
return 0;
}
本文介绍了一种通过矩阵运算来模拟猫咪进行特定锻炼计划的算法。面对一系列复杂的操作指令,如获取花生、吃掉所有花生及交换花生等,文章提出了一种巧妙的方法来解决这一问题:将操作转化为矩阵运算,利用矩阵乘法来高效地计算经过多次重复后的最终状态。此外,还讨论了如何在不影响其他元素的情况下实现对特定位置数值的加法操作。
773

被折叠的 条评论
为什么被折叠?



