DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Nature-Friendly Village

Back to problem

Editorial

For an empty lot ccc, let w(c)w(c)w(c) be the number of houses among its at most 888 neighboring cells.

If one tree is planted on ccc, that tree is counted once for every adjacent house. Therefore it increases the required total by exactly w(c)w(c)w(c). Contributions from different empty lots are independent.

The task is thus to choose some values w(c)w(c)w(c), each between 000 and 888, so that their sum is at least KKK while minimizing how many values are chosen. For any fixed number of chosen lots, the largest possible sum is obtained by taking the largest values first. Hence it is optimal to take lots in the order 8,7,…,18,7,\ldots,18,7.

If the sum of w(c)w(c)w(c) over all empty lots is smaller than KKK, the requirement is impossible and the answer is -1. If K=0K=0K=0, the answer is 000.

Each w(c)w(c)w(c) is found by checking at most 888 neighboring cells. Since only the values 0,1,…,80,1,\ldots,80,1,…,8 are possible, it is enough to count the frequency of each value; sorting is unnecessary. The time complexity is O(RC)O(RC)O(R per test case and overall. The grid uses memory.

Solution written by GPT5.6

,
…
,
1
C
)
O(∑RC)O(\sum RC)O(∑RC)
O(RC)O(RC)O(RC)