您的位置:首页 > 其它

hdu 2276 Kiki & Little Kiki 2 矩阵的应用

2011-07-28 19:49 423 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2276
题目描述:
 There are n lights in a circle numbered from 1 to n. The left of light 1 is light n, and the left of light k (1< k<= n) is the light k-1.At time of 0, some of them turn on, and others turn off.
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)

The input contains one or more data sets. The first line of each data set is an integer m indicate the time, the second line will be a string T, only contains '0' and '1' , and its length n will not exceed 100. It means all lights in the circle from 1 to n.
If the ith character of T is '1', it means the light i is on, otherwise the light is off.

由题意很容易得出:
light[0] = (light[n-1] + light[0])%2;
light[1] = (light[0] + light[1])%2;
light[2] = (light[1] + light[[2])%2;
所以,可以模拟。担考虑到M很大,所要优化。
???怎么优化呢。我也不会,看了人家的Code才Understand。所以说要多做题目,找experience.
对于2^M次方,要想快速求出可以分治:
.==>   if M is even
                       2^M=2^(M/2) * 2^(M/2);
             else
                      2^M=2*(2^(M/2)*2^(M/2);
所以可以利用矩阵的模仿上面的方法。
用;matrix^M * strmatrix = result;
 
先要构造一个矩阵!
| 1 0 0 0 ....1 |
| 1 1 0 0.....0 |     
| 0 1 1 0 ....0|  
另外还要用到单位矩阵。
Code:
 #include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
#define MAXV 105

struct Node{
int Graph[MAXV][MAXV];
};
Node unit,init,Right;
int t,len;
//string str;
char str[MAXV];
void Init(){
int i,j;
for(i=0;i<len;++i)
for(j=0;j<len;++j){
unit.Graph[i][j]=(i==j);
init.Graph[i][j]=Right.Graph[i][j]=0;
}
init.Graph[0][0]=init.Graph[0][len-1]=1;

for(i=1;i<len;++i)
init.Graph[i][i-1]=init.Graph[i][i]=1;
for(i=0;i<len;++i)
Right.Graph[i][0]=str[i]-'0';
}
Node Multy(Node &a,Node &b){
Node c;
int i,j,k;
for(i=0;i<len;++i)
for(j=0;j<len;++j){
c.Graph[i][j]=0;
for(k=0;k<len;++k)
c.Graph[i][j]+=a.Graph[i][k]*b.Graph[k][j];
c.Graph[i][j]%=2;
}
return c;
}
Node Cal(){
Node p,q;
p=unit;q=init;
while(t){
if(t&1)
p=Multy(p,q);
t>>=1;
q=Multy(q,q);
}
p=Multy(p,Right);
return p;
}
int main() {
int i;
// while(cin>>t){
while(scanf("%d",&t)!=EOF){
// cin>>str;
scanf("%s",str);
// len=str.length();
len=strlen(str);
Init();
Node res=Cal();
for(i=0;i<len;++i)
printf("%d",res.Graph[i][0]);
printf("\n");
// cout<<res.Graph[i][0];
// cout<<endl;
}
return 0;
}

 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息