好用的代码

· · 算法·理论

分数:

这个东西被用到了P2122

更新

  1. 2022-12-03 加入了分数取模的内容
  2. 2023-08-02 加入了复数的内容
  3. 2023-08-04 加入了高精度的内容(暂无除法)
#define ll long long
struct fraction
{
    ll deno,nume;
    void reduct()
    {
        if(nume==0)deno=1;
        ll gcd=__gcd(deno,nume);
        deno/=gcd;nume/=gcd;
    }
    void PrintFrac()
    {
        reduct();
        if(deno!=1)printf("%lld/%lld\n",nume,deno);
        else printf("%lld\n",nume);
    }
    void exgcd(ll a,ll b,ll &x,ll &y)
    {
        if(b==0){x=1;y=0;return;}
        exgcd(b,a%b,y,x);
        y-=(a/b)*x;
    }
    ll inv(ll x,ll p)
    {
        ll ansx,ansy;
        exgcd(x,p,ansx,ansy);
        ansx=(ansx%p+p)%p;
        return ansx;
    }
    void PrintInv(ll p)
    {
        reduct();
        printf("%lld\n",(((nume%p)*inv(deno,p))%p+p)%p);
    }
    fraction friend operator +(const fraction A,const fraction B)
    {
        fraction res;
        ll Lcm=A.deno/__gcd(A.deno,B.deno)*B.deno;
        res.deno=Lcm;
        res.nume=(Lcm/A.deno*A.nume)+(Lcm/B.deno*B.nume);
        res.reduct();
        return res;
    }
    fraction friend operator -(const fraction A,const fraction B)
    {
        fraction res;
        ll Lcm=A.deno/__gcd(A.deno,B.deno)*B.deno;
        res.deno=Lcm;
        res.nume=(Lcm/A.deno*A.nume)-(Lcm/B.deno*B.nume);
        res.reduct();
        return res;
    }
    fraction friend operator *(const fraction A,const fraction B)
    {
        fraction res;
        res.deno=A.deno*B.deno;
        res.nume=A.nume*B.nume;
        res.reduct();
        return res;
    }
    fraction friend operator /(const fraction A,const fraction B)
    {
        fraction res;
        res.deno=A.deno*B.nume;
        res.nume=A.nume*B.deno;
        res.reduct();
        return res;
    }
};

高精度结构体(内含复数结构体)

const int N=1e3+5;
const double pi=acos(-1);
struct cp
{
    double real,imag;
    cp friend operator +(const cp a,const cp b){return (cp){a.real+b.real,a.imag+b.imag};}
    cp friend operator -(const cp a,const cp b){return (cp){a.real-b.real,a.imag-b.imag};}
    cp friend operator *(const cp a,const cp b){return (cp){a.real*b.real-a.imag*b.imag,a.imag*b.real+a.real*b.imag};}
};
void DFT(cp F[],int len)
{
    if(len==1)return;
    cp F0[N],F1[N];
    for(int i=0;i<len;i+=2)F0[i/2]=F[i],F1[i/2]=F[i+1];
    DFT(F0,len/2);DFT(F1,len/2);
    cp w=(cp){cos(2*pi/len),sin(2*pi/len)},idw=(cp){1,0};
    for(int i=0;i<len;i++)
    {
        int id=i%(len/2);
        F[i]=F0[id]+idw*F1[id];
        idw=idw*w;
    }
}
void IDFT(cp F[],int len)
{
    DFT(F,len);
    for(int i=1;i<len-i;i++)swap(F[i],F[len-i]);
    for(int i=0;i<len;i++)F[i].real/=len,F[i].imag/=len;
}
void FFT(cp F[],cp G[],int UpNum)
{
    DFT(F,UpNum);DFT(G,UpNum);
    for(int i=0;i<UpNum;i++)F[i]=F[i]*G[i];//点积 
    IDFT(F,UpNum);
}
struct hp
{
    int p,len;
    int num[N];
    hp(){p=1;len=0;memset(num,0,sizeof(num));}
    void inline ass(string x)//赋值 
    {
        bool f=(x[0]=='-');
        p=(x[0]=='-'?-1:1);len=x.size();
        for(int i=0;i<len-f;i++)num[i]=x[i+f]-'0';
        len=len-1-f;
        for(int i=0;i<len-i;i++)swap(num[i],num[len-i]);
    }
    void inline read()    
    {
        len=-1;
        char ch=getchar();
        while(!isdigit(ch)){if(ch=='-')p=-1;ch=getchar();}
        while(isdigit(ch)){num[++len]=ch-'0';ch=getchar();}
        for(int i=0;i<len-i;i++)swap(num[i],num[len-i]);
    }
    void inline print()
    {
        if(p==-1)printf("-");
        for(int i=len;i>=0;i--)printf("%d",num[i]);
        printf("\n");
    }
    bool friend operator >(const hp A,const hp B)
    {
        if(A.p!=B.p)return A.p>B.p;
        if(A.len!=B.len)return A.len*A.p>B.len*B.p;
        for(int i=A.len;i>=0;i--)
            if(A.num[i]!=B.num[i])return A.num[i]*A.p>B.num[i]*B.p;
        return false;
    }
    bool friend operator <(const hp A,const hp B)
    {
        if(A.p!=B.p)return A.p<B.p;
        if(A.len!=B.len)return A.len*A.p<B.len*B.p;
        for(int i=A.len;i>=0;i--)
            if(A.num[i]!=B.num[i])return A.num[i]*A.p<B.num[i]*B.p;
        return false;
    }
    bool friend operator ==(const hp A,const hp B)
    {
        if(A.p!=B.p)return false;
        if(A.len!=B.len)return false;
        for(int i=A.len;i>=0;i--)
            if(A.num[i]!=B.num[i])return false;
        return true;
    }
    void abs(){p=1;}
    hp friend operator +(const hp A,const hp B)
    {
        hp res;
        if(A.p==B.p)
        {
            res.len=max(A.len,B.len);
            for(int i=0;i<=res.len;i++)res.num[i]=A.num[i]+B.num[i];
            for(int i=0;i<=res.len;i++)
            {
                res.num[i+1]+=(res.num[i]>=10);
                res.num[i]-=(res.num[i]>=10)?10:0;
                res.len+=(res.num[res.len+1]!=0);
            }
            res.p=A.p;
        }
        else 
        {
            hp NewA=A,NewB=B;
            NewB.p*=-1;
            res=NewA-NewB;
        }
        return res;
    }
    hp friend operator -(const hp A,const hp B)
    {
        hp res;
        if(A.p==B.p)
        {
            res.p=A.p;
            hp AbsA=A,AbsB=B;
            AbsA.abs();AbsB.abs();
            if(AbsA<AbsB)swap(AbsA,AbsB),res.p*=-1;
            res.len=AbsA.len;
            for(int i=0;i<=res.len;i++)
            {
                res.num[i]+=AbsA.num[i]-AbsB.num[i];
                if(res.num[i]<0)res.num[i]+=10,res.num[i+1]--;
            }
            while(res.num[res.len]==0&&res.len)res.len--;
            if(res.len==0&&res.num[0]==0)res.p=1;
        }
        else 
        {
            hp NewA=A,NewB=B;
            NewB.p*=-1;
            res=NewA+NewB;
        }
        return res;
    }
    hp friend operator *(const hp A,const hp B)
    {
        int UpNum=1;hp res;
        res.len=A.len+B.len;
        if(A.p!=B.p)res.p=-1;
        else res.p=1;
        while(UpNum<res.len+1)UpNum<<=1;
        cp F[N],G[N];
        for(int i=0;i<=A.len;i++)F[i].real=A.num[i];
        for(int i=0;i<=B.len;i++)G[i].real=B.num[i];
        FFT(F,G,UpNum);
        for(int i=0;i<=res.len;i++)
        {
            res.num[i]+=int(F[i].real+0.5);
            res.num[i+1]+=res.num[i]/10;
            res.num[i]%=10;
            res.len+=(res.num[res.len+1]!=0);
        }
        return res;

    }//FFT:O(nlogn)做法 
//  hp friend operator /(const hp A,const hp B)
//  {
//      
//  } //不会,鸽 
};

好玩的迷宫生成器

代码出处在代码的最后一行,虽然是搬的,但是有改动。(因为一开始输出的迷宫太丑了,不然你为什么会看到return;后面还有代码)然后运行时请将:文字调到最小、背景调成白色、窗口大小自行看着调大吧。。。

upd on 23.1.18:更新了答案的输出

/*
 * MazeGen.c -- Mark Howell -- 8 May 1991
 *
 * Usage: MazeGen [width [height [seed]]]
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<windows.h>

#define WIDTH 40
#define HEIGHT 30

#define UP 0
#define RIGHT 1
#define DOWN 2
#define LEFT 3
#ifdef TRUE
#undef TRUE
#endif /* TRUE */

#define TRUE 1

#define cell_empty(a) (!(a)->up && !(a)->right && !(a)->down && !(a)->left)

typedef struct {
    unsigned int up      : 1;
    unsigned int right   : 1;
    unsigned int down    : 1;
    unsigned int left    : 1;
    unsigned int path    : 1;
    unsigned int visited : 1;
} cell_t;
typedef cell_t *maze_t;

void CreateMaze (maze_t maze, int width, int height);
void SolveMaze (maze_t maze, int width, int height);
void PrintMaze (maze_t maze, int width, int height);
void color(int x);
void wall(int x);
void road(int x);
int main (int argc, char *argv [])
{
//  freopen("maze.txt","w",stdout);
    color(0xf0);
    int width = WIDTH;
    int height = HEIGHT;
    maze_t maze;

    if (argc >= 2)
        width = atoi (argv [1]);

    if (argc >= 3)
        height = atoi (argv [2]);

    if (argc >= 4)
        srand (atoi (argv [3]));
    else
        srand ((int) time ((time_t *) NULL));

    if (width <= 0 || height <= 0) {
        (void) fprintf (stderr, "Illegal width or height value!\n");
        exit (EXIT_FAILURE);
    }
    maze = (maze_t) calloc (width * height, sizeof (cell_t));
    if (maze == NULL) {
        (void) fprintf (stderr, "Cannot allocate memory!\n");
        exit (EXIT_FAILURE);
    }
    CreateMaze (maze, width, height);

    PrintMaze (maze, width, height);

    (void) putchar ('\n');(void) putchar ('\n');(void) putchar ('\n');(void) putchar ('\n');(void) putchar ('\n');

    system("pause");

    SolveMaze (maze, width, height);

    PrintMaze (maze, width, height);

    free (maze);
    exit (EXIT_SUCCESS);

    return (0);

}/* main */

void color(int x)
{
    HANDLE h;//创建句柄,详细句柄知识,请百度一下或查MSDN
    h = GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄
    SetConsoleTextAttribute(h,x);
}

void CreateMaze (maze_t maze, int width, int height)
{
//  return;
    maze_t mp, maze_top;
    char paths [4];
    int visits, directions;

    visits = width * height - 1;
    mp = maze;
    maze_top = mp + (width * height) - 1;

    while (visits) {
        directions = 0;

        if ((mp - width) >= maze && cell_empty (mp - width))
            paths [directions++] = UP;
        if (mp < maze_top && ((mp - maze + 1) % width) && cell_empty (mp + 1))
            paths [directions++] = RIGHT;
        if ((mp + width) <= maze_top && cell_empty (mp + width))
            paths [directions++] = DOWN;
        if (mp > maze && ((mp - maze) % width) && cell_empty (mp - 1))
            paths [directions++] = LEFT;

        if (directions) {
            visits--;
            directions = ((unsigned) rand () % directions);

            switch (paths [directions]) {
                case UP:
                    mp->up = TRUE;
                    (mp -= width)->down = TRUE;
                    break;
                case RIGHT:
                    mp->right = TRUE;
                    (++mp)->left = TRUE;
                    break;
                case DOWN:
                    mp->down = TRUE;
                    (mp += width)->up = TRUE;
                    break;
                case LEFT:
                    mp->left = TRUE;
                    (--mp)->right = TRUE;
                    break;
                default:
                    break;
            }
        } else {
            do {
                if (++mp > maze_top)
                    mp = maze;
            } while (cell_empty (mp));
        }
    }
}/* CreateMaze */

void SolveMaze (maze_t maze, int width, int height)
{
    maze_t *stack, mp = maze;
    int sp = 0;

    stack = (maze_t *) calloc (width * height, sizeof (maze_t));
    if (stack == NULL) {
        (void) fprintf (stderr, "Cannot allocate memory!\n");
        exit (EXIT_FAILURE);
    }
    (stack [sp++] = mp)->visited = TRUE;

    while (mp != (maze + (width * height) - 1)) {

        if (mp->up && !(mp - width)->visited)
            stack [sp++] = mp - width;
        if (mp->right && !(mp + 1)->visited)
            stack [sp++] = mp + 1;
        if (mp->down && !(mp + width)->visited)
            stack [sp++] = mp + width;
        if (mp->left && !(mp - 1)->visited)
            stack [sp++] = mp - 1;

        if (stack [sp - 1] == mp)
            --sp;

        (mp = stack [sp - 1])->visited = TRUE;
    }
    while (sp--)
        if (stack [sp]->visited)
            stack [sp]->path = TRUE;

    free (stack);

}/* SolveMaze */

void wall(int x){while(x--){color(0x00);printf("  ");color(0xff);}}
void road(int x){while(x--)printf("  ");}
void path(int x){while(x--){color(0xcc);printf("  ");color(0xff);}}
void PrintMaze (maze_t maze, int width, int height)
{
//  Sleep(1000*60*5);
    maze->up = TRUE;
    (maze + width * height - 1)->down = TRUE;
    for(int w = 0; w < width; w++)
    {
        wall(1);
        if ((maze + w)->up)
            if((maze + w)->path) road(1),path(1),road(1);
            else road(3);
        else wall(3);
    }
    wall(1);printf("\n");
    for(int h = 0; h < height; h++)
    {
        for(int i = 0; i < 3; i++)
        {
            for(int w = 0; w < width; w++)
            {
                if ((maze + w)->left)
                    if((maze + w)->path && (maze + w - 1)->path && i == 1)path(1);
                    else road(1);
                else wall(1);
                if((maze + w)->path)
                {
                    if(i == 0)
                    {
                        if(!h && !w){road(1),path(1),road(1);continue;}
                        if(h && (maze + w - width)->path && (maze + w)->up)road(1),path(1),road(1);
                        else road(3);
                    }
                    if(i == 1)
                    {
                        if(w && (maze + w - 1)->path && (maze + w)->left)path(1);
                        else road(1);
                        path(1);
                        if(w != width - 1 && (maze + w + 1)->path && (maze + w)->right)path(1);
                        else road(1);
                    }
                    if(i == 2)
                    {
                        if(h == height - 1 && w == width - 1){road(1),path(1),road(1);continue;}
                        if(h != height - 1 && (maze + w + width)->path && (maze + w)->down)road(1),path(1),road(1);
                        else road(3);
                    }
                }
                else road(3);
            }
            wall(1);printf("\n");
        }
        for(int w = 0; w < width; w++)
        {
            wall(1);
            if ((maze + w)->down)
                if((maze + w)->path && (h == height - 1 ||(maze + w + width)->path))road(1),path(1),road(1);
                else road(3);
            else
                wall(3);
        }       
        wall(1);printf("\n");
        maze+=width;
    }
    return;

    int w, h;
    char *line, *lp;

    line = (char *) calloc ((width + 1) * 2, sizeof (char));
    if (line == NULL) {
        (void) fprintf (stderr, "Cannot allocate memory!\n");
        exit (EXIT_FAILURE);
    }
    maze->up = TRUE;
    (maze + (width * height) - 1)->down = TRUE;

    for (lp = line, w = 0; w < width; w++) {
        *lp++ = '+';
        if ((maze + w)->up)
            *lp++ = ((maze + w)->path) ? '.' : ' ';
        else
            *lp++ = '-';
    }
    *lp++ = '+';
    (void) puts (line);
    for (h = 0; h < height; h++) {
        for (lp = line, w = 0; w < width; w++) {
            if ((maze + w)->left)
                *lp++ = ((maze + w)->path && (maze + w - 1)->path) ? '.' : ' ';
            else
                *lp++ = '|';
            *lp++ = ((maze + w)->path) ? '.' : ' ';
        }
        *lp++ = '|';
        (void) puts (line);
        for (lp = line, w = 0; w < width; w++) {
            *lp++ = '+';
            if ((maze + w)->down)
                *lp++ = ((maze + w)->path && (h == height - 1 ||
                         (maze + w + width)->path)) ? '.' : ' ';
            else

                *lp++ = '-';
        }
        *lp++ = '+';
        (void) puts (line);
        maze += width;
    }
    free (line);

}/* PrintMaze */
//https://www.cnblogs.com/hcbin/archive/2010/10/25/1860778.html

Nim游戏:

#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
int lvl,n,hand;
string str[2]={"现在由玩家操作\n","现在由电脑操作\n"}; 
string win[2]={"玩家胜利!!!\n","电脑胜利!!!\n"};
int a[15],La[15],Ra[15];
int id,num;
int Rint(int l,int r);
void init();
void printA();
void read();
void ComCalc();
void Random();
void SC(int k);
bool GameOver();
int main(){
    srand(time(0));
    init(); 
    while(1)
    {
        cout<<str[hand];
        if(hand)//Com
        {
            printA();
            ComCalc();
            a[id]-=num;
            Sleep(1000);
        }
        else //Peo
        {
            printA(); 
            printf("输入两个数,第一个为选择的石子堆的序号,第二个为取走的个数\n");
            read();
            a[id]-=num;
        }
        if(GameOver())break;
        hand^=1;
    }
    cout<<win[hand];
    Sleep(2000);
    return 0;
} 
int Rint(int l,int r){return rand()%(r-l+1)+l;}
void init()
{
    printf("请输入难度:1~3\n");scanf("%d",&lvl);lvl=min(lvl,3);lvl=max(lvl,1);
    system("cls");
    n=lvl+2;
    La[1]=1;Ra[1]=(1<<3)-1;
    La[2]=1;Ra[2]=(1<<4)-1;
    La[3]=1;Ra[3]=(1<<5)-1;
    int p=Rint(64,67);
    if(p==66)
    {
        for(int i=1;i<n;i++)a[i]=Rint(La[lvl],Ra[lvl]),a[n]^=a[i];
        if(a[n]==0)a[n]=Rint(La[lvl],Ra[lvl]);
        id=Rint(1,n-1);
        swap(a[id],a[n]);
    }
    else for(int i=1;i<=n;i++)a[i]=Rint(La[lvl],Ra[lvl]); 
    printA();
    printf("选择先手输入1,选择后手输入2\n");scanf("%d",&hand);printf("\n开始!\n\n\n");
    hand--;
}
void printA(){printf("当前的石子数是:\n");for(int i=1;i<=n;i++)printf("%d ",a[i]);printf("\n");}
void read()
{
    while(1)
    {
        scanf("%d%d",&id,&num);
        if(id<1||id>n||num<=0||num>a[id])printf("输入不合法!\n");
        else break;
    }
}
void ComCalc()
{
    int Ans=0;
    for(int i=1;i<=n;i++)Ans^=a[i];
    if(Ans)SC(Ans);
    else Random();
}
int cc[15],l;
void Random()
{
    l=0;
    for(int i=1;i<=n;i++)
        if(a[i])cc[++l]=i;
    id=cc[Rint(1,l)];
    num=Rint(1,a[id]);
    printf("电脑选择了拿走了第%d堆的%d块石子\n\n",id,num);
}
void SC(int k)
{
    l=0;
    for(int i=1;i<=n;i++)
        if(a[i]>(a[i]^k))cc[++l]=i;
    id=cc[Rint(1,l)];
    num=a[id]-(a[id]^k);
    printf("电脑选择了拿走了第%d堆的%d块石子\n\n",id,num);
}
bool GameOver()
{
    for(int i=1;i<=n;i++)
        if(a[i])return false;
    return true;
}

一些游戏的代码:

void GoToXY(int x,int y)
{
    COORD pos = {y,x};                 //设置光标位置
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);    // 获取标准输出设备句柄
    SetConsoleCursorPosition(hOut, pos);      //两个参数分别是指定哪个窗体,什么位置?
}
int color(int x,int y)//x为底色,y为字体色 
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),x*16+y);
    /*
    0:黑色 
    1:蓝色 
    2:绿色 
    3:湖蓝色 
    4:红色 
    5:紫色 
    6:黄色 
    7:白色 
    8:灰色 
    9:淡蓝色 
    10:淡绿色 
    11:浅绿色 
    12:淡红色  
    13:淡紫色
    14:淡黄色 
    15:亮白色 
    */
}
void top(int s)
{
    string name=get_name();
    system("cls");
    bool flag=1; 
    int p=1;
    for(int i=1;i<=10;i++)
    {
        if(flag&&data[p].score<=s)
        {
            for(int c=0;c<11;c++)
            {
                for(int j=1;j<=30;j++)printf("\b \b");
                color(0,6+c%2);
                printf("%02d.   ",i);
                cout<<name<<"   ";
                printf("%03d",s);
                Sleep(50);
            }
            color(0,7);
            printf("\n");
            flag=0;
        }
        else 
        {
            printf("%02d.   ",i);
            cout<<data[p].name<<"   ";
            printf("%03d\n",data[p].score);
            p++;
        }
        Sleep(200);
    }
}
string get_name()
{
    string letter="ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    int p[3]={0,0,0};
    system("cls");
    string name="AAA";
    printf("Your Name:\n");
    cout<<name;
    int x=1,y=0;
    GoToXY(x,y);
    while(1)
    {
        if(_kbhit())
        {
            char ch=getch();
            if(ch=='\r')return name;
            switch(ch)
            {
                case 'w':p[y]=(p[y]+1)%27;name[y]=letter[p[y]];cout<<name[y];printf("\b");break;
                case 's':p[y]=(p[y]+26)%27;name[y]=letter[p[y]];cout<<name[y];printf("\b");break;
                case 'a':y=max(0,y-1);GoToXY(x,y);break;
                case 'd':y=min(2,y+1);GoToXY(x,y);break;
            }
        }
    }
}
void Set_screen(int x,int y)
{
    char cmd[32]={0};
    sprintf(cmd,"mode con cols=%d lines=%d",y,x);
    system(cmd);
}
bool password(string correct)
{
    char pw[1005],ch;
    int len=0;
    srand(time(0));
    int r=rand()%100+1;
    for(int i=3;i>0;i--)
    {
        string str;
        printf("密码是:");
        while((ch=getch())!='\r')
        {
            if(ch!='\b')
            {
                pw[++len]=ch;
                printf("*");
            }
            else 
            {
                if(len)
                {
                    printf("\b \b");
                    len--;
                }
            }
        }
        for(int j=1;j<=len;j++)str+=pw[j];
        printf("\n");
        if(str==correct)
        {
            printf("密码正确!");
            Sleep(500);
            system("cls");
            return true;
        }
        else 
        {
            if(i-1)printf("密码错误!你还有%d次机会!\n",i-1);
            else printf("密码错误!再见\n");
        }
        len=0;
        Sleep(500);
        system("cls");
    }
    return false;
}