1. 程式人生 > >每日一水之 luogu2907 [USACO08OPEN]農場周圍的道路Roads Around The Farm

每日一水之 luogu2907 [USACO08OPEN]農場周圍的道路Roads Around The Farm

tin etime 輸入輸出 empty arm around class using top

題目描述

Farmer John‘s cows have taken an interest in exploring the territory around the farm. Initially, all N (1 <= N <= 1,000,000,000) cows commence traveling down a road in one big group. Upon encountering a fork in the road, the group sometimes chooses to break into two smaller (nonempty) groups with each group continuing down one of the roads. When one of those groups arrives at another fork, it might split again, and so on.

The cows have crafted a peculiar way of splitting: if they can split into two groups such that the sizes of the groups differ by exactly K (1 <= K <= 1000), then they will split in that way; otherwise, they stop exploring and just start grazing peacefully.

Assuming that there will always be new forks in the road, compute the final number of groups of peacefully grazing cows.

約翰的N(1≤N≤1,000,000,000)只奶牛要出發去探索牧場四周的土地.她們將沿著一條路走,一直走到三岔路口(可以認為所有的路口都是這樣的).這時候,這一群奶牛可能會分成兩群,分別沿著接下來的兩條路繼續走.如果她們再次走到三岔路口,那麽仍有可能繼續分裂成兩群繼續走. 奶牛的分裂方式十分古怪:如果這一群奶牛可以精確地分成兩部分,這兩部分的牛數恰好相差K(1≤K≤1000),那麽在三岔路口牛群就會分裂.否則,牛群不會分裂,她們都將在這裏待下去,平靜地吃草. 請計算,最終將會有多少群奶牛在平靜地吃草.

輸入輸出格式

輸入格式:

  • Line 1: Two space-separated integers: N and K

輸出格式:

  • Line 1: A single integer representing the number of groups of grazing cows

輸入輸出樣例

輸入樣例#1:
6 2 
輸出樣例#1:
3 

說明

There are 6 cows and the difference in group sizes is 2.

There are 3 final groups (with 2, 1, and 3 cows in them).

6 / \ 2 4 / \ 1 3

題解

看到這道題第一眼反應就是搜索了吧。第一次寫的搜索竟然沒過,由於判斷條件太多導致超時了QAQ。後來加了優化,代碼如下:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 
 5 using namespace std;
 6 int ans,n,k;
 7 void dfs(int x) {
 8     if(x<k+2 || (x+k)&1) { 
 9     //x<k+2表示現在數量不足以分成兩組,(x+k)&1表示數量單數不可能分成兩組(可不能把牛牛分成兩半ovo) 
10         ans++;
11         return;
12     }
13     else {
14         dfs((x-k)>>1);
15         dfs(((x-k)>>1)+k);
16     }
17 }
18 int main() {
19     scanf("%d%d",&n,&k);
20     dfs(n);
21     printf("%d",ans);
22     return 0;
23 }

ps:每日一水有利於身體健康哦ovo

每日一水之 luogu2907 [USACO08OPEN]農場周圍的道路Roads Around The Farm