原题
原题
原题
这是道好题,有很多细节要注意,稍不留神就丢分了。
1、首先很容易想到枚举1~9九个数字,要使得组成的数字是m的位数,又不能超过n,先去构造一个最短的m的倍数,然后再重复这个数即可;
2、当然,枚举过程中可能好几个数字都满足要求,那么记录每个数字的最短长度,最终在最长的位数中选取答案即可;
3、这里有一点要注意:满足要求的数,最长的可能不止一个,那么就要选数字大的那个作为答案(程序中在判n % cnt[i] <= lft 是取到了等号,就是处理这个细节)
比赛中没有做对,是忘了更新lft了。。。
#include <bits/stdc++.h>
using namespace std;
int T, n, m, digit, times;
vector <int> ans;
vector <int> cnt;
int main(){
cin >> T;
while (T--){
cin >> n >> m;
ans.clear();
cnt.clear();
for (int i=1; i<10; ++i){//枚举数字
long long s = 0;
int c = 0;//不能从一位数开始,因为m可能是一位数
while (c < n){
s = s*10 + i;
s %= m;
if (s==0){
ans.push_back(i);
cnt.push_back(c+1);
// break这里不能这么做
}
c++;
}
}
if (ans.size() == 0) cout << -1 << endl;
else{
int lft = 100000;//剩下的位数越少,数越大
for (int i=0; i<ans.size(); ++i){
if (n % cnt[i] <= lft){//等号取到,因为数字越大值越大
digit = ans[i];
times = n/cnt[i] * cnt[i];
lft = n%cnt[i];//忘了更新了!!!
}
}
cout << string(times, (char)(48+digit)) << endl;
}
}
return 0;
}题目分析 我们可以对于每个数字先进行 %3 操作这样就可以把大量的数据转换成0 1 2 三个数的问题
问题解决 注意到:满足条件的结果只会有9种情况 分别为
{0,0,0}重复,
{1,1,1}重复,
{0,1,2}重复,
{0,2,1}重复,
{1,0,2}重复,
{1,2,0}重复,
{2,0,1}重复,
{2,1,0}重复,
{2,2,2}重复。我们定义 t 数组表示任意相邻的三个数可能产生的9种情况
int t[9][3] = {{0, 0, 0}, {1, 1, 1},
{0, 1, 2}, {0, 2, 1},
{1, 0, 2}, {1, 2, 0},
{2, 0, 1}, {2, 1, 0},
{2, 2, 2}};在解决过程中,我们将预处理好的序列直接进行覆盖,这样的结果一定是满足条件的 对于每一种覆盖方式
-
t[i][j % 3] > a[j]这种情况下,只需要将a[j]添补到t[i][j % 3]即可,操作次数为t[i][j % 3] - a[j] -
t[i][j % 3] = a[j]这种情况下,我们不进行操作 -
t[i][j % 3] < a[j]这种情况下,我们不改变a[j],而是通过改变其他的值再凑出新的3,操作次数为t[i][j % 3] + 3 - a[j]
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
const int INF = 0x3f3f3f3f;
int a[N], n;
int t[9][3] = {{0, 0, 0}, {1, 1, 1}, {0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}, {2, 2, 2}};
int ans = INF;
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
a[i] %= 3;
}
int res;
for (int i = 0; i < 9; i++) {
res = 0;
for (int j = 1; j <= n; j++) {
if (t[i][j % 3] >= a[j]) res += t[i][j % 3] - a[j];
else res += t[i][j % 3] + 3 - a[j];
}
ans = min(ans, res);
}
cout << ans;
return 0;
}最后对于9种情况产生的方案数打擂台最小值,便得到结果