array median transformation minimum steps

后端 未结 3 874
不思量自难忘°
不思量自难忘° 2021-01-13 02:12

Given an array A with n integers. In one turn one can apply the following operation to any consecutive subarray A[l..r] : assign to all A i (l <= i <= r) median of sub

3条回答
  •  时光取名叫无心
    2021-01-13 02:56

    This is the problem from codechef Long Contest.Since the contest is already over,so awkwardiom ,i am pasting the problem setter approach (Source : CC Contest Editorial Page).

    "Any state of the array can be represented as a binary mask with each bit 1 means that corresponding number is equal to the max and 0 otherwise. You can run DP with state R[mask] and O(n) transits. You can proof (or just believe) that the number of statest will be not big, of course if you run good DP. The state of our DP will be the mask of numbers that are equal to max. Of course, it makes sense to use operation only for such subarray [l; r] that number of 1-bits is at least as much as number of 0-bits in submask [l; r], because otherwise nothing will change. Also you should notice that if the left bound of your operation is l it is good to make operation only with the maximal possible r (this gives number of transits equal to O(n)). It was also useful for C++ coders to use map structure to represent all states."

    The C/C++ Code is::

    #include 
    #include 
    using namespace std;
    
    int bc[1<<15];
    const int M = (1<<15) - 1;
    
    void setMin(int& ret, int c)
    {
        if(c < ret) ret = c;
    }
    
    void doit(int n, int mask, int currentSteps, int& currentBest)
    {
        int numMax = bc[mask>>15] + bc[mask&M];
        if(numMax == n) {
            setMin(currentBest, currentSteps);
            return;
        }
        if(currentSteps + 1 >= currentBest)
            return;
        if(currentSteps + 2 >= currentBest)
        {
            if(numMax * 2 >= n) {
                setMin(currentBest, 1 + currentSteps);
            }
            return;    
        }  
    
        if(numMax < (1<= a) {
                    doit(n, c, currentSteps + 1, currentBest);
                }
            }
        }
    }
    
    int v[32];
    void solveCase() {
        int n;
        scanf(" %d", &n);
        int maxElement = 0;
        for(int i=0;i maxElement) maxElement = v[i];
        }
        int mask = 0;
        for(int i=0;i>1] + (i&1);
        }
        int cases;
        scanf(" %d",&cases);
        while(cases--) solveCase();
    }
    

提交回复
热议问题