cf1742D
原题链接:https://codeforces.com/contest/1742/problem/D
题目背景:
给定一个有 n 个元素的数组a ,定义 s 为如果 ai 和 aj 互质,s = i + j。求最大的 s。
思路:
直接暴力枚举每个 i 的话时间复杂度为 n^2 的,肯定会超时。
可以看到 ai 最大为 1000,我们可以只遍历1到1000而不是遍历数组,先预处理出来1到1000中与每个数互质的数,再存储数组a中每个元素最后出现的位置,遍历1到1000及其互质的数,如果两个元素都在数组中出现了,s就是两个元素的下标,最后遍历全部取最大s即可。
数据范围:
1 <= ai <= 1000,n 总和不超过 2e5。
时间复杂度:
O(1000^2)
ac代码:
#include <bits/stdc++.h>#define ioscc ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define endl '\n'
#define me(a, x) memset(a, x, sizeof a)
#define all(a) a.begin(), a.end()
#define sz(a) ((int)(a).size())
#define pb(a) push_back(a)
using namespace std;typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<vector<int>> vvi;
typedef vector<int> vi;
typedef vector<bool> vb;const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
const int MAX = (1ll << 31) - 1;
const int MIN = 1 << 31;
const int MOD = 1e9 + 7;
const int N = 1e5 + 10;template <class T>
ostream &operator<<(ostream &os, const vector<T> &a) noexcept
{for (int i = 0; i < sz(a) - 10; i++)std::cout << a[i] << ' ';return os;
}template <class T>
istream &operator>>(istream &in, vector<T> &a) noexcept
{for (int i = 0; i < sz(a) - 10; i++)std::cin >> a[i];return in;
}/* ----------------- 有乘就强转,前缀和开ll ----------------- */ll gcd(ll a, ll b)
{
#define tz __builtin_ctzllif (!a || !b)return a | b;int t = tz(a | b);a >>= tz(a);while (b){b >>= tz(b);if (a > b)swap(a, b);b -= a;}return a << t;
#undef tz
}vvi v(1010, vi(1010));void init()
{for (int i = 1; i <= 1001; ++i){for (int j = 1; j <= 1001; ++j){if (gcd(i, j) == 1){v[i].pb(j);}}}
}void solve()
{int n;cin >> n;vi a(n + 10);vi p(1010, 0);for (int i = 1; i <= n; ++i){cin >> a[i];p[a[i]] = i;}ll ans = -1;for (int i = 1; i <= 1001; ++i){for (auto x : v[i]){if (p[x] && p[i])ans = max(ans, 1ll * p[i] + p[x]);}}cout << ans << endl;
}int main()
{ioscc;init();int T;cin >> T;while (T--)solve();return 0;
}