- BFS기본 (배열사용)

#include <iostream>

using namespace std;

char name[6] = "ABCDE";

int map[5][5] = {
        0,1,1,0,0,
        0,0,0,1,1,
        0,0,0,0,0,
        0,0,0,0,0,
        0,0,0,0,0
};

int head = 0, tail = 1;
int queue[11];

int main() {

    queue[0] = 0;
    while (head != tail) {
        int now = queue[head++];

        cout << name[now] << " ";

        for (int i = 0; i < 5; i++) {
            if (map[now][i] == 1) {
                queue[tail++] = i;
            }
        }
    }

    return 0;
}

- BFS기본 (Queue 사용)

#include <iostream>
#include <queue>

using namespace std;

char name[6] = "ABCDE";

int map[5][5] = {
        0,1,1,0,0,
        0,0,0,1,1,
};

queue<int> q;

int main() {

    q.push(0);

    while (!q.empty()) {
        int now = q.front();
        q.pop();

        cout << name[now] << " ";

        for (int i = 0; i < 5; i++) {
            if (map[now][i] == 1) {
                q.push(i);
            }
        }
    }

    return 0;
}

- BFS기본 (인접리스트, Queue사용)

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

vector<vector<int>> vect(5);
char name[6] = "ABCDE";
queue<int>q;

int main() {
    vect[0].push_back(1);
    vect[0].push_back(2);
    vect[1].push_back(3);
    vect[1].push_back(4);

    q.push(0);

    while (!q.empty()) {
        int now = q.front();
        q.pop();

        cout << name[now] << " ";
        for (int i = 0; i < vect[now].size(); i++) {
            int next = vect[now][i];
            q.push(next);
        }
    }

    return 0;
}

- BFS 그래프 1번씩 탐색

#include <iostream>

using namespace std;

char name[6] = "ABCDE";

int map[4][4] = {
    0,1,0,1,
    0,0,1,0,
    1,0,0,1,
    1,0,0,0,
};

struct node {
    int index;
    int level;
}queue[20];

int head = 0, tail = 1;
int used[4];

void bfs() {
    while (head != tail) {
        node now = queue[head++];
        
        cout << name[now.index] << " ";
        
        for (int x = 0; x < 4; x++) {
            if (map[now.index][x] == 1 && used[x] == 0) {
                used[x] = 1;
                queue[tail++] = { x, now.level + 1 };
            }
        }
    }
}

int main() {
    
    queue[0] = { 0,0 };
    used[0] = 1;
    bfs();

    return 0;
}

- BFS A->E 최소이동거리

#include <iostream>

using namespace std;
char name[6] = "ABCDE";
int map[5][5] = {
    0,1,1,0,0,
    0,0,1,1,0,
    0,1,0,1,1,
    0,1,0,0,1,
    0,0,0,0,0,
};

struct node {
    int index;
    int level;
}queue[100] = { 0,0 };

int head = 0, tail = 1;
int used[5]; //싸이클방지 한번씩만 탐색할때

void bfs() {
    while (head != tail) {
        node now = queue[head++];

        if (now.index == 4) { // name[now.index]=='E'
            cout << now.level;
            return;
        }

        for (int i = 0; i < 5; i++) {
            if (map[now.index][i] == 1 && used[i] == 0) {
                used[i] = 1;
                queue[tail++] = { i,now.level + 1 };
            }
        }
    }
}

int main() {
    used[0] = 1;
    bfs();

    return 0;
}

- BFS A->D 갈수있는 경로 몇가지?

#include <iostream>

using namespace std;
char name[6] = "BACD";

int map[4][4] = {
    0,0,1,1,
    1,0,1,0,
    1,0,0,1,
    0,0,0,0,
};

struct node {
    int index;
    int level;
    int used[4];
}queue[100];

int head = 0, tail = 1, cnt = 0;

void bfs() {
    queue[0].index = 1;
    queue[0].used[1] = 1;

    while (head != tail) {
        node now = queue[head++];

        if (now.index == 3) { // name[now.index]=='E'
            cnt++;
        }

        for (int i = 0; i < 4; i++) {
            if (map[now.index][i] == 1 && now.used[i] == 0) {
                queue[tail] = now;
                queue[tail].index = i;
                queue[tail].level = now.level + 1;
                queue[tail].used[i] = 1;
                tail++;
            }
        }
    }
}

int main() {
    bfs();

    cout << cnt;
    return 0;
}

- BFS A->D 갈수있는 모든경로 출력

#include <iostream>

using namespace std;
char name[6] = "ABCD";

int map[4][4] = {
    0,1,1,1,
    0,0,0,1,
    0,0,0,1,
    1,0,1,0,
};

struct node {
    int index;
    int level;
    int used[4];
    char path[10];
}queue[100] = { 0,0,{1},{'A'}};

int head = 0, tail = 1;

void bfs() {
    while (head != tail) {
        node now = queue[head++];

        if (now.index == 3) { // name[now.index]=='E'
            cout << now.path << endl;
        }

        for (int i = 0; i < 4; i++) {
            if (map[now.index][i] == 1 && now.used[i] == 0) {
                queue[tail] = now;
                queue[tail].index = i;
                queue[tail].level = now.level + 1;
                queue[tail].used[i] = 1;
                queue[tail].path[now.level + 1] = name[i];
                tail++;
            }
        }
    }
}

int main() {

    bfs();
    
    return 0;
}

- 연속된 5개의 합을 구하는데, 합이 최대인곳의 좌표 출력 (On2)

#include <iostream>

using namespace std;
char name[6] = "ABCD";

int arr[11] = { 3,17,4,11,1,5,2,3,4,5,7 };

int mmax = 0;
int sum = 0;
int maxindex = 0;

void bfs() {

    for (int i = 0; i < 7; i++) {
        sum = 0;
        for (int j = i; j < i + 5; j++) {
            sum += arr[j];
        }
        if (sum > mmax) {
            mmax = sum;
            maxindex = i;
        }
    }
    
}

int main() {

    bfs();
    
    cout << maxindex;
    return 0;
}

- 연속된 5개의 합을 구하는데, 합이 최대인곳의 좌표 출력 -> 슬라이딩윈도우 (시간복잡도 On)

#include <iostream>

using namespace std;
char name[6] = "ABCD";

int arr[11] = { 3,17,4,11,1,5,2,3,4,5,7 };

int mmax = 0;
int sum = 0;
int maxindex = 0;

void bfs() {

    for (int i = 0; i < 5; i++) {
        sum += arr[i];
    }

    for (int i = 0; i < 6; i++) {
        if (sum > mmax) {
            mmax = sum;
            maxindex = i;
        }
        sum += arr[i + 5];
        sum -= arr[i];
    }
    
}

int main() {

    bfs();
    
    cout << maxindex;
    return 0;
}

1. N과 M(1)

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;
int m, n;
int path[10] = { 0 };
int used[10] = { 0 };

void run(int le) {

    if (le == m) {
        for (int i = 0; i < le; i++) {
            cout << path[i] << " ";
        }
        cout << "\n";
    }

    for (int x = 0; x < n; x++) {
        if (used[x] != 0) continue;
        used[x] = 1;
        path[le] = x + 1;
        run(le + 1);
        used[x] = 0;
        path[le] = 0;
    }
}

int main() {
    cin >> n >> m;

    run(0);
    return 0;
    
}

1. N과 M(2)

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;
int m, n;
int path[10] = { 0 };
int used[10] = { 0 };

void run(int le, int s) {

    if (le == m) {
        for (int i = 0; i < le; i++) {
            cout << path[i] << " ";
        }
        cout << "\n";
    }

    for (int x = s; x < n; x++) {
        if (used[x] != 0)continue;
        used[x] = 1;
        path[le] = x + 1;
        run(le + 1, x+1); //s+1이아닌 x+1
        used[x] = 0;
        path[le] = 0;
    }
}

int main() {
    cin >> n >> m;

    run(0, 0);
    return 0;
    
}

3. N과 M(3)

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;
int m, n;
int path[10] = { 0 };

void run(int le) {

    if (le == m) {
        for (int i = 0; i < m; i++) {
            cout << path[i] << " ";
        }
        cout << "\n";
        return;
    }

    for (int x = 0; x < n; x++) {
        path[le] = x + 1;
        run(le + 1); 
        path[le] = 0;
    }
}

int main() {
    cin >> n >> m;

    run(0);
    return 0;
    
}

4. N과 M(4)

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;
int m, n;
int path[10] = { 0 };

void run(int le, int s) {

    if (le == m) {
        for (int i = 0; i < m; i++) {
            
            cout << path[i] << " ";
        }
        cout << "\n";
        return;
    }

    for (int x = s; x < n; x++) {
        path[le] = x + 1;
        run(le + 1, x); 
        path[le] = 0;
    }
}

int main() {
    cin >> n >> m;

    run(0, 0);
    return 0;
    
}

5. N-Queen

- Test1. 정답은 맞는데 시간초과..

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;
int n;
int path[20] = { 0 };
int used[20] = { 0 };

//예를 들어(0, 1)을 기준으로 했을때,
//대각선에 있는 점(1, 2) 은(0 - 1) = (1 - 2) = -1 을 만족하며
//대각선에 있는 점(2, 3) 은(0 - 2) = (1 - 3) = -2 를 만족한다.


int cnt = 0;

int abs(int v) {
    if (v < 0) return -v;
    else return v;
}

void check() {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j)continue;
            if (abs(path[i] - path[j]) == abs(i - j)) return;
            if (i == n - 1) {
                /*for (int q = 0; q < n; q++)
                    cout << path[q];
                cout << endl;*/
                cnt++;
                return;
            }
        }
    }
}

void run(int le) {

    if (n == 1) {
        cnt++;
            return;
    }


    if (le == n) {
        check();
        return;
    }

    for(int x = 0; x < n; x++) {
        if (used[x] != 0) continue;
        used[x] = 1;
        path[le] = x;
        run(le + 1);
        used[x] = 0;
        path[le] = 0;
    }

}

int main() {
    cin >> n;
    
    run(0);

    cout << cnt;

    return 0;    
}

- Test2. 이중반복문 사용하지 않고 조건문 활용하기

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;
int n;
int path[20] = { 0 };

//예를 들어(0, 1)을 기준으로 했을때,
//대각선에 있는 점(1, 2) 은(0 - 1) = (1 - 2) = -1 을 만족하며
//대각선에 있는 점(2, 3) 은(0 - 2) = (1 - 3) = -2 를 만족한다.


int cnt = 0;

int abs(int v) {
    if (v < 0) return -v;
    else return v;
}

bool check(int le) { // 같은행에 있을수는 없음
    for (int i = 0; i < le; i++) {
             //이전퀸의 같은 열 || 이전퀸과의 위치차의 절댓값이 같으면 대각선 
        if (path[le] == path[i] || le - i == abs(path[le] - path[i]))
            return false;
    }


    return true;
}

//le = 행, path[le]=해당 행의 퀸 위치
void run(int le) {

    if (n == 1) {
        cnt++;
        return;
    }


    if (le == n) {
        cnt++;

        /*for (int q = 0; q < n; q++)
            cout << path[q];
        cout << endl;*/

        return;
    }

    for (int x = 0; x < n; x++) {
        path[le] = x;
        if (check(le)) //해당행의 배치가 가능하면 재귀 -> 시간복잡도 줄임
            run(le + 1);
    }

}

int main() {
    cin >> n;

    run(0);

    cout << cnt;

    return 0;
}

7. 연산자 끼워넣기

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;

int n;
int num[12] = { 0 };
int p, m, mu, di;
vector <char>cal;
char path[12];
int used[12];
int mmax = -21e8;
int mmin = 21e8;

void run(int le) {
    if (le == n - 1) {
        int result = num[0];
        for (int x = 0; x < le; x++) {
            if (path[x] == 'p')
                result += num[x + 1];
            else if (path[x] == 'm')
                result -= num[x + 1];
            else if(path[x]=='M')
                result *= num[x + 1];
            else if (path[x] == 'D')
                result /= num[x + 1];
        }
        if (result > mmax) mmax = result;
        if (result < mmin) mmin = result;
    }
    
    for (int i = 0; i < n - 1; i++) {
        if (used[i] != 0)continue;
        used[i] = 1;
        path[le] = cal[i];
        run(le + 1);
        used[i] = 0;
        path[le] = '\0';
    }
}

int main() {

    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> num[i];

    cin >> p >> m >> mu >> di;
    
    for (int i = 0; i < p; i++) {
        cal.push_back('p');
    }
    for (int i = 0; i < m; i++) {
        cal.push_back('m');
    }
    for (int i = 0; i < mu; i++) {
        cal.push_back('M');
    }
    for (int i = 0; i < di; i++) {
        cal.push_back('D');
    }

    run(0);

    cout << mmax << '\n' << mmin;

    return 0;    
}

'APS > 백준' 카테고리의 다른 글

[2512] 예산 C++  (0) 2022.02.09
[1920] 수 찾기 C++  (0) 2022.02.08
[3273] 두 수의 합  (0) 2021.08.25
[단계별로 풀어보기] 브루트 포스  (0) 2021.08.16
[단계별로 풀어보기] 재귀  (0) 2021.08.16

cli 명령어로 디비와 백엔드를 연동해보자

1. 작업할 폴더를 만든다. (폴더명 001-sequelize-re)
2. 001-sequelize-re 경로로 이동한다.
3. node package manage로 폴더를 관리한다(npm init -y)
4. 필요 라이브러리를 설치한다.
(npm i express mysql2 sequelize sequelize-cli)
5. npx sequelize init
(config, migrations, models, seeders 폴더가 생성된다.)
6. config 폴더안에 config.js 파일로 가서 db와 맞춰준다. (본인 환경과 맞게)
7 npx sequelize db:create 데이터베이스 스키마를 생성한다.
8 npx sequelize model:generate --name 테이블 이름 --attributes 컬럼이름 (테이블을 생성한다) 띄어쓰기 금지
9 마이그레이션 한다 npx sequelize db:migrate -> up 메서드 실행npx sequelize db:migrate -> down메서드 실행
9-1 컬럼을 추가하고 싶다면 npx sequelize migration:generate --name 이름
9-2 (migrations 폴더안에 새로 생긴 파일안에서 up 메서드를 완성한다)
     await queryInterface.addColumn('users', "test",{
       type:Sequelize.STRING,
     });
9-3 마이그레이션 한다. npx sequelize db:migrate
9-4 models파일에도 추가해준다
10 더미데이터 넣기(seeders를 사용) npx sequelize seed:generate --name 테이블이름
10-1 seeders 폴더안에 파일을 완성한다
10-2 npx sequelize db:seed:all  

 

 

npm init -y

npm i express mysql2 sequelize sequelize-cli

npx sequelize init

npx sequelize db:create

npx sequelize model:generate --name order_list --attributes item:string,type:string

npx sequelize seed:generate --name order_lists

npx sequelize db:seed:all  

'WEB > Node.js' 카테고리의 다른 글

[21.08.17]Node 시작하기  (0) 2021.08.17

서버는 노드로

메신저는 일렉트로닉 프레임

 

REPL : Node의 Shell

 -> 사용자 명령을 읽고, 수행 후 출력하는 동작을 반복하는 터미널

 -> Read(읽고), Eval(해석하고), Print(출력하고, Loop(반복하고)

 

forEach

 -> undefined

map/ filtert/ reduce

 -> 배열반환

 

함수와 메서드

 -> 메서드는 함수의 부분집합이라고 생각하면 됨(함수가 메서드를 포함)

 -> this사용시에만 객체 자신멤버에 접근 가능

 

48p -> 실행결과 예측

 

모듈 = 재사용하기위한 코드 조각

 

서버 = 응답을해주는 컴퓨터

 

npm init -> 초기화 (package.json 생성)  -y

npm install express

npx nodemon (실행할 서버)

 -> 전역설치안하면 새로 만들때마다 설치필요?

npm i dotenv express morgan nodemon

 

nodemon ~.js

 

브라우저에서 http://localhost:포트번호/(루트)

 

postman

new -> http request

 

env  -> 환경변수 관리

morgan -> 로그관리

 

params는 id

 

get -> params에 표부분

post -> 바디에 json으로 text작성 후 send

 

GET

http://localhost:3001/user:id1?name=chicken

 -> user:id1 주소창입력

 -> name(key) chicken(value) params query

 

POST

http://localhost:3001/user

 ->body

{

    "id":"1234",

    "password":"5678"

}

 

PATCH

http://localhost:3001/user:id1

 -> body

{

    "name":"hello"

}

'WEB > Node.js' 카테고리의 다른 글

[21.08.19] Sequelize  (0) 2021.08.19

1. 블랙잭

#include <iostream>

using namespace std;

int n, m;
int card[100];
int cmax = 0;
int sum;
int path[100];
int used[100];

void run(int le) {
    
    if (le == 3) {
        sum = 0;

        for (int i = 0; i < 3; i++) {
            //cout << path[i]<<" ";
            sum += path[i];
        }

        
        //cout << sum << endl;

        if (cmax < sum && sum <= m) {
            cmax = sum;
        }
        return;
    }

    for (int i = 0; i < n; i++) {
        if (used[i] == 1) continue;
        used[i] = 1;
        path[le] = card[i];
        run(le + 1);
        used[i] = 0;
        path[le] = 0;
    }

    if (le == 0)
        cout << cmax;
}

int main() {

    cin >> n;
    cin >> m;

    for (int i = 0; i < n; i++) {
        cin >> card[i];
    }

    run(0);

    return 0;
}

2. 분해합

 - Test1. 재귀사용 - 시간초과

#include <iostream>
#include <cmath>

using namespace std;

int m=0; //자릿수 구하기
int n; //주어진 분해합의 최소생성자 찾기 
int path[8];
int mmin = 1000000;

void run(int le) {

    if (le == m) {
        int sum = 0;
        int s=0;
        for (int x = 0; x < m; x++) {
           // cout << path[x] << " ";
            sum += path[x];
            s += path[x] * pow(10, x);
        }

        if (sum + s == n) {
            if (mmin > s)
                mmin = s;
        }

        //cout << endl;
        
        return;
    }

    for (int i = 0; i <= 9; i++) {
        path[le] = i;
        run(le + 1);
        path [le]= 0;
    }

    return;

}

int main() {

    cin >> n;

    int tmp = n;
    while (tmp) {
        tmp /= 10;
        m++;
        }

    run(0);

    if (mmin == 1000000) cout << 0;
    else cout << mmin;

    return 0;
}

- Test2. 재귀함수 사용X

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

int m=0; //자릿수 구하기
int n; //주어진 분해합의 최소생성자 찾기 
int path[8];
int mmin = 1000000;

int run(int le) {
    int sum=0;
    int tmp = le;
    while (tmp) {
        sum += tmp % 10;
        tmp /= 10;
    }

    return sum + le;
}

int main() {
    vector<int>vec;
    cin >> n;

    for (int i = 1; i <= n; i++) {
        if (run(i) == n)
            vec.push_back(i);
    }

    if (vec.empty()) {
        cout << 0;
        return 0;
    }

    else {
        int size = vec.size();
        for (int i = 0; i < size; i++)
        {
            if (mmin > vec[i])
                mmin = vec[i];
        }
    }

    cout << mmin;
    return 0;
}

3. 덩치

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;
vector<pair<int, int>>vec;
vector<int> result;

int n;

void check(int i) {

    for (int x = 0; x < n; x++) {
        if (i == x)continue;
        if (vec[i].first < vec[x].first && vec[i].second < vec[x].second) {
            result[i]++;
        }
    }
}

int main() {
    int cm, kg;
    cin >> n;


    for (int i = 0; i < n; i++) {
        cin >> cm >> kg;
        vec.push_back(make_pair(cm, kg));
        result.push_back(1);
    }

    for (int i = 0; i < n; i++) {
        check(i);
    }

    for (int i = 0; i < n; i++) {
        cout << result[i] << " ";
    }

    return 0;
}

4. 체스판 다시 칠하기

 -> 비교함수부분 비교조건 앞으로 잘보자..

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

int n, m; //n행, m열
char map[50][50];

char bkmap[9][9] = {
    "BWBWBWBW",
    "WBWBWBWB",
    "BWBWBWBW",
    "WBWBWBWB",
    "BWBWBWBW",
    "WBWBWBWB",
    "BWBWBWBW",
    "WBWBWBWB"
};


char wtmap[9][9] = {
    "WBWBWBWB",
    "BWBWBWBW",
    "WBWBWBWB",
    "BWBWBWBW",
    "WBWBWBWB",
    "BWBWBWBW",
    "WBWBWBWB",
    "BWBWBWBW"
};

int check(int y, int x) {

    int bc = 0, wc = 0;

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if(map[y+i][x+j] != bkmap[i][j])bc++; //비교조건 확인..
            else if (map[y+i][x+j] != wtmap[i][j]) wc++;
        }
    }

    if (bc >= wc) return wc;
    else return bc;

}

int main() {
    
    cin >> n >> m; 

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++)
            cin >> map[i][j];
    }

    int min = 100;

    for (int a = 0; a <= n - 8; a++) { //y
        for (int b = 0; b <= m - 8; b++) { //x
            int result = check(a, b);
            if (min >= result)
                min = result;
        }
    }

    cout << min;


    return 0;
}

5. 영화감독 숌

#include <iostream>
#include <vector>
#include <cstring>
#include <string>

using namespace std;

vector<int>vec;

void check(int i) {
    string tmp = to_string(i);

    if (tmp.find("666", 0) != -1)
        vec.push_back(i);

}

int main() {
    int n;
    cin >> n;

    int a = 666;
    while (1) {
        check(a);
        if (vec.size() == n)
            break;
        a++;
    }

    cout << vec.back();
    return 0;
    
}

'APS > 백준' 카테고리의 다른 글

[2512] 예산 C++  (0) 2022.02.09
[1920] 수 찾기 C++  (0) 2022.02.08
[3273] 두 수의 합  (0) 2021.08.25
[단계별로 풀어보기] 백트래킹  (0) 2021.08.20
[단계별로 풀어보기] 재귀  (0) 2021.08.16

1. 팩토리얼

#include <iostream>

using namespace std;

int n;
int a=1;

void run(int le) {

    a *= le;

    if (n <= 1) {
        cout << 1;
        return;
    }

    if (le == n) {
        cout << a;
        return;
    }
   
    run(le + 1);
    
}

int main() {

    cin >> n;

    run(1);

    return 0;
}

 

2. 피보나치 수 5

#include <iostream>
#include <vector>

using namespace std;

int n;
vector<int> p;

void run(int le) {

    if (le == n) {
        cout << p[n];
        return;
    }

    p.push_back(p[le] + p[le - 1]);

    if (n <= 1) {
        cout << n;
        return;
    }

    

    run(le + 1);

}

int main() {

    cin >> n;

    p.push_back(0);
    p.push_back(1);

    run(1);

    return 0;
}

3. 별 찍기 - 10

#include<iostream>

using namespace std;

// n=3인경우 -> (1,1) (1,4) (1,7) (1,10),...
// n=9인경우 -> (3,3) (3,4) (3,5) / (4,3) (4,4) (4,5) / (5,3) (5,4) (5,5)
 
void run(int i, int j, int n) {
    if ((i / n) % 3 == 1 && (j / n) % 3 == 1) {
        cout << " ";
    }
    else {
        if (n / 3 == 0) 
            cout << "*";
        else {
            run(i, j, n/3);
        }
    }
}

int main() {
    int n;
    cin >> n;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            run(i, j, n);
        }
        cout << '\n';
    }

    return 0;
}

4. 하노이 탑 이동 순서

//하노이탑 이동경로 -> N번째 판을 c로 이동시키기위해 N-1까지 b로 먼저 이동, b에서 c로 이동
//시간초과시 endl -> \n 변경 (그래도 시간초가나오면 scanf, printf)

#include <iostream>
#include <vector>
#include <cmath> //pow사용시 필요함

using namespace std;
// ㅡ ㅡ ㅡ
//  A  B  C

//A판에있는 n-1개의 원판을 B판으로
//A판에 남은 가장 큰원판을 C판으로
//B판의 n-1개의 원판을 C판으로

void hanoi(int n, int start, int by, int to) { //원판수, 출발지, 경유지, 목적지
   //재귀를 돌면서 출발지, 경유지, 목적지가 섞임

    if (n == 1)
        cout << start << " " << to << '\n';

    else    {
        hanoi(n-1, start, to, by); //a판의 n-1개의 원판을 b판으로 옮기는 과정
        //a판에서 c판을 이용해 b판으로 옮긴다.
        cout << start << " " << to << '\n'; //a판의 가장큰 원판 c판으로 옮기기 출력
        hanoi(n - 1, by, start, to); //b판의 n-1의 원판을 c판으로 옮기는 과정
        //b판에서 a판을 이용해 c판으로 옮긴다.
    }

}

int main() {
    int n;
    cin >> n;

    int count=1;
    // 이동횟수는 2의 n제곱 -1
    for (int i = 1; i <= n; i++) {
        count *= 2;
    }

    cout << count - 1 << '\n';

    hanoi(n, 1,2,3); //a판 b판 c판

    return 0;
}

 

'APS > 백준' 카테고리의 다른 글

[2512] 예산 C++  (0) 2022.02.09
[1920] 수 찾기 C++  (0) 2022.02.08
[3273] 두 수의 합  (0) 2021.08.25
[단계별로 풀어보기] 백트래킹  (0) 2021.08.20
[단계별로 풀어보기] 브루트 포스  (0) 2021.08.16

1. 루시와 엘라 찾기

SELECT ANIMAL_ID, NAME, SEX_UPON_INTAKE
FROM ANIMAL_INS
WHERE NAME="Lucy" OR NAME="Ella" OR NAME="Pickle" OR NAME="Rogan" OR NAME="Sabrina" OR NAME="Mitty"
SELECT ANIMAL_ID, NAME, SEX_UPON_INTAKE
FROM ANIMAL_INS
WHERE NAME in ("Lucy","Ella","Pickle","Rogan","Sabrina","Mitty")

2. 이름에 el이 들어가는 동물 찾기

SELECT ANIMAL_ID, NAME
FROM ANIMAL_INS
WHERE ANIMAL_TYPE = "Dog" AND NAME LIKE "%el%"
ORDER BY NAME

3. 중성화 여부 파악하기

SELECT 
    ANIMAL_ID, NAME, 
    IF(SEX_UPON_INTAKE LIKE "%Neutered%" OR SEX_UPON_INTAKE LIKE "%Spayed%", 'O', 'X') AS "중성화"
FROM ANIMAL_INS
ORDER BY ANIMAL_ID

4. 오랜 기간 보호한 동물(2)

SELECT A.ANIMAL_ID, A.NAME
FROM ANIMAL_INS A, ANIMAL_OUTS B
WHERE A.ANIMAL_ID = B.ANIMAL_ID 
ORDER BY B.DATETIME - A.DATETIME DESC
LIMIT 2

5. DATETIME에서 DATE로 형 변환

SELECT 
    ANIMAL_ID, NAME, 
    /* Y(0000), M/D(영문), y(00), m,d(숫자) */
    DATE_FORMAT(DATETIME, "%Y-%m-%d") AS "날짜"
FROM ANIMAL_INS
ORDER BY ANIMAL_ID

1. 없어진 기록 찾기

-- RIGHT JOIN
SELECT B.ANIMAL_ID, B.NAME
FROM ANIMAL_INS A 
RIGHT JOIN ANIMAL_OUTS B
ON A.ANIMAL_ID=B.ANIMAL_ID
WHERE A.ANIMAL_ID IS NULL
ORDER BY ANIMAL_ID

-- NOT IN
SELECT ANIMAL_ID, NAME
FROM ANIMAL_OUTS
WHERE ANIMAL_ID NOT IN (SELECT ANIMAL_ID FROM ANIMAL_INS)

2. 있었는데요 없었습니다

SELECT A.ANIMAL_ID, A.NAME FROM ANIMAL_INS A, ANIMAL_OUTS B 
WHERE A.ANIMAL_ID=B.ANIMAL_ID AND A.DATETIME > B.DATETIME
ORDER BY A.DATETIME

3. 오랜 기간 보호한 동물(1)

-- LEFT JOIN
SELECT INS.NAME, INS.DATETIME
FROM ANIMAL_INS INS
LEFT JOIN ANIMAL_OUTS OUTS
ON INS.ANIMAL_ID=OUTS.ANIMAL_ID
WHERE OUTS.DATETIME IS NULL
ORDER BY INS.DATETIME
LIMIT 3

-- NOT IN
SELECT NAME, DATETIME
FROM ANIMAL_INS
WHERE ANIMAL_ID NOT IN(
    SELECT ANIMAL_ID
    FROM ANIMAL_OUTS
)
ORDER BY DATETIME
LIMIT 3

4. 보호소에서 중성화한 동물

SELECT OUTS.ANIMAL_ID, OUTS.ANIMAL_TYPE, OUTS.NAME
FROM ANIMAL_OUTS OUTS
JOIN ANIMAL_INS INS
ON OUTS.ANIMAL_ID = INS.ANIMAL_ID
WHERE INS.SEX_UPON_INTAKE !=OUTS.SEX_UPON_OUTCOME
ORDER BY ANIMAL_ID

+ Recent posts