leetcode 春季个人赛

AC前三题,感觉以后放假还得去混混洛谷长一下见识

第一题 

LCP 28. 采购方案

先排序,再二分往前找和当前数相加小于target合适的个数

class Solution {
public:
    const int mm = 1e9 + 7;
    int purchasePlans(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        long ans = 0;
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] >= target)break;int pos = -1;
            pos = upper_bound(nums.begin(), nums.begin() + i, target - nums[i]) - nums.begin(); 
            ans = (ans + pos) % mm;
        }
        return ans;
    }
};

第二题

LCP 29. 乐团站位

数学题

0层的数字共有(num - 1) * 4

1层的数字共有(num - 3) * 4 , 前两层(2 * num - 2 * 2) * 4

2层的数字共有(num - 5) * 4 , 前三层(3 * num - 3 * 3) * 4

...... 依此类推

L层 开始的数字应该是 (L * num - L * L) * 4 + 1

再判断给定坐标是在四条边的哪一条边上

class Solution {
public:
    int orchestraLayout(int num, int xPos, int yPos) {
        //先找到它在第几层
        //计算出层开始时的编号
        //算出对应乐器编号
        long l = min(min(xPos, num - 1 - xPos), min(yPos, num - 1 - yPos));
        long pre = (num * l - l * l) * 4 % 9;
        long ans = 0;
        if(xPos == l){
            ans = pre + (yPos - l + 1);
            ans %= 9;
        }else if(num - 1 - yPos == l){
            ans = pre + num - (l * 2) - 1 + (xPos - l + 1);
            ans %= 9;
        }else if(num - 1 - xPos == l){
            ans = pre + (num - (l * 2) - 1) * 2 + (num - l - yPos);
            ans %= 9;
        }else{
            ans = pre + (num - (l * 2) - 1) * 3 + (num - l - xPos);
            ans %= 9;
        }
        return ans == 0 ? 9 : ans;
    }
};

第三题

LCP 30. 魔塔游戏

贪心 + 优先队列

用小根堆存储所有的负值,我们优先把耗血量最大的留到最后打就能获得最少的操作次数

同时用sum记录移动到末尾打的怪

class Solution {
public:
    int magicTower(vector<int>& nums) {
        priority_queue<int, vector<int>, greater<int>> q;
        long ans = 0;
        long cur = 1;
        long sum = 0;
        for(int i = 0; i < nums.size(); i++){
            cur += nums[i];
            if(nums[i] < 0) q.push(nums[i]);
            while(cur <= 0){
                if(q.empty()) return -1;
                cur -= q.top();
                sum += q.top();
                q.pop();
                ans++;
            }
        }
        if(cur + sum < 1) return -1;
        return ans;
    }
};
原文地址:https://www.cnblogs.com/Dancing-Fairy/p/14619211.html