挺基础挺经典的状压DP,叫TSP来着?
1 //#include<bits/stdc++.h> 2 #include<cstdio> 3 #include<cstring> 4 #include<iostream> 5 #include<queue> 6 #include<algorithm> 7 #define inc(i,l,r) for(int i=l;i<=r;i++) 8 #define dec(i,l,r) for(int i=l;i>=r;i--) 9 #define link(x) for(edge *j=h[x];j;j=j->next) 10 #define mem(a) memset(a,0,sizeof(a)) 11 #define inf 1e9 12 #define ll long long 13 #define succ(x) (1<<x) 14 #define NM 11 15 using namespace std; 16 int read(){ 17 int x=0,f=1;char ch=getchar(); 18 while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} 19 while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); 20 return x*f; 21 } 22 int d[succ(NM)][NM],a[NM][NM],n,m,ans; 23 int main(){ 24 while(n=read()){ 25 mem(d);mem(a);ans=inf;m=succ(n)-1; 26 inc(i,0,n) 27 inc(j,0,n)a[i][j]=read(); 28 inc(k,0,n) 29 inc(i,0,n) 30 inc(j,0,n) 31 a[i][j]=min(a[i][j],a[i][k]+a[k][j]); 32 inc(i,1,m) 33 inc(j,1,n)d[i][j]=inf; 34 inc(i,1,n)d[succ(i-1)][i]=a[0][i]; 35 inc(t,1,m) 36 inc(i,1,n) 37 if(d[t][i]<inf) 38 inc(j,1,n) 39 if(!(t&succ(j-1))) 40 d[t|succ(j-1)][j]=min(d[t|succ(j-1)][j],d[t][i]+a[i][j]); 41 inc(i,1,n) 42 ans=min(ans,d[m][i]+a[i][0]); 43 printf("%d\n",ans); 44 } 45 return 0; 46 }