9.26总结

本文通过实例演示如何利用栈实现括号平衡检查,涉及输入验证、栈操作和输出判断。通过编程解决题目,深入理解栈在判断括号平衡中的应用,并探讨了额外字符处理和清空栈的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把之前做过的题在做一遍并且写题解,因为有的题做过第一次第二次拿过来就不一定还能做出来。

The Balance of the World

The world should be finely balanced. Positive vs. negative, light vs. shadow, and left vs. right brackets. Your mission is to write a program that judges whether a string is balanced with respect to brackets so that we can observe the balance of the world.

A string that will be given to the program may have two kinds of brackets, round (“( )”) and square (“[ ]”). A string is balanced if and only if the following conditions hold.

  • For every left round bracket (“(”), there is a corresponding right round bracket (“)”) in the following part of the string.
  • For every left square bracket (“[”), there is a corresponding right square bracket (“]”) in the following part of the string.
  • For every right bracket, there is a left bracket corresponding to it.
  • Correspondences of brackets have to be one to one, that is, a single bracket never corresponds to two or more brackets.
  • For every pair of corresponding left and right brackets, the substring between them is balanced.

Input

The input consists of one or more lines, each of which being a dataset. A dataset is a string that consists of English alphabets, space characters, and two kinds of brackets, round (“( )”) and square (“[ ]”), terminated by a period. You can assume that every line has 100 characters or less. The line formed by a single period indicates the end of the input, which is not a dataset.

Output

For each dataset, output “yes” if the string is balanced, or “no” otherwise, in a line. There may not be any extra characters in the output.

Sample Input

So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
 .
.

Output for the Sample Input

yes
yes
no
no
no
yes
yes

判断括号是否对称,使用栈,碰到左括号就进栈,碰到右括号出栈,判断是否对称,!!!!!!!!一定要在最后再判断一下栈是否为空!!!!!!在这个地方卡了好几次,还要注意输入结束的标志,输入.表示结束,但是前面有空格的话就说明这还是一个案例。还有就是对栈的清空操作了。找了半天没有clear这个操作,只能自己写清空操作。第一次做的时候感觉对栈有所了解,今天更加熟悉栈的操作了。

#include<iostream>
#include<stack>
#include<string>
#include<stdio.h>
using namespace std;
int main()
{

    string s;
    while(getline(cin,s))
    {
        stack<char> st;
        bool k=true;
        if(s[0]=='.')
            break;
        else
        {
            for(int i=0;i<s.length();i++)
            {
                if(s[i]=='.')
                    break;
                if(s[i]=='('||s[i]=='[')
                    st.push(s[i]);
                else if(s[i]==')')
                {
                    if(st.empty()||st.top()!='(')
                        k=false;
                    else
                    {
                        st.pop();
                    }
                }
                else if(s[i]==']')
                {
                    if(st.empty()||st.top()!='[')
                        k=false;
                    else
                    {
                        st.pop();
                    }
                }
            }
            if(!st.empty())k=false;
            k?cout<<"yes"<<endl:cout<<"no"<<endl;
            while(!st.empty())
            {
                st.pop();
            }
        }
    }
    return 0;
}

Let the Balloon Rise

Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges’ favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.

This year, they decide to leave this lovely job to you.

Input

Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) – the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.

A test case with N = 0 terminates the input and this test case is not to be processed.

Output

For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.

Sample Input

5
green
red
blue
red
red
3
pink
orange
pink
0

Sample Output

red
pink

判断出现次数对多的颜色,使用map,存最大的次数,最后迭代找。

刚开始我想在存最大次数的时候直接把最大的颜色用max_name存着,但是运行之后发现不行,还有就是注意对这个图的清空操作。

#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
    int n;
    string color;
    map<string,int> m;
    while(cin>>n&&n!=0)
    {
        int max_count=0;
        while(n--)
        {
            cin>>color;
            m[color]++;
            if(m[color]>max_count)
                max_count=m[color];
        }
        for(map<string,int>::iterator it=m.begin();it!=m.end();it++)
        {
            if(it->second==max_count)
            {
                cout<<it->first<<endl;
                break;
            }
        }
        m.clear();
    }
    return 0;
}

Shopping

Every girl likes shopping,so does dandelion.Now she finds the shop is increasing the price every day because the Spring Festival is coming .She is fond of a shop which is called “memory”. Now she wants to know the rank of this shop’s price after the change of everyday.

Input

One line contians a number n ( n<=10000),stands for the number of shops.
Then n lines ,each line contains a string (the length is short than 31 and only contains lowercase letters and capital letters.)stands for the name of the shop.
Then a line contians a number m (1<=m<=50),stands for the days .
Then m parts , every parts contians n lines , each line contians a number s and a string p ,stands for this day ,the shop p 's price has increased s.

Output

Contains m lines ,In the ith line print a number of the shop “memory” ‘s rank after the ith day. We define the rank as :If there are t shops’ price is higher than the “memory” , than its rank is t+1.

Sample Input

3
memory
kfc
wind
2
49 memory
49 kfc
48 wind
80 kfc
85 wind
83 memory

Sample Output

1
2

题意:看memory这个商店在价格在第几位,是累加,而不是更新。

!!在循环输入的时候不要使用while,要使用for,因为while循环之后值会变,因为下一次一次循环还要使用,所以不能改变第一次输入的值,就是样例里的3,代码里的n,代码里的t可以用while,因为是测试的组数,而n是商店的个数,一直都是n个商店不变的,在这个地方卡输入了,怎么输入都没有输出结果。

第二次做一遍也没能做出来。

#include<stdio.h>
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cmath>
#include<cstdio>
using namespace std;
int main()
{

    int n,t,p;
    string s;
    while(cin>>n)
    {
        map<string,int> m;
        for(int i=0;i<n;i++)
        {
            cin>>s;
        }
        cin>>t;
        while(t--)
        {

            for(int i=0;i<n;i++)
            {
                cin>>p>>s;
                m[s]+=p;
            }
            int ans=1;
            for(map<string,int>::iterator it=m.begin();it!=m.end();it++)
            {
                if(it->second>m["memory"])
                    ans++;
            }
            cout<<ans<<endl;
        }
    }
    return 0;
}

产生冠军

有一群人,打乒乓球比赛,两两捉对撕杀,每两个人之间最多打一场比赛。
球赛的规则如下:
如果A打败了B,B又打败了C,而A与C之间没有进行过比赛,那么就认定,A一定能打败C。
如果A打败了B,B又打败了C,而且,C又打败了A,那么A、B、C三者都不可能成为冠军。
根据这个规则,无需循环较量,或许就能确定冠军。你的任务就是面对一群比赛选手,在经过了若干场撕杀之后,确定是否已经实际上产生了冠军。

Input

输入含有一些选手群,每群选手都以一个整数n(n<1000)开头,后跟n对选手的比赛结果,比赛结果以一对选手名字(中间隔一空格)表示,前者战胜后者。如果n为0,则表示输入结束。

Output

对于每个选手群,若你判断出产生了冠军,则在一行中输出“Yes”,否则在一行中输出“No”。

Sample Input

3
Alice Bob
Smith John
Alice Smith
5
a c
c d
d e
b e
a d
0

Sample Output

Yes
No

题意:判断冠军,是否能判断出来谁是冠军,如果能判断出来就yes否则就no

使用两个集合,一个用来存参赛选手的姓名,另一个用来存失败的选手的姓名,最后两个集合做差值,如果正正好好等于一的话就说明有且只有一个人没有被打败过,那么就能判断出冠军,如果不等于一的话就说明找不出冠军来,输出no。

这题一遍就做出来了,就是思维题。

#include<iostream>
#include<string>
#include<set>
#include<stdio.h>
using namespace std;
int main()
{
    set<string> s1,s2;
    string str1,str2;
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0)
            break;
        while(n--)
        {
            cin>>str1>>str2;
            s1.insert(str1);
            s1.insert(str2);
            s2.insert(str2);
        }
        s1.size()-s2.size()==1?cout<<"Yes"<<endl:cout<<"No"<<endl;
        s1.clear();
        s2.clear();
    }
    return 0;
}

Stones

Because of the wrong status of the bicycle, Sempr begin to walk east to west every morning and walk back every evening. Walking may cause a little tired, so Sempr always play some games this time.
There are many stones on the road, when he meet a stone, he will throw it ahead as far as possible if it is the odd stone he meet, or leave it where it was if it is the even stone. Now give you some informations about the stones on the road, you are to tell me the distance from the start point to the farthest stone after Sempr walk by. Please pay attention that if two or more stones stay at the same position, you will meet the larger one(the one with the smallest Di, as described in the Input) first.

Input

In the first line, there is an Integer T(1<=T<=10), which means the test cases in the input file. Then followed by T test cases.
For each test case, I will give you an Integer N(0<N<=100,000) in the first line, which means the number of stones on the road. Then followed by N lines and there are two integers Pi(0<=Pi<=100,000) and Di(0<=Di<=1,000) in the line, which means the position of the i-th stone and how far Sempr can throw it.

Output

Just output one line for one test case, as described in the Description.

Sample Input

2
2
1 5
2 4
2
1 5
6 6

Sample Output

11
12

题意:扔石头,从左边开始,扔奇数块石头,下标为奇数,偶数就不管,如果两块石头在同一个位置,扔最大的,输出最远的那块石头的位置。

用优先队列,遇到奇数就加上距离,然后放回去,最后输出位置。

#include<stdio.h>
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cmath>
#include<cstdio>
using namespace std;
struct stone
{
    int pos,dis;
};
bool operator<(const stone &a,const stone &b)
{
    if(a.pos==b.pos)
        return a.dis>b.dis;
    return a.pos>b.pos;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        priority_queue<stone> qu;
        int n;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            stone s;
            cin>>s.pos>>s.dis;
            qu.push(s);
        }
        int cnt=1;
        while(!qu.empty())
        {
            stone t;
            if(cnt%2!=0)
            {
                t=qu.top();
                qu.pop();
                t.pos+=t.dis;
                qu.push(t);
                cnt++;
            }
            else
            {
                t=qu.top();
                qu.pop();
                cnt++;
            }
            if(qu.empty())
                cout<<t.pos<<endl;
        }

    }
    return 0;
}

pairs

John has nn points on the X axis, and their coordinates are (x[i],0),(i=0,1,2,…,n−1)(x[i],0),(i=0,1,2,…,n−1). He wants to know how many pairs<a,b><a,b> that |x[b]−x[a]|≤k.(a<b)|x[b]−x[a]|≤k.(a<b)

Input

The first line contains a single integer TT (about 5), indicating the number of cases.
Each test case begins with two integers n,k(1≤n≤100000,1≤k≤109)n,k(1≤n≤100000,1≤k≤109).
Next nn lines contain an integer xixi, means the X coordinates.

Output

For each case, output an integer means how many pairs<a,b><a,b> that |x[b]−x[a]|≤k|x[b]−x[a]|≤k.

Sample Input

2
5 5
-100
0
100
101
102
5 300
-100
0
100
101
102

Sample Output

3
10

题意:从第一个数据开始,往他后面找,与他相差不超过正负k的数,有一个算一个,ans加一。

对输入的数据进行排序,注意要从下标为1的开始输入,控制循环条件为小于等于,因为之后要找位置,位置的序号要从1开始,所以输入数据的时候下标就从1开始,输入之后用sort排序,接下来就开始找位置,从第一个元素开始判断,从当前位置,到结束位置,找第一个大于等于当前元素的位置,用l记录,大的下标减去小的下标,然后ans加上。

注意!!ans用long long 定义,第一次用int ,wa了一发。

#include<stdio.h>
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        int a,b,p[100010];
        long long ans=0;
        cin>>a>>b;
        for(int i=1;i<=a;i++)
            cin>>p[i];
        sort(p+1,p+a+1);
        for(int i=1;i<=a;i++)
        {
            int l=lower_bound(p+i+1,p+a+1,p[i]-b)-p-1;
            int r=upper_bound(p+i+1,p+a+1,p[i]+b)-p-1;
            ans+=r-l;
        }
        cout<<ans<<endl;
    }
    return 0;
}

ps:不要为了偷懒而使用万能头。

D. Make a Power of Two

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given an integer nn. In 11 move, you can do one of the following actions:

  • erase any digit of the number (it’s acceptable that the number before the operation has exactly one digit and after the operation, it is “empty”);
  • add one digit to the right.

The actions may be performed in any order any number of times.

Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number 301301 the digit 33, the result is the number 0101 (not 11).

You need to perform the minimum number of actions to make the number any power of 22 (i.e. there’s an integer kk (k≥0k≥0) such that the resulting number is equal to 2k2k). The resulting number must not have leading zeroes.

E.g. consider n=1052n=1052. The answer is equal to 22. First, let’s add to the right one digit 44 (the result will be 1052410524). Then let’s erase the digit 55, so the result will be 10241024 which is a power of 22.

E.g. consider n=8888n=8888. The answer is equal to 33. Let’s erase any of the digits 88 three times. The result will be 88 which is a power of 22.

Input

The first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases. Then tt test cases follow.

Each test case consists of one line containing one integer nn (1≤n≤1091≤n≤109).

Output

For each test case, output in a separate line one integer mm — the minimum number of moves to transform the number into any power of 22.

Example

input

Copy

12
1052
8888
6
75
128
1
301
12048
1504
6656
1000000000
687194767

output

Copy

2
3
1
3
0
0
2
1
3
4
9
2

Note

The answer for the first test case was considered above.

The answer for the second test case was considered above.

In the third test case, it’s enough to add to the right the digit 44 — the number 66 will turn into 6464.

In the fourth test case, let’s add to the right the digit 88 and then erase 77 and 55 — the taken number will turn into 88.

The numbers of the fifth and the sixth test cases are already powers of two so there’s no need to make any move.

In the seventh test case, you can delete first of all the digit 33 (the result is 0101) and then the digit 00 (the result is 11).

这题是前两天刚刚做过的题,今天回头再看一遍,由于过得时间不是很长,所以还是没有什么大问题的。

题意:就是给一个数,操作就是可以删除任意一个数,然后只能在末尾加数,让他变成一个二的倍数,让操作数最小

思路:拿输入的数跟2的n次幂进行比较,从头开始比较,看两个相似程度,如果相等的话就都往后移,不相等的话就只移输入的字符串,初始化操作我想直接使用to_string存字符串,但是编译器有毛病,选择了c++11还是用不了,所以使用sstream来转成字符串,答案就是删除的长度加上网上加的长度。

#include<bits/stdc++.h>
using namespace std;
long long num[60];
void init()
{
     for(int i=0;i<60;i++)
        num[i]=pow(2,i);
}
int main()
{
    int t;
    init();
    cin>>t;
    while(t--){
        string s1;
        cin>>s1;
        int l1=s1.length(),l2;
        int p1,p2,ans=2*l1;
        for(int i=0;i<60;i++){
            p1=0;
            p2=0;
            stringstream sstream;
            sstream<<num[i];
            string nn;
            sstream>>nn;
            int cnt=0;
            l2=nn.length();
            while(p1<l1&&p2<l2){
                if(s1[p1]==nn[p2]){
                    p2++;
                    cnt++;
                }
                p1++;
            }
            ans=min(ans,(l1-cnt+l2-p2));
        }
        cout<<ans<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值