POJ-1985 树的最长路径
来源:互联网 发布:十颗心大数据 编辑:程序博客网 时间:2024/06/05 18:18
紫书上dp写法的代码链接
两次dfs的代码链接
我的垃圾代码,WA
想要两次dfs解决,还加了点没必要dp,搞到最后也不知道什么用例通不过,还是得好好长点姿势才行啊:
#include <cstdio>#include <cstring>#include <vector>#include <queue>#include <iostream>#include <cmath>#include <vector>#include <algorithm>#include <map>using namespace std;#define DEBUGconst int maxn=70000+5,maxv=26,INF=0x3f3f3f3f;struct Edge{ int to; int next; int w;}edge[2 * maxn];int cnt,head[maxn],dp[maxn],p;char c;void add(int u,int v,int w){ edge[cnt].w=w; edge[cnt].to=v; edge[cnt].next=head[u]; head[u]=cnt++;}void dfs(int u,int r){ dp[u]=0; for(int i=head[u];~i;i=edge[i].next){ int t=edge[i].to; if(t==r)continue; dfs(t,u); dp[u]=max(dp[u],dp[t]+edge[i].w); }}void find(int u,int r){ int temp=0; int node=-1; for(int i=head[u];~i;i=edge[i].next){ int t=edge[i].to; if(t==r)continue; if(temp<dp[t]+edge[i].w){ temp=dp[t];node=t; } // if(u==1)printf(" to=%d dp=%d\n",t,dp[t] ); } // printf("%d~~",u ); if(node!=-1)find(node,u); // else p=u; if(p==-1)p=u;}int main(){#ifdef DEBUG freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);#endif int n,m; while(scanf("%d%d\n",&n,&m)&&n!=0){ int a,b,w; cnt=0;p=-1; memset(dp,0,sizeof(dp)); memset(head,-1,sizeof(head)); while(m--){ scanf("%d%d%d %c\n",&a,&b,&w,&c); // printf("%d %d %d %c\n",a,b,w,c); add(a,b,w); add(b,a,w); } dfs(1,-1); find(1,-1); // printf("%d %d\n",p,dp[1]); // for(int i=1;i<=n;i++)printf("---%d %d\n",i,dp[i] ); memset(dp,0,sizeof(dp)); dfs(p,-1); printf("%d\n",dp[p]); }#ifdef DEBUG fclose(stdin); fclose(stdout);#endif return 0;}
阅读全文
0 0
- POJ-1985 树的最长路径
- 二叉树的最长路径
- 二叉树的最长路径
- 二叉树的最长路径
- 二叉树的最长路径
- poj 3018 gift boxes DAG上的最长路径
- poj 3764 最长异或路径(二进制trie树)
- 求树中最长路径 树的直径
- 求一个树的最长路径
- 求树的直径(最长路径)
- hiho 11 树的最长路径
- 二叉树的最长/最短路径
- 树的直径模板~~最长路径
- poj1985Cow Marathon (树的最长路径)
- HNUSTOJ 1444:树的最长路径
- 图的最长路径
- 图的最长路径
- POJ 1985 树的直径(最长链)
- 数据库的几种连接查询
- 前端面试最为经典的问题:输入URL到页面加载完成都发生了什么
- CPU31X-2DP通过DP网络连接远程IO站
- Spring配置和IOC
- MFC菜单的实现
- POJ-1985 树的最长路径
- 10个最佳ES6特性
- Qt Quick元素布局
- Mysql 数据库date, datetime类型设置0000-00-00默认值报错问题
- Python使用seaborn包之路——下载包、更新anaconda3、jupyter notebook切换Python3
- Leetcode-Remove Duplicates from Sorted List-Python
- 输入挂
- CSS3 选择器浏览器兼容性汇总 IE8
- MySQL LOAD DATA INFILE 导入 CSV 格式数据