P9914 「RiOI-03」匀速相遇 题解

· · 题解

考虑相遇的条件。

对于第 i 个 \text{A} 类点与第 j 个 \text{B} 类点,先假设这两个点能够相遇,则设他们相遇的时间为 x,由题意可得

\begin{cases} a_i \times x = j \\ b_j \times x = i \end{cases}

整理一下可以得到

\begin{cases} x = \frac{j}{a_i}\\x = \frac{i}{b_j} \end{cases} \therefore \frac{j}{a_i} = \frac{i}{b_j}

十字相乘可得

a_i \times i = b_j \times j

用一个桶记录 a_i \times i,再在 \text{B} 数组中查询即可。

需要注意的是,移速为 0 的点需要额外排除。

AC Code


#include<bits/stdc++.h>
#define ll long long
#define rll register ll
#define F(i,a,b) for(rll i=a;i<=b;i++)
#define Fdn(i,a,b) for(rll i=a;i>=b;i--)
#define int ll

using namespace std;

const int inf = 0x3f3f3f3f,mod = 1e9 + 7; 
const int maxn = 1e6 + 7;

int n, m;
int a[maxn], b[maxn];
int ans;
unordered_map<int , int> mp;

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    F(i, 1, n){
        cin >> a[i], a[i] *= i;
        if(a[i] != 0)
            ++mp[a[i]];
    } 
    F(i, 1, m) {
        cin >> b[i], b[i] *= i;
        if(b[i] != 0)
            ans += mp[b[i]];
    }

    cout << ans << endl;

    return 0;
}```