hdu 4607 Park Visit(树型DP)
2014-06-18 17:28
357 查看
题意:给出一个树,问访问树上k个点,最少需要走多少距离。
思路:要让路径最短,那么就应该尽可能少的走重复路径。求出最长边,如果要访问的点小于最长边上的点,那么走的路径长度就是k-1(因为没有回溯)。如果大于最长路径的点,那么要加上剩下的点数*2。
求最长边的方法我用的是以前做过的一道树形DP的方法:点击打开链接。
思路:要让路径最短,那么就应该尽可能少的走重复路径。求出最长边,如果要访问的点小于最长边上的点,那么走的路径长度就是k-1(因为没有回溯)。如果大于最长路径的点,那么要加上剩下的点数*2。
求最长边的方法我用的是以前做过的一道树形DP的方法:点击打开链接。
#include<stdio.h> #include<string.h> #define N 100005 struct node { int son; int next; } Edge[N*2]; struct f { int fir; int sec; int max; } dp ; int head ,vis ; int cnt; int Max(int x,int y) { if(x>y) return x; else return y; } void AddEdge(int x,int y) { Edge[cnt].son=y,Edge[cnt].next=head[x],head[x]=cnt++; Edge[cnt].son=x,Edge[cnt].next=head[y],head[y]=cnt++; return ; } void dfs(int father) { int u=head[father]; vis[father]=1; for(int i=u; i!=-1; i=Edge[i].next) { int son=Edge[i].son; if(vis[son]) continue; dfs(son); int temp; dp[father].sec=Max(dp[father].sec,dp[son].fir+1); if(dp[father].fir<dp[father].sec) temp=dp[father].fir,dp[father].fir=dp[father].sec,dp[father].sec=temp; } return ; } void bfs(int father) { dp[father].max=dp[father].fir+dp[father].sec; int u=head[father]; vis[father]=1; for(int i=u; i!=-1; i=Edge[i].next) { int son=Edge[i].son; if(vis[son]) continue; if(dp[son].fir+1!=dp[father].fir) dp[son].fir=dp[father].fir+1; else { dp[son].sec=Max(dp[father].sec+1,dp[son].sec); int temp; if(dp[son].fir<dp[son].sec) temp=dp[son].fir,dp[son].fir=dp[son].sec,dp[son].sec=temp; } bfs(son); } return ; } int main() { int T; scanf("%d",&T); while(T--) { int n,m; scanf("%d%d",&n,&m); int i; cnt=0; memset(head,-1,sizeof(head)); for(i=1; i<n; i++) { int x,y; scanf("%d%d",&x,&y); AddEdge(x,y); } memset(dp,0,sizeof(dp)); memset(vis,0,sizeof(vis)); dfs(1); memset(vis,0,sizeof(vis)); bfs(1); int max=0; for(i=1; i<=n; i++) max=Max(dp[i].max,max); for(i=1; i<=m; i++) { int x; scanf("%d",&x); if(x<=max+1) printf("%d\n",x-1); else printf("%d\n",max+(x-max-1)*2); } } return 0; }
相关文章推荐
- HDU 4607 Park Visit(树的直径)
- hdu-4607-Park Visit
- HDU 4607 Park Visit(树的直径)
- hdu 4607 Park Visit 贪心
- hdu 4607 Park Visit (dfs)
- hdu 4607 Park Visit 求树的直径
- hdu 4607 Park Visit
- hdu 4607 Park Visit(求树的最长直径)
- hdu 4607 Park Visit 求树的直径
- HDU 4607 Park Visit 求树直径
- hdu 4607 Park Visit
- HDU 4607 Park Visit (DP最长链)
- Hdu 4607 Park Visit 2013多校1 (树的直径)
- HDU 4607 Park Visit (DP最长链)
- HDU 4607 Park Visit (树的直径)
- hdu 4607 Park Visit
- hdu 4607 Park Visit
- 【HDU】4607 - Park Visit(树的直径)
- hdu 4607 Park Visit
- hdu 4607 Park Visit (树的直径)