String LCM

本文介绍了如何使用C++解决Codeforces问题1473B,通过计算两个字符串的最小公倍数并构造新字符串,若新字符串相等则输出,否则返回-1。关键函数包括计算最小公倍数和构造字符串。
摘要由CSDN通过智能技术生成

题目链接:Problem - 1473B - Codeforces

解题思路:

先算出两个字符串的最小公倍数,再分别除以字符串长度,构造出两个新的字符串,就是最小公倍数除以老字符串长度个老字符串相加,打个比方,a字符串长度为4,b字符串长度为6,最小公倍数就是12,那么新字符串a就是12 / 4个老的字符串a相加,b同理,如果两个新的字符串相等,九叔出一个新的字符串,否则输出-1。

下面是c++代码:

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
    string boring(string, int);
    int lcm(int, int);
    int t, n;
    string a, b;
    cin >> t;
    while (t != 0) {
        cin >> a >> b;
        int alength = a.length(), blength = b.length();
        int g =  lcm(alength, blength);
        if (boring(a, g / alength) == boring(b,  g / blength)) {
            cout << boring(a, g / alength) << endl;
        }
        else {
            cout << -1 << endl;
        }
        t--;
    }
    return 0;
}
string boring(string s, int k) {
    string str = "";
    while (k != 0) {
        str += s;
        k--;
    }
    return str;
}
int lcm(int x, int y)
{
    if (x > y) {
        x = x ^ y;
        y = x ^ y;
        x = x ^ y;
    }
    int num = x, count = 1;
    while (1) {
        num = x * count;
        if (num % x == 0 && num % y == 0) {
            return num;
        }
        count++;
    }
}

  • 16
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值