0%

[題解]樹狀圖分析

a123. 樹狀圖分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(0),cin.tie(0)
#define lld long long
#define N 100005
using namespace std;
int n,father[N],h[N];

vector<int>edge[N];

void dfs(int cur){
int maxn = 0;
for(auto next:edge[cur]){
dfs(next);
maxn = max(maxn,h[next]+1);
}
h[cur] = maxn;
}

signed main(){
ios;
memset(h,0,sizeof(h));
memset(father,0,sizeof(father));

cin>>n;
for(int i=1;i<=n;i++){
int k;cin>>k;
for(int j=0;j<k;j++){
int temp;cin>>temp;
edge[i].push_back(temp);
father[temp] = i;
}
}
int root = 1;
while(father[root]!=0)root++;

dfs(root);

lld ans = 0;
for(int i=1;i<=n;i++)ans += h[i];

cout<<root<<endl<<ans<<endl;
}


//O(N)的作法
#include <bits/stdc++.h>
#define lld long long
using namespace std;
lld n,m;

int main(){
int t;scanf("%d",&t);
while(t--){
int n,m,ans = 1;scanf("%d %d",&n,&m);
m--; //從0開始
for(int i=1;i<n;i++){ //共n-1步要走
if(m&1)ans = ans*2+1; //往右邊走
else ans = ans*2;
m = m>>1; //由低bit到高bit決定每一步要怎麼走
}
printf("%lld\n",ans);
}
}