CCF 201412-4 最优灌溉(最小生成树,prime算法,kurskal算法)

xiaoxiao2021-02-28  37

试题编号: 201412-4 试题名称: 最优灌溉 时间限制: 1.0s 内存限制: 256.0MB 问题描述:   雷雷承包了很多片麦田,为了灌溉这些麦田,雷雷在第一个麦田挖了一口很深的水井,所有的麦田都从这口井来引水灌溉。   为了灌溉,雷雷需要建立一些水渠,以连接水井和麦田,雷雷也可以利用部分麦田作为“中转站”,利用水渠连接不同的麦田,这样只要一片麦田能被灌溉,则与其连接的麦田也能被灌溉。   现在雷雷知道哪些麦田之间可以建设水渠和建设每个水渠所需要的费用(注意不是所有麦田之间都可以建立水渠)。请问灌溉所有麦田最少需要多少费用来修建水渠。 输入格式   输入的第一行包含两个正整数n, m,分别表示麦田的片数和雷雷可以建立的水渠的数量。麦田使用1, 2, 3, ……依次标号。   接下来m行,每行包含三个整数ai, bi, ci,表示第ai片麦田与第bi片麦田之间可以建立一条水渠,所需要的费用为ci。 输出格式   输出一行,包含一个整数,表示灌溉所有麦田所需要的最小费用。 样例输入 4 4 1 2 1 2 3 4 2 4 2 3 4 3 样例输出 6 样例说明   建立以下三条水渠:麦田1与麦田2、麦田2与麦田4、麦田4与麦田3。 评测用例规模与约定   前20%的评测用例满足:n≤5。   前40%的评测用例满足:n≤20。   前60%的评测用例满足:n≤100。   所有评测用例都满足:1≤n≤1000,1≤m≤100,000,1≤ci≤10,000。 代码: 1.prime算法

#include<algorithm> #include<cstdio> #include<bits\stdc++.h> using namespace std; const int N = 1005; const int INF = 1e6; int vis[N], g[N][N], n, m, x, y, z,index, total = 0,cost[N]; void prime() { //初始化 vis[1] = 1; for (int i = 1; i <= n; i++) { cost[i] = g[1][i]; } //开始搜索 for (int i = 1; i < n; i++) { int mincost = INF; //找到此点出发最短的边 for (int j = 1; j <= n; j++) { if (!vis[j] && cost[j] < mincost) { mincost = cost[j]; index = j; } } vis[index] = 1; total += mincost; //更新周围点的最小cost for (int j = 1; j <= n; j++) { if (!vis[j] && cost[j] > g[index][j]) { cost[j] = g[index][j]; } } } } int main() { cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { g[i][j] = INF; } } while (m--) { cin >> x >> y >> z; g[x][y] = z; g[y][x] = z; } prime(); cout << total; }

2.kruskal算法

#include<algorithm> #include<cstdio> #include<bits\stdc++.h> using namespace std; const int N = 1005; struct edge { int u, v, cost; bool operator < (const edge& n) const { return cost > n.cost; } }; priority_queue<edge> q; //使用并查集判断当前图是否联通 int id[N], n, m, total = 0; class UF { public: void build() { for (int i = 1; i <= n; i++) { id[i] = i; } } int find(int x) { if (id[x] == x) { return x; } else return find(id[x]); } void connect(int x, int y) { x = find(x); y = find(y); if (x == y) return; else{ id[x] = y; return; } } }; bool cmp(edge x, edge y) { return x.cost<y.cost; } void kruskal() { UF uf; uf.build(); while(!q.empty()) { edge e = q.top(); q.pop(); if (uf.find(e.u) != uf.find(e.v)) { uf.connect(e.u, e.v); total += e.cost; } } } int main() { cin >> n >> m; for (int i = 0; i < m; i++) { edge e; cin >> e.u >> e.v >> e.cost; q.push(e); } kruskal(); cout << total; return 0; }
转载请注明原文地址: https://www.6miu.com/read-2350334.html

最新回复(0)