- 树的并查算法
- 实验六 图的应用 CCF-201709-4 通信网络
一、树的并查算法
使用并查集一般都有优化,合并和压缩,有的合并考虑树的高度,有的合并考虑根结点的权值等等。
在这个例子中,用编号代表每个元素,数组array表示的是父亲的编号,par[x]=x时,x是所在的树的根。
1、ParPtrTree.h
#include
using namespace std;
#ifndef _ParPtrTree
#define _ParPtrTree
namespace wangzhe
{
class ParPtrTree
{
private:
int *array;
int size;
public:
ParPtrTree(int sz);
~ParPtrTree();
int FIND(int curr) const;
void UNION(int a,int b);
bool same(int a,int b);
};
}
#endif
2、ParPtrTree.cpp
#include
using namespace std;
#include"ParPtrTree.h"
namespace wangzhe
{
ParPtrTree::ParPtrTree(int sz)
{
size=sz;
array=new int[sz];
for(int i=0;i
3、main.cpp
#include
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#include"ParPtrTree.h"
using namespace wangzhe;
int main(int argc, char** argv)
{
ParPtrTree *ppt=new ParPtrTree(100);
cout<same(3,1)<FIND(3)<FIND(1)<UNION(3,1);
cout<same(3,1)<FIND(3)<FIND(1)<
4、运行结果

二、实验六 图的应用 CCF-201709-4 通信网络
删除(注释)了部分无用的代码,添加了一些数据成员和方法,此为提交判分的版本,一开始拿了5分,修修改改甚至拿了0分(崩溃)

想了N载春秋,最后在什造大佬的提点下,醍醐灌顶,原来是SetEdge方法添加边时,若两个顶点相同的话,原先的代码会给出提示信息:“Illegal Vertex”。遂将这句提示信息给注释掉再提交,60分,剩下四个样例超时了,应该用邻接表的,但已经满足老师规定的要求了遂不再费时修改。

看来这数据还是有点意思。
满分可以参考以前写的这篇CCF-CSP-201709-4 通信网络
60分超时代码:
//CSDN博客:https://blog.csdn.net/qq_40889820
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include