【题解】2020牛客寒假算法基础集训营4

比赛链接:https://ac.nowcoder.com/acm/contest/3005




A - 欧几里得(规律 + 斐波那契数列)

原题链接:https://ac.nowcoder.com/acm/contest/3005/A

  • 思路: 对于这类问题,暴力肯定超时。那么可以先打下表,把前十个 a 和 b 打表找规律,会发现 a 和 b 分别是斐波那契数列。

Code:

#include <iostream>
using namespace std;
typedef long long ll;
ll f1[100],f2[100],ans[100];
int main(){
    f1[0]=1,f1[1]=2;
    for(int i=2;i<=80;i++)
        f1[i]=f1[i-1]+f1[i-2];
    f2[0]=0,f2[1]=1;f2[2]=2;
    for(int i=3;i<=80;i++)
        f2[i]=f2[i-1]+f2[i-2];
    for(int i=0;i<=80;i++)
        ans[i]=f1[i]+f2[i];
    int t;    cin>>t;
    while(t--){
        int n;    cin>>n;
        cout<<ans[n]<<endl;
    }
    return 0;
}


B - 括号序列(栈)

原题链接:https://ac.nowcoder.com/acm/contest/3005/B

  • 思路: 经典栈问题。

Code:

#include <iostream>
#include <stack>
using namespace std;
int main(){
    string str;    cin>>str;
    stack<char> s;
    for(int i=0;i<str.length();i++){
        if(str[i]=='(')
            s.push(str[i]);
        if(str[i]==')'){
            if(!s.empty() && s.top()=='(')
                s.pop();
            else{
                cout<<"No"<<endl;
                return 0;
            }
                
        }
        if(str[i]=='[')
            s.push(str[i]);
        if(str[i]==']'){
            if(!s.empty() && s.top()=='['){
                s.pop();
                
            }
            else{
                cout<<"No"<<endl;
                return 0;
            }
                
        }
        if(str[i]=='{')
            s.push(str[i]);
        if(str[i]=='}'){
            if(!s.empty() && s.top()=='{'){
                s.pop();
                
            }
            else{
                cout<<"No"<<endl;
                return 0;
            }
                
        }
    }
    if(s.empty())
        cout<<"Yes"<<endl;
    else
        cout<<"No"<<endl;
    return 0;
}


发布了123 篇原创文章 · 获赞 57 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44668898/article/details/104292168
今日推荐