Codeforces 618D Hamiltonian Spanning Tree (DFS)

Source: Internet
Author: User

Topic Link: "Codeforces 618D"

A spanning tree consisting of n nodes and (n-1) edges is given, and the spanning tree is made from the complete graph containing the n nodes, the weights on the top of the spanning tree are X, the weights of the edges in the full graph but not on the spanning tree are Y, and the shortest path to iterate through all the points

Each point in the shortest path has a maximum of two edges, divided into two types of discussion:

1. X<y ==> makes the edges in the shortest path as many as possible in the spanning tree

Define a point as the starting point, Dfs runs one side, the edge of the running edge record node V There are still several sides can be connected (that is, left in the code), and ANS to record the number of edges on the spanning tree

2. X>=y ==> make the edges in the shortest path as many as possible in the spanning tree

When the number of edges on the spanning tree is n-1, there must be 1 edges on the spanning tree, or 0.

#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <
String> #include <vector> using namespace std;
#define LL __int64 int n, x, y;
int ans;
vector<int>vec[200020];
    int dfs (int u, int p) {int left=2;
    	for (int i=0; i<vec[u].size (); i++) {int v = vec[u][i];
    	if (v==p) continue;
    	int x = DFS (v, u);
    		if (left>0 && x==1) {ans++;
    	left--; }} return left>0?
1:0;
	} int main () {cin>>n>>x>>y;
	int u, v;
	ll S1, S2;
		for (int i=0; i<n-1; i++) {cin>>u>>v;
		Vec[u].push_back (v);
	Vec[v].push_back (U);
	} ans=0;
		if (x<y) {DFS (1,-1);
		S1 = (ll) Ans*x + (LL) (n-ans-1) *y;
	cout<<s1<<endl;
				} else {for (int i=1; i<=n; i++) {if ((int) vec[i].size () ==n-1) {Ans=1;
			Break
		}} s2= (LL) Ans*x + (LL) (n-ans-1) *y;
	cout<<s2<<endl; 
} return 0; }



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.