USACO Milking Cows
题意:给出n个区间(a, b) (n<=5000, a,b<=1000000)
将n个区间合并,求最长连续区间和最长区间间隔
先按x升序和y升序排序
tempe保存目前连续区间的右边界
1、i与当前连续区间连续的话必须满足seg[i].e <= tempe,然后更新tempe和最长连续区间值
2、不满足条件,则新开一个连续区间,更新tempe和最长区间间隔值
attention!
1、three bugs= =
2、一开始想的思路错了,往离散化线段树方向想
/*
ID: byluolu1
PROG: milk2
LANG: C++
*/
#include <cstdio>
#include <cstdlib>
#define N 5005
struct Seg
{
int s, e;
}seg[N];
int cmp(const void *a, const void *b)
{
struct Seg *x = (struct Seg *)a;
struct Seg *y = (struct Seg *)b;
if(x->s == y->s)
return x->e - y->e;
return x->s - y->s;
}
int main()
{
FILE *fin = fopen("milk2.in", "r");
FILE *fout = fopen("milk2.out", "w");
int n;
fscanf(fin, "%d",&n);
for(int i=0; i<n; i++)
fscanf(fin, "%d%d",&seg[i].s, &seg[i].e);
qsort(seg, n, sizeof(struct Seg), cmp);
int lm = seg[0].e - seg[0].s, lnm = 0, maxlm = 0, maxlnm = 0, tempe = seg[0].e;
maxlm = lm;// - bug1
for(int i=1; i<n; i++)
{
if(seg[i].s <= tempe) // - bug2
{
if(seg[i].e > tempe)
{
lm += seg[i].e - tempe;
tempe = seg[i].e;
}
maxlm = lm > maxlm ? lm : maxlm;
}
else
{
lnm = seg[i].s - tempe;// - bug3
maxlnm = lnm > maxlnm ? lnm : maxlnm;
lm = seg[i].e - seg[i].s;
maxlm = lm > maxlm ? lm : maxlm;
tempe = seg[i].e;
}
}
fprintf(fout, "%d %d\n",maxlm, maxlnm);
return 0;
}
ID: byluolu1
PROG: milk2
LANG: C++
*/
#include <cstdio>
#include <cstdlib>
#define N 5005
struct Seg
{
int s, e;
}seg[N];
int cmp(const void *a, const void *b)
{
struct Seg *x = (struct Seg *)a;
struct Seg *y = (struct Seg *)b;
if(x->s == y->s)
return x->e - y->e;
return x->s - y->s;
}
int main()
{
FILE *fin = fopen("milk2.in", "r");
FILE *fout = fopen("milk2.out", "w");
int n;
fscanf(fin, "%d",&n);
for(int i=0; i<n; i++)
fscanf(fin, "%d%d",&seg[i].s, &seg[i].e);
qsort(seg, n, sizeof(struct Seg), cmp);
int lm = seg[0].e - seg[0].s, lnm = 0, maxlm = 0, maxlnm = 0, tempe = seg[0].e;
maxlm = lm;// - bug1
for(int i=1; i<n; i++)
{
if(seg[i].s <= tempe) // - bug2
{
if(seg[i].e > tempe)
{
lm += seg[i].e - tempe;
tempe = seg[i].e;
}
maxlm = lm > maxlm ? lm : maxlm;
}
else
{
lnm = seg[i].s - tempe;// - bug3
maxlnm = lnm > maxlnm ? lnm : maxlnm;
lm = seg[i].e - seg[i].s;
maxlm = lm > maxlm ? lm : maxlm;
tempe = seg[i].e;
}
}
fprintf(fout, "%d %d\n",maxlm, maxlnm);
return 0;
}