The fences that surround Farmer Brown's collection of pastures have gotten out of control. They are made up of straight segments from 1 through 200 feet long that join together only at their endpoints though sometimes more than two fences join together at a given endpoint. The result is a web of fences enclosing his pastures. Farmer Brown wants to start to straighten things out. In particular, he wants to know which of the pastures has the smallest perimeter.
Farmer Brown has numbered his fence segments from 1 to N (N = the total number of segments). He knows the following about each fence segment:
- the length of the segment
- the segments which connect to it at one end
- the segments which connect to it at the other end.
Happily, no fence connects to itself.
Given a list of fence segments that represents a set of surrounded pastures, write a program to compute the smallest perimeter of any pasture. As an example, consider a pasture arrangement, with fences numbered 1 to 10 that looks like this one (the numbers are fence ID numbers):
1
+---------------+
|/ /|
2| /7 / |
| / / |
+---+ / |6
| 8 / /10 |
3| /9 / |
| / / |
+-------+-------+
4 5
The pasture with the smallest perimeter is the one that is enclosed by fence segments 2, 7, and 8.
PROGRAM NAME: fence6
INPUT FORMAT
| Line 1: | N (1 <= N <= 100) |
| Line 2..3*N+1: |
N sets of three line records:
|
SAMPLE INPUT (file fence6.in)
10 1 16 2 2 2 7 10 6 2 3 2 2 1 7 8 3 3 3 2 1 8 2 4 4 8 1 3 3 9 10 5 5 8 3 1 9 10 4 6 6 6 1 2 5 1 10 7 5 2 2 1 2 8 9 8 4 2 2 2 3 7 9 9 5 2 3 7 8 4 5 10 10 10 2 3 1 6 4 9 5
OUTPUT FORMAT
The output file should contain a single line with a single integer that represents the shortest surrounded perimeter.
SAMPLE OUTPUT (file fence6.out)
12
解题思路:
这是一道比较典型的深搜题,同样使用状态修改还原的方法来减少空间占用和传入参数,为了防止中间出现循环路,加了个added[]的bool数组
个人觉得我这个side数组还是加得比较独到的,不知道别人能不能看懂我的意思,这个东西加上异或运算就可以省去选择端点的麻烦
最后,简单地分析一下就可以知道其实DFS应该还是有一些重复查找的(就是added数组剪掉的枝 = =|||),不过我交上去一看已经几乎全部0s秒杀了,怎么再把这些废枝利用起来我又暂时没想好,那就这样好了。。。
代码:
本篇介绍了一种算法方案,用于解决寻找由不同长度直线段构成的围栏中,包围牧场的最小周长问题。通过深度优先搜索(DFS)实现状态修改与还原,避免循环路径,并采用异或运算简化端点选择。
1087

被折叠的 条评论
为什么被折叠?



