---
# System prepended metadata

title: ZeroJudge f315. 低地距離
tags: [ZeroJudge, APCS, C++]

---

# ZeroJudge f315. 低地距離
[f315. 低地距離 (題目連結)](https://zerojudge.tw/ShowProblem?problemid=f315)

**BFS做法**
<font color="#00CE17">**AC**</font> **(0.7s, 12MB)**
```cpp=
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int N = 1e5 + 5;
int n, k, st[N << 3];
pair<int, int> p[N];

void build(int pos, int x, int v = 1, int l = 0, int r = k - 1){
	if(l == r){
		st[v] = x; return;
	}
	int m = (l + r) >> 1;
	if(pos <= m) build(pos, x, v << 1, l, m);
	else if(pos > m) build(pos, x, v << 1 | 1, m + 1, r);
	st[v] = st[v << 1] + st[v << 1 | 1];
}

int qry(int ql, int qr, int v = 1, int l = 0, int r = k - 1){
	if(ql == l && qr == r) return st[v];
	int m = (l + r) >> 1;
	if(qr <= m) return qry(ql, qr, v << 1, l, m);
	if(ql > m) return qry(ql, qr, v << 1 | 1, m + 1, r);
	return qry(ql, m, v << 1, l, m) + qry(m + 1, qr, v << 1 | 1, m + 1, r);
}

signed main(){
	
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	cin>>n;
	k = n << 1;
	for(int i=1; i<=n; i++){
		p[i].first = -1;
		p[i].second = -1;
	}
	for(int i=0; i<k; i++){
		int x;
		cin>>x;
		if(p[x].first == -1) p[x].first = i;
		else p[x].second = i;
	}
	int ans = 0;
	for(int i=1; i<=n; i++){
		ans += qry(p[i].first, p[i].second);
		build(p[i].first, 1);
		build(p[i].second, 1);
	}
	cout<<'\n'<<ans;
	
	return 0;
}
```
###### 闕以諾 2022/7/6

###### tags: `C++` `ZeroJudge` `APCS`