出题人题解:(O(m^2))
class Solution {
public:
bool carPooling(vector<vector<int>>& trips, int capacity) {
int all = 0;//判断会不会超过最大载客量
int destination=trips[0][2];
for (int i = 0; i < trips.size(); i++)//找到最远的地点
{
all += trips[i][0];
if (trips[i][2] > destination)
destination = trips[i][2];
}
if (all <= capacity)
return true;
all = 0;
for (int i = 0; i < destination; i++)//不断循环测试每前进一站会发生什么
{
for (int k = 0; k < trips.size(); k++)//是否有人下车上车
{
if (trips[k][2] == i)//下车
{
all -= trips[k][0];
}
if (trips[k][1] == i)//上车
{
all += trips[k][0];
}
}
if (all > capacity)
return false;
}
return true;
}
};
更优解:O(m)
#include <bits/stdc++.h>
using namespace std;
#define sc(x) scanf("%lld", &x)
typedef long long ll;
const ll mn = 1010;
ll n, m, s[mn], in[mn], out[mn], a, b, c, cnt, tp;
signed main()
{
sc(m), sc(n);
while (m--)
{
sc(a), sc(b), sc(c);
in[b] += a, out[c] += a;
tp = max({tp, b, c});
}
for (ll i = 1; i <= tp; ++i)
{
cnt = cnt - out[i] + in[i];
if (cnt > n)
{
printf("0");
return 0;
}
}
printf("1");
return 0;
}