182D - Common Divisors - CodeForces Solution


brute force hashing implementation math strings *1400

Please click on ads to support us..

Python Code:

from copy import deepcopy
s1=input()
s2=input()
if len(s1)>len(s2):
    s1,s2=deepcopy(s2),deepcopy(s1)

def func(s1,s2):
    if (len(s1)%len(s2)!=0):
        return False
    bla=len(s1)//len(s2)
    s2=s2*bla 
    if s2==s1:
        return True
    return False


ans=0
for i in range(len(s1)):
    if func(s1,s1[:i+1]) and func(s2,s1[:i+1]):
        ans+=1 
print(ans)

C++ Code:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<bits/stdc++.h>
#include <unordered_map>
#define ll long long
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define sz(v) (int)(v.size())
#define watch(x) cout << #x << " = " << x << endl;
#define fix(n) cout << fixed << setprecision(n);
#define mem(v, d) memset(v, d, sizeof(v))
ll gcd(ll x, ll y) { return(!y) ? x : gcd(y, x % y); }
ll lcm(ll x, ll y) { return((x / gcd(x, y)) * y); }
const int N = 1e5 + 1;
const int MOD = 1e9 + 7;
const int OO = 0x3f3f3f3f3;
const double EPS = 1e-9;
const double PI = acos(-1);
using namespace std;
bool valid(string div, string s) {
	string tmp = div;
	while (sz(tmp) < sz(s)) {
		tmp += div;
	}
	return tmp == s;
}
int main() {
	std::ios_base::sync_with_stdio(0);
	cin.tie(NULL); cout.tie(NULL);
	//freopen("mex.in", "r", stdin);
	//freopen("output.txt", "w", stdout);
	string s, t, tmp = ""; cin >> s >> t;
	ll cnt = 0;
	//cout << s + t << "\n" << t + s << "\n";;
	if ((s + t) != (t + s))return cout << 0, 0;
	for (int i = 1; i <= min(sz(s), sz(t)); i++) {
		tmp += s[i - 1];
		if (sz(s) % i == 0 && sz(t) % i == 0 && valid(tmp, s) && valid(tmp, t))cnt++;
	}cout << cnt;
	return 0;
}




Comments

Submit
0 Comments
More Questions

137. Single Number II
130. Surrounded Regions
129. Sum Root to Leaf Numbers
120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees
75. Sort Colors
74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence