HDU 4705 - Y
Posted stort
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 4705 - Y相关的知识,希望对你有一定的参考价值。
Y
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 2575 Accepted Submission(s): 723
Problem Description
Sample Input
4
1 2
1 3
1 4
Sample Output
1
题意:
给你一棵树,求三个点不连续的个数
思路:
总的减去,3个在一条路径上的,以中间的数为 根,那么对于这个点就是,(n - his son - his) * his son
AC代码:
1 # include <bits/stdc++.h> 2 #pragma comment(linker, "/STACK:1024000000,1024000000") 3 using namespace std; 4 5 const int MAX = 100010; 6 typedef long long int ll; 7 struct node 8 { 9 int to; 10 int next; 11 }tree[MAX * 2]; 12 int head[MAX], num[MAX]; 13 int tol = 0; 14 int n; 15 ll sum; 16 void add(int a, int b) 17 { 18 tree[tol].to = b; 19 tree[tol].next = head[a]; 20 head[a] = tol++; 21 } 22 23 void dfs(int root, int f) 24 { 25 int tep = 0; 26 for(int i = head[root]; i != -1; i = tree[i].next) 27 { 28 int son = tree[i].to; 29 if(son == f) 30 continue; 31 dfs(son, root); 32 33 num[root] += num[son]; 34 tep += num[son]; 35 sum += (ll) (n - tep - 1) * num[son]; 36 } 37 } 38 39 int main() 40 { 41 while(scanf("%d", &n) != EOF) 42 { 43 tol = 0; 44 sum = 0; 45 memset(head, -1, sizeof(head)); 46 for(int i = 0; i < MAX; i++) 47 num[i] = 1; 48 int a, b; 49 for(int i = 1; i < n; i++) 50 { 51 scanf("%d%d", &a, &b); 52 add(a, b); 53 add(b, a); 54 } 55 dfs(1, -1); 56 ll all = (ll)n * (n - 1) * (n - 2) / 6; 57 58 printf("%I64d\\n", all - sum); 59 } 60 return 0; 61 }
以上是关于HDU 4705 - Y的主要内容,如果未能解决你的问题,请参考以下文章