207. 课程表

我们可以将本题建模成一个求拓扑排序的问题:将每一门课看成一个节点,如果想要学习课程 A之前必须完成课程 B,那么我们从B到A连接一条有向边。这样以来,在拓扑排序中,B一定出现在 A的前面

思路:

考虑拓扑排序中最前面的节点,该节点一定不会有任何入边,也就是它没有任何的先修课程要求。当我们将一个节点加入答案中后,我们就可以移除它的所有出边,代表着它的相邻节点少了一门先修课程的要求。如果某个相邻节点变成了「没有任何入边的节点」,那么就代表着这门课可以开始学习了。按照这样的流程,我们不断地将没有入边的节点加入答案,直到答案中包含所有的节点(得到了一种拓扑排序)或者不存在没有入边的节点(图中包含环)

算法:

使用一个队列来进行广度优先搜索。初始时,所有入度为 00 的节点都被放入队列中,它们就是可以作为拓扑排序最前面的节点,并且它们之间的相对顺序是无关紧要的。

在广度优先搜索的每一步中,我们取出队首的节点u:

我们将u放入答案中

我们移除 u的所有出边,也就是将u的所有相邻节点的入度减少1。如果某个相邻节点v的入度变为0,那么我们就将v放入队列中

在广度优先搜索的过程结束后。如果答案中包含了这n个节点,那么我们就找到了一种拓扑排序,否则说明图中存在环,也就不存在拓扑排序了

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
31
32
33
34
35
36
37
38
39
40
41
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
//入度 in degree
vector<int> indeg;
vector<vector<int>> edges;
//resize内的默认初始化值为0
indeg.resize(numCourses);
edges.resize(numCourses);
for (const auto& info : prerequisites)
{
//以info[1]为起始的边,指向info[0]
edges[info[1]].push_back(info[0]);
//info[0]的入度加一,指向它的是info[1]
++indeg[info[0]];
}
queue<int> q;
for (int i = 0; i < numCourses; i++)
{
//把最开始入度为0的点push进去
if (indeg[i] == 0)
{
q.push(i);
}
}
int visited = 0;
while (!q.empty())
{
visited++;
int u = q.front();
q.pop();
for (int v : edges[u])
{
--indeg[v];
//如果去掉指向它的u之后,v点的入度变为0,那么push进队列
if (indeg[v] == 0)
{
q.push(v);
}
}
}
return visited == numCourses;
}

8. 字符串转换整数

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 有限自动机,写一个有限自动机类
class Automation{
public:
unordered_map<string, vector<string>> table = {
{"start", {"start", "signed", "in_number", "end"}},
{"signed", {"end", "end", "in_number", "end"}},
{"in_number", {"end", "end", "in_number", "end"}},
{"end", {"end", "end", "end", "end"}}
};
string status = "start";
int get_col(char c)
{
if(c == ' ')
return 0;
if(c == '+' || c == '-')
return 1;
if(isdigit(c))
return 2;
return 3;
}
int sign = 1;
long long res = 0;
void get(char c)
{
status = table[status][get_col(c)];
if(status == "in_number")
{
res = res * 10 + (c - '0');
res = sign == 1 ? min(res, (long long)INT_MAX) : min(res, -(long long)INT_MIN);
}
if(status == "signed")
{
sign = c == '+' ? 1 : -1;
}
}
};

class Solution{
public:
int myAtoi(string str) {
Automation atmn;
for(char c : str)
{
atmn.get(c);
}
return atmn.sign * atmn.res;
}
};