cf886d Restoration of string

明确几点

  1. 假设有串 ab,那么 a 后头必须是 b,b 前头必须是 a,否则就不是最频繁的了。
  2. 不可成环,aba是非法的。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
using namespace std;
int n, len, ru[35], chu[35];
bool edge[35][35], dan[35], vis[35];
char ss[35];
string ans;
bool dfs(int x){
	vis[x] = true;
	ans = ans + char(x+'a');
	for(int i=0; i<26; i++){
		if(edge[x][i]){
			if(vis[i])	return false;
			return dfs(i);
		}
	}
	return true;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		scanf("%s", ss);
		len = strlen(ss);
		if(len==1)	dan[ss[0]-'a'] = true;
		else
			for(int i=0; i<len-1; i++)
				edge[ss[i]-'a'][ss[i+1]-'a'] = true;
	}
	for(int i=0; i<26; i++)
		for(int j=0; j<26; j++)
			if(edge[i][j])
				ru[j]++, chu[i]++;
	for(int i=0; i<26; i++)
		if(ru[i]>1 || chu[i]>1){//忠臣不侍二主,好字符不能同时做另外两个字符的前、后
			printf("NO
");
			return 0;
		}
	ans = "";
	for(int i=0; i<26; i++){
		if(ru[i]==0 && chu[i])
			if(!dfs(i)){
				printf("NO
");
				return 0;
			}
		if(dan[i] && ru[i]==0 && chu[i]==0)//单个字符特判
			ans = ans + (char)(i+'a');
	}
	for(int i=0; i<26; i++)
		if(ru[i] || chu[i])
			if(!vis[i]){
				printf("NO
");
				return 0;
			}
	cout<<ans<<endl;
	return 0;
}
原文地址:https://www.cnblogs.com/poorpool/p/8325334.html