Machineboy空
C# 문제 풀이 빠른 입출력 본문
문제 풀이시, 입력을 좀 더 효율적으로 처리하기 위해서 정리해둔다.
입력: 입력값을 정수로 바꾸기
string input = Console.ReadLine();
int num = int.Parse(input);
int input = int.Parse(Console.ReadLine());
입력: 여러 개의 입력값을 공백으로 구분하여 나누기
string input = Console.ReadLine();
string[] splited = input.Split(' ');
string[] input = Console.ReadLine().Split();
입력: 입력 길이가 정해져 있지 않은 경우
while(true){
string input = Console.ReadLine();
if(input == null) break;
}
출력: StringBuilder 활용하기
https://www.acmicpc.net/problem/15552
1) 시간초과 코드
- Console.Write 반복 호출
- string 사용
using System;
namespace CodingTestForBaekJoon
{
class Program
{
static void Main(string[] args)
{
string T = Console.ReadLine();
int numT = Int32.Parse(T);
for (int i = 0; i < numT; i++)
{
string[] pair = Console.ReadLine().Split();
int A = Int32.Parse(pair[0]);
int B = Int32.Parse(pair[1]);
int Sum = A + B;
Console.WriteLine(Sum);
}
}
}
}
2) 통과한 코드
String Builder | String |
가변 객체 (mutable) | 불변 객체(immutable) |
문자열 수정할 때, 기존 버퍼에 데이터를 추가 | 문자열을 수정하면 기존 객체를 버리고, 새로운 객체 생성 |
기존의 메모리 공간을 재사용, 할당, 복사 반복되지 않음. | 매번 새로운 메모리 공간을 할당, 이전 문자열 복사 |
using System;
using System.Text;
namespace CodingTestForBaekJoon
{
class Program
{
static void Main(string[] args)
{
int T = int.Parse(Console.ReadLine());
StringBuilder result = new StringBuilder();
for (int i = 0; i < T; i++)
{
string[] s = Console.ReadLine().Split();
int a = int.Parse(s[0]);
int b = int.Parse(s[1]);
result.AppendLine((a + b).ToString());
}
Console.Write(result.ToString());
}
}
}
(이하 참고해보면 좋은 자료)
빠른 입출력 모음
이 문서에 없는 관련 정보를 알고 계신다면 이 구글 폼에 제출해주세요. 감사합니다. C scanf와 printf는 충분히 빠릅니다. scanf 얘기가 나와서 덧붙이자면, 빠른 입출력과는 관계 없는 얘기지만 scanf
docs.google.com
N개의 행 입력받기
int N = int.Parse(Console.ReadLine());
for(int i = 0; i < N; i++){}
while(N-- > 0){}
'언어 > C#' 카테고리의 다른 글
자주 쓰는 Math Library 함수 (0) | 2025.03.17 |
---|---|
NullReferenceException (0) | 2025.03.12 |
C# 메소드 오버로딩(Overloading) (0) | 2025.02.28 |
C# 자원 해제(Resource Clean up) try~catch, finally, using Dipose() (0) | 2025.02.26 |
C# 데이터 형식 변환(Type Convension) & Type Casting (0) | 2025.02.25 |