POJ1065 Dilworth定理

来源:互联网 发布:去库存是什么意思知乎 编辑:程序博客网 时间:2024/06/05 02:36

Description

There is a pile of n wooden sticks. The length and weight of each stick are known in advance. The sticks are to be processed by a woodworking machine in one by one fashion. It needs some time, called setup time, for the machine to prepare processing a stick. The setup times are associated with cleaning operations and changing tools and shapes in the machine. The setup times of the woodworking machine are given as follows: 
(a) The setup time for the first wooden stick is 1 minute. 
(b) Right after processing a stick of length l and weight w , the machine will need no setup time for a stick of length l' and weight w' if l <= l' and w <= w'. Otherwise, it will need 1 minute for setup. 
You are to find the minimum setup time to process a given pile of n wooden sticks. For example, if you have five sticks whose pairs of length and weight are ( 9 , 4 ) , ( 2 , 5 ) , ( 1 , 2 ) , ( 5 , 3 ) , and ( 4 , 1 ) , then the minimum setup time should be 2 minutes since there is a sequence of pairs ( 4 , 1 ) , ( 5 , 3 ) , ( 9 , 4 ) , ( 1 , 2 ) , ( 2 , 5 ) .

Input

The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case consists of two lines: The first line has an integer n , 1 <= n <= 5000 , that represents the number of wooden sticks in the test case, and the second line contains 2n positive integers l1 , w1 , l2 , w2 ,..., ln , wn , each of magnitude at most 10000 , where li and wi are the length and weight of the i th wooden stick, respectively. The 2n integers are delimited by one or more spaces.

Output

The output should contain the minimum setup time in minutes, one per line.

Sample Input

3 5 4 9 5 2 2 1 3 5 1 4 3 2 2 1 1 2 2 3 1 3 2 2 3 1 

Sample Output

213

这个题目定义了一种偏序关系≤(L1, W1)≤(L2, W2)当且仅当L1<=L2且W1<=W2给的输入就是一个偏序集,目标就是把这个偏序集划分为一系列chain,并要求chain的个数尽可能少根据Dilworth定理,最少的chain个数等于最大的antichain的大小(1)对antichain中任意两点P(L1, W1)和Q(L2, W2),L1不等于L2(否则P和Q就是可比较的,违反反链性质),W1不等于W2(2)如果将反链中的点按照L值从小到大排列,那么W是递减的(考察任意两个相邻的点P(L1, W1)和Q(L2, W2),假设他们违反了递减性质,即W1<=W2,那么P和Q就是可比较的,违反了反链性质)考虑到这两点,可以先对所有点按照L值从小到大排列,如果L值相同,W值小的在前  最长反链就是在这个序列中取一个最长的子序列,要求W值是递减的——这就是最长递减子序列(不可以相等)问题了,可以用动态规划在O(n^2)时间内解决。


int maxDecreaseLen(vector<Point>& vec){    int len = vec.size();    int x[len];//x[i]存储以vec[i]结尾的最长递减子序列长度    int max = 0;    for (int i = 0; i < len; i++) {//update x[i] one by one        x[i] = 1;        for (int j = 0; j < i; j++) {            if (x[i] <= x[j] && vec[j].w > vec[i].w) {//...j.....i                x[i] = x[j] + 1;            }        }        if (max < x[i]) {            max = x[i];        }    }    return max;}




0 0