A - Constructing Roads

本文介绍了一种使用Kruskal算法解决村庄间道路建设问题的方法,目的是通过已有的部分连接,构建一个完整的连通网络,并确保新建道路总长度最短。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.

Input

The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.

Output

You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.

Sample Input

3

0 990 692

990 0 179

692 179 0

1

1 2

Sample Output

179

  • 题意概括  :

N个村庄修路,现已有m个村庄之间修好了路,问要使所有村庄都连通,求需要修路的最小长度。

  • 解题思路  :

输入数据,将图存入一个数组里,然后用Kruskal算法即可。

#include<stdio.h>
#include<string.h>
#include<algorithm>

using namespace std;

int f[110];

struct node
{
	int u,v,w;
}e[10010];

int getf(int x)
{
	if(f[x] != x)
	f[x] = getf(f[x]);
	return f[x];
}
int merge(int x,int y)
{
	int t1,t2;
	t1 = getf(x);
	t2 = getf(y);
	if(t1!= t2)
	{
		f[t2] = t1;
		return 1;
	}
	return 0;
}
int cmp(node x,node y)
{
	return x.w<y.w;
}
int main()
{
	int n,i,j,k,w,m,x,y,sum;
	while(~ scanf("%d",&n))
	{
		for(i = 1;i<=n;i ++)
		{
			f[i] = i;
		}
		k = 0;
		for(i = 1;i<=n;i ++)
		{
			for(j = 1;j<=n;j ++)
			{
				scanf("%d",&w);
				if(j>i)
				{
					e[k].u = i;
					e[k].v = j;
					e[k].w = w;
					k ++;
				}
			}
		}
		sort(e,e+k,cmp);
		scanf("%d",&m);
		for(i = 0;i<m;i ++)
		{
			scanf("%d %d",&x,&y);
			merge(x,y);
		}
		sum = 0;
		for(i = 0;i<k;i ++)
		{
			if(merge(e[i].u,e[i].v))
			{
				sum += e[i].w;
			}
		}
		printf("%d\n",sum);
	}
	return 0;
}

 

### A* Algorithm Road Network Construction in Java The A* (A-star) algorithm is a widely used pathfinding and graph traversal technique that combines the advantages of Dijkstra's algorithm and greedy best-first search. It uses heuristics to guide its search towards the goal, making it more efficient than other algorithms when finding optimal paths. Below is an example implementation of the A* algorithm for constructing or searching through a road network using Java: #### Implementation Details In this code snippet, we define nodes representing intersections on the map with their coordinates. The heuristic function calculates Euclidean distance between two points as an estimate of cost-to-go[^1]. Additionally, edges represent roads connecting these intersections along with associated costs such as travel time or distance. ```java import java.util.*; class Node implements Comparable<Node> { int id; double gCost; // Cost from start node to current node. double hCost; // Heuristic estimated cost from current node to target node. double fCost; // Total cost = gCost + hCost. Node parent; public Node(int id, double gCost, double hCost, Node parent) { this.id = id; this.gCost = gCost; this.hCost = hCost; this.fCost = gCost + hCost; this.parent = parent; } @Override public int compareTo(Node other) { return Double.compare(this.fCost, other.fCost); } } public class AStarAlgorithm { private static final Map<Integer, List<Edge>> adjacencyList = new HashMap<>(); static { initializeGraph(); } private static void initializeGraph() { // Example initialization of a simple graph where each edge has weight/costs. addEdge(0, 1, 5); addEdge(0, 2, 3); addEdge(1, 3, 6); addEdge(2, 1, 2); addEdge(2, 3, 4); addEdge(3, 4, 7); } private static void addEdge(int u, int v, int w) { Edge e = new Edge(v, w); if (!adjacencyList.containsKey(u)) { adjacencyList.put(u, new ArrayList<>()); } adjacencyList.get(u).add(e); // Assuming undirected graph by adding reverse edge too. e = new Edge(u, w); if (!adjacencyList.containsKey(v)) { adjacencyList.put(v, new ArrayList<>()); } adjacencyList.get(v).add(e); } public static List<Integer> findPath(int startId, int endId) { PriorityQueue<Node> openSet = new PriorityQueue<>(); Set<Integer> closedSet = new HashSet<>(); openSet.add(new Node(startId, 0, calculateHeuristic(startId, endId), null)); while (!openSet.isEmpty()) { Node currentNode = openSet.poll(); if (closedSet.contains(currentNode.id)) continue; if (currentNode.id == endId) { return reconstructPath(currentNode); } closedSet.add(currentNode.id); for (Edge neighbor : adjacencyList.getOrDefault(currentNode.id, Collections.emptyList())) { if (closedSet.contains(neighbor.destination)) continue; double tentativeGScore = currentNode.gCost + neighbor.weight; boolean isNewNode = true; Node existingNeighborNode = null; Iterator<Node> iterator = openSet.iterator(); while (iterator.hasNext()) { Node n = iterator.next(); if (n.id == neighbor.destination) { existingNeighborNode = n; break; } } if (existingNeighborNode != null && tentativeGScore >= existingNeighborNode.gCost) continue; double hScore = calculateHeuristic(neighbor.destination, endId); Node newNode = new Node( neighbor.destination, tentativeGScore, hScore, currentNode ); if (isNewNode || tentativeGScore < existingNeighborNode.gCost) { openSet.add(newNode); } } } return null; // No valid path found. } private static double calculateHeuristic(int nodeId, int endNodeId) { // For simplicity assuming precomputed positions here... Point[] points = {new Point(0, 0), new Point(1, 1), new Point(2, 2)}; Point pStart = points[nodeId]; Point pEnd = points[endNodeId]; return Math.sqrt(Math.pow(pStart.x - pEnd.x, 2) + Math.pow(pStart.y - pEnd.y, 2)); } private static List<Integer> reconstructPath(Node node) { List<Integer> path = new LinkedList<>(); while (node != null) { path.add(node.id); node = node.parent; } Collections.reverse(path); return path; } static class Edge { int destination; int weight; public Edge(int dest, int wt) { this.destination = dest; this.weight = wt; } } static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } public static void main(String[] args) { System.out.println(findPath(0, 4)); // Output should be shortest/optimal path based on weights. } } ``` This program demonstrates how you can implement A*, including defining your own data structures like `Node`, `Point` and `Edge`. Note that real-world applications would require much larger datasets describing actual city maps rather than toy examples shown above.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值