728x90
https://www.acmicpc.net/problem/2257
2257번: 화학식량
첫째 줄에 화학식이 주어진다. 화학식은 H, C, O, (, ), 2, 3, 4, 5, 6, 7, 8, 9만으로 이루어진 문자열이며, 그 길이는 100을 넘지 않는다.
www.acmicpc.net
#include <stdio.h> // 화학식량
#include <stdlib.h>
#include <string.h>
typedef struct
{
int ptr;
int *stk;
}STACK;
int is_empty(STACK *s)
{
if (s->ptr <= 0)
return 1;
else
return 0;
}
void push_plus(STACK *s, int data)
{
s->stk[s->ptr] += data;
}
int pop(STACK *s)
{
return s->stk[s->ptr--];
}
int main()
{
char str[101];
scanf("%s", str);
int len = strlen(str);
STACK s;
s.ptr = 0;
s.stk = (int*)malloc(sizeof(int) * len);
for (int i = 0; i < len; i++)
s.stk[i] = 0;
int temp;
for (int i = 0; i < len; i++)
{
if (str[i] == 'H')
{
temp = 1;
push_plus(&s, 1);
}
else if (str[i] == 'C')
{
temp = 12;
push_plus(&s, 12);
}else if (str[i] == 'O')
{
temp = 16;
push_plus(&s, 16);
}
else if (str[i] == '(')
{
s.stk[++s.ptr] = 0;
}
else if (str[i] == ')')
{
temp = pop(&s);
push_plus(&s, temp);
}
else if (str[i] >= 2 && str[i] <= '9')
{
push_plus(&s, temp * ((str[i] - '0') - 1));
}
}
printf("%d", s.stk[0]);
return 0;
}
MEMO
-- 스택에 값을 계속 추가(push)하는 것이 아니라 값을 더하기(push_plus)
-- '(' 가 나오면 ')' 가 나오기 전까지 스택의 다음 공간에 값을 더하기(push_plus)
-- 스택의 처음 공간(s.stk[0])에 최종합이 담겨짐
!!스택의 개념은 알고 있지만 제대로 활용하기 위해서 문제를 많이 풀어보아야 할 것 같다.!!
728x90
728x90
'백준[baekjoon] > C언어' 카테고리의 다른 글
백준(baekjoon) [C] - 11866번: 요세푸스 문제 0 (0) | 2023.01.22 |
---|---|
백준(baekjoon) [C] - 1966번: 프린터 큐 (0) | 2023.01.22 |
백준(baekjoon) [C] - 2164번: 카드2 (0) | 2023.01.21 |
백준(baekjoon) [C] - 2493번: 탑 (0) | 2023.01.21 |
백준(baekjoon) [C] - 23253번: 자료구조는 정말 최고야(실패) (0) | 2023.01.20 |