c++题目_P1546 [USACO3.1] 最短网络 Agri-Net

题目背景

Farmer John 被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。

题目描述

FJ 已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。

你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过 105105。

输入格式

第一行农场的个数 𝑁N(3≤𝑁≤1003≤N≤100)。

接下来是一个 𝑁×𝑁的矩阵,表示每个农场之间的距离。理论上,他们是 𝑁 行,每行由 𝑁 个用空格分隔的数组成,实际上,由于每行 8080 个字符的限制,因此,某些行会紧接着另一些行。当然,对角线将会是 00,因为不会有线路从第 𝑖个农场到它本身。

输出格式

只有一个输出,其中包含连接到每个农场的光纤的最小长度。

输入输出样例

输入 #1复制

复制代码
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

输出 #1复制

复制代码
28

说明/提示

题目翻译来自NOCOW。

USACO Training Section 3.1

这一题我所提供的代码示例基于 Prim 算法的最小生成树解法。

cpp 复制代码
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

int findMinDist(vector<int>& dist, vector<bool>& included, int N) {
    int minDist = INT_MAX;
    int minDistIdx = -1;

    for (int i = 0; i < N; i++) {
        if (!included[i] && dist[i] < minDist) {
            minDist = dist[i];
            minDistIdx = i;
        }
    }

    return minDistIdx;
}

int calculateMinLength(vector<vector<int>>& graph, int N) {
    vector<int> dist(N, INT_MAX);
    vector<bool> included(N, false);

    dist[0] = 0;

    for (int i = 0; i < N - 1; i++) {
        int u = findMinDist(dist, included, N);
        included[u] = true;

        for (int v = 0; v < N; v++) {
            if (graph[u][v] && !included[v] && graph[u][v] < dist[v]) {
                dist[v] = graph[u][v];
            }
        }
    }

    int minLength = 0;
    for (int i = 0; i < N; i++) {
        minLength += dist[i];
    }

    return minLength;
}

int main() {
    int N;
    cin >> N;

    vector<vector<int>> graph(N, vector<int>(N));

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cin >> graph[i][j];
        }
    }

    int minLength = calculateMinLength(graph, N);
    cout << minLength << endl;

    return 0;
}
相关推荐
吴建旭 智宅焕4 小时前
智能家居全国交付中执行端能力跃迁的架构设计:从标准装调到交付专家的系统化路径
网络·网络协议·智能家居
专注仿真4 小时前
知识问答模型用到的算法集详解及代码实例
python·算法·代码·大模型训练·控制算法
罗西的思考5 小时前
【轻量化复刻大模型 / KIMI K3】AttnRes 模块交互式演示
人工智能·算法·机器学习
小七在进步5 小时前
string的使用(1)
c++·visual studio
SomeOtherTime5 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood5 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青6 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
Eyfcom6 小时前
〖全球化架构 05〗跨国网络专线优化:QUIC 协议与 SD-WAN 在跨境传输中的实战
网络·架构·跨境物流快递系统·全球化架构
Dream Cosmos8 小时前
传输层协议之UDP
网络·网络协议·udp
好悬给我拽开线9 小时前
ZILOT 论文解析
算法