rails

链接

这道题,问你火车进站再出站的车厢可能排列情况(全英文也太阴了吧)

我们默认左边是车头,不妨假设只有5节车厢,为1 2 3 4 5进站

假设5在最前,我们发现必须把车一起开进站,那么只能是5 4 3 2 1了

假设4在最前,我们发现前四节车厢必须一起开进站,只能是4 3 2 1,而第五节车厢可以放入任意位置

发现规律了,我们的车厢后面比自己小的车厢必须严格单调递减

比如 4 5 3 2 1是递减的,因为5比4大,不算进去

3 4 5 2 1也是递减的

那么,方法有了,怎么用代码实现呢,我们不妨设一个current=当前车厢-1,接着将current右移,当current遇到小于等于自己的数字时,current进行赋值,一旦遇到比自己大却比一开始的车厢数字小时,直接返回No

没遇到返回No的情况就返回Yes

代码实现

#include<bits/stdc++.h>
using namespace std;
string func(vector<int>ans){
    for (int i = 0;i < ans.size()-1;i++) {
     int count = ans[i] - 1;
     for (int j = i+1;j < ans.size();j++) {
         if (ans[j] < ans[i] && ans[j] <= count) {
             count = ans[j];
         }
         else if (ans[j] < ans[i] && ans[j] > count) {
             return "No";
         }
     }
 }
 return "Yes";
}
int main(){
    int n;
    while(cin >> n && n != 0){
        while(true){
            vector<int> ans;
            int first;
            cin >> first;
            if(first == 0){
                cout << endl; 
                break;
            }
            ans.push_back(first);
            for(int i = 1; i < n; i++){
                int num;
                cin >> num;
                ans.push_back(num);
            }
            cout << func(ans) << endl;
        }
    }
    return 0;
}

时间复杂度O(n²) 空间复杂度:O(n)

全部评论

相关推荐

昨天 08:30
哈尔滨理工大学
在C++中,结构体(struct)&nbsp;是一种用户自定义数据类型,用于将不同类型的变量(成员)组合成一个整体,核心作用是“打包”相关数据,方便管理和使用。1.&nbsp;结构体的基本定义与使用结构体通过&nbsp;&nbsp;struct&nbsp;&nbsp;关键字定义,语法如下,结合代码示例更易理解:代码:#include#&nbsp;includeusing&nbsp;namespace&nbsp;std;//&nbsp;1.&nbsp;定义结构体(相当于创建一个新的&amp;quot;数据模板&amp;quot;)struct&nbsp;Student&nbsp;{//&nbsp;成员变量:不同类型的数据string&nbsp;name;&nbsp;&nbsp;//&nbsp;姓名(string类型)int&nbsp;age;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;年龄(int类型)float&nbsp;score;&nbsp;&nbsp;//&nbsp;分数(float类型)};&nbsp;&nbsp;//&nbsp;注意:结构体定义结尾必须加分号int&nbsp;main()&nbsp;{//&nbsp;2.&nbsp;声明结构体变量(使用&amp;quot;模板&amp;quot;创建具体数据)Student&nbsp;stu1;&nbsp;&nbsp;//&nbsp;stu1&nbsp;是&nbsp;Student&nbsp;类型的变量//&nbsp;3.&nbsp;给成员变量赋值(通过&amp;quot;变量名.成员名&amp;quot;访问)stu1.name&nbsp;=&nbsp;&amp;quot;张三&amp;quot;;stu1.age&nbsp;=&nbsp;18;stu1.score&nbsp;=&nbsp;92.5;//&nbsp;4.&nbsp;访问并输出成员变量cout&nbsp;&amp;lt;&amp;lt;&nbsp;&amp;quot;姓名:&amp;quot;&nbsp;&amp;lt;&amp;lt;&nbsp;stu1.name&nbsp;&amp;lt;&amp;lt;&nbsp;endl;cout&nbsp;&amp;lt;&amp;lt;&nbsp;&amp;quot;年龄:&amp;quot;&nbsp;&amp;lt;&amp;lt;&nbsp;stu1.age&nbsp;&amp;lt;&amp;lt;&nbsp;endl;cout&nbsp;&amp;lt;&amp;lt;&nbsp;&amp;quot;分数:&amp;quot;&nbsp;&amp;lt;&amp;lt;&nbsp;stu1.score&nbsp;&amp;lt;&amp;lt;&nbsp;endl;return&nbsp;0;}输出结果:plaintext姓名:张三年龄:18分数:92.5
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务