您的位置:首页 > 其它

Catenyms

2015-06-09 23:47 183 查看

http://poj.org/problem?id=2337

#include<iostream>

#include<cstring>

using namespace std;

struct Edge

{

 int v,next,id;

}edge[1005];

int n,m;

char word[1005][25];

int father[30],stk[1005],in[30],out[30],head[30],ecount,top,s;

bool vis[1005],rep;

int find(int x)

{

 if(father[x]==x)

  return x;

 else

 {

  father[x]=find(father[x]);

  return father[x];

 }

}

void addedge(int a,int b,int c)

{

 edge[ecount].next=head[a];

 edge[ecount].id=c;

 edge[ecount].v=b;

 head[a]=ecount++;

 int temp=head[a];

 while(edge[temp].next!=-1)

 {

  int u=edge[temp].id;

  int v=edge[edge[temp].next].id;

  if(strcmp(word[u],word[v])>0)

  {

   swap(edge[temp].v,edge[edge[temp].next].v);

   swap(edge[temp].id,edge[edge[temp].next].id);

  }

  temp=edge[temp].next;

 }

}

void dfs(int v,int e)

{

 vis[e]=true;

 int i;

 for(i=head[v];i!=-1;i=edge[i].next)

  if(!vis[i])

   dfs(edge[i].v,i);

 stk[top++]=e;

}

void work()

{

 memset(vis,0,sizeof(vis));

 top=0;

 dfs(s,ecount);

}

void merge(int x,int y)

{

 int t1=find(x);

 int t2=find(y);

 if(t1!=t2)

  father[t2]=t1;

}

void input()

{

 int i;

 for(i=0;i<n;i++)

  father[i]=i;

 memset(in,0,sizeof(in));

 memset(out,0,sizeof(out));

 ecount=0;

 memset(head,-1,sizeof(head));

 cin>>m;

 for(i=0;i<m;i++)

 {

  cin>>word[i];

  int a=word[i][0]-'a';

  int b=word[i][strlen(word[i])-1]-'a';

  addedge(a,b,i);

  merge(a,b);

  in[b]++;

  out[a]++;

 }

}

bool ok()

{

 s=0;

 int i,cnt1=0,cnt2=0;

 for(i=0;i<n;i++)

 {

  if(abs(in[i]-out[i])>1)

   return false;

  if(in[i]-out[i]==1)

   cnt1++;

  if(out[i]-in[i]==1)

  {

   s=i;

   cnt2++;

  }

 }

 if(cnt1==0 && cnt2==0)

  rep=true;

 else

  rep=false;

 if(cnt1>1 || cnt2>1 || cnt1!=cnt2)

  return false;

 cnt1=0;

 for(i=0;i<n;i++)

  if(i==father[i] && (in[i] || out[i]))

   cnt1++;

 if(cnt1>1)

  return false;

 bool first=true;

 if(rep)

 {

  for(i=0;i<n;i++)

   if(head[i]!=-1 && (first || strcmp(word[edge[head[s]].id],word[edge[head[i]].id])>0))

   {

    first=false;

    s=i;

   }

 }

 return true;

}

void print()

{

 top--;

 cout<<word[edge[stk[top-1]].id];

 top--;

 while(top>0)

 {

  cout<<"."<<word[edge[stk[top-1]].id];

  top--;

 }

 putchar(10);

}

int main()

{

// freopen("C:\\Users\\John\\Desktop\\hi.txt","r",stdin);

 int t;

 cin>>t;

 while(t--)

 {

  n=26;

  input();

  if(!ok())

  {

   cout<<"***\n";

   continue;

  }

  else

   work();

  print();

 }

 return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: