OJ模板库

来源:互联网 发布:recorder.js 编辑:程序博客网 时间:2024/05/22 02:00

最近刷了好几次的oj,好受伤好多都是类似的题目。

最长回文子串

string preprocess(string &str){    string afterProcessStr="#";    for(int i=0;i<str.size();++i)    {        afterProcessStr += str.substr(i, 1)+"#";    }    return afterProcessStr;    //afterProcessStr.clear();}int maxpalindrome(string &str){   string afterProcessStr=preprocess(str);  // cout<<afterProcessStr<<endl;   int maxEdge=0,center=0;   int *p=new int[afterProcessStr.size()]();   int ans=0;   int cur=0;   for(int i=1;i<afterProcessStr.size();++i)   {       p[i]=(maxEdge>i)?min(maxEdge-i,p[2*center-i]):0;       while(i-1-p[i]>=0&&i+1+p[i]<afterProcessStr.size()&&afterProcessStr[i+1+p[i]]==afterProcessStr[i-1-p[i]])          ++p[i];          if(i+p[i]>maxEdge)          {              center=i;              maxEdge=i+p[i];          }          if(p[i]>ans)           ans=p[i];   }    return ans;}

注意上文中preprocess函数会花费大量时间最好是采用预分配内存。

static string afterProcessStr(1000002*2,'#');

具体见:http://blog.csdn.net/zhouyelihua/article/details/46964175

最大公约数

经常使用的最大公约数的方法有辗转相除法

/*输入x,y返回x,y的最大公约数*/int gcd(int x,int y){if(x<y)  return gcd(y,x);if(0==y)    return x;else{    if(0==x&0x1)    {        if(0==y&0x01)            return (gcd(x>>1,y>>1)<<1);        else            return gcd(x>>1,y);    }    else    {      if(0==y&0x01)            return gcd(x,y>>1);        else            return gcd(y,x-y);    }}}
0 0
原创粉丝点击