uva 1642 Magical GCD

很经典的题目,愣是没做出来。。

题意:给出一个序列,求一子序列,满足其GCD(子序列)* length(子序列)最大。

题解:

  类似单调队列的思想,每次将前面所得的最大公约数与当前数进行GCD,若GCD变小,则将原来的最大公约数替换成当前GCD,因为原来的已经不可能取到了。

  实现时利用的是STL中的map。另外经WLM牛的指点,得知map在遍历时插入删除是十分危险的操作,最后用滚动map实现。

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <set>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)>(y)?(y):(x))
#define INF 0x3f3f3f3f
#define LL long long

using namespace std;

LL ans, a;
int n, t;
map<LL, LL> mapp[2];

LL gcd(LL a, LL b)
{
    return b?gcd(b, a%b):a;
}

int main()
{
    scanf("%d", &t);
    while(t--)
    {
        ans=0;
        scanf("%d", &n);
        int k=0;
        mapp[k].clear();
        for(int i=1; i<=n; i++, k^=1)
        {
            scanf("%I64d", &a);
            mapp[!k].clear();
            ans=max(ans, a);
            if(mapp[!k].find(a)==mapp[!k].end())
                mapp[!k][a]=i;
            for(map<LL, LL>::iterator it=mapp[k].begin(); it != mapp[k].end(); it++)
            {
                LL tmp=gcd(a, it->first);
                ans=max(ans, tmp*(i-it->second+1));
                if(mapp[!k].find(tmp)==mapp[!k].end())
                    mapp[!k][tmp]=it->second;
                else if(mapp[!k][tmp]>it->second)
                        mapp[!k][tmp]=it->second;
            }
        }
        printf("%I64d
", ans);
    }
    return 0;
}
View Code

当然不用滚动也可以,因为加入的元素都小于当前元素,不会影响到后面,其次删除时 用 map.erase(it++)就可以了

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <set>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)>(y)?(y):(x))
#define INF 0x3f3f3f3f
#define LL long long

using namespace std;

LL ans, a;
int n, t;
map<LL, LL> mapp;

LL gcd(LL a, LL b)
{
    return b?gcd(b, a%b):a;
}

int main()
{
    scanf("%d", &t);
    while(t--)
    {
        ans=0;
        scanf("%d", &n);
        mapp.clear();
        for(int i=1; i<=n; i++)
        {
            scanf("%I64d", &a);
            if(mapp.find(a) == mapp.end())
                mapp[a]=i;
            for(map<LL, LL>::iterator it=mapp.begin(); it != mapp.end(); )
            {
                LL tmp=gcd(a, it->first);
                ans=max(ans, tmp*(i-it->second+1));
                if(mapp.find(tmp) == mapp.end())
                    mapp[tmp]=it->second;
                else
                    mapp[tmp]=min(mapp[tmp], it->second);
                if(tmp<it->first)
                    mapp.erase(it++);
                else
                    it++;
            }
        }
        printf("%I64d
", ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/Mathics/p/3984964.html