题目:
Farmer John is lining up his N cows (2≤N≤103), numbered 1…N, for a photoshoot. FJ initially planned for the i-th cow from the left to be the cow numbered ai, and wrote down the permutation a1,a2,…,aN on a sheet of paper. Unfortunately, that paper was recently stolen by Farmer Nhoj!
Luckily, it might still possible for FJ to recover the permutation that he originally wrote down. Before the sheet was stolen, Bessie recorded the sequence b1,b2,…,bN−1 that satisfies bi=ai+ai+1 for each 1≤i<N.
Based on Bessie’s information, help FJ restore the “lexicographically minimum” permutation a that could have produced b. A permutation x is lexicographically smaller than a permutation y if for some j, xi=yi for all i<j and xj<yj (in other words, the two permutations are identical up to a certain point, at which x is smaller than y). It is guaranteed that at least one such a exists.
Input
The first line of input contains a single integer N.
The second line contains N−1 space-separated integers b1,b2,…,bN−1.
Output
A single line with N space-separated integers a1,a2,…,aN.
Example
inputCopy
5
4 6 7 6
outputCopy
3 1 5 2 4
Note
a produces b because 3+1=4, 1+5=6, 5+2=7, and 2+4=6.
这个题目非常之狗,看起来无从下手,但是只要开始假设,因为他是字典序最小的答案,所以你让答案序列第一个数为1,第二个数等于多少呢?然后发现,答案序列就是全都已知了,所以就是枚举首位数就行了。
代码也非常之少,要做的就是枚举首位数字,然后查重。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <queue>
#include <stack>
#include <map>
//鬼畜头文件
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
typedef unsigned long long ULL;
typedef long long LL;
//鬼畜define
bool tong[1010];
int all[1010];
int n;
int main()
{
scanf("%d",&n);
for(int time=0;time<n-1;time++)scanf("%d",&all[time]);
int ans;
for(int time=1;time<all[0];time++)
{//枚举起点的值
memset(tong,false,sizeof(tong));
int last=time;
tong[last]=true;
int flag=1;
for(int time1=0;time1<n-1;time1++)
{
last=all[time1]-last;
if(last<=0||last>n||tong[last]==true){flag=0;break;}
tong[last]=true;
}
if(flag){ans=time;break;}
}
printf("%d",ans);
for(int time=0;time<n-1;time++)
{
ans=all[time]-ans;
printf(" %d",ans);
}
printf("\n");
return 0;
}
本文介绍了一种算法,用于解决 Farmer John 的奶牛排列问题。通过枚举首位数字并检查重复,算法能够恢复被 Farmer Nhoj 盗走的纸上的原始排列,确保找到的解是最小字典序的。代码简洁高效,利用了 C++ 的标准库。
646

被折叠的 条评论
为什么被折叠?



