RT. 这题我去年 AC 的,现在发现之前的 AC 代码被 hack 了,WA 了一片。。。。。
dfs 做法,有 dalao 能看看哪有问题吗?
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int n,m;
const int inf=0x3f3f3f3f;
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(!isdigit(ch))
{
if(ch=='-')f=-1;
ch=getchar();
}
while(isdigit(ch))
{
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
return x*f;
}
const int maxn=13;
bool vis[maxn][maxn];
int imap[maxn][maxn];
int sd[maxn];//记录从起点到路径开始
int ans=inf;
int tot = 1;
int f[maxn] /*第几个点*/[maxn]/*深度*/[maxn]/*tot*/;
inline void memset()
{
for(int i=0;i<13;i++)
for(int j=0;j<13;j++)imap[i][j]=inf;
}
inline void memset2()
{
for(int j=0;j<13;j++)sd[j]=0;
}
inline int min(int a,int b)
{
return a<b?a:b;
}
void dfs(int x,int step,int cur)
{
if(cur>ans)return;
// cout<<"step: "<<step<<endl;
if(step==n)
{
ans=min(ans,cur);
// cout<<"cur: "<<cur<<endl;
return;
}
for(register int to=1;to<=n;to++)
{
if(!sd[to])// mod zgc
{
for(register int u=1;u<=n;u++)
{
if(imap[u][to]!=inf&&sd[u]!=0)
{
if(f[to][sd[u]+1][tot+1]<cur+sd[u]*imap[u][to])
continue;
if(cur+sd[u]*imap[u][to]>ans)continue;
f[to][sd[u] + 1][tot+1] = cur + sd[u] * imap[u][to];
sd[to]=sd[u]+1;
cur+=sd[u]*imap[u][to];
sd[to]=sd[u]+1;
tot++;
dfs(to,step+1,cur);
tot--;
cur-=sd[u]*imap[u][to];
sd[to]=0;
}
}
}
}
}
void dfs_henman(int x,int step,int cur)
{
if(cur>ans)return;
if(step==n)
{
ans=min(ans,cur);
return;
}
for(register int to=1;to<=n;to++)
{
if(!sd[to])// mod zgc
{
for(register int u=1;u<=n;u++)
{
if(imap[u][to]!=inf&&sd[u]!=0)
{
if(cur+sd[u]*imap[u][to]>ans)continue;
sd[to]=sd[u]+1;
cur+=sd[u]*imap[u][to];
sd[to]=sd[u]+1;
dfs_henman(to,step+1,cur);
cur-=sd[u]*imap[u][to];
sd[to]=0;
}
}
}
}
}
int main()
{
memset();
n=read();
m=read();
int x,y,v;
for(register int i=1;i<=m;i++)
{
x=read();
y=read();
v=read();
imap[x][y]=imap[y][x]=min(imap[x][y],v);
}
if(n>10)
{
for(register int i=1;i<=n;i++)
{
tot = 1;
memset(f, 0x3f, sizeof(f));
sd[i]=1;
dfs(i,1,0);
sd[i]=0;
}
}
if(n<=10)
{
for(register int i=1;i<=n;i++)
{
sd[i]=1;
dfs_henman(i,1,0);
sd[i]=0;
}
}
printf("%d",ans);
return 0;
}