CSES - APIO 2007 - Results
Submission details
Task:Mobiles
Sender:ArktinenKarpalo
Submission time:2019-03-07 14:52:07 +0200
Language:C++
Status:COMPILE ERROR

Compiler report

input/code.cpp:1:10: error: #include expects "FILENAME" or <FILENAME>
 #include 3
          ^
input/code.cpp:2:1: error: expected unqualified-id before '<' token
 <bits/stdc++.h>
 ^
input/code.cpp:15:1: error: 'vector' does not name a type
 vector<int> laps[401010], v, v2; // laps
 ^~~~~~
input/code.cpp:16:1: error: 'vector' does not name a type
 vector<int> taso[402020];
 ^~~~~~
input/code.cpp: In function 'void haku(int)':
input/code.cpp:27:2: error: 'v' was not declared in this scope
  v.push_back(s);
  ^
input/code.cpp:28:2: error: 'taso' was not declared in this scope
  taso[lvl[s]].push_back(s);
  ^~~~
input/code.cpp: In function 'void haku2(int)':
input/code.cpp:36:3: error: 'v2' was not declared in this scope
   v2.push_back(lvl[s]);
   ^~
input/code.cpp: In function 'int main()':
input/code.cpp:45:2: error: 'cin' was not declared in this scope
  cin.tie(0);
  ^~~
input/code.cpp:45:2: note: suggested alternative: 'main'
  cin.tie(0);
  ^~~
  main
input/code.cpp:46:2: error: 'co...

Code

#include 3
<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define N (1<<18)
#define M 1000000007
#define P complex<long long>
#define X real()
#define Y imag()

using namespace std;

int n, a, b, par[401010], lvl[401010], cnt=2, rs[401010], l[402020], r[402020], ans;
vector<int> laps[401010], v, v2; // laps
vector<int> taso[402020];

void haku(int s) {
	if(l[s]) {
		lvl[l[s]] = lvl[s]+1;
		haku(l[s]);
	}
	if(r[s]) {
		lvl[r[s]] = lvl[s]+1;
		haku(r[s]);
	}
	v.push_back(s);
	taso[lvl[s]].push_back(s);
}

void haku2(int s) {
	bool ok = false;
	if(l[s]) {
		haku2(l[s]);
	} else {
		v2.push_back(lvl[s]);
		ok = true;
	}
	if(r[s]) {
		haku2(r[s]);
	} else {
	}
}
int main() {
	cin.tie(0);
	cout.tie(0);
	ios_base::sync_with_stdio(0);
	cin >> n;
	rs[1] = 1;
	for(int i=1; i<=n; i++) {
		cin >> a >> b;
		int aS = cnt;
		if(a != -1)
			rs[a] = aS;
		cnt++;
		int bS = cnt;
		if(b != -1)
			rs[b] = bS;
		cnt++;
		l[rs[i]] = aS;
		r[rs[i]] = bS;
		laps[rs[i]].push_back(aS);
		laps[rs[i]].push_back(bS);
	}
	haku(1);
	for(int i=200020; i>=0; i--) {
		for(auto u:taso[i]) {
			if(l[u]) {
				lvl[u] = max(lvl[u], lvl[l[u]]);
			}
			if(r[u]) {
				lvl[u] = max(lvl[u], lvl[r[u]]);
			}
		}
	}
	for(int i=200020; i>=0; i--) {
		for(auto u:taso[i]) {
			if(l[u]) {
				lvl[u] = min(lvl[u], lvl[l[u]]);
			}
			if(r[u]) {
				lvl[u] = min(lvl[u], lvl[r[u]]);
			}
			if(l[u] && r[u]) {
				if(lvl[l[u]] < lvl[r[u]]) {
					ans++;
					swap(r[u], l[u]);
				}
			}
		}
	}
	haku2(1);
	bool ok = false;
	int ed = v2[0];
	for(auto u:v2) {
		if(u != ed) {
			if(ed-u != 1) {
				cout << -1;
				exit(0);
			} else {
				if(ok) {
					cout << -1;
					exit(0);
				} else {
					ok = true;
				}
			}
		}
		ed = u;
	}
	cout << ans << endl;
}