Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 14605 | Accepted: 3612 |
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.
Input
The input file consists of multiple test cases, ending with three zeroes "0 0 0". For each test case, three integers n, m and k are given firstly, where n is the number of cats and k is the length of the move sequence. The following k lines describe the sequence.
(m≤1,000,000,000, n≤100, k≤100)
Output
For each test case, output n numbers in a single line, representing the numbers of peanuts the cats have.
Sample Input
3 1 6 g 1 g 2 g 2 s 1 2 g 3 e 2 0 0 0
Sample Output
2 0 1
Source
题意:有n只猫,三种关于花生的命令(得花生,吃花生,交换花生),给出一套命令,重复m次,问最后每只猫得到多少花生。
解题思路:m那么大,肯定是矩阵快速幂,先构造一个矩阵(n+1)*(n+1)的矩阵,最后一位用来维护得花生的数量,若吃花生,则将这一列清零,若交换花生,则将两列进行交换
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
#include <functional>
using namespace std;
#define LL long long
const int INF=0x3f3f3f3f;
int n,m,k;
struct Matrix
{
LL v[109][109];
Matrix()
{
memset(v,0,sizeof v);
}
} dan;
Matrix mul(Matrix a,Matrix b,int d)
{
Matrix ans;
for(int i=0; i<d; i++)
for(int j=0; j<d; j++)
{
if(!a.v[i][j]) continue;
for(int k=0; k<d; k++)
ans.v[i][k]+=a.v[i][j]*b.v[j][k];
}
return ans;
}
Matrix pow(Matrix a,int k,int d)
{
Matrix ans=dan;
while(k)
{
if(k&1) ans=mul(ans,a,d);
k>>=1;
a=mul(a,a,d);
}
return ans;
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&k)&&(n+m+k))
{
for(int i=0;i<n;i++) dan.v[0][i]=0;
dan.v[0][n]=1;
Matrix a,ans;
for(int i=0;i<=n;i++) a.v[i][i]=1;
char ch[5];
int x,y;
while(k--)
{
scanf("%s%d",ch,&x);
x--;
if(ch[0]=='g') a.v[n][x]++;
else if(ch[0]=='e')
{
for(int i=0;i<=n;i++)
a.v[i][x]=0;
}
else
{
scanf("%d",&y);
y--;
for(int i=0;i<=n;i++)
swap(a.v[i][x],a.v[i][y]);
}
}
ans=pow(a,m,n+1);
printf("%lld",ans.v[0][0]);
for(int i=1;i<n;i++)
printf(" %lld",ans.v[0][i]);
printf("\n");
}
return 0;
}