本想练习差分约束,搜到了这道题,暂时没能想出构图方法,
//6973#9056660 helloworld 1716 Accepted 432K 16MS G++ 973B 2011-08-02 09:32:52 //6974#9056670 helloworld 1716 Accepted 208K 0MS C++ 1056B 2011-08-02 09:34:01 //9056812 NKHelloWorld 1716 Accepted 432K 16MS G++ 1088B 2011-08-02 09:50:53 #include <cstdio> #include <algorithm> using namespace std; typedef struct { int l,r; }NODE; NODE node[11000]; bool cmp(NODE a,NODE b) { return a.r < b.r; } int max1,max2,cnt = 0,n; int main() { int i,j; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d%d",&node[i].l,&node[i].r); sort(node,node+n,cmp); //for(i=0;i<n;i++) printf("%d\t%d\n",node[i].l,node[i].r); max1 = node[0].r-1; max2 = node[0].r; cnt = 2; for(i=1;i<n;i++) { if(max2 < node[i].l) { max1 = node[i].r-1; max2 = node[i].r; //printf("%d %d\n",max1,max2); cnt += 2; } else if(max1 < node[i].l) { max1 = max2; max2 = node[i].r; //printf("%d %d\n",max1,max2); cnt ++; } } printf("%d\n",cnt); return 0; }
但是却想到了贪心的做法。。。首先将各段按右端点由小到大排序,这样,对于排在第一个的线段,要求在这一段上去两个点,那么我们不妨取最右侧的两个点,即right,right-1,因为越靠右侧取点,这个点能被后面线段用上的可能性越大。我们将当前取的两个点记作max1,max2,对于下一段,分三种情况:一,max1,max2都包含在下一段中,那么就不需要再取点,直接继续找下一段;二,max1不包含,max2包含在下一段中,此时另max1 = max2,max2 = 下一段右端点;三、都不包含在下一段,则max1=right-1,max2=right。依次进行下去,复杂度O(n)。这应该是本题很快的算法了,差分约束应该无法做到线性复杂度。好吧,下面再写个差分约束试试。