51nod 1737 配对(树的重心)
来源:互联网 发布:mg汽车 知乎 编辑:程序博客网 时间:2024/06/05 06:31
求出来树的重心,计算重心到每个点的距离加和。
tle了老长时间,把数组开大两倍后,就过了。
一直以为是代码矬,结果是内存开小了。调试期间还搜了别人题解,发现还有更好的做法。
我的:
#include <bits/stdc++.h>using namespace std;template <class T>inline bool scan_d(T &ret){ char c; int sgn; if(c=getchar(),c==EOF) return 0; //EOF while(c!='-'&&(c<'0'||c>'9')) c=getchar(); sgn=(c=='-')?-1:1; ret=(c=='-')?0:(c-'0'); while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0'); ret*=sgn; return 1;}inline void out(long long x){ if(x>9) out(x/10); putchar(x%10+'0');}const int MAXN = 200100;struct Edge{ int to,next,w;} edge[MAXN];int head[MAXN],tot;int son[MAXN],n,root=1,temp;long long res = 0;void addedge(int u, int v, int w){ edge[tot].to = v; edge[tot].w = w; edge[tot].next = head[u]; head[u] = tot++;}void init(){ memset(head, -1, sizeof(head)); tot = 0;}void dfs(int u, int fa){ int v,tmp = 0; son[u] = 1; for(int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if(v == fa) continue; dfs(v,u); son[u] += son[v]; tmp = max(tmp,son[v]); } tmp = max(tmp,n-son[u]); if(tmp < temp) { temp = tmp; root = u; }}void solve(int u, int fa, long long len){ int v; res += len; for(int i = head[u]; i != -1; i = edge[i].next) { v = edge[i].to; if(v == fa) continue; solve(v,u,len+edge[i].w); }}int main(){ scan_d(n); init(); temp = n; int u,v,w; for(int i = 0; i < n-1; ++i) { scan_d(u); scan_d(v); scan_d(w); addedge(u,v,w); addedge(v,u,w); } dfs(1,-1); solve(root,-1,0); out(res); return 0;}
模仿的别人的:
http://www.cnblogs.com/enigma-aw/p/6275197.html
#include <bits/stdc++.h>using namespace std;const int MAXN = 200100;struct Edge{ int to,next,w;};Edge edge[MAXN];int head[MAXN],tot;int son[MAXN];int n;void addedge(int u, int v, int w){ edge[tot].to = v; edge[tot].next = head[u]; edge[tot].w = w; head[u] = tot++;}long long res = 0;void dfs(int u, int fa){ son[u] = 1; int v; for(int i = head[u]; i != -1; i = edge[i].next) { v = edge[i].to; if(v == fa) continue; dfs(v,u); son[u] += son[v]; res += edge[i].w*(long long)min(son[v],n-son[v]); }}int main(){ ios::sync_with_stdio(false); cin >> n; memset(head,-1,sizeof(head)); tot = 0; int u,v,w; for(int i = 0; i < n-1; ++i) { cin >> u >> v >> w; addedge(u,v,w); addedge(v,u,w); } dfs(1,-1); cout << res << endl; return 0;}
阅读全文
0 0
- 51nod 1737 配对【树的重心】
- 51nod 1737 配对 树的重心
- 51nod 1737 配对(树的重心)
- 51NOD算法马拉松21(迎新年) A - 1737 配对(dfs树的重心)
- 51nod 1737 配对 && Codeforces 700B Connecting Universities【树的重心】
- 51nod 1737【树的重心】
- 51nod-1737 配对
- 【51NOD 1737】配对
- 51nod 1737 配对
- 51Nod 1737 配对
- 51Nod-1737-配对
- 51nod 1737 配对(求贡献)
- #bzoj3376#快递配对(树 + 重心)
- 51nod 1737 配对 乱搞
- 51 nod 1737 配对(贡献)
- 51nod 1737 配对 【树形dp】
- 【51NOD 1558】树中的配对
- 51Nod-2006-飞行员配对(二分图最大匹配)
- MySQL的五子句查询和回溯统计
- Java中的几种对象PO、VO、DAO、BO、DTO、POJO解释说明
- [BZOJ4337 BJOI2015 树的同构]树哈希
- 最优二叉检索树
- 递推C 三国役事——巴蜀之危(投信投错)
- 51nod 1737 配对(树的重心)
- 递推D 王小二切饼
- 移动性能测试 Android 获取详细功耗
- FTP与SFTP的区别
- 火星人(Luogu P1088)解题报告
- 1022. D进制的A+B (20)-----Python
- 如何提高c/c++大型项目的软件质量?
- 递推E 母牛的故事
- easyUI整理