Project Euler 107:Minimal network 最小网络

Minimal network

The following undirected network consists of seven vertices and twelve edges with a total weight of 243.

The same network can be represented by the matrix below.

  A B C D E F G
A - 16 12 21 - - -  
B 16 - - 17 20 - -  
C 12 - - 28 - 31 -  
D 21 17 28 - 18 19 23  
E - 20 - 18 - - 11  
F - - 31 19 - - 27  
G - - - 23 11 27 -  

However, it is possible to optimise the network by removing some edges and still ensure that all points on the network remain connected. The network which achieves the maximum saving is shown below. It has a weight of 93, representing a saving of 243 ? 93 = 150 from the original network.

Using network.txt (right click and ‘Save Link/Target As…’), a 6K text file containing a network with forty vertices, and given in matrix form, find the maximum saving which can be achieved by removing redundant edges whilst ensuring that the network remains connected.



最小网络

下面这个无向网络包含有7个顶点和12条边,其总重量为243。

这个网络也可以用矩阵的形式表示如下。

  A B C D E F G
A - 16 12 21 - - -  
B 16 - - 17 20 - -  
C 12 - - 28 - 31 -  
D 21 17 28 - 18 19 23  
E - 20 - 18 - - 11  
F - - 31 19 - - 27  
G - - - 23 11 27 -  

然而,我们其实可以优化这个网络,移除其中的一些边,同时仍然保证每个顶点之间都是连通的。节省重量最多的网络如下图所示,其总重量为93,相比原来的网络节省了243 ? 93 = 150。

在这个6K的文本文件network.txt(右击并选择“目标另存为……”)中存放了一个包含有40个顶点的网络的连通矩阵。移除其中冗余的边,同时仍然保证每个顶点之间都是连通的,求最多能节省的重量。

解题

Prim算法 或者 kruskal 算法

Java

package Level4;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeMap;

public class PE0107{
    static int[][] network = new int[40][40];
    static int len = 40;
    static int AllSum=0;
    static int shortestSum =0;
    public static void run(){
        String filename = "src/Level4/p107_network.txt";
        readData(filename);
        AllSum = getArrSum();
        System.out.println("所有元素的和:"+AllSum);
        shortestSum = Prim();
        System.out.println("最短路径的和:"+shortestSum);
        System.out.println("路径之差:"+ (AllSum - shortestSum));
    }
    public static int Prim(){
        ArrayList<Integer> known = new ArrayList<Integer>();
        ArrayList<Integer> goods = new ArrayList<Integer>();
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        known.add(0);
        map.put(0, 0);
        while(true){
            int min = Integer.MAX_VALUE;
            int index = -1;
            int mapindex = -1;
            for(int i=0;i<known.size();i++){
                for(int j=0;j< len;j++){
                    int now = network[map.get(i)][j];
                    if(now < min && now!=-1 && !known.contains(j)){
                        min = now;
                        index = j;
                        mapindex = known.size();
                    }
                }
            }
            goods.add(min);
            known.add(index);
            map.put(mapindex,index);
            if( known.size() == len)
                break;
        }
        int sum =0;
        for(int i=0;i<goods.size() ;i++){
            sum+=goods.get(i);
        }
        return sum;
    }
    public static int getArrSum(){
        int sum = 0;
        for(int i=0;i<network.length;i++){
            for(int j=i+1;j<network[0].length;j++){
                if(network[i][j]!=-1)
                    sum +=network[i][j];
            }
        }
        return sum;
    }
    public static void StrToArr(int index,String line){
        String[] strArr = line.split(",");

        for(int i=0;i<strArr.length;i++){
            if(!strArr[i].equals("-")){
                network[index][i] = Integer.parseInt(strArr[i]);
            }else{
                network[index][i] = -1;
            }
        }
    }
    public static void readData(String filename){
        BufferedReader bufferedReader;
        int index = 0;
        try {
            bufferedReader = new BufferedReader(new FileReader(filename));
            String line ="";
            try {
                while((line = bufferedReader.readLine())!=null){
                    StrToArr(index,line);
                    index++;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("文件没有数据");
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("没有发现文件");
        }
    }
    public static void main(String[] args){
        long t0 = System.currentTimeMillis();
        run();
        long t1 = System.currentTimeMillis();
        long t = t1 - t0;
        System.out.println("running time="+t/1000+"s"+t%1000+"ms");
    }
}
时间: 2024-08-05 19:32:02

Project Euler 107:Minimal network 最小网络的相关文章

您能找到的最小网络协议实现程序

现实世界中您能找到的最小网络协议实现的程序 1 #!/usr/bin/env python 2 # Simple Gopher Client - Chapter 1 - gopherclient.py 3 #<PYTHON网络编程基础> 第35页 4 5 6 import socket, sys 7 8 port = 70 9 host = sys.argv[1] 10 filename = sys.argv[2] 11 12 s = socket.socket(socket.AF_INET,

Python练习题 037:Project Euler 009:毕达哥拉斯三元组之乘积

本题来自 Project Euler 第9题:https://projecteuler.net/problem=9 # Project Euler: Problem 9: Special Pythagorean triplet # A Pythagorean triplet is a set of three natural numbers, # a < b < c, for which, a**2 + b**2 = c**2 # For example, 3**2 + 4**2 = 9 +

Project Euler 做题记录

Project Euler 太好玩了...(雾 Problem 675 设 \(\omega(n)\) 表示 \(n\) 的质因子个数,\(S(n)=\sum_{d|n}2^{\omega(d)}\),求 \(F(n)=\sum_{i=2}^nS(i!) \bmod (10^9+87)\). \(n=10^7\) solution \(n=\prod_{i=1}^kp_i^{e_i}\) \(S(n)=\prod_{i=1}^k(2e_i+1)\) 线性筛求出每个数的最小质因子之后就可以对 \(

Python练习题 048:Project Euler 021:10000以内所有亲和数之和

本题来自 Project Euler 第21题:https://projecteuler.net/problem=21 ''' Project Euler: Problem 21: Amicable numbers Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b

Python练习题 047:Project Euler 020:阶乘结果各数字之和

本题来自 Project Euler 第20题:https://projecteuler.net/problem=20 ''' Project Euler: Problem 20: Factorial digit sum n! means n × (n ? 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! i

Python练习题 046:Project Euler 019:每月1日是星期天

本题来自 Project Euler 第19题:https://projecteuler.net/problem=19 ''' How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? Answer: 171 ''' from datetime import * firstDay = date(1901,1,1) lastDay = date(

poj Command Network 最小树形图

规定根节点,求一颗生成树使得权值最小,但由于是有向图,所以最小生成树算法失效. 查资料后得知此类问题叫做最小树形图. 解决最小树形图问题的朱刘算法,算法核心基于找 [最小弧集->找环,消环缩点] 的思想,来慢慢构造树形图. 所有的灵魂都在这张图上.0.0 注意缩点后的弧权值的处理 #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algo

Python练习题 035:Project Euler 007:第10001个素数

本题来自 Project Euler 第7题:https://projecteuler.net/problem=7 # Project Euler: Problem 7: 10001st prime # By listing the first six prime numbers: # 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? # Answer

Python练习题 034:Project Euler 006:和平方与平方和之差

本题来自 Project Euler 第6题:https://projecteuler.net/problem=6 # Project Euler: Problem 6: Sum square difference # The sum of the squares of the first ten natural numbers is, # 1**2 + 2**2 + ... + 10**2 = 385 # The square of the sum of the first ten natur