1278B - A and B - CodeForces Solution


greedy math *1500

Please click on ads to support us..

Python Code:

import sys
'''
1,2,...,n 的数组中选取j个数求和得sumj
abs(sumj*2-sumn)
4*0+1 [1,1]
4*0+2 [3,3]
3 [6, 0]
4 [10, 8]
5 [15, 5]
6 [21, 17]
7 [28, 12]
8 [36, 30]
9 [45, 23]
10 [55, 47]

1 1
2 3

g(n)=1+...+n

f(0)=[g[0],g(-1)+2]

f(1)=[g(1),1=g(-2)+2] 1
f(2)=[g(2),g(1)+2] 1

f(3)=[g(3),0=g(0)+2] 0
f(4)=[g(4),g(3)+2] 0

f(5)=[g(5),g(2)+2] 1
f(6)=[g(6),g(5)+2] 1

f(7)=[g(7),g(4)+2]
f(8)=[g(8),g(7)+2]

f(2n+1)=[(2n-1)+2

0*4+1 0 1
0*4+2 1 3 
1*4+1,2 [2,10] 21
2*4+1,2 [11,27]  55

0*4+3 3 6
0*4+4 5 10

2
13
212
1313
21212
131313
'''


def g(n):
    if n == -2:
        return -1
    if n == -1:
        return -2
    return n*(n+1)/2


def run(a, b):
    c = abs(a-b)
    i = int(((8*c+1)**0.5-1)/2)
    while 1:
        ma = g(i)
        if i % 2 == 0:
            mi = g(i-1)+2
        else:
            mi = g(i-3)+2
        if mi <= c and c <= ma:
            if i % 4 == 1 or i % 4 == 2:
                if c % 2 == 1:
                    return i
            else:
                if c % 2 == 0:
                    return i
        i += 1


if sys.argv[-1] == 't':
    cases = [
        [0, 19, 6],
        [0, 12, 7],
        [0, 15, 5],
        [1, 3, 3],
        [11, 11, 0],
        [30, 20, 4]
    ]
    for case in cases:
        r = run(*case[:-1])
        if r != case[-1]:
            print(case, r)
    print(run(0, 10**9)-int(((8*(10**9)+1)**0.5-1)/2))
    for i in range(1, 10**5):
        re = run(0, 0+i)
                                        
else:
    for _ in range(int(input())):
        print(run(*[int(d) for d in input().split(" ")]))

	  	 						 										 	 	  	 	

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#include <string>
#include <cmath>
#include <algorithm>

int main() {
	#define int long long
	int t; cin >> t;
	while (t--) {
		int a, b; cin >> a >> b;
		int diff=abs(a-b);
		int sum=0, ans=1;
		while (sum<diff) {
			sum+=ans;
			ans++;
		}
		if (sum==diff) {
			cout << ans-1 << endl;
		}
		else {
			if (sum%2==diff%2) {
				cout << ans-1 << endl;
			}
			else if (ans%2==1) {
				cout << ans << endl;
			}
			else {
				cout << ans+1 << endl;
			}
		}
	}
}


Comments

Submit
0 Comments
More Questions

432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=