A. Find a Number (thinking + dp + bfs)

topic

Meaning of the questions:

    Given a d and s, and desirably constructed as small as possible the number of x, such that x is a multiple of each of d and x and is s.
     1 d 500 , 1 s 5000 1≤d≤500,1≤s≤5000

analysis:

    D subconsciously think that is a multiple of enumeration, and then maintain each. But the problem lies not with the multiples and the correlation between each bit, so to enumerate the multiples will be very large, and may be no solution.
    Using the previous ideas, based on the number of each enumeration if we do? Enumerate every number is the need to maintain two variables, and each bit modulus and. Since d and s are not large, so much the number of states. For a number, if there is less than the number of its modulus and each and all of its the same, then this number is not necessarily the answer. So how do we enumeration, enumeration naturally from small to large, try adding one after each number, so that small to large enumeration, then the median is an enumeration with the same length, so I used a wide search to achieve. Complexity is d * s, that is up to all the status updates out.

#include <iostream>
#include <queue>
#include <string>
using namespace std;

typedef long long ll;

struct node{
	int mod;
	int sum;
	string res;
	node(int a,int b,string c)
	{
		mod = a;
		sum = b;
		res = c;
	}
};

int vis[505][5005];

string bfs(int d,int s)
{
	queue<node> q;
	q.push(node(0,0,""));
	vis[0][0] = 1;
	while( !q.empty() )
	{
		node t = q.front();
	//	cout << t.res << '\n';
		q.pop();
		if( t.mod == 0 && t.sum == s ) return t.res;
		for (int i = 0; i <= 9; i++)
		{
			int mod = ( t.mod * 10 + i ) % d;
			int sum = t.sum + i;
			if( sum > s || vis[mod][sum] ) continue;
			string res = t.res;
			char z = i + '0';
			res += z;
			q.push(node(mod,sum,res));
			vis[mod][sum] = 1;
		}
	}
	return "-1";
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int d,s;
	cin >> d >> s;
	cout << bfs(d,s) << '\n';
	return 0;
}

Published 132 original articles · won praise 6 · views 7906

Guess you like

Origin blog.csdn.net/weixin_44316314/article/details/105181588