博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HackerRank "Kundu and Tree" !!
阅读量:4342 次
发布时间:2019-06-07

本文共 1546 字,大约阅读时间需要 5 分钟。

Learnt from here: http://www.cnblogs.com/lautsie/p/3798165.html

Idea is: we union all pure black edges so we get 1+ pure black edge groups. Then we can simply pick only 1 vertex from each pure-black group to form a triangle. Then it will be all combination problem.

Only with some data type tuning to make it pass all tests:

#include 
#include
#include
#include
#include
#include
#include
using namespace std;unordered_map
parent;unordered_map
num;#define M 1000000007int find(int i){ while(i != parent[i]) i = parent[i]; return i; }void merge(int i, int j) // merge j to i{ int pi = find(i); int pj = find(j); if (pi == pj) return; num[pi] += num[pj]; parent[pj] = pi;}int main() { // Get input int n; cin >> n; for (int i = 0; i <= n; i++) { parent[i] = i; num[i] = 1; } // union all black edges for (int i = 0; i < (n-1); i++) { int a, b; cin >> a >> b; char c; cin >> c; if (c == 'b') { merge(a, b); } } // Now we have grouped all connected pure black edges // Idea is, we pick 1 from 1 black set to make sure there's no pure // black edges in one triangle. and we pick three long long p1 = 0; long long p2 = 0; long long p3 = 0; for(int i = 1 ; i <= n; i ++) { if(i == parent[i]) { long long x = num[i]; p1 += x; p2 += (x * x); p3 += (x * x * x); } } long long ret = p1 * p1 * p1 - 3 * p2 * p1 + 2 * p3; cout << ((ret / 6) % M) << endl; return 0;}
View Code

转载于:https://www.cnblogs.com/tonix/p/4996496.html

你可能感兴趣的文章
07 js自定义函数
查看>>
jQueru中数据交换格式XML和JSON对比
查看>>
form表单序列化后的数据转json对象
查看>>
[PYTHON]一个简单的单元測试框架
查看>>
[BZOJ4303]数列
查看>>
一般处理程序在VS2012中打开问题
查看>>
C语言中的++和--
查看>>
thinkphp3.2.3入口文件详解
查看>>
POJ 1141 Brackets Sequence
查看>>
Ubuntu 18.04 root 使用ssh密钥远程登陆
查看>>
Servlet和JSP的异同。
查看>>
虚拟机centOs Linux与Windows之间的文件传输
查看>>
ethereum(以太坊)(二)--合约中属性和行为的访问权限
查看>>
IOS内存管理
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>
Blob(二进制)、byte[]、long、date之间的类型转换
查看>>
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>