IMOS-累积和法
概念
imos法是将累积和算法扩展到多次元、高次元的方法
基础IMOS法
最简单的imos法是1次元0次系数的求解思想。如图,有三个俄罗斯方块,悬空的部分会掉下来,求从左到右的高度
例题
题目描述:经营一个咖啡厅,咖啡厅的客人在S时刻进店,E时刻进店。求店里最多有多少客人?
**方法一:朴素解法 **
#include <iostream>
#include <algorithm>
using namespace std;
#define C 4
#define T 10
// 每个客人的进入时间
int S[C] = { 1, 3, 5, 7 };
// 每个客人的离开时间
int E[C] = { 2, 8, 6, 8 };
// 店里的人数
int table[T];
///SubMain//
int main(int argc, char *argv[])
{
memset(table, 0, sizeof(table));
for (int i = 0; i < C; i++)
{
// 从时间 S[i] 到 E[i] - 1 店里人数计数加一
for (int j = S[i]; j < E[i]; j++)
{
table[j]++;
}
}
// 找最大値
cout << *max_element(table, table + T) << endl;
system("pause");
return 0;
}
///End Sub//
时间复杂度为o(CT)
方法二:IMOS法
#include <iostream>
#include <algorithm>
using namespace std;
#define C 4
#define T 10
// 每个客人的进入时间
int S[C] = { 1, 3, 5, 7 };
// 每个客人的离开时间
int E[C] = { 2, 8, 6, 8 };
// 店里的人数
int table[T];
///SubMain//
int main(int argc, char *argv[])
{
memset(table, 0, sizeof(table));
for (int i = 0; i < C; i++)
{
table[S[i]]++; // 入店+1
table[E[i]]--; // 出店-1
}
// 累加
for (int i = 1; i < T; i++)
{
table[i] += table[i - 1];
}
// 找最大値
cout << *max_element(table, table + T) << endl;
system("pause");
return 0;
}
///End Sub//
整体思路:等价于使用了微积分的方法,首先对进店和出店的动作进行微分,那么进店为+1,出店为-1。求店内人数相当于求解对时间轴进行积分
LeetCode题目日程安排表
题目
解题内容
class MyCalendarTwo {
public:
MyCalendarTwo() {
}
bool book(int start, int end) {
can[start]++;
can[end]--;
int sum=0;
for(auto t:can){
sum+=t.second;
if(sum>2){
can[start]--; //主要理解微分与积分的方法,该方法思路简便。但效率不高
can[end]++;
return false;
}
}
return true;
}
private:
map<int,int> can;
};
/**
* Your MyCalendarTwo object will be instantiated and called as such:
* MyCalendarTwo obj = new MyCalendarTwo();
* bool param_1 = obj.book(start,end);
*/