HDU-5875-Function

鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=5875

題意:給定數組a[],m 個詢問L,R,求a[L],依次取模a[L+1]...a[R]後的值。

題解:找出每個數後面第一個比他小的數的位置,但在最壞的情況下還是O(mn)。。。

CODE:

#include <bits/stdc++.h>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define INF 0x3f3f3f3f
#define LL long long
#define bug cout<<"bug"<<endl
const int MAXN = 200007;
const int MAXM = 20007;
const int MOD = 1e9 + 9;
using namespace std;
int a[MAXN],link[MAXN];
stack<int> s;
int main()
{
    int T;
    scanf("%d",&T);
    int n,m;
    while(T--)
    {
        scanf("%d",&n);
        memset(link,0,sizeof(link));
        while(!s.empty())s.pop();
        for(int i=1; i<=n; ++i)
        {
            scanf("%d",&a[i]);
            while(!s.empty()&&a[s.top()]>=a[i])
            {
                link[s.top()]=i;
                s.pop();
            }
            s.push(i);
        }
        int l,r;
        scanf("%d",&m);
        for(int i=0; i<m; ++i)
        {
            scanf("%d%d",&l,&r);
            int x=a[l];
            while(link[l] && link[l]<=r)
            {
                l=link[l];
                x%=a[l];
            }
            printf("%d\n",x);
        }
    }
    return 0;
}
/*
1
3
2 3 3
1
1 3
*/


發佈了397 篇原創文章 · 獲贊 9 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章