一、線段覆蓋
n個開區間(ai,bi),選擇盡量多個區間,使得這些區間兩兩不相交
右端點排序(<)兼顧左端點(>),再從左到右遇到不相交的就選
1 sort(he+1,he+n+1,cmp); 2 int tot=0,now=-1000; 3 for(int i=1; i<=n; i++) { 4 if(he[i].l>=now) now=he[i].r,tot++; 5 } 6 printf("%d", tot);
二、區間選點
n個閉區間[ai,bi],選擇盡量少的點,使得每個區間至少有一個點
右端點排序(<)兼顧左端點(>),每次選擇可選區間的最后一個點
1 sort(he+1,he+n+1,cmp); 2 int tot=0,now=-1; 3 for(int i=1; i<=n; i++) { 4 if(he[i].l>now) now=he[i].r,tot++; 5 } 6 printf("%d", tot);
三、區間覆蓋
數軸上有n個閉區間[ai,bi],選擇盡量少的區間覆蓋一條指定的線段[s,t]
左端點排序(<)兼顧右端點(<),每次選擇從當前起點能覆蓋到的最長的區間
1 sort(he+1,he+n+1,cmp); 2 int tot=0,now=-1,to=-1; 3 for(int i=1; i<=n; i++) { 4 if(he[i].l<=now) to=max(to,he[i].r); 5 else now=to,to=max(he[i].r),tot++; 6 } 7 printf("%d", tot);