包含头文件

LeetCode类型的题目

LeetCode网站的题目的特点:

  • 给出了函数原型,只要在函数体里补充代码即可
  • 使用C++语言时,不需要包含头文件,不需要using std里面的类或变量
  • 使用Java或Python等语言时,也不需要import package
  • 算法的输出一般通过return给出,不需要打印

HihoCoder类型的题目

这种oj类型的题目,需要写出完整的代码,包含头文件(C/C++),导入用到的包(Java、Python),而且要用完整的输入和输出。
为了编写代码的快速性,通常会把需要用到的头文件、宏定义、类型定义等事先写出来,在做题的时候直接拷贝,下面的是常用的头文件和宏定义等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>

using namespace std;

#define MP(a, b) make_pair(a, b)
#define PB(a) push_back(a)

const int INF = 0x3f3f3f3f;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<unsigned int,unsigned int> puu;
typedef pair<int, double> pid;
typedef pair<ll, int> pli;
typedef pair<int, ll> pil;

template <class T,class U>inline void Max(T &a,U b){if(a < b) a = b;}
template <class T,class U>inline void Min(T &a,U b){if(a > b) a = b;}

第19行代码把int类型的无限大设置为0x3f3f3f3f,0x3f3f3f3f的十进制是1061109567,是10^9级别的(和0x7fffffff一个数量级),而一般场合下的数据都是小于10^9的,所以它可以作为无穷大使用而不致出现数据大于无穷大的情形。
另一方面,由于一般的数据都不会大于10^9,所以当我们把无穷大加上一个数据时,它并不会溢出(这就满足了“无穷大加一个有穷的数依然是无穷大”),事实上0x3f3f3f3f + 0x3f3f3f3f=2122219134,这非常大但却没有超过32-bit int的表示范围,所以0x3f3f3f3f还满足了我们“无穷大加无穷大还是无穷大”的需求。
最后,0x3f3f3f3f还能给我们带来一个意想不到的额外好处:
如果我们想要将某个数组清零,我们通常会使用memset(a,0,sizeof(a)),方便又高效,但是当我们想将某个数组全部赋值为无穷大时,就不能使用memset函数而得自己写循环了,因为memset是按字节操作的,它能够对数组清零是因为0的每个字节都是0(一般我们只有赋值为-1和0的时候才使用它)。现在好了,如果我们将无穷大设为0x3f3f3f3f,那么奇迹就发生了,0x3f3f3f3f的每个字节都是0x3f!所以要把一段内存全部置为无穷大,我们只需要memset(a,0x3f,sizeof(a))

万能头文件

#include<bits/stdc++.h>这个头文件包含了C++的所有头文件,为了方便,可以直接包含这个头文件。不过有的编译器可能不支持,这个需要注意。

输入和输出

LeetCode类型的题目不需要用户关注输入和输出,而HihoCoder类型的题目需要用户写出完整的输入和输出格式。一般的格式如下:
C语言:

1
2
3
4
5
6
7
8
9
#include <stdio.h>

int main(void) {
int a, b;
while(scanf("%d%d", &a, &b) != EOF) {
printf("%d\n", a + b);
}
return 0;
}

C++语言:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main(void) {
int a, b;
while(cin >> a >> b) {
cout << a + b << endl;
}
return 0;
}

Java语言:

1
2
3
4
5
6
7
8
9
10
11
12
13
	
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b);
}
}
}

C#语言:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	
using System;

public class AplusB
{
private static void Main()
{
string line;
while((line = Console.ReadLine()) != null)
{
string[] tokens = line.Split(' ');
Console.WriteLine(int.Parse(tokens[0]) + int.Parse(tokens[1]));
}
}
}

Python2语言:

1
2
3
4
5
6
7
	
while True:
try:
(x, y) = (int(x) for x in raw_input().split())
print x + y
except EOFError:
break

特别地,对于Google apac test这样的竞赛题目,输入和输出要求在文件中,那么需要重定向标准输入和标准输出:

1
2
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);

Ref:
为何程序员喜欢将INF设置为0x3f3f3f3f?