ACM study day3

今天练了二分和快速幂,题目挺难的,挑几个我做上的说一下吧。

先给出几个二分和快速幂的模板函数;

二分

void BS(int m)
{
    int x=0,y=a[m-1]-a[0];
    while(y-x>1)
    {
        int mid=(x+y)/2;
        if(judge(mid))
            x=mid;
        else
            y=mid;
    }
    cout<<x<<endl; 
}

快速幂

LL PowerMod(LL a, LL b)//a^b  
{  
    LL ans = 1;  
    while (b > 0)  
    {  
        if (b & 1)  
        {  
            ans = (ans*a) % MOD;  
        }  
        b >>= 1;  
        a = (a*a) % MOD;  
    }  
    return ans;  
}  

矩阵乘法加矩阵快速幂取模

struct mat  
{  
    ll a[2][2];  
};  
mat mat_mul(mat x,mat y)  
{  
    mat res;  
    memset(res.a,0,sizeof(res.a));  
    for(int i=0;i<2;i++)  
        for(int j=0;j<2;j++)  
        for(int k=0;k<2;k++)  
        res.a[i][j]=(res.a[i][j]+x.a[i][k]*y.a[k][j])%MOD;  
    return res;  
}  

void mat_pow(int n) 
{ 
mat c,res; 
c.a[0][0]=c.a[0][1]=c.a[1][0]=1; 
c.a[1][1]=0; 
memset(res.a,0,sizeof(res.a)); 
for(int i=0;i<2;i++) res.a[i][i]=1; 
while(n) 
{ 
if(n&1) res=mat_mul(res,c); 
c=mat_mul(c,c); 
n=n>>1; 
} 
printf("%I64d
",res.a[0][1]); 
}

A  POJ 2456

这道题就是二分,但是二分检验的地方比较有趣,全部贴上来,那个judge函数我想了一阵子。。。(比较笨)。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <map>
#include <vector>
#include <set>
#include <queue>
using namespace std;
int a[100010];
int m,n;
bool judge(int d)
{
    int fir,last=0;
    for(int i=0;i<n-1;i++)
    {
    fir=last+1;
    while(fir<m&&a[fir]-a[last]<d)
        fir++;
    if(fir==m)
        return false;
    last=fir;
    } 
    return true;
}
void BS(int m)
{
    int x=0,y=a[m-1]-a[0];
    while(y-x>1)
    {
        int mid=(x+y)/2;
        if(judge(mid))
            x=mid;
        else
            y=mid;
    }
    cout<<x<<endl; 
}

int main()
{

cin>>m>>n;
for(int i=0;i<m;i++)
{
    scanf("%d",&a[i]);
}
sort(a,a+m);
BS(m);
return 0;
}
原文地址:https://www.cnblogs.com/PixelOrange/p/8318753.html