Search is not available for this dataset
name stringlengths 2 112 | description stringlengths 29 13k | source int64 1 7 | difficulty int64 0 25 | solution stringlengths 7 983k | language stringclasses 4 values |
|---|---|---|---|---|---|
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
#pragma GCC optimize(3)
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const long long mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template <typename T>
inline void read(T &a) {
char c = getchar();
T x = 0, f = 1;
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) {
x = (x << 1) + (x << 3) + c - '0';
c = getchar();
}
a = f * x;
}
int gcd(int a, int b) { return (b > 0) ? gcd(b, a % b) : a; }
string str;
int f[N][2];
set<string> ans;
int main() {
cin >> str;
int n = str.length();
if (n <= 6) {
puts("0");
return 0;
}
for (int i = n - 1; i >= 5; i--) {
if (i + 2 == n) {
f[i][0] = 1;
continue;
}
if (i + 3 == n) {
f[i][1] = 1;
continue;
}
if (i + 2 < n) {
if (f[i + 2][1] == 1) f[i][0] = 1;
if (f[i + 2][0] == 1 &&
((str[i] != str[i + 2]) || (str[i + 1] != str[i + 3])))
f[i][0] = 1;
}
if (i + 3 < n) {
if (f[i + 3][0] == 1) f[i][1] = 1;
if (f[i + 3][1] == 1 &&
((str[i] != str[i + 3]) || (str[i + 1] != str[i + 4]) ||
(str[i + 2] != str[i + 5])))
f[i][1] = 1;
}
}
for (int i = 5; i < n; i++) {
if (f[i][0]) ans.insert(str.substr(i, 2));
if (f[i][1]) ans.insert(str.substr(i, 3));
}
cout << ans.size() << '\n';
for (auto t : ans) {
cout << t << '\n';
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int mem[50010][3];
string str;
int N;
int valid(int i, int p) {
int &val = mem[i][p];
if (val >= 0) return val;
if (i >= N) return 1;
if (i == N - 1) return 0;
string pr = str.substr(i - p, p);
string cur = str.substr(i, 2);
val = 0;
if (pr != cur && valid(i + 2, 2)) {
val = 1;
return 1;
}
if (i == N - 2) {
return 0;
}
cur = str.substr(i, 3);
if (cur != pr && valid(i + 3, 3)) {
val = 1;
}
return val;
}
string all[50010 * 2];
int S;
int main() {
int i;
cin >> str;
N = str.length();
memset(mem, -1, sizeof(mem));
for (i = 5; i < N - 1; ++i) {
if (valid(i + 2, 2)) {
all[S++] = str.substr(i, 2);
}
if (i < N - 2 && valid(i + 3, 3)) {
all[S++] = str.substr(i, 3);
}
}
sort(all, all + S);
S = unique(all, all + S) - all;
cout << S << "\n";
for (i = 0; i < S; ++i) {
cout << all[i] << "\n";
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int NMAX = 10005;
int n, dp[2][NMAX];
char s[NMAX];
set<string> S;
string Str(int x, int y) {
string aux = "";
for (int i = x; i <= y; i++) aux += s[i];
return aux;
}
int main() {
int i, j, l;
cin.sync_with_stdio(false);
cin >> (s + 1);
n = strlen(s + 1);
dp[0][n + 1] = dp[1][n + 1] = 1;
for (i = n; i >= 6; i--) {
for (j = 0; j <= 1; j++)
if ((i + j + 1) <= n)
for (l = 0; l <= 1; l++)
if (dp[l][i + j + 2] == 1) {
if (Str(i, i + j + 1) != Str(i + j + 2, i + j + 2 + l + 1)) {
dp[j][i] = 1;
S.insert(Str(i, i + j + 1));
}
}
}
cout << S.size() << "\n";
for (auto it : S) cout << it << "\n";
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9 + 100;
const long double eps = 1e-11;
const long double pi = acos(-1.0L);
int myrand() { return rand(); }
unsigned rdtsc() {
unsigned ans;
asm("rdtsc" : "=a"(ans));
return ans;
}
int rnd(int x) { return myrand() % x; }
void precalc() {}
const int maxn = 1e5;
int n;
string str;
char s[maxn];
int dp[5][maxn];
bool read() {
if (scanf("%s", s) < 1) {
return false;
}
str = string(s);
n = strlen(s);
return true;
}
void solve() {
memset(dp, 0, sizeof(dp));
dp[2][n - 2] = 1;
dp[3][n - 3] = 1;
for (int i = n - 4; i >= 5; i--) {
for (int j = 2; j <= 3; j++) {
if (dp[j ^ 1][i + j]) {
dp[j][i] = 1;
}
if (i + j * 2 <= n) {
string s1 = str.substr(i, j);
string s2 = str.substr(i + j, j);
if (s1 != s2 && dp[j][i + j]) {
dp[j][i] = 1;
}
}
}
}
set<string> ans;
for (int i = 5; i < n; i++) {
for (int j = 2; j <= 3; j++) {
if (i + j > n) {
continue;
}
if (i + j == n - 1) {
continue;
}
string cur = str.substr(i, j);
if (dp[2][i + j] || dp[3][i + j] || n == i + j) {
ans.insert(cur);
}
}
}
printf("%d\n", ((int)((ans).size())));
for (string s : ans) {
printf("%s\n", s.c_str());
}
}
int main() {
srand(rdtsc());
precalc();
while (true) {
if (!read()) {
break;
}
solve();
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 10;
string s;
set<string> ans;
int dp[4][maxn];
int main() {
cin >> s;
ans.clear();
int len = s.length();
if (len >= 7) ans.insert(s.substr(len - 2, 2));
if (len >= 8) ans.insert(s.substr(len - 3, 3));
reverse(s.begin(), s.end());
memset(dp, 0, sizeof dp);
dp[2][1] = 1;
dp[3][2] = 1;
for (int i = 3; i < len - 5; i++) {
dp[2][i] = dp[3][i - 2] |
(dp[2][i - 2] && (s.substr(i - 3, 2) != s.substr(i - 1, 2)));
dp[3][i] = dp[2][i - 3] |
(dp[3][i - 3] && (s.substr(i - 5, 3) != s.substr(i - 2, 3)));
if (dp[2][i]) {
string tmp = s.substr(i - 1, 2);
reverse(tmp.begin(), tmp.end());
ans.insert(tmp);
}
if (dp[3][i]) {
string tmp = s.substr(i - 2, 3);
reverse(tmp.begin(), tmp.end());
ans.insert(tmp);
}
}
cout << (int)ans.size() << endl;
for (set<string>::iterator it = ans.begin(); it != ans.end(); it++) {
cout << *it << endl;
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | '''ACCEPTED'''
import sys
pow2 = pow # for modular expo pow2(base, n, mod)
from math import *
from time import time
from collections import defaultdict
from bisect import bisect_right, bisect_left
from string import ascii_lowercase as lcs
from string import ascii_uppercase as ucs
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
#getcontext().prec = 500
#sys.setrecursionlimit(30000)
# What doesn't challenge you, makes you weaker.
mod = 10**9 + 7
INF = sys.maxint
raw_input = lambda: sys.stdin.readline().rstrip()
die = lambda : exit(0)
flush= lambda : sys.stdout.flush()
r_s = lambda: raw_input().strip() #read str
r_ss = lambda: raw_input().split() #read stringss
r_i = lambda: int(raw_input()) #read int
r_is = lambda: map(int, raw_input().split())#read ints
r_f = lambda: float(raw_input()) #read float
r_fs = lambda: map(Decimal, raw_input().split()) #read floats
# For effieciently taking lots of queries with each query in a separate line
# having integer values separated by space. A 2d list is made with each row
# corresponding to line. Each row is a list with all the values.
# Use this for fast I/O by taking all input in one go.
r_qs = lambda: map(lambda s:map(int, s.split(' ')), sys.stdin.readlines())
'''-------------------------------------------------------------------'''
def main():
s = r_s()
# Special Cases
if len(s)<7:
print 0
return
if len(s) == 7:
print 1
print s[-2:]
return
# End of Special Cases
dp2 = [0 for i in range(len(s)+1)] # dp2[i] = 1 means its possible to pick s[i:i+2]
dp3 = [0 for i in range(len(s)+1)] # dp3[i] = 1 means its possible to pick s[i:i+3]
n = len(s)
s = '0' + s # For 1 - indexing
subs = set()
# Base cases
dp2[n-1] = 1
subs.add(s[n-1:n+1])
dp3[n-2] = 1
subs.add(s[n-2:n+1])
# Filling dp
for i in range(n-3, 5, -1):
if (dp2[i+2]!=0 and s[i:i+2] != s[i+2:i+4]) or dp3[i+2] != 0:
dp2[i] = 1
subs.add(s[i:i+2])
if (dp3[i+3]!=0 and s[i:i+3] != s[i+3:i+6]) or dp2[i+3] != 0:
dp3[i] = 1
subs.add(s[i:i+3])
subs = list(subs)
subs.sort()
print len(subs)
for elem in subs:
print elem
if __name__ == '__main__':
try:
sys.stdin = open('input.txt')
print 'Running at local.'
for i in range(r_i()):
main()
except IOError:
main()
# main()
def dbg(var):
def get_name(**kwargs):
return kwargs.keys()[0]
print "Value of '" + get_name(var=var) + "' is", var
| PYTHON |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int DP[10005][2];
int main() {
string a;
cin >> a;
set<string> Ans;
DP[a.length() - 2][0] = 1;
DP[a.length() - 2][1] = 0;
DP[a.length() - 3][0] = 0;
DP[a.length() - 3][1] = 1;
if (a.length() >= 7) Ans.insert(a.substr(a.length() - 2, 2));
if (a.length() >= 8) Ans.insert(a.substr(a.length() - 3, 3));
a += "000";
for (int i = a.length() - 7; i >= 5; i--) {
if (a.substr(i, 2) != a.substr(i + 2, 2) && DP[i + 2][0] == 1) {
DP[i][0] = 1;
Ans.insert(a.substr(i, 2));
} else {
if (DP[i + 2][1] == 1) {
DP[i][0] = 1;
Ans.insert(a.substr(i, 2));
}
}
if (a.substr(i, 3) != a.substr(i + 3, 3) && i <= a.length() - 9 &&
DP[i + 3][1] == 1) {
DP[i][1] = 1;
Ans.insert(a.substr(i, 3));
} else {
if (DP[i + 3][0] == 1) {
DP[i][1] = 1;
Ans.insert(a.substr(i, 3));
}
}
}
cout << Ans.size() << endl;
for (auto i = Ans.begin(); i != Ans.end(); i++) cout << *i << endl;
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int mn = INT_MIN;
const int mx = INT_MAX;
const int mod = 1000000007;
bool dp[10004];
set<string> st;
int main() {
ios::sync_with_stdio(0);
cin.tie(NULL);
memset(dp, 0, sizeof(dp));
string s;
cin >> s;
reverse(s.begin(), s.end());
dp[1] = 1;
dp[2] = 1;
for (auto i = 3; i < int(s.size()); i++) {
if (i - 2 >= 0 &&
((i - 3) < 0 || (i - 3 >= 0 && (i - 5 >= 0 && dp[i - 5])
? 1
: s.substr(i - 3, 2) != s.substr(i - 1, 2))))
dp[i] = dp[i - 2];
if (i - 3 >= 0 &&
((i - 5) < 0 || (i - 5 >= 0 && (i - 5 >= 0 && dp[i - 5])
? 1
: s.substr(i - 5, 3) != s.substr(i - 2, 3))))
dp[i] = max(dp[i], dp[i - 3]);
}
for (auto i = 0; i < int(s.size() - 1); i++) {
if (i - 2 >= 0 && dp[i - 2] && (i) < (s.size() - 1 - 4)) {
string tmp = s.substr(i - 1, 2);
reverse(tmp.begin(), tmp.end());
st.insert(tmp);
} else if (i == 1 && (i) < (s.size() - 1 - 4)) {
string tmp = s.substr(i - 1, 2);
reverse(tmp.begin(), tmp.end());
st.insert(tmp);
};
if (i - 3 >= 0 && dp[i - 3] && (i) < (s.size() - 1 - 4)) {
string tmp = s.substr(i - 2, 3);
reverse(tmp.begin(), tmp.end());
st.insert(tmp);
} else if (i == 2 && (i) < (s.size() - 1 - 4)) {
string tmp = s.substr(i - 2, 3);
reverse(tmp.begin(), tmp.end());
st.insert(tmp);
};
}
cout << st.size() << "\n";
for (auto i : st) {
cout << i << "\n";
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
set<string> ans;
vector<bool> dp2(s.length() + 10, false), dp3(s.length() + 10, false);
dp2[s.length()] = dp3[s.length()] = true;
for (int n = s.length() - 2; n >= 5; n--) {
if (dp2[n] = (dp3[n + 2] ||
(dp2[n + 2] && s.substr(n, 2) != s.substr(n + 2, 2)))) {
ans.insert(s.substr(n, 2));
}
if (dp3[n] = (dp2[n + 3] ||
(dp3[n + 3] && s.substr(n, 3) != s.substr(n + 3, 3)))) {
ans.insert(s.substr(n, 3));
}
}
cout << ans.size() << endl;
for (auto& a : ans) {
cout << a << endl;
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int dp[10010][4];
string s;
set<string> v;
int dfs(int x, int d) {
if (x == s.size()) {
return 1;
}
if (dp[x][d] != -1) return dp[x][d];
int ans = 0;
for (int i = 2; i <= 3; i++) {
if (x + i > s.size()) continue;
if (i == d and s.substr(x - d, d) == s.substr(x, d)) continue;
if (dfs(x + i, i)) {
v.insert(s.substr(x, i));
ans = 1;
}
}
return dp[x][d] = ans;
}
int main() {
memset(dp, -1, sizeof(dp));
cin >> s;
for (int i = 5; i <= s.size(); i++) dfs(i, 0);
v.erase("");
cout << v.size() << endl;
for (auto t : v) cout << t << endl;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int l = s.size();
bool app[l + 2][2];
for (int i = 0; i < l + 2; i++) {
app[i][0] = false;
app[i][1] = false;
}
app[l - 1][0] = false;
app[l - 1][1] = false;
app[l - 2][0] = true;
app[l - 2][1] = false;
app[l - 3][0] = false;
app[l - 3][1] = true;
for (int i = l - 4; i > -1; i--) {
if (app[i + 2][1] == true) {
app[i][0] = true;
} else if (app[i + 2][0] == true) {
if (s.substr(i + 2, 2) != s.substr(i, 2)) {
app[i][0] = true;
}
} else {
app[i][0] = false;
}
if (app[i + 3][0] == true) {
app[i][1] = true;
} else if (app[i + 3][1] == true) {
if (s.substr(i + 3, 3) != s.substr(i, 3)) {
app[i][1] = true;
}
} else {
app[i][1] = false;
}
}
vector<string> v;
for (int i = 5; i < l; i++) {
if (app[i][0]) {
v.push_back(s.substr(i, 2));
}
if (app[i][1]) {
v.push_back(s.substr(i, 3));
}
}
sort(v.begin(), v.end());
if (v.size() == 0) {
cout << 0 << endl;
return 0;
}
vector<string> v2;
string temp = "";
for (string thing : v) {
if (thing != temp) {
v2.push_back(thing);
temp = thing;
}
}
cout << v2.size() << endl;
for (string thing : v2) {
cout << thing << endl;
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
int N, f[10001], g[10001], h[10001];
char a[10002];
int main() {
scanf("%s", a + 1);
while (a[N + 1]) N++;
f[N] = 1;
for (int i = N; i >= 7; i--) {
if (f[i]) {
g[i - 2] = 1;
h[i - 3] = 1;
}
if (g[i]) {
if (a[i - 1] != a[i + 1] || a[i] != a[i + 2]) g[i - 2] = 1;
h[i - 3] = 1;
}
if (h[i]) {
g[i - 2] = 1;
if (a[i - 2] != a[i + 1] || a[i - 1] != a[i + 2] || a[i] != a[i + 3])
h[i - 3] = 1;
}
}
std::set<std::string> S;
for (int i = 7; i <= N; i++)
if (f[i] || g[i] && (a[i - 1] != a[i + 1] || a[i] != a[i + 2]) || h[i])
S.insert(std::string(a + i - 1, a + i + 1));
for (int i = 8; i <= N; i++)
if (f[i] || g[i] ||
h[i] &&
(a[i - 2] != a[i + 1] || a[i - 1] != a[i + 2] || a[i] != a[i + 3]))
S.insert(std::string(a + i - 2, a + i + 1));
printf("%d\n", int(S.size()));
for (auto &i : S) std::cout << i << std::endl;
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | s = input()
s = s[5:]
if len(s) < 2:
print(0)
elif len(s) == 2:
print(1)
print(s)
elif len(s) == 3:
print(2)
for suff in sorted([s, s[-2:]]):
print(suff)
else:
D = [[False for _ in range(2)] for _ in range(len(s))]
suffixes = { s[-2:], s[-3:] }
D[-2][0] = True
D[-3][1] = True
for i in range(len(s) - 4, -1, -1):
if (s[i:i+2] != s[i+2:i+4] and D[i+2][0]) or D[i+2][1]:
D[i][0] = True
suffixes |= { s[i:i+2] }
if (i <= len(s) - 6 and s[i:i+3] != s[i+3:i+6] and D[i+3][1]) or D[i+3][0]:
D[i][1] = True
suffixes |= { s[i:i+3] }
print(len(suffixes))
for suffix in sorted(suffixes):
print(suffix)
| PYTHON3 |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void Read(T &x) {
int f = 1;
char t = getchar();
while (t < '0' || t > '9') {
if (t == '-') f = -1;
t = getchar();
}
x = 0;
while (t >= '0' && t <= '9') {
x = x * 10 + t - '0';
t = getchar();
}
x *= f;
}
template <typename T>
inline void Write(T x) {
static int output[20];
int top = 0;
if (x < 0) putchar('-'), x = -x;
do {
output[++top] = x % 10;
x /= 10;
} while (x > 0);
while (top > 0) putchar('0' + output[top--]);
putchar('\n');
}
template <typename T>
inline void chkmin(T &x, T y) {
if (x > y) x = y;
}
template <typename T>
inline void chkmax(T &x, T y) {
if (x < y) x = y;
}
const int maxn = 10005;
int n;
char s[maxn];
bool f[maxn][2];
vector<string> ans;
void input() {
scanf("%s", s + 1);
n = strlen(s + 1);
}
void solve() {
f[n + 1][0] = f[n + 1][1] = 1;
for (int i = n; i > 5; i--) {
f[i][0] |= f[i + 2][1];
if (s[i] != s[i + 2] || s[i + 1] != s[i + 3]) f[i][0] |= f[i + 2][0];
f[i][1] |= f[i + 3][0];
if (s[i] != s[i + 3] || s[i + 1] != s[i + 4] || s[i + 2] != s[i + 5])
f[i][1] |= f[i + 3][1];
if (f[i][0]) {
string res;
res.push_back(s[i]);
res.push_back(s[i + 1]);
ans.push_back(res);
}
if (f[i][1]) {
string res;
res.push_back(s[i]);
res.push_back(s[i + 1]);
res.push_back(s[i + 2]);
ans.push_back(res);
}
}
sort(ans.begin(), ans.end());
ans.erase(unique(ans.begin(), ans.end()), ans.end());
cout << ans.size() << endl;
for (int i = 0; i < (int)ans.size(); i++) {
cout << ans[i] << endl;
}
}
int main() {
input();
solve();
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
FastScanner in;
PrintWriter out;
static final String FILE = "";
String s;
TreeSet<String> set = new TreeSet<>();
boolean used[][];
void work(int v, int len) {
if (v < 5)
return;
if (used[v][len])
return;
used[v][len] = true;
String curr = s.substring(v, v + len);
set.add(curr);
for (int i = v - 2; i >= v - 3; i--) {
if (i < 5)
continue;
String ns = s.substring(i, v);
if (ns.equals(curr))
continue;
work(i, v - i);
}
}
public void solve() {
s = in.next();
used = new boolean[s.length()][4];
work(s.length() - 2, 2);
work(s.length() - 3, 3);
out.println(set.size());
for (String ss : set)
out.println(ss);
}
public void run() {
if (FILE.equals("")) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
try {
in = new FastScanner(new FileInputStream(FILE +
".in"));
out = new PrintWriter(new FileOutputStream(FILE +
".out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
solve();
out.close();
}
public static void main(String[] args) {
(new Main()).run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
class Pair<A extends Comparable<A>, B extends Comparable<B>>
implements Comparable<Pair<A, B>> {
public A a;
public B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Pair<A, B> o) {
if (o == null || o.getClass() != getClass())
return 1;
int cmp = a.compareTo(o.a);
if (cmp == 0)
return b.compareTo(o.b);
return cmp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (a != null ? !a.equals(pair.a) : pair.a != null) return
false;
return !(b != null ? !b.equals(pair.b) : pair.b != null);
}
}
class PairInt extends Pair<Integer, Integer> {
public PairInt(Integer u, Integer v) {
super(u, v);
}
}
class PairLong extends Pair<Long, Long> {
public PairLong(Long u, Long v) {
super(u, v);
}
}
} | JAVA |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long int max(long long int a, long long int b) {
if (a > b)
return a;
else
return b;
}
long long int min(long long int a, long long int b) {
if (a < b)
return a;
else
return b;
}
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
int XX[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int YY[] = {-1, 0, 1, -1, 1, -1, 0, 1};
string str;
long long int n;
set<string> s;
long long int dp[10004][5];
long long int func(long long int ind, long long int flag) {
if (dp[ind][flag] != -1) return dp[ind][flag];
long long int cnt = 0, flag2 = 0, flag3 = 0;
if (ind - 2 >= 4) {
if (flag == 1) {
string str3, str4;
if (str.substr(ind - 1, 2) == str.substr(ind + 1, 2)) {
flag2 = 1;
}
}
if (flag2 == 0) {
string str2;
str2.push_back(str[ind - 1]);
str2.push_back(str[ind]);
s.insert(str2);
cnt += 1 + func(ind - 2, 1);
}
}
if (ind - 3 >= 4) {
if (flag == 2) {
if (str.substr(ind - 2, 3) == str.substr(ind + 1, 3)) flag3 = 1;
}
if (flag3 == 0) {
string str2;
str2.push_back(str[ind - 2]);
str2.push_back(str[ind - 1]);
str2.push_back(str[ind]);
s.insert(str2);
cnt += 1 + func(ind - 3, 2);
}
}
return dp[ind][flag] = cnt;
}
int main() {
memset(dp, -1, sizeof(dp));
ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
long long int i, j;
cin >> str;
n = str.length();
long long int ans = func(n - 1, 0);
cout << s.size() << "\n";
for (auto itr : s) cout << itr << "\n";
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int main() {
string s;
ios_base::sync_with_stdio(false);
cin >> s;
int k, l, i, j;
l = s.length();
set<string> my;
int dp[l + 1];
dp[l - 2] = 1;
dp[l - 3] = 2;
if (l <= 6) {
cout << 0;
return 0;
}
if (l == 7) {
cout << 1 << endl;
cout << s.substr(l - 2, 2);
return 0;
}
my.insert(s.substr(l - 2, 2));
my.insert(s.substr(l - 3, 3));
for (i = l - 4; i >= 5; --i) {
dp[i] = 0;
if (dp[i + 2] && !(dp[i + 2] == 1 && (s.at(i) == s.at(i + 2) &&
s.at(i + 1) == s.at(i + 3)))) {
my.insert(s.substr(i, 2));
dp[i]++;
}
if (i != l - 4 && dp[i + 3] &&
!(dp[i + 3] == 2 &&
(s.at(i) == s.at(i + 3) && s.at(i + 1) == s.at(i + 4) &&
s.at(i + 2) == s.at(i + 5)))) {
my.insert(s.substr(i, 3));
dp[i] += 2;
}
}
cout << my.size() << endl;
set<string>::iterator it;
for (it = my.begin(); it != my.end(); ++it) cout << (*it) << endl;
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 |
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;
public class P666A{
static long mod=1000000007;
public static void main(String[] args) throws Exception{
InputReader in = new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
//int t=in.readInt();
// while(t-->0)
//{
//int n=in.readInt();
//long n=in.readLong();
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.readInt();
}*/
String a=in.readString();
char c[]=a.toCharArray();
int n=c.length;
int ans=0;
TreeSet<String>ts=new TreeSet<String>();
boolean dp2[]=new boolean[n+1];
boolean dp3[]=new boolean[n+1];
for(int i=n-2;i>=5;i--)
{
if(i+2==n)
{
String x=a.substring(i,i+2);
dp2[i]=true;
ts.add(x);
}
else
{
String x=a.substring(i,i+2);
if(i+3<n)
{
String y=a.substring(i+2,i+4);
if(x.compareTo(y)!=0&&dp2[i+2])
{
ts.add(x);
dp2[i]=true;
}
}
}
if(i+2<=n&&dp3[i+2])
{
String x=a.substring(i,i+2);
dp2[i]=true;
ts.add(x);
}
if(i+2<n)
{
if(i+3==n)
{
String x=a.substring(i,i+3);
dp3[i]=true;
ts.add(x);
}
else
{
String x=a.substring(i,i+3);
if(i+5<n)
{
String y=a.substring(i+3,i+6);
if(x.compareTo(y)!=0&&dp3[i+3])
{
ts.add(x);
dp3[i]=true;
}
}
}
if(i+3<=n&&dp2[i+3])
{
String x=a.substring(i,i+3);
dp3[i]=true;
ts.add(x);
}
}
}
pw.println(ts.size());
for(String x:ts)
pw.println(x);
//}
pw.close();
}
/* returns nCr mod m */
public static long comb(long n, long r, long m)
{
long p1 = 1, p2 = 1;
for (long i = r + 1; i <= n; i++) {
p1 = (p1 * i) % m;
}
p2 = factMod(n - r, m);
p1 = divMod(p1, p2, m);
return p1 % m;
}
/* returns a/b mod m, works only if m is prime and b divides a */
public static long divMod(long a, long b, long m)
{
long c = powerMod(b, m - 2, m);
return ((a % m) * (c % m)) % m;
}
/* calculates factorial(n) mod m */
public static long factMod(long n, long m) {
long result = 1;
if (n <= 1)
return 1;
while (n != 1) {
result = ((result * n--) % m);
}
return result;
}
/* This method takes a, b and c as inputs and returns (a ^ b) mod c */
public static long powerMod(long a, long b, long c) {
long result = 1;
long temp = 1;
long mask = 1;
for (int i = 0; i < 64; i++) {
mask = (i == 0) ? 1 : (mask * 2);
temp = (i == 0) ? (a % c) : (temp * temp) % c;
/* Check if (i + 1)th bit of power b is set */
if ((b & mask) == mask) {
result = (result * temp) % c;
}
}
return result;
}
public static long gcd(long x,long y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int abs(int a,int b)
{
return (int)Math.abs(a-b);
}
public static long abs(long a,long b)
{
return (long)Math.abs(a-b);
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b)
{
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b)
{
if(a>b)
return b;
else
return a;
}
static boolean isPowerOfTwo (long v) {
return (v & (v - 1)) == 0;
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static class Pair implements Comparable<Pair>
{
int a,b;
Pair (int a,int b)
{
this.a=a;
this.b=b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.a!=o.a)
return Integer.compare(this.a,o.a);
else
return Integer.compare(this.b, o.b);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
static long sort(int a[],int n)
{ int b[]=new int[n];
return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
{ long mid=left+(right-left)/2;
c= mergeSort(a,b,left,mid);
c+=mergeSort(a,b,mid+1,right);
c+=merge(a,b,left,mid+1,right); }
return c; }
static long merge(int a[],int b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]<=a[j]) {b[k++]=a[i++]; }
else { b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1) b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
a[i] = b[i]; return c; }
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//StringBuilder sb=new StringBuilder("");
//InputReader in = new InputReader(System.in);
//PrintWriter pw=new PrintWriter(System.out);
//String line=br.readLine().trim();
//int t=Integer.parseInt(br.readLine());
// while(t-->0)
//{
//int n=Integer.parseInt(br.readLine());
//long n=Long.parseLong(br.readLine());
//String l[]=br.readLine().split(" ");
//int m=Integer.parseInt(l[0]);
//int k=Integer.parseInt(l[1]);
//String l[]=br.readLine().split(" ");
//l=br.readLine().split(" ");
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(l[i]);
}*/
//System.out.println(" ");
//}
} | JAVA |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 6;
char str[maxn];
int dp[maxn][2];
int n;
vector<string> ans;
int main() {
scanf("%s", str);
n = strlen(str);
reverse(str, str + n);
for (int i = 1; i < n - 5; i++) {
if (i == 1) {
string s1 = "";
s1 += str[i];
s1 += str[i - 1];
ans.push_back(s1);
dp[i][0] = 1;
}
if (i == 2) {
string s1 = "";
s1 += str[i];
s1 += str[i - 1];
s1 += str[i - 2];
ans.push_back(s1);
dp[i][1] = 1;
}
if (i - 3 >= 0 && (str[i] != str[i - 2] || str[i - 1] != str[i - 3]) &&
dp[i - 2][0] == 1) {
string s1 = "";
s1 += str[i];
s1 += str[i - 1];
ans.push_back(s1);
dp[i][0] = 1;
}
if (i - 2 >= 0 && dp[i - 2][1] == 1) {
string s1 = "";
s1 += str[i];
s1 += str[i - 1];
ans.push_back(s1);
dp[i][0] = 1;
}
if (i - 5 >= 0 &&
(str[i] != str[i - 3] || str[i - 1] != str[i - 4] ||
str[i - 2] != str[i - 5]) &&
dp[i - 3][1] == 1) {
string s1 = "";
s1 += str[i];
s1 += str[i - 1];
s1 += str[i - 2];
ans.push_back(s1);
dp[i][1] = 1;
}
if (i - 3 >= 0 && dp[i - 3][0] == 1) {
string s1 = "";
s1 += str[i];
s1 += str[i - 1];
s1 += str[i - 2];
ans.push_back(s1);
dp[i][1] = 1;
}
}
sort(ans.begin(), ans.end());
ans.erase(unique(ans.begin(), ans.end()), ans.end());
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++) cout << ans[i] << endl;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
int n, l;
set<string> ans;
string s;
map<pair<int, string>, int> mp;
bool solve(int idx, string tmp = "") {
if (idx >= s.size()) {
return 1;
}
if (mp.count({idx, tmp})) {
return mp[{idx, tmp}];
}
string s3, s2;
bool x3, x2;
x3 = x2 = 0;
if (idx + 2 <= s.size() && idx + 3 != s.size()) {
s2 = s.substr(idx, 2);
if (s2 != tmp) {
x2 = solve(idx + 2, s2);
}
}
if (idx + 3 <= s.size() && idx + 4 != s.size()) {
s3 = s.substr(idx, 3);
if (s3 != tmp) {
x3 = solve(idx + 3, s3);
}
}
if (x2) ans.insert(s2);
if (x3) ans.insert(s3);
return mp[{idx, tmp}] = (x2 || x3);
}
int main() {
cin >> s;
if (s.size() < 7)
cout << 0;
else {
for (int i = 5; i < s.size() - 1; i++) solve(i, "");
cout << ans.size() << endl;
for (auto i : ans) {
cout << i << endl;
}
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Set;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
String s = in.next();
int n = s.length();
boolean[][] can = new boolean[2][n + 1];
for (int i = n - 1; i >= 5; i--) {
if (i + 1 < n) {
if (i + 2 == n ||
can[1][i + 2] ||
(can[0][i + 2] && !s.substring(i, i + 2).equals(s.substring(i + 2, i + 4)))) {
can[0][i] = true;
}
}
if (i + 2 < n) {
if (i + 3 == n ||
can[0][i + 3] ||
(can[1][i + 3] && !s.substring(i, i + 3).equals(s.substring(i + 3, i + 6)))) {
can[1][i] = true;
}
}
}
Set<String> ans = new TreeSet<>();
for (int i = 0; i < n; i++) {
if (can[0][i]) {
ans.add(s.substring(i, i + 2));
}
if (can[1][i]) {
ans.add(s.substring(i, i + 3));
}
}
out.println(ans.size());
for (String str : ans) {
out.println(str);
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
}
}
| JAVA |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | def get_suffixes(string):
if len(string) < 7:
return []
suffix_string = string[5:][::-1]
result = set()
result.add(suffix_string[:2])
dp2 = [1, 0, 1] + [0] * (len(suffix_string) -2)
dp3 = [1] + [0] * len(suffix_string)
for n in xrange(3, len(suffix_string) + 1):
if dp3[n-2] or (dp2[n-2] and suffix_string[n-4:n-2] != suffix_string[n-2:n]):
result.add(suffix_string[n-2:n])
dp2[n] = 1
if dp2[n-3] or (dp3[n-3] and suffix_string[n-6:n-3] != suffix_string[n-3:n]):
result.add(suffix_string[n-3:n])
dp3[n] = 1
return sorted(map(lambda x: x[::-1], result))
suffixes = get_suffixes(raw_input())
print len(suffixes)
for i in suffixes: print i | PYTHON |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 10005, inf = 0x3f3f3f3f;
const long long llinf = 0x3f3f3f3f3f3f3f3f;
const long double pi = acos(-1.0L);
string a[maxn * 2];
string s;
bool dp[maxn][2];
int main() {
cin >> s;
int i, len = s.length(), m = 0;
memset(dp, 0, sizeof(dp));
for (i = len - 2; i >= 5; i--) {
if (len - i == 2) {
a[++m] = s.substr(i, 2);
dp[i][0] = 1;
} else if (len - i == 3) {
a[++m] = s.substr(i, 3);
dp[i][1] = 1;
} else if (len - i == 4) {
if (s.substr(i, 2) != s.substr(i + 2, 2)) {
a[++m] = s.substr(i, 2);
dp[i][0] = 1;
}
} else {
if ((s.substr(i, 2) != s.substr(i + 2, 2) && dp[i + 2][0]) ||
dp[i + 2][1]) {
a[++m] = s.substr(i, 2);
dp[i][0] = 1;
}
if ((s.substr(i, 3) != s.substr(i + 3, 3) && dp[i + 3][1]) ||
dp[i + 3][0]) {
a[++m] = s.substr(i, 3);
dp[i][1] = 1;
}
}
}
sort(a + 1, a + m + 1);
int ans = unique(a + 1, a + m + 1) - a - 1;
printf("%d\n", ans);
for (i = 1; i <= ans; i++) {
cout << a[i] << endl;
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
string s, s1;
set<string> se;
bool mark[20000][2];
bool cmp(int i, int j) {
if (j >= s.size()) return true;
if (s[i] != s[j]) return true;
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin >> s;
mark[s.size()][2] = true;
mark[s.size()][3] = true;
for (int i = s.size() - 2; i > 4; i--) {
s1 = s[i];
s1 += s[i + 1];
if (mark[i + 2][3] ||
(mark[i + 2][2] && (cmp(i, i + 2) || cmp(i + 1, i + 3)))) {
mark[i][2] = true;
se.insert(s1);
}
if (i < s.size() - 2)
if (mark[i + 3][2] ||
(mark[i + 3][3] &&
(cmp(i, i + 3) || cmp(i + 1, i + 4) || cmp(i + 2, i + 5)))) {
mark[i][3] = true;
s1 += s[i + 2];
se.insert(s1);
}
}
cout << se.size() << endl;
while (se.size()) {
cout << *(se.begin()) << '\n';
se.erase(se.begin());
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const long long INF = 2e18;
const int N = 11234;
int n, m;
set<string> st;
char s[N];
int dp[N][4];
void dfs(int pos, string pre, int len) {
if (pos - 1 < 5) return;
if (dp[pos][len]) return;
dp[pos][len] = 1;
string str = "";
for (int i = 1; i >= 0; --i) str += s[pos - i];
if (str != pre) {
st.insert(str);
dfs(pos - 2, str, 2);
}
if (pos - 2 >= 5) {
str = "";
for (int i = 2; i >= 0; --i) str += s[pos - i];
if (str != pre) {
st.insert(str);
dfs(pos - 3, str, 3);
}
}
}
int main() {
while (scanf("%s", s) != EOF) {
int i, j;
memset(dp, 0, sizeof(dp));
st.clear();
n = strlen(s);
if (n < 5)
puts("0");
else {
dfs(n - 1, "", 0);
printf("%d\n", st.size());
set<string>::iterator it = st.begin();
for (; it != st.end(); ++it) {
cout << *it << endl;
}
}
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
char str[10024];
bool vis[10024][4];
set<string> ans;
set<string>::iterator it;
int main() {
int len, sum = 0;
scanf("%s", str);
len = strlen(str);
memset(vis, true, sizeof(vis));
vis[len][0] = false;
for (int i = len; i >= 5; i--) {
for (int j = 0; j < 4; j++) {
if (!vis[i][j]) {
string x = "", y = "";
for (int k = 0; k < j; k++) y = y + str[i + k];
for (int k = 1; (i - k) >= 5 && k < 4; k++) {
x = str[i - k] + x;
if (x != y && k > 1) {
ans.insert(x);
vis[i - k][k] = false;
}
}
}
}
}
printf("%d\n", int(ans.size()));
for (it = ans.begin(); it != ans.end(); it++) {
cout << *it << endl;
}
if (sum > 200) system("pause");
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | import sys
input = sys.stdin.readline
s = input().strip()
n = len(s)
poss = [[False] * 2 for _ in range(n)]
poss[n - 2][0] = poss[n - 3][1] = True
for i in range(n - 4, -1, -1):
poss[i][0] = s[i: i + 2] != s[i + 2: i + 4] and poss[i + 2][0] or poss[i + 2][1]
poss[i][1] = s[i: i + 3] != s[i + 3: i + 6] and poss[i + 3][1] or poss[i + 3][0]
ans = set()
for i in range(5, n):
if poss[i][0]:
ans.add(s[i: i + 2])
if poss[i][1]:
ans.add(s[i:i + 3])
print(len(ans))
for x in sorted(ans):
print(x)
| PYTHON3 |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | import java.util.HashSet;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.io.IOException;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
Set<String> sol = new HashSet<String>();
boolean[][] found;
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.next();
found = new boolean[2][s.length()];
find(s, s.length()-1, -1, "");
out.println(sol.size());
List<String> aa = new ArrayList<String>(sol);
Collections.sort(aa);
for (String ss: aa){
out.println(ss);
}
}
private void find(String s, int index, int conf, String prev) {
if (index<4){
//can't be root
return;
}
if (conf == -1 || !found[conf][index]){
if (index-2 >= 4){
String curr = s.substring(index-2+1, index-2+1+2);
if (!prev.equals(curr)){
sol.add(curr);
find(s, index-2, 0, curr);
}
}
if (index - 3 >= 4){
String curr = s.substring(index-3+1, index-3+1+3);
if (!prev.equals(curr)){
sol.add(curr);
find(s, index-3, 1, curr);
}
}
if (conf != -1) {
found[conf][index] = true;
}
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
}
public String next(){
while (tokenizer == null || !tokenizer.hasMoreTokens()){
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException("FATAL ERROR", e);
}
}
return tokenizer.nextToken();
}
}
| JAVA |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
bool mark[10005][5];
set<string> st;
char s[10005];
void go(int len, int bf) {
if (mark[len][bf]) return;
if (len <= 6) return;
mark[len][bf] = true;
bool fl = false;
if (bf == 2) {
fl |= (s[len - 1] != s[len + 1]);
fl |= (s[len - 2] != s[len]);
}
if (fl || bf != 2) {
string tmp = "";
tmp += s[len - 2];
tmp += s[len - 1];
st.insert(tmp);
go(len - 2, 2);
}
if (len <= 7) return;
fl = false;
if (bf == 3) {
fl |= (s[len - 1] != s[len + 2]);
fl |= (s[len - 2] != s[len + 1]);
fl |= (s[len - 3] != s[len]);
}
if (fl || bf != 3) {
string tmp = "";
tmp += s[len - 3];
tmp += s[len - 2];
tmp += s[len - 1];
st.insert(tmp);
go(len - 3, 3);
}
}
int main() {
scanf("%s", s);
go(strlen(s), 0);
printf("%d\n", st.size());
for (set<string>::iterator it = st.begin(); it != st.end(); it++) {
printf("%s\n", it->c_str());
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")
const int N = 1e4 + 5;
const long long int mod = 1e9 + 7;
const long long int Mod = 998244353;
const long double Pi = acos(-1);
const long long int Inf = 4e18;
using namespace std;
string s;
set<string> v;
bool dp[N][4];
void f(int len, string last) {
if (len < 5)
return;
else if (dp[len][(int)(int)last.size()])
return;
else {
dp[len][int((int)last.size())] = true;
if (last != "") v.insert(last);
string k1(s.begin() + len - 3, s.begin() + len);
if (k1.compare(last) != 0) f(len - 3, k1);
string k2(s.begin() + len - 2, s.begin() + len);
if (k2.compare(last) != 0) f(len - 2, k2);
}
}
void TestCase() {
cin >> s;
for (int i = 0; i < N; i++) {
for (int j = 0; j < 4; j++) dp[i][j] = false;
}
int n = (int)s.size();
f(n, "");
cout << (int)v.size() << "\n";
for (auto &o : v) cout << o << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
;
int T = 1;
while (T--) {
TestCase();
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
ifstream fin("alfa.in");
ofstream fout("alfa.out");
string s;
bool dp[10001][4];
string rasp[20001];
int main() {
int i, n, k = 0, rs = 0;
cin >> s;
n = s.size();
s = s + "000";
if (n >= 7) {
dp[n - 2][2] = 1;
rasp[++k] = s[n - 2];
rasp[k] += s[n - 1];
}
if (n >= 8) {
dp[n - 3][3] = 1;
rasp[++k] = s[n - 3];
rasp[k] += s[n - 2];
rasp[k] += s[n - 1];
}
for (i = n - 4; i > 4; i--) {
dp[i][2] = dp[i + 2][3] |
(dp[i + 2][2] && (s[i] != s[i + 2] || s[i + 1] != s[i + 3]));
dp[i][3] = dp[i + 3][2] |
(dp[i + 3][3] && (s[i] != s[i + 3] || s[i + 1] != s[i + 4] ||
s[i + 2] != s[i + 5]));
if (dp[i][2] == 1) {
rasp[++k] = s[i];
rasp[k] += s[i + 1];
}
if (dp[i][3] == 1) {
rasp[++k] = s[i];
rasp[k] += s[i + 1];
rasp[k] += s[i + 2];
}
}
sort(rasp + 1, rasp + k + 1);
for (i = 1; i <= k; i++)
if (rasp[i - 1] != rasp[i]) rs++;
cout << rs << '\n';
for (i = 1; i <= k; i++)
if (rasp[i - 1] != rasp[i]) cout << rasp[i] << '\n';
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
template <class T>
inline bool Min(T &a, T b) {
return a > b ? (a = b, true) : false;
}
template <class T>
inline bool Max(T &a, T b) {
return a < b ? (a = b, true) : false;
}
inline int ni() {
int a;
scanf("%d", &a);
return a;
}
inline ll nl() {
ll a;
scanf("%lld", &a);
return a;
}
inline double nd() {
double a;
scanf("%lf", &a);
return a;
}
inline void pi(int a) { printf("%d ", a); }
inline void pl(ll a) { printf("%lld ", a); }
inline void pd(double a) { printf("%.12lf ", a); }
const int N = 1e4 + 10;
int can[N][5];
bool comp(string &s, int i, int j, int len) {
if (i + len > s.size() or j + len > s.size()) return false;
for (int p = 0; p < len; i++, j++, p++)
if (s[i] != s[j]) return false;
return true;
}
void solve() {
string s;
cin >> s;
vector<string> a;
for (int i = 0; i < (int)(N); ++i)
for (int j = 0; j < (int)(5); ++j) can[i][j] = false;
can[s.size()][2] = can[s.size()][3] = true;
for (int i = int(s.size()) - 1; i >= 5; i--) {
for (int j = 2; j <= 3; j++) {
if (i + j > s.size()) continue;
if (i + j < s.size() and i + j + 2 > s.size()) continue;
if (comp(s, i, i + j, j)) {
if (can[i + j][(j == 2 ? 3 : 2)]) {
a.push_back(s.substr(i, j));
can[i][j] = true;
}
} else {
if (can[i + j][2] or can[i + j][3]) {
can[i][j] = true;
a.push_back(s.substr(i, j));
}
}
}
}
sort((a).begin(), (a).end());
a.resize(unique((a).begin(), (a).end()) - a.begin());
printf("%d\n", int(a.size()));
for (int i = 0; i < (int)(a.size()); ++i) puts(a[i].c_str());
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
srand((int)clock());
solve();
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
using ull = unsigned long long;
using ll = long long;
using ld = long double;
using vi = vector<ll>;
using vvi = vector<vi>;
using vb = vector<bool>;
using ii = pair<ll, ll>;
constexpr bool LOG = true;
void Log() {
if (LOG) cerr << "\n";
}
template <class T, class... S>
void Log(T t, S... s) {
if (LOG) cerr << t << "\t", Log(s...);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> s;
if (s.size() <= 5) {
cout << 0 << endl;
return 0;
}
s = s.substr(5);
ll n = s.size();
vector<bool> pos(n + 1, false);
vector<vector<string>> strings(n + 1);
pos[n] = true;
strings[n].push_back("");
for (ll i = n - 1; i >= 0; --i) {
if (i + 2 <= n && pos[i + 2]) {
if (strings[i + 2].size() > 1 || strings[i + 2][0] != s.substr(i, 2)) {
pos[i] = true;
strings[i].push_back(s.substr(i, 2));
}
}
if (i + 3 <= n && pos[i + 3]) {
if (strings[i + 3].size() > 1 || strings[i + 3][0] != s.substr(i, 3)) {
pos[i] = true;
strings[i].push_back(s.substr(i, 3));
}
}
}
set<string> ans;
for (auto &v : strings)
for (auto &s : v) ans.insert(s);
cout << ans.size() - 1 << endl;
for (auto &s : ans)
if (s.size() > 0) cout << s << '\n';
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
const int INF = INT_MAX;
const long long INFL = LLONG_MAX;
const long double pi = acos(-1);
string s;
int dp2[10010];
int dp3[10010];
int main() {
ios_base::sync_with_stdio(0);
cout.precision(15);
cout << fixed;
cout.tie(0);
cin.tie(0);
cin >> s;
int N = int((s).size());
dp2[N - 2] = 1;
dp3[N - 3] = 1;
set<string> ans;
for (int i = N - 1; i >= 5; i--) {
if (dp2[i]) {
ans.insert(s.substr(i, 2));
dp3[i - 3] = 1;
if (s.substr(i, 2) != s.substr(i - 2, 2)) {
dp2[i - 2] = 1;
}
}
if (dp3[i]) {
ans.insert(s.substr(i, 3));
dp2[i - 2] = 1;
if (s.substr(i, 3) != s.substr(i - 3, 3)) {
dp3[i - 3] = 1;
}
}
}
cout << int((ans).size()) << '\n';
for (auto t : ans) {
cout << t << '\n';
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
const int32_t LETT = 26;
const size_t MAX_STR = 20000;
char str[MAX_STR];
int32_t strLen;
bool occur2[LETT * LETT];
bool occur3[LETT * LETT * LETT];
bool pos2[MAX_STR];
bool pos3[MAX_STR];
int main() {
scanf("%s", str);
strLen = strlen(str);
int32_t code = str[strLen - 1] - 'a' + (str[strLen - 2] - 'a') * 26;
int32_t possibCnt = 0;
if (strLen >= 7) {
occur2[code] = true;
pos2[strLen - 2] = true;
possibCnt++;
}
code = code + (str[strLen - 3] - 'a') * 26 * 26;
if (strLen >= 8) {
occur3[code] = true;
pos3[strLen - 3] = true;
possibCnt++;
}
for (int32_t i = strLen - 4; i > 4; i--) {
if (pos3[i + 2]) {
pos2[i] = true;
} else if ((pos2[i + 2]) &&
((str[i] != str[i + 2]) || (str[i + 1] != str[i + 3]))) {
pos2[i] = true;
}
code = (str[i] - 'a') * 26 + str[i + 1] - 'a';
if (pos2[i]) {
if (not occur2[code]) {
occur2[code] = true;
possibCnt++;
}
}
if (pos2[i + 3]) {
pos3[i] = true;
} else if ((pos3[i + 3]) &&
((str[i] != str[i + 3]) || (str[i + 1] != str[i + 4]) ||
(str[i + 2] != str[i + 5]))) {
pos3[i] = true;
}
code = code * 26 + str[i + 2] - 'a';
if (pos3[i]) {
if (not occur3[code]) {
occur3[code] = true;
possibCnt++;
}
}
}
printf("%i\n", possibCnt);
code = 0;
for (int32_t f = 0; f < LETT; f++) {
for (int32_t s = 0; s < LETT; s++) {
code = f * 26 + s;
if (occur2[code]) {
printf("%c%c\n", f + 'a', s + 'a');
}
code *= 26;
for (int32_t t = 0; t < LETT; t++) {
if (occur3[code]) {
printf("%c%c%c\n", f + 'a', s + 'a', t + 'a');
}
code++;
}
}
}
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > dp;
set<string> S;
string s;
vector<vector<string> > Substr;
vector<int> Len;
int solve(int index, int mode) {
if (dp[index][mode] != -1) return dp[index][mode];
if (index + 1 <= 4) return dp[index][mode] = 0;
if (Substr[index - 1][2] != Substr[index + 1][Len[mode]]) {
if (solve(index - 2, 0)) {
S.insert(Substr[index - 1][2]);
}
}
if (Substr[index - 2][3] != Substr[index + 1][Len[mode]]) {
if (solve(index - 3, 1)) {
S.insert(Substr[index - 2][3]);
}
}
return dp[index][mode] = 1;
}
int main() {
cin >> s;
Len.assign(2, 0);
Len[0] = 2;
Len[1] = 3;
int n = (s).size();
dp.assign(n, vector<int>(2, -1));
Substr.assign(n, vector<string>(4, " "));
for (int i = 0 - (0 > n); i != n - (0 > n); i += 1 - 2 * (0 > n)) {
for (int j = i - (i > n); j != n - (i > n); j += 1 - 2 * (i > n)) {
if (j - i + 1 > 3) continue;
Substr[i][j - i + 1] = s.substr(i, j - i + 1);
}
}
if (solve(n - 3, 0)) S.insert(Substr[n - 2][Len[0]]);
if (solve(n - 4, 1)) S.insert(Substr[n - 3][Len[1]]);
cout << (S).size() << "\n";
for (auto& e : S) {
cout << e << "\n";
}
return 0;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | #include <bits/stdc++.h>
using namespace std;
long long int dp2[10004] = {0}, dp3[10004] = {0};
set<string> ans;
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string s, s1, s2;
cin >> s;
long long int n = s.length();
if (n < 7) {
cout << 0 << endl;
return 0;
}
dp2[n - 2] = 1;
dp3[n - 3] = 1;
for (long long int i = n - 4; i >= 4; i--) {
if (dp3[i + 2]) dp2[i] = 1;
s1 = s.substr(i, 2);
s2 = s.substr(i + 2, 2);
if (s1.compare(s2) && dp2[i + 2]) dp2[i] = 1;
if (dp2[i + 3]) dp3[i] = 1;
s1 = s.substr(i, 3);
s2 = s.substr(i + 3, 3);
if (s1.compare(s2) && dp3[i + 3]) dp3[i] = 1;
}
set<string> ans;
for (long long int i = n - 2; i > 4; i--) {
if (dp2[i]) ans.insert(s.substr(i, 2));
if (dp3[i]) ans.insert(s.substr(i, 3));
}
cout << ans.size() << endl;
for (set<string>::iterator it = ans.begin(); it != ans.end(); ++it)
cout << *it << endl;
}
| CPP |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. | 2 | 7 | # Reberland Linguistics
import sys
word = input()
suffixes = set()
possible = {(len(word), 2)}
my_set = set()
while possible:
d, x = possible.pop()
a = d + x
for i in [x, 5 - x]:
l = d - i
q = (l, i)
# if q in my_set or (l < 5) or (word[l:d] == word[d:a]):
# break
if q in my_set or (l < 5) or (word[l:d] == word[d:a]):
continue
suffixes.add(word[l:d])
possible.add(q)
my_set.add(q)
suffixes_alph = sorted(suffixes)
print(len(suffixes))
print(*suffixes_alph, sep='\n')
| PYTHON3 |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8;
const double INF = 1e100;
struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
double abs() const { return hypot(x, y); }
double arg() const { return atan2(y, x); }
Point operator*(double o) const { return Point(x * o, y * o); }
Point operator+(const Point& o) const { return Point(x + o.x, y + o.y); }
Point operator-(const Point& o) const { return Point(x - o.x, y - o.y); }
bool operator<(const Point& o) const {
return x < o.x - EPS || (x < o.x + EPS && y < o.y - EPS);
}
Point scale(double o) const { return *this * (o / abs()); }
Point rotl() const { return Point(-y, x); }
Point rotr() const { return Point(y, -x); }
};
struct Triangle {
Point p[4];
double q[3];
void init() {
p[3] = p[0];
for (int i = 0; i < 3; ++i) {
q[i] = (p[i + 1] - p[i]).abs();
}
sort(q, q + 3);
}
};
void gao(const Point& a, const Point& b, double da, double db,
vector<Point>& ret, int dump = 0) {
double sum = (b - a).abs();
double dif = (da * da - db * db) / sum;
double ra = (sum + dif) / 2;
double rb = (sum - dif) / 2;
double h = da * da - ra * ra;
if (h < -EPS) {
return;
} else {
h = sqrt(max(0.0, h));
}
Point v = (b - a).scale(h);
ret.push_back(a + (b - a).scale(ra) + v.rotl());
ret.push_back(a + (b - a).scale(ra) + v.rotr());
ret.push_back(a + (b - a).scale(rb) + v.rotl());
ret.push_back(a + (b - a).scale(rb) + v.rotr());
}
int main() {
int ans;
double e[4];
Triangle t[4];
vector<Point> v;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 3; ++j) {
scanf("%lf%lf", &t[i].p[j].x, &t[i].p[j].y);
}
t[i].init();
}
ans = 9;
for (int i = 0; i < 81; ++i) {
for (int j = 0, k = i; j < 4; ++j, k /= 3) {
e[j] = t[j].q[k % 3];
}
if (*max_element(e, e + 4) * 2 - accumulate(e, e + 4, 0.0) < EPS) {
ans = 8;
break;
}
}
for (int i = 0; i < 12; ++i) {
for (int j = (i / 3 + 1) * 3; j < 12; ++j) {
for (int k = (j / 3 + 1) * 3; k < 12; ++k) {
Point a(0, 0);
Point b(t[i / 3].q[i % 3], 0);
v.clear();
gao(a, b, t[j / 3].q[j % 3], t[k / 3].q[k % 3], v);
if (v.empty()) {
continue;
}
Point c = v[0];
vector<Point> va, vb, vc;
gao(a, b, t[i / 3].q[(i + 1) % 3], t[i / 3].q[(i + 2) % 3], va);
gao(a, c, t[j / 3].q[(j + 1) % 3], t[j / 3].q[(j + 2) % 3], vb);
gao(b, c, t[k / 3].q[(k + 1) % 3], t[k / 3].q[(k + 2) % 3], vc);
for (const Point& pa : va) {
for (const Point& pb : vb) {
for (const Point& pc : vc) {
set<Point> st = {a, b, c, pa, pb, pc};
ans = min(ans, (int)st.size() + 2);
for (int l = 0; l < 12; ++l) {
if (i / 3 + j / 3 + k / 3 + l / 3 != 6) {
continue;
}
for (const Point& u : st) {
for (const Point& v : st) {
if (fabs((u - v).abs() - t[l / 3].q[l % 3]) > EPS) {
continue;
}
vector<Point> vd;
gao(u, v, t[l / 3].q[(l + 1) % 3], t[l / 3].q[(l + 2) % 3],
vd);
for (const Point& pd : vd) {
ans = min(ans, (int)st.size() + 1 - (int)st.count(pd));
}
}
}
}
}
}
}
}
}
}
int tmp = 3;
for (int i = 1; i < 4; ++i) {
int acc = 2;
for (int j = 0; j < i; ++j) {
bool same = true;
for (int k = 0; k < 3 && same; ++k) {
same &= fabs(t[i].q[k] - t[j].q[k]) < EPS;
}
if (same) {
acc = 0;
break;
}
}
for (int j = 0; j < 3 * i && acc > 1; ++j) {
for (int k = 0; k < 3; ++k) {
if (fabs(t[j / 3].q[j % 3] - t[i].q[k]) < EPS) {
acc = 1;
break;
}
}
}
tmp += acc;
}
ans = min(ans, tmp);
printf("%d\n", ans);
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
struct point {
double x, y;
};
double dist(point P, point Q) {
double dx = P.x - Q.x, dy = P.y - Q.y;
return sqrt(dx * dx + dy * dy);
}
vector<point> cccross(point O1, double r1, point O2, double r2) {
double d = dist(O1, O2);
double t = (d * d + r1 * r1 - r2 * r2) / 2.0 / d / d;
double fx = O1.x + (O2.x - O1.x) * t, fy = O1.y + (O2.y - O1.y) * t;
double h = sqrt(r1 * r1 - t * d * t * d);
double dx = (O2.y - O1.y) / d * h, dy = (O1.x - O2.x) / d * h;
vector<point> ans;
point ans1 = {fx + dx, fy + dy};
ans.push_back(ans1);
point ans2 = {fx - dx, fy - dy};
ans.push_back(ans2);
return ans;
}
vector<double> tri[10];
void read(int id) {
point P, Q, R;
cin >> P.x >> P.y >> Q.x >> Q.y >> R.x >> R.y;
tri[id].push_back(dist(P, Q));
tri[id].push_back(dist(P, R));
tri[id].push_back(dist(Q, R));
sort(tri[id].begin(), tri[id].end());
}
bool quad(double a, double b, double c, double d) {
double x[] = {a, b, c, d};
sort(x, x + 4);
return (x[0] + x[1] + x[2] + 1.0E-9 > x[3]);
}
bool triineq(double a, double b, double c) {
double x[] = {a, b, c};
sort(x, x + 3);
return (x[0] + x[1] + 1.0E-9 > x[2]);
}
bool equals(double x, double y) { return (x - y < 1.0E-9 && x - y > -1.0E-9); }
int N;
point P[20];
int a[(1 << 4)], dp[(1 << 4)];
void dfs(int mask) {
int i, x, y, z;
a[mask] = min(a[mask], N);
for ((i) = 0; (i) < (int)(4); (i)++)
if (!(mask & (1 << i))) {
int mask2 = (mask | (1 << i));
bool found = false;
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++)
for ((z) = 0; (z) < (int)(N); (z)++) {
if (equals(dist(P[x], P[y]), tri[i][0]) &&
equals(dist(P[x], P[z]), tri[i][1]) &&
equals(dist(P[y], P[z]), tri[i][2])) {
dfs(mask2);
found = true;
}
}
if (!found)
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++) {
if (equals(dist(P[x], P[y]), tri[i][0])) {
N++;
P[N - 1] = cccross(P[x], tri[i][1], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][1], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][1])) {
N++;
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][2])) {
N++;
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][1])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][1])[1];
dfs(mask2);
N--;
}
}
}
}
vector<point> allcross(point O1, double r1, point O2, double r2) {
vector<point> ans = cccross(O1, r1, O2, r2);
vector<point> ans2 = cccross(O1, r2, O2, r1);
ans.push_back(ans2[0]);
ans.push_back(ans2[1]);
return ans;
}
void init(void) {
int a, b, c, i, j, k, x, y, z, mask;
for ((i) = 0; (i) < (int)(4); (i)++) {
N = 3;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[i][0];
P[2] = cccross(P[0], tri[i][1], P[1], tri[i][2])[0];
dfs(1 << i);
}
for ((a) = 0; (a) < (int)(4); (a)++)
for ((b) = 0; (b) < (int)(a); (b)++)
for ((c) = 0; (c) < (int)(b); (c)++)
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++) {
if (triineq(tri[a][i], tri[b][j], tri[c][k])) {
N = 6;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[a][i];
P[2] = cccross(P[0], tri[b][j], P[1], tri[c][k])[0];
vector<point> three = allcross(P[0], tri[a][(i + 1) % 3], P[1],
tri[a][(i + 2) % 3]);
vector<point> four = allcross(P[0], tri[b][(j + 1) % 3], P[2],
tri[b][(j + 2) % 3]);
vector<point> five = allcross(P[1], tri[c][(k + 1) % 3], P[2],
tri[c][(k + 2) % 3]);
for ((x) = 0; (x) < (int)(4); (x)++)
for ((y) = 0; (y) < (int)(4); (y)++)
for ((z) = 0; (z) < (int)(4); (z)++) {
P[3] = three[x];
P[4] = four[y];
P[5] = five[z];
dfs((1 << a) | (1 << b) | (1 << c));
}
}
}
}
int main(void) {
int i, j, k, l;
for ((i) = 0; (i) < (int)(4); (i)++) read(i);
int ans = 9;
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++)
for ((l) = 0; (l) < (int)(3); (l)++)
if (quad(tri[0][i], tri[1][j], tri[2][k], tri[3][l])) ans = 8;
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) a[i] = (1 << 29);
a[0] = 0;
init();
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) {
dp[i] = a[i];
for (j = 1; j < i; j++)
if ((i & j) == j) dp[i] = min(dp[i], dp[j] + a[i ^ j] - 1);
}
ans = min(ans, dp[15]);
cout << ans << endl;
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
int n, m, k;
bool debug = false;
struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
double abs() const { return hypot(x, y); }
double arg() const { return atan2(y, x); }
Point operator*(double o) const { return Point(x * o, y * o); }
Point operator+(const Point& o) const { return Point(x + o.x, y + o.y); }
Point operator-(const Point& o) const { return Point(x - o.x, y - o.y); }
bool operator<(const Point& o) const {
return x < o.x - 1e-9 || (x < o.x + 1e-9 && y < o.y - 1e-9);
}
Point scale(double o) const { return *this * (o / abs()); }
Point rotY() const { return Point(-y, x); }
Point rotX() const { return Point(y, -x); }
};
struct Tirangle {
Point p[3];
double len[3];
void init() {
for (int i = 0; i < 3; i++) {
len[i] = (p[(i + 1) % 3] - p[i]).abs();
}
sort(len, len + 3);
}
};
void makeT(const Point& a, const Point& b, double da, double db,
vector<Point>& ret, int dump = 0) {
double sum = (a - b).abs();
double dif = (da * da - db * db) / sum;
double ra = (sum + dif) / 2;
double rb = (sum - dif) / 2;
double h = da * da - ra * ra;
if (h < -1e-9) {
return;
} else {
h = sqrt(max(0.0, h));
}
Point v = (b - a).scale(h);
ret.push_back(a + (b - a).scale(ra) + v.rotY());
ret.push_back(a + (b - a).scale(ra) + v.rotX());
ret.push_back(a + (b - a).scale(rb) + v.rotY());
ret.push_back(a + (b - a).scale(rb) + v.rotX());
}
Tirangle t[4];
int main() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
scanf("%lf%lf", &t[i].p[j].x, &t[i].p[j].y);
}
t[i].init();
}
int ans = 9;
double edge[4];
for (int i = 0; i < 81; i++) {
for (int j = 0, k = i; j < 4; j++, k /= 3) {
edge[j] = t[j].len[k % 3];
}
if (*max_element(edge, edge + 4) * 2 - accumulate(edge, edge + 4, 0.0) <
1e-9) {
ans = 8;
break;
}
}
vector<Point> v;
for (int i = 0; i < 12; ++i) {
for (int j = (i / 3 + 1) * 3; j < 12; ++j) {
for (int k = (j / 3 + 1) * 3; k < 12; ++k) {
Point a(0, 0);
Point b(t[i / 3].len[i % 3], 0);
v.clear();
makeT(a, b, t[j / 3].len[j % 3], t[k / 3].len[k % 3], v);
if (v.empty()) {
continue;
}
Point c = v[0];
vector<Point> va, vb, vc;
makeT(a, b, t[i / 3].len[(i + 1) % 3], t[i / 3].len[(i + 2) % 3], va);
makeT(a, c, t[j / 3].len[(j + 1) % 3], t[j / 3].len[(j + 2) % 3], vb);
makeT(b, c, t[k / 3].len[(k + 1) % 3], t[k / 3].len[(k + 2) % 3], vc);
for (const Point& pa : va) {
for (const Point& pb : vb) {
for (const Point& pc : vc) {
set<Point> st = {a, b, c, pa, pb, pc};
ans = min(ans, (int)st.size() + 2);
for (int l = 0; l < 12; ++l) {
if (i / 3 + j / 3 + k / 3 + l / 3 != 6) {
continue;
}
for (const Point& u : st) {
for (const Point& v : st) {
if (fabs((u - v).abs() - t[l / 3].len[l % 3]) > 1e-9) {
continue;
}
vector<Point> vd;
makeT(u, v, t[l / 3].len[(l + 1) % 3],
t[l / 3].len[(l + 2) % 3], vd);
for (const Point& pd : vd) {
ans = min(ans, (int)st.size() + 1 - (int)st.count(pd));
}
}
}
}
}
}
}
}
}
}
int tmp = 3;
for (int i = 1; i < 4; ++i) {
int acc = 2;
for (int j = 0; j < i; ++j) {
bool same = true;
for (int k = 0; k < 3 && same; ++k) {
same &= fabs(t[i].len[k] - t[j].len[k]) < 1e-9;
}
if (same) {
acc = 0;
break;
}
}
for (int j = 0; j < 3 * i && acc > 1; ++j) {
for (int k = 0; k < 3; ++k) {
if (fabs(t[j / 3].len[j % 3] - t[i].len[k]) < 1e-9) {
acc = 1;
break;
}
}
}
tmp += acc;
}
ans = min(ans, tmp);
printf("%d\n", ans);
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
struct point {
double x, y;
};
double dist(point P, point Q) {
double dx = P.x - Q.x, dy = P.y - Q.y;
return sqrt(dx * dx + dy * dy);
}
vector<point> cccross(point O1, double r1, point O2, double r2) {
double d = dist(O1, O2);
double t = (d * d + r1 * r1 - r2 * r2) / 2.0 / d / d;
double fx = O1.x + (O2.x - O1.x) * t, fy = O1.y + (O2.y - O1.y) * t;
double h = sqrt(r1 * r1 - t * d * t * d);
double dx = (O2.y - O1.y) / d * h, dy = (O1.x - O2.x) / d * h;
vector<point> ans;
point ans1 = {fx + dx, fy + dy};
ans.push_back(ans1);
point ans2 = {fx - dx, fy - dy};
ans.push_back(ans2);
return ans;
}
vector<double> tri[10];
void read(int id) {
point P, Q, R;
cin >> P.x >> P.y >> Q.x >> Q.y >> R.x >> R.y;
tri[id].push_back(dist(P, Q));
tri[id].push_back(dist(P, R));
tri[id].push_back(dist(Q, R));
sort(tri[id].begin(), tri[id].end());
}
bool quad(double a, double b, double c, double d) {
double x[] = {a, b, c, d};
sort(x, x + 4);
return (x[0] + x[1] + x[2] + 1.0E-9 > x[3]);
}
bool triineq(double a, double b, double c) {
double x[] = {a, b, c};
sort(x, x + 3);
return (x[0] + x[1] + 1.0E-9 > x[2]);
}
bool equals(double x, double y) { return (x - y < 1.0E-9 && x - y > -1.0E-9); }
int N;
point P[20];
int a[(1 << 4)], dp[(1 << 4)];
void dfs(int mask) {
int i, x, y, z;
a[mask] = min(a[mask], N);
for ((i) = 0; (i) < (int)(4); (i)++)
if (!(mask & (1 << i))) {
int mask2 = (mask | (1 << i));
bool found = false;
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++)
for ((z) = 0; (z) < (int)(N); (z)++) {
if (equals(dist(P[x], P[y]), tri[i][0]) &&
equals(dist(P[x], P[z]), tri[i][1]) &&
equals(dist(P[y], P[z]), tri[i][2])) {
dfs(mask2);
found = true;
}
}
if (!found)
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++) {
if (equals(dist(P[x], P[y]), tri[i][0])) {
N++;
P[N - 1] = cccross(P[x], tri[i][1], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][1], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][1])) {
N++;
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][2])) {
N++;
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][1])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][1])[1];
dfs(mask2);
N--;
}
}
}
}
vector<point> allcross(point O1, double r1, point O2, double r2) {
vector<point> ans = cccross(O1, r1, O2, r2);
vector<point> ans2 = cccross(O1, r2, O2, r1);
ans.push_back(ans2[0]);
ans.push_back(ans2[1]);
return ans;
}
void init(void) {
int a, b, c, i, j, k, x, y, z, mask;
for ((i) = 0; (i) < (int)(4); (i)++) {
N = 3;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[i][0];
P[2] = cccross(P[0], tri[i][1], P[1], tri[i][2])[0];
dfs(1 << i);
}
for ((a) = 0; (a) < (int)(4); (a)++)
for ((b) = 0; (b) < (int)(a); (b)++)
for ((c) = 0; (c) < (int)(b); (c)++)
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++) {
if (triineq(tri[a][i], tri[b][j], tri[c][k])) {
N = 6;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[a][i];
P[2] = cccross(P[0], tri[b][j], P[1], tri[c][k])[0];
vector<point> three = allcross(P[0], tri[a][(i + 1) % 3], P[1],
tri[a][(i + 2) % 3]);
vector<point> four = allcross(P[0], tri[b][(j + 1) % 3], P[2],
tri[b][(j + 2) % 3]);
vector<point> five = allcross(P[1], tri[c][(k + 1) % 3], P[2],
tri[c][(k + 2) % 3]);
for ((x) = 0; (x) < (int)(4); (x)++)
for ((y) = 0; (y) < (int)(4); (y)++)
for ((z) = 0; (z) < (int)(4); (z)++) {
P[3] = three[x];
P[4] = four[y];
P[5] = five[z];
dfs((1 << a) | (1 << b) | (1 << c));
}
}
}
}
int main(void) {
int i, j, k, l;
for ((i) = 0; (i) < (int)(4); (i)++) read(i);
int ans = 9;
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++)
for ((l) = 0; (l) < (int)(3); (l)++)
if (quad(tri[0][i], tri[1][j], tri[2][k], tri[3][l])) ans = 8;
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) a[i] = (1 << 29);
a[0] = 0;
init();
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) {
dp[i] = a[i];
for (j = 1; j < i; j++)
if ((i & j) == j) dp[i] = min(dp[i], dp[j] + a[i ^ j] - 1);
}
ans = min(ans, dp[15]);
cout << ans << endl;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
double e[4][3], x[10], y[10], tx[4][3], ty[4][3];
bool used[4];
int ans;
int sgn(double a) { return a < -1e-8 ? -1 : a > 1e-8 ? 1 : 0; }
vector<pair<double, double>> solve(double x1, double y1, double x2, double y2,
double l, double l1, double l2) {
if (sgn(l + l1 - l2) < 0 || sgn(l + l2 - l1) < 0 || sgn(l2 + l1 - l) < 0)
return {};
double vx = x2 - x1, vy = y2 - y1, ux = -vy, uy = vx;
double a = ((l1 * l1 - l2 * l2) / l / l + 1) / 2;
double d = l1 * l1 / l / l - a * a;
if (!sgn(d)) return {{x1 + a * vx, y1 + a * vy}};
double b = sqrt(d);
return {{x1 + a * vx + b * ux, y1 + a * vy + b * uy},
{x1 + a * vx - b * ux, y1 + a * vy - b * uy}};
}
bool check8() {
for (int wb = 0; wb < 81; ++wb) {
int w[4] = {wb % 3, wb / 3 % 3, wb / 9 % 3, wb / 27 % 3};
double s = 0, m = 0;
for (int i = 0; i < 4; ++i) {
s += e[i][w[i]];
m = max(m, e[i][w[i]]);
}
if (sgn(s - m - m) >= 0) return true;
}
return false;
}
int reduce(int ot, int t) {
for (int i = t - 1; i >= ot; --i) {
for (int j = 0; j < i; ++j)
if (!sgn(x[j] - x[i]) && !sgn(y[j] - y[i])) {
x[i] = x[t - 1];
y[i] = y[t - 1];
--t;
break;
}
}
return t;
}
void dfs(int t) {
ans = min(ans, t + (!used[0] + !used[1] + !used[2] + !used[3]) * 2);
if (t >= ans) return;
if (used[0] && used[1] && used[2] && used[3]) {
ans = t;
return;
}
for (int i = 0; i < t; ++i)
for (int j = 0; j < t; ++j)
if (i != j) {
double l2 =
(x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
double l = hypot(x[i] - x[j], y[i] - y[j]);
for (int k = 0; k <= 3; ++k)
if (!used[k]) {
used[k] = true;
for (int z = 0; z < 3; ++z)
if (!sgn(e[k][z] * e[k][z] - l2)) {
double k1 = e[k][(z + 1) % 3], k2 = e[k][(z + 2) % 3];
for (auto [nx, ny] : solve(x[i], y[i], x[j], y[j], l, k1, k2)) {
x[t] = nx;
y[t] = ny;
dfs(reduce(t, t + 1));
}
}
used[k] = false;
}
for (int p = 0; p <= 3; ++p)
if (!used[p])
for (int q = p + 1; q <= 3; ++q)
if (!used[q]) {
used[p] = used[q] = true;
for (int zp = 0; zp < 3; ++zp) {
double lp = e[p][zp], lp1 = e[p][(zp + 1) % 3],
lp2 = e[p][(zp + 2) % 3];
for (int zq = 0; zq < 3; ++zq) {
double lq = e[q][zq], lq1 = e[q][(zq + 1) % 3],
lq2 = e[q][(zq + 2) % 3];
for (auto [nx, ny] :
solve(x[i], y[i], x[j], y[j], l, lp, lq)) {
x[t] = nx, y[t] = ny;
auto pl = solve(x[i], y[i], nx, ny, lp, lp1, lp2);
for (auto pl2 : solve(x[i], y[i], nx, ny, lp, lp2, lp1))
pl.push_back(pl2);
auto ql = solve(x[j], y[j], nx, ny, lq, lq1, lq2);
for (auto ql2 : solve(x[j], y[j], nx, ny, lq, lq2, lq1))
ql.push_back(ql2);
for (auto [px, py] : pl)
for (auto [qx, qy] : ql) {
x[t + 1] = px, y[t + 1] = py;
x[t + 2] = qx, y[t + 2] = qy;
dfs(reduce(t, t + 3));
}
}
}
}
used[p] = used[q] = false;
}
}
}
int main() {
for (int i = 0; i < 4; ++i) {
scanf("%lf%lf%lf%lf%lf%lf", &tx[i][0], &ty[i][0], &tx[i][1], &ty[i][1],
&tx[i][2], &ty[i][2]);
e[i][0] = hypot(tx[i][0] - tx[i][1], ty[i][0] - ty[i][1]);
e[i][1] = hypot(tx[i][0] - tx[i][2], ty[i][0] - ty[i][2]);
e[i][2] = hypot(tx[i][2] - tx[i][1], ty[i][2] - ty[i][1]);
sort(e[i], e[i] + 3);
}
ans = 9;
if (check8()) --ans;
for (int i = 0; i < 4; ++i) {
used[i] = true;
x[0] = tx[i][0];
y[0] = ty[i][0];
x[1] = tx[i][1];
y[1] = ty[i][1];
x[2] = tx[i][2];
y[2] = ty[i][2];
dfs(3);
used[i] = false;
}
cout << ans << endl;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
struct point {
double x, y;
};
double dist(point P, point Q) {
double dx = P.x - Q.x, dy = P.y - Q.y;
return sqrt(dx * dx + dy * dy);
}
vector<point> cccross(point O1, double r1, point O2, double r2) {
double d = dist(O1, O2);
double t = (d * d + r1 * r1 - r2 * r2) / 2.0 / d / d;
double fx = O1.x + (O2.x - O1.x) * t, fy = O1.y + (O2.y - O1.y) * t;
double h = sqrt(r1 * r1 - t * d * t * d);
double dx = (O2.y - O1.y) / d * h, dy = (O1.x - O2.x) / d * h;
vector<point> ans;
point ans1 = {fx + dx, fy + dy};
ans.push_back(ans1);
point ans2 = {fx - dx, fy - dy};
ans.push_back(ans2);
return ans;
}
vector<double> tri[10];
void read(int id) {
point P, Q, R;
cin >> P.x >> P.y >> Q.x >> Q.y >> R.x >> R.y;
tri[id].push_back(dist(P, Q));
tri[id].push_back(dist(P, R));
tri[id].push_back(dist(Q, R));
sort(tri[id].begin(), tri[id].end());
}
bool quad(double a, double b, double c, double d) {
double x[] = {a, b, c, d};
sort(x, x + 4);
return (x[0] + x[1] + x[2] + 1.0E-9 > x[3]);
}
bool triineq(double a, double b, double c) {
double x[] = {a, b, c};
sort(x, x + 3);
return (x[0] + x[1] + 1.0E-9 > x[2]);
}
bool equals(double x, double y) { return (x - y < 1.0E-9 && x - y > -1.0E-9); }
int N;
point P[20];
int a[(1 << 4)], dp[(1 << 4)];
void dfs(int mask) {
int i, x, y, z;
a[mask] = min(a[mask], N);
for ((i) = 0; (i) < (int)(4); (i)++)
if (!(mask & (1 << i))) {
int mask2 = (mask | (1 << i));
bool found = false;
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++)
for ((z) = 0; (z) < (int)(N); (z)++) {
if (equals(dist(P[x], P[y]), tri[i][0]) &&
equals(dist(P[x], P[z]), tri[i][1]) &&
equals(dist(P[y], P[z]), tri[i][2])) {
dfs(mask2);
found = true;
}
}
if (!found)
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++) {
if (equals(dist(P[x], P[y]), tri[i][0])) {
N++;
P[N - 1] = cccross(P[x], tri[i][1], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][1], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][1])) {
N++;
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][2])) {
N++;
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][1])[0];
dfs(mask2);
P[N - 1] = cccross(P[x], tri[i][0], P[y], tri[i][1])[1];
dfs(mask2);
N--;
}
}
}
}
vector<point> allcross(point O1, double r1, point O2, double r2) {
vector<point> ans = cccross(O1, r1, O2, r2);
vector<point> ans2 = cccross(O1, r2, O2, r1);
ans.push_back(ans2[0]);
ans.push_back(ans2[1]);
return ans;
}
void init(void) {
int a, b, c, i, j, k, x, y, z, mask;
for ((i) = 0; (i) < (int)(4); (i)++) {
N = 3;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[i][0];
P[2] = cccross(P[0], tri[i][1], P[1], tri[i][2])[0];
dfs(1 << i);
}
for ((a) = 0; (a) < (int)(4); (a)++)
for ((b) = 0; (b) < (int)(a); (b)++)
for ((c) = 0; (c) < (int)(b); (c)++)
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++) {
if (triineq(tri[a][i], tri[b][j], tri[c][k])) {
N = 6;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[a][i];
P[2] = cccross(P[0], tri[b][j], P[1], tri[c][k])[0];
vector<point> three = allcross(P[0], tri[a][(i + 1) % 3], P[1],
tri[a][(i + 2) % 3]);
vector<point> four = allcross(P[0], tri[b][(j + 1) % 3], P[2],
tri[b][(j + 2) % 3]);
vector<point> five = allcross(P[1], tri[c][(k + 1) % 3], P[2],
tri[c][(k + 2) % 3]);
for ((x) = 0; (x) < (int)(4); (x)++)
for ((y) = 0; (y) < (int)(4); (y)++)
for ((z) = 0; (z) < (int)(4); (z)++) {
P[3] = three[x];
P[4] = four[y];
P[5] = five[z];
dfs((1 << a) | (1 << b) | (1 << c));
}
}
}
}
int main(void) {
int i, j, k, l;
for ((i) = 0; (i) < (int)(4); (i)++) read(i);
int ans = 9;
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++)
for ((l) = 0; (l) < (int)(3); (l)++)
if (quad(tri[0][i], tri[1][j], tri[2][k], tri[3][l])) ans = 8;
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) a[i] = (1 << 29);
a[0] = 0;
init();
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) {
dp[i] = a[i];
for (j = 1; j < i; j++)
if ((i & j) == j) dp[i] = min(dp[i], dp[j] + a[i ^ j] - 1);
}
ans = min(ans, dp[15]);
cout << ans << endl;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
struct Point {
double x, y;
Point(double _x = 0, double _y = 0) {
x = _x;
y = _y;
}
};
int result;
Point p[4][3], e[4][3], pts[12];
double dst[12][12];
int permutation[4];
void rotate(Point &p, double d) {
double cosd = cos(d);
double sind = sin(d);
double x = p.x * cosd - p.y * sind;
double y = p.x * sind + p.y * cosd;
p.x = x;
p.y = y;
}
double ppDistance(const Point &a, const Point &b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
double sqr(double x) { return x * x; }
int getIntersect(double X1, double Y1, double R1, double X2, double Y2,
double R2, Point &P, Point &Q) {
double dst = ppDistance(Point(X1, Y1), Point(X2, Y2));
if (dst > R1 + R2 + eps || dst < fabs(R1 - R2) - eps) return 0;
if (dst <= eps) return 0;
double a = X1 - X2;
double b = Y1 - Y2;
double c = -(a * (X1 + X2) + b * (Y1 + Y2) - sqr(R1) + sqr(R2)) / 2.0;
double CX = X1, CY = Y1;
double x1, y1, x2, y2;
if (fabs(a) > fabs(b)) {
double A = sqr(a) + sqr(b);
double B = 2.0 * b * (c + a * CX) - 2.0 * sqr(a) * CY;
double C = sqr(c + a * CX) + sqr(a) * (sqr(CY) - sqr(R1));
double delta = sqr(B) - 4 * A * C;
if (delta < -eps) return 0;
if (delta < 0) delta = 0;
delta = sqrt(delta);
y1 = (-B + delta) / (2 * A);
x1 = (-c - b * y1) / a;
y2 = (-B - delta) / (2 * A);
x2 = (-c - b * y2) / a;
P.x = x1;
P.y = y1;
Q.x = x2;
Q.y = y2;
} else {
swap(a, b);
swap(CX, CY);
double A = sqr(a) + sqr(b);
double B = 2.0 * b * (c + a * CX) - 2.0 * sqr(a) * CY;
double C = sqr(c + a * CX) + sqr(a) * (sqr(CY) - sqr(R1));
double delta = sqr(B) - 4 * A * C;
if (delta < -eps) return 0;
if (delta < 0) delta = 0;
delta = sqrt(delta);
y1 = (-B + delta) / (2 * A);
x1 = (-c - b * y1) / a;
y2 = (-B - delta) / (2 * A);
x2 = (-c - b * y2) / a;
swap(x1, y1);
swap(x2, y2);
swap(a, b);
swap(CX, CY);
P.x = x1;
P.y = y1;
Q.x = x2;
Q.y = y2;
}
return 2;
}
void DFS(int d) {
if (d == 3) {
int m = 0;
for (int i = 0; i < d; i++)
for (int j = 0; j < 3; j++) {
bool is_exists = false;
for (int k = 0; !is_exists && k < m; k++)
if (fabs(e[i][j].x - pts[k].x) <= eps &&
fabs(e[i][j].y - pts[k].y) <= eps)
is_exists = true;
if (!is_exists) pts[m++] = e[i][j];
}
if (m >= result) return;
if (m + 2 < result) {
result = m + 2;
}
double l1 = ppDistance(p[d][0], p[d][1]);
double l2 = ppDistance(p[d][0], p[d][2]);
double l3 = ppDistance(p[d][1], p[d][2]);
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
dst[i][j] =
(i == j) ? 0 : ((i > j) ? dst[j][i] : ppDistance(pts[i], pts[j]));
for (int i = 0; i < m; i++)
for (int j = i + 1; j < m; j++)
if (fabs(dst[i][j] - l1) <= eps)
for (int k = 0; k < m; k++)
if (fabs(dst[i][k] - l2) <= eps && fabs(dst[j][k] - l3) <= eps ||
fabs(dst[i][k] - l3) <= eps && fabs(dst[j][k] - l2) <= eps) {
result = m;
return;
}
if (m + 1 >= result) return;
for (int i = 0; i < m; i++)
for (int j = i + 1; j < m; j++)
if (fabs(dst[i][j] - l1) <= eps || fabs(dst[i][j] - l2) <= eps ||
fabs(dst[i][j] - l3) <= eps) {
result = m + 1;
return;
}
return;
}
bool dup[12];
memset(dup, false, sizeof(dup));
for (int i = 0; i < d * 3; i++)
for (int j = i + 1; j < d * 3; j++) {
Point p1 = e[i / 3][i % 3];
Point p2 = e[j / 3][j % 3];
if (fabs(p1.x - p2.x) <= eps && fabs(p1.y - p2.y) <= eps) dup[j] = true;
}
for (int i = 0; i < d * 3; i++)
if (!dup[i])
for (int j = 0; j < d * 3; j++)
if (!dup[j]) {
if (i == j) continue;
Point p1 = e[i / 3][i % 3];
Point p2 = e[j / 3][j % 3];
if (fabs(p1.x - p2.x) <= eps && fabs(p1.y - p2.y) <= eps) continue;
Point g1 = Point(p[d][1].x - p[d][0].x, p[d][1].y - p[d][0].y);
Point g2 = Point(p[d][2].x - p[d][0].x, p[d][2].y - p[d][0].y);
double rot = atan2(p2.y - p1.y, p2.x - p1.x) - atan2(g1.y, g1.x);
rotate(g1, rot);
rotate(g2, rot);
e[d][0] = p1;
e[d][1] = Point(p1.x + g1.x, p1.y + g1.y);
e[d][2] = Point(p1.x + g2.x, p1.y + g2.y);
DFS(d + 1);
}
if (d == 1 && permutation[1] < permutation[2])
for (int i = 0; i < d * 3; i++)
if (!dup[i])
for (int j = 0; j < d * 3; j++)
if (!dup[j]) {
if (i == j) continue;
Point p1 = e[i / 3][i % 3];
Point p2 = e[j / 3][j % 3];
if (fabs(p1.x - p2.x) <= eps && fabs(p1.y - p2.y) <= eps) continue;
double l1 = ppDistance(p[d][0], p[d][1]);
double l2 = ppDistance(p[d + 1][0], p[d + 1][1]);
Point h[2];
int c = getIntersect(p1.x, p1.y, l1, p2.x, p2.y, l2, h[0], h[1]);
for (int k = 0; k < c; k++) {
Point g1 = Point(p[d][1].x - p[d][0].x, p[d][1].y - p[d][0].y);
Point g2 = Point(p[d][2].x - p[d][0].x, p[d][2].y - p[d][0].y);
double rot =
atan2(h[k].y - p1.y, h[k].x - p1.x) - atan2(g1.y, g1.x);
rotate(g1, rot);
rotate(g2, rot);
e[d][0] = p1;
e[d][1] = Point(p1.x + g1.x, p1.y + g1.y);
e[d][2] = Point(p1.x + g2.x, p1.y + g2.y);
DFS(d + 1);
}
}
if (d == 2 && permutation[2] < permutation[3]) {
int m = 0;
for (int i = 0; i < d; i++)
for (int j = 0; j < 3; j++) {
bool is_exists = false;
for (int k = 0; !is_exists && k < m; k++)
if (fabs(e[i][j].x - pts[k].x) <= eps &&
fabs(e[i][j].y - pts[k].y) <= eps)
is_exists = true;
if (!is_exists) pts[m++] = e[i][j];
}
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
if (i != j)
for (int k = 0; k < 3; k++) {
Point p1 = pts[i];
Point p2 = pts[j];
if (fabs(p1.x - p2.x) <= eps && fabs(p1.y - p2.y) <= eps) continue;
double l1 = ppDistance(p[d][0], p[d][1]);
double l2 = ppDistance(p[d + 1][k], p[d + 1][(k + 1) % 3]);
Point h[2];
int c = getIntersect(p1.x, p1.y, l1, p2.x, p2.y, l2, h[0], h[1]);
for (int u = 0; u < c; u++) {
Point g1 = Point(p[d][1].x - p[d][0].x, p[d][1].y - p[d][0].y);
Point g2 = Point(p[d][2].x - p[d][0].x, p[d][2].y - p[d][0].y);
double rot =
atan2(h[u].y - p1.y, h[u].x - p1.x) - atan2(g1.y, g1.x);
rotate(g1, rot);
rotate(g2, rot);
e[d][0] = p1;
e[d][1] = Point(p1.x + g1.x, p1.y + g1.y);
e[d][2] = Point(p1.x + g2.x, p1.y + g2.y);
DFS(d + 1);
}
}
}
}
int main() {
Point a[4][3];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) {
double x, y;
scanf("%lf%lf", &x, &y);
a[i][j] = Point(x, y);
}
result = 12;
for (int i = 0; i < 4; i++) permutation[i] = i;
do {
for (int mset = 0; mset < (1 << 3); mset += 2)
for (int set = 0; set < (1 << 3); set += 2)
for (int rot = 0; rot < 27; rot += 3) {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) p[i][j] = a[permutation[i]][j];
for (int i = 0; i < 4; i++)
if (mset & (1 << i))
for (int j = 0; j < 3; j++) p[i][j].x = -p[i][j].x;
for (int state = rot, i = 0; i < 4; i++, state /= 3)
for (int j = 0; j < state % 3; j++) {
Point t = p[i][0];
p[i][0] = p[i][1];
p[i][1] = p[i][2];
p[i][2] = t;
}
for (int i = 0; i < 4; i++)
if (set & (1 << i)) swap(p[i][1], p[i][2]);
for (int j = 0; j < 3; j++) e[0][j] = p[0][j];
DFS(1);
}
} while (next_permutation(permutation + 1, permutation + 4) != 0);
printf("%d\n", result);
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
complex<double> leer() {
double x, y;
cin >> x >> y;
return complex<double>(x, y);
}
void leer(double input[3]) {
complex<double> in[3];
for (int i = 0; i < 3; i++) in[i] = leer();
for (int i = 0; i < 3; i++) {
int nexti = (i + 1) % 3;
input[i] = abs(in[nexti] - in[i]);
}
}
struct punt {
double x, y;
};
punt point2punt(complex<double> p) {
punt pp;
pp.x = real(p);
pp.y = imag(p);
return pp;
}
complex<double> punt2point(punt p) { return complex<double>(p.x, p.y); }
double error = 1e-5;
bool menor(double x, double y) { return x < y - error; }
bool menorigual(double x, double y) { return x < y + error; }
bool igual(double x, double y) { return x > y - error and x < y + error; }
bool operator<(punt p1, punt p2) {
return menor(p1.x, p2.x) or (igual(p1.x, p2.x) and menor(p1.y, p2.y));
}
double t[4][3];
int sol = 9;
void calculaciclo4() {
int total = 3 * 3 * 3 * 3;
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
longitud[i] = t[i][b];
}
if (menorigual(longitud[0], longitud[3]) and
menorigual(longitud[1], longitud[3]) and
menorigual(longitud[2], longitud[3]) and
menorigual(longitud[3], longitud[0] + longitud[1] + longitud[2])) {
sol = min(sol, 8);
return;
}
}
}
complex<double> elige(double a, double b, double c, int indice) {
if (indice == 0 or indice == 1) {
double alfa = acos((a * a + b * b - c * c) / (2.0 * a * b));
if (indice == 0) return complex<double>(b * cos(alfa), b * sin(alfa));
return complex<double>(b * cos(alfa), -b * sin(alfa));
}
double alfa = acos((a * a + c * c - b * b) / (2.0 * a * c));
if (indice == 2) return complex<double>(c * cos(alfa), c * sin(alfa));
return complex<double>(c * cos(alfa), -c * sin(alfa));
}
void calculaciclo4con2() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
double longi[3];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (not igual(longitud[0], longitud[1])) continue;
for (int i0 = 0; i0 < 4; i0++) {
complex<double> p0 =
elige(eleccion[0][0], eleccion[0][1], eleccion[0][2], i0);
for (int i1 = 0; i1 < 4; i1++) {
complex<double> p1 =
elige(eleccion[1][0], eleccion[1][1], eleccion[1][2], i1);
longi[0] = abs(p1 - p0);
longi[1] = longitud[2];
longi[2] = longitud[3];
sort(longi, longi + 3);
if (menorigual(longi[0], longi[2]) and
menorigual(longi[1], longi[2]) and
menorigual(longi[2], longi[0] + longi[1])) {
sol = min(sol, 7);
return;
}
}
}
}
}
set<punt> vector2set(vector<punt> &v) {
set<punt> s;
for (int i = 0; i < int(v.size()); i++) s.insert(v[i]);
return s;
}
complex<double> normaliza(complex<double> p) {
if (igual(abs(p), 0.0)) return p;
return p / abs(p);
}
void calculaciclo3() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (menorigual(longitud[0], longitud[2]) and
menorigual(longitud[1], longitud[2]) and
menorigual(longitud[2], longitud[0] + longitud[1])) {
vector<punt> v(6);
complex<double> p0(0, 0);
v[0] = point2punt(p0);
complex<double> p1(eleccion[0][0], 0);
v[1] = point2punt(p1);
for (int i = 0; i < 2; i++) {
complex<double> p2 = elige(longitud[0], longitud[2], longitud[1], i);
v[2] = point2punt(p2);
for (int i0 = 0; i0 < 4; i0++) {
v[3] = point2punt(
elige(eleccion[0][0], eleccion[0][1], eleccion[0][2], i0));
for (int i1 = 0; i1 < 4; i1++) {
v[4] = point2punt(p1 + ((p2 - p1) / abs(p2 - p1)) *
elige(eleccion[1][0], eleccion[1][1],
eleccion[1][2], i1));
for (int i2 = 0; i2 < 4; i2++) {
v[5] = point2punt(p2 + ((p0 - p2) / abs(p0 - p2)) *
elige(eleccion[2][0], eleccion[2][1],
eleccion[2][2], i2));
set<punt> s = vector2set(v);
sol = min(sol, int(s.size()) + 2);
for (set<punt>::iterator it0 = s.begin(); it0 != s.end(); it0++) {
complex<double> q0 = punt2point(*it0);
set<punt>::iterator it1 = it0;
it1++;
for (; it1 != s.end(); it1++) {
complex<double> q1 = punt2point(*it1);
if (igual(abs(q1 - q0), eleccion[3][0])) {
sol = min(sol, int(s.size()) + 1);
set<punt>::iterator it2 = it1;
it2++;
for (; it2 != s.end(); it2++) {
complex<double> q2 = punt2point(*it2);
if ((igual(abs(q2 - q1), eleccion[3][1]) and
igual(abs(q0 - q2), eleccion[3][2])) or
(igual(abs(q2 - q1), eleccion[3][2]) and
igual(abs(q0 - q2), eleccion[3][1])))
sol = min(sol, int(s.size()));
}
}
}
}
}
}
}
}
}
}
}
void calculaciclo2y2() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (igual(longitud[0], longitud[1]) and igual(longitud[2], longitud[3])) {
int count0 = 4;
if ((igual(eleccion[0][1], eleccion[1][1]) and
igual(eleccion[0][2], eleccion[1][2])) or
(igual(eleccion[0][2], eleccion[1][1]) and
igual(eleccion[0][1], eleccion[1][2])))
count0 = 3;
int count2 = 4;
if ((igual(eleccion[2][1], eleccion[3][1]) and
igual(eleccion[2][2], eleccion[3][2])) or
(igual(eleccion[2][2], eleccion[3][1]) and
igual(eleccion[2][1], eleccion[3][2])))
count2 = 3;
sol = min(sol, count0 + count2 - 1);
}
}
}
void calculaciclo2() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (igual(longitud[0], longitud[1])) {
if (igual(longitud[1], longitud[2])) {
sol = min(sol, 7);
if (igual(longitud[2], longitud[3])) sol = min(sol, 6);
}
int count0 = 4;
if ((igual(eleccion[0][1], eleccion[1][1]) and
igual(eleccion[0][2], eleccion[1][2])) or
(igual(eleccion[0][2], eleccion[1][1]) and
igual(eleccion[0][1], eleccion[1][2])))
count0 = 3;
sol = min(sol, count0 + 4);
}
}
}
double input[4][3];
int indice[4];
int main() {
for (int i = 0; i < 4; i++) {
leer(input[i]);
indice[i] = i;
}
do {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) t[i][j] = input[indice[i]][j];
calculaciclo4();
calculaciclo4con2();
calculaciclo3();
calculaciclo2y2();
calculaciclo2();
} while (next_permutation(indice, indice + 4));
cout << sol << endl;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8;
const double INF = 1e100;
struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
double abs() const { return hypot(x, y); }
double arg() const { return atan2(y, x); }
Point operator*(double o) const { return Point(x * o, y * o); }
Point operator+(const Point& o) const { return Point(x + o.x, y + o.y); }
Point operator-(const Point& o) const { return Point(x - o.x, y - o.y); }
bool operator<(const Point& o) const {
return x < o.x - EPS || (x < o.x + EPS && y < o.y - EPS);
}
Point scale(double o) const { return *this * (o / abs()); }
Point rotl() const { return Point(-y, x); }
Point rotr() const { return Point(y, -x); }
};
struct Triangle {
Point p[4];
double q[3];
void init() {
p[3] = p[0];
for (int i = 0; i < 3; ++i) {
q[i] = (p[i + 1] - p[i]).abs();
}
sort(q, q + 3);
}
};
void gao(const Point& a, const Point& b, double da, double db,
vector<Point>& ret, int dump = 0) {
double sum = (b - a).abs();
double dif = (da * da - db * db) / sum;
double ra = (sum + dif) / 2;
double rb = (sum - dif) / 2;
double h = da * da - ra * ra;
if (h < -EPS) {
return;
} else {
h = sqrt(max(0.0, h));
}
Point v = (b - a).scale(h);
ret.push_back(a + (b - a).scale(ra) + v.rotl());
ret.push_back(a + (b - a).scale(ra) + v.rotr());
ret.push_back(a + (b - a).scale(rb) + v.rotl());
ret.push_back(a + (b - a).scale(rb) + v.rotr());
}
int main() {
int ans;
double e[4];
Triangle t[4];
vector<Point> v;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 3; ++j) {
scanf("%lf%lf", &t[i].p[j].x, &t[i].p[j].y);
}
t[i].init();
}
ans = 9;
for (int i = 0; i < 81; ++i) {
for (int j = 0, k = i; j < 4; ++j, k /= 3) {
e[j] = t[j].q[k % 3];
}
if (*max_element(e, e + 4) * 2 - accumulate(e, e + 4, 0.0) < EPS) {
ans = 8;
break;
}
}
for (int i = 0; i < 12; ++i) {
for (int j = (i / 3 + 1) * 3; j < 12; ++j) {
for (int k = (j / 3 + 1) * 3; k < 12; ++k) {
Point a(0, 0);
Point b(t[i / 3].q[i % 3], 0);
v.clear();
gao(a, b, t[j / 3].q[j % 3], t[k / 3].q[k % 3], v);
if (v.empty()) {
continue;
}
Point c = v[0];
vector<Point> va, vb, vc;
gao(a, b, t[i / 3].q[(i + 1) % 3], t[i / 3].q[(i + 2) % 3], va);
gao(a, c, t[j / 3].q[(j + 1) % 3], t[j / 3].q[(j + 2) % 3], vb);
gao(b, c, t[k / 3].q[(k + 1) % 3], t[k / 3].q[(k + 2) % 3], vc);
for (const Point& pa : va) {
for (const Point& pb : vb) {
for (const Point& pc : vc) {
set<Point> st = {a, b, c, pa, pb, pc};
ans = min(ans, (int)st.size() + 2);
for (int l = 0; l < 12; ++l) {
if (i / 3 + j / 3 + k / 3 + l / 3 != 6) {
continue;
}
for (const Point& u : st) {
for (const Point& v : st) {
if (fabs((u - v).abs() - t[l / 3].q[l % 3]) > EPS) {
continue;
}
vector<Point> vd;
gao(u, v, t[l / 3].q[(l + 1) % 3], t[l / 3].q[(l + 2) % 3],
vd);
for (const Point& pd : vd) {
ans = min(ans, (int)st.size() + 1 - (int)st.count(pd));
}
}
}
}
}
}
}
}
}
}
int tmp = 3;
for (int i = 1; i < 4; ++i) {
int acc = 2;
for (int j = 0; j < i; ++j) {
bool same = true;
for (int k = 0; k < 3 && same; ++k) {
same &= fabs(t[i].q[k] - t[j].q[k]) < EPS;
}
if (same) {
acc = 0;
break;
}
}
for (int j = 0; j < 3 * i && acc > 1; ++j) {
for (int k = 0; k < 3; ++k) {
if (fabs(t[j / 3].q[j % 3] - t[i].q[k]) < EPS) {
acc = 1;
break;
}
}
}
tmp += acc;
}
ans = min(ans, tmp);
printf("%d\n", ans);
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
struct P {
double x, y;
P() {}
P(double _x, double _y) : x(_x), y(_y) {}
double abs() { return sqrt(x * x + y * y); }
P operator+(const P& a) const { return P(x + a.x, y + a.y); }
P operator-(const P& a) const { return P(x - a.x, y - a.y); }
P operator*(const double& a) const { return P(x * a, y * a); }
P operator/(const double& a) const { return P(x / a, y / a); }
bool operator<(const P& a) const {
return x < a.x - eps || fabs(x - a.x) < eps && y < a.y;
}
bool operator==(const P& a) const { return (*this - a).abs() < eps; }
P rot() { return P(y, -x); }
void get() { scanf("%lf%lf", &x, &y); }
};
struct T {
P a[3];
double b[3];
void get() {
for (int i = 0; i < 3; i++) a[i].get();
for (int i = 0; i < 3; i++) b[i] = (a[i] - a[(i + 1) % 3]).abs();
}
} a[4];
bool equ(double a, double b) { return fabs(a - b) < eps; }
bool tri(double a, double b, double c) {
return a + b > c - eps && b + c > a - eps && c + a > b - eps;
}
void geti(P a, P b, double la, double lb, vector<P>& e) {
double d = (a - b).abs();
if (!tri(la, lb, d)) return;
if (la + lb < d + eps)
e.push_back(a + (b - a) * la / d);
else {
double co = (d * d + la * la - lb * lb) / (2 * d * la),
si = sqrt(max(0.0, 1.0 - co * co));
e.push_back(a + (b - a) * la * co / d + (b - a).rot() * la * si / d),
e.push_back(a + (b - a) * la * co / d - (b - a).rot() * la * si / d);
}
sort(e.begin(), e.end()), e.erase(unique(e.begin(), e.end()), e.end());
}
int S = 9;
void ff(vector<P> a, vector<T> b) {
S = min(S, (int)a.size() + (int)b.size() * 2);
if ((int)a.size() >= S) return;
if (b.empty()) {
S = min(S, (int)a.size());
return;
}
for (int i = 0; i < (int)a.size(); i++)
for (int j = i + 1; j < (int)a.size(); j++) {
double d = (a[i] - a[j]).abs();
for (int k = 0; k < (int)b.size(); k++) {
vector<P> e;
for (int l = 0; l < 3; l++)
if (equ(b[k].b[l], d))
geti(a[i], a[j], b[k].b[(l + 1) % 3], b[k].b[(l + 2) % 3], e),
geti(a[i], a[j], b[k].b[(l + 2) % 3], b[k].b[(l + 1) % 3], e);
for (int l = 0; l < (int)e.size(); l++) {
vector<P> a0 = a;
a0.push_back(e[l]);
sort(a0.begin(), a0.end()),
a0.erase(unique(a0.begin(), a0.end()), a0.end());
vector<T> b0 = b;
b0.erase(b0.begin() + k);
ff(a0, b0);
}
}
}
}
int main() {
for (int i = 0; i < 4; i++) a[i].get();
for (int k = 0; k < 81; k++) {
double e[4];
for (int i = 0, j = k; i < 4; j /= 3, i++) e[i] = a[i].b[j % 3];
if (e[0] + e[1] + e[2] + e[3] > 2 * *max_element(e, e + 4) - eps)
S = min(S, 8);
}
for (int i = 0; i < 4; i++) {
vector<P> a0;
for (int j = 0; j < 3; j++) a0.push_back(a[i].a[j]);
sort(a0.begin(), a0.end()),
a0.erase(unique(a0.begin(), a0.end()), a0.end());
vector<T> b0;
for (int j = 0; j < 4; j++)
if (i != j) b0.push_back(a[j]);
ff(a0, b0);
}
for (int i = 0; i < 4; i++) {
vector<int> p;
for (int j = 0; j < 4; j++)
if (j != i) p.push_back(j);
for (int k = 0; k < 27; k++) {
vector<P> a0;
vector<double> l;
for (int i = 0, j = k; i < 3; j /= 3, i++) l.push_back(a[p[i]].b[j % 3]);
vector<P> e;
a0.push_back(P(0, 0)), a0.push_back(P(0, l[0]));
geti(P(0, 0), P(0, l[0]), l[2], l[1], e);
if (e.empty()) continue;
a0.push_back(e[0]);
for (int o = 0; o < 64; o++) {
vector<P> a1 = a0;
for (int i = 0, j = k; i < 3; j /= 3, i++) {
e.clear();
if ((o >> i * 2) & 1)
geti(a0[i], a0[(i + 1) % 3], a[p[i]].b[(j % 3 + 1) % 3],
a[p[i]].b[(j % 3 + 2) % 3], e);
else
geti(a0[i], a0[(i + 1) % 3], a[p[i]].b[(j % 3 + 2) % 3],
a[p[i]].b[(j % 3 + 1) % 3], e);
if (e.empty()) goto end;
if ((int)e.size() == 1)
a1.push_back(e[0]);
else if (((o >> i * 2) & 3) / 2)
a1.push_back(e[0]);
else
a1.push_back(e[1]);
}
sort(a1.begin(), a1.end()),
a1.erase(unique(a1.begin(), a1.end()), a1.end());
ff(a1, vector<T>(1, a[i]));
end:;
}
}
}
for (int w = 0; w < 81; w++)
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 4; j++) {
if (!equ(a[i].b[w % 3], a[j].b[w / 3 % 3])) continue;
vector<P> e, f;
geti(P(0, 0), P(0, a[i].b[w % 3]), a[i].b[(w % 3 + 1) % 3],
a[i].b[(w % 3 + 2) % 3], e),
geti(P(0, 0), P(0, a[i].b[w % 3]), a[i].b[(w % 3 + 2) % 3],
a[i].b[(w % 3 + 1) % 3], e),
geti(P(0, 0), P(0, a[j].b[w / 3 % 3]), a[j].b[(w / 3 % 3 + 1) % 3],
a[j].b[(w / 3 % 3 + 2) % 3], f),
geti(P(0, 0), P(0, a[j].b[w / 3 % 3]), a[j].b[(w / 3 % 3 + 2) % 3],
a[j].b[(w / 3 % 3 + 1) % 3], f);
vector<double> d;
for (int i = 0; i < (int)e.size(); i++)
for (int j = 0; j < (int)f.size(); j++)
d.push_back((e[i] - f[j]).abs());
sort(d.begin(), d.end()),
d.erase(unique(d.begin(), d.end(), equ), d.end());
for (int k = 0; k < 4; k++)
if (k != i && k != j)
for (int l = k + 1; l < 4; l++)
if (l != i && l != j) {
if (tri(a[k].b[w / 9 % 3], a[l].b[w / 27 % 3],
a[i].b[w % 3] - eps))
S = min(S, 7);
if (equ(a[k].b[w / 9 % 3], a[l].b[w / 27 % 3])) {
e.clear(), f.clear();
geti(P(0, 0), P(0, a[k].b[w / 9 % 3]),
a[k].b[(w / 9 % 3 + 1) % 3], a[k].b[(w / 9 % 3 + 2) % 3],
e),
geti(P(0, 0), P(0, a[k].b[w / 9 % 3]),
a[k].b[(w / 9 % 3 + 2) % 3],
a[k].b[(w / 9 % 3 + 1) % 3], e),
geti(P(0, 0), P(0, a[l].b[w / 27 % 3]),
a[l].b[(w / 27 % 3 + 1) % 3],
a[l].b[(w / 27 % 3 + 2) % 3], f),
geti(P(0, 0), P(0, a[l].b[w / 27 % 3]),
a[l].b[(w / 27 % 3 + 2) % 3],
a[l].b[(w / 27 % 3 + 1) % 3], f);
for (int k = 0; k < (int)e.size(); k++)
for (int l = 0; l < (int)f.size(); l++)
for (int w = 0; w < (int)d.size(); w++)
if (equ((e[k] - f[l]).abs(), d[w])) S = min(S, 6);
}
}
}
printf("%d\n", S);
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
struct point {
double x, y;
};
double dist(point P, point Q) {
double dx = P.x - Q.x, dy = P.y - Q.y;
return sqrt(dx * dx + dy * dy);
}
vector<point> crossing(point O1, double r1, point O2, double r2) {
double d = dist(O1, O2);
double t = (d * d + r1 * r1 - r2 * r2) / 2.0 / d / d;
double fx = O1.x + (O2.x - O1.x) * t, fy = O1.y + (O2.y - O1.y) * t;
double h = sqrt(r1 * r1 - t * d * t * d);
double dx = (O2.y - O1.y) / d * h, dy = (O1.x - O2.x) / d * h;
vector<point> ans;
point ans1 = {fx + dx, fy + dy};
ans.push_back(ans1);
point ans2 = {fx - dx, fy - dy};
ans.push_back(ans2);
return ans;
}
vector<double> tri[10];
void read(int id) {
point P, Q, R;
cin >> P.x >> P.y >> Q.x >> Q.y >> R.x >> R.y;
tri[id].push_back(dist(P, Q));
tri[id].push_back(dist(P, R));
tri[id].push_back(dist(Q, R));
sort(tri[id].begin(), tri[id].end());
}
bool quad(double a, double b, double c, double d) {
double x[] = {a, b, c, d};
sort(x, x + 4);
return (x[0] + x[1] + x[2] + 1.0E-9 > x[3]);
}
bool triineq(double a, double b, double c) {
double x[] = {a, b, c};
sort(x, x + 3);
return (x[0] + x[1] + 1.0E-9 > x[2]);
}
bool equals(double x, double y) { return (x - y < 1.0E-9 && x - y > -1.0E-9); }
int N;
point P[20];
int a[(1 << 4)], dp[(1 << 4)];
void dfs(int mask) {
int i, x, y, z;
a[mask] = min(a[mask], N);
for ((i) = 0; (i) < (int)(4); (i)++)
if (!(mask & (1 << i))) {
int mask2 = (mask | (1 << i));
bool found = false;
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++)
for ((z) = 0; (z) < (int)(N); (z)++) {
if (equals(dist(P[x], P[y]), tri[i][0]) &&
equals(dist(P[x], P[z]), tri[i][1]) &&
equals(dist(P[y], P[z]), tri[i][2])) {
dfs(mask2);
found = true;
}
}
if (!found)
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++) {
if (equals(dist(P[x], P[y]), tri[i][0])) {
N++;
P[N - 1] = crossing(P[x], tri[i][1], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = crossing(P[x], tri[i][1], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][1])) {
N++;
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][2])) {
N++;
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][1])[0];
dfs(mask2);
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][1])[1];
dfs(mask2);
N--;
}
}
}
}
vector<point> crossed(point O1, double r1, point O2, double r2) {
vector<point> ans = crossing(O1, r1, O2, r2);
vector<point> ans2 = crossing(O1, r2, O2, r1);
ans.push_back(ans2[0]);
ans.push_back(ans2[1]);
return ans;
}
void init() {
int a, b, c, i, j, k, x, y, z;
for ((i) = 0; (i) < (int)(4); (i)++) {
N = 3;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[i][0];
P[2] = crossing(P[0], tri[i][1], P[1], tri[i][2])[0];
dfs(1 << i);
}
for ((a) = 0; (a) < (int)(4); (a)++)
for ((b) = 0; (b) < (int)(a); (b)++)
for ((c) = 0; (c) < (int)(b); (c)++)
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++) {
if (triineq(tri[a][i], tri[b][j], tri[c][k])) {
N = 6;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[a][i];
P[2] = crossing(P[0], tri[b][j], P[1], tri[c][k])[0];
vector<point> three = crossed(P[0], tri[a][(i + 1) % 3], P[1],
tri[a][(i + 2) % 3]);
vector<point> four = crossed(P[0], tri[b][(j + 1) % 3], P[2],
tri[b][(j + 2) % 3]);
vector<point> five = crossed(P[1], tri[c][(k + 1) % 3], P[2],
tri[c][(k + 2) % 3]);
for ((x) = 0; (x) < (int)(4); (x)++)
for ((y) = 0; (y) < (int)(4); (y)++)
for ((z) = 0; (z) < (int)(4); (z)++) {
P[3] = three[x];
P[4] = four[y];
P[5] = five[z];
dfs((1 << a) | (1 << b) | (1 << c));
}
}
}
}
int main() {
int i, j, k, l;
for ((i) = 0; (i) < (int)(4); (i)++) read(i);
int ans = 9;
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++)
for ((l) = 0; (l) < (int)(3); (l)++)
if (quad(tri[0][i], tri[1][j], tri[2][k], tri[3][l])) ans = 8;
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) a[i] = (1 << 29);
a[0] = 0;
init();
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) {
dp[i] = a[i];
for (j = 1; j < i; j++)
if ((i & j) == j) dp[i] = min(dp[i], dp[j] + a[i ^ j] - 1);
}
ans = min(ans, dp[15]);
cout << ans << endl;
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
struct P {
double x, y;
P() {}
P(double _x, double _y) : x(_x), y(_y) {}
double abs() { return sqrt(x * x + y * y); }
P operator+(const P& a) const { return P(x + a.x, y + a.y); }
P operator-(const P& a) const { return P(x - a.x, y - a.y); }
P operator*(const double& a) const { return P(x * a, y * a); }
P operator/(const double& a) const { return P(x / a, y / a); }
bool operator<(const P& a) const {
return x < a.x - eps || fabs(x - a.x) < eps && y < a.y;
}
bool operator==(const P& a) const { return (*this - a).abs() < eps; }
P rot() { return P(y, -x); }
void get() { scanf("%lf%lf", &x, &y); }
};
struct T {
P a[3];
double b[3];
void get() {
for (int i = 0; i < 3; i++) a[i].get();
for (int i = 0; i < 3; i++) b[i] = (a[i] - a[(i + 1) % 3]).abs();
}
} a[4];
bool equ(double a, double b) { return fabs(a - b) < eps; }
bool tri(double a, double b, double c) {
return a + b > c - eps && b + c > a - eps && c + a > b - eps;
}
void geti(P a, P b, double la, double lb, vector<P>& e) {
double d = (a - b).abs();
if (!tri(la, lb, d)) return;
if (la + lb < d + eps)
e.push_back(a + (b - a) * la / d);
else {
double co = (d * d + la * la - lb * lb) / (2 * d * la),
si = sqrt(max(0.0, 1.0 - co * co));
e.push_back(a + (b - a) * la * co / d + (b - a).rot() * la * si / d),
e.push_back(a + (b - a) * la * co / d - (b - a).rot() * la * si / d);
}
sort(e.begin(), e.end()), e.erase(unique(e.begin(), e.end()), e.end());
}
int S = 9;
void ff(vector<P> a, vector<T> b) {
S = min(S, (int)a.size() + (int)b.size() * 2);
if ((int)a.size() >= S) return;
if (b.empty()) {
S = min(S, (int)a.size());
return;
}
for (int i = 0; i < (int)a.size(); i++)
for (int j = i + 1; j < (int)a.size(); j++) {
double d = (a[i] - a[j]).abs();
for (int k = 0; k < (int)b.size(); k++) {
vector<P> e;
for (int l = 0; l < 3; l++)
if (equ(b[k].b[l], d))
geti(a[i], a[j], b[k].b[(l + 1) % 3], b[k].b[(l + 2) % 3], e),
geti(a[i], a[j], b[k].b[(l + 2) % 3], b[k].b[(l + 1) % 3], e);
for (int l = 0; l < (int)e.size(); l++) {
vector<P> a0 = a;
a0.push_back(e[l]);
sort(a0.begin(), a0.end()),
a0.erase(unique(a0.begin(), a0.end()), a0.end());
vector<T> b0 = b;
b0.erase(b0.begin() + k);
ff(a0, b0);
}
}
}
}
int main() {
for (int i = 0; i < 4; i++) a[i].get();
for (int k = 0; k < 81; k++) {
double e[4];
for (int i = 0, j = k; i < 4; j /= 3, i++) e[i] = a[i].b[j % 3];
if (e[0] + e[1] + e[2] + e[3] > 2 * *max_element(e, e + 4) - eps)
S = min(S, 8);
}
for (int i = 0; i < 4; i++) {
vector<P> a0;
for (int j = 0; j < 3; j++) a0.push_back(a[i].a[j]);
sort(a0.begin(), a0.end()),
a0.erase(unique(a0.begin(), a0.end()), a0.end());
vector<T> b0;
for (int j = 0; j < 4; j++)
if (i != j) b0.push_back(a[j]);
ff(a0, b0);
}
for (int i = 0; i < 4; i++) {
vector<int> p;
for (int j = 0; j < 4; j++)
if (j != i) p.push_back(j);
for (int k = 0; k < 27; k++) {
vector<P> a0;
vector<double> l;
for (int i = 0, j = k; i < 3; j /= 3, i++) l.push_back(a[p[i]].b[j % 3]);
vector<P> e;
a0.push_back(P(0, 0)), a0.push_back(P(0, l[0]));
geti(P(0, 0), P(0, l[0]), l[2], l[1], e);
if (e.empty()) continue;
a0.push_back(e[0]);
for (int o = 0; o < 64; o++) {
vector<P> a1 = a0;
for (int i = 0, j = k; i < 3; j /= 3, i++) {
e.clear();
if ((o >> i * 2) & 1)
geti(a0[i], a0[(i + 1) % 3], a[p[i]].b[(j % 3 + 1) % 3],
a[p[i]].b[(j % 3 + 2) % 3], e);
else
geti(a0[i], a0[(i + 1) % 3], a[p[i]].b[(j % 3 + 2) % 3],
a[p[i]].b[(j % 3 + 1) % 3], e);
if (e.empty()) goto end;
if ((int)e.size() == 1)
a1.push_back(e[0]);
else if (((o >> i * 2) & 3) / 2)
a1.push_back(e[0]);
else
a1.push_back(e[1]);
}
sort(a1.begin(), a1.end()),
a1.erase(unique(a1.begin(), a1.end()), a1.end());
ff(a1, vector<T>(1, a[i]));
end:;
}
}
}
for (int w = 0; w < 81; w++)
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 4; j++) {
if (!equ(a[i].b[w % 3], a[j].b[w / 3 % 3])) continue;
vector<P> e, f;
geti(P(0, 0), P(0, a[i].b[w % 3]), a[i].b[(w % 3 + 1) % 3],
a[i].b[(w % 3 + 2) % 3], e),
geti(P(0, 0), P(0, a[i].b[w % 3]), a[i].b[(w % 3 + 2) % 3],
a[i].b[(w % 3 + 1) % 3], e),
geti(P(0, 0), P(0, a[j].b[w / 3 % 3]), a[j].b[(w / 3 % 3 + 1) % 3],
a[j].b[(w / 3 % 3 + 2) % 3], f),
geti(P(0, 0), P(0, a[j].b[w / 3 % 3]), a[j].b[(w / 3 % 3 + 2) % 3],
a[j].b[(w / 3 % 3 + 1) % 3], f);
vector<double> d;
for (int i = 0; i < (int)e.size(); i++)
for (int j = 0; j < (int)f.size(); j++)
d.push_back((e[i] - f[j]).abs());
sort(d.begin(), d.end()),
d.erase(unique(d.begin(), d.end(), equ), d.end());
for (int k = 0; k < 4; k++)
if (k != i && k != j)
for (int l = k + 1; l < 4; l++)
if (l != i && l != j) {
if (tri(a[k].b[w / 9 % 3], a[l].b[w / 27 % 3],
a[i].b[w % 3] - eps))
S = min(S, 7);
if (equ(a[k].b[w / 9 % 3], a[l].b[w / 27 % 3])) {
e.clear(), f.clear();
geti(P(0, 0), P(0, a[k].b[w / 9 % 3]),
a[k].b[(w / 9 % 3 + 1) % 3], a[k].b[(w / 9 % 3 + 2) % 3],
e),
geti(P(0, 0), P(0, a[k].b[w / 9 % 3]),
a[k].b[(w / 9 % 3 + 2) % 3],
a[k].b[(w / 9 % 3 + 1) % 3], e),
geti(P(0, 0), P(0, a[l].b[w / 27 % 3]),
a[l].b[(w / 27 % 3 + 1) % 3],
a[l].b[(w / 27 % 3 + 2) % 3], f),
geti(P(0, 0), P(0, a[l].b[w / 27 % 3]),
a[l].b[(w / 27 % 3 + 2) % 3],
a[l].b[(w / 27 % 3 + 1) % 3], f);
for (int k = 0; k < (int)e.size(); k++)
for (int l = 0; l < (int)f.size(); l++)
for (int w = 0; w < (int)d.size(); w++)
if (equ((e[k] - f[l]).abs(), d[w])) S = min(S, 6);
}
}
}
printf("%d\n", S);
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
struct point {
double x, y;
};
double dist(point P, point Q) {
double dx = P.x - Q.x, dy = P.y - Q.y;
return sqrt(dx * dx + dy * dy);
}
vector<point> crossing(point O1, double r1, point O2, double r2) {
double d = dist(O1, O2);
double t = (d * d + r1 * r1 - r2 * r2) / 2.0 / d / d;
double fx = O1.x + (O2.x - O1.x) * t, fy = O1.y + (O2.y - O1.y) * t;
double h = sqrt(r1 * r1 - t * d * t * d);
double dx = (O2.y - O1.y) / d * h, dy = (O1.x - O2.x) / d * h;
vector<point> ans;
point ans1 = {fx + dx, fy + dy};
ans.push_back(ans1);
point ans2 = {fx - dx, fy - dy};
ans.push_back(ans2);
return ans;
}
vector<double> tri[10];
void read(int id) {
point P, Q, R;
cin >> P.x >> P.y >> Q.x >> Q.y >> R.x >> R.y;
tri[id].push_back(dist(P, Q));
tri[id].push_back(dist(P, R));
tri[id].push_back(dist(Q, R));
sort(tri[id].begin(), tri[id].end());
}
bool quad(double a, double b, double c, double d) {
double x[] = {a, b, c, d};
sort(x, x + 4);
return (x[0] + x[1] + x[2] + 1.0E-9 > x[3]);
}
bool triineq(double a, double b, double c) {
double x[] = {a, b, c};
sort(x, x + 3);
return (x[0] + x[1] + 1.0E-9 > x[2]);
}
bool equals(double x, double y) { return (x - y < 1.0E-9 && x - y > -1.0E-9); }
int N;
point P[20];
int a[(1 << 4)], dp[(1 << 4)];
void dfs(int mask) {
int i, x, y, z;
a[mask] = min(a[mask], N);
for ((i) = 0; (i) < (int)(4); (i)++)
if (!(mask & (1 << i))) {
int mask2 = (mask | (1 << i));
bool found = false;
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++)
for ((z) = 0; (z) < (int)(N); (z)++) {
if (equals(dist(P[x], P[y]), tri[i][0]) &&
equals(dist(P[x], P[z]), tri[i][1]) &&
equals(dist(P[y], P[z]), tri[i][2])) {
dfs(mask2);
found = true;
}
}
if (!found)
for ((x) = 0; (x) < (int)(N); (x)++)
for ((y) = 0; (y) < (int)(N); (y)++) {
if (equals(dist(P[x], P[y]), tri[i][0])) {
N++;
P[N - 1] = crossing(P[x], tri[i][1], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = crossing(P[x], tri[i][1], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][1])) {
N++;
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][2])[0];
dfs(mask2);
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][2])[1];
dfs(mask2);
N--;
}
if (equals(dist(P[x], P[y]), tri[i][2])) {
N++;
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][1])[0];
dfs(mask2);
P[N - 1] = crossing(P[x], tri[i][0], P[y], tri[i][1])[1];
dfs(mask2);
N--;
}
}
}
}
vector<point> crossed(point O1, double r1, point O2, double r2) {
vector<point> ans = crossing(O1, r1, O2, r2);
vector<point> ans2 = crossing(O1, r2, O2, r1);
ans.push_back(ans2[0]);
ans.push_back(ans2[1]);
return ans;
}
void init() {
int a, b, c, i, j, k, x, y, z;
for ((i) = 0; (i) < (int)(4); (i)++) {
N = 3;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[i][0];
P[2] = crossing(P[0], tri[i][1], P[1], tri[i][2])[0];
dfs(1 << i);
}
for ((a) = 0; (a) < (int)(4); (a)++)
for ((b) = 0; (b) < (int)(a); (b)++)
for ((c) = 0; (c) < (int)(b); (c)++)
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++) {
if (triineq(tri[a][i], tri[b][j], tri[c][k])) {
N = 6;
P[0].x = P[0].y = P[1].y = 0.0;
P[1].x = tri[a][i];
P[2] = crossing(P[0], tri[b][j], P[1], tri[c][k])[0];
vector<point> three = crossed(P[0], tri[a][(i + 1) % 3], P[1],
tri[a][(i + 2) % 3]);
vector<point> four = crossed(P[0], tri[b][(j + 1) % 3], P[2],
tri[b][(j + 2) % 3]);
vector<point> five = crossed(P[1], tri[c][(k + 1) % 3], P[2],
tri[c][(k + 2) % 3]);
for ((x) = 0; (x) < (int)(4); (x)++)
for ((y) = 0; (y) < (int)(4); (y)++)
for ((z) = 0; (z) < (int)(4); (z)++) {
P[3] = three[x];
P[4] = four[y];
P[5] = five[z];
dfs((1 << a) | (1 << b) | (1 << c));
}
}
}
}
int main() {
int i, j, k, l;
for ((i) = 0; (i) < (int)(4); (i)++) read(i);
int ans = 9;
for ((i) = 0; (i) < (int)(3); (i)++)
for ((j) = 0; (j) < (int)(3); (j)++)
for ((k) = 0; (k) < (int)(3); (k)++)
for ((l) = 0; (l) < (int)(3); (l)++)
if (quad(tri[0][i], tri[1][j], tri[2][k], tri[3][l])) ans = 8;
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) a[i] = (1 << 29);
a[0] = 0;
init();
for ((i) = 0; (i) < (int)((1 << 4)); (i)++) {
dp[i] = a[i];
for (j = 1; j < i; j++)
if ((i & j) == j) dp[i] = min(dp[i], dp[j] + a[i ^ j] - 1);
}
ans = min(ans, dp[15]);
cout << ans << endl;
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
struct P {
double x, y;
P() {}
P(double _x, double _y) : x(_x), y(_y) {}
double abs() { return sqrt(x * x + y * y); }
P operator+(const P& a) const { return P(x + a.x, y + a.y); }
P operator-(const P& a) const { return P(x - a.x, y - a.y); }
P operator*(const double& a) const { return P(x * a, y * a); }
P operator/(const double& a) const { return P(x / a, y / a); }
bool operator<(const P& a) const {
return x < a.x - eps || fabs(x - a.x) < eps && y < a.y;
}
bool operator==(const P& a) const { return (*this - a).abs() < eps; }
P rot() { return P(y, -x); }
void get() { scanf("%lf%lf", &x, &y); }
};
struct T {
P a[3];
double b[3];
void get() {
for (int i = 0; i < 3; i++) a[i].get();
for (int i = 0; i < 3; i++) b[i] = (a[i] - a[(i + 1) % 3]).abs();
}
} a[4];
bool equ(double a, double b) { return fabs(a - b) < eps; }
bool tri(double a, double b, double c) {
return a + b > c - eps && b + c > a - eps && c + a > b - eps;
}
void geti(P a, P b, double la, double lb, vector<P>& e) {
double d = (a - b).abs();
if (!tri(la, lb, d)) return;
if (la + lb < d + eps)
e.push_back(a + (b - a) * la / d);
else {
double co = (d * d + la * la - lb * lb) / (2 * d * la),
si = sqrt(max(0.0, 1.0 - co * co));
e.push_back(a + (b - a) * la * co / d + (b - a).rot() * la * si / d),
e.push_back(a + (b - a) * la * co / d - (b - a).rot() * la * si / d);
}
sort(e.begin(), e.end()), e.erase(unique(e.begin(), e.end()), e.end());
}
int S = 9;
void ff(vector<P> a, vector<T> b) {
S = min(S, (int)a.size() + (int)b.size() * 2);
if ((int)a.size() >= S) return;
if (b.empty()) {
S = min(S, (int)a.size());
return;
}
for (int i = 0; i < (int)a.size(); i++)
for (int j = i + 1; j < (int)a.size(); j++) {
double d = (a[i] - a[j]).abs();
for (int k = 0; k < (int)b.size(); k++) {
vector<P> e;
for (int l = 0; l < 3; l++)
if (equ(b[k].b[l], d))
geti(a[i], a[j], b[k].b[(l + 1) % 3], b[k].b[(l + 2) % 3], e),
geti(a[i], a[j], b[k].b[(l + 2) % 3], b[k].b[(l + 1) % 3], e);
for (int l = 0; l < (int)e.size(); l++) {
vector<P> a0 = a;
a0.push_back(e[l]);
sort(a0.begin(), a0.end()),
a0.erase(unique(a0.begin(), a0.end()), a0.end());
vector<T> b0 = b;
b0.erase(b0.begin() + k);
ff(a0, b0);
}
}
}
}
int main() {
for (int i = 0; i < 4; i++) a[i].get();
for (int k = 0; k < 81; k++) {
double e[4];
for (int i = 0, j = k; i < 4; j /= 3, i++) e[i] = a[i].b[j % 3];
if (e[0] + e[1] + e[2] + e[3] > 2 * *max_element(e, e + 4) - eps)
S = min(S, 8);
}
for (int i = 0; i < 4; i++) {
vector<P> a0;
for (int j = 0; j < 3; j++) a0.push_back(a[i].a[j]);
sort(a0.begin(), a0.end()),
a0.erase(unique(a0.begin(), a0.end()), a0.end());
vector<T> b0;
for (int j = 0; j < 4; j++)
if (i != j) b0.push_back(a[j]);
ff(a0, b0);
}
for (int i = 0; i < 4; i++) {
vector<int> p;
for (int j = 0; j < 4; j++)
if (j != i) p.push_back(j);
for (int k = 0; k < 27; k++) {
vector<P> a0;
vector<double> l;
for (int i = 0, j = k; i < 3; j /= 3, i++) l.push_back(a[p[i]].b[j % 3]);
vector<P> e;
a0.push_back(P(0, 0)), a0.push_back(P(0, l[0]));
geti(P(0, 0), P(0, l[0]), l[2], l[1], e);
if (e.empty()) continue;
a0.push_back(e[0]);
for (int o = 0; o < 64; o++) {
vector<P> a1 = a0;
for (int i = 0, j = k; i < 3; j /= 3, i++) {
e.clear();
if ((o >> i * 2) & 1)
geti(a0[i], a0[(i + 1) % 3], a[p[i]].b[(j % 3 + 1) % 3],
a[p[i]].b[(j % 3 + 2) % 3], e);
else
geti(a0[i], a0[(i + 1) % 3], a[p[i]].b[(j % 3 + 2) % 3],
a[p[i]].b[(j % 3 + 1) % 3], e);
if (e.empty()) goto end;
if ((int)e.size() == 1)
a1.push_back(e[0]);
else if (((o >> i * 2) & 3) / 2)
a1.push_back(e[0]);
else
a1.push_back(e[1]);
}
sort(a1.begin(), a1.end()),
a1.erase(unique(a1.begin(), a1.end()), a1.end());
ff(a1, vector<T>(1, a[i]));
end:;
}
}
}
for (int w = 0; w < 81; w++)
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 4; j++) {
if (!equ(a[i].b[w % 3], a[j].b[w / 3 % 3])) continue;
vector<P> e, f;
geti(P(0, 0), P(0, a[i].b[w % 3]), a[i].b[(w % 3 + 1) % 3],
a[i].b[(w % 3 + 2) % 3], e),
geti(P(0, 0), P(0, a[i].b[w % 3]), a[i].b[(w % 3 + 2) % 3],
a[i].b[(w % 3 + 1) % 3], e),
geti(P(0, 0), P(0, a[j].b[w / 3 % 3]), a[j].b[(w / 3 % 3 + 1) % 3],
a[j].b[(w / 3 % 3 + 2) % 3], f),
geti(P(0, 0), P(0, a[j].b[w / 3 % 3]), a[j].b[(w / 3 % 3 + 2) % 3],
a[j].b[(w / 3 % 3 + 1) % 3], f);
vector<double> d;
for (int i = 0; i < (int)e.size(); i++)
for (int j = 0; j < (int)f.size(); j++)
d.push_back((e[i] - f[j]).abs());
sort(d.begin(), d.end()),
d.erase(unique(d.begin(), d.end(), equ), d.end());
for (int k = 0; k < 4; k++)
if (k != i && k != j)
for (int l = k + 1; l < 4; l++)
if (l != i && l != j) {
if (tri(a[k].b[w / 9 % 3], a[l].b[w / 27 % 3],
a[i].b[w % 3] - eps))
S = min(S, 7);
if (equ(a[k].b[w / 9 % 3], a[l].b[w / 27 % 3])) {
e.clear(), f.clear();
geti(P(0, 0), P(0, a[k].b[w / 9 % 3]),
a[k].b[(w / 9 % 3 + 1) % 3], a[k].b[(w / 9 % 3 + 2) % 3],
e),
geti(P(0, 0), P(0, a[k].b[w / 9 % 3]),
a[k].b[(w / 9 % 3 + 2) % 3],
a[k].b[(w / 9 % 3 + 1) % 3], e),
geti(P(0, 0), P(0, a[l].b[w / 27 % 3]),
a[l].b[(w / 27 % 3 + 1) % 3],
a[l].b[(w / 27 % 3 + 2) % 3], f),
geti(P(0, 0), P(0, a[l].b[w / 27 % 3]),
a[l].b[(w / 27 % 3 + 2) % 3],
a[l].b[(w / 27 % 3 + 1) % 3], f);
for (int k = 0; k < (int)e.size(); k++)
for (int l = 0; l < (int)f.size(); l++)
for (int w = 0; w < (int)d.size(); w++)
if (equ((e[k] - f[l]).abs(), d[w])) S = min(S, 6);
}
}
}
printf("%d\n", S);
return 0;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
complex<double> leer() {
double x, y;
cin >> x >> y;
return complex<double>(x, y);
}
void leer(double input[3]) {
complex<double> in[3];
for (int i = 0; i < 3; i++) in[i] = leer();
for (int i = 0; i < 3; i++) {
int nexti = (i + 1) % 3;
input[i] = abs(in[nexti] - in[i]);
}
}
struct punt {
double x, y;
};
punt point2punt(complex<double> p) {
punt pp;
pp.x = real(p);
pp.y = imag(p);
return pp;
}
complex<double> punt2point(punt p) { return complex<double>(p.x, p.y); }
double error = 1e-5;
bool menor(double x, double y) { return x < y - error; }
bool menorigual(double x, double y) { return x < y + error; }
bool igual(double x, double y) { return x > y - error and x < y + error; }
bool operator<(punt p1, punt p2) {
return menor(p1.x, p2.x) or (igual(p1.x, p2.x) and menor(p1.y, p2.y));
}
double t[4][3];
int sol = 9;
void calculaciclo4() {
int total = 3 * 3 * 3 * 3;
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
longitud[i] = t[i][b];
}
if (menorigual(longitud[0], longitud[3]) and
menorigual(longitud[1], longitud[3]) and
menorigual(longitud[2], longitud[3]) and
menorigual(longitud[3], longitud[0] + longitud[1] + longitud[2])) {
sol = min(sol, 8);
return;
}
}
}
complex<double> elige(double a, double b, double c, int indice) {
if (indice == 0 or indice == 1) {
double alfa = acos((a * a + b * b - c * c) / (2.0 * a * b));
if (indice == 0) return complex<double>(b * cos(alfa), b * sin(alfa));
return complex<double>(b * cos(alfa), -b * sin(alfa));
}
double alfa = acos((a * a + c * c - b * b) / (2.0 * a * c));
if (indice == 2) return complex<double>(c * cos(alfa), c * sin(alfa));
return complex<double>(c * cos(alfa), -c * sin(alfa));
}
void calculaciclo4con2() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
double longi[3];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (not igual(longitud[0], longitud[1])) continue;
for (int i0 = 0; i0 < 4; i0++) {
complex<double> p0 =
elige(eleccion[0][0], eleccion[0][1], eleccion[0][2], i0);
for (int i1 = 0; i1 < 4; i1++) {
complex<double> p1 =
elige(eleccion[1][0], eleccion[1][1], eleccion[1][2], i1);
longi[0] = abs(p1 - p0);
longi[1] = longitud[2];
longi[2] = longitud[3];
sort(longi, longi + 3);
if (menorigual(longi[0], longi[2]) and
menorigual(longi[1], longi[2]) and
menorigual(longi[2], longi[0] + longi[1])) {
sol = min(sol, 7);
return;
}
}
}
}
}
set<punt> vector2set(vector<punt> &v) {
set<punt> s;
for (int i = 0; i < int(v.size()); i++) s.insert(v[i]);
return s;
}
complex<double> normaliza(complex<double> p) {
if (igual(abs(p), 0.0)) return p;
return p / abs(p);
}
void calculaciclo3() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (menorigual(longitud[0], longitud[2]) and
menorigual(longitud[1], longitud[2]) and
menorigual(longitud[2], longitud[0] + longitud[1])) {
vector<punt> v(6);
complex<double> p0(0, 0);
v[0] = point2punt(p0);
complex<double> p1(eleccion[0][0], 0);
v[1] = point2punt(p1);
for (int i = 0; i < 2; i++) {
complex<double> p2 = elige(longitud[0], longitud[2], longitud[1], i);
v[2] = point2punt(p2);
for (int i0 = 0; i0 < 4; i0++) {
v[3] = point2punt(
elige(eleccion[0][0], eleccion[0][1], eleccion[0][2], i0));
for (int i1 = 0; i1 < 4; i1++) {
v[4] = point2punt(p1 + ((p2 - p1) / abs(p2 - p1)) *
elige(eleccion[1][0], eleccion[1][1],
eleccion[1][2], i1));
for (int i2 = 0; i2 < 4; i2++) {
v[5] = point2punt(p2 + ((p0 - p2) / abs(p0 - p2)) *
elige(eleccion[2][0], eleccion[2][1],
eleccion[2][2], i2));
set<punt> s = vector2set(v);
sol = min(sol, int(s.size()) + 2);
for (set<punt>::iterator it0 = s.begin(); it0 != s.end(); it0++) {
complex<double> q0 = punt2point(*it0);
set<punt>::iterator it1 = it0;
it1++;
for (; it1 != s.end(); it1++) {
complex<double> q1 = punt2point(*it1);
if (igual(abs(q1 - q0), eleccion[3][0])) {
sol = min(sol, int(s.size()) + 1);
set<punt>::iterator it2 = it1;
it2++;
for (; it2 != s.end(); it2++) {
complex<double> q2 = punt2point(*it2);
if ((igual(abs(q2 - q1), eleccion[3][1]) and
igual(abs(q0 - q2), eleccion[3][2])) or
(igual(abs(q2 - q1), eleccion[3][2]) and
igual(abs(q0 - q2), eleccion[3][1])))
sol = min(sol, int(s.size()));
}
}
}
}
}
}
}
}
}
}
}
void calculaciclo2y2() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (igual(longitud[0], longitud[1]) and igual(longitud[2], longitud[3])) {
int count0 = 4;
if ((igual(eleccion[0][1], eleccion[1][1]) and
igual(eleccion[0][2], eleccion[1][2])) or
(igual(eleccion[0][2], eleccion[1][1]) and
igual(eleccion[0][1], eleccion[1][2])))
count0 = 3;
int count2 = 4;
if ((igual(eleccion[2][1], eleccion[3][1]) and
igual(eleccion[2][2], eleccion[3][2])) or
(igual(eleccion[2][2], eleccion[3][1]) and
igual(eleccion[2][1], eleccion[3][2])))
count2 = 3;
sol = min(sol, count0 + count2 - 1);
}
}
}
void calculaciclo2() {
int total = 3 * 3 * 3 * 3;
double eleccion[4][3];
double longitud[4];
for (int c = 0; c < total; c++) {
int cc = c;
for (int i = 0; i < 4; i++) {
int b = cc % 3;
cc /= 3;
if (b == 0) {
eleccion[i][0] = t[i][0];
eleccion[i][1] = t[i][1];
eleccion[i][2] = t[i][2];
} else if (b == 1) {
eleccion[i][0] = t[i][1];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][2];
} else {
eleccion[i][0] = t[i][2];
eleccion[i][1] = t[i][0];
eleccion[i][2] = t[i][1];
}
longitud[i] = t[i][b];
}
if (igual(longitud[0], longitud[1])) {
if (igual(longitud[1], longitud[2])) {
sol = min(sol, 7);
if (igual(longitud[2], longitud[3])) sol = min(sol, 6);
}
int count0 = 4;
if ((igual(eleccion[0][1], eleccion[1][1]) and
igual(eleccion[0][2], eleccion[1][2])) or
(igual(eleccion[0][2], eleccion[1][1]) and
igual(eleccion[0][1], eleccion[1][2])))
count0 = 3;
sol = min(sol, count0 + 4);
}
}
}
double input[4][3];
int indice[4];
int main() {
for (int i = 0; i < 4; i++) {
leer(input[i]);
indice[i] = i;
}
do {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) t[i][j] = input[indice[i]][j];
calculaciclo4();
calculaciclo4con2();
calculaciclo3();
calculaciclo2y2();
calculaciclo2();
} while (next_permutation(indice, indice + 4));
cout << sol << endl;
}
| CPP |
68_E. Contact | Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.
Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Input
Each of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 β€ x1, y1, x2, y2, x3, y3 β€ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
Output
First line should contain minimum number of columns enough to land all spaceships.
Examples
Input
0 0 1 0 1 2
0 0 0 2 2 2
0 0 3 0 1 2
0 0 3 0 2 2
Output
4
Input
0 0 0 1 1 1
0 0 0 2 2 2
0 0 0 5 5 5
0 0 0 17 17 17
Output
9
Note
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.
In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns. | 2 | 11 | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8;
const double INF = 1e100;
struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
double abs() const { return hypot(x, y); }
double arg() const { return atan2(y, x); }
Point operator*(double o) const { return Point(x * o, y * o); }
Point operator+(const Point& o) const { return Point(x + o.x, y + o.y); }
Point operator-(const Point& o) const { return Point(x - o.x, y - o.y); }
bool operator<(const Point& o) const {
return x < o.x - EPS || (x < o.x + EPS && y < o.y - EPS);
}
Point scale(double o) const { return *this * (o / abs()); }
Point rotl() const { return Point(-y, x); }
Point rotr() const { return Point(y, -x); }
};
struct Triangle {
Point p[4];
double q[3];
void init() {
p[3] = p[0];
for (int i = 0; i < 3; ++i) {
q[i] = (p[i + 1] - p[i]).abs();
}
sort(q, q + 3);
}
};
void gao(const Point& a, const Point& b, double da, double db,
vector<Point>& ret, int dump = 0) {
double sum = (b - a).abs();
double dif = (da * da - db * db) / sum;
double ra = (sum + dif) / 2;
double rb = (sum - dif) / 2;
double h = da * da - ra * ra;
if (h < -EPS) {
return;
} else {
h = sqrt(max(0.0, h));
}
Point v = (b - a).scale(h);
ret.push_back(a + (b - a).scale(ra) + v.rotl());
ret.push_back(a + (b - a).scale(ra) + v.rotr());
ret.push_back(a + (b - a).scale(rb) + v.rotl());
ret.push_back(a + (b - a).scale(rb) + v.rotr());
}
int main() {
int ans;
double e[4];
Triangle t[4];
vector<Point> v;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 3; ++j) {
scanf("%lf%lf", &t[i].p[j].x, &t[i].p[j].y);
}
t[i].init();
}
ans = 9;
for (int i = 0; i < 81; ++i) {
for (int j = 0, k = i; j < 4; ++j, k /= 3) {
e[j] = t[j].q[k % 3];
}
if (*max_element(e, e + 4) * 2 - accumulate(e, e + 4, 0.0) < EPS) {
ans = 8;
break;
}
}
for (int i = 0; i < 12; ++i) {
for (int j = (i / 3 + 1) * 3; j < 12; ++j) {
for (int k = (j / 3 + 1) * 3; k < 12; ++k) {
Point a(0, 0);
Point b(t[i / 3].q[i % 3], 0);
v.clear();
gao(a, b, t[j / 3].q[j % 3], t[k / 3].q[k % 3], v);
if (v.empty()) {
continue;
}
Point c = v[0];
vector<Point> va, vb, vc;
gao(a, b, t[i / 3].q[(i + 1) % 3], t[i / 3].q[(i + 2) % 3], va);
gao(a, c, t[j / 3].q[(j + 1) % 3], t[j / 3].q[(j + 2) % 3], vb);
gao(b, c, t[k / 3].q[(k + 1) % 3], t[k / 3].q[(k + 2) % 3], vc);
for (const Point& pa : va) {
for (const Point& pb : vb) {
for (const Point& pc : vc) {
set<Point> st = {a, b, c, pa, pb, pc};
ans = min(ans, (int)st.size() + 2);
for (int l = 0; l < 12; ++l) {
if (i / 3 + j / 3 + k / 3 + l / 3 != 6) {
continue;
}
for (const Point& u : st) {
for (const Point& v : st) {
if (fabs((u - v).abs() - t[l / 3].q[l % 3]) > EPS) {
continue;
}
vector<Point> vd;
gao(u, v, t[l / 3].q[(l + 1) % 3], t[l / 3].q[(l + 2) % 3],
vd);
for (const Point& pd : vd) {
ans = min(ans, (int)st.size() + 1 - (int)st.count(pd));
}
}
}
}
}
}
}
}
}
}
int tmp = 3;
for (int i = 1; i < 4; ++i) {
int acc = 2;
for (int j = 0; j < i; ++j) {
bool same = true;
for (int k = 0; k < 3 && same; ++k) {
same &= fabs(t[i].q[k] - t[j].q[k]) < EPS;
}
if (same) {
acc = 0;
break;
}
}
for (int j = 0; j < 3 * i && acc > 1; ++j) {
for (int k = 0; k < 3; ++k) {
if (fabs(t[j / 3].q[j % 3] - t[i].q[k]) < EPS) {
acc = 1;
break;
}
}
}
tmp += acc;
}
ans = min(ans, tmp);
printf("%d\n", ans);
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int minim(int a, int b, int c) {
if (a <= b and a <= c)
return 1;
else if (b <= a and b <= c)
return 2;
else if (c <= a and c <= b)
return 3;
else
return 0;
}
int main() {
int x, y;
cin >> x >> y;
int side1, side2, side3;
side1 = side2 = side3 = y;
int count = 0;
bool flag = true;
while (flag) {
int mini = minim(side1, side2, side3);
if (mini == 1) {
side1 = min(x, side2 + side3 - 1);
count++;
}
if (mini == 2) {
side2 = min(x, side1 + side3 - 1);
count++;
}
if (mini == 3) {
side3 = min(x, side1 + side2 - 1);
count++;
}
if (side1 == side2 and side2 == side3 and side3 == x) flag = false;
}
cout << count << endl;
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int e[3];
int main() {
int x, y;
while (~scanf("%d%d", &x, &y)) {
int ans = 0;
e[1] = e[2] = e[0] = y;
while (1) {
int t = 0;
for (int i = 0; i < 3; i++) {
if (e[t] > e[i]) t = i;
}
e[t] = e[(t + 1) % 3] + e[(t + 2) % 3] - 1 > x
? x
: e[(t + 1) % 3] + e[(t + 2) % 3] - 1;
ans++;
if (e[0] == e[1] && e[1] == e[2] && e[2] == x) break;
}
printf("%d\n", ans);
}
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | x, y = map(int, input().split())
a, b, c = y, y, y
cnt = 0
while True:
if a >= x and b >= x and c >= x:
break
cnt += 1
if cnt % 3 == 0:
a = b+c - 1
elif cnt % 3 == 1:
b = c + a - 1
elif cnt % 3 == 2:
c = b+a - 1
print(cnt) | PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
private static final boolean TEST_CASES = false;
private static class Solver {
void solve(int testCaseNo) {
int x = IO.nextInt();
int y = IO.nextInt();
if ( y < x ) {
int t = x;
x = y;
y = t;
}
int[] a = new int[3];
a[0] = a[1] = a[2] = x;
int i = 0, res = 0;
while (true) {
if (isDone(a, y)) break;
if (a[i] == y) {
i = (i + 1)%3;
continue;
}
checkNget(a, i, y);
res++;
i = (i + 1)%3;
}
IO.writer.println(res);
}
boolean isDone(int[] a, int y) {
if (a[0] != y) return false;
if (a[1] != y) return false;
if (a[2] != y) return false;
return true;
}
void checkNget(int[] a, int i, int y) {
int j = (i+1)%3;
int k = (i+2)%3;
if (isValid(y, a[j], a[k])) {
a[i] = y;
return;
}
if (y > a[i]) {
a[i] = a[j] + a[k] - 1;
} else {
if (a[j] <= a[k]) {
a[i] = a[k] - a[j] + 1;
} else
a[i] = a[j] - a[k] + 1;
}
}
boolean isValid(int a, int b, int c) {
if (a >= (b + c)) return false;
if (b >= (a + c)) return false;
if (c >= (b + a)) return false;
return true;
}
}
private static class IO {
private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static final PrintWriter writer = new PrintWriter(System.out);
private static StringTokenizer tokenizer = null;
static String nextToken() {
checkTokenizer();
return tokenizer.nextToken();
}
static int nextInt() {
return Integer.parseInt(nextToken());
}
static void close() {
writer.flush();
}
private static boolean isTokenizerEmpty() {
return tokenizer == null || !tokenizer.hasMoreTokens();
}
private static void checkTokenizer() {
while (isTokenizerEmpty()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
private static void go() {
int testCases = TEST_CASES ? IO.nextInt() : 1;
Solver solver = new Solver();
for (int testCase = 0; testCase < testCases; testCase++) {
solver.solve(testCase);
}
}
public static void main(String[] args) {
try {
go();
} finally {
IO.close();
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int solve(int x, int y) {
int cnt = 0;
int a = y, b = y, c = y;
while (a < x || b < x || c < x) {
if (a <= b && a <= c) {
a = b + c - 1;
cnt++;
continue;
} else if (b <= a && b <= c) {
b = a + c - 1;
cnt++;
continue;
} else {
c = a + b - 1;
cnt++;
}
}
return cnt;
}
int main() {
int x, y;
cin >> x >> y;
cout << solve(x, y);
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
template <typename tn>
inline tn next(void) {
tn k;
cin >> k;
return k;
}
template <typename tn>
inline ostream& operator<<(ostream& os, const vector<tn>& v) {
for (unsigned i = 0; i < v.size(); i++) os << v[i] << ' ';
return os;
}
int tri[3];
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
int a, b, cnt = 0;
cin >> a >> b;
for (int i = 0; i < 3; i++) tri[i] = b;
while (!(tri[0] == a && tri[1] == a && tri[2] == a)) {
sort(tri, tri + 3);
for (int i = 0; i < 2; i++) {
int x, y;
switch (i) {
case 0:
x = 1, y = 2;
break;
case 1:
x = 0, y = 2;
break;
case 2:
x = 0, y = 1;
break;
}
if (tri[i] != a) {
tri[i] = min(a, abs(tri[x] + tri[y]) - 1);
cnt++;
break;
}
}
}
cout << cnt << endl;
return ~~(0 - 0);
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
void v(int &a, int &b, int &c) {
int d;
if (c < a) {
swap(a, c);
}
if (c < b) {
swap(b, c);
}
if (a > b) {
swap(a, b);
}
}
string s;
int main() {
int x, y, a[3], ans = 0;
cin >> x >> y;
a[0] = a[1] = a[2] = y;
while (a[0] != x || a[1] != x || a[2] != x) {
v(a[0], a[1], a[2]);
int now = a[0];
a[0] = a[1] + a[2] - 1;
if (a[0] > x) {
a[0] = x;
}
ans++;
}
cout << ans << endl;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class C_MemoryAndDeEvolution_ED {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] input = bf.readLine().trim().split(" ");
int a = Integer.parseInt(input[0]);
int b = Integer.parseInt(input[1]);
int[] arr = { b, b, b };
int num = arr[1] + arr[2] - 1;
int count = 0;
if (num >= a) {
num = a;
}
arr[0] = num;
count++;
int intermediate;
while (!isDone(arr, a)) {
Arrays.sort(arr);
intermediate = arr[1] + arr[2]-1;
if (intermediate > a) {
intermediate = a;
}
arr[0] = intermediate;
count++;
}
System.out.println(count);
}
public static boolean isDone(int[] arr, int a) {
if (arr[0] == a && arr[1] == a && arr[2] == a) {
return true;
}
return false;
}
} | JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 |
import java.util.Scanner;
/**
* @author shayan.hati
* @since 11/09/16.
*/
public class MemoryDevolution {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
int y = scn.nextInt();
int prev = y;
int newVal = y;
int count = 0;
while(newVal+prev-1 < x){
int temp = newVal;
newVal = newVal+prev-1;
prev = temp;
count++;
}
System.out.println(count+3);
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int main() {
int x, y;
cin >> x >> y;
int besta = y, bestb = y, bestc = y;
int turns = 0;
while (true) {
if (besta >= x && bestb >= x && bestc >= x) {
cout << turns << endl;
break;
}
turns++;
if (turns % 3 == 1) besta = bestb + bestc - 1;
if (turns % 3 == 2) bestb = besta + bestc - 1;
if (turns % 3 == 0) bestc = besta + bestb - 1;
}
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #!/usr/bin/env python3.5
import sys
def read_data():
return map(int, next(sys.stdin).split())
def solve(f, t):
if f > t:
f, t = t, f
if f == t:
return 0
a, b, c = f, f, f
count = 0
while a < t:
c = min(a + b - 1, t)
c, b, a = sorted((a, b, c))
count += 1
#print(a, b, c)
if b < t:
#print(t, t, c)
count += 1
if c < t:
#print(t, t, t)
count += 1
return count
if __name__ == "__main__":
f, t = read_data()
print(solve(f, t))
| PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.util.Scanner;
public class Main {
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int s = scan.nextInt(), e = scan.nextInt();
int a = e, b = e, c = e;
long count = 0;
while(a != s || b != s || c != s){
c=a+b-1<s?a+b-1:s;
int temp = c;
c = b;
b = a;
a = temp;
count++;
}
System.out.println(count);
}
} | JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | x, a = map(int, input().split())
b = c = a
res = 0
while a < x:
a, b, c = b, c, b + c - 1
res += 1
print(res)
# Made By Mostafa_Khaled | PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int x, y, ans = 0;
cin >> x >> y;
int a[3] = {y, y, y};
while (a[0] != x || a[1] != x || a[2] != x) {
sort(a, a + 3);
int sum = a[1] + a[2];
if (sum - 1 > x)
a[0] = x;
else
a[0] = sum - 1;
ans++;
}
cout << ans << '\n';
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
void solve() {
int x, y, ans = 0;
cin >> x >> y;
int y1 = y, y2 = y, y3 = y;
int x1 = x, x2 = x, x3 = x;
while (y1 != x1 && y2 != x2 && y3 != x3) {
if (ans % 3 == 0) {
if (y2 + y3 - 1 >= x)
y1 = x;
else
y1 = y2 + y3 - 1;
} else if (ans % 3 == 1) {
if (y1 + y3 - 1 >= x)
y2 = x;
else
y2 = y1 + y3 - 1;
} else if (ans % 3 == 2) {
if (y2 + y1 - 1 >= x)
y3 = x;
else
y3 = y2 + y1 - 1;
}
ans++;
}
cout << ans + 2;
}
int main() {
std::ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int t = 1;
while (t--) {
solve();
}
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.util.*;
import java.io.*;
public class MemoryAndDeEvolution {
public static InputReader in;
public static PrintWriter out;
public static final int MOD = (int) (1e9 + 7);
public static void main(String[] args) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int x = in.nextInt(),
y = in.nextInt();
int result = 0;
int[] sides = new int[]{y, y, y};
while((!(sides[0] == sides[1] && sides[0] == sides[2] && sides[0] == x))) {
Arrays.sort(sides);
sides[0] = Math.min(x, sides[1] + sides[2] - 1);
result++;
}
out.println(result);
out.close();
}
static class Node implements Comparable<Node> {
int next;
long dist;
public Node(int u, int v) {
this.next = u;
this.dist = v;
}
public void print() {
out.println(next + " " + dist + " ");
}
public int compareTo(Node n) {
return Integer.compare(-this.next, -n.next);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | x,y=[int(x) for x in input().split()]
a=[y,y,y]
c=0
while(True):
a.sort()
if(a[2]+a[1]>x):
break
a[0]=a[1]+a[2]-1
c+=1
print(c+3) | PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | a, b = input().split()
x = int(a)
y = int(b)
x_v = [y, y, y]
result = 0
while (x_v[0] != x) or (x != x_v[1] ) or (x != x_v[2]):
x_v.sort()
x_v[0] = min(x, x_v[1] + x_v[2] - 1)
result += 1
print(result)
| PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}
///////////////////////////////////////////////////////////////////////////////////////////
// RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL //
// RR RRR AAAAA HHH HHH IIIIIIIIIII LLL //
// RR RRR AAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHHHHHHHHHH III LLL //
// RRRRRR AAA AAA HHHHHHHHHHH III LLL //
// RR RRR AAAAAAAAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL //
///////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Reader sc=new Reader();
int x=sc.i();
int y=sc.i();
if(x<y*2)
System.out.println(3);
else
{
int arr[]=new int[3];
arr[0]=y;arr[1]=y;arr[2]=y;
int count=0;
while(arr[0]!=x||arr[1]!=x||arr[2]!=x)
{
arr[0]=Math.min(x,arr[1]+arr[2]-1);
Arrays.sort(arr);
count++;
}
System.out.println(count);
}
}
} | JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import sys
y, x = map(int, raw_input().split())
current = [ x, x, x ]
goal = [ y, y, y ]
steps = 0
while current != goal:
best_index, best_value = -1, -1
for i, a in enumerate(current):
b, c = current[(i + 1) % 3], current[(i + 2) % 3]
x = min(y, b + c - 1)
if x > a and x > best_value:
best_index, best_value = i, x
current[best_index] = best_value
steps += 1
print(steps)
| PYTHON |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import math
x, y = map(int, input().split())
res = 0
now = [y, y, y]
while min(now) < x:
res += 1
ind = now.index(min(now))
o1, o2 = (ind + 1) % 3, (ind + 2) % 3
now[ind] = now[o1] + now[o2] - 1
print(res)
| PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.util.*;
import java.io.*;
public class sol
{
/********* SOLUTION STARTS HERE ************/
private static void solve(FastScanner s1, PrintWriter out){
int x = s1.nextInt();
int y = s1.nextInt();
int a[] = new int[3];
for (int i=0;i<3;++i){
a[i] = y;
}
int cost = 0;
while(true){
System.out.println();
int mi = Math.min(a[0],Math.min(a[1],a[2]));
int miar = 0;
int maar = 0;
for(int i=0;i<3;++i){
if (a[i] == mi){
miar = i;
break;
}
}
int ma = Math.max(a[0],Math.max(a[1],a[2]));
for(int i=0;i<3;++i){
if (a[i] == ma && i != miar){
maar = i;
break;
}
}
if(mi == x && ma == x){
break;
}
++cost;
int midr = 0;
for(int i=0;i<3;++i){
if (i != miar && i != maar){
midr = i;
}
}
int cal = a[maar]+a[midr]-1;
if (cal < x){
a[miar] = cal;
} else {
a[miar] = x;
}
}
System.out.println(cost);
}
/********** TEMPLATE STARTS HERE ***********/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/*********** TEMPLATE ENDS HERE *************/
} | JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int main() {
long long x, y, a[3], d = 0;
cin >> x >> y;
a[0] = a[1] = a[2] = y;
while (a[0] != x) {
a[0] = min(a[2] + a[1] - 1, x);
sort(a, a + 3);
d++;
}
cout << d;
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int x=in.nextInt();
int y=in.nextInt();
int[] a = new int[] {y,y,y};
int recent=0;
int count=0;
while(a[recent]<x){
count++;
if(recent==0){
a[0]=a[1]+a[2]-1;
}
if(recent==2){
a[2]=a[1]+a[0]-1;
}
if(recent==1){
a[1]=a[2]+a[0]-1;
}
recent++;
if(recent==3)
recent=0;
}
System.out.println(count);
}
static class Scanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Scanner(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine(){
String fullLine=null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine=reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.io.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;
public class Palindrome {
static double eps=(double)1e-6;
static long mod=(int)1e9+7;
public static void main(String args[]){
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Scanner sc=new Scanner(System.in);
//----------My Code----------
int x=in.nextInt();
int y=in.nextInt();
int arr[]=new int[3];
arr[0]=y;
arr[1]=y;
arr[2]=y;
int steps=0;
while(arr[0]<x)
{
arr[0]=arr[1]+arr[2]-1;
Arrays.sort(arr);
steps++;
}
System.out.println(steps);
//---------------The End------------------
out.close();
}
static class TrieNode{
boolean isLeaf;
int b;
TrieNode[] a=new TrieNode[256];
}
static void insert(String key,TrieNode root){
TrieNode temp=root;
for(int i=0;i<key.length();i++){
// System.out.println(i);
if(temp.a[key.charAt(i)]==null){
temp.a[key.charAt(i)]=new TrieNode();
}
temp.a[key.charAt(i)].b+=1;
temp=temp.a[key.charAt(i)];
}
temp.isLeaf=true;
}
static TrieNode search(String key,TrieNode root){
TrieNode temp=root;
for(int i=0;i<key.length();i++){
if(temp.a[key.charAt(i)]==null)
return null;
temp=temp.a[key.charAt(i)];
}
return (temp);
}
static String max(String key,TrieNode root){
TrieNode temp=root;
String res="";
for(int i=0;i<key.length();i++){
if(temp.a[(key.charAt(i)-'0')^1]!=null){
// System.out.println("Hetr");
temp=temp.a[(key.charAt(i)-'0')^1];
res+="1";
}
else if(temp.a[(key.charAt(i)-'0')]!=null){
//System.out.println("Hetr");
temp=temp.a[(key.charAt(i)-'0')];
res+="0";
}
}
// System.out.println(res+"jj");
return res;
}
static void remove(String key,TrieNode root){
TrieNode temp=root;
for(int i=0;i<key.length();i++){
if(temp==null)
return;
if(temp.a[(key.charAt(i)-'0')]!=null&&temp.a[key.charAt(i)-'0'].b>1){
temp.a[(key.charAt(i)-'0')].b--;
temp=temp.a[(key.charAt(i)-'0')];
}
else
{
temp.a[key.charAt(i)-'0']=null;
return;
}
}
if(temp!=null)
temp.isLeaf=false;
}
public static void printSorted(TrieNode node, String s) {
for (int ch = 0; ch < node.a.length; ch++) {
TrieNode child = node.a[ch];
if (child != null){
printSorted(child, s + (char)(ch));
}
}
if (node.isLeaf) {
System.out.println(s);
}
}
private static void permutation(String prefix, String str,HashSet<String> hs) {
int n = str.length();
if (n == 0) hs.add(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n),hs);
}
}
static int recursiveBinarySearch(int[] sortedArray, int start, int end, int key) {
if (start <= end) {
int mid = start + (end - start) / 2;
if (key < sortedArray[mid]) {
return recursiveBinarySearch(sortedArray, start, mid-1, key);
} else if (key > sortedArray[mid]) {
return recursiveBinarySearch(sortedArray, mid+1, end , key);
} else {
return mid;
}
}
return -(start + 1);
}
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
static long gcd(long x, long y)
{
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
static class pair implements Comparable<pair> {
int x;
int y;
//int i;
pair(int xx,int yy){
x=xx;
y=yy;
//i=ii;
}
@Override
public int compareTo(pair arg0) {
return Long.compare(this.y, arg0.y);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine(){
String fullLine=null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine=reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | s=input().split()
a=int(s[0])
b=int(s[1])
count=0
g=0
C=list(range(3))
C[0]=b
C[1]=b
C[2]=b
while C[0]!=a or C[1]!=a or C[2]!=a:
if C[1]+C[2]>a:
C[0]=a
count+=1
g=C[2]
C[2]=C[1]
C[1]=C[0]
C[0]=g
else:
C[0]=C[1]+C[2]-1
count+=1
g=C[2]
C[2]=C[1]
C[1]=C[0]
C[0]=g
print(count)
| PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int main() {
int x, y, ans = 0;
cin >> y >> x;
vector<int> xa = {x, x, x};
vector<int> ya = {y, y, y};
while (xa != ya) {
sort(xa.begin(), xa.end());
int temp = xa[1] + xa[2] - 1;
if (temp > y)
xa[0] = y;
else
xa[0] = temp;
ans++;
}
cout << ans << endl;
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 |
import java.io.*;
import java.util.*;
public class C370 {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int x,y,a,b,c,ans,t,t2,i;
x = sc.nextInt(); y = sc.nextInt();
ans = 0;
a = b = c = y;
while(true) {
a = Math.min(x , b + c - 1);
t = a; a = b; b = c; c = t;
ans++;
if (((a==x) && (c==x)) && (b==x)) break;
}
System.out.println(ans);
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int T = 3;
const long long MAX = 1000000001;
long long n, m, k;
int N[T];
int A[T];
int x, y;
void foo() { N[0] = min(x, N[1] + N[2] - 1); }
int main() {
cin >> x >> y;
N[0] = N[1] = N[2] = y;
int ans = 0;
while (N[0] != x || N[1] != x || N[2] != x) {
ans++;
sort(N, N + 3);
foo();
}
cout << ans << endl;
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int a[4], k, ans = 0;
int main() {
scanf("%d%d", &k, &a[1]);
a[2] = a[3] = a[1];
if (a[1] + a[2] > k) {
printf("3");
return 0;
}
while (1) {
sort(a + 1, a + 4);
if (a[1] + a[2] > k)
break;
else {
ans++;
a[1] = min(a[3] + a[2] - 1, k);
}
}
printf("%d", ans + 2);
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
struct sjx {
int b[3];
sjx(int x) {
for (int i = 0; i < 3; i++) b[i] = x;
}
bool ok(int x) {
for (int i = 0; i < 3; i++)
if (b[i] != x) return false;
return true;
}
void change(int x) {
sort(b, b + 3);
int MAX = b[1] + b[2] - 1;
b[0] = min(x, MAX);
}
};
int main() {
int x, y;
scanf("%d %d", &x, &y);
sjx s(y);
int cnt = 0;
while (1) {
if (s.ok(x)) break;
s.change(x);
cnt++;
}
printf("%d\n", cnt);
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.util.Scanner;
public class C712 {
public static void main(String... xxx){
Scanner sc = new Scanner(System.in);
int x = sc.nextInt(), y = sc.nextInt();
int ans = 0;
int a = y, b = y, c = y;
while (true)
{
if (a >= x && b >= x && c >= x){System.out.println(ans);return;}
if (ans%3 == 0) a = b + c - 1;
else if (ans % 3 == 1)b = a + c - 1;
else c = a + b - 1;
ans++;
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
int qmin(int a, int b, int c) {
int d = min(a, min(b, c));
if (a == d) return 1;
if (b == d) return 2;
if (c == d) return 3;
}
int main() {
int x, y;
int ans = 0;
scanf("%d %d", &x, &y);
int a = y, b = y, c = y;
while (1) {
int op = qmin(a, b, c);
if (a == x && b == x && c == x) break;
if (op == 1) {
ans++;
a = b + c - 1;
if (a > x) a = x;
}
if (op == 2) {
ans++;
b = a + c - 1;
if (b > x) b = x;
}
if (op == 3) {
ans++;
c = a + b - 1;
if (c > x) c = x;
}
}
printf("%d\n", ans);
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
const int INF = 1e9 + 7;
int x, y, e[3];
int calc(int a, int b, int c) {
e[0] = a, e[1] = b, e[2] = c;
sort(e, e + 3);
int ret = 0;
while (e[2] != y) {
e[2] = max(y, e[1] - e[0] + 1);
sort(e, e + 3);
++ret;
}
return ret;
}
int solve(int x, int y) {
if (x < 2 * y) return 3;
int ans = 0;
for (int i = (0); i < (3); ++i) e[i] = y;
while (e[0] != x) {
e[0] = min(x, e[1] + e[2] - 1);
sort(e, e + 3);
++ans;
}
return ans;
}
int main() {
scanf("%d%d", &x, &y);
printf("%d", solve(x, y));
return 0;
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 |
import java.io.*;
import java.util.*;
// this is not good for reading double values.
public class third {
static long m = 100000007;
public static void main(String[] args) throws IOException {
Reader r = new Reader();
PrintWriter o = new PrintWriter(System.out, false);
// PrintWriter o = new PrintWriter(new FileOutputStream("file" +
// ".out"));
int a = r.nextInt();
int b = r.nextInt();
if (a == b)
o.println(0);
else if (a / 2 < b) {
o.println(3);
} else if (a / 2 == b)
o.println(4);
else {
int b1 = b, b2 = b, b3 = b;
int count = 0;
while ((b1 != a) && (b2 != a) && (b3 != a)) {
int b1b2 = b1 + b2;
int b2b3 = b2 + b3;
int b1b3 = b1 + b3;
if (b1b2 > a)
b3 = a;
else if (b2b3 > a)
b1 = a;
else if (b1b3 > a)
b2 = a;
else {
int min;
b1b2 = Math.abs(a - b1b2);
b2b3 = Math.abs(a - b2b3);
b1b3 = Math.abs(a - b1b3);
if (b1b2 >= b2b3)
min = b2b3;
else
min = b1b2;
if (min >= b1b3)
min = b1b3;
else
min = min;
if (min == b1b2) {
b3 = (b1 + b2 - 1);
if (b3 > a)
b3 = a;
} else if (min == b2b3) {
b1 = b2 + b3 - 1;
if (b1 > a)
b1 = a;
} else if (min == b1b3) {
b2 = b1 + b3 - 1;
if (b2 > a)
b2 = a;
}
}
//o.println(b1 + " " + b2 + " " + b3);
count++;
//if ((b1 + b2 <= b3) || (b2 + b3 <= b1) || (b1 + b3 <= b2)) {
// o.println("ERROR " + count);
// break;
//}
}
o.println(count + 2);
}
o.close();
}
// input/output
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int size) throws IOException {
int[] arr = new int[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
public long[] readLongArray(int size) throws IOException {
long[] arr = new long[size];
for (int i = 0; i < size; i++)
arr[i] = nextLong();
return arr;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | # import itertools
import bisect
# import math
from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(10 ** 5)
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
slmii = lambda: sorted(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
def lcm(a, b): return (a * b) // gcd(a, b)
def main():
# for _ in " " * int(input()):
x, y = mii()
cnt = 0
a, b, c = y, y, y
while max(a, b, c) < x:
ss = sorted([a, b, c])
a = ss[0]
b = ss[1]
c = ss[2]
a = min(x, b + c - 1)
cnt += 1
print(cnt + 2)
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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
| PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream is;
OutputStream os;
try {
is = new FileInputStream("input.txt");
os = new FileOutputStream("output.txt");
} catch (FileNotFoundException e) {
is = System.in;
os = System.out;
}
InputReader in = new InputReader(is);
PrintWriter out = new PrintWriter(os);
Contest contest = new Contest(in, out);
contest.solve();
out.close();
}
static class Contest {
InputReader in;
PrintWriter out;
public Contest(InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
public void solve() {
int x = in.nextInt();
int y = in.nextInt();
int[] a = {y, y, y};
int ans = 0;
while(a[0] != x || a[1] != x || a[2] != x)
{
Arrays.sort(a);
int nv = a[0];
while(nv < x && a[1] + a[2] > nv + 1 && a[1] + nv + 1 > a[2] && a[2] + nv + 1 > a[1])
nv++;
a[0] = nv;
//out.printf("%d %d %d\n", a[0], a[1], a[2]);
ans++;
}
out.print(ans);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer tk;
public InputReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
tk = null;
}
public String next() {
if(tk == null || !tk.hasMoreTokens()) {
try {
tk = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tk.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public Long nextLong() {
return Long.parseLong(next());
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastInput in, PrintWriter out) {
int x = in.nextInt();
int y = in.nextInt();
int a = y;
int b = y;
int c = y;
int res = 0;
while (!isValid(a, b, c, x)) {
++res;
if (res % 3 == 1) a = b + c - 1;
if (res % 3 == 2) b = a + c - 1;
if (res % 3 == 0) c = a + b - 1;
}
out.print(res);
}
private boolean isValid(int a, int b, int c, int x) {
return a >= x && b >= x && c >= x;
}
}
static class FastInput {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastInput(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | a, b = map(int, input().split())
if(a> b):
a, b =b, a
l = [a, a, a]
# print(l)
ans = 0
while(True):
if(sum(l) == 3*b):
break
for i in range(3):
if(l[i]<b):
temp = sum(l)-l[i]
l[i] = min(b, temp-1)
ans +=1
if(sum(l) == 3*b):
break
if(sum(l) == 3*b):
break
print(ans) | PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
int main() {
int num1, num2, cnt, a, b, c;
cin >> num1 >> num2;
a = b = c = num2;
cnt = 0;
while (1) {
if (a >= num1 && b >= num1 && c >= num1) {
cout << cnt << endl;
break;
}
cnt++;
if (cnt % 3 == 1) {
a = b + c - 1;
} else if (cnt % 3 == 2) {
b = a + c - 1;
} else if (cnt % 3 == 0) {
c = a + b - 1;
}
}
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int src = in.nextInt(), dst = in.nextInt();
out.print(doCalc(new int[]{dst, dst, dst}, src));
}
int doCalc(int[] abc, int dst) {
if (abc[0] == abc[1] && abc[1] == abc[2] && abc[2] == dst) return 0;
Arrays.sort(abc);
abc[0] = Math.min(abc[1] + abc[2] - 1, dst);
return 1 + doCalc(abc, dst);
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| JAVA |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 |
x,y = map(int, raw_input().split(' '))
i = j = k = y
c = 0
while i != x or j != x or k != x:
if i == x:
c =c
elif x>j+k-1:
i = j+k-1
c += 1
elif x<j+k-1:
i = x
c += 1
if j == x:
c = c
elif x>i+k-1:
j = i+k-1
c += 1
elif x<i+k-1:
j = x
c += 1
if k == x:
c = c
elif x>i+j-1:
k = i+j-1
c += 1
elif x<j+i-1:
k = x
c += 1
print c
| PYTHON |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | end,start=map(int,raw_input().split())
sides=[]
for i in range(3):
sides.append(start)
count=0
while(1):
#print sides
if(sides[0],sides[1],sides[2])==(end,end,end):
break
sides.sort()
sides[0]=min(sides[1]+sides[2]-1,end)
count+=1
print count
| PYTHON |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 9;
const long long int inf = INT_MAX;
bool cmp(pair<int, int> &a, pair<int, int> &b) { return (a.first > b.first); }
vector<pair<int, int> > adj[MAX];
long long int dis[MAX];
int par[MAX];
int main() {
int q;
int n, m;
int a[MAX];
int x, y;
cin >> x >> y;
int ba = y, bb = y, bc = y, i = 0;
while (1) {
if (ba >= x && bb >= x && bc >= x) {
cout << i;
break;
}
i++;
if (i % 3 == 1) {
ba = bb + bc - 1;
} else if (i % 3 == 2) {
bb = ba + bc - 1;
} else {
bc = ba + bb - 1;
}
}
}
| CPP |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | x, y = map(int, input().split())
arr, res = [y, y, y], 0
while arr[0] < x:
res += 1
arr[0] = min(arr[1] + arr[2] - 1, x)
arr.sort()
print(res)
| PYTHON3 |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <image>
<image>. | 2 | 9 | lst=list(map(int,input().split()))
y=lst[1]
x=lst[0]
res=0
ba,bc,bd=y,y,y
while True:
if ba>=x and bb>=x and bc>=x:
print(res)
break
res+=1
if res%3==0:
ba=bb+bc-1
if res%3==1:
bb=ba+bc-1
if res%3==2:
bc=bb+ba-1
| PYTHON3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.