POJ-2421-Constructing Roads
链接:https://vjudge.net/problem/POJ-2421#author=tsacm123
题意:
有N个村庄,从1到N,你应该修建一些道路,这样每两个村庄就可以连接起来。我们说两个村庄A和B相连,当且仅当A和B之间有一条路,或者存在一个村庄C使得A和C之间有一条路,并且C和B相连。我们知道一些村庄之间已经有一些道路了,你的工作是修建一些道路,这样所有的村庄都连接起来,所有道路的长度都是最小的。
思路:
最小生成树
代码:
#include <iostream> #include <memory.h> #include <string> #include <istream> #include <sstream> #include <vector> #include <stack> #include <algorithm> #include <map> #include <queue> #include <math.h> using namespace std; typedef long long LL; const int MAXM = 20000+10; const int MAXN = 100+10; struct Path { int _l,_r; double _value; bool operator < (const Path & that)const{ return this->_value < that._value; } }path[MAXM]; int Father[MAXN]; int Get_F(int x) { return Father[x] = (Father[x] == x) ? x : Get_F(Father[x]); } int main() { int n, q; cin >> n; int pos = 0; int len; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { cin >> len; if (i != j) { path[++pos]._l = i; path[pos]._r = j; path[pos]._value = len; } } cin >> q; int l,r; for (int i = 1;i <= q;i++) { cin >> l >> r; path[++pos]._l = l; path[pos]._r = r; path[pos]._value = 0; } for (int i = 1; i <= n; i++) Father[i] = i; sort(path + 1, path + 1 + pos); int sum = 0; for (int i = 1; i <= pos; i++) { int tl = Get_F(path[i]._l); int tr = Get_F(path[i]._r); if (tl != tr) { Father[tl] = tr; sum += path[i]._value; } } cout << sum << endl; return 0; }