需要注意的点
徐仓仓 Lv3

输出格式

补位

需要注意题目的输出格式,可能不会直说,若是00001时,注意要在高位补0

1
2
3
printf("%05d",a);//以0补充
printf("%5d",a);//以5位右对齐输出
printf("%.5f",b);//保留五位小数

科学计数法

用cout输出大数会产生科学计数法

iomanip——定义IO流输出输入格式的头文件

1
2
cout << fixed << setprecision(0) << 数据 << endl;
//不以科学计数法输出—固定格式+0精度

取余

要求对结果的大数取模时,若最后再取模,可能在计算过程中越界,如:

1
2
3
4
while(i<n){
a+=b;
}
return a%100;

存在公式
$$
(a\pm b)%p=(a%p\pm b%p)%p\
(ab)%m=(a%mb%m)%m\
a^b%m=(a%m)^b%m
$$
因此,可以在循环中取模

1
2
3
4
while(i<n){
a=(a+b)%100;
}
return a;

时间超限

  • 输入输出

利用coutcin在数据量大时会直接超时,需使用**printf()scanf()**。

  1. char数组
1
2
3
char a[10];
scanf("%s",a);
printf("%s",a);
  1. string

只能用cin和cout进行输入输出,可利用c_str()转换为char数组。

1
2
3
4
string s;
cin>>s;
cout<<s;
printf("%s",s.c_str())

double精度问题

double可能会导致误差,如double*int和int*double计算所得答案不同

1
2
3
4
5
//1104 Sum of Number Segments
double ans=0,temp;
ans += temp * (i + 1) * (N - i);
ans += (i + 1) * (N - i) * temp;
//两者计算答案不同

可以利用long long 型,对浮点数先乘1000后除1000的方法避免误差( 假设测试样例的小数在三位以内,四五六位经过多次累加进位后依然可能会引起精度问题)

1
2
3
long long ans = 0;
ans += (long long)(a * 1000 * (N - i) * (i + 1));
printf("%.2f\n", ans / 1000.0);

1106 Lowest Price in Supply Chain中,需计算叶子节点的深度,利用复利法计算结果

若递归时,参数设为double,会导致错误点二错误

1
2
3
4
5
6
double rate;
void DFS(int root,double price){
……
DFS(newroot, (1+rate) * price);
……
}

若递归时,参数设置为int记录层数,最后再计算,成功AC

1
2
3
4
5
6
void DFS(int root,int layer) {
……
DFS(newroot, layer + 1);
……
}
double price = pow((1 + r), minlayer) * P;

cmath

引入#include<cmath>

以e为底:log(exp(n))

以10为底:log10(n)

以m为底:log(n)/log(m)

map和哈希表

​ 将学生名字abc9(由三个字母和一个数字组成)对应到表中,利用map<string,int>可能导致存储过大,提示段错误,因此可考虑hash表的形式。

  • map

    map中元素自动按键从小到大排序
1
2
map<string,int>clas;
clas["abc9"]=1;

可通过map.count()函数判断某键是否存在。

1
2
clas.count("abc9");//1
clas.count("aaa8");//0
  • hash

1
2
3
4
5
6
7
8
9
//将字母和数字利用ASCII表映射到数字
int hash(char name[5]){
int num=0;
for(int i=0;i<3;i++){
num=num*26+name[i]-'A';//注意*26和减'A'
}
num=num*10+name[3]-'0';//注意*10和减'0'
return num;
}

转变后姓名对应着索引,可知索引最大是26*26*26*10,创建数组或vector时需注意大小const int maxn=200000。

静态链表

当结点的地址是比较小的整数(如5位数的地址)时,可采用静态链表,相比动态链表更加方便。

1
2
3
4
5
6
7
struct Node {
char data;
int next;
}node[size];
//……
node[00011].data = data;
node[00011].next = next;

 Comments