2019校招真题编程(三)安置路灯

安置路灯

题目描述

小Q正在给一条长度为n的道路设计路灯安置方案。

为了让问题更简单,小Q把道路视为n个方格,需要照亮的地方用’.'表示, 不需要照亮的障碍物格子用’X’表示。

小Q现在要在道路上设置一些路灯, 对于安置在pos位置的路灯, 这盏路灯可以照亮pos - 1, pos, pos + 1这三个位置。

小Q希望能安置尽量少的路灯照亮所有’.'区域, 希望你能帮他计算一下最少需要多少盏路灯。

输入的第一行包含一个正整数t(1 <= t <= 1000), 表示测试用例数
接下来每两行一个测试数据, 第一行一个正整数n(1 <= n <= 1000),表示道路的长度。
第二行一个字符串s表示道路的构造,只包含’.‘和’X’。

对于每个测试用例, 输出一个正整数表示最少需要多少盏路灯。

我的思路

滑动窗口,其中第一个必须为.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    int t=0;
    //cout<<"testing nums:";
    cin>>t;
    vector<int>res(t,0);
    for(int i=0; i<t; i++)
    {
        int n;
        //cout<<"enter nums: ";
        cin>>n;
        string s;
        //cout<<"enter the numbers of streets: ";
        cin>>s;
        int count=0, j=0;
        while(j<s.length())
        {
            if(s[j]=='.')
            {
                count+=1;
                j+=3;
            }
            else j++;
        }
        res[i]=count;
    }
    
    for(int i=0;i<t;i++)
        cout<<res[i]<<endl;
    return 0;
}

运行时间:30ms

占用内存:772k

发布了68 篇原创文章 · 获赞 2 · 访问量 6167

猜你喜欢

转载自blog.csdn.net/qq_30050175/article/details/104110209