[0906]滴滴笔试题参考解题报告
连续最大和
分析:
经典水题。没啥好说的. 时间复杂度: O(n)
参考code:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
scanf("%d",&n);
int sum = 0, mx = -99999999;
for(int j = 0; j < n; j++){
int temp;
scanf("%d",&temp);
if(sum < 0) sum = temp;
else sum += temp;
mx = max(sum, mx);
}
printf("%d\n",mx);
}
餐馆
分析:
贪心。先把顾客进行消费金额降序,人数升序排序。 然后枚举每波顾客去二分当前最适合的 桌子的容量,维护答案即可,注意答案可能爆int。 这题裸暴力过不了。 不能拆桌。时间复杂度:O(mlogm + nlogm)
参考code:
#include <iostream>
#include <map>
#include <vector>
#include <map>
using namespace std;
struct node{
int b,c;
};
int cmp(node x,node y){
if (x.c == y.c) {
return x.b < y.b;
}
return x.c > y.c;
}
int n,m;
long long ans;
std::vector<node> v;
std::multimap<int, int> mp;
int main(){
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++){
int x; scanf("%d",&x);
mp.insert(std::pair<int, int>(x, 1));
}
for(int i = 0; i < m; i++){
int x, y;
scanf("%d%d",&x,&y);
node tmp;
tmp.b = x, tmp.c = y;
v.push_back(tmp);
}
sort(v.begin(),v.end(),cmp);
for(int i = 0; i < m; i++){
std::map<int,int>::iterator it = mp.lower_bound(v[i].b);
if (it != mp.end()) {
mp.erase(it);
ans += v[i].c;
}
}
printf("%lld\n",ans);
}
巨人网络成长空间 50人发布