본문 바로가기
problem-solving

boj 12925: Numbers

by pikkaso 2022. 1. 22.

https://www.acmicpc.net/problem/12925

 

12925번: Numbers

각 Test case에 대해, “Case #c: x”의 형식으로 각 줄에 정답을 출력한다. c는 Test Case의 번호이다. (1부터 매겨진다.) x는 해당 Test Case의 정답이다.

www.acmicpc.net

 

(7)번식을 n이 크기가 크기때문에 분할정복 으로 캐싱하며 해결하면 된다. 기본적으로 Identity및 matrix multiplication을 class작성하여 구현하였다.

#include<bits/stdc++.h>
#define MOD 1000000000LL
using namespace std;

typedef long long ll;
int tc,n,c=0;

ll mod(ll x, ll y){
    if(x%y < 0) return x%y+y;
    else return x%y;
}

ll trans_(ll x){
  return x%MOD;
}

class matrix{
    public:
    int sizeofm;
    vector<vector<ll>> m;
    matrix(int n):sizeofm(n){}
    matrix(int n, vector<vector<ll>> v):sizeofm(n){
        m.resize(n,vector<ll>(n,0));
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                m[i][j] = v[i][j];
            }
        }
    }
};

vector<vector<ll>> mul(vector<vector<ll>> A, vector<vector<ll>> B){
    vector<vector<ll>> C(2,vector<ll>(2,0));
    for(int row=0;row<2;row++){
        for(int col=0;col<2;col++){
            ll sum = 0;
            for(int i=0;i<2;i++){
                sum += A[row][i] * B[i][col];
                sum = trans_(sum);
            }
            C[row][col] = sum;
        }
    }
    return C;
}

vector<vector<ll>> identity(){
    vector<vector<ll>> I(2,vector<ll>(2,0));
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){
            if(i==j) I[i][j] = 1LL;
            else I[i][j] = 0;
        }
    }
    return I;
}

vector<vector<ll>> power(matrix &A, long long B){
    if(B == 0) return identity();
    else if(B == 1) return A.m;
    else if(B & 1){
        vector<vector<ll>> tmp = power(A,B/2);
        return mul(A.m,mul(tmp,tmp));
    }
    else{
        vector<vector<ll>> tmp = power(A,B/2);
        return mul(tmp,tmp);
    }
}

int main(){

  ios::sync_with_stdio(0);
  cin.tie(0);
  cin>>tc;
  vector<vector<ll>> v(2,vector<ll>(2,0));
  v[0][0] = 6LL;
  v[0][1] = -4LL;
  v[1][0] = 1LL;
  v[1][1] = 0;
  matrix Ir(2,v);
  while(tc--){
    cin>>n;
    vector<vector<ll>> nIr = power(Ir,n-1);
    ll ans_ll = mod(mod(nIr[1][0]*28LL+nIr[1][1]*6LL-1LL,MOD),MOD)%1000LL;
    string ans = to_string(ans_ll);
    if(ans_ll < 100) ans = "0" + ans;
    if(ans_ll < 10) ans = "0" + ans;
    cout<<"Case #"<<++c<<": "<<ans<<'\n';
  }


  return 0;
}

 

'problem-solving' 카테고리의 다른 글

boj 16957: 체스판 위의 공  (0) 2022.02.11
boj 23848: 등비수열의 합  (0) 2022.01.22
boj 10159: 저울  (0) 2021.08.26
boj 16922: 로마 숫자 만들기  (0) 2021.06.03
boj 10265: MT  (0) 2021.04.11

댓글