PAT (Advanced Level) Practice——1008,1009

1008:

难度:简单

题意:

我们城市最高的建筑只有一部电梯。N个数字表示电梯将按指定顺序停在哪些楼层。电梯上一层需要 6 秒,下一层需要 4 秒。电梯将在每个站点停留 5 秒。对于给定的N个数字,您将计算完成这些请求所花费的总时间。电梯开始时位于 0 楼,满足请求后不必返回一楼。

思路:

每次更新现在所在的楼层以及计算本层和下一层的差距,根据正负乘以对应需要花费的时间即可(注意负数要乘以绝对值

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n; cin >> n;
    vector<int> a(n);
    for(int i = 0; i < n; i++) cin >> a[i];
    int now = 0,ans = 0;
    for(int i = 0; i < n; i++){
        int tmp = a[i] - now;
        // cout <<"tmp:" <<tmp << '\n';
        if(tmp > 0) ans += 6 * tmp;
        else if(tmp < 0) ans += 4 * abs(tmp);
        now = a[i];
    }
    cout << (ans + n * 5) << '\n';
    return 0;
}

 1009:

题意:

和之前1002相似PAT (Advanced Level) Practice——1001,1002-CSDN博客 ,计算多项式A x B的值。

思路:

首先双层循环计算对应的e指数和系数,重要的是合并同类项这一步,不太爱写循环,所以可以直接用map,完美去重。

还有系数为0的不能加入到map中,不注意这一点,测试点0无法通过

这里由于系数是double类型,具有精度差,所以我们可以利用一个数代表0(1e-9或者1e-6),总之很小就行,如果系数小于这个很小的数,就把其视为0,就需要使用erase消除该项

    int e = a[i].exp + b[j].exp;
    double c = a[i].coe * b[j].coe;
    if (fabs(c) > 1e-9) {  // 排除系数为0的情况
        mp[e] += c;  // 如果系数为0,则不会添加到map中
    if (fabs(mp[e]) < 1e-9) {
            mp.erase(e);  // 如果累加后系数接近0,则从map中删除
        }
    }

其次就是输出时,map是自动降序排序的,并且map不可以用sort函数,所以在申明map的时候我们就可以设置其排序函数为降序。

map<int, double, greater<int>> mp; //降序自动排列
#include <bits/stdc++.h>
using namespace std;

typedef struct {
    int exp;
    double coe;
} X;

map<int, double, greater<int>> mp; //降序自动排列

int main() {
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);

    int na;
    cin >> na;
    vector<X> a(na);
    for (int i = 0; i < na; i++) 
        cin >> a[i].exp >> a[i].coe;

    int nb;
    cin >> nb;
    vector<X> b(nb);
    for (int i = 0; i < nb; i++) 
        cin >> b[i].exp >> b[i].coe;

    for (int i = 0; i < na; i++) {
        for (int j = 0; j < nb; j++) {
            int e = a[i].exp + b[j].exp;
            double c = a[i].coe * b[j].coe;
             if (fabs(c) > 1e-9) {  // 排除系数为0的情况
                mp[e] += c;  // 如果系数为0,则不会添加到map中
                if (fabs(mp[e]) < 1e-9) {
                    mp.erase(e);  // 如果累加后系数接近0,则从map中删除
                }
            }
        }
    }

    cout << mp.size();
    for (auto i : mp) {
        printf(" %d %.1f", i.first, i.second);
    }
    return 0;
}

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值