题意:给定 n 个数,问你从有多少下标 i < j,并且 ai + aj 是2的倍数。
析:方法一:
从输入开始暴力,因为 i < j 和 i > j 是一样,所以可以从前面就开始查找,然后计数,用个map就搞定,不过时间有点长,接近两秒。
方法二:
先排序,然后暴力,暴力的原则是找前面的,也是用map查找,时间62ms。
代码如下:
#include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> using namespace std ; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f; const double eps = 1e-8; const int maxn = 1e5 + 5; const int dr[] = {0, 0, -1, 1}; const int dc[] = {-1, 1, 0, 0}; int n, m; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } map<int, int> mp; int main(){ cin >> n; int x; LL ans = 0; for(int i = 0; i < n; ++i){ scanf("%d", &x); for(int j = 1; j < 31; ++j){ ans += mp[(1<<j)-x]; } ++mp[x]; } cout << ans << endl; return 0; }
#include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> using namespace std ; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f; const double eps = 1e-8; const int maxn = 1e5 + 5; const int dr[] = {0, 0, -1, 1}; const int dc[] = {-1, 1, 0, 0}; int n, m; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } map<int, int> mp; int a[maxn]; int main(){ cin >> n; int x; LL ans = 0; for(int i = 0; i < n; ++i){ scanf("%d", &a[i]); } sort(a, a+n); for(int i = 0; i < n; ++i){ for(LL j = 1; j <= 2 * a[i]; j *= 2){//注意是long long if(j <= a[i]) continue; ans += mp[j-a[i]]; } ++mp[a[i]]; } cout << ans << endl; return 0; }
时间: 2024-10-13 19:00:34