集合的定义与查并操作
2017-01-13 15:58
197 查看
用的数据是:
数组下标:0 1 2 3 4 5 6 7 8 9
data: 1 2 3 4 5 6 7 8 9 10
parent: -2 3 0 -2 0 -3 3 5 5 5
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
typedef struct {
int data;/*数组中的值*/
int parent;/*代表当前这个值(data)的根结点上的值(data)的数组下标*/
}SetType;
const int MAX = 10;
int Find(SetType S[],int X)
{
int i = 0;
for(;i < MAX && S[i].data !=X; i++);
for(;S[i].parent >= 0; i = S[i].parent);
return i;
}
void Union(SetType S[],int root1,int root2)
{
if(S[root2].parent < S[root1].parent)
{
S[root2].parent += S[root1].parent;
S[root1].parent = root2;
}
else
{
S[root1].parent += S[root2].parent;
S[root2].parent = root1;
}
}
int main(void)
{
SetType S[10];
int root1,root2;
int parent;
for(int i = 0; i < 10; i++)
{
S[i].data = i+1;
scanf("%d",&parent);
S[i].parent = parent;
}
root1 = Find(S,3);
root2 = Find(S,9);
printf("root1 = %d root2 = %d\n\n",root1,root2);
Union(S,root1,root2);
printf("S[0].parent = %d S[5].parent = %d",S[0].parent,S[5].parent);
return 0;
}
数组下标:0 1 2 3 4 5 6 7 8 9
data: 1 2 3 4 5 6 7 8 9 10
parent: -2 3 0 -2 0 -3 3 5 5 5
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
typedef struct {
int data;/*数组中的值*/
int parent;/*代表当前这个值(data)的根结点上的值(data)的数组下标*/
}SetType;
const int MAX = 10;
int Find(SetType S[],int X)
{
int i = 0;
for(;i < MAX && S[i].data !=X; i++);
for(;S[i].parent >= 0; i = S[i].parent);
return i;
}
void Union(SetType S[],int root1,int root2)
{
if(S[root2].parent < S[root1].parent)
{
S[root2].parent += S[root1].parent;
S[root1].parent = root2;
}
else
{
S[root1].parent += S[root2].parent;
S[root2].parent = root1;
}
}
int main(void)
{
SetType S[10];
int root1,root2;
int parent;
for(int i = 0; i < 10; i++)
{
S[i].data = i+1;
scanf("%d",&parent);
S[i].parent = parent;
}
root1 = Find(S,3);
root2 = Find(S,9);
printf("root1 = %d root2 = %d\n\n",root1,root2);
Union(S,root1,root2);
printf("S[0].parent = %d S[5].parent = %d",S[0].parent,S[5].parent);
return 0;
}
相关文章推荐
- Java集合工具类(三)-泛型集合工具类,用于便捷快速的定义、操作集合。包含Set的交集、并集...
- Java集合工具类(一)-泛型集合工具类,用于便捷快速的定义、操作集合。包含Set的交集、并集...
- Java集合工具类(二)-泛型集合工具类,用于便捷快速的定义、操作集合。包含Set的交集、并集...
- SQL Server实用操作小技巧集合
- Sql Server实用操作小技巧集合(收集)
- Sql Server实用操作小技巧集合
- Sql Server实用操作小技巧集合
- Sql Server实用操作小技巧集合(转载)
- Sql Server实用操作小技巧集合
- Sql Server实用操作小技巧集合
- Sql Server实用操作小技巧集合
- Sql Server实用操作小技巧集合
- 解决: 集合已修改,枚举操作可能不会执行问题
- Sql Server实用操作小技巧集合
- 如何进行定义特性(Attribute),并且在程序中如何检索定义的特性,可以根据用户定义的不同特性进行不同的操作。
- 在ASP中用集合成批操作数据库 (转)
- 在ASP中用集合成批操作数据库
- 二叉树的集合操作
- SQL Server实用操作小技巧集合
- Server实用操作小技巧集合