每日一题 No.55 Conscripttion

来源:互联网 发布:淘宝批量设置运费模板 编辑:程序博客网 时间:2024/05/20 20:43

本题要求:

需要招募女兵N人,男兵M人。每征募一个人需要花费10000美元。但是如果已经招募的人中有一些关系亲密的人,那么可以少花一些钱。给出若干的男女之间的1~9999之间的亲密度关系,征募某个人的费用是10000-(已经征募的人中和自己的亲密度的最大值)。要求通过适当的征募顺序使得征募所有人所需费用最小。

输入格式:

第一行输入 N M R(关系数)
接下来R行
每行输入f t c 代表第f号男与第t号女的亲密度为c

输出格式:

输出最小费用

输入样例:

5 5 8
4 3 6831
1 3 4583
0 0 6592
0 1 3063
3 3 4975
1 3 2049
4 2 2104
2 2 781

输出样例:

71071

解题思路 :

使用kruskal算法算法即可

代码 :

#include <iostream>#include <vector>#include <algorithm>using namespace std;  class Edge {    public:        int u;        int v;        int cost;        Edge(int u, int v, int cost) {            this->u = u;            this->v = v;            this->cost = cost;        }        Edge() {        }};using namespace std;  int par[1001];int rank[1001];void init(int n) {    for (int i = 0; i < n; i++) {        par[i] = i;        rank[i] = 0;    }}int find(int x) {    if (par[x] == x) {        return x;    } else {        return par[x] = find(par[x]);    }}void unite(int x, int y) {    x = find(x);    y = find(y);    if (x == y) {        return;    } else if (rank[x] < rank[y]){        par[x] = y;    } else {        par[y] = x;        if (rank[x] == rank[y]) {            rank[x]++;        }    }}bool same(int x, int y) {    return find(x) == find(y); } bool comp(const Edge& e1, const Edge& e2) {    return e1.cost < e2.cost;}vector<Edge> es;int V, E;int kruskal() {    sort(es.begin(), es.end(), comp);    init(V);    int res = 0;    for (int i = 0; i < E; i++) {        Edge e = es[i];        if (!same(e.u, e.v)) {            unite(e.u, e.v);            res += e.cost;        }    }    return res;}int main() {    int N, M, R;    cin >> N >> M >> R;    V = N + M;    E = R;    for (int i = 0; i < R; i++) {        int f, t, c;        cin >> f >> t >> c;        es.push_back(Edge(f, t + N, -c));    }    cout << 10000 * V + kruskal() << endl;    return 0; }
原创粉丝点击