Cities
Time limit:4000/2000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 579 Accepted Submission (s): 179
Problem Descriptionlong Long Ago,there is a knight called jayye.he lives in a small country. This country are made up to n cities connected by n-1 roads (that means it's a tree). The king wants to reward Jayye because he beats the devil and save the princess. The king decide to give Jayye exactly K cities as his daughter ' s dowry.
Here comes the question. Although Jayye beats the Devil,his knee was injured. So he doesn ' t want to move too Much,he wants his citys as close as Possible,that are, Jayye wants the expected distance of His cities as small as possible.
The expected distance is defined as the expected distance between node U and node V,both u and V were randomly choose from Jayye ' s K cities equiprobably (that means first choose U-randomly from Jayye's K Cities,then Choose v randomly from Jayye ' s K cities,so the case U equals to V is possible).
Suppose you are the king,please determine the K cities so, Jayye is happy.
Because The author is lazy,you only need tell me the minimum expect distance.
Inputthe first line contains a single integer t,indicating the number of test cases.
Each test case begins with the integers n and k,indicating the number of cities in this country,the number of cities the K ING gives to the knight. Then follows N-1 Lines,each line contains three integers a,b,and C, indicating there was a road connects City A and City b With length C.
[Technical specification]
1 <= T <= 100
1 <= K <= min (50,n)
1 <= N <= 2000
1 <= A, b <= n
0 <= C <= 100000
Outputfor each case, output one line, contain one integer, the minimum expect distance multiply K2.
Sample Input12 21 2 1
Sample Output2 Dp[i][j] is used to denote the minimum cost of selecting J points in a subtree of the root node of I
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <cmath > #include <algorithm> #include <cstdlib> #include <vector>using namespace std; #define LL Long Longconst Long Long inf=20000*100000000ll;vector<int> e[2010],w[2010];int n,k; LL dp[2010][100],temp[100];void dfs (int u,int fa) {for (int i=0;i<e[u].size (); i++) {int v=e[u][i]; if (V==FA) continue; DFS (V,U); for (int j=0;j<=k;j++) TEMP[J]=DP[U][J]; for (int j=0;j<=k;j++) {for (int t=0;t<=j;t++) temp[j]=min (temp[j],dp[u][j-t]+dp[v][ t]+t* (K-T) *w[u][i]*2); } for (int j=0;j<=k;j++) DP[U][J]=TEMP[J]; }}int Main () {int tt,x,y,z; scanf ("%d", &TT); while (tt--) {scanf ("%d%d", &n,&k); for (int i=1;i<=n;i++) {e[i].clear (); W[i].clear (); } for (int i=1;i<n;i++) {scanf ("%d%d%d", &x,&y,&z); E[x].push_back (y); E[y].push_back (x); W[x].push_back (z); W[y].push_back (z); } for (int i=1;i<=n;i++) {for (int j=0;j<=k;j++) {if (j<=1) dp[i][j]=0; else Dp[i][j]=inf; }} dfs (1,-1); printf ("%i64d\n", Dp[1][k]); } return 0;}
(Tree-shaped DP) HDU 5148