Cities
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 579 Accepted Submission(s): 179
Problem Description
Long long ago,there is a knight called JayYe.He lives in a small country.This country is made up of 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 is, 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 are 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 that JayYe is happy.
Because the author is lazy,you only need tell me the minimum expect distance.
Input
The first line contains a single integer T,indicating the number of test cases.
Each test case begins with two integers n and K,indicating the number of cities in this country,the number of cities the king gives to the knight.Then follows n-1 lines,each line contains three integers a,b,and c, indicating there is 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
Output
For each case, output one line, contain one integer, the minimum expect distance multiply K2.
Sample Input
1
2 2
1 2 1
Sample Output
2
dp[i][j]用来表示 以i为根节点的子树中选J个点的最小代价
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<algorithm> #include<cstdlib> #include<vector> using namespace std; #define LL long long const 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; }