程式碼片1

PengPengBlog發表於2017-05-23
#include <vector>
#include<iostream>


void func(std::vector<int> vec, int &maxCountOn, int &maxCountOff)
{
    /*! preparation */
    size_t length = vec.size();

    size_t curCountOn = 0; /*!< current */
    size_t curCountOff = 0; /*!< current */

    /*! intialize first element */
    size_t previous = vec[0];
    bool countOn;
    if (0 == previous)
    {
        ++curCountOff;
        countOn = false;
    }
    else // previous > 0
    {
        ++curCountOn;
        countOn = true;

    }

    /*! loop starts with the 2nd element */
    for (size_t i = 1; i < length; i++)
    {
        size_t current = vec[i];
        if (countOn)  ////亮點在這兒。 countOn 可以一直延伸。 可以將中間幾段單獨剔出來來處理。 因為連續不斷,所以可以踢出來單獨處理。
        {
            if (current > 0)
            {
                ++curCountOn;
            }
            else // current == 0
            {
                /*! update maxCountOn */
                maxCountOn = maxCountOn < curCountOn ? curCountOn : maxCountOn;
                curCountOn = 0;
                countOn = false;
                curCountOff = 1;
            }
        }
        else // count off
        {
            if (0 == current)
            {
                ++curCountOff;
            }
            else // current > 0
            {
                /*! update maxCountOff */
                maxCountOff = maxCountOff < curCountOff ? curCountOff : maxCountOff;
                curCountOff = 0;
                countOn = true;
                curCountOn = 1;
            }
        }
    }

    /*! update last continuous segment */
    maxCountOn = maxCountOn < curCountOn ? curCountOn : maxCountOn;
    maxCountOff = maxCountOff < curCountOff ? curCountOff : maxCountOff;

}


int main()
{
    int maxCountOn = 0, maxCountOff = 0;

    int Arr[17] ={1, 1, 1, 1, 0, 0, 0, 5, 5, 1, 1, 1, 0, 0, 0, 0, 0};
    std::vector<int> vec;

    for(size_t i = 0; i<17; i++)
    {
        vec.push_back(Arr[i]);
    }

    func(vec,maxCountOn,maxCountOff );

    std::cout<<maxCountOn<<"    "<<maxCountOff<<"   "<<std::endl;
}




相關文章