传送门:gym - 102361G
思路分析
取走旗子的方式一定是一条轮廓线,所以直接dp就行了
AC代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (int)(x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const int N = 14;
char s[N][N];
int dp[20000001],w[N][N];
struct line{
int x,y,dir;
}a[N*2];
struct node{
int x,y,type,idx,val;
}tmp[N*2];
signed main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
int n;
cin>>n;
for(int i=1;i<=n;i++) cin>>s[i]+1;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>w[i][j];
}
}
mem(dp,INF);
int st = (1<<n)-1;
dp[st] = 0;
int m = 1<<(n<<1);
m = m-1-st;
int ans = 0;
for(int i=0;i<=m;i++){
if(dp[i]<INF){
ans = dp[i];
int x = 1,y = 1;
for(int j=0, k=i ; j<2*n ; j++,k>>=1){
a[j].dir = k&1;
a[j].x = x;
a[j].y = y;
if(a[j].dir) ++x;
else ++y;
}
bool ok = true;
for(int j=0;j<2*n-1;j++){
if(a[j].dir && !a[j+1].dir){
if(s[a[j].x][a[j].y] == '.'){
dp[i+(1<<j)] = min(dp[i+(1<<j)],dp[i]);
ok = false;
}
}
}
if(!ok) continue;
int tot = 0;
for(int j=0;j<2*n-1;j++){
if(a[j].dir && !a[j+1].dir){
int x = a[j].x;
int y = a[j].y;
tmp[++tot] = {x,y,s[x][y]-'A',j,w[x][y]};
}
}
for(int j=1;j<=tot;j++) dp[i+(1<<tmp[j].idx)] = min(dp[i+(1<<tmp[j].idx)],dp[i]+tmp[j].val);
for(int j = 1;j<=tot;j++){
for(int k=j+1;k<=tot;k++){
if(tmp[j].type!=tmp[k].type){
int nesta = i+(1<<tmp[j].idx)+(1<<tmp[k].idx);
dp[nesta] = min(dp[nesta],dp[i]+abs(tmp[j].val - tmp[k].val));
}
}
}
}
}
cout<<ans<<endl;
return 0;
}