그 밖의 방법들

빠른 입출력 [C/C++] 백준 15552번 - 빠른 A+B, 최대한 다양하게

치킨먹고싶어요 2022. 5. 25. 16:01

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

 

15552번: 빠른 A+B

첫 줄에 테스트케이스의 개수 T가 주어진다. T는 최대 1,000,000이다. 다음 T줄에는 각각 두 정수 A와 B가 주어진다. A와 B는 1 이상, 1,000 이하이다.

www.acmicpc.net

핵심

아래의 코드를 main에 넣으시면 cin과 cout의 속도가 비약적으로 상승합니다.

ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cs

혹은 아래와 같은 방식으로 적으시고 main에 fastio()를 선언해 줍니다.

#define fastio() ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cs

 

1. 가장 일반적인 방법

#include <iostream>
 
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n;
    cin >> n;
    int a, b;
    for (int i = 0; i < n; i++) {
        cin >> a >> b;
        cout << a + b << "\n";
    }
}
cs

 

2. 특이한 방법

static const auto fastio = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();
cs

 

static const auto와 람다로 main에 쓰지 않더라도 자동으로 실행해 줍니다.

#include <iostream>
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();
int main() {
    int n, a, b; std::cin >> n;
    while(n-- and std::cin >> a >> b) std::cout << a + b << "\n";
}
cs

3. 클래스

클래스로도 구현해 줍시다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
static const auto fastio = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();
class cal {
public:
    int add(int a, int b);
};
int cal::add(int a, int b) {
    return a + b;
}
auto main() -> int {
    int n, a, b; std::cin >> n; cal c;
    for (;n-->0;std::cin >> a >> b, std::cout << c.add(a, b) << "\n");
}
 
cs