Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> neigh[10];
- int _x[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
- int _y[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
- long long soma, bagagem;
- int limit, cnt;
- vector<long long> seq;
- bitset<10> vis;
- map<long long, string> id;
- bool check(int x, int y){
- return x >= 0 && x < 3 && y >= 1 && y <= 3;
- }
- void build(){
- neigh[0].push_back(7);
- neigh[0].push_back(8);
- neigh[0].push_back(9);
- neigh[7].push_back(0);
- neigh[8].push_back(0);
- neigh[9].push_back(0);
- for(int i = 0; i < 3; i++){
- for(int j = 1; j <= 3; j++){
- //cout << "Dad = " << i << " " << j << endl;
- for(int k = 0; k < 8; k++){
- int x = i + _x[k];
- int y = j + _y[k];
- //cout << "Son = " << x << " " << y << endl;
- if(check(x, y)) {
- neigh[3*i + j].push_back(3*x + y);
- }
- }
- }
- }
- }
- void digit(int no, int size, long long val, string &form);
- void contem(int val){
- for(int i = 0; i < seq.size(); i++){
- if(seq[i] == val) {
- seq.erase(seq.begin()+i);
- bagagem -= val;
- break;
- }
- }
- }
- void forNeigh(int no, long long valor){
- vis[no] = true;
- for(int i = 0; i < neigh[no].size(); i++){
- int viz = neigh[no][i];
- if(!vis[viz]){
- string aux = "";
- aux += (char)('0'+i);
- digit(viz, 1, viz, aux);
- }
- }
- vis[no] = false;
- contem(valor);
- }
- void adiciona(long long valor, int cont, string &form){
- if(valor + bagagem < soma){
- bagagem += valor;
- seq.push_back(valor);
- id[valor] = form;
- forNeigh(cont, valor);
- }else if(valor + bagagem == soma){
- bagagem += valor;
- for(int i = 0; i < seq.size(); i++){
- cout << " " << id[seq[i]];
- }
- printf("%lld\n", valor);
- seq.push_back(valor);
- id[valor] = form;
- cnt++;
- forNeigh(cont, valor);
- }
- }
- void digit(int no, int size, long long val, string &form){
- //cout << "--> " << val << endl;
- if(size == limit) {
- //cout << "limit\n";
- vis[no] = true;
- adiciona(val, no, form);
- vis[no] = false;
- }else if(val == soma-bagagem) {
- //cout << "equal\n";
- vis[no] = true;
- adiciona(val, no, form);
- vis[no] = false;
- }else if(val+bagagem < soma){
- vis[no] = true;
- for(int i = 0; i < neigh[no].size(); i++){
- int viz = neigh[no][i];
- if(!vis[viz]){
- string aux = form;
- aux += (char)('0'+viz);
- digit(viz, size + 1, val*10 + viz, aux);
- }
- }
- vis[no] = false;
- contem(val);
- }
- }
- void print(){
- for(int i = 0; i < 10; i++){
- cout << "#" << i << " = ";
- for(int j = 0; j < neigh[i].size(); j++) cout << neigh[i][j] << " \n"[j == neigh[i].size()-1];
- }
- }
- int main(){
- build();
- print();
- scanf("%lld %d", &soma, &limit);
- cnt = 0;
- vis.reset();
- for(int i = 0; i <= 9;i++){
- bagagem = 0;
- seq.clear();
- id.clear();
- string aux = "";
- aux += (char)('0'+i);
- digit(i, 1, i, aux);
- }
- if(cnt == 0) printf("impossivel\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement