初学LCA求助
查看原帖
初学LCA求助
306962
MVP_Harry楼主2020/7/28 13:29

这题不知道错哪儿了,总共WA了4个点,long long该开的也应该都开了。

代码如下(含注释):

#include<bits/stdc++.h>
using namespace std;
#define ll long long

const int maxt = 70;

ll F[maxt + 1];
int Q;

ll find(ll u, ll v) {
	if (u == 1 || v == 1) return 1;
	vector<ll> pre1; vector<ll> pre2; //两个vector分别存储u和v的祖先们
	pre1.pb(u), pre2.pb(v);
	for (int i = maxt; i >= 0; i--) {
		if (u > F[i]) {  //有点像倍增的思想,不停地减去斐波那契数列
			u -= F[i]; pre1.pb(u);
		}
		if (u == 1) break;
		if (v > F[i]) {
			v -= F[i]; pre2.pb(v);
		}
		if (v == 1) break;
	}
	for (int i = 0; i < (int) pre1.size(); i++) { //由于两个vector都是单调递减的,所以用二分查一下
		vector<ll>::iterator it = lower_bound(pre2.begin(), pre2.end(), pre1[i], greater<ll>());
		if (*it == pre1[i]) return *it;
	}
	return 1;
}

int main() {
	ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> Q;
    F[0] = 1, F[1] = 1;
    for (int i = 2; i <= maxt; i++) F[i] = F[i - 1] + F[i - 2]; //斐波那契数列
    while (Q--) { 
    	int u, v;
    	cin >> u >> v;
    	cout << find(u, v) << endl;
    }
	return 0;
}

望大佬指点QwQ

2020/7/28 13:29
加载中...