0%

LAB2A

Bug

耗时最长的bug:

  • 产生原因
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    L:Leader F:Follower C:Candidate C:Crash
    s1(L) s2(F) s3(F) // initial
    s1(C) s2(L) s3(F) // s2 send HeartBeat to s1(GoRoutine x1) and s3(GoRoutine x2)
    // but s1 is crash, if we use Lock() and defer Unlock(), x1 will block x2 from Heartbeating until RPC faild(Takes Many times)
    s1(C) <-AppendEntries- s2(L)
    ...long time untile RPC return false
    s3(F) <-AppendEntries- s2(L) // at this moment, s3 has many election timeout
    [Server3:Term1] election timeout, Start an election
    [Server3:Term2] send requestVote to [Sever1]
    [Server3:Term2] send requestVote to [Sever2]
    ...
    [Server3:Term20] election timeout, Start an election
    [Server3:Term21] send requestVote to [Sever1]
    [Server3:Term21] send requestVote to [Sever2]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    func (rf *Raft) BroadcastHeartBeat() {
    BroadCastPrintf("[Server%v:Term%d] BroadCastHeartBeat", rf.me, rf.currentTerm)
    for i := range rf.peers {
    if i == rf.me {
    continue
    }
    go func(server int) {
    // Bug here
    // rf.mu.Lock()
    // defer rf.mu.Unlock()
    args := AppendEntriesArgs{
    Term: rf.currentTerm,
    LeaderId: rf.me,
    }
    var reply AppendEntriesReply
    EntryPrintf("[Server%v:Term%d] send AppendEntries RPC to [Server%d]", rf.me, rf.currentTerm, server)
    if rf.sendAppendEntries(server, &args, &reply) {
    // dosomething
    }
    }(i)
    }
    }

拓扑排序

在无环有向图中,一条有向边s->e可以看作是一种顺序关系(s 大于 e, 或者只有当s发生后e才能发生)。假设是先后发生的约束,求得一个所有节点都发生的序列称作拓扑排序。
搜索这样一种路径我们可以从indegree为0的节点开始。
使用的数据结构

1
2
vector<int> indegree(n)
queue<int> //储存入度为0的节点

喧闹和富有

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
class Solution {
public:
vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
int n = quiet.size();
vector<vector<int>> g(n);
vector<int> indegree(n,0);

vector<int> ans(n,0);
for(int i = 0;i < n;++i) ans[i] = i;

for(auto& r : richer){
g[r[0]].push_back(r[1]);
indegree[r[1]]++;
}
queue<int> q;
for(int i = 0;i < n;++i){
if(!indegree[i])
q.push(i);
}

while(!q.empty()){
int idx = q.front();q.pop();

for(auto& to : g[idx]){
if(quiet[to] > quiet[idx]){
// node idx is quiter than to
ans[to] = ans[idx];
quiet[to] = quiet[idx];
}
indegree[to]--;
if(!indegree[to])
q.push(to);
}
}
return ans;
}
};

在提交记录中看到一个巨牛的写法: 我们是要把最小值往节点的子节点传递,假设有一条路径,开始节点是最小值,我们要把他往后传:

1
a -> b -> c -> ... -> d -> e -> f

第一次扫描所有路径,由于[s,e]不一定按照顺序分布,假设我们传递到c

1
a(min) -> b(min) -> c(min) -> ... -> d -> e ->f

再反过来扫描所有边,也无法传递到整个路径
构造测试用例:[[0,1],[4,5],[3,4],[1,2],[2,3],[6,7],[5,6]]
[4,0,7,3,1,5,6,2]
方法确实错了

欧拉路径

欧拉路径即从某一顶点出发,通过且通过一次所有边的一条路径。如果能够回到出发点,那么称作欧拉回路。

判断欧拉路径

对无向图:

  • 如果所有的顶点度数为偶数 <=> 欧拉通路
  • 如果只有两个顶点度数为奇数 <=> 欧拉路径

对于有向图:

  • 如果所有顶点入度等于出度 <=> 欧拉通路
  • 如果只有两个点入读与出度不等,且差为 1 和 -1 <=> 欧拉路径
找到一欧拉路径

如果存在一个欧拉路径,那么从某一点出发进行dfs,那么:

  • 最终会搜索回到自身
  • 搜索到欧拉路径终点

例如对下面的图:

1
2
3
        -> E -> F
A -> B <-> G
<-> D

可能先搜索到path1: ->E->F, 再搜索到path2: ->G->B->D->B
从B开始的路径就是 B + path2 + path1

如果要保证字典序,那么我们需要从字典序较小的节点进行搜索,最后再将路劲逆序,这样如果存在欧拉终点,欧拉终点是先退出的dfs,之后陆续退出的是字节序较大的点。

1
2
3
dfs(A) -> dfs(B) -> dfs(D) -> dfs(B) -> dfs(E) -> dfs(F) -> return

-> dfs(G) -> dfs(B) -> return

重新安排行程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
sort(tickets.begin(),tickets.end());
reverse(tickets.begin(),tickets.end());
unordered_map<string,vector<string>> g;
for(auto& t:tickets){
g[t[0]].push_back(t[1]);
}
vector<string> ans;
function<void(string)> dfs = [&](string cur){
while(g[cur].size() > 0){
string next = g[cur].back();
g[cur].pop_back();
dfs(next);
}
ans.push_back(cur);
};
dfs("JFK");
reverse(ans.begin(),ans.end());
return ans;
}
};

获得某一范围的最大值

非固定长度(满足一定约束)

摘水果
人固定在startPos,移动距离是k。范围就是 2*x + y <= k, 先朝某一方向走x步,然后再朝另一方向走到startPos后走y步。
可以便利所有的[l,r]的情况,然后二分查找位置,利用前缀和相加。

但是这条约束还可以进一步化简为 r - l + min(r - startPos, startPos - l) <= k
所以可以先找到最右边的l,然后往右走一步:

  • 满足约束,相加
  • 不满足约束,左边前进一步

一些琐碎的细节:

  • 不满足约束时,l最多前进到startPos右边第一个。此时计算距离需要加abs
  • 使用tmp来保存这一”滑动窗口”的值
  • 不满足条件时,l前进一步,r需要固定住
    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
    class Solution {
    public:
    int maxTotalFruits(vector<vector<int>>& fruits, int startPos, int k) {
    int n = fruits.size();
    int l = 0;
    while(l < n && fruits[l][0] + k < startPos) l++;
    int ans = 0;
    int r = l;
    for(;r < n && fruits[r][0] <= startPos;r++)
    ans += fruits[r][1];
    int left_wall = r;
    int tmp = ans;
    for(;r < n && l <= left_wall;r++){
    int cost = fruits[r][0] - fruits[l][0] +
    min(fruits[r][0] - startPos,abs(startPos - fruits[l][0])) ;

    if(cost <= k){
    tmp += fruits[r][1];
    ans = max(ans,tmp);
    }else{
    tmp = tmp - fruits[l][1];
    r--;
    l++;
    }
    }
    return ans;
    }
    };

lambda表达式

从functor开始

C++中functor仿函数就是使用起来向函数的一种对象,通过重载()运算符来实现,例如下面定义的Plus类,每一个实例调用()运算符,返回参数加固定的一个值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
class Plus
{
int value;
public:
Plus(int v):value(v){};
int operator() (int x) const {
return x + value;
}
};
int main(){
Plus plus5(5);
std::cout << plus5(40); //45
}

对于这样的仿函数类,我们只调用了(),此外还需要类中有一个成员变量value,其它的都是语法规范。通过使用lambda表达式,我们可以省略这些繁琐的代码,如下面这段代码,我们只需要一个value,传入参数以及函数体。

1
2
auto plus5 = [value = 5](int x){return x + value;};
std::cout << plus5(40); //45

实际上lambda表达式就类似一个functor,对于上方lambda语句,实际上它等价于:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class __lambda_2_15
{
public:
inline /*constexpr */ int operator()(int x) const
{
return x + value;
}
private:
int value;
public:
__lambda_2_15(const int & _value)
: value{_value}
{}
};
__lambda_2_15 plus5 = __lambda_2_15{5};

一个lambda表达式会创建一个匿名的类(effective c++ 称作闭包类closure class), 等式左边就是lambda创建的运行时对象(或者称作闭包closure), 对象持有数据的拷贝或者引用(当作类成员变量)。使用lambda表达式,就类似于使用一个匿名的functor。 而在functor类中,还可以有函数模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Plus
{
int value;
public:
Plus(int v):value(v){};
template <class T>
T operator() (T x) const {
return x + value;
}
};
int main(){
auto plus1 = Plus(1);
std::cout << plus1(2); //3
std::cout << plus1(3.14); //4.14
}

这个functor就类似于下面这段语句。

1
2
3
auto plus1 = [value = 1](auto x){return x + value;};
std::cout << plus1(2); //3
std::cout << plus1(3.14); //3.14

但是要注意的是,函数模板并不是函数,在传入参数时,编译器会进行类型推导,进而实例化一个函数出来。例如对于plus1(3.14)编译器就会特化一个函数:

1
2
3
4
5
template<>
inline /*constexpr */ double operator()(double x) const
{
return x + static_cast<double>(value);
}

因此对于下面这段代码,运行时实际有两个静态变量,分别在对应的函数中定义。

1
2
3
4
5
6
7
8
9
10
int main(){
auto plus1 = [value = 1](auto x){
static int a = 0;
return x + value + (a++);
};
std::cout << plus1(2)<<std::endl; //3
std::cout << plus1(3.14)<<std::endl; //4.14
std::cout << plus1(3)<<std::endl; //5
std::cout << plus1(1.1)<<std::endl; //3.1
}