10773 : 제로

서희찬·2021년 9월 15일
0

백준

목록 보기
33/105

문제

코드

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STACK_LEN 100000

typedef int Data;

typedef struct stack{
    Data stackArr[STACK_LEN];
    int topIndex;
}Stack;

void stackInit(Stack * pstack); // init
void SPush(Stack * pstack, Data data); //push
void SPop(Stack * pstack); // pop

int main(void)
{
    int num;
    int sum=0;
    int newNum;
    //스택생성,초기화
    Stack stack;
    stackInit(&stack);

    scanf("%d",&num);
    for(int i=0;i<num;i++)
    {
        scanf("%d",&newNum);
        if(newNum!=0)
        {
            SPush(&stack, newNum);
            
        }else
        {
            SPop(&stack); //빼기
        }
    }
    for(int i=0;i<=stack.topIndex;i++)
    {
        sum+=stack.stackArr[i];
    }
    
    printf("%d\n",sum);
    return 0;
}

void stackInit(Stack * pstack)
{
    pstack->topIndex = -1; //빈상태
}


void SPush(Stack * pstack, Data data)
{
    pstack->stackArr[++(pstack->topIndex)] = data; // 데이터 저장
}

void SPop(Stack * pstack)
{
    pstack->topIndex -= 1;
}

해설

PUSH 와 POP 을 응용한 문제이다.
0이 아닌 숫자가 들어오면 푸쉬를 해주고 0이 들어오면 topIndex에 위치한 값을 팝 해주면 되는것이다!!

처음에 런타임 에러가 떠서 새로작성한 코드가 위의 첫번째 코드인데 ...
런타임에러 뜬 이유 분석해보니 스택의 길이 떄문이였다 .. 크흑 .. ㅋ

원래 짠 코드로 다시 돌려보니 첫번째 보다 훨씬 좋은 성능을 보여줬다.

밑에 것이 원래 짠 코드이다 !

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STACK_LEN 100000
int sum=0;
typedef int Data;

typedef struct stack{
    Data stackArr[STACK_LEN];
    int topIndex;
}Stack;

void stackInit(Stack * pstack); // init
int SIsEmpty(Stack * pstack); // empty

void SPush(Stack * pstack, Data data); //push
void SPop(Stack * pstack); // pop
Data SSum(Stack * pstack);

int main(void)
{
    int num;

    int newNum;
    //스택생성,초기화
    Stack stack;
    stackInit(&stack);

    scanf("%d",&num);
    for(int i=0;i<num;i++)
    {
        scanf("%d",&newNum);
        if(newNum!=0)
        {
            SPush(&stack, newNum);
            
        }else
        {
            SPop(&stack); //빼기
        }
    }
//    for(int i=0;i<=stack.topIndex;i++)
//    {
//        sum+=stack.stackArr[i];
//    }
    
    printf("%d\n",SSum(&stack));
    return 0;
}

void stackInit(Stack * pstack)
{
    pstack->topIndex = -1; //빈상태
}


void SPush(Stack * pstack, Data data)
{
    pstack->stackArr[++(pstack->topIndex)] = data; // 데이터 저장
}

void SPop(Stack * pstack)
{
    pstack->topIndex -= 1;
}
//
Data SSum(Stack * pstack)
{
    for(int i=0;i<=pstack->topIndex;i++)
    {
        sum+=pstack->stackArr[i];
    }
    return sum;
}
profile
부족한 실력을 엉덩이 힘으로 채워나가는 개발자 서희찬입니다 :)

0개의 댓글