描述
Robert Prim and Joseph Kruskal have started a traveling band during their sabbatical. They hope to hit it big, but at the moment they’re making even less money than before. This tight budget makes it difficult to plan their debut tour. They’d like to visit every major city in their state and return to the city they started at, but after considering the cost of renting each venue, they’ve discovered that they’ll have to skip one of the cities. As they don’t have an incredibly reliable nor comfortable vehicle to travel in, they’ve decided to exclude the city that will result in the shortest road trip. Since Prim and Kruskal hate cycles, they’ve already narrowed down the roads they plan to use for their trip such that there are no cycles whatsoever, yet they can still reach each city. The question is, what’s the length of their optimal trip?
输入
The first line is the number K of input data sets, followed by the K data sets, each of the following form:
The first line of each data set contains two integers V and E, the number of cities and the number of roads, respectively, where 2 ≤ V ≤ 100 and 1 ≤ E ≤ 100.
This is followed by E lines, each describing a 2-way road. Each line has three integers ai, bi, di where 1 ≤ ai, bi ≤ V are the cities at the endpoints of road i and di is its length. Prim and Kruskal always start at city 1, and there are no cycles in the graph (other than the fact they can repeatedly go back and forth on the same road).
输出
For each data set, output “Data Set x:” on a line by itself, where x is its number. On the next line, output the minimum distance they will travel assuming they skip the correct city, hit every other city, and return to where they began.
样例输入
1
5 4
1 2 3
2 3 7
3 4 3
3 5 4
样例输出
Data Set 1:
26
题意:
给定一张无环(划重点)无向图,求去掉一个点使得从1开始经过除了去掉的点之外所有点并回到1点的最小距离。
思路:
一开始被题目吓坏了,以为是个难题,想了好久。第一次思考无果后,再次读题,看到重点——无环。发现,唉~这表面上是个图其实是棵树,那题目的答案不就是所有树边和的再减去最大叶子节点边最后乘2吗?
再简单分析下:题目给定的是一棵树,要满足祛除一个点并保证遍历所有其他点,那么祛除的点就只能是叶节点,问题得到简化;由于是树那么,从点1到达其他点就只有一条路径,很显然最短的路线就是从父节点出发到达某个子节点,然后再回到父节点,接着在对其他子节点重复这个过程,问题得到大简化;因为去掉的是叶节点,所以它的祛除不会对到达其他点的路径产生影响,所以答案应是(树边和 - 最大叶节点到其父节点的边)*2.
代码(比较菜,写的有点长。。。):
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
struct node
{
int pt,val;
};
vector<node>G[105];
bool vis[105];
int skip,sum;
void dfs(int u)
{
int n,v,f=0;
n=G[u].size();
for(int i=0;i<n;i++)
{
v=G[u][i].pt;
if(vis[v])continue;
vis[v]=true;
f++;
dfs(v);
sum+=2*G[u][i].val;
}
if(!f)
{
skip=max(skip,2*G[u][0].val);
}
return ;
}
int main()
{
int t;
scanf("%d",&t);
for(int no=1;no<=t;no++)
{
int n,m,a,b,v;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)G[i].clear(),vis[i]=0;
while(m--)
{
scanf("%d%d%d",&a,&b,&v);
G[a].push_back({b,v});
G[b].push_back({a,v});
}
vis[1]=true;skip=sum=0;
printf("Data Set %d:\n",no);
dfs(1);
printf("%d\n",sum-skip);
}
}
若有什么错误,欢迎指正^ _ ^ 。