UVa 1642 魔法GCD + 区间问题总结

题目和题解请见刘汝佳紫皮书340页。

代码中用了STL中的map。也是现在才知道到map在系统中是以pair的形式存储的,first是键值,second是对应的映射值。

map的遍历仍然是使用类的迭代器。

代码如下:

#include
#include
#include
#include
#include
#include
#define LL long long
using namespace std;
const LL maxn=100000+5;

LL n;
map mp;

inline void _read(LL &x){
    char ch=getchar(); bool mark=false;
    for(;!isdigit(ch);ch=getchar())if(ch=='-')mark=true;
    for(x=0;isdigit(ch);ch=getchar())x=x*10+ch-'0';
    if(mark)x=-x;
}

LL gcd(LL x,LL y){
	return y? gcd(y,x%y): x;
}

int main(){
    LL i,j,T;
    _read(T);
	while(T--){
		LL ans=0,x;
    	_read(n);
    	mp.clear();
    	for(i=1;i<=n;i++){
    		_read(x);
    		if(!mp.count(x))mp[x]=i;
    		map::iterator it;
    		for(it=mp.begin();it!=mp.end();){
    			LL cur=gcd(x,it->first);
    			ans=max(ans,cur*(i-it->second+1));
    			if(!mp.count(cur)) mp[cur]=it->second;
    			else mp[cur]=min(mp[cur],it->second);
    			if(curfirst)mp.erase(it++);
    			else it++;
			}
		}
		cout<
以下是对区间问题的一点总结:

方法一: 区间转点

一般是和或者差之类的问题,通过前缀和可以转化为点的问题。

方法二: 确定一边端点

代码中一般用枚举其中一个端点来体现。

这种题目的重点在于转移,总是要维护一个和答案有关的东西(就像本题中的那个map),要考虑如果给定的那个端点移动会造成什么影响。一般会用到线段树之类的数据结构来维护,例如以下两题:

(1) Mex II

(2)Codeforces Round #365 (Div. 2) D (线段树)

方法三:写累了不想写了



你可能感兴趣的:(思维趣题,数学)