| Task: | Tree matching |
| Sender: | HopeICanCode |
| Submission time: | 2016-09-25 22:25:12 +0300 |
| Language: | C++ |
| Status: | READY |
| Result: | ACCEPTED |
| test | verdict | time | |
|---|---|---|---|
| #1 | ACCEPTED | 0.06 s | details |
| #2 | ACCEPTED | 0.37 s | details |
| #3 | ACCEPTED | 0.37 s | details |
| #4 | ACCEPTED | 0.37 s | details |
| #5 | ACCEPTED | 0.39 s | details |
| #6 | ACCEPTED | 0.37 s | details |
| #7 | ACCEPTED | 0.38 s | details |
Code
#include <bits/stdc++.h>
#define UNVISITED -1
#define MOD 1000000007
#define _ ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0), cout.precision(15);
using namespace std;
typedef long long int64;
typedef pair<int, int> ii;
vector< ii > children;
vector< vector<int> > memo;
int64 solve(int root, int match){
int left = children[root].first, right = children[root].second;
if(left == 0 && right == 0) return 1;
if(memo[root][match] != -1) return memo[root][match];
int64 ans = 0;
if(left != 0 && right != 0){
ans = solve(left, false) * solve(right, false);
if(match == false){
ans %= MOD;
ans += solve(left, true) * solve(right, false);
ans %= MOD;
ans += solve(left, false) * solve(right, true);
}
} else if(left != 0){
ans = solve(left, false);
if(match == false) ans %= MOD, ans += solve(left, true);
} else if(right != 0){
ans = solve(right, false);
if(match == false) ans %= MOD, ans += solve(right, true);
}
ans %= MOD;
return memo[root][match] = ans;
}
int main(){ _
int n; cin >> n;
children.assign(n+1, ii(0, 0));
memo.assign(n+1, vector<int> (2, -1));
for(int i = 1; i <= n; ++i)
cin >> children[i].first >> children[i].second;
// if(n == 1) cout << 1 << endl;
// else {
solve(1, false); solve(1, true);
cout << memo[1][0]<< endl;
// }
// for(int i = 1; i <= n; ++i)
// cout << i << ": " << memo[i][false] << endl;
return 0;
}
Test details
Test 1
Verdict: ACCEPTED
| input |
|---|
| 7 5 6 0 0 4 0 2 0 ... |
| correct output |
|---|
| 19 |
| user output |
|---|
| 19 |
Test 2
Verdict: ACCEPTED
| input |
|---|
| 1000000 406968 281253 108264 0 0 0 0 0 ... |
| correct output |
|---|
| 159944844 |
| user output |
|---|
| 159944844 |
Test 3
Verdict: ACCEPTED
| input |
|---|
| 1000000 1000000 325587 791377 324030 873422 0 0 0 ... |
| correct output |
|---|
| 114625606 |
| user output |
|---|
| 114625606 |
Test 4
Verdict: ACCEPTED
| input |
|---|
| 1000000 495129 959931 0 703069 862854 0 0 423221 ... |
| correct output |
|---|
| 922109659 |
| user output |
|---|
| 922109659 |
Test 5
Verdict: ACCEPTED
| input |
|---|
| 1000000 667150 768657 0 528730 716704 103616 554625 0 ... |
| correct output |
|---|
| 331516797 |
| user output |
|---|
| 331516797 |
Test 6
Verdict: ACCEPTED
| input |
|---|
| 1000000 490726 891332 0 988621 0 469251 224815 393797 ... |
| correct output |
|---|
| 831971669 |
| user output |
|---|
| 831971669 |
Test 7
Verdict: ACCEPTED
| input |
|---|
| 1000000 554662 668 0 0 0 0 0 806138 ... |
| correct output |
|---|
| 593438800 |
| user output |
|---|
| 593438800 |
