1. 程式人生 > >URAL1495搜索_背包?

URAL1495搜索_背包?

numbers memset ngs imp and front from clas second

1495. One-two, One-two 2

Time limit: 2.0 second

Memory limit: 64 MB

A year ago the famous gangster Vito Maretti woke up in the morning and realized that he was bored of robbing banks of round sums. And for the last year he has been taking from banks sums that have only digits 1 and 2 in their decimal notation. After each robbery, Vito divides the money between N members of his gang. Your task is to determine the minimal stolen sum which is a multiple of N.

Input
The input contains the number N (1 ≤ N ≤ 106).

Output
Output the minimal number which is a multiple of N and whose decimal notation contains only digits 1 and 2. If it contains more than 30 digits or if there are no such numbers, then output "Impossible".

Samples

input:5

output:
Impossible

Input:8

Output:112

題意

給定一個整數n,求n的倍數sum,要求sum的每一位都是1或者2,sum應是最小的,sum不存在或者位數超過30位時輸出Impossible

解法

一個公式: (a*b)%c = (a%c)*(b%c)%c
bfs搜索,從低位開始搜索,範圍限定在0到 n-1 , 用string記錄每個結果,每個結果對應著一個%n的值,如果這個值=0 那麽這個就是最終結果
一開始竟然從先搜索低位!還調了半天+ + 迷
據說可以用背包的思想解,後續補坑。。。
#include <bits/stdc++.h>
using namespace std;
typedef pair<int
,string>P; const int maxn = 1e6+10; int vis[maxn]; char x[]="012"; int n; string bfs() { queue<P>q; q.push(P(0,"")); while(!q.empty()) { string now = q.front().second; int num = q.front().first; q.pop(); for(int i=1;i<=2;i++) { int mid = (num*10+i)%n; if(mid ==0) return now+x[i]; if(!vis[mid]&&now.size()<30) q.push(P(mid,now+x[i])); vis[mid]=1; } } return " "; } int main() { while(cin>>n){ memset(dp,0,sizeof(dp)); memset(vis,0,sizeof(vis)); string fin=bfs(); if(fin!=" ")cout<<fin<<endl; else cout<<"Impossible"<<endl; } return 0; }

URAL1495搜索_背包?