HDU 2276 Kiki & Little Kiki 2 (位元運算+矩陣快速冪),hdu2276kiki

來源:互聯網
上載者:User

HDU 2276 Kiki & Little Kiki 2 (位元運算+矩陣快速冪),hdu2276kiki
HDU 2276 Kiki & Little Kiki 2 (位元運算+矩陣快速冪)

ACM

題目地址:HDU 2276 Kiki & Little Kiki 2

題意: 
一排燈,開關狀態已知,每過一秒:第i個燈會根據剛才左邊的那個燈的開關情況變化,如果左邊是開的,它就會變化,如果是關的,就保持原來狀態。問m秒後的狀態。 
第1個的左邊是最後一個。

分析: 
轉移不好想啊。。。 
變化是這樣的:

 
  1. 原來 左邊 變化
  2. 1 1 0
  3. 1 0 1
  4. 0 1 1
  5. 0 0 0

然後想到 (~原來)^(左邊)=變化 
發現搞不成矩陣TAT... 
看了別人題解後發現:(原來+左邊)&2=變化,瞬間orz。 
不過這樣想才沒錯,矩陣需要的是加法。

於是構造矩陣。見大神的矩陣:

 
  1. "1 0 0...0 1
  2. 1 1 0...0 0
  3. 0 1 1...0 0
  4. 0 0 1...0 0
  5. ...........
  6. 0 0 0...1 1
  7. "

最後要注意,如果直接矩陣乘法%2會跪,因為資料太大了。 
這時候可以用位元運算最佳化。 
我們注意到:(1+1)%2和1^1結果一樣,1*1和1&1結果一樣,所以相乘函數改下就行了。

代碼:

/**  Author:      illuz <iilluzen[at]gmail.com>*  Blog:        http://blog.csdn.net/hcbbt*  File:        2276.cpp*  Create Date: 2014-08-03 22:47:12*  Descripton:   */#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <cmath>using namespace std;#define repf(i,a,b) for(int i=(a);i<=(b);i++)typedef long long ll;const int SIZE = 101;// max size of the matrixint n;string s;struct Mat{int n;int v[SIZE][SIZE];// value of matrixMat(int _n = SIZE) {n = _n;memset(v, 0, sizeof(v));}void init(ll _v) {memset(v, 0, sizeof(v));repf (i, 0, n - 1)v[i][i] = _v;}void output() {repf (i, 0, n - 1) {repf (j, 0, n - 1)printf("%d ", v[i][j]);puts("");}puts("");}} a, b, c;Mat operator * (Mat a, Mat b) {Mat c(a.n);repf (i, 0, a.n - 1) {repf (j, 0, a.n - 1) {c.v[i][j] = 0;repf (k, 0, a.n - 1) {c.v[i][j] ^= (a.v[i][k] & b.v[k][j]);}}}return c;}Mat operator ^ (Mat a, ll k) {Mat c(a.n);c.init(1);while (k) {if (k&1) c = c * a;a = a * a;k >>= 1;}return c;}void init() {cin >> s;int len = s.length();a.n = b.n = c.n = len;a.init(0);b.init(0);c.init(0);repf (i, 0, len - 1) {b.v[i][0] = s[i] - '0';}a.v[0][0] = a.v[0][a.n - 1] = 1;repf (i, 1, a.n - 1) {a.v[i][i] = a.v[i][i - 1] = 1;}}void solve(int n) {c = a ^ (n);c = c * b;repf (i, 0, c.n - 1) {printf("%d", c.v[i][0]);}puts("");}int main() {while (~scanf("%d", &n)) {init();solve(n);}return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.