题解:UVA11166 带符号二进制 Power Signs
ABC 没写出来 D 题,结束后发现是自己没初始化变量的脑瘫错误后于是愤然写一篇题解。
思路
显然(
即连续的 1 可以转换为 + 接着 0 后再加上一个 -。
于是思路就很明确了,0 的字符数量到
If there are several possible answers, output the one that is lexicographically smallest (by the ASCII ordering).
如果有多种可能的答案,输出字典序最小的那一个(按照 ASCII 排序)。
这说明我们还要考虑字典序。
(在 ASCII 中,+ - 0)
当两个 1 在开头时,可以表示为 110...。
转化,得 ++0...。
替换,得 +0-0...,这样会使字符串长度变长,因此不是最优解。
当两个 1 在中间时,可以表示为 ...0110...。
转化,得 ...0++0...。
替换,得 ...+0-0...,因为 + 0,所以字典序更小。
当两个 1 在末尾时,可以表示为 ...011。
转化,得 ...0++。
替换,得 ...+0-,因为 + 0,所以字典序更小。
综上,当 1 在字符串中间时进行替换,其余情况什么都不做。
注意事项
11011
转换时,应从结尾开始,先转换成:
+++0-
这时如果不考虑 + 连接起来的情况,就会终止,而这不是最优解,可以继续转换为:
+00-0-
(中间多出来一个 0,因为要使前面的权值更大。)
代码
写出来基本逻辑后就在打补丁,代码逻辑差,仅供参考。
#include <cstdio>
char s[50005];
inline void write(int pos, int len) {
s[pos] = '1';
for (int i = 1; i < len; ++i) s[pos + i] = '0';
s[pos + len] = '-';
}
int main() {
for (int i, _1ind; fgets(s + 1, 50005, stdin) && s[1] != '0';) {
for (i = 1; s[i] && s[i] != '\n'; ++i);
for (_1ind = -1, --i, s[0] = '0'; i; --i) {
if (s[i] == '1') {
if (_1ind == -1) _1ind = i;
while (s[i] == '1') --i;
++i;
continue;
}
if (_1ind != -1) {
int _1len = _1ind - i;
if (_1len >= 2) write(i, _1len), _1ind = i;
else _1ind = -1;
}
}
for (_1ind = 1; s[_1ind] == '1'; ++_1ind);
if (--_1ind > 2) write(0, _1ind);
for (int i = 0; s[i]; ++i) if (s[i] == '1') s[i] = '+';
fputs(s[0] == '0' ? s + 1 : s, stdout);
}
}