您的位置:首页 > 其它

UVA 116 Unidirectional TSP

2015-10-05 20:31 330 查看
题目大意:

见紫书。

解题思路:

简单的搜索,按照步骤去写就行了。

直接上代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=1000;
const int inf =0x3f3f3f3f;
int dp[maxn][maxn];
int mp[maxn][maxn];
int nex[maxn][maxn];
int n,m;

int dfs(int x,int y)
{
int ret;
int k;

if(dp[x][y]!=-1)
{
return dp[x][y];
}

if(y==m)
{
// cout<<mp[x][y]<<endl;
return dp[x][y]=mp[x][y];
}

if(x==1)
{
ret=dfs(x,y+1);
nex[x][y]=x;

if(x+1<=n)
{
k=dfs(x+1,y+1);
if(k<ret)
{
ret=k;
nex[x][y]=x+1;
}
}

k=dfs(n,y+1);
if(k<ret)
{
ret=k;
nex[x][y]=n;
}
}

else if(x==n)
{
ret=dfs(1,y+1);
nex[x][y]=1;

if(x-1>0)
{
k=dfs(x-1,y+1);
if(k<ret)
{
ret=k;
nex[x][y]=x-1;
}
}

k=dfs(x,y+1);
if(k<ret)
{
ret=k;
nex[x][y]=x;
}
}

else
{
ret=dfs(x-1,y+1);
nex[x][y]=x-1;

k=dfs(x,y+1);
if(k<ret)
{
ret=k;
nex[x][y]=x;
}

k=dfs(x+1,y+1);
if(k<ret)
{
ret=k;
nex[x][y]=x+1;
}
}

return dp[x][y]=ret+mp[x][y];

}
int main()
{
while(scanf ("%d %d",&n,&m)!=EOF)
{
for(int i=1 ;i<=n ;i++)
{
for(int j=1 ;j<=m; j++)
{
scanf("%d",&mp[i][j]);
}
}

int ans=inf;
int ret;

memset(dp,-1,sizeof(dp));
for(int i=1;i<=n;i++)
{
int k=dfs(i,1);
if(k<ans)
{
ans=k;
ret=i;
}
}
for(int i=1;i<=m;i++)
{
if(i==1) printf("%d",ret);
else printf(" %d",ret);
ret=nex[ret][i];
}
puts("");
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: