类型:枚举
题目:http://acm.hdu.edu.cn/showproblem.php?pid=2847
来源:2009 Multi-University Training Contest 4 - Host by HDU
思路:
(1)一定有解。原因是对于原串s之后连接k的二进制串即是k的倍数
(2)从(n / k + 1) * k 开始枚举,找到满足条件的解即可退出
(3)使用两个下标i, j移动判断当前串是否满足
//hdoj 2847 Binary String
//wa ac 375MS 268K
#include <iostream>
#include <sstream>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define FOR(i,a,b) for(i = (a); i < (b); ++i)
#define FORE(i,a,b) for(i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(i = (a); i > (b); --i)
#define FORDE(i,a,b) for(i = (a); i >= (b); --i)
int k, n, tmp, t, cnt, l, r;
char s[30], endd[30];
int main() {
int i;
while(scanf("%s %d", s, &k) != EOF){
int len = strlen(s);
n = 0;
FOR(i, 0, len)
n = n * 2 + s[i] - '0';
if(n % k == 0) {
printf("%s\n", s);
continue;
}
t = (n / k + 1 ) * k;
while(1){
tmp = t;
cnt = 0;
while(tmp) {
endd[cnt++] = tmp % 2 + '0';
tmp >>= 1;
}
for(l = 0, r = 0; l < len && r < cnt;) {
if(s[l] == endd[cnt - 1 - r])
++l, ++r;
else
++r;
}
if(l >= len)
break;
t += k;
}
FORDE(i, cnt - 1, 0)
printf("%c", endd[i]);
printf("\n");
}
return 0;
}