您的位置:首页 > 大数据 > 人工智能

hdu 3452 Bonsai(有点纠结的)

2010-07-21 16:59 351 查看
]/*
这个题目怎么说呢?很早以前省赛训练的时候,zhc写过的,但是当时不会DFS
但是这次暑假集训的时候还是不会,悲剧的说,感觉树的DFS 就是很陌生,感觉跟地图的就是不一样
接下来重点DFS 和 DP
通过这个题目对数的DFS 有了稍微的认识
题目描述: 给你一个无向树,每个边都有一个权值,要求删除一些边,保证叶子节点不存在到根节点的路径。
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1005;
const int INF = 0x7f7f7f7f;
int cost

;
int w
;
bool hash
;

struct node
{
struct node *next;
int dis;
int y;
};
node *map
;
void init()
{
for(int i = 0; i < N; i++)
{
map[i] = new node();
map[i]->next = NULL;
}
}
void add(int v, int u, int w)
{
node *p;
p = new node();
p->y = u;
p->dis = w;
p->next = map[v]->next;
map[v]->next = p;
}
void dfs(int ss)//2652832	2010-07-21 16:41:37	Accepted	3452	78MS	9124K	2213 B	C++	悔惜晟
{
node *r;
hash[ss] = true;
int ans = 0;
bool flag = false;
for(r = map[ss]->next; r != NULL; r = r->next)
{
if(!hash[r->y])
{
w[r->y] = r->dis;
flag= true;
dfs( r->y );
ans += w[r->y];
}
}
if(!flag)
return;
w[ss] = min(ans, w[ss]);
}
//别人的dp 代码 Orz
int DFS(int r,  int n)
{
int ans = 0;
bool flag = false;
hash[r] = true;
for(int i = 1; i <= n; i++)
{
if(cost[r][i] != INF && !hash[i])
{
flag = true;
ans += min(DFS(i, n), cost[r][i]);

}
}
if(flag)
return ans;
return INF;

}
void DFS(int root ,int n)
{
bool flag = false;
hash[root] = true;
int ans  = 0;
for(int i = 1; i <= n; i++)
{
if(cost[root][i] < INF && !hash[i])
{
hash[i] = true;
flag = true;
w[i] = cost[root][i];
DFS(i, n);
ans += w[i];
}
}
if(!flag)
return;
w[root] = min(ans, w[root]);

}

int DFS(int r,  int n) //想不明白为何这个是错误的
{
int ans = 0;
bool flag = false;
hash[r] = true;
for(int i = 1; i <= n; i++)
{
if(cost[r][i] != INF && !hash[i])
{
w[i] = cost[r][i];
hash[i] = true;
flag = true;
ans += DFS(i, n);
}
}
if(!flag)
return w[r];
w[r] = min(ans, w[r]);
}
int main()
{
int n, r;
freopen("huixisheng.in", "r", stdin);
while(scanf("%d %d", &n, &r) != EOF && n + r)
{
if(n == 1)
{
puts("0");
continue;
}
memset(hash, false, sizeof(hash));
memset(cost, 0x7f, sizeof(cost));
int v, u, ww;
init();
for(int i = 1; i < n; i++)
{
scanf("%d %d %d", &v, &u, &ww);
add(v, u, ww);
add(u, v, ww);
cost[u][v] = cost[v][u] = ww;
}
w[r] = INF;
// DFS(r,  n);
dfs(r);
printf("%d/n", w[r]);
}
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struct null 2010