NC222476. [USACOJan2020B]Photoshoot
描述
输入描述
The first line of input contains a single integer N.
The second line contains N−1 space-separated integers b1,b2,…,bN−1.
输出描述
A single line with N space-separated integers a1,a2,…,aN.
示例1
输入:
5 4 6 7 6
输出:
3 1 5 2 4
说明:
a produces b because 3+1=4, 1+5=6, 5+2=7, and 2+4=6.C++(g++ 7.5.0) 解法, 执行用时: 3ms, 内存消耗: 464K, 提交时间: 2023-04-02 10:40:48
#include <bits/stdc++.h> using namespace std; typedef long long i64; const i64 mod = 1e9 + 7; int main() { ios::sync_with_stdio(false); cin.tie(0); // b{i} = a{i} + a{i + 1} // b{i} - a{i} = a{i + 1} // b{1} - a{1} = a{2} // b{2} - a{2} = a{3} int n; cin >> n; vector<int> b(n + 2); for (int i = 1; i + 1 <= n; i++) { cin >> b[i]; } vector<int> a(n + 2); for (int i = 1; i <= n; i++) { vector<int> vis(n + 2); vis[i] = 1; a[1] = i; bool yes = true; for (int i = 2; i <= n; i++) { a[i] = b[i - 1] - a[i - 1]; if (a[i] < 1 || a[i] > n || vis[a[i]]) { yes = false; break; } vis[a[i]] = 1; } if (yes) { for (int i = 1; i <= n; i++) { cout << a[i] << " \n"[i == n]; } return 0; } } return 0; }
C++(clang++ 11.0.1) 解法, 执行用时: 3ms, 内存消耗: 496K, 提交时间: 2022-11-29 12:31:48
#include<iostream> #include<cstring> using namespace std; int n,a[1100],b[1100],v[1100]; int main(){ cin>>n; for(int i=1;i<=n-1;i++){ cin>>a[i]; } for(int i=1;i<=n;i++){ //第一个位置是i memset(v,0,sizeof(v)); b[1]=i; v[i]=1; //标记 int flag=0; for(int j=2;j<=n;j++){ //确定n个位置的值 b[j]=a[j-1]-b[j-1]; if(b[j]>n || v[b[j]]){ //超出范围 或 已经存在 flag=1; break; }else{ v[b[j]]=1; //标记 } } if(flag==0){ for(int j=1;j<=n;j++){ cout<<b[j]<<' '; } break; } } return 0; }
Python3 解法, 执行用时: 85ms, 内存消耗: 4780K, 提交时间: 2021-12-11 11:16:22
n=eval(input()) bl=input() bl=bl.split(" ") for x in range(1,n+1): c=x res=[x] for y in range(len(bl)): c=eval(bl[y])-c if c in res or c<=0: break res.append(c) if len(res)==n: for x in res: print(x,end=" ") break