一段代码优化的程序(Sherlock和询问)

文章详细介绍了如何解决数组操作问题,通过遍历数组和使用计数数组来实现特定的数学运算,最终输出经过运算后的数组状态。适用于对算法和数据结构有一定了解的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目: 

Watson给了Sherlock一个问题,请帮助Sherlock解决这个问题。 
Watson给了一个数组 A1,A2,AN。 
他也给了另外两个数组 B1,B2BM 和 C1,C2,CM。 
然后他要Sherlock做如下的操作:

for i=1 to M do
    for j=1 to N do
        if j%B[i]==0 then
            A[j]=A[j]*C[i]
        endif
    end do
end do

Sherlock必须回报数组 A 最后的状态给Watson。

输入格式 
第一行包含 N 和 M,下一行是 N 个元素代表 A,接下来两行各有 M 个元素分别代表数组 B和数组 C

输出格式 
在一行中输出 N 个数,代表数组 A 最后的状态。输出 A 中的每个元素对 (109+7) 取余的结果。

约束条件: 
1N,M105 
1B[i]N 
1A[i],C[i]105

代码:

 public static void main(String[] args)throws  Exception{
        BufferedReader br=new BufferedReader(new InputStreamReader((System.in)));
        PrintWriter pw=new PrintWriter(System.out);
       String[] tempstr=br.readLine().split(" ");
       int N=Integer.parseInt(tempstr[0]);
        int M=Integer.parseInt(tempstr[1]);
        long[] A=new long[N+1];
        long[] count=new  long[N+1];//记录重复相乘.也就是B[i]=B[j]的时候A[k*B[i]]*=C[i]*C[j];把B[i]编程count的下标
        int[] B=new int[M];
        long [] C=new long[M];
        int i;
        String[] tempstr1=br.readLine().split(" ");
        for(i=0;i<N;i++){
            A[i+1]=Integer.parseInt(tempstr1[i]);
        }
           String[] tempStr2=br.readLine().split(" ");
           String[] tempStr3=br.readLine().split(" ");
        for( i=0;i<M;i++) {
            B[i] = Integer.parseInt(tempStr2[i]);
            C[i] = Integer.parseInt(tempStr3[i]);
        }
        int test=1000000007;
     for(i=0;i<B.length;i++){
         if(count[B[i]]==0){
             count[B[i]]=C[i];
         }else{
             count[B[i]]=(count[B[i]]*C[i])%test;
         }
     }
        int temp;
        for(i=1;i<count.length;i++){
            int j=1;
            temp=i*j;
           while(temp<A.length){
               if(count[i]!=0){
                A[temp]=(count[i]*A[temp])%test;
               }
               j++;
               temp=i*j;
           }
        }
        for(i=1;i<A.length;i++){
            pw.print(A[i]+" ");
        }
        pw.flush();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值