@(K ACMer) by 题解工厂
题意:
给你一个已有刻度的尺子,求要量出x,y两个长度,最少需要添加多少个刻度.
分析:
显然如果存在的刻度已经可以量出x和y就直接输出0.
这里判断尺子的刻度是否能量出x(y),是非常典型的尺取法,O(n)的时间内解决.
然后就要判断能否只用一个刻度就可以?这里去暴力的搜索是很超时的方法,正确的是用map去查是否直接由目标值….做的时候没有多想能否继续降低复杂度就写了,是极大地错误.
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3fffffff, M = (int)(1e5 + 100);
int main(void)
{
ios::sync_with_stdio(false);
int n, l, x, y;
l1: while (cin >> n >> l >> x >> y) {
set<int> s;
for (int i = 0 ;i < n; i++) {
int c;
cin >> c;
s.insert(c);
}
bool ok1 = false, ok2 = false;
set<int>::iterator i, j, it;
for ( i = s.begin(), j = s.begin();j != s.end();) {
if (*j - *i == x) {ok1 = true; break;}
else if (*j - *i < x) {j++;}
else i++;
}
for ( i = s.begin(), j = s.begin();j != s.end();) {
if (*j - *i == y) {ok2 = true; break;}
else if (*j - *i < y) {j++;}
else i++;
}
if (ok1 && ok2) {cout << 0 << endl; continue;}
else if (ok1) {cout << 1 << endl << y << endl; continue;}
else if (ok2) {cout << 1 << endl << x << endl; continue;}
for (i = s.begin(); i != s.end(); i++) {
int z = *i + x;
if (z <= l) {
if (s.count(z + y) || s.count(z - y)) {
cout << 1 << endl << z << endl;
goto l1;
}
}
z = *i - x;
if (z >= 0) {
if (s.count(z + y) || s.count(z - y)) {
cout << 1 << endl << z << endl;
goto l1;
}
}
z = *i + y;
if (z <= l) {
if (s.count(z + x) || s.count(z - x)) {
cout << 1 << endl << z << endl;
goto l1;
}
}
z = *i - y;
if (z >= 0) {
if (s.count(z + x) || s.count(z - x)) {
cout << 1 << endl << z << endl;
goto l1;
}
}
}
cout << 2 << endl << x << " " << y << endl;
}
return 0;
}