tom's blog

By tom, history, 5 years ago, In English
int highest(long long n) {
    int r = 0;
    while(n) {
        r++;
        n >>= 1;
    }
    return r-1;
}

int dfs(long long n) {
    if(n == 0) return 0;
    int h = highest(n);
    long long n1 = n-(1LL<<h);
    long long n2 = (1LL<<(h+1))-n;
    int res = 1+dfs(n1);
    if(n2 < n) res = min(res, 1+dfs(n2));
    return res;
}

What is complexity of dfs(n) and why?

 
 
 
 
  • Vote: I like it
  • +4
  • Vote: I do not like it

»
5 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

At most log(n) phase n1 will equal to 0. If (n2&(1LL<<h)) and n2<n then when call DFS(n2),the n2 in that DFS will be equal to n and thus it don't call in further. Else it's similar to n1. Function highest work in log(n). So total complexity is O(log(n)^2). Currently I can't think of any case when DFS(n) produce two small DFS and so on. Correct me if I'm wrong.

»
5 years ago, # |
  Vote: I like it +5 Vote: I do not like it

I thought so, but it's not true. It's probably something like O(2number of blocks with consecutive 1's), but I can't prove it. DFS(n2) will not be called iff n binary representation is 100...0