1409D
题意:给你两个数n,s,你可以对n进行+1操作,使得n各个位加起来的值小于等于s,求最小的操作数
思路:最暴力的方法,一个一个加过去,这个是我一开始就不敢想的方法,但我的方法怎么说呢就是感觉挺多漏洞的,先说一下最暴力的方法把,因为你对n进行操作肯定是从个位数加向最高位,所以就个十百这样家过去,然后对于得到的n判断其各个位和是否小于等于s,如果小于等于那么就跳出这个循环。我的想法就是,从高位开始(完全相反,但效率更高,因为我不用判断,从低位不行,因为你进一位和不一定是加一),判断最高位到当前的位的和是否小于等于s,如果小于等于的话直接跳出循环,(主要是这里的判断有点麻烦)
暴力代码如下:
#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
inline int read(){
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
return x*f;
}
int sum(ll x){
int res = 0;
while(x){
res += x%10;
x /= 10;
}
return res;
}
inline void cf(){
int t = read();
while(t--){
ll n, s;
cin>>n>>s;
if(sum(n)<=s){printf("0\n");continue;}
ll cnt = 1, ans = 0;
for(int i = 0; i < 19; i++){
int digit = (n/cnt)%10;
ll add = cnt*((10-digit)%10);
n += add;
ans += add;
if(sum(n)<=s) break;
cnt *= 10;
}
printf("%lld\n", ans);
}
return ;
}
signed main(){
cf();
return 0;
}
稍微不那么暴力的代码:
#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
inline int read(){
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
return x*f;
}
int a[20];
void cf(){
int t = read();
while(t--){
ll n, s;
scanf("%lld%lld", &n, &s);
ll res = 0, len = 0, flag = 0;
ll x = n;
while(x){
res += x%10;
a[len++] = x%10;
if(x%10) flag++;
x /= 10;
}
if(res<=s) {
printf("0\n");continue;
}
ll ans = 0;
res = 0;
per(i,0,len-1){
ans += a[i];
if(a[i]) flag--;
if(ans+1>s){
if(ans==s&&flag==0) {printf("0\n"); break;}
rep(j,0,i){
res += a[j] * (ll)pow(10, j);
}
printf("%lld\n", (ll)pow(10,i+1)-res);break;
}
}
}
return ;
}
signed main(){
cf();
return 0;
}