В общем, была задача на оптимизацию плана работ: есть набор заказов, и в каждом N тасков. Таски могут зависеть друг от друга или нет, имеют длительность и тип. Ещё есть M работников, каждый из которых может выполнять таски только определённых типов, причём, у каждого своя скорость.
Если все таски в заказе выполнены, фирма получает сколько-то денег. У заказа есть дедлайн, за просрочку штраф (за каждый день просрочки), который вычитается из цены заказа. И ещё фирма тратит деньги за каждый день своей работы независимо от того, как загружены её сотрудники (то есть просто платит зарплаты по сути). Ещё важен учёт праздников и выходных.
Нужно заработать на определённом наборе заказов и работников как можно больше денег. Полный текст задачи и код программы проверки есть в репозитории. Эта задача является изменённым заказом, который мы с напарником решали в реальной жизни: оптимизация работы печатных станков для типографии. Правда, тогда и мы справились так себе, и заказчик в итоге сначала захотел всё вручную сам делать, а потом и вовсе похоронил проект при смене директора.
!!! Не читайте дальше, если хотите сначала попробовать решить самостоятельно, потому что я сейчас опишу эффективные подходы и результаты.
________________________________________
Так вот. Мы с другим экспертом Андреем сразу сели и написали разные варианты, чтобы задать шкалу, по которой будем оценивать решения команд. За пару часов я собрал примитивный жадный алгоритм, который сортировал заказы по прибыльности и укладывал в сетку кое-как, это дало нам нижнюю оценку. Мой алгоритм заработал ~75 млн виртуальных рублей, мы решили для оценки поставить нижней границей 40 млн. То есть всё, что ещё ниже, оценивалось в ноль баллов за качество оптимизации.
Затем Андрей закрылся дома на три дня и вышел на свет со сложным жадным алгоритмом, который очень хитро сортировал заказы и очень хитро укладывал их в сетку, попутно выбирая разные способы этой укладки в зависимости от конкретного заказа. Это позволило заработать ~275 млн рублей. Мы сделали верхней границей для оценки 280 млн.
К сожалению, в итоге только две команды из десяти прошли нижнюю границу, заработав, соответственно, ~91 и ~105 млн. К верхней границе не приблизился никто. И у четырёх команд алгоритм вообще не смог уложить без нарушений задачи в сетку (то есть, например, произвольно менял длительности, накладывал задачи друг на друга, давал одному работнику две задачи в один момент и так далее). Важной ошибкой команд, на мой взгляд, являлся тот факт, что никто не воспользовался возможностью запустить алгоритм на несколько минут и дать ему поработать. По условиям задания, можно было тянуть до 5 минут на одну оптимизацию, но по факту решения команд отрабатывали за единицы и десятки секунд.
На самом конкурсе, пока команды работали, я решил попробовать сделать быстрое (по времени написания) но эффективное решение. Сначала попробовал жадную сортировку + доведение до лучшего варианта методом имитации отжига. В качестве нового состояния я просто менял местами заказы целиком. Этот вариант работал пару минут и дал мне около ~200 млн дохода. К слову, команда-лидер использовала такой же подход, просто не докрутила число итераций и температуру.
Ну и потом я взял готовую либу по реализации классической генетики с особями и скрещиванием. Особью был массив с приоритетами заказов (которые конечно же нужно было аккуратно уложить чистым алгоритмом). Тип скрещивания: scattered. Всего 15 поколений по 20 особей, и это за минуту-полторы давало ~230-240 млн. Считаю, что для конкурса это самый лучший выбор: пишется одним человеком за день и даёт почти максимум, при этом легко настраивается на нужную длительность работы, легко параллелится.
Ну а потом уже дома я посидел и накодил свой вариант сложного жадного с плавающим окном перебора отсортированных заказов и плавающей же укладкой по работникам. Такая штука за две минуты зарабатывает ~281 млн. Но за три дня в условиях стресса я бы такое не сделал, скорее всего.
#dev
#SON DƏQİQƏ
‼️Böyük Britaniyanın müdafiə naziri John Healey bildirib ki, Rusiyaya məxsus sualtı qayıqlar Atlantik okeanında “gizli əməliyyatlar” həyata keçirməyə çalışır.
https://t.me/Tehlil_Tenqid_tv
🤩🤩🤩🤩🤩
Most Iranians have lived their whole lives under the Iranian regime, which took power in a 1979 revolution that toppled the monarchy, only to replace it with autocratic clerics.
It is hard to assess support for the government in a country with such a heavily restricted media climate, and where open dissent can mean jail and death.
Yet, for almost two decades, protest movements have managed to thrive, often sparked by political unrest, a sudden rise in fuel prices, economic turmoil or the repression of women’s rights.
In 2009, in what was known as the Green movement, hundreds of thousands of people took to the streets over disputed presidential elections. The protests were met with a bloody state crackdown.
In 2022, one of most powerful uprisings, the Woman, Life, Freedom movement, was sparked by the death in custody of Mahsa Amini over her alleged improper wearing of the hijab.
The most recent wave of protests began in late December. They began as small-scale strikes in Tehran’s bazaar over plunging currency. As they spread into countrywide rallies of mass upset, security forces launched one of their deadliest crackdowns, killing thousands.
An Iranian doctor who treated protesters in January for gunshot wounds said he still had some hope the war would “at least result in real change”.
“What we fear most is the war stopping now in its current stage,” he said. “Then we’ll be left with the same people who massacred us last month … only stronger.”
But many others in the anti-regime movement are hearing reports of newborn babies being killed by the US and Israeli strikes, and conclude simply that now three governments, rather than one, are killing Iranians.
A protester in Tehran said: “A significant portion of the people I’ve been speaking to, after witnessing the killing of civilians, have altered their perception of military intervention.”
#Ali#Khamenei#son#trump#war#killing
📱American Оbserver - Stay up to date on all important events
🇺🇸
Trump Suits In Favor of Wrapping Up the War. But What’s Next?
🤩🤩🤩🤩🤩
After years of arrests, disappearances and mass killings of protesters, the hatred in Iran from some quarters for the hardline, oppressive governing regime had boiled into such a desperate rage that many believed Trump’s promise that the US would “come to their rescue”.
Now, after a fortnight of war, with US and Israeli airstrikes killing hundreds as they hit residential blocks, shops, fuel depots and even a school, the mood is changing.
“They are also lying! Like the regime has been lying to us,” said Amir, a student at the University of Tehran. “You are all worse than each other.”
The anti-regime protester has let himself hope for more from the US and Israel, which on the first day of the war had swiftly killed Iran’s most feared and powerful man, the supreme leader.
Yet the regime lives on, with Ayatollah Ali Khamenei’s son quickly appointed to replace him, while Israel has widened and intensified its attacks on the country of more than 90 million people.
“We’re tense. We are really tense,” said Amir. “I feel worse when I am alone. Khamenei’s death has left us with this weird sense of emptiness. Like I am now forced to think about the future, which seems so chaotic right now. We never got to look at him in the eye. He died just like that? Without facing justice for what he did to us?”
The turning point for Amir was the Israeli strikes on fuel depots in Tehran last week, with one attack on the Shahran oil depot overshadowing the capital with black smoke. A rain shower later covered trees, homes and cars with layers of toxic oil.
“I genuinely believe now they [the US and Israel] didn’t have a plan. I was still hoping I was wrong, but the Shahran attack changed the way I look at this war right now,” he said.
“If the regime is what you want to hit, even if you think these depots were used by the regime, where do you draw the line? What about us, the ordinary Iranians? We rely on this civil infrastructure. Why take away our ability to govern in the future? Who can rebuild utter ruins?”
Amir said he now had constant anxiety about Iran “turning into another Iraq”, a country the US invaded in 2003, promising freedom but delivering a civil war.
Israeli leaders have also previously called on Palestinians in Gaza and the Lebanese people to rise up against oppression, only to later kill them in large numbers.
“My heart is so heavy,” said Amir. “I don’t even have tears left. Only anger and more anger. At this regime, and them,” he added, referring to the US and Israel.
Others people also have a shift in their attitudes towards the war, especially after the attack on oil depots, but also after seeing images of the country’s heritage sites damaged.
#Ali#Khamenei#son#trump#war#killing
📱American Оbserver - Stay up to date on all important events
🇺🇸
Muammar Gaddafi’s Son Has Been Killed in Tripoli
Saif al-Islam Gaddafi, the son of the late Libyan dictator Muammar Gaddafi and for years the second most powerful person in the country, has been killed in a village south-west of Tripoli, officials said on Tuesday night.
The 53-year-old died from gunshot wounds in the town of Zintan, 85 miles south-west of the capital, according to the Libyan attorney general’s office. Gaddafi’s own office said he was killed in his home by masked assailants.
Once seen as a pro-western reformer who might usher Libya towards constitutional change, Gaddafi quickly backed his father’s violent crackdown on nationwide popular protests in 2011.
The international criminal court in the same year issued a warrant against him for crimes against humanity over the repression, an accusation echoed by a Tripoli court in 2015.
The Libyan chief prosecutor’s office said it was looking for suspects and had dispatched forensic experts to the village, but did not provide further details of the killing.
According to Gaddafi’s office, four masked men had stormed his house, turned off its cameras and clashed with him before killing him, in what it described as a “cowardly and treacherous assassination”.
His sister, by contrast, told Libyan TV that he had died near the border with Algeria.
His father was eventually toppled with assistance from Nato, and killed in 2011, ending four decades of rule. The country has since been consumed by fighting between different militias and remains divided 15 years later, with two rival governments controlling different parts of the country.
Saif al-Islam Gaddafi tried to flee Libya for neighbouring Niger in 2011 but was caught by a militia and was imprisoned for six years in Zintan, before being freed in 2017 as part of an amnesty deal.
When Gaddafi was captured in the Sahara in 2011 after months on the run, the figure known for his jeans and sweater had a thick black beard and was wearing flowing khaki robes – dressed to blend in with the nomads who were hiding him.
Four years after he was released, Gaddafi announced himself as a candidate for Libya’s 2021 presidential elections.
The announcement provoked outrage from those who had suffered under his father’s dictatorship, and from anti-Gaddafi militias.
Rebel groups rejected his candidacy and he was disqualified owing to his 2015 conviction of war crimes, with the election ultimately collapsing in the end.
#muammar#gaddafi#son#killed
📱American Оbserver - Stay up to date on all important events
🇺🇸
⌨️⌨️⌨️⌨️⌨️
The appointment of Mojtaba Khamenei was welcomed by Yemen’s Houthi rebels, who are backed by the Iranian regime.
“We congratulate the Islamic Republic of Iran, its leadership and people, on the selection of Sayyid Mojtaba Khamenei as Supreme Leader of the Islamic Revolution at this important and pivotal juncture,” the group said in a statement on Telegram.
Mojtaba Khamenei’s elevation marks the first time since the 1979 Islamic revolution that Iran’s supreme leadership has passed from father to son.
It is a development likely to ignite debate inside Iran about the emergence of a dynastic system in a state founded explicitly to overthrow hereditary rule after the shah.
Ayatollah Ali Khamenei, who ruled for 37 years, was killed in a US-Israeli strike on Tehran on 28 February, on the first day of the war with Iran.
Across Iran’s political and security establishment, officials moved swiftly to welcome the appointment of Mojtaba Khamenei as the country’s new supreme leader.
The Revolutionary Guards declared they stood ready to follow him, signalling broad backing from the country’s core institutions.
Earlier in the day, in a post on X in Farsi, the Israeli military said it would continue pursuing every successor of Ali Khamenei and would pursue every person who sought to appoint a successor for him.
For many analysts, Khamenei’s appointment is a symbolic move designed to make the regime still appear strong and determined not to bow to western pressure.
The 56-year-old cleric has never held elected office nor formally occupied a senior position within Iran’s government. He has spent much of his life at the centre of power in Iran while remaining largely out of public view.
To his supporters, Khamenei represents continuity with the ideological line established by Ayatollah Ruhollah Khomeini and maintained by his father. To critics, his rise raises uncomfortable questions about the concentration of power – and the possibility of hereditary leadership in a state founded in revolt against monarchy.
Oil prices surged more than 25% on Monday to their highest levels since mid-2022, as major Middle Eastern oil producers cut supply because they cannot safely send shipments through the strait of Hormuz to refiners worldwide.
Traffic through the strait was largely closed after Iran attacked at least five ships, with a limited number of tankers transiting, choking off a key artery accounting for about 20% of global oil and LNG supply.
#khamenei#mojtaba#son#iran#leader#rule
📱American Оbserver - Stay up to date on all important events
🇺🇸
Ali Khamenei’s Second Son Took His Place
Who is He?
⌨️⌨️⌨️⌨️⌨️
Mojtaba Khamenei, the second son of the late Iranian supreme leader Ayatollah Ali Khamenei, has been chosen as his successor, as the war enters its 10th day and fresh missile and drone strikes reverberate across the Middle East.
After members of the clerical body responsible for selecting Iran’s highest authority announced the decision on Sunday, Iranian institutions and politicians, from the foreign ministry to lawmakers, issued statements expressing their allegiance.
“We will obey the commander-in-chief until the last drop of our blood,” a statement from the defence council said.
The move could lead to a further escalation of the war, given Donald Trump had already acknowledged that Mojtaba Khamenei was the most likely successor and made clear he considered him an “unacceptable” choice.
The US president said earlier on Sunday that Iran’s next supreme leader was “not going to last long” if Tehran did not get his approval first.
When asked about the appointment during an interview with the Times of Israel published late on Sunday, Trump was reported as saying: “We’ll see what happens.”
In the same interview, Trump said a decision on when to end the war would be a “mutual” one, together with Netanyahu.
Trump also asserted that Iran would have destroyed Israel if he and Netanyahu had not been around. “Iran was going to destroy Israel and everything else around it (…) We’ve worked together. We’ve destroyed a country that wanted to destroy Israel,” he was quoted as saying.
The Israeli military said it had launched a wave of strikes on Monday targeting “regime infrastructure” in central Iran, the first such announcement since the appointment of the new supreme leader.
The military also announced strikes on the Iran-backed militant group Hezbollah in Lebanon.
Iran and its proxies appeared to have launched attacks, too, with rocket and drone strikes targeting a US diplomatic facility near Baghdad’s international airport that were intercepted by the C-RAM defence system, said police sources.
A drone strike targeted a US military base near Erbil airport in Iraqi Kurdistan, security sources said, while Saudi authorities reported intercepting a drone east of its northern al-Jawf region.
In Bahrain, the health ministry reported 32 people were wounded overnight by an Iranian drone attack on the island of Sitra.
They include a 17-year-old girl who suffered severe head and eye injuries, and a two-month-old baby, according to the ministry.
Iranian state media also showed a projectile said to have been launched at Israel bearing the slogan: “At your command, Sayyid Mojtaba,” using an Islamic honorific.
#khamenei#mojtaba#son#iran#leader#rule
📱American Оbserver - Stay up to date on all important events
🇺🇸