当前位置: 代码迷 >> 综合 >> 北林oj-算法设计与分析-Removing the Wall(C++,思路+代码)
  详细解决方案

北林oj-算法设计与分析-Removing the Wall(C++,思路+代码)

热度:36   发布时间:2023-11-29 10:07:51.0

描述

There is a wall in Tom's garden, which is builded by N different bricks. Bricks may have different height, but their width are the same. For example, when N is 7, and H=[1,2,6,1,1,7,1], this wall will be look like:

One day, Tom bought a new car and he wants to park it in his garden. So he needs to remove some parts of the wall. In order to reduce the cost, the sum of height of the removing part should be as low as possible.

输入

Each test case starts with two integers N, K (1<=N<=1*10^3,1<=K<=N). n means this wall is builded by N different bricks, and K means the width of the car. The next line will be n integers H1,H2,..,Hn(1<=Hi<=100), representing the height of the N bricks. The input will be terminated at the end of file (EOF).

输出

For each test case, you must print an integer M which means removing from the Mth brick. If there is more than one position, print the most left one.

输入样例 1 

7 3
1 2 6 1 1 7 1

输出样例 1

3
//注意这里有一个隐藏的换行符,输出的时候格式注意!!

提示

In the sample, the sum of the numbers of the 3rd, 4th, 5th bricks is 8, which is the lowest, so the wall should be removed from the 3rd position.

思路:

题目翻译一下就是车宽度是多少,就有多宽的墙全被拆除,问最少拆几块。

数据的存储格式使用vector,因为数组不支持长度可变的变量。

这个题可以使用快慢指针。指针的跨度就是车宽k,注意数组如果是从0开始使用的,那么也要从0开始计数。两个指针中间的所有数值构成一个块,这个块里的所有值加起来就是这次要拆的砖块数量。

拿测试用例1 2 6 1 1 7 1举例,车宽是3,初始位置slow在[0]号,指的是1;fast在[2]号,指的是6,所以第一次要拆的数量就是1 + 2 + 6 = 9。

题目乍一看是暴力算法,每次这个块向右移动一位就要重新算一次块内的值,但是细想一下并不用每次都重新计算,这也是这个题可以优化的地方——仅使用循环计算一次当前的值,后面的值可以这样做:fast后移一位,当前总和test加上fast的值,然后减去slow的值,slow再后移一位,直至fast到了数组长度-1的位置。(-1,因为后面还要fast++,不-1会溢出)

设置计算最小数量的值mini = 30000(数尽量大,不大会过不了)按这样每次计算好test以后,和现在的mini比大小,如果比mimi小,就记录mini = test,同时记录slow所指向的位置 + 1用于输出。

可以思考一个问题:为什么有的使用双指针的题就不能这么计算,而是每次都要重新for循环计算块内的值,而这个题可以只循环一次?

——————————分割线——————————

答案是这个题的块的长度不变,十分“标准”:fast和slow是在一个循环体内执行的,而且每次只移动一位,所以进行简单的加和相减就可以了。

代码如下(有注释):

#include<iostream>
#include<bits/stdc++.h>
using namespace std;int main()
{int n, k;while (cin >> n && cin >> k){//构造墙数组vector<int> v(n);for (int i = 0; i < n; i++)cin >> v[i];int fast = k - 1, slow = 0; //这是那个车的宽度(在数组中所以减1)int anspos = 0; //最后要输出的位置long mini = 30000; //拆除的最小砖块数,这个数小了会是WAlong test = 0; //每次遍历所要拆的砖块数量,临时变量//先算第一次testfor (int i = slow; i <= fast; i++)test += v[i];//这里注意是n - 1while (fast < n - 1){//fast后移一位,test加上fast++;test += v[fast];//test减去最前面的值,加上后移一位的值test -= v[slow];slow++;	//判断,可能记录ansposif (mini > test){mini = test;anspos = slow + 1;}}cout << anspos << endl;}return 0;
}

  相关解决方案