2021/3/20个人赛补题B - Array Reconstructing

B - Array Reconstructing

题目描述:
You are given an array a consisting of n elements a1, a2, …, an. Array a has a special property, which is:
ai = (ai - 1 + 1) % m, for each i (1 < i ≤ n)
You are given the array a with some lost elements from it, each lost element is replaced by -1. Your task is to find all the lost elements again, can you?
The first line contains an integer T, where T is the number of test cases.

The first line of each test case contains two integers n and m (1 ≤ n ≤ 1000) (1 ≤ m ≤ 109), where n is the size of the array, and m is the described modulus in the problem statement.

The second line of each test case contains n integers a1, a2, …, an ( - 1 ≤ ai < m), giving the array a. If the ith element is lost, then ai will be -1. Otherwise, ai will be a non-negative integer less than m.

It is guaranteed that the input is correct, and there is at least one non-lost element in the given array.
For each test case, print a single line containing n integers a1, a2, …, an, giving the array a after finding all the lost elements.

It is guaranteed that an answer exists for the given input.
该题目大意为一个数组有一个特殊的性质ai = (ai - 1 + 1) % m, for each i (1 < i ≤ n),该数组中有一些丢失的元素,用-1代替,该题目就是让你找丢失的元素,并把数组元素一一输出。

样例:

输入

4
5 10
1 2 3 4 5
4 10
7 -1 9 -1
6 7
5 -1 -1 1 2 3
6 10
5 -1 7 -1 9 0

输出

1 2 3 4 5
7 8 9 0
5 6 0 1 2 3
5 6 7 8 9 0

思路:找到第一个不为”-1“的数,然后往前,往后推(暴力模拟的思想),往前推时需要注意,如果后一个数为0,那么前一个数则为m-1。

代码如下(示例):

#include <bits/stdc++.h>
using namespace std;
const int N=1001;
int a[N];
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,m;
        cin>>n>>m;
       for(int i=1;i<=n;i++)
        {
           cin>>a[i];
        }
       int flag;
       for(int i=1;i<=n;i++)
       {
           if(a[i]!=-1)
           {
               flag=i;
               break;
           }
       }
       for(int i=flag-1;i>=1;i--)
       {
           if(a[i+1]==0) a[i]=m-1;
           else a[i]=a[i+1]-1;
       }
       for(int i=flag+1;i<=n;i++)
       {
           a[i]=(a[i-1]+1)%m;
       }
       for(int i=1;i<=n;i++)
       {
           if(i==n) cout<<a[i]<<endl;
           else cout<<a[i]<<' ';
       }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值