C++ 로 알고리즘 문제풀기에 필요한 내용이어서 메모해둔다. 

 

백준에서 문제풀때 bits/stdc++.h 만 추가하면 되니까 유용하다.

다른 온라인 저지 사이트에서는 사용 안되는 곳이 있으니깐 유의하자.  

 

stdc++.h는 c++ 대부분의 헤더파일명을 다 갖고 있다. 그래서 따로 #include "vector" 해 줄 필요가 없다.

 

환경은 mac M1이고, Clion으로 프로젝트를 만들었다. 아무 설정 없으면 file not found가 뜬다. 

헤더 파일을 못찾는다. 파일이 없으니까 못찾음. 

 

 

1.  터미널 열고  gcc 라이브러리 경로를 확인한다. 

/Library/Developer 어쩌구 경로가 보인다. 

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.5 (clang-1205.0.22.9)
Target: arm64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

2. 아래 명령으로 라이브러리 참조 경로로 이동하자. 

cd /Library/Developer/CommandLineTools/usr/include

3. 아래 명령으로 해당 경로에서 Finder를 열 수 있다. 

open ./

 

3. include 디렉토리 하위에 bits 라는 디렉토리를 만들자. 

 

4. bits 디렉토리 하위에 stdc++.h  파일을 하나 만든다. 

gcc-mirror 깃허브에서 코드를 받을 수 있다.

https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/precompiled/stdc%2B%2B.h

// C++ includes used for precompiling -*- C++ -*-

// Copyright (C) 2003-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

/** @file stdc++.h
 *  This is an implementation file for a precompiled header.
 */

// 17.4.1.2 Headers

// C
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif

5. include 해서 실행되는지 확인하자. 

 


 

 

728x90

문제

윷놀이 백준 2490 c++

 

"맞았습니다."코드 

#include "iostream"
using namespace std;

// 백준 2490 윷놀이
int a, result;
string str = "DCBAE";

void func(){

    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 4; j++){
            cin >> a;
            result += a;
        }
        cout << str[result] << '\n';
        a = result = 0;
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    func();
    return 0;
}


리뷰 

 

답으로 출력할 문자를 이어붙여서 문자열 "DCBAE" 로 만들었다. 

1의 개수를 인덱스로 썼다. 

  0의 개수 1의 개수  문자
1 3 A
2 2 B
3 1 C
4 0 D
0 4 E

 

728x90

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

숫자 백준 10093 c++  (0) 2021.11.20
일곱 난쟁이 백준 2309 c++  (0) 2021.11.20
홀수 백준 2576 c++  (0) 2021.11.19
주사위 세개 c++ 백준 2480  (0) 2021.11.19
BFS 스페셜 저지 백준 16940 c++  (0) 2020.11.05

문제 

홀수 백준 2576

 

"맞았습니다"코드 

#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;

// 백준 2576 홀수
int a;
vector<int> v;
int sumOfOdd;

void func(){

    for(int i = 0; i < 7; i++){
        cin >> a;
        if(a % 2 == 1){
            sumOfOdd += a;
            v.push_back(a);
        }
    }

    sort(v.begin(), v.end());

    if(sumOfOdd == 0){
        cout << -1;
    }else{
        cout << sumOfOdd << '\n';
        cout << v[0];
    }
}


int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    func();
    return 0;
}

 

 

728x90

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

일곱 난쟁이 백준 2309 c++  (0) 2021.11.20
윷놀이 백준 2490 c++  (0) 2021.11.19
주사위 세개 c++ 백준 2480  (0) 2021.11.19
BFS 스페셜 저지 백준 16940 c++  (0) 2020.11.05
N과 M(5), (6) 백준 15654번 c++  (0) 2020.10.22

문제

주사위 세개

 

"맞았습니다." 코드 

#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;

// 백준 2480 주사위 세개

vector<int> v(3);
int result;

void func(){

    sort(v.begin(), v.end());

    if(v[0] == v[2]) { // 셋 다 같은 수
        cout << 10000 + (1000 * v[0]);
    }
    else if((v[0] == v[1]) || (v[1] == v[2])) { // 2개가 같은 수. 항상 공통인 숫자는 2번째 숫자.
        cout << 1000 + (v[1] * 100) ;
    }
    else{ // 셋 다 서로 다른 수
        cout << v[2] * 100;
    }
}

void input(){
    cin >> v[0] >> v[1] >> v[2];
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    input();
    func();

    return 0;
}


리뷰

조건식을 잘못써서 처음에 틀렸다. 

 

틀린 코드는 아래와 같다. 

if((v[0] == v[1]) == v[2]) { // 셋 다 같은 수
    result = 10000 + (1000 * v[0]);
}

틀린 이유는 숫자끼리 비교해야하는데, true와 숫자를 비교했기 때문이다. 

주사위 숫자가 1 1 3 일때, 1 과 1은 같으니까 참이 나온다. 

따라서 1과 3을 비교하게 되는게 아니라, 

true와 3을 비교하게 되므로 항상 true가 나온다. 그래서 틀렸다. 

 

고쳐서 맞은 코드는 아래와 같다.

#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;

// 백준 2480 주사위 세개

vector<int> v(3);
int result;

void func(){

    sort(v.begin(), v.end());

    if((v[0] == v[1]) && (v[1] == v[2])) { // 셋 다 같은 수
        result = 10000 + (1000 * v[0]);
    }
    else if((v[0] == v[1]) && (v[1] != v[2])) { // 앞쪽 2개가 같은 수
        result = 1000 + (v[0] * 100) ;
    }
    else if((v[0] != v[1]) && (v[1] == v[2])) { // 뒤쪽 2개가 같은 수
        result = 1000 + (v[1] * 100) ;
    }
    else{ // 셋 다 서로 다른 수
        result = v[2] * 100;
    }
    cout << result;
}

void input(){
    cin >> v[0] >> v[1] >> v[2];
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    input();
    func();

    return 0;
}

 

좀더 깔끔한 코드는 아래와 같다. 

 

일단 정렬을 한다. 

 

셋 다 같은 수라면, 첫번째 숫자와 세번째 숫자가 같을 것이다. 

    if(v[0] == v[2]) { // 셋 다 같은 수
        cout << 10000 + (1000 * v[0]);
    }

 

같은 수가 2개라면, 1번째 2번째가 같거나. 2번째와 3번째가 같을 것이다. 

두 조건 모두 가운데 숫자가 공통으로 들어간다. 

    else if((v[0] == v[1]) || (v[1] == v[2])) { // 2개가 같은 수. 항상 공통인 숫자는 2번째 숫자.
        cout << 1000 + (v[1] * 100) ;
    }

 

바킹독님 코드 참고 

바킹독님의 코드를 보고 나니깐 벡터를 안써도 됬겠구나 싶었다. 

 

정렬하지 않고, 숫자 두 개가 같은 경우는 3가지 다.

1째와 2째를 비교. 2째와 3째를 비교. 1째와 2째를 비교. 

 

셋 다 다른 수일 때는, max() 함수를 쓴 것이 좋았다. 

728x90

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

윷놀이 백준 2490 c++  (0) 2021.11.19
홀수 백준 2576 c++  (0) 2021.11.19
BFS 스페셜 저지 백준 16940 c++  (0) 2020.11.05
N과 M(5), (6) 백준 15654번 c++  (0) 2020.10.22
알고스팟 1261번 백준 c++  (0) 2020.10.22

환경 

centOS7.5 

MariaDB 

 

목표

B테이블과 연관관계가 있는 A테이블을 삭제하고 싶음 

 

문제 상황 

MariaDB [bim_library]> delete from library_info where library_no between 1 and 50;
ERROR 1451 (23000): Cannot delete or update a parent row: 
a foreign key constraint fails 
(`bim_library`.`tag`, CONSTRAINT `FK2tk1sqt8jfmgqn7st8l73214` 
FOREIGN KEY (`library_no`) REFERENCES `library_info` (`library_no`))

 

해결 과정 

외래키를 해제해주는 명령어가 있었음 

set foreign_key_checks = 0;

테이블 드랍 하고, 

 

반드시 다시 외래키를 체크하는 옵션을 켜줘야 한다. 

set foreign_key_checks = 1;
728x90

@ColumnDefault

ddl-auto 조건이 create 또는 create-drop일 때

즉, 테이블을 처음 생성할 때 컬럼 기본값 제약조건을 정의해준다. 

컬럼에 붙이는 애노테이션.

 

Identifies the DEFAULT value to apply to the associated column via DDL.

DDL에 적용되는 기본 정의 라고 되어있다

Annotation Type ColumnDefault  hibernate javadoc 

 

@DynamicInsert

null이 아닌 값만 insert 해준다. 

만약, null이 들어온 경우, 제약조건에 명시된 기본값이 있다면 그것이 적용되어 insert 된다. 

테이블에 붙이는 애노테이션.

 

Annotation DynamicInsert hibernate userguide 


참고한 글 

JPA @ColumnDefault에 대한 오해, 컬럼 default 적용하기

jpa insert 시 default 값 적용 

테이블에 default 값 적용

728x90

+ Recent posts