您的位置:首页 > 其它

南阳oj 单词拼接 欧拉回路

2014-05-07 16:37 225 查看
#include<iostream>

#include<cstring>

#include<string>

#include<cstdio>

#include<vector>

#include<queue>

#include<algorithm>

using namespace std;

int Map[27][27];//Map[i][i]表示i到j的个数

vector<string> ans;

priority_queue<string,vector<string>,greater<string> >M[37][27];//二维队列每一个点表示一个优先队列,队列的元素是一个串

void en(int u)

{

int flag=1;

while(flag)

{

int vv;

flag=0;

string str="{";

for(int i=1; i<27; i++)

{

if(Map[u][i])

{

if(str>M[u][i].top())

{

flag=1;

vv=i;

str=M[u][i].top();

}

}

}

if(flag)

{

Map[u][vv]--;

M[u][vv].pop();

//cout << "+++"<< " "<< str<<endl;

en(vv);//先挑出字典序最小的,存放在当前层的str内后,就从队列删除当递归回来时再把当前层的str串存放的vector中

//cout<<"---" << str <<endl;

ans.push_back(str);

}/*tag gaa gkd dfg*/

}//先找到tag再找到gaa递归不执行if和while(),函数返回,回到tag-gaa时,即u=g-96,vv=a-96时把gaa存图,再执行while()找到gkd,找到dfg在存图

}//tag-gaa返回把gaa存图tag-gkd-dfg存dfg再存gkd接着存tag

int st()

{

int chu,ru,start=0,ans=0;

for(int i=1; i<27; i++)

{

chu=0,ru=0;

for(int j=1; j<27; j++)

{

if(Map[i][j]!=0&&start==0)//如果是欧拉回路的话出发点就是字典序最小的

start=i;

chu+=Map[i][j];//i点的出度

ru+=Map[j][i];//i点的入度

}

if(chu!=ru)

{

if(chu>ru)//(前提是图连通)欧拉通路必须是出发点的出度-入度为1,终点的入度-出度为1(aba bab 出度等于入度但图不连通所以要判断ans的大小是否等于n)

ans+=chu-ru;

else//aa bb ab ab ab ba 就不能连通

ans+=ru-chu;

}

if(chu>ru)//如果是欧拉通路(欧拉道路)的话出发点就是出度-入度为1的点

start=i;

}

//cout << ans <<endl;

if(ans>2)

return -1;

return start;

}

int main()

{

int i,n,t,start;

string str;

scanf("%d",&t);

while(t--)

{

memset(Map,0,sizeof(Map));

scanf("%d",&n);

for(i=1; i<27; i++)

for(int j=1; j<27; j++)

while(!M[i][j].empty())

M[i][j].pop();

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

{

cin>>str;

int len=(int)str.size();

Map[str[0]-96][str[len-1]-96]++;

M[str[0]-96][str[len-1]-96].push(str);

}

start=st();

if(start==-1)

{

printf("***\n");

continue;

}

ans.clear();

en(start);

if((int)ans.size()!=n)//abc cba def fed

{

printf("***\n",ans.size());

continue;

}

for(i=ans.size()-1; i>=0; i--)

{

cout<<ans[i];

if(i!=0)

cout<<".";

}

printf("\n");

}

return 0;

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