赋值了吗?
Time Limit: 1000MS | Memory Limit: 65535KB |
Submissions: 170 | Accepted: 48 |
Sample Input
3 1 a=a 2 b=c c=d 4 b=a c=d d=b e=f
Sample Output
a none a b d 这是一个并查集问题,开始时,只有a有值,当a为某个变量赋值的时候,便将该变量加入到a所在集合中,通过查询父节点便可知该变量是否赋值,有一种情况:b=c c=a这种情况下只有a,c有值,b没有赋值,在将两个节点合并之时,应该先查看右边的变量是否已经赋值,如果没有赋值,便不能将两个节点合并。
#include <stdio.h>
typedef struct
{
int parent;
int rank;
}TreeNode;
void Init(TreeNode *Node, int n)
{
int i;
for (i = 0; i <= 30; i++)
{
Node[i].parent = i;
Node[i].rank = 0;
}
}
int FindSet(TreeNode *Node, int n)
{
if (n != Node[n].parent)
{
return FindSet(Node, Node[n].parent);
}
else
{
return n;
}
}
void Union(TreeNode *Node, int n1, int n2)
{
if (FindSet(Node, n2) != 0)
{
return;
}
n1 = FindSet(Node, n1);
n2 = FindSet(Node, n2);
if (Node[n1].rank > Node[n2].rank)
{
Node[n2].parent = n1;
}
else
{
Node[n1].parent = n2;
if (Node[n1].rank == Node[n2].rank)
{
Node[n2].rank++;
}
}
}
int main()
{
int N;
int n;
TreeNode Node[105];
scanf("%d", &N);
char str[5];
char stra[100];
int t = 1;
while(N--)
{
t = 1;
scanf("%d", &n);
Init(Node, n);
for (int i = 0; i < n; i++)
{
scanf("%s", str);
stra[i] = str[0];
if (str[0] == 'a' || str[2] == 'a')
{
t = 0;
}
Union(Node, str[0] - 'a', str[2] - 'a');
}
int f = 0;
int j;
int q = 0;
for (j = 0 + t; j < 30; j++)
{
if (FindSet(Node, j) == 0)
{
f = 1;
if (q == 0)
{
printf("%c", j + 'a');
q++;
}
else
{
printf(" %c", j + 'a');
q++;
}
}
}
if (f == 0)
{
printf("none\n");
}
else
{
printf("\n");
}
}
return 0;
}
来源:https://www.cnblogs.com/lzmfywz/archive/2013/04/11/3014820.html