差分2

fufuaifufu發表於2024-11-19

1109.航班預訂統計
題目連結:https://leetcode.cn/problems/corporate-flight-bookings/description/
題解程式碼:

class Solution {
public:
    vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {
        vector<int> d(n);
        for(auto&booking:bookings){
            d[booking[0]-1]+=booking[2];
            if(booking[1]<n){
                 d[booking[1]]-=booking[2];
            }
        }
        for(int i=1;i<n;i++){
            d[i]+=d[i-1];
        }
        return d;
    }
};

1049.拼車
題目連結:https://leetcode.cn/problems/car-pooling/description/
題解程式碼:

class Solution {
public:
    bool carPooling(vector<vector<int>>& trips, int capacity) {
        int tmax=0;
        for(auto& trip:trips) tmax=max(tmax,trip[2]);
        vector<int> d(tmax+1);
        for(auto& trip:trips){
            d[trip[1]]+=trip[0];
            d[trip[2]]-=trip[0];
        }
        int count = 0;
        for (int i = 0; i <= tmax; i++) {
            count += d[i];
            if (count > capacity) {
                return false;
            }
        }
        return true;
    }
};

B. Penchick and Satay Sticks
題目連結:https://codeforces.com/contest/2031/problem/B
題解程式碼:

#include<bits/stdc++.h>
using namespace std;
int main()
{
  int t;
  cin>>t;
  while(t--){
      int n;
      cin>>n;
      vector<int> p(n+1);
      string ans="YES";
      for(int i =1;i<=n;i++){
      cin>>p[i];
      if(abs(p[i]-i)>=2) ans="NO";
      cout<<ans<<endl;
      }
  }
    return 0;
}

相關文章