NYOJ 300 hdu 2276 Kiki Little Kiki 2 (矩阵快速幂)
生活随笔
收集整理的這篇文章主要介紹了
NYOJ 300 hdu 2276 Kiki Little Kiki 2 (矩阵快速幂)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Kiki & Little Kiki 2
時間限制:5000?ms ?|? 內存限制:65535?KB 難度:4 描述Change the state of light i (if it's on, turn off it; if it is not on, turn on it) at t+1 second (t >= 0), if the left of light i is on !!! Given the initiation state, please find all lights’ state after M second. (2<= n <= 100, 1<= M<= 10^8) 輸入
If the ith character of T is '1', it means the light i is on, otherwise the light is off.
題意:給出一些燈的初始狀態(用0、1表示),對這些燈進行m次變換;若當前燈的前一盞燈的狀態為1,則調整當前燈的狀態,0變為1,1變為0;否則不變。第1盞燈的前一盞燈是最后一盞燈。問最后每盞燈的狀態。
分析:通過模擬可以發現,假設有n盞燈,第i盞燈的狀態為f[i],則f[i] = (f[i] + f[i-1])%2;又因為這些燈形成了環,則f[i] = (f[i] + f[(n+i-2)%n+1])%2. 這樣初始狀態形成一個1*n的矩陣,然后構造出如下n*n的矩陣:
1 ?1 ?0…… 0 ? 0
0 ?1 ?1…… 0 ? 0
……………………
1 ?0 ?0…… 0 ? 1
每次乘以這個矩陣得出的結果就是下一個狀態。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 105; char state[N]; struct Matrix {Matrix() {}void Init(int n) {row = n; col = n;memset(mat, 0, sizeof(mat));for(int i = 0; i < n; i++)mat[i][i] = 1;}void Init(int m, int n) {row = m; col = n;memset(mat, 0, sizeof(mat));}int row, col;int mat[N][N];const Matrix &Pow(int n); };const Matrix &operator *(const Matrix &A, const Matrix &B) {Matrix res;res.Init(A.row, B.col);for(int i = 0; i < A.row; i++) {for(int j = 0; j < A.col; j++) {if(A.mat[i][j]) {for(int k = 0; k < B.col; k++) {if(B.mat[j][k])res.mat[i][k] = res.mat[i][k] ^ (A.mat[i][j] & B.mat[j][k]);}}}}return res; }const Matrix &Matrix::Pow(int n) {Matrix tmp, pre;tmp = *this;pre.Init(this->row);while(n) {if(n&1) pre = tmp * pre;tmp = tmp * tmp;n >>= 1;}return pre; }int main() {int m;Matrix A, B, ans;while(~scanf("%d", &m)) {scanf("%s",state);int len = strlen(state);A.Init(1, len);for(int i = 0; i < len; i++)A.mat[0][i] = state[i] - '0';B.Init(len);for(int i = 0; i < len; i++) {B.mat[i][i] = 1;B.mat[i][(i+1)%len] = 1;}ans = A * B.Pow(m);for(int i = 0; i < len; i++)printf("%d", ans.mat[0][i]);printf("\n");}return 0; }
總結
以上是生活随笔為你收集整理的NYOJ 300 hdu 2276 Kiki Little Kiki 2 (矩阵快速幂)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Github 上热门的 Spring B
- 下一篇: SpringBoot 2.x Shard