Traveling Salesman around Lake(模拟)

题目描述
There is a circular pond with a perimeter of K meters, and N houses around them.
The i-th house is built at a distance of Ai meters from the northmost point of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints
·2≤K≤106
·2≤N≤2×105
·0≤A1<…<AN<K
·All values in input are integers.

输入
Input is given from Standard Input in the following format:

K N
A1 A2 … AN

输出
Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

样例输入
【样例1】
20 3
5 10 15
【样例2】
20 3
0 5 15

样例输出
【样例1】
10
【样例2】
10

提示
样例1解释
If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.
样例2解释
If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.

题目大意:
在一个圆形周长为K的池塘上有N个房子
原点是在最北边,然后给出N个数据(每个房子到原点的距离,是弧线距离)
求最少要花多少距离可以经过所有房子
思路:
从一个房子出发,要经过所有的房子,最后回到的只能是这个房子相邻的房子中的一个
所以只要找到两个相邻房子的最大距离,再用周长减去最大距离,即可得到最短路径
注意第一个点和最后一个点之间的距离要特殊判断( 周长-(最后一个点的值-第一个点的值) )
题目说给的值是小于K的,每个值应该可以不用对K取模(大于K的话同一个点对K取模的值相同)

AC代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
 
typedef long long ll;
ll k,n,t,tmp;
vector<ll> arr;
 
int main()
{
    ios::sync_with_stdio(false);
    cin >> k >> n;
    for(ll i = 0; i < n; i++)
    {
        cin >> tmp;
        arr.push_back(tmp%k);
    }
    for(ll i = 1; i < n-1; i++)
    {
        tmp = max(abs(arr[i] - arr[i-1]),abs(arr[i+1] - arr[i]));
        t = max(t,tmp);
    }
    tmp = max(abs(arr[1] - arr[0]),k - abs(arr[0] - arr[n-1]));
    t =  max(t,tmp);
    tmp = max(abs(arr[n-1] - arr[n-2]),k - abs(arr[0] - arr[n-1]));
    t =  max(t,tmp);
    cout << k - t << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值