Walking Between Houses
There are nn houses in a row. They are numbered from 11 to nn in order from left to right. Initially you are in the house 11.
You have to perform kk moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house xx to the house yy, the total distance you walked increases by |x−y||x−y| units of distance, where |a||a| is the absolute value of aa. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).
Your goal is to walk exactly ss units of distance in total.
If it is impossible, print "NO". Otherwise print "YES" and any of the ways to do that. Remember that you should do exactly kk moves.
The first line of the input contains three integers nn, kk, ss (2≤n≤1092≤n≤109, 1≤k≤2⋅1051≤k≤2⋅105, 1≤s≤10181≤s≤1018) — the number of houses, the number of moves and the total distance you want to walk.
If you cannot perform kk moves with total walking distance equal to ss, print "NO".
Otherwise print "YES" on the first line and then print exactly kk integers hihi (1≤hi≤n1≤hi≤n) on the second line, where hihi is the house you visit on the ii-th move.
For each jj from 11 to k−1k−1 the following condition should be satisfied: hj≠hj+1hj≠hj+1. Also h1≠1h1≠1 should be satisfied.
10 2 15
YES
10 4
10 9 45
YES
10 1 10 1 2 1 2 1 6
10 9 81
YES
10 1 10 1 10 1 10 1 10
10 9 82
NO
题目意思:
现在有n个房子排成一列,编号为1~n,起初你在第1个房子里,现在你要进行k次移动,每次移动一都可以从一个房子i移动到另外一个其他的房子j
里(i != j),移动的距离为|j - i|。问你进过k次移动后,移动的总和可以刚好是s吗?若可以则输出YES并依次输出每次到达的房子的编号,
否则输出NO。
解题思路:
每次至少移动一个单位的距离,至多移动n-1个单位的距离,所以要想完成上述要求每次决策前后一定要满足条件:
k <= s && k*(n-1) >= s
假设当前决策为移动x单位的距离,所以要满足下述条件:
( k-1 <= s-x) && (x <= n-1)
得:max(x) = min( (s - k + 1) , (n-1) )
因此我们的决策为:每次移动的大小为 s与k的差值 和 n-1 中的较小值,使得s和k尽快的相等。
1 #include<cstdio>
2 #include<cstring>
3 #include<cstring>
4 #define ll long long int
5 #include<algorithm>
6 using namespace std;
7 ll n,s,k;
8 int main()
9 {
10 ll sum,i,pos,len;
11 scanf("%lld%lld%lld",&n,&k,&s);
12 if(k>s||k*(n-1)<s)
13 {
14 printf("NO\n");
15 }
16 else
17 {
18 printf("YES\n");
19 pos=1;///记录位置
20 while(k--)
21 {
22 len=min(s-k,n-1);
23 s=s-len;
24 if(pos+len<=n)///向前移还是向后移的判断
25 {
26 pos=pos+len;
27 }
28 else
29 {
30 pos=pos-len;
31 }
32 printf("%d ",pos);
33 }
34 }
35 return 0;
36 }
来源:oschina
链接:https://my.oschina.net/u/4417289/blog/3878526