图的遍历——DFS
深度优先遍历深度优先遍历,简称DFS,是一种图的遍历方式,特点是不撞南墙不回头
实现代码12345678910111213141516171819void DFSTravel(int numv,vector<vector<int>> const&g,int u){ vector<bool> visited(numv,false); DFS(u,visited,g); //若是连通图,只执行这步 for(int i=0;i<numv;i++) if(!visited[i]) DFS(i,visited,g);}void DFS(int v,vector<bool>& visited,vector<vector<int>> const& g){ visited[v]=true; cout<<v+1<<" "; for(int i=0; ...
1232
畅通工程
问题描述某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
输入要求测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。注意:两个城市之间可以有多条道路相通,也就是说3 31 21 22 1这种输入也是合法的当N为0时,输入结束,该用例不被处理。
输出要求对每个测试用例,在1行里输出最少还需要建设的道路数目。
输入样本4 21 34 33 31 21 32 35 21 23 5999 00
输出样本102998
基本思路一个简单的并查集问题,如果两个可以合并,则计数+1,最后用城镇数目-计数-1(结点数比边数多1),即可得到答案。
实现代码12345678910111213141516171819202122232 ...
1213
How many tables
问题描述Today is Ignatius’ birthday. He invites a lot of friends. Now it’s dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C ...
1198
Farm Irrigation
题目描述Benny has a spacious farm land to irrigate. The farm land is a rectangle, and is divided into a lot of samll squares. Water pipes are placed in these squares. Different square has a different type of pipe. There are 11 types of pipes, which is marked from A to K, as Figure 1 shows.
Benny has a map of his farm, which is an array of marks denoting the distribution of water pipes over the whole farm. For example, if he has a map
ADCFJKIHE
then the water pipes are distributed li ...
1301
Jungle Roads
问题描述The Head Elder of the tropical(热带) island of Lagrishan has a problem. A burst(爆发) of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly(残酷地), so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get ...
最小生成树算法——prim
prim概述prim是基于顶点来求得最小生成树,因而适用于稠密图。
基本思想、维护两个集合VT和ET,ET为所有已确定属于最小生成树的边,VT保存ET的所有边的端点,每一步都将距离VT“最近”但是不属于VT的顶点移入VT。
伪代码12345671 VT←{v},其中v为顶点集V的任意顶点(起始点),ET←∅2 If VT=V,则输出T={VT,ET}, Else2.1 在集合E中选取权值最小的边uv,其中u∈VT,v∈V-VT (如存在多条,选一条即可)2.2 VT←VT∪{v},ET←ET∪{uv};2.3 return step 2
输入样本6 10A B 14A F 13A E 22B F 12B C 21C F 18C D 16D E 20D F 19E F 24
7 11A B 7A D 5B C 8B D 9B E 7C E 5D E 15D F 6E F 8E G 9F G 11
0 0
PS:0 0表示终止输入
输出样本The minimal spanning tree’s ...