防卡常技巧总结

· · 科技·工程

作用

防卡常技巧,对应防止题目卡常导致TLE的情况。

技巧一:快读快写

定义

由于getchar()的读入速度较快,我们可以利用getchar()进行输入,以不同的情况用不同的方法处理getchar()读入的字符。
同样,可以用putchar()快速输出。

例子

快读int:

inline void cin(int &x){
    x=0;
    bool f=false;
    char c=' ';
    while((c<'0'||c>'9')&&c!='-')c=getchar();
    if(c=='-'){
        f=true;
        c=getchar();
    }
    while(c<='9'&&c>='0'){
        x=x*10+c-'0';
        c=getchar();
    }
    if(f)x=-x;
}

快读long long:

inline void cin(long long &x){
    x=0;
    char c=' ';
    bool f=false;
    while((c<'0'||c>'9')&&c!='-')c=getchar();
    if(c=='-'){
        f=true;
        c=getchar();
    }
    while(c<='9'&&c>='0'){
        x=x*10+c-'0';
        c=getchar();
    }
    if(f)x=-x;
}

快写int:

inline void cout(int f){
    if(f<0){
    putchar('-');
    f=-f;
   }
   if(f>=10)cout(f/10);
   putchar(f%10+'0');
}

技巧二 :链式前向星

定义

图论题中用于连邻接表的一种方法,且是其中建立和调用速度较快的方式。

模板

建链式前向星:

struct edge{
   int to,id,nxt; 
}e[20002];
int s[5009];
inline void add(int x,int y,int z){
    e[z*2-1]=edge{y,z,s[x]};
    e[z*2]=edge{x,z,s[y]};
    s[x]=z*2-1;
    s[y]=z*2;
}

调用链式前向星:

//v表示对应节点
for(int i=s[v];i!=0;i=e[i].nxt)

技巧三: 减少不必要的空间使用

定义

额外的空间会影响速度,故而要减少此情况。

例子

做P2680和P2607时,将部分变量的类型由long long改为int会使数据点回馈从TLE变为AC(保证其它无问题时)。

技巧四:特殊代码

定义

部分代码语句会加快速度,使得速度加快,从而防卡常。

例子

函数前加 inline,如:

inline void dfs(int nk,int l){
    dep[nk]=dep[l]+1;
    dep[m]=1;
    eulur[++cnt]=nk;
    id[nk]=cnt;
    edge atc=e[s[nk]];
    while(true){
        if(atc.end!=l){
            dfs(atc.end,atc.begin);
            eulur[++cnt]=nk;
        }
        if(atc.next==0)return;
        atc=e[atc.next];
    }
}

会使函数宏定义,但对 struct 或 class 使用会 CE。
函数读入变量类型加入 register 可以使函数进入寄存器,通常处理器处理寄存器内内容较快,但其不能存太多变量,如:

inline void dfs(register int nk,register int l){
    dep[nk]=dep[l]+1;
    dep[m]=1;
    eulur[++cnt]=nk;
    id[nk]=cnt;
    edge atc=e[s[nk]];
    while(true){
        if(atc.end!=l){
            dfs(atc.end,atc.begin);
            eulur[++cnt]=nk;
        }
        if(atc.next==0)return;
        atc=e[atc.next];
    }
}

总结

可以通过快读快写,减少不必要的空间的方法在题目卡常时多拿分或AC,当题目为图论题时还可以用链式前向星。

福利

练习题:

  1. 合并果子(数据加强版):范围大,限时小;
  2. Switch the Lamp On:限时超小,卡Dijkstra;
  3. 运输计划:较为卡常;
  4. 骑士:特别卡常。