图论的dfs的题目,帮看下

lingling1989r 2009-05-12 10:47:38
题目:
http://acm-hit.sunner.cn/index.php?option=com_wrapper&Itemid=39

思路仿照下面这个写的
http://hi.baidu.com/novosbirsk/blog/item/a449c0a8506220b7cb130c8a.html

不过,结果总是出问题,帮忙找下吧。。


#include <iostream>

using namespace std;

#define MAX 10005

void swap(int &a,int &b)
{
int c;
c=a;
a=b;
b=c;
}

struct ArcNode//edege of the graphic
{
int to;
int weight;
ArcNode *next;
};


typedef struct VNode//node of the graphic
{
int i;
ArcNode *firstarc;
}nodelist[MAX];

class Gra
{
public:
nodelist vnodelist;//represent the graphic
int degree[MAX];
int maxlen;//the result
int startv;//the start of the route
int visited[MAX];
int max;//the number of the vilige
Gra()
{
memset(visited,0,sizeof(visited));
memset(degree,0,sizeof(degree));
maxlen=0;
startv=0;
}
void add(int x,int y,int w);
void setit();
void dfs(int t,int sum);
void cle();
};

//some pro?if half?
void Gra::add(int x,int y,int w)
{
ArcNode *p1=new ArcNode();
ArcNode *p2=new ArcNode();
p1->to=y;p1->weight=w;p1->next=NULL;
p2->to=x;p2->weight=w;p2->next=NULL;
vnodelist[x].firstarc=p1;
vnodelist[y].firstarc=p2;
degree[x]++;
degree[y]++;
}

void Gra::setit()
{
int i;
for(i=0;i<max;i++)
{
if(degree[i]==1)
break;
}
dfs(i,0);
dfs(startv,0);
cout<<maxlen<<endl;
}

void Gra::dfs(int t,int sum)
{
ArcNode *p;
visited[t]=1;
bool flag=false;

for(p=vnodelist[t].firstarc;p;p=p->next)
{
if(!visited[p->to])
{
flag=true;
dfs(p->to,sum+(p->weight));
}
}
if(!flag)
{
if(sum>maxlen)
{
maxlen=sum;
startv=t;
}
}
}

void Gra::cle()
{
ArcNode *p;
for(int i=0;i<max;i++)
{
visited[i]=0;
degree[i]=0;
for(p=vnodelist[i].firstarc;p;p=p->next)
{
delete p;
}
vnodelist[i].firstarc=NULL;
}
maxlen=0;
startv=0;
}
int main()
{
char va;
int a,b,c;
Gra g;
while(cin>>va)
{
if(va=='*')
{
//initilize the graphic and dfs
g.setit();
g.cle();
continue;
}
a=va-'0';
cin>>b>>c;
if(a>b)
swap(a,b);//besure that a<b
g.max=b>g.max?b:g.max;//record the num of the vilige
g.add(a-1,b-1,c);
}
return 0;
}
...全文
184 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
lingling1989r 2009-05-17
  • 打赏
  • 举报
回复
就把分给顶我贴的人吧。
错还是要自己查才好,写了堆输出语句,找到了部分错误。

邻接矩阵在往里插数据的时候,头插或是尾插没有用好。导致把原来的数据给冲了。
liliangbao 2009-05-12
  • 打赏
  • 举报
回复
帮顶~

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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