USACO--2.4Cow Tours

本文介绍了一种在图论中优化最小距离最大值的方法,通过并查集和Floyd算法,实现了时间复杂度从n^7降低到n^3的高效解决方案。

题目大意:一个图被分成若干个连通块,我们可以选择在这些连通块中增加一条边,求加边以后所有点最小距离最大值最小的情况(有些绕口~)。
思路:最暴力的思路就是依次枚举需要连边的连通块然后再枚举这两个连通块中需要连接的定点,然后再用Floyd算出所有点的最小距离,然后再求最大值。这样时间复杂度是n^7,肯定会超时。仔细想一下我们其实并不关心我们枚举的边是属于哪个连通块的,我们只需要保证枚举的边不在同一个连通块中就行了。所以我们可以只枚举那么不在同一个连通块中的边,然后重新求一下所有点的最短路,然后再求出最大值。这样时间复杂度是n^5,还是会超时的。
但是其实我们不需要每次都重新调用Floyd求一次最小距离;考虑两个连通块C1,C2,我们选一条边e(i,j)将他们连起来那么在新形成的连通块中最小距离的最大值应为(i到中C1点距离的最大值)+dist[i,j]+(j到C2中点距离的最大值)。所以如果我们提前将每个点到其所在连通块中其它点最小距离的最大值处理出来的话,我们在枚举边以后就不要重新计算所有点之间的最小距离了。时间复杂度n^3,n最大为150,完全可以接受。
至于枚举每条边的时候需要保证其顶点不在同一个连通块中,我们可以用并查集来实现。

代码如下:

/*
ID:15674811
LANG:C++
PROG:cowtour
*/

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

#define INF 0x3f3f3f3f
#define maxn 155

double d[maxn][maxn];
int n,m[maxn][maxn];
int fa[maxn];

int Find(int x)
{
    return fa[x]==x?x:fa[x]=Find(fa[x]);
}

void Merge(int x,int y)
{
    int fx=Find(x);
    int fy=Find(y);
    if(fx!=fy)
    {
        fa[fx]=fy;
    }
}

void floyd()
{
    for(int k=1;k<=n;k++)
        for(int i=1;i<=n;i++)
          for(int j=1;j<=n;j++)
          {
              if(d[i][j]>d[i][k]+d[k][j])
                 d[i][j]=d[i][k]+d[k][j];
          }
}

double dist(double x1,double y1,double x2,double y2)
{
    double xx=(x1-x2)*(x1-x2);
    double yy=(y1-y2)*(y1-y2);
    return sqrt(xx+yy);
}

double dx[maxn],dy[maxn];
double v[maxn];

void print()
{
    for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
                if(d[i][j]!=INF+0.0)
                   printf("%5.4lf ",d[i][j]);
                else
                   printf("0 ");
            printf("\n");
        }
}

int main()
{
    freopen("cowtour.in","r",stdin);
    freopen("cowtour.out","w",stdout);
    while(scanf("%d\n",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
               d[i][j]=INF+0.0;
            d[i][i]=0.0;
        }
        for(int i=1;i<=n;i++)
            fa[i]=i;
        for(int i=1;i<=n;i++)
            scanf("%lf%lf\n",&dx[i],&dy[i]);
        for(int i=1;i<=n;i++,getchar())
            for(int j=1;j<=n;j++)
            {
                m[i][j]=getchar()-'0';
                if(m[i][j])
                    Merge(i,j);
            }
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
            {
                if(m[i][j])
                   d[i][j]=dist(dx[i],dy[i],dx[j],dy[j]);
            }
       // print();
        floyd();
        //print();
        double tmp=0.0;
        for(int i=1;i<=n;i++)
        {
            double Max=0.0;
            for(int j=1;j<=n;j++)
            {
                if(d[i][j]!=(INF+0.0)&&Max<d[i][j])
                     Max=d[i][j];
                if(d[i][j]!=INF)
                     tmp=max(tmp,d[i][j]);
            }
            v[i]=Max;
        }
      /*  for(int i=1;i<=n;i++)
            printf("%.4lf ",v[i]);
        printf("\n");*/
        double ans=INF+0.0;
        for(int i=1;i<=n;i++)
            for(int j=i+1;j<=n;j++)
            {
                int fx=Find(i);
                int fy=Find(j);
                if(fx!=fy)
                {
                    ans=min(ans,v[i]+v[j]+dist(dx[i],dy[i],dx[j],dy[j]));
                }
            }
        ans=max(ans,tmp);
        printf("%.6lf\n",ans);
    }
  return 0;
}
### 解题思路 "The Lost Cow" 是一道经典的模拟问题,目标是计算 Farmer John 找到 Bessie 需要行走的距离。Farmer John 使用一种特定的策略来寻找 Bessie:他从初始位置 `x` 开始,依次向右走一段距离,再返回原点;接着向左走更远的一段距离,再次回到原点,如此反复直到找到 Bessie。 #### 关键逻辑 1. **移动模式** 每次移动的距离按照序列 \( \pm 1, \mp 2, \pm 4, \ldots \) 增加,即每次翻倍并改变方向。 2. **终止条件** 当 Farmer John 到达的位置覆盖了 Bessie 的实际坐标 `y` 时停止搜索。具体来说: - 如果 `x < y`,则当某一次移动到达或超过 `y` 时结束; - 如果 `x > y`,则当某一次移动到达或低于 `y` 时结束。 3. **总路径长度** 计算总的路径长度时需要注意最后一次未完全完成的往返行程应减去多余的部分。 --- ### C++ 实现代码 以下是基于上述逻辑的一个标准实现: ```cpp #include <iostream> #include <cmath> using namespace std; int main() { long long x, y; cin >> x >> y; if (x == y) { cout << 0; return 0; } long long pos = x, step = 1, total_distance = 0; while (true) { // 向右移动 long long next_pos = pos + step; if ((x < y && next_pos >= y) || (x > y && next_pos <= y)) { total_distance += abs(y - pos); break; } total_distance += abs(next_pos - pos); pos = next_pos; // 返回起点 total_distance += abs(pos - x); // 向左移动 step *= -2; next_pos = pos + step; if ((x < y && next_pos >= y) || (x > y && next_pos <= y)) { total_distance += abs(y - pos); break; } total_distance += abs(next_pos - pos); pos = next_pos; // 返回起点 total_distance += abs(pos - x); step *= -2; } cout << total_distance; return 0; } ``` 此代码实现了 Farmer John 寻找 Bessie 的过程,并精确计算了所需的总路径长度[^1]。 --- ### Pascal 实现代码 如果偏好 Pascal,则可以参考以下代码片段: ```pascal var n, x, y, t, ans: longint; begin assign(input, 'lostcow.in'); reset(input); assign(output, 'lostcow.out'); rewrite(output); readln(x, y); if x = y then begin writeln(0); halt; end; n := x; t := 1; ans := 0; repeat ans := ans + abs(t) + abs(n - x); n := x + t; t := -t * 2; if ((n >= y) and (x < y)) or ((n <= y) and (x > y)) then begin ans := ans - abs(n - y); break; end; until false; writeln(ans); close(input); close(output); end. ``` 这段代码同样遵循相同的逻辑结构,适用于需要提交至 USACO 平台的情况[^3]。 --- ### Python 实现代码 对于初学者而言,Python 提供了一种更为简洁的方式表达这一算法: ```python def lost_cow(x, y): if x == y: return 0 position = x step = 1 total_distance = 0 while True: # Move to the right new_position = position + step if (x < y and new_position >= y) or (x > y and new_position <= y): total_distance += abs(new_position - position) total_distance -= abs(new_position - y) break total_distance += abs(new_position - position) position = new_position total_distance += abs(position - x) # Move to the left step *= -2 new_position = position + step if (x < y and new_position >= y) or (x > y and new_position <= y): total_distance += abs(new_position - position) total_distance -= abs(new_position - y) break total_distance += abs(new_position - position) position = new_position total_distance += abs(position - x) return total_distance # Example usage print(lost_cow(int(input()), int(input()))) ``` 该版本通过逐步调整步长和方向完成了整个搜索流程[^4]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值