Kingdom Uva1670 road map

Meaning of the questions:

Given a tree, then lets you add as few edges, so that the entire graph cut edges do not exist.

Ideas:

Look to put up a leaf node directly connected one by one up. This is wrong, because it may fall into a tall tree.
Here Insert Picture Description
FIG red line is connected is wrong, this subtree will fall, and when the parent node is connected to the cutting edge of that cutting edge does not cut the communication. So to the subtree to communicate with the outside, when a method to find a point of greater than 1 as the root, DFS find, every time looking foot leaves 3, the left and right sides together, the rest for the next round intermediate 3 a. 0,1,2 months may end up remaining leaves.
0 leaves without treatment. He took a leaf and root together. It took two leaves together.

// 添加最少边,使得任意删除一条边后图仍然连通 
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
#include <algorithm>
#define fi first
#define se second
#define pii pair<int,int>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
const int maxn = 100000+5;
int n;
vector<int> G[maxn], leaves;
vector<pii> ans;

int dfs(int u, int fa){
	for(int i = 0; i < G[u].size(); ++i){
		if(G[u][i] != fa) dfs(G[u][i], u);
	}
	if(G[u].size() == 1){
		leaves.push_back(u);
		if(leaves.size() == 3){
			int t = leaves[1];
			ans.push_back(make_pair(leaves[0], leaves[2]));
			leaves.clear();
			leaves.push_back(t);
		}
	}
}

int main()
{
	//freopen("in.txt","r",stdin);
	
	while(scanf("%d",&n) == 1&&n){
		for(int i = 1; i <= n; ++i) G[i].clear(); ans.clear(); leaves.clear();
		int root = -1;
		for(int i = 0; i < n-1; ++i){
			int u,v; scanf("%d%d",&u,&v);
			G[u].push_back(v);
			G[v].push_back(u);
			if(G[u].size() > 1) root = u;
			if(G[v].size() > 1) root = v;
		}
		
		if(root != -1) dfs(root , -1);
		
		if(leaves.size() == 2){ ans.push_back(make_pair(leaves[0], leaves[1])); }
		else if(leaves.size() == 1){ ans.push_back(make_pair(leaves[0], root)); }
		printf("%d\n", ans.size());
		
		for(int i = 0; i < ans.size(); ++i){
			printf("%d %d\n", ans[i].fi, ans[i].se);
		}
	}

	return 0;
}


Guess you like

Origin blog.csdn.net/CY05627/article/details/93525039