斯坦福 演算法2 第二週作業

2021-09-20 12:48:40 字數 2584 閱讀 4764

來自斯坦福**的algorithms: design and analysis,與目前coursera上的版本內容沒有變化,不過時間安排略有不同。

可以有反例。但我貌似沒咋想出來。錯誤的原因大概是因為用在了有向圖上面。

問題1:用kruskal演算法實現課上講的聚類演算法。

**如下:

#include #include #include #include #include #include #include #include #include #include using namespace std;

#define int_max 2147483647

void readgraph(string filename,vector>& edges,int& size) );

}}class unionfind

; int find(int x) else

return cur; //返回指向負數的結點,也就是根節點

}void union(int a, int b)

counts--;//合併後已有集合數量減一

}int size()

};int clustering(vector> edges, int n, int k) ;

sort(edges.begin(),edges.end(),cmp);//按weight公升序排列各個edge

int i = 0;

for(; i < edges.size() && uf.size() > k; i++)

int res = 0;

for(int j = i; j < edges.size(); j++)

}return res;

}int main()

答案是106。這裡主要注意一下unionfind的實現,用了path compression,leader結點指向的負值表示其集合的rank。

問題2:每個結點是個01表示的字串,結點之間的距離是漢明距離。由於節點數太多不可能對所有的邊進行排序。因此可以針對結點的特點來計算距離。

因為要最終的距離大於等於3,因此可以只合併距離小於3的邊。其實挺好算的,每次改變結點中的某一位或者某兩位就表示距離當前結點距離為1或2的另乙個結點。

坑爹的地方是,這裡讀入的結點居然是有重複的。所以相當於還要考慮距離為0的邊。很生氣,debug很久才發現。我的處理是直接在輸入時候去掉重複的結點。

#include #include #include #include #include #include #include #include #include #include using namespace std;

#define int_max 2147483647

void readgraph(string filename,vector& nodes, unordered_map& mp, int& size, int& length)

size = nodes.size()-1;

}class unionfind

; int find(int x) else

return cur; //返回指向負數的結點,也就是根節點

}void union(int a, int b)

counts--;//合併後已有集合數量減一

}int size()

};int clustering(vectornodes, unordered_map& mp, int n, int length)

if(i % 1000 == 0)

cout << "distance 1: "<< i << " uf.size(): "<< uf.size()<< endl;

}for(int i = 1; i <= n; i++)

cur[k] = ('1'-cur[k])+'0';

}if(i % 1000 == 0)

cout << "distance 2: "<< i << " uf.size(): "<< uf.size()

unordered_mapmp;

int n,length;

readgraph(filename,nodes,mp,n,length);

int res = clustering(nodes,mp,n,length);

cout << res << endl;

return 0;

}

答案是6118.

斯坦福 演算法1 第一周作業

來自斯坦福 的algorithms design and analysis,與目前coursera上的版本內容沒有變化,不過時間安排略有不同。三路歸併排序的複雜度。和兩路沒有啥區別,依然要遞迴log nlogn logn 層,只不過log的底數從2變成3。每一層的計算複雜度依然是o n 根據大o表示...

斯坦福 ios學習 筆記(二)

1.alloc用於記憶體分配,init用於初始化記憶體。2.當我們只是區域性使用數字型別的時候,不要用nsnumber,因為它只是將其傳遞給方法。3.nsninteger和unsigned int是一回事。nsninteger是64位無符號整型。4.作用是讓所以字串為字串物件。5.containso...

斯坦福CS224n課程作業

作業要求如下 解析 題目要求我們證明 softmax 函式具有常數不變性。解答 對於 x c 的每一維來說,有如下等式成立 softmax x c frac c e c frac e e e frac e e e frac e softmax x 則可知 softmax x softmax x c ...