Second My Problem First HDU - 3706 (Monotone Queue)

Title Link

https://vjudge.net/problem/HDU-3706

The main idea of the topic

Here are n, A, B;
Let you calculate S I = A mod B, T I = Min {S K | i-A <= K <= i, K >= 1}
T i (1 <= i <= n) mod B

Core idea

Bare monotone queue problem
Specific knowledge about monotonous queues in this blog is more detailed: http://blog.csdn.net/justmeh/article/details/5844650

Code

Array simulation

#include<bits/stdc++.h>
using namespace std;

typedef pair<int, int> P;
typedef long long ll;
P cnt[100005];//first store value, second store id

int main()  
{  
    ll n,a,b;   
    while(scanf("%lld %lld %lld",&n,&a,&b)!=EOF)  
    {  
        int  k1=1,k2=1;         //Queue header and tail  
        long long  ans=1,s=1;  
        for(int i=1;i<=n;i++)  
        {  
            s=(s*a)%b;  
            while(k1!=k2 && cnt[k2-1].first>s) --k2;//Maintaining monotonous queues  
            cnt[k2].second=i,cnt[k2++].first=s; //Join the team  
            while(i-cnt[k1].second>a) ++k1; //The number of elements is more than a, and they are in line.  
            ans*=cnt[k1].first;                //product  
            ans%=b;  
        }  
        printf("%lld\n",ans);  
    }  
    return 0;  
}  

Double-ended queue with stl

#include<bits/stdc++.h>
using namespace std;

typedef pair<int, int> P;
const int INF = 1e9 + 7;
deque<P>cnt;

int main()
{
        long long n, a, b;
        while(~scanf("%lld%lld%lld", &n, &a, &b))
        {
            cnt.clear();
                long long ans = 1, s = 1;
        for(int k = 1; k <= n; ++k)
        {
            s = (s*a)%b;
            while(!cnt.empty() && cnt.back().first > s) cnt.pop_back();
            cnt.push_back(P(s, k));
            if(cnt.back().second < k - a) cnt.pop_front();
            ans*=cnt.front().first;
            ans%=b;
        }
        cout<<ans<<endl;
        }
        return 0;
}

Heart Capability and Attention Points

  • The two methods have the same time, indicating that deque efficiency is still possible, but if the id is maintained with deque, it will be overtime.
  • Pay attention to the detonation of int s, we must pay attention to the long long long ah

Posted by mark_and_co on Wed, 13 Feb 2019 21:09:19 -0800