这个题比较巧妙,竟然是最短路,可怕…
链接
题意:给你一串字符串,按照x-y counter的方式组成,问对于每一个0到9的x-y counter,需要多少步组成,不能组成输出-1.
For example, a 4-2-counter can act as follows:
it prints 0, and adds 4 to its value, so the current value is 4, and the output is 0;
it prints 4, and adds 4 to its value, so the current value is 8, and the output is 04;
it prints 8, and adds 4 to its value, so the current value is 12, and the output is 048;
it prints 2, and adds 2 to its value, so the current value is 14, and the output is 0482;
it prints 4, and adds 4 to its value, so the current value is 18, and the output is 04824.
思路:先预处理出0-9的每个数加x、y的值,这里的步数为1,由于数据较小,进行Floyed,找每两个数之间到达的最小步数,最后相加。注意dis存的是步数,所以相加时要减1.
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int inf=0x3f3f3f3f;
char s[2000010];
int dis[10][10];
int fun(int x,int y){
memset(dis,inf,sizeof(dis));
for(int i=0;i<=9;i++){
dis[i][(i+x)%10]=dis[i][(i+y)%10]=1;
}
for(int k=0;k<=9;k++){
for(int i=0;i<=9;i++){
for(int j=0;j<=9;j++){
dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);
}
}
}
int l=strlen(s);
int ans=0;
for(int i=0;i<l-1;i++){
int a=s[i]-'0';
int b=s[i+1]-'0';
if(dis[a][b]==inf)
return -1;
else ans+=dis[a][b]-1;
}
return ans;
}
int main(){
scanf("%s",s);
for(int i=0;i<=9;i++){
for(int j=0;j<=9;j++){
printf("%d ",fun(i,j));
}
printf("\n");
}
return 0;
}