http://acm.hdu.edu.cn/showproblem.php?pid=5524
Subtrees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 184 Accepted Submission(s): 99
Problem Description
There is a complete binary tree with N nodes.The subtree of the node i has Ai nodes.How many distinct numbers are there of Ai?
Input
There are multiple test cases, no more than 1000 cases.
For each case contains a single integer N on a line.(1≤N≤1018)
For each case contains a single integer N on a line.(1≤N≤1018)
Output
The output of each case will be a single integer on a line:the number of subtrees that contain different nodes.
Sample Input
5
6
7
8
Sample Output
3
4
3
5
Source
在Hack的时候截别人的代码, 然而我并不懂什么意思, 但相信自己以后会会的!!!
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> typedef long long ll; using namespace std; ll ans=0 , Max=0, n; void search(ll x) { ll lc=x, rc=x, dep=0; while(lc*2<=n) lc *= 2, dep++; while(rc*2+1<=n) rc = rc*2 + 1; if(lc<=rc) Max = max(Max, dep); else { search(x*2); search(x*2+1); ans++; } } int main() { while(~scanf("%I64d", &n)) { ans = 0; Max = 0; search(1); printf("%I64d ", ans+Max+1); } return 0; }
#include<iostream> #include<stdio.h> #include<algorithm> #include<set> using namespace std; typedef long long ll; set<ll> st; set<ll>::iterator it; void deal(ll n) { ll k, t; if((it=st.find(n)) !=st.end()) return ; st.insert(n); for(k=62; k>=0; k--) { if((1ll<<k)&(n+1))break; } t = n - (1ll<<k) + 1; deal((1ll<<(k-1)) +min(t, 1ll<<(k-1))-1); deal((1ll<<(k-1)) +max(0ll, t-(1ll<<(k-1)))-1); } int main() { ll n; while(~scanf("%I64d", &n)) { st.clear(); st.insert(0); st.insert(1); deal(n); printf("%d ", st.size()-1); } return 0; }