1. Interval problem
1.1 Interval selection point
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int n;
struct Range
{
int l,r;
bool operator < (const Range &w)const
{
return r < w.r;
}
}range[N];
int main()
{
scanf("%d",&n);
for(int i = 0;i < n;i ++)
{
int l,r;
scanf("%d%d",&l,&r);
range[i] = {l,r};
}
sort(range,range + n);
int res = 0,ed = -2e9;
for(int i = 0;i < n;i ++)
if(range[i].l > ed)
{
res ++;
ed = range[i].r;
}
printf("%d\n",res);
return 0;
}
1.2 Maximum number of disjoint intervals
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int n;
struct Range
{
int l,r;
bool operator < (const Range &w)const
{
return r < w.r;
}
}range[N];
int main()
{
scanf("%d",&n);
for(int i = 0;i < n;i ++)
{
int l,r;
scanf("%d%d",&l,&r);
range[i] = {l,r};
}
sort(range,range + n);
int res = 0,ed = -2e9;
for(int i = 0;i < n;i ++)
if(range[i].l < ed)
{
res ++;
ed = range[i].r;
}
printf("%d\n",res);
return 0;
}
1.3 Interval grouping
2. Huffman tree
Merge fruit
Pick the smallest two piles from all the piles and merge them each time
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
priority_queue<int,vector<int>,greater<int>>heap;
while(n --)
{
int x;
scanf("%d",&x);
heap.push(x);
}
int res = 0;
while(heap.size() > 1)
{
int a = heap.top(); heap.pop();
int b = heap.top(); heap.pop();
res += a + b;
heap.push(a + b);
}
printf("%d\n",res);
return 0;
}