# [子集DP 斯坦纳树 模板题] HDU 4085 Peach Blossom Spring & BZOJ 4006 [JLOI2015]管道连接

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define cl(x) memset(x,0,sizeof(x))
using namespace std;

inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
}
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=55;

int n,m,h;
int w[N][N];
int vst[N];
int f[1<<11][N],ans[1<<11];

inline bool check(int s){
int ret=0;
for(int i=0;i<h;i++) ret+=(s>>i)&1,ret-=(s>>i+h)&1;
return !ret;
}

int main(){
int Q,iu,iv,iw;;
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
while (Q--){
for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) w[i][j]=1<<27;
for (int i=1;i<=n;i++) w[i][i]=0;
for (int i=0;i<(1<<h+h);i++) for (int j=1;j<=n;j++) f[i][j]=1<<27;
for (int i=0;i<h;i++) f[1<<i][i+1]=f[1<<h+i][n-i]=0;
cl(vst);
for (int i=1;i<(1<<h+h);i++){
for (int j=1;j<=n;j++)
for (int k=(i-1)&i;k;k=(k-1)&i)
f[i][j]=min(f[i][j],f[k][j]+f[i^k][j]);
for (int t=1;t<=n;t++){
int k=0;
for (int j=1;j<=n;j++) if (vst[j]!=i && (!k || f[i][k]>f[i][j])) k=j;
if (t==1) ans[i]=f[i][k];
vst[k]=i;
for (int j=1;j<=n;j++) f[i][j]=min(f[i][j],f[i][k]+w[k][j]);
}
if (check(i))
for (int k=(i-1)&i;k;k=(k-1)&i)
ans[i]=min(ans[i],ans[k]+ans[i^k]);
else
ans[i]=1<<27;
}
if (ans[(1<<h+h)-1]>=1<<27)
printf("No solution\n");
else
printf("%d\n",ans[(1<<h+h)-1]);
}
return 0;
}

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define cl(x) memset(x,0,sizeof(x))
using namespace std;

inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
}
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=1005;
const int M=3005;

struct edge{
int u,v,w; int next;
}G[M<<1];

inline void add(int u,int v,int w,int p){
}

int Q[N*M],l,r;
int ins[N];
#define V G[p].v
inline void SPFA(int n,int *f){
l=r=-1;
for (int i=1;i<=n;i++) Q[++r]=i,ins[i]=1;
while (l<r){
int u=Q[++l]; ins[u]=0;
if (f[V]>f[u]+G[p].w){
f[V]=f[u]+G[p].w;
if (!ins[V]) Q[++r]=V,ins[V]=1;
}
}
}

int n,m,h;
int f[1<<11][N],ans[1<<11];
int x[N],y[N],st[N];

inline bool check(int s){
for (int i=1;i<=10;i++) if ((s&st[i])!=st[i] && (s&st[i])!=0) return 0;
return 1;
}

int main(){
int Q,iu,iv,iw;;
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
for (int i=0;i<(1<<h);i++) for (int j=1;j<=n;j++) f[i][j]=1<<27;
for (int i=1;i<=h;i++) f[1<<(i-1)][x[i]]=0,st[y[i]]|=1<<(i-1);
for (int i=1;i<(1<<h);i++){
if (i==1024)
i=1024;
for (int j=1;j<=n;j++)
for (int k=(i-1)&i;k;k=(k-1)&i)
f[i][j]=min(f[i][j],f[k][j]+f[i^k][j]);
SPFA(n,f[i]);
ans[i]=1<<27;
for (int j=1;j<=n;j++) ans[i]=min(ans[i],f[i][j]);
if (check(i))
for (int k=(i-1)&i;k;k=(k-1)&i)
ans[i]=min(ans[i],ans[k]+ans[i^k]);
else
ans[i]=1<<27;
}
printf("%d\n",ans[(1<<h)-1]);
return 0;
}


©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客