UVA 10020 Minimal coverage
生活随笔
收集整理的這篇文章主要介紹了
UVA 10020 Minimal coverage
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
大意:數(shù)軸上有n個閉區(qū)間[ai,bi],選擇盡量少的區(qū)間覆蓋一條指定的線段[s,t]。
?
思路:貪心,具體見劉汝佳白書P154。把各區(qū)間按照a從小到大排序。如果區(qū)間1的起點不是s,無解,否則選擇起點在s的最長區(qū)間。選擇此區(qū)間[ai,bi]后,新的起點設(shè)置為bi,然后經(jīng)過依次掃描之后就可以得出最小的線段數(shù)。并用另一個結(jié)構(gòu)體儲存路徑。
?
另外:排序可有可無,有了只不過是一種優(yōu)化措施,沒有排序的話程序也對,最主要的算法還是貪心。
?
CODE:
#include?<iostream>#include?<cstdlib>
#include?<cstring>
#include?<algorithm>
#include?<cstdio>
using?namespace?std;
#define?MAXN?100010
struct?node
{
????int?l;
????int?r;
}a[MAXN]?,?path[MAXN];
int?cmp(const?node?&a,?const?node?&b)
{
????if(a.l?!=?b.l)????return?a.l?<?b.l;
????else?return?a.r?>?b.r;????//這里不影響程序的正確性?
}
int?n,?m;
void?init()
{
????memset(a,?0,?sizeof(a));
????memset(path,?0,?sizeof(path));
}
void?solve()
{
????int?flag,?pos;
????int?Max?=?0,?tot?=?0,?ans?=?0,?left?=?0;
????sort(a,?a+n,?cmp);?//排序,?
????for(;;)
????{
????????if(left?>=?m)?break;
????????Max?=?flag?=?0;
????????for(int?i?=?0;?i?<?n;?i++)
????????{
????????????if(a[i].l?<=?left)
????????????{
????????????????if(a[i].r?>?Max)
????????????????{
????????????????????pos?=?i;
????????????????????Max?=?a[i].r;
????????????????????flag?=?1;
????????????????}?//找最右邊的區(qū)間?
????????????}
????????}
????????if(flag)
????????{
????????????ans++;
????????????left?=?Max;?????//更新最大區(qū)間?
????????????path[tot++]?=?a[pos];
????????}
????????else?break;
????}
????if(flag)
????{
????????printf("%d\n",?tot);
????????for(int?i?=?0;?i?<?tot;?i++)
????????{
????????????printf("%d?%d\n",?path[i].l,?path[i].r);
????????}
????}
????else?printf("0\n");
}
int?main()
{
????int?T;
????scanf("%d%*c",?&T);
????while(T--)
????{
????????init();
????????int?i?=?0;
????????int?x,?y;
????????scanf("%d",?&m);
????????while(scanf("%d%d",?&x,?&y))
????????{
????????????if(!x?&&?!y)?break;
????????????a[i].l?=?x,?a[i].r?=?y;
????????????i++;
????????}
????????n?=?i;
????????solve();
????????if(T)?printf("\n");
????}
????return?0;
}
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/g0feng/archive/2012/10/15/2725090.html
總結(jié)
以上是生活随笔為你收集整理的UVA 10020 Minimal coverage的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UVA 10706 Number Seq
- 下一篇: PendingIntent与Intent