codeforces Transformation: from A to B (水题)

本文介绍了一道Codeforces上的题目,通过逆向思维从目标数B出发,利用除法和减法逐步回溯至起始数A,实现数字间的转换。文章提供了一种简单高效的解决方案,并附带完整的C语言代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给你两个数A和B让你把A转换成B,只能用两种方法,每一次让A乘2或者让A乘10加1,问你需要操作几次能成功,并把每一次更新的A值输出。


首先想到的方法就是搜索dfs,但是每回在第五个数据测试时都RE。之后又想了想,发现每一次更新的数要么是奇数,要么是偶数,当是奇数是就是乘10加1,是偶数时就是乘2,所以从B往前推,只有两种可能,要是能推到A,测成功,否则失败。这个题真心水,是我想复杂了,原本想着是用搜索,结果什么也不用,cf上的题真的是考你的思维!!!

#include<stdio.h>
#include<string.h>
int path[105];
int main()
{
    int a,b,sum=0,flag;
    scanf("%d%d",&a,&b);
    path[++sum]=b;
    flag=1;
    while(b>a)
    {
        if((b-1)%10==0)
        {
            path[++sum]=(b-1)/10;
            b=(b-1)/10;
        }
        else if(b%2==0)
        {
            path[++sum]=b/2;
            b/=2;
        }
        else
        {
            flag=0;
            break;
        }
    }
    if(a==b)
    {
        printf("YES\n");
        printf("%d\n",sum);
        for(int i=sum;i>=1;i--)
        {
            printf("%d ",path[i]);
        }
    }
    else
    {
        printf("NO\n");
    }
    return 0;
}



You are given a positive integer N and two strings S and T, each of length N and consisting of lowercase English letters. Determine whether it is possible to make S identical to T by repeating the operation below any number of times (possibly zero). If it is possible, also find the minimum number of operations required. Choose two lowercase English letters x,y and replace every occurrence of x in S with y. Constraints 1≤N≤2×10 5 N is an integer. Each of S and T is a string of length N, consisting of lowercase English letters. Input The input is given from Standard Input in the following format: N S T Output If it is possible to make S identical to T, print the minimum number of operations required. Otherwise, print −1. Sample Input 1 Copy 6 afbfda bkckbb Sample Output 1 Copy 4 By performing the operation four times in the following way, you can make S identical to T: Choose x= b and y= c. S becomes afcfda. Choose x= a and y= b. S becomes bfcfdb. Choose x= f and y= k. S becomes bkckdb. Choose x= d and y= b. S becomes bkckbb, which is identical to T. It cannot be done with fewer than four operations, so the minimum number of operations required is 4. Sample Input 2 Copy 4 abac abac Sample Output 2 Copy 0 S and T are already identical, so no operations are required. Sample Input 3 Copy 4 abac abrc Sample Output 3 Copy -1 No matter how you repeat the operation, it is impossible to make S identical to T. Sample Input 4 Copy 4 abac bcba Sample Output 4 Copy 4 C++,中文!!!
最新发布
03-30
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值