数学题: HDU 1271
2 HDU 1271 整数对
题意:http://acm.hdu.edu.cn/showproblem.php?pid=1271
算法:对于输入的数P = pk 10^k + pk-1 10^k-1 + ..+ pt 10 ^ t + ..p1
N1 = ak 10^k + ak-1 10^k-1 + ..+ at 10 ^ t + ..a1
假设去掉第t位:
N2 = ak 10^k-1 + ak-1 10^k-2 + ..+ at-1 10 ^ t-1 + ..a1
N1 + N2 = P
可以得到一系列等式
对于每一位取值,有两种可能,枚举删除第t位的值,最坏情况下时间复杂度2的9次方乘以10
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> using namespace std; int v[20], p[20],num[20],val; int array[200010],id; bool result; void init( ) { v[0] = 1; for(int i = 1; i <= 9; i++) { v[i] = 10 * v[i-1]; } } int get(int N) { int cnt = 0; while( N ) { p[cnt] = N % 10; N /= 10; ++cnt; } return cnt - 1; } void dfs(int now, int bit, int c) { if( now > val ) return; if( now == val ) { if( bit == val ) { num[now] = p[now] - c; if( num[now] <= 0 ) return; } if( p[now] == num[now] + c ) { int sum = 0; for(int j = val; j >= 0; j--) sum += num[j] * v[j]; array[id++] = sum; result = true; return; } } if( now == bit ) { for(int j = 0; j <= 9; j++) { for(int i = 0; i <= 1; i++) { num[now] = j; num[now +1] = p[now] + 10 * i - num[now] - c; if( num[now + 1] < 0 ) continue; if( num[now + 1] >= 10 ) continue; dfs(now + 1, bit, i); } } } else if( now < bit ) { for(int i = 0; i <= 1; ++i) { num[now] = (p[now] + 10 * i - c ) / 2; if( num[now] * 2 != ( p[now] + 10 * i - c) ) continue; if( num[now ] < 0 ) continue; if( num[now] >= 10 ) continue; dfs( now + 1, bit, i); } } else { for(int i = 0; i <= 1; ++i) { num[now + 1] = (p[now] + 10 * i - num[now] - c); if( num[now + 1] < 0 ) continue; if( num[now + 1] >= 10 ) continue; dfs( now + 1, bit, i); } } } void solve(int N ) { result = false; val = get( N ); id = 0; for(int i = 0; i <= val; ++i) { dfs(0, i , 0); //当前位数i,去除第i位,进位 } if ( !result ) puts("No solution."); else { sort(array,array+id); id = unique(array,array + id) - array; printf("%d",array[0]); for(int i = 1; i < id; ++i) printf(" %d",array[i]); puts(""); } } int main( ) { int N; init(); while( scanf("%d",&N),N) { solve( N ); } return 0; }