date: 2024-02-28
title: "Divide-and-Conquer"
status: DONE
author:
- AllenYGY
tags:
- NOTE
- DC
- Algorithm
created: 2024-02-28
updated: 2024-04-17T17:24
publish: TrueDivide-and-Conquer
Algorithm Algorithm Divide and Conquer
if sizeof(P) is small then
return sol(P)
else
Split P into P1,P2,P3,…
for i←1 to n do
si←DC(Pi)
end for
return combine(s1,s2,…)
end if
VMAX = R[1],mi=0,mj=0
for i = 1 to N do
V = 0
for j = i to N do
// calculate V ( i, j )
V = V + R [ j ]
if V > VMAX then
VMAX = V
mi=i
mj=j
end if
end for
end for
return VMAX
Algorithm Maximum Contiguous Subarray Problem {Brute Force Reuse Data}
VMAX=R[1]
mi=0
mj=0
for i=1 to N do
V=0
for j=i to N do
//calculate V(i,j)
V=V+R[j]
if V>VMAX then
VMAX=V
mi=i
mj=j
end if
end for
end for
return VMAX
R[i...j]R[i...j]Algorithm Maximum Contiguous Subarray Problem
if i=j then
return R[i]
else
s1←MCS(R,i,⌊(i+j)/2⌋)//Using floor function for lower rounding
s2←MCS(R,⌊(i+j)/2⌋+1,j)
A←MaxSuffix(R,i,⌊(i+j)/2⌋)+MaxPrefix(R,⌊(i+j)/2⌋+1,j)
return MAX(s1,s2,A)
end if
class Solution {
public:
int maxPreffix(vector<int>&nums,int i ,int j){
int ans=nums[i];
int tmp=0;
for(;i<=j;i++){
tmp+=nums[i];
if(tmp>ans){
ans=tmp;
}
}
return ans;
}
int maxSuffix(vector<int>&nums,int i ,int j){
int ans=nums[j];
int tmp=0;
for(;i<=j;j--){
tmp+=nums[j];
if(tmp>ans){
ans=tmp;
}
}
return ans;
}
int MSA(vector<int>&nums,int i ,int j){
if(i==j){
return nums[i];
}
else{
int S1=MSA(nums,i,(i+j)/2);
int S2=MSA(nums,(i+j)/2+1,j);
int A = maxSuffix(nums,i,(i+j)/2)+maxPreffix(nums,(i+j)/2+1,j);
return max({S1,S2,A});
}
}
int maxSubArray(vector<int>& nums) {
return MSA(nums,0,nums.size()-1);
}
};
Definition: A x B
Algorithm Polynomial Multi1(A(x),B(x))
if n=0 then
return a0×b0
else
A0(x)=a0+a1x+⋯+a⌊2n⌋−1x⌊2n⌋−1
A1(x)=a⌊2n⌋+a⌊2n⌋+1x+⋯+anxn−⌊2n⌋
B0(x)=b0+b1x+⋯+b⌊2n⌋−1x⌊2n⌋−1
B1(x)=b⌊2n⌋+b⌊2n⌋+1x+⋯+bnxn−⌊2n⌋
U(x)=PolyMult1(A0(x),B0(x))
V(x)=PolyMult1(A0(x),B1(x))
W(x)=PolyMult1(A1(x),B0(x))
Z(x)=PolyMult1(A1(x),B1(x))
return U(x)+(V(x)+W(x))x⌊2n⌋+Z(x)x2⌊2n⌋
end if
Algorithm Polynomial Multi2(A(x),B(x))
if n=0 then
return a0×b0
else
A0(x)=a0+a1x+⋯+a⌊2n⌋−1x⌊2n⌋−1
A1(x)=a⌊2n⌋+a⌊2n⌋+1x+⋯+anxn−⌊2n⌋
B0(x)=b0+b1x+⋯+b⌊2n⌋−1x⌊2n⌋−1
B1(x)=b⌊2n⌋+b⌊2n⌋+1x+⋯+bnxn−⌊2n⌋
Y(x)=PolyMult2(A0(x)+A1(x),B0(x)+B1(x))
U(x)=PolyMult2(A0(x),B0(x))
Z(x)=PolyMult2(A1(x),B1(x))
return U(x)+(Y(x)−U(x)−Z(x))x⌊2n⌋+Z(x)x2⌊2n⌋
end if