贪心算法水题
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
struct node
{
int start;
int end;
};
struct node arr[100010];
int cmp(const void *a, const void *b)
{
struct node *pa = (struct node*)a;
struct node *pb = (struct node*)b;
if(pa->start > pb->start)
return 1;
else if(pa->start == pb->start)
return 0;
else
return -1;
}
void func(int n, int m)
{
int i, j;
int count;
int max_end, choose_start, choose_end;
vector<struct node> v;
struct node no;
bool f;
qsort(arr, n, sizeof(struct node), cmp);
int end = 0; //当前覆盖的区域的右边的坐标
v.clear();
for(i=0; i<n; )
{
if(arr[i].start <= end)
{
max_end = arr[i].end;
choose_start = arr[i].start;
choose_end = arr[i].end;
for(j=i; j<n; j++)
{
if(arr[j].start <= end)
{
if(arr[j].end > max_end)
{
max_end = arr[j].end;
choose_start = arr[j].start;
choose_end = arr[j].end;
}
}
else
{
break;
}
}
end = max_end;
no.start = choose_start;
no.end = choose_end;
v.push_back(no);
if(end >= m)
break;
i = j;
}
else
{
break;
}
}
if(end >= m)
{
printf("%d\n", v.size());
for(i=0; i<v.size(); i++)
printf("%d %d\n", v[i].start, v[i].end);
}
else
{
printf("0\n");
}
}
int main(void)
{
int i, n, m, count;
int start, end;
//freopen("input.dat", "r", stdin);
scanf("%d", &n);
for(i=1; i<=n; i++)
{
scanf("%d", &m);
count = 0;
while(1)
{
scanf("%d %d", &start, &end);
if(!start && !end)
break;
if(end<0 || start>m)
continue;
arr[count].start = start;
arr[count].end = end;
count ++;
}
if(i >= 2)
printf("\n");
func(count, m);
}
return 0;
}