最_长_连_续_子_串---- 乘--积

Posted cofludy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最_长_连_续_子_串---- 乘--积相关的知识,希望对你有一定的参考价值。

输入一个数值序列numbers,输出某一个连续子串长度,满足小于给定乘积上限k。

这里有两种解法,其一为O(N^2),其二基本为O(N)

 1 #include<iostream>
 2 #include <stdio.h>
 3 #include<algorithm>
 4 #include<vector>
 5 #include<map>
 6 
 7 using namespace std;
 8 
 9 long getSubArray(vector<int> &numbers, int k)
10 
11     long count = 0;
12     for (int i = 0; i < numbers.size();++i) 
13         long mul = numbers[i];
14         if (mul <= k) 
15             count++;
16             for (int j = i+1; j < numbers.size();++j) 
17                 mul *= numbers[j];
18                 if (mul <= k) 
19                     count++;
20                 
21                 else
22                     break;
23                 
24             
25             
26     
27     return count; 
28 
29 
30 long getSubArray2(vector<int> &numbers, int k)
31 
32     vector<int> loc(numbers.size(), 0);
33     vector<long> muls(numbers.size(), 0);
34     int i = 0;
35     int mul = numbers[i];
36     if (mul <= k) 
37         int j = i + 1;
38         for (;j < numbers.size();++j) 
39             mul *= numbers[j];
40             if (mul > k) 
41                 break;
42             
43         
44         loc[i] = j;
45         muls[i] = mul;
46     
47     else
48     
49         loc[i] = i;
50         muls[i] = numbers[i];
51     
52 
53     for (int i = 1;i < numbers.size();++i) 
54         int mul = muls[i-1]/(numbers[i-1]);
55         if (mul <= k) 
56             int j = loc[i-1] + 1;
57             for (; j < numbers.size(); j++)
58                 mul *= numbers[j];
59                 if (mul > k) 
60                     break;
61                 
62             
63             loc[i] = j;
64             muls[i] = mul;
65         
66         else
67             loc[i] = loc[i - 1] > i ? loc[i - 1] : i;
68             muls[i] = mul;
69         
70     
71 
72     long count = 0;
73     for (int i = 0; i < numbers.size();++i) 
74         count += loc[i] - i;
75     
76     return count;
77 
78 
79 
80 int main()
81 
82     cout << "hello, world!" << endl;
83     int i = 5, j = 2;
84     int k=i<<j;
85     printf("%d %d \n", 0xff , k);
86     printf("%d %d \n", i << j, j >> i);
87 
88     vector<int> arr = 2,34,11,1,2,3,4,5,6,65,33,1,1,23,2,4,2,123,24,12,2,22;
89     int m = 20;
90     int count = getSubArray(arr, m);
91     int count2 = getSubArray2(arr, m);
92     cout << count <<"  "<<count2<< endl;
93     system("pause");
94     return 0; 
95 

 

以上是关于最_长_连_续_子_串---- 乘--积的主要内容,如果未能解决你的问题,请参考以下文章

矩阵连乘-动态规划

动态规划_公共最长子序列 java

c语言函数习题

BZOJ_2946_[Poi2000]公共串_后缀数组+二分答案

b_51_回文串划分(预处理+dp)

nyoj133_子序列_离散化_尺取法