동식이 취업시키기 작전/코딩테스트
[백준] 1541 잃어버린 괄호(C#)
이동식이
2024. 1. 26. 22:32
728x90
문제
https://www.acmicpc.net/problem/1541
1541번: 잃어버린 괄호
첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다
www.acmicpc.net
수학문제다. 괄호를 적절히 삽입하여 가장 작은 수를 구해야한다.
코드
using System;
using System.Text;
using System.Collections.Generic;
namespace dongsik
{
class Baekjoon
{
static void Main(string[] str)
{
string[] arr = Console.ReadLine().Split("-");
string[] plus = arr[0].Split("+");
int total = 0;
foreach(string s in plus)
{
total += int.Parse(s);
}
if(arr.Length <= 1)
{
Console.WriteLine(total);
return;
}
for(int i = 1; i < arr.Length; i++)
{
string[] minus = arr[i].Split("+");
foreach(string s in minus)
{
total -= int.Parse(s);
}
}
Console.WriteLine(total);
}
}
}
고민
가장 작은 수를 구해야하므로 빼기를 잘 해야한다. 그래서 우린 주어진 수에서 마이너스만 잘 해주면 된다.
마이너스를 기준으로 split을 하면 배열의0번째는 무조건 더해주고 나머지는 모두 빼주면 된다.
어떤 말이냐면
이렇게 정리된다.