1456 只会穷举 超时

languagec 2005-04-23 08:36:36
http://acm.zju.edu.cn/show_problem.php?pid=1456

// 超时
// 这种题目不穷举怎么解?

#include <iostream.h>

int stack[100],top;
int temp[100],len=100;
int mincost=100000,cost;
int map[100][100];
int N;
int passed[100];
int tax[100];
int t;

void Memcpy()
{
int i;
for(i=0;i<100;i++)
temp[i]=stack[i];
}

void save_min()
{
if(cost<mincost)
{
mincost=cost;
len=top;
Memcpy();
}
if(cost==mincost)
{
if(len>top)
{
len=top;
Memcpy();
}
}
}

void print(int f)
{
int i;
temp[len++]=t;
cout<<"From "<<f<<" to "<<t<<" :"<<endl;
cout<<"Path: "<<temp[0];//-->5-->4-->3
for(i=1;i<len;i++)
{
cout<<"-->"<<temp[i];
}
cout<<endl;
cout<<"Total cost : "<<mincost<<endl;
cout<<endl;
}


void trv(int cur)
{
int c;
for(c=1;c<=N;c++)
{
if(!passed[c]&&map[cur][c]!=-1)
{
if(c==t)
{
cost=cost+map[cur][c];
save_min();
cost=cost-map[cur][c];
continue;
}

stack[top++]=c;
cost=cost+map[cur][c]+tax[c];
passed[c]=1;
trv(c);
passed[c]=0;
cost=cost-map[cur][c]-tax[c];
top--;
}
}
}


void clear()
{
int i;
for(i=0;i<100;i++)
{
passed[i]=0;
}
cost=0;
mincost=100000;
top=0;
len=100;
}

int main()
{
int i,j,f;
while(cin>>N&&N!=0)
{
for(i=1;i<=N;i++)
for(j=1;j<=N;j++)
cin>>map[i][j];
for(i=1;i<=N;i++)
cin>>tax[i];
while(cin>>f>>t&&(f!=-1&&t!=-1) )
{
clear();
passed[f]=1;
stack[top++]=f;
trv(f);
print(f);
}
}
return 0;
}
...全文
164 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
languagec 2005-04-23
  • 打赏
  • 举报
回复
Posted: Thu Aug 19, 2004 8:44 am Post subject:

--------------------------------------------------------------------------------

ºÜÔç×öµÄ
ÆäʵÏÖÔÚÏëÀ´Ò²²»ÊǺÜÄÑ
¾ÍÊÇÒ»¸ö·¾¶ÅжÏÎÊÌ⣬¸üÐÂʱ¼Ç¼ǰÇý¾Í¿ÉÒÔÁË
Ò»Ö±wa¾ÍÊÇÒòΪ·¾¶ÅжϵÄʱºò´íÁËÒ»¸öµØ·½
a-->b-->c ºÍ a-->b-->d ½´×ϵÄ·¾¶
µ±ÇÒ½öµ±aÏàͬµÄʱºò²ÅÐèÒªÅжϵڶþ¸ö
³ÌÐò×î³õÕâ¸öµØ·½¾Í´íÁË
Ò»Ö±¶¼¼áÐÅÄǸö·¾¶Åжϵĺ¯Êý²»»áÓÐÎÊÌâ
ËùÒÔ²éÁËÒ»¸öÔÂҲû²é³öÀ´ÎÊÌâ

都是这种东西
zhang_jiang 2005-04-23
  • 打赏
  • 举报
回复
在每次计算的时候你都把上次计算的结果都清空了.这里浪费了不少时间.
保留计算结果, 下次还能用到. 这样再试试.
mmmcd 2005-04-23
  • 打赏
  • 举报
回复
http://acm.zju.edu.cn/forum/viewtopic.php?t=4990&highlight=1456
galois_godel 2005-04-23
  • 打赏
  • 举报
回复
就是floyd算法改进下即可
mmmcd 2005-04-23
  • 打赏
  • 举报
回复
IE菜单栏->查看->编码->简体中文

33,029

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧