Mountain built primary school (dynamic programming)

Government in the construction of a road in a mountainous area, just across the total m each village villages once, no loop or cross any two villages only through this route to and from. The distance between any two adjacent villages known as DI (a positive integer), where, 0 <i <m. In order to improve the cultural quality of the mountains, the Government has decided to choose from the m n villages built in the village primary school (set 0 <n≤m <500). Please The given distance m, n and all the neighboring villages, in which primary selection built village, which makes the sum of all the nearest village primary minimum, the minimum value is calculated.

 

Entry

 

The first behavior and m n, separated by spaces therebetween

2 m-1 acts integers, sequentially represents the distance from one end to the other end of neighboring villages, a space between the integer intervals.

E.g:

10 3
2 4 6 5 2 4 3 1 3

It represents 10 villages to build three schools. The first and the second villages villages distance is 2, the second and the third villages villages distance of 4, the third and the fourth villages villages distance is 6, ..., 9 to 10 villages from villages 3.

 

 

Export

 

And the villages to the minimum distance to the nearest school.

 

Sample input

10 2
3 1 3 1 1 1 1 1 3

Sample Output

18

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 int n,m;
 7 int dis[505],arr[505][505],dp[505][505];
 8 
 9 int main(){
10     ios::sync_with_stdio(false);
11     cin>>n>>m;
12     dis[1]=1;
13     for(int I = 2 ; I <= n-; I ++) >> CIN DIS [I], DIS [I] + DIS = [I- . 1 ];    /// location of each point 
14      for ( int I = . 1 ; I <= n-; I ++ )
 15      for ( int J = I + . 1 ; J <= n-; J ++ ) {
 16          ARR [I] [J] = ARR [I] [J- . 1 ] + DIS [J], DIS [I J >> + . 1 ];   /// between i ~ j minimum build a city 
. 17      }
 18 is      Memset (DP, 0x3f3f3f3f , the sizeof (DP));
 . 19      for ( int I = . 1; i <= n-; i ++) DP [i] [ . 1 ] = ARR [ . 1 ] [i];     /// determining boundary conditions i villages before a selected distance and the minimum value of 
20 is      for ( int i = . 1 ; I <= n-; I ++ ) {
 21 is          for ( int J = . 1 ; J <= m; J ++ ) {
 22 is              for ( int K = J- . 1 ; K <I; K ++) {    // begin selected from the j-1 th 
23 is                  DP [I] [J] = min (DP [I] [J], DP [K] [J- . 1 ] + ARR [K + . 1 ] [I]);
 24              } 
 25          }
 26 is      }
 27     cout << dp[n][m] << endl;
28     return 0;
29 }
View Code

 

Guess you like

Origin www.cnblogs.com/qq-1585047819/p/11279694.html