P1103 Book Arrangement

Topic description

Frank is a very neat person. He has a stack of books and a bookshelf and wants to put books on the bookshelf. The bookshelf can hold all the books, so Frank first arranges the books on the bookshelf in order of height. But Frank found that because many of the books were of different widths, the books still looked very uneven. So he decided to remove k books from it so that the bookshelf could look neater.

The irregularity of a bookshelf is defined as the sum of the absolute values ​​of the difference between the widths of every two books. For example there are 4 books:

1x2 5x3 2x4 3x1 Then Frank arranges it like this:

1x2 2x4 3x1 5x3 Unevenness is 2+3+2=7

Knowing that the height of each book is different, please find the minimum irregularity after removing k books.

Input and output format

Input format:

The two numbers n and k in the first line represent how many books there are, and how many books are removed. (1<=n<=100, 1<=k<n)

The following n lines, each with two numbers representing the height and width of a book, are both less than 200.

Guaranteed to not repeat the height

Output format:

One integer per line representing the minimum irregularity of the bookshelf.

Input and output example

Input Example #1: Copy
4 1
1 2
2 4
3 1
5 3
Output Sample #1: Copy
3

 

Solution:

  Change the thinking of this question, removing $k$ from $n$ is equivalent to selecting $nk$ items, so it is easy to think of a backpack.

  For the items sorted by height, define the state $f[i][j]$ to represent the minimum value of the $i$ items selected in the first $j$ items, then the initial state $f[1][i]=0, i\in[1,n]$ (indicates that $1$ is selected from the first $i$, and the evaluated value is $0$).

  Then it is not difficult to think of the state transition equation: $f[i][j]=Min(f[i][j],f[i-1][p]+abs(a[j].wa[p].w )),i\in[2,nk],j\in[i,n],p\in[1,j)$, indicating that the minimum value of the selected $i$ in the first $j$ is from the previous $p Choose from $i-1$ and add the current collocation value.

  Then the final output target state $f[nk][i], the minimum value in i\in[nk,n]$ is $OK$.

Code:

 1 #include<bits/stdc++.h>
 2 #define Min(a,b) ((a)>(b)?(b):(a))
 3 #define For(i,a,b) for(int (i)=(a);(i)<=(b);(i)++)
 4 using namespace std;
 5 const int N=205;
 6 int n,k,f[N][N],ans=520520520;
 7 struct node{
 8     int h,w;
 9     bool operator<(const node a)const{return h<a.h;}
10 }a[N];
11 int main(){
12     ios::sync_with_stdio(0);
13     memset(f,0x3f,sizeof(f));
14     cin>>n>>k;
15     For(i,1,n) cin>>a[i].h>>a[i].w;
16     sort(a+1,a+n+1);
17     f[0][0]=0;
18     For(i,1,n)f[1][i]=0;
19     For(i,2,n-k) For(j,i,n) For(p,1,j-1)
20         f[i][j]=Min(f[i][j],f[i-1][p]+abs(a[j].w-a[p].w));
21     For(i,n-k,n)ans=Min(ans,f[n-k][i]);
22     cout<<ans;
23     return 0;
24 }

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326605133&siteId=291194637