环游大同80天(vijos1107)

本文介绍了使用搜索算法求解树结构中最长路径的方法,包括寻找起点、进行两次深度优先搜索以确保找到直径,适用于图论和算法领域的学习。
算法:搜索

其实就是求树的最长链。
1.先找一个是景点的地方。
2.以这个点为起点做一遍搜索,搜出一个最远点。
3.再以那个最远点做起点再搜一遍即可。

做两遍搜索的原因是第一次搜索有可能不在最远点的位置上,因此还要根据这个点找一个最远的点,即直径。

program vijos1107;

const
 maxn=1000;
 dx:array [1..4] of -1..1=(0,-1,0,1);
 dy:array [1..4] of -1..1=(-1,0,1,0);

var
 n,m,tot,ans,mx,my:longint;
 a:array [0..maxn,0..maxn] of char;
 b:array [0..maxn,0..maxn] of boolean;

procedure init;
var
 i,j:longint;
begin
 readln(m,n);
 fillchar(b,sizeof(b),false);
 for i:=1 to n do
  begin
   for j:=1 to m do read(a[i,j]);
   readln;
  end;
end;

procedure dfs(x,y:longint);
var
 i,tx,ty:longint;
begin
 if tot>=ans then
  begin
   ans:=tot;
   mx:=x;
   my:=y;
  end;
 for i:=1 to 4 do
  begin
   tx:=x+dx[i];
   ty:=y+dy[i];
   if (tx>0) and (tx<=n) and (ty>0) and (ty<=m) and (a[tx,ty]='.') and (not b[tx,ty]) then
    begin
     b[tx,ty]:=true;
     inc(tot);
     dfs(tx,ty);
     dec(tot);
    end;
  end;
end;

procedure main;
var
 i,j:longint;
begin
 for i:=1 to n do
  begin
   for j:=1 to m do
    begin
     if a[i,j]='.' then
      begin
       tot:=0;
       b[i,j]:=true;
       dfs(i,j);
       fillchar(b,sizeof(b),false);
       tot:=0;
       b[mx,my]:=true;
       dfs(mx,my);
       writeln(ans);
       close(input);
       close(output);
       halt;
      end;
    end;
  end;
end;

begin
 assign(input,'VJ1107.in'); reset(input);
 assign(output,'VJ1107.out'); rewrite(output);

 init;
 main;

 close(input); close(output);
end.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值