B. You Are Given a Decimal String…
能简简单单暴力的为什么要exgcd呢
一定要预处理!!!
正解
#include <bits/stdc++.h>
#define MAXN 2000010
#define ll long long
using namespace std;
const int INF = 0x3f3f3f3f;
char s[MAXN];
ll ans[15][15];
int rem[15][15][15];
void Init(){
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
for(int k = 0; k < 10; k++)
rem[i][j][k] = INF;
for(int a = 0; a < 10; a++)
for(int b = 0; b < 10; b++)
for(int q = 0; q < 10; q++)
for(int p = 0; p < 10; p++)
if(p + q) rem[a][b][(q * a + p * b) % 10] = min(rem[a][b][(q * a + p * b) % 10], q + p - 1);
}
int main(){
scanf("%s", s);
int len = strlen(s);
Init();
for(int a = 0; a <= 9; a++)
for(int b = a; b <= 9; b++)
for(int now = 1; now < len; now++){
int t = s[now] - s[now - 1];
if(rem[a][b][(t + 10) % 10] == INF){ans[a][b] = -1; break;}
ans[a][b] += rem[a][b][(t + 10) % 10];
}
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++)
printf("%lld ", i < j ? ans[i][j] : ans[j][i]);
printf("\n");
}
return 0;
}
傻逼exgcd 会wa的那种
void exgcd(int a, int b, int& d, int& x, int& y){
if(!b) {d = a; x = 1; y = 0; }
else{ exgcd(b, a%b, d, y, x); y -= x*(a/b); }
}
void Init(){
for(int a = 0; a < 10; a++){
for(int b = a; b < 10; b++){
for(int t = -9; t <= 9; t++){
int tmp, d, x, y;
rem[a][b][t + 10] = INF;
for(int k = 0; k < 10; k++){
tmp = t + k * 10;
if(tmp < 0) continue;
exgcd(a, b, d, x, y);
if(a == 0 || b == 0){
if(tmp == 0) { rem[a][b][t + 10] = 0; break;}
else if(a == 0 && b == 0) break;
else if(tmp % (a + b) == 0){
rem[a][b][t + 10] = tmp / (a + b) - 1;
break;
}
}
else{
if(tmp % d) continue;
tmp /= d;
x *= tmp, y *= tmp;
int aa = a/d, bb = b/d, i = 0;
while(x < 0) x += bb, y -= aa;
while(x >= 0) x -= bb, y += aa;
x += bb, y -= aa;
while(x >= 0 && y >= 0){
rem[a][b][t + 10] = min(rem[a][b][t + 10], x + y - 1);
x += bb, y -= aa;
}
}
//简化版
/*if(a == 0 || b == 0){
if(tmp == 0) { rem[a][b][t + 10] = 0; break;}
else if(a == 0 && b == 0) break;
else if(tmp % (a + b) == 0){ rem[a][b][t + 10] = tmp / (a + b) - 1; break;}
}
else{
if(tmp % d) continue;
x *= tmp / d, y *= tmp / d;
int aa = a/d, bb = b/d, delta = 0;
if(y < tmp / b) delta = ((tmp / b) - y) / aa;
else if(y > tmp / b) delta = -((y - (tmp / b) - 1) / aa + 1);
y += delta * aa, x -= delta * bb;
if(x >= 0 && y >= 0) rem[a][b][t + 10] = min(rem[a][b][t + 10], x + y - 1);
}*/
}
}
}
}
}
其实我觉得exgcd也挺科学的 但就是不知道为什么会wa……