白痴做法 : 状态压缩DP
其实直接搜更快
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <utility>
#include <cmath>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 3000;
const int mod = 20100501;
int dp[(1<<17)+10][18][18];
int one[70000];
char s[maxn];
int d[maxn];
int ans[maxn];
int remain[maxn];
int main() {
ios::sync_with_stdio(false);
cin>>s;
int n=strlen(s);
if(n==18)
{
cout<<-1<<endl;
return 0;
}
int i,j,k,t=1<<n,p,r;
for(i=0;i<68000;++i) one[i]=one[i>>1]+(i&1);
for(i=0;i<200;++i) remain[i]=i%17;
for(i=1;i<=n;++i) d[i]=s[i-1]-'0';
memset(dp,-1,sizeof(dp));
dp[0][0][0]=0;
int st=(1<<n);
int mask=(1<<16)-1;
for(j=1;j<=n;++j)
{
for(i=0;i<st;++i)
{
if(one[i>>16]+one[i&mask]!=j-1) continue;
for(k=1;k<=n;++k)
{
t=1<<(k-1);
if(i&t) continue;
for(r=0;r<17;++r)
{
if(dp[i][j-1][r]==-1) continue;
p=remain[r*10+d[k]];
dp[i|t][j][p]=i<<6|r;
}
}
}
}
t=(1<<n)-1;
if(dp[t][n][0]!=-1)
{
int cnt=0;
r=0;
int pre;
int tot=n;
while(n>0)
{
pre=dp[t][n][r]>>6;
pre^=t;
for(i=0;i<tot;++i)
if((1<<i)&pre)
ans[cnt++]=d[i+1];
pre=t;
t=dp[pre][n][r]>>6;
r=dp[pre][n][r]&31;
n--;
}
reverse(ans,ans+cnt);
for(i=0;i<cnt;++i)
{
cout<<ans[i];
}
cout<<endl;
}
else
cout<<-1<<endl;
return 0;
}