题目大概是这样说的
这道题如果使用位运算爆搜的方法一定会超时。实际上,组成unluck数的只有两个数,使用键值对的方式就能够记录当前的数组中是否出现了与这个数可以组成unlucky数的数字。
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<map>
using namespace std;
int main()
{
#ifdef ON
freopen("sb.txt", "r", stdin);
#endif // !ON
int casenum;
cin >> casenum;
for (int i = 0; i < casenum; i++)
{
int n, T;
cin >> n >> T;
vector<int>nums;
map<int, int>p0, p1;
vector<int>a(n);
for (int k = 0; k < n; k++)
{
int t;
cin >> t;
nums.push_back(t);
}
for (int i = 0; i < nums.size(); i++)
{//
int c = nums[i];
if (p0[T - c] > 0)
{
if (p0[T - c] > p1[T - c])
{
p1[c]++;
a[i] = 1;
}
else
{
p0[c]++;
a[i] = 0;
}
}
else
{
p0[c]++;
a[i] = 0;
}
}
for (int f = 0; f < a.size()-1; f++)
{
cout << a[f] << " ";
}
cout << a[a.size() - 1] << endl;
}
return 0;
}
codeforce的大佬还给出了这样一种更加快速的算法。
这种方法体现了贪心的思想,大于T的数字分到一组,小于T的数字分到一组,等于 T / 2 T/2 T/2的数字单独处理。
#include<bits/stdc++.h>
using namespace std;
#define fo(i,n) for(int i=0; i<n; i++)
#define fo1(i,n) for(int i=1; i<=n; i++)
#define all(c) c.begin(), c.end()
#define tr(container, it) for(typeof(container.begin()) it = container.begin(); it!=container.end(); it++)
#define present(container, element) (container.find(element)!=container.end())
#define pb push_back
typedef vector< int > vi;
typedef long long ll;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
int n, t;
cin >> n >> t;
int a[n];
int prev = 0;
fo(i, n) {
cin >> a[i];
if (t % 2 == 0) {
if (a[i] < t / 2)
cout << "0 ";
else if (a[i] > t / 2)
cout << "1 ";
else if (a[i] == t / 2 && prev == 0) {
cout << "1 ";
prev = 1;
}
else if (a[i] == t / 2 && prev == 1)
{
cout << "0 ";
prev = 0;
}
}
else {
if (a[i] <= t / 2)
cout << "0 ";
else
cout << "1 ";
}
}
cout << endl;
}
}