思路:
虽然说是很简单,但其实好的代码与一般的代码差别还是很大的。
一般的想法就是两个数组分别sort,然后用两个指针维护结果。
好的想法则是只用一个数组,根据绝对值sort,然后扫一边判断相邻两位的符号是否不同。
这基于一个很简单的贪心思路:选的两个数应尽量小并且接近。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vll;
const int MAXN = 1e6 + 10;
const ll INF = 0x3f3f3f3f;
const ll MOD = 1e9 + 7;
const double eps = 1e-8;
int n, m, k;
vi p;
bool cmp(int a, int b){
return abs(a) < abs(b);
}
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
cout << setprecision(10) << fixed;
int times;
cin >> times;
while(times--){
cin >> n;
p.clear();
p.resize(n);
for(int i = 0; i < n; i++)
cin >> p[i];
sort(p.begin(), p.end(), cmp);
int res = 1;
for(int i = 1; i < n; i++)
if((ll)p[i] * (ll)p[i - 1] < 0)
res++;
cout << res << endl;
}
cerr << "execute time : " << (double)clock() / CLOCKS_PER_SEC << endl;
return 0;
}
未来可期。