题解:

(并查集处理往上跳的时候,一定要先让u,v往上跳到并查集的祖先,不然会wa掉)

代码如下:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
const int maxn = 1e5 + ;
typedef long long LL;
int f[maxn], g[maxn], p[maxn], deep[maxn];
LL W[maxn];
int ffind(int x) { return f[x] == x ? f[x] : f[x] = ffind(f[x]); }
int gfind(int x) { return g[x] == x ? g[x] : g[x] = gfind(g[x]); }
struct Line{
int u1, v1, u2, v2;
int cost;
bool operator <(const Line& B) const{
return cost < B.cost;
}
};
vector<int> G[maxn];
vector<Line> V; void dfs(int x, int fa, int d){
deep[x] = d;
p[x] = fa;
for(int i = ; i < G[x].size(); i++){
int to = G[x][i];
if(to == fa) continue;
dfs(to, x, d+);
}
} void Merge(int u, int v, LL w){
u = ffind(u); v = ffind(v);
while(ffind(u) != ffind(v)){
if(deep[u] < deep[v]) swap(u, v);
int fa = ffind(u);
u = p[fa];
f[fa] = ffind(u);
u = ffind(u);
if(gfind(fa) != gfind(u)){
W[gfind(u)] += (W[gfind(fa)] + w);
g[gfind(fa)] = gfind(u);
}
}
} int main()
{
int T, n, m, x, y;
cin>>T;
while(T--){
cin>>n>>m;
memset(W, , sizeof(W));
for(int i = ; i <= n; i++) g[i] = f[i] = i;
for(int i = ; i <= n; i++) G[i].clear();
V.clear();
V.resize(m);
for(int i = ; i < n; i++){
scanf("%d %d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs(, , );
for(int i = ; i < m; i++){
scanf("%d %d %d %d %d", &V[i].u1, &V[i].v1, &V[i].u2, &V[i].v2, &V[i].cost);
}
sort(V.begin(), V.end());
for(int i = ; i < V.size(); i++){
Line line = V[i];
int u = line.u1, v = line.v1, lca1, lca2;
Merge(u, v, line.cost);
lca1 = ffind(u);
u = line.u2, v = line.v2;
Merge(u, v, line.cost);
lca2 = ffind(u);
if(gfind(lca1) != gfind(lca2)) {
W[gfind(lca2)] += (W[gfind(lca1)] + line.cost);
g[gfind(lca1)] = gfind(lca2);
}
}
int num = ;
for(int i = ; i <= n; i++) if(gfind(i) == gfind()) num++;
cout<<num<<" "<<W[gfind()]<<endl;
}
return ;
}

最新文章

  1. Android IPC机制之ContentProvider
  2. nodejs随记01
  3. 转:Google全程面试题目(未完成)
  4. LINQ Operators之过滤(Filtering)
  5. bug报告-常用词汇中英对照表
  6. node.js在windows下的学习笔记(7)---express的app.js的详细配置说明
  7. C#中几种数据库的大数据批量插入
  8. 常用http响应报文分析
  9. UnityShader-菲涅尔反射(Fresnel Reflection)
  10. Linux中oops信息调试【转】
  11. chrome 安装setupvpn 解决chorme未能成功加载扩展程序的问题
  12. Python全栈day9习题
  13. Spring Boot 之整合 EasyUI 打造 Web 应用
  14. 译:Spring Boot 自动伸缩
  15. Windows PowerShell 入門(5)-制御構文
  16. 注解:大话AOP与Android的爱恨情仇
  17. css之hover改变子元素和其他元素样式
  18. MariaDB和mySQL到底区别在哪,实验说明问题!
  19. HDU1575-Tr 【矩阵快速幂】(模板题)
  20. MAMP和WAMP搭建Web环境,数据库,数据分布可视化

热门文章

  1. python核心编程2 第十五章 练习
  2. bootstrap实现分页
  3. vs2017升级、安装
  4. x-pack本地安装方式
  5. .Net 面试题 汇总(三)
  6. shell重温---基础篇(shell数组&amp;数组操作)
  7. ORA-12705: Cannot access NLS data files or invalid
  8. P1991 无线通讯网
  9. Error: Error while compiling statement: FAILED: SemanticException Unable to determine if hdfs://hadoopNode2:8020/user/hive/warehouse/test is encrypted...
  10. Mysql自学笔记