题意:
computing a max-spacing k-clustering. spacing 是指两个 cluster 之间的最小距离
输入:
[number_of_nodes]
[edge 1 node 1] [edge 1 node 2] [edge 1 cost]
[edge 2
node 1] [edge 2 node 2] [edge 2 cost]
输出:
maximum spacing of a 4-clustering. 将所有的点分到4个非空的 cluster 中, 如何分才能使得 4 个 cluster 之间的距离最大. 使用 max-spacing 4-cluster 算法得到便是这样一个划分方案
思路:
1. 初始时, 每个点都是一个 cluster
2. 将所有的 edge 放入优先队列, 或者放入 vector 并排序
3. 每次取出 cost 最小的一条边, 若边的两个端点已属于同一个 cluster, 则再取下一条, 否则, 合并两个 cluster 成为一个新的 cluster
4. 重复步骤 3 直到只剩下 4 个 cluster
细节:
1. 使用路径压缩的并查集
2. 最后求 maximum spacing of 4-clustering 的时候要保证最小 cost 的那条边属于不同的 cluster
Submit original work, copying violates the class Honor Code
class Edge{ public: int start; int end; int cost; public: Edge(int st, int ed, int cst):start(st),end(ed),cost(cst) {} Edge(){ Edge(0, 0, 0); } bool operator<(const Edge &other) { return (cost < other.cost)? true:false; } bool operator<(const Edge &other) const { return (cost < other.cost)? true:false; } }; int curSize = 0; vector minHeap; const int maxVertex = 500; int numCluster = maxVertex; int cluster[maxVertex+1]; const int K = 4; void init() { for(int i = 1; i <= maxVertex; i ++) { cluster[i] = i; } } int findSet(int vertex) { if(cluster[vertex] != vertex) { cluster[vertex] = findSet(cluster[vertex]); } return cluster[vertex]; } bool mergeSet(int start, int end) { int faStart = findSet(start); int faEnd = findSet(end); if(faStart != faEnd) { cluster[faEnd] = faStart; return true; } return false; } int main() { int start, end, cost; int curVertex = maxVertex; Edge edge; scanf("%d", &start); init(); minHeap.reserve(130000); while(scanf("%d%d%d", &start, &end, &cost)!=EOF) { minHeap.push_back(Edge(start, end, cost)); curSize++; } sort(minHeap.begin(), minHeap.end()); vector::iterator vec_it; for(vec_it = minHeap.begin(); curVertex > K; vec_it++) { if(mergeSet(vec_it->start, vec_it->end)) curVertex--; } vec_it--; // 找到 cluster 之间的最小距离 for(; ;vec_it++) { if(findSet(vec_it->start) != findSet(vec_it->end) ) { cout << (vec_it)->cost <<endl; cout << "sss"<<endl; break; } } return 0; } |
Coursera Algorithm Part II PA2,布布扣,bubuko.com
Coursera Algorithm Part II PA2
原文地址:http://www.cnblogs.com/zhouzhuo/p/3758243.html