백준 10773 : 제로 // 성공

C# 2020. 10. 30. 22:22

나코더 기장 재민이는 동아리 회식을 준비하기 위해서 장부를 관리하는 중이다.

재현이는 재민이를 도와서 돈을 관리하는 중인데, 애석하게도 항상 정신없는 재현이는 돈을 실수로 잘못 부르는 사고를 치기 일쑤였다.

재현이는 잘못된 수를 부를 때마다 0을 외쳐서, 가장 최근에 재민이가 쓴 수를 지우게 시킨다.

재민이는 이렇게 모든 수를 받아 적은 후 그 수의 합을 알고 싶어 한다. 재민이를 도와주자!

첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000)

이후 K개의 줄에 정수가 1개씩 주어진다. 정수는 0에서 1,000,000 사이의 값을 가지며, 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경우 해당 수를 쓴다.

정수가 "0"일 경우에 지울 수 있는 수가 있음을 보장할 수 있다.

:: 성공

: 이전과 달리 그냥 스택을 사용

: 스택 기능 중에 SUM이 있길래 그대로 사용, 꽤 짧다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stack02
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Stack<int> stack = new Stack<int>();

            int commandSize = Int32.Parse(input);
            for(int i = 0; i < commandSize; i++)
            {
                input = Console.ReadLine();
                int inputParse = Int32.Parse(input);

                if (inputParse == 0)
                {
                    stack.Pop();
                } else
                {
                    stack.Push(inputParse);
                }
            }

            Console.WriteLine(stack.Sum());
        }
    }
}

 

'C#' 카테고리의 다른 글

백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 9012 : 괄호 // 성공  (0) 2020.10.31
Study : Quick Sort  (0) 2020.10.26
숫자 출력 시 1000단위 구분기호 추가하는 법  (0) 2020.09.24
블로그 이미지

RIsN

,

::武器を変える。

youtu.be/SlFWpbw6N3Q

>>改善すべき:武器変更を他のスクリプトに入れて使う?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestApp3 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // :: Initialise Buttons
        Button btnNoHand = GameObject.Find("Button_NoHand").GetComponent<Button>();   
        Button btnAxe = GameObject.Find("Button_Axe").GetComponent<Button>();   
        Button btnSpear = GameObject.Find("Button_Spear").GetComponent<Button>();

        // :: Create Character and Instantiate
        GameObject unit = Object.Instantiate(Resources.Load<GameObject>("ch_03_01"));

        // :: Initialise dummyRHand
        Transform dummyRHand = null;

        // :: Find DummyRHand and Remember it
        Transform[] unitChildren = unit.transform.GetComponentsInChildren<Transform>();
        foreach(var child in unitChildren)
        {
            if(child.name == "DummyRHand")
            {
                dummyRHand = child;
                break;
            }
        }

        // :: Initialise currentWeaponName
        string currentWeaponName = null;

        // :: Add Event Listener : Button No Hand
        btnNoHand.onClick.AddListener(() =>
        {
            // :: When you have weapon
            if(currentWeaponName != null)
            {
                // :: Find current weapon by name
                Transform currentWeapon = dummyRHand.transform.Find(currentWeaponName);

                // :: Release parent
                currentWeapon.transform.SetParent(null);

                // :: Destroy current weapon
                Object.Destroy(currentWeapon.gameObject);

                // :: Set Current Weapon Name : null
                currentWeaponName = null;
            }
        });

        // :: Add Event Listener : Button Axe
        btnAxe.onClick.AddListener(() =>
        {
            // :: When you don't have weapon
            if (currentWeaponName == null)
            {
                // :: Resources Load and Set Parent
                var currentWeapon = Object.Instantiate<GameObject>(Resources.Load<GameObject>("Axe_3"));
                currentWeapon.transform.SetParent(dummyRHand, false);

                // :: Set Current Weapon Name
                currentWeaponName = currentWeapon.name;
            }
        });

        // :: Add Event Listener : Button Spear
        btnSpear.onClick.AddListener(() =>
        {
            // :: When you don't have weapon
            if (currentWeaponName == null)
            {
                // :: Resources Load and Set Parent
                var currentWeapon = Object.Instantiate<GameObject>(Resources.Load<GameObject>("Spear_7"));
                currentWeapon.transform.SetParent(dummyRHand);
                currentWeapon.transform.localPosition = Vector3.zero;
                currentWeapon.transform.localRotation = Quaternion.Euler(Vector3.zero);

                // :: Set Current Weapon Name
                currentWeaponName = currentWeapon.name;
            }
        });

    }
}
블로그 이미지

RIsN

,

::目標たちを辿って宝箱を開けてみよう。

:2020-10-29

youtu.be/taYBOVJ_OHg

>>改善すべき:関数を分けるより、一つのログを作ってそれに従うようにしよう。

>>疑問点:キュー(Queue)を使ってみたが方向性が違った感じがする。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class App : MonoBehaviour
{
    // Start is called before the first frame update
    Queue<GameObject> targets;
    GameObject beforeTarget;
    GameObject chestClosed;
    GameObject chestOpened;
    GameObject lastTarget;
    void Start()
    {
        // :: Load Targets with name
        targets = new Queue<GameObject>();
        for(int i = 1; i <= 3; i++)
        {
            targets.Enqueue(GameObject.Find("Target" + i));

            if(i == 3)
            {
                lastTarget = GameObject.Find("Target" + i);
            }
        }
        Debug.Log(targets.Count);

        // :: Initialise Chest
        GameObject chestPrefabA = Resources.Load<GameObject>("chest_close");
        GameObject chectPrefabB = Resources.Load<GameObject>("chest_open");

        // :: Render Chest Closed and Set Position
        chestClosed = Object.Instantiate<GameObject>(chestPrefabA);
        chestClosed.transform.position = lastTarget.transform.position + new Vector3(0, 0f, 0.5f);
        chestClosed.transform.eulerAngles = new Vector3(-90, -90, 0);

        // :: Render Chest Open and Set Position and Set Active false;
        chestOpened = Object.Instantiate<GameObject>(chectPrefabB);
        chestOpened.transform.position = chestClosed.transform.position;
        chestOpened.transform.eulerAngles = chestClosed.transform.eulerAngles;
        chestOpened.SetActive(false);

        // :: Initialise beforeTarget
        beforeTarget = new GameObject();

        // :: Button Load and Attach OnClick Function : Create
        Button BUTTON_create = GameObject.Find("Button_Create").GetComponent<Button>();
        BUTTON_create.onClick.AddListener(() => OnClick());

        // :: Button Load and Attach OnClick Function : GoAndTurn
        Button BUTTON_goAndTurn = GameObject.Find("Button_GoAndTurn").GetComponent<Button>();
        BUTTON_goAndTurn.onClick.AddListener(() => { RunToTarget(); });
    }

    // :: Run to Target
    void RunToTarget(float speed = 0.5f)
    {   
        // :: If you have remain targets
        if(targets.Count > 0)
        {
            // :: Go Target
            beforeTarget = targets.Peek();
            unit.GetComponent<Unit>().RunToTarget(targets.Dequeue(), speed);
        }
    }
    // :: Go Target
    void WalkToTarget(float speed = 0.5f)
    {
        // :: If you have remain targets
        if (targets.Count > 0)
        {
            // :: Go Target
            beforeTarget = targets.Peek();
            unit.GetComponent<Unit>().WalkToTarget(targets.Dequeue(), speed);
        }
    }

    // :: Go Complete
    void GoComplete()
    {
        // :: Target Remains
        if(targets.Count > 0)
        {
            // :: When arrived target1
            if (targets.Peek().name.Contains("2"))
            {
                // :: Look at target forward
                unit.GetComponent<Unit>().LookTarget(beforeTarget.transform.forward);
                unit.GetComponent<Unit>().WaitNow();
            }
            else
            {
                // :: Walk To Target
                this.WalkToTarget();
            }
        } else
        {
            Debug.Log("You've got treasure!");
            chestClosed.SetActive(false);
            chestOpened.SetActive(true);
            
        }
    }

    // :: Wait Complete
    void WaitComplete()
    {
        Debug.Log("wait is Over!");

        // :: Walk To Target
        this.WalkToTarget();
    }

    // :: OnClick Function
    // ::: for Variables
    GameObject unit; // :: Unit
    void OnClick()
    {
        // :: Unit Resources Load & Instantiate
        unit = Instantiate<GameObject>(Resources.Load<GameObject>("ch_03_01"));
        unit.AddComponent<Unit>().goComplete = () => { GoComplete(); };
        unit.GetComponent<Unit>().waitComplete = () => { WaitComplete(); };
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Unit : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // :: Look at direction of Target
    public void LookTarget(Vector3 direction)
    {
        this.gameObject.transform.LookAt(direction);
    }

    // :: Go and Turn with Target
    // ::: for Variables

    // :: Run To Target Function
    // ::: for Variables
    bool isGo = false;
    string animationName_Run = "run@loop";
    string animationName_Idle = "idle@loop";
    GameObject target; // ::: target
    float speed = 0.5f; // ::: Move Speed
    public void RunToTarget(GameObject target, float speed = 0.5f)
    {
        // :: Remember Target
        this.target = target;

        // :: Remember Speed
        this.speed = speed;

        // :: Look at Target
        this.LookTarget(this.target.transform.position);

        // :: Animation Run
        this.gameObject.GetComponent<Animation>().Play(animationName_Run);

        // :: Start Update
        isGo = true;
    }

    // :: Walk To Target Function
    string animationName_Walk = "walk@loop";
    public void WalkToTarget(GameObject target, float speed = 0.05f)
    {
        // :: Remember Target
        this.target = target;

        // :: Remember Speed
        this.speed = speed;

        // :: Look at Target
        this.LookTarget(this.target.transform.position);

        // :: Animation Run
        this.gameObject.GetComponent<Animation>().Play(animationName_Walk);

        // :: Start Update
        isGo = true;
    }

    // :: Wait Function
    float waitTime;
    bool isWait = false;
    float elapsedTime = 0f;
    public CheckComplete waitComplete = () => { };
    public void WaitNow(float waitTime = 3f)
    {
        // :: Remember Wait Time
        this.waitTime = waitTime;

        // :: Start Update
        isWait = true;
    }

    // Update is called once per frame
    // ::: for Variables
    public delegate void CheckComplete();
    public CheckComplete goComplete = () => { };
    void Update()
    {
        // :: Start Go
        if(isGo)
        {
            // :: Go Toward
            this.gameObject.transform.position = Vector3.MoveTowards(this.gameObject.transform.position, this.target.transform.position, speed * Time.deltaTime);

            // :: Check Distance
            float distance = Vector3.Distance(this.gameObject.transform.position, this.target.transform.position);

            // :: When near the Cube
            if(distance <= 0.2f)
            {
                // :: Stop Go
                isGo = false;

                // :: Change Animation
                this.gameObject.GetComponent<Animation>().Play(animationName_Idle);

                // :: Send Move Complete
                this.goComplete();
            }
        }
        // :: Start Wait
        else if(isWait)
        {
            // :: Check Elapsed Time
            elapsedTime += Time.deltaTime;
            Debug.Log(elapsedTime);

            // :: When Wait is Over
            if(elapsedTime >= waitTime)
            {
                // :: Stop Wait
                isWait = false;

                // :: Send Wait Complete
                this.waitComplete();
            }
        }
    }
}
블로그 이미지

RIsN

,