490C - Hacking Cypher - CodeForces Solution


brute force math number theory strings *1700

Please click on ads to support us..

Python Code:

from __future__ import division, print_function
from collections import defaultdict
import math
import sys
import os
from io import BytesIO, IOBase
from collections import deque, Counter, OrderedDict, defaultdict
import heapq
import bisect
from bisect import bisect_left,bisect_right

BUFSIZE = 8192


class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = "x" in file.mode or "r" not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b"\n") + (not b)
			ptr = self.buffer.tell()
			self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode("ascii"))
		self.read = lambda: self.buffer.read().decode("ascii")
		self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
	
	sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop("end", "\n"))
	if kwargs.pop("flush", False):
		file.flush()


if sys.version_info[0] < 3:
	sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
	sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

def inp():
    return(int(input()))
def inps():
    return input().strip()
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input().strip()
    return(list(s[:len(s)]))
def invr():
    return(map(int,input().split()))

from types import GeneratorType
def bootstrap(f,stack=[]):
	def wrappedfunc(*args,**kwargs):
		to=f(*args,**kwargs)
		if stack:
			return to
		else:
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to=next(to)
				else:
					stack.pop()
					if not stack:
						break
					to=stack[-1].send(to)
			return to
	return wrappedfunc



s=insr()
a,b=invr()
n=len(s)

rem1=[0 for i in range(n+1)]
for i in range(n):
    rem1[i+1]=(rem1[i]*10 + int(s[i]))%a 
rem2=[0 for i in range(n+1)]
p=1
for i in range(n-1,-1,-1):
    rem2[i]=(rem2[i+1]+int(s[i])*p)%b
    p=(p*10)%b
ans=-1
for i in range(n-1):
    if rem1[i+1]==0==rem2[i+1] and s[i+1]!='0':
        ans=i
        break
if ans==-1:
    print('NO')
else:
    print('YES')
    print("".join(s[:ans+1]))
    print("".join(s[ans+1:]))

C++ Code:

#include <bits/stdc++.h>
 
using namespace std;
 
#define DIVYA ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define ll long long
#define umap unordered_map
#define uset unordered_set
#define lb lower_bound
#define ub upper_bound
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define all(v) (v).begin(),(v).end()
#define all1(v) (v).begin()+1,(v).end()
#define allr(v) (v).rbegin(),(v).rend()
#define allr1(v) (v).rbegin()+1,(v).rend()
#define sort0(v) sort(all(v))
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
#define sz(x) (ll)x.size()
#define pb push_back
#define ppb pop_back
#define mkp make_pair
#define inf 1000000000000000005
const ll mod = 1e9 + 7;
 
ll inv(ll i) {if (i == 1) return 1; return (mod - ((mod / i) * inv(mod % i)) % mod) % mod;}
 
ll mod_mul(ll a, ll b) {a = a % mod; b = b % mod; return (((a * b) % mod) + mod) % mod;}
 
ll mod_add(ll a, ll b) {a = a % mod; b = b % mod; return (((a + b) % mod) + mod) % mod;}
 
ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b);}
 
ll ceil_div(ll a, ll b) {return a % b == 0 ? a / b : a / b + 1;}
 
ll pwr(ll a, ll b) {a %= mod; ll res = 1; while (b > 0) {if (b & 1) res = res * a % mod; a = a * a % mod; b >>= 1;} return res;}
//****************************Template Ends*******************************//
 
const int MOD = 998244352;
ll hsh[1000010];
 
int get_rem1(char s,int a,ll d){
     d=((int(s)-int('0'))+10*d)%a;
    return d;
}
int get_rem2(char s,int a,ll d,int i){
     d=(d+((int(s)-int('0'))*hsh[i]))%a;
    return d;
}
 
 
void calculate_hsh(int a){
    hsh[0]=1%a;
    for(int i=1;i<1000010;i++){
        hsh[i]=(hsh[i-1]*10)%a;
    }
}
 
int main() {
    DIVYA;
    int a,b,c=0;
    
    string s,s2;
    cin>>s;
    cin>>a>>b;
    ll d[s.size()];
    ll e[s.size()];
     d[0]=0;
     e[0]=0;
     calculate_hsh(b);
    for(int i=1;i<s.size();i++){
    d[i]=get_rem1(s[i-1],a,d[i-1]);
    e[i]=get_rem2(s[s.size()-i],b,e[i-1],i-1);
    }
    for(int i=1;i<s.size();i++){
        if(s[i]!='0'){
        if(d[i]==0&&e[s.size()-i]==0){
          c=1;
          cout<<"YES"<<endl;
          cout<<s.substr(0,i)<<endl;
          cout<<s.substr(i,s.size()-i)<<endl;
          break;
        }
        }
    }
    if(c==0){
        cout<<"NO"<<endl;
    }
 return 0;
}
 


Comments

Submit
0 Comments
More Questions

322. Coin Change
307. Range Sum Query - Mutable
287. Find the Duplicate Number
279. Perfect Squares
275. H-Index II
274. H-Index
260. Single Number III
240. Search a 2D Matrix II
238. Product of Array Except Self
229. Majority Element II
222. Count Complete Tree Nodes
215. Kth Largest Element in an Array
198. House Robber
153. Find Minimum in Rotated Sorted Array
150. Evaluate Reverse Polish Notation
144. Binary Tree Preorder Traversal
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