zoukankan      html  css  js  c++  java
  • 算法学习--Day5

    其实今天是第六天,不过昨天写的题目有些杂乱,都是贪心的算法,所以昨天的题目就不放上来了。

    今天开始入手数据结构吧啦吧啦。。

    数据结构当时学的时候感觉挺简单的,不过现在真正上代码之后发现情况并不妙,还是好好刷题好好学习。

    第一题不是oj上的,但是我感觉很有用,是堆栈的基础题目。所以我把它也放上来。

    题目介绍:输入包括多组数据,每组数据一行,包含一个字符串与左右括号()。

    样例输入:  )(rttyy())sss)(

    输出:  

    )(rttyy())sss)(     

    ?              ?$

     

    #include <stdio.h>
    #include<iostream>
    #include <stack>
    using namespace std;
    
    stack<int> S;
    char str[110];
    char ans[110];
    
    int main(){
        while (scanf("%s",str)!=EOF){
            for (int i = 0; str[i]!=0; ++i) {
                if (str[i]=='('){
                    S.push(i);
                    ans[i]=' ';
                }
                else if(str[i]==')'){
                    if(!S.empty()){
                        S.pop();
                        ans[i]=' ';
                    }
                    else{
                        ans[i]='?';
                    }
                }
                else ans[i]=' ';
    
            }
            while (!S.empty()){
                ans[S.top()]='$';
                S.pop();
            }
            cout<<ans<<endl;
        }
        return 0;
    }

    这里用到了stack库,并初始化了一个int类型的S堆栈。

    使用了 pop、top、push、empty函数来操作这个堆栈。

     

    题目描述

    哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。

    输入描述:

    输入有多组数据。
    每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。

    输出描述:

    输出权值。
    示例1

    输入

    5  
    1 2 2 5 9
    

    输出

    37

    #include <iostream>
    #include <queue>
    #include <stdio.h>
    using namespace std;
    priority_queue<int, vector<int>, greater<int> > q;
    
    int main(){
    int n;
        while (scanf("%d",&n)!=EOF){
            while (!q.empty()) q.pop();
            for (int i = 0; i <n ; ++i) {
                int x;
                cin>>x;
                q.push(x);
            }
            int ans=0;
            while (q.size()>1){
                int a = q.top();
                q.pop();
                int b = q.top();
                q.pop();
                ans+=a+b;
                q.push(a+b);
            }
            cout<<ans<<endl;
        }
        return 0;
    }
  • 相关阅读:
    [CF786B] Legacy
    [CF833B] The Bakery
    [JSOI2008] 最小生成树计数
    [SDOI2010] 外星千足虫
    [POJ1830] 开关问题
    [Luogu1365] WJMZBMR打osu! / Easy
    [Noip2016] 换教室
    [NOI2002] 荒岛野人
    [计蒜之道复赛 2018] 贝壳找房计数比赛
    [SDOI2014] 旅行
  • 原文地址:https://www.cnblogs.com/Pinging/p/8893788.html
Copyright © 2011-2022 走看看