poj 2513 colored sticks

本文探讨了一种结合字典树和并查集的数据结构解决方案,用于解决特定的字符串匹配和连接问题。通过实例讲解,展示了如何利用字典树进行高效字符串查找,并通过并查集判断字符串之间的连通性,最终实现复杂问题的简化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码
#include <iostream>
#include
<stdio.h>
using namespace std;

#define MAX 27
#define S 500003
struct Node
{
int id;
Node
*next[MAX];

};

bool judge_con();
bool judge_fre( );
Node
* InitNode();
int fre[S];
int father[S];
int Insert(Node *,char *);
int getfather(int);

int sum=-1;
int main()
{
for(int i=0;i<S;i++)
father[i]
=i;
int x;
int y;
Node
*head=InitNode();
char a[12];char b[12];

while(cin>>a){ //用while(scanf("%s%s",a,b)!=EOF) 省时间
cin>>b;
x
= Insert(head,a);
y
= Insert(head,b);

father[getfather(x)]
=getfather(y);
fre[x]
++;
fre[y]
++;
}

if(judge_fre()&&judge_con())
cout
<<"Possible";
else cout<<"Impossible";


}


int getfather(int i)
{
if(father[i]!=i)
{
father[i]
=getfather(father[i]);
}

return father[i];
}



int Insert(Node * h,char *p)
{
Node
* tmp;
tmp
=h;
int i=0;
int num;
while(p[i] )
{
num
=p[i]-'a';
if(tmp->next[num]!=NULL)
tmp
=tmp->next[num];
else {
tmp
->next[num]=InitNode();
tmp
=tmp->next[num];
}
i
++;
}
if(tmp->id==-1)
{sum
++; //竟然在这里忘记了括号
tmp->id=sum;
}
return tmp->id;
}
Node
* InitNode()
{
Node
*p=new Node ;
p
->id=-1;
for(int i=0;i<MAX;i++)
p
->next[i]=NULL;
return p;
}

bool judge_fre( )
{
int i=0;int k=0;
for(i=0;i<=sum;i++)
if(fre[i]%2!=0)
k
++;

if(k==0||k==2)
return true;
else return false;
}

bool judge_con()
{
int j=0;
int x=getfather(0);

for( j=0;j<=sum;j++)
if(getfather(j)!=x)
break;
if(j==sum+1)
return true ;
else return false;
}

 

这题 开始 RE 了好多回  后来才发现是数组开小了  才导致指针越界    还是应该仔细看题   S开始弄成了250003

此题做法是 字典树+并查集             就是一个hash映射问题

转载于:https://www.cnblogs.com/anotherday/archive/2010/12/04/1896050.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值