반응형

문제 출처 :

 

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


알고리즘 분석 :


문제 해결에 필요한 사항

1. 식에서의 괄호의 이해


2. -의 이용


-가 나오면 그다음 -가 나오기 전까지 모든 +는 -( .. + .. + .. + .. )로 묶어내어 모두 음수값으로 만들어 버릴 수 있다.


예를들어 2 + 3 - 2 + 1 + 1 + 1 - 1 - 1은


5 - (2 + 1 + 1 + 1) - 1 - 1로 만들어 내는 알고리즘을 이용하면 된다.



소스 코드 : 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <stdlib.h>
#include <string.h>
 
using namespace std;
 
char str[51];
int i = 0;
 
void passInt()
{
    while ('0' <= str[i] && str[i] <= '9')
        i++;
}
 
int main()
{
    int sum = 0;
    int minus = 0;
    int len;
 
    cin >> str;
    len = strlen(str);
 
    if (str[0== '-')
    {
        i++;
        minus -= atoi(str);
        passInt();
    }
    else
    {
        sum += atoi(str);
        passInt();
    }
    while (i < len)
    {
        if (str[i] == '+')
        {
            i++;
            sum += atoi(str+i);
            passInt();
        }
 
        else if (str[i] == '-')
        {
            i++;
            minus -= atoi(str+i);
            passInt();
 
            while (i < len)
            {
                if (str[i] == '+')
                {
                    i++;
                    minus -= atoi(str + i);
                    passInt();
                }
                else
                    break;
            }
        }
 
        else
            passInt();        
    }
 
    printf("%d", sum + minus);
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


반응형