POJ 1258
来源:互联网 发布:如家精选 知乎 编辑:程序博客网 时间:2024/06/02 07:15
Description
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
Solution
题目大意:n个农场都互相联通,需要用光纤将这些农场全部连接起来,且光纤长度最小。
解题思路:最小生成树,输入二维矩阵,代表它们之间的距离。prim模板题
Code
#include <stdio.h>#include <algorithm>#define maxn 1000#define INF 0x3f3f3f3fusing namespace std;int n, m, fa[maxn];bool vis[maxn];int dis[maxn];int mp[maxn][maxn];int prim(int n) { int ans = 0; memset(vis, false, sizeof(vis)); vis[0] = true; for (int i = 0; i < n; i++) dis[i] = mp[0][i]; for (int i = 1; i < n; i++) { int minn = INF; int pos = -1; for (int j = 0; j<n; j++) { if (!vis[j] && minn>dis[j]) { minn= dis[j]; pos= j; } } if (minn == INF) return -1; ans+= minn; vis[pos] = true; for (int j = 0; j< n; j++) { if (!vis[j] && dis[j] > mp[pos][j]) dis[j] = mp[pos][j]; } } return ans;}int main(){ while (~scanf_s("%d",&n)) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf_s("%d", &mp[i][j]); int ans = prim(n); printf("%d\n", ans); } return 0;}
- Poj 1258
- poj 1258
- POJ 1258
- poj 1258
- POJ 1258
- POJ 1258
- poj 1258
- poj 1258
- poj 1258
- POJ 1258
- poj 1258
- poj 1258
- poj 1258
- POJ 1258
- POJ 1258
- POJ 1258
- POJ 1258
- POJ - 1258
- Octave/Matlab 基础
- CodeForces
- eclipse c++11 环境搭建
- Java框架Struts2实现图片上传
- RedHat7安装Systemc 编译仿真
- POJ 1258
- 递归之快速排序
- 模拟继承和多态--C语言模式实现C++继承和多态
- 定时器(setTimeout)的秘密
- poj 2440 DNA 递推在模下存在循环节
- BBB(五):BoneScript编程
- HTML入门笔记23-HTML内嵌视频文件
- selenium使用Xpath+CSS+JavaScript+jQuery的定位方法(治疗selenium各种定位不到,点击不了的并发症)
- Yii2中session写入redis详细教程