Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 3819 | Accepted: 1514 |
Description
Input
Output
Sample Input
a b f g a b b f v w x y z v y x v z v w v
Sample Output
abfg abgf agbf gabf wxzvy wzxvy xwzvy xzwvy zwxvy zxwvy
Source
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<queue> #include<map> #include<cmath> #include<algorithm> #define INF 0x3f3f3f3f using namespace std; const int MAXM=1005; int mmax,cur,ecnt,first[27],in[27],h[27],g[27][27]; int num[27],done[27],p[27]; int nex[MAXM],v[MAXM]; map<char,int>mp; map<int,char>bmp; int topsort(int n) { queue<int>q; memset(h,0,sizeof h); memset(num,0,sizeof num); for(int i=1;i<=n;i++) { if(!in[i])q.push(i); if(!in[i]&&first[i]==-1)h[i]=-1;//自由因子层数计零 } int cur=0;mmax=0; while(!q.empty()) { int x=q.front();q.pop(); num[h[x]+1]++; cur++; for(int e=first[x];~e;e=nex[e]) { h[v[e]]=max(h[v[e]],h[x]+1); if(h[v[e]]>mmax)mmax=h[v[e]];//最高层数 if(--in[v[e]]==0)q.push(v[e]); } } return n==cur; } void add_(int a,int b) { v[ecnt]=b; nex[ecnt]=first[a]; first[a]=ecnt++; } void dfs(int sum,int free)//sum为进队字母总数,free为进队自由因子数 { if(sum==cur) { for(int i=1;i<=cur;i++) putchar(bmp[p[i]]); printf("\n"); } for(int i=1;i<=cur;i++) if(!done[i]){ if(h[i]==-1)//自由因子不受层数限制,只要点到,就dfs { done[i]=1; p[sum+1]=i; dfs(sum+1,free+1); done[i]=0; continue; } if(sum-free<num[h[i]])continue;//已进队的非自由因子是否满足输出该层的要求 done[i]=1; p[sum+1]=i; dfs(sum+1,free); done[i]=0; } } int main() { int i,cas=0;char c,cc[1000]; while(gets(cc)) { if(!strlen(cc))continue; if(cas++>0)printf("\n"); mp.clear();bmp.clear(); int t=strlen(cc); vector<char>vec; for(i=0;i<t;i++) if(cc[i]>='a'&&cc[i]<='z')vec.push_back(cc[i]); t=vec.size();cur=0; sort(vec.begin(),vec.end());//将输入数据有序化,方便dfs for(i=0;i<t;i++) mp[vec[i]]=++cur,bmp[cur]=vec[i]; memset(g,0,sizeof g); memset(in,0,sizeof in); memset(first,-1,sizeof first); int x,y,k=1; while((c=getchar())!='\n') { if(c==' ')continue; if(k==1){x=mp[c],k++;continue;} if(k==2)y=mp[c];k=1; if(!g[x][y]&&x&&y) { g[x][y]=1; add_(x,y); in[y]++; } } topsort(cur); num[0]=0; for(i=2;i<=mmax+1;i++)//num[]存的是输出该层的前提(即要想第3层输出就必须输完前两层),层数从零记起 num[i]+=num[i-1]; dfs(0,0); } return 0; }