HDU-2196 Computer

本文介绍了一种利用树的直径来解决寻找树上每一点到其他各点最大距离的问题。通过两次广度优先搜索(BFS),首先找到树直径的一个端点,然后以此端点再次进行BFS找到树的另一个端点,最终确定每个节点的最大距离。

D - Computer

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit

Status
Description
A school bought the first computer some time ago(so this computer’s id is 1). During the recent years the school bought N-1 new computers. Each new computer was connected to one of settled earlier. Managers of school are anxious about slow functioning of the net and want to know the maximum distance Si for which i-th computer needs to send signal (i.e. length of cable to the most distant computer). You need to provide this information.

这里写图片描述

Hint: the example input is corresponding to this graph. And from the graph, you can see that the computer 4 is farthest one from 1, so S1 = 3. Computer 4 and 5 are the farthest ones from 2, so S2 = 2. Computer 5 is the farthest one from 3, so S3 = 3. we also get S4 = 4, S5 = 4.
Input
Input file contains multiple test cases.In each case there is natural number N (N<=10000) in the first line, followed by (N-1) lines with descriptions of computers. i-th line contains two natural numbers - number of computer, to which i-th computer is connected and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input are separated by a space.
Output
For each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).
Sample Input
5
1 1
2 1
3 1
1 1
Sample Output
3
2
3
4
4


  1. 题意:给你多个数据,比如上例:5代表有5个节点;第二行代表第二个节点和第一个节点相连,且边权是1;第三行代表第三个节点何地二个节点相连接,边权为1.
  2. 思路:根据题所给的信息每个新电脑和原来的电脑连接可以判断所给图形为一棵树,题意就是要求树的每一点与其他点的最大距离,可以借助树的直径进行转化(到树上任一点的最大距离的点一定树的直径上而且是两端):任选一点跑一遍bfs找到直径的的起点S,再用S点为起点跑一遍bfs找到直径的终点E,并保存此时每个点和S的距离;再用E为起点跑一遍bfs,记录每个点与其的距离。再比较两次结果,取最大者。
  3. 失误:刚开始没用树的直径,循环一遍bfs超时,感觉应该用树的直径做,但写出来测试数据对,提交错误。看了学长的思路才明白,我把任意的点都默认成直径上的点了,就是按一条线段上的点一样考虑了;改正之后还是有些小错误,在代码中指出。
  4. 代码如下:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

const int MAXN=1e6+10;
int head[MAXN],dis[MAXN],d1[MAXN],d2[MAXN];
bool vis[MAXN];
int edgenum,ans,Tnode,n;

struct Edge{
    int from;
    int to; 
    int val;
    int next;

}edge[MAXN];

void init()
{
    memset(head,-1,sizeof(head)); edgenum=0;  
}

void addedge(int u,int v,int w)
{
    Edge E={u,v,w,head[u]};//用这种方式初始化结构体中变量顺序不能颠倒  
    edge[edgenum]=E;   //错误现象:死机状态 
    head[u]=edgenum++;
}

void bfs(int s)
{
    memset(dis,0,sizeof(dis));  memset(vis,false,sizeof(vis));
    queue<int> que;  que.push(s); dis[s]=0; vis[s]=true; ans=0;
    while(!que.empty()) 
    {
        int now=que.front(); que.pop();
        for(int i=head[now];~i;i=edge[i].next)
        {
              int go=edge[i].to;
              if(!vis[go])
              {
                  if(dis[go]<dis[now]+edge[i].val)  dis[go]=dis[now]+edge[i].val;
//                if(ans<dis[go])//刚学邻接表,不怎麽理解,先记着用的:dis保存的是数组下标所带表的节点到起始节点的距离
//                {
//                     ans=dis[go];
//                     Tnode=go;
//                  }
                    vis[go]=true;
                    que.push(go);
              }
         } 
    }
    for(int i=1;i<=n;++i)//跑的和在里面差不多 
    {
        if(ans<dis[i])
        {
            ans=dis[i];
            Tnode=i;
        }
    }
}

int main()
{
    int i,v,w,S,end;
    while(~scanf("%d",&n))
    {
        init();
        for(i=2;i<=n;++i)//没想到i从2开始 
        {
            scanf("%d%d",&v,&w);
            addedge(i,v,w);
            addedge(v,i,w);
        }
        bfs(1);  S=Tnode;
        bfs(S);  end=Tnode;
        for(i=1;i<=n;++i)  d1[i]=dis[i] ;
        bfs(end); 
    //  for(i=1;i<=n;++i)  d2[i]=dis[i];
        for(i=1;i<=n;++i)//跑的快了三分之一 
        {
            ans=d1[i]>dis[i]?d1[i]:dis[i];
            printf("%d\n",ans); 
         } 
    }
    return 0;
 } 
### 关于HDU - 6609 的题目解析 由于当前未提供具体关于 HDU - 6609 题目的详细描述,以下是基于一般算法竞赛题型可能涉及的内容进行推测和解答。 #### 可能的题目背景 假设该题目属于动态规划类问题(类似于多重背包问题),其核心在于优化资源分配或路径选择。此类问题通常会给出一组物品及其属性(如重量、价值等)以及约束条件(如容量限制)。目标是最优地选取某些物品使得满足特定的目标函数[^2]。 #### 动态转移方程设计 如果此题确实是一个变种的背包问题,则可以采用如下状态定义方法: 设 `dp[i][j]` 表示前 i 种物品,在某种条件下达到 j 值时的最大收益或者最小代价。对于每一种新加入考虑范围内的物体 k ,更新规则可能是这样的形式: ```python for i in range(n): for s in range(V, w[k]-1, -1): dp[s] = max(dp[s], dp[s-w[k]] + v[k]) ``` 这里需要注意边界情况处理以及初始化设置合理值来保证计算准确性。 另外还有一种可能性就是它涉及到组合数学方面知识或者是图论最短路等相关知识点。如果是后者的话那么就需要构建相应的邻接表表示图形结构并通过Dijkstra/Bellman-Ford/Floyd-Warshall等经典算法求解两点间距离等问题了[^4]。 最后按照输出格式要求打印结果字符串"Case #X: Y"[^3]。 #### 示例代码片段 下面展示了一个简单的伪代码框架用于解决上述提到类型的DP问题: ```python def solve(): t=int(input()) res=[] cas=1 while(t>0): n,k=list(map(int,input().split())) # Initialize your data structures here ans=find_min_unhappiness() # Implement function find_min_unhappiness() res.append(f'Case #{cas}: {round(ans)}') cas+=1 t-=1 print("\n".join(res)) solve() ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值