Kiki & Little Kiki 2
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1376 Accepted Submission(s): 726
Problem Description
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)
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)
Input
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.
If the ith character of T is '1', it means the light i is on, otherwise the light is off.
Output
For each data set, output all lights' state at m seconds in one line. It only contains character '0' and '1.
Sample Input
1 0101111 10 100000001
Sample Output
1111000 001000010
package acm.hdu;
import java.util.Scanner;
public class Hdu2276_20130606_2119 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long m;
String str ;
while(in.hasNextLong()){
m = in.nextLong();
str = in.next();
int [][] result = solve(str,m);
showA(result);
}
}
private static int [][] solve(String str,long m){
int n = str.length();
int [][] init = new int[1][n];
int [][] unit = new int[n][n];
int [][] temp = getArray(n);
for(int i = 0; i < n; ++i){
init[0][i] = str.charAt(i) - '0';
unit[i][i] = 1;
}
while(m > 0){
if((m&1)==1){
unit = multipyMatrix(temp,unit);
}
temp = multipyMatrix(temp,temp);
m >>= 1;
}
return multipyMatrix(init,unit);
}
private static int [][] multipyMatrix(int [][] a, int [][] b){
int [][] c = new int[a.length][b[0].length];
for(int i = 0; i < a.length; ++i){
for(int j = 0;j < b[0].length; ++j){
for(int k = 0; k < b.length; ++k){
c[i][j] = c[i][j]^(a[i][k]&b[k][j]);
}
}
}
return c;
}
private static int [][] getArray(int n){
int [][] array = new int[n][n];
for(int i = 0; i < n-1; ++i){
array[i][i] = 1;
array[i][i+1] = 1;
}
array[n-1][n-1] = 1;
array[n-2][n-1] = 1;
array[n-1][0] = 1;
return array;
}
private static void showA(int [][] array){
StringBuilder sb = new StringBuilder();
for(int [] as:array){
for(int a: as){
sb.append(a);
}
}
System.out.println(sb);
}
}