int PARTITION(int a[],int p,int r)
{ //i指向小于x的最后一个值的下标
//j指向当前正在进行比较的元素下标
int temp;
int i=p-1;
int x=a[r];
for (int j=p;j<r;++j)
{
if (a[j]<=x)
{
++i;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
//for循环结束后,此时i+1就是x该插入的位置,之前的值都小于x,之后的都大于x
temp=a[i+1];
a[i+1]=a[r];
a[r]=temp;
return i+1;
}
void QUICKSORT(int a[],int p,int r)
{
if (p<r)
{
int q=PARTITION(a,p,r);
QUICKSORT(a,p,q-1);
QUICKSORT(a,q+1,r);
}
}
bool isExist(int* arr,int SUM,vector<int> &pos_1,vector<int> &pos_2,int lenght)
{
int low=0;
int high=lenght-1;
bool isFind=false;
while(low<high)
{
if (low-1>=0&&arr[low]==arr[low-1])
{
low++;
continue;
}
if (high+1<lenght&&arr[high]==arr[high+1])
{
high--;
continue;
}
if (arr[low]+arr[high]<SUM)
{
low++;
}
else
if (arr[low]+arr[high]>SUM)
{
high--;
}
else
{
pos_1.push_back(low++);
pos_2.push_back(high--);
isFind=true;
}
}
return isFind;
}
void FindSum(const vector<int> &A,const vector<int> &B,unsigned int M)
{
int sizeA=A.size();
int sizeB=B.size();
int* a=new int[sizeA];
int* b=new int[sizeB];
int index;
for (index=0;index<sizeA;++index) a[index]=A[index];
for (index=0;index<sizeB;++index) b[index]=B[index];
QUICKSORT(a,0,sizeA-1);
QUICKSORT(b,0,sizeB-1);
vector<int> pos_1,pos_2;
bool isFind=false;
for (index=0;index<sizeA;++index)
{
if (index-1>=0&&a[index]==a[index-1]) continue;
if (isExist(b,M-a[index],pos_1,pos_2,sizeB))
{
for(int i=0;i<pos_1.size();++i)
{
cout<<"A:"<<a[index]<<" B:"<<b[pos_1[i]]<<" "<<b[pos_2[i]]<<endl;
}
isFind=true;
}
pos_1.clear();
pos_2.clear();
}
for (index=0;index<sizeB;++index)
{
if (index-1>=0&&b[index]==b[index-1]) continue;
if (isExist(a,M-b[index],pos_1,pos_2,sizeA))
{
for(int i=0;i<pos_1.size();++i)
{
cout<<"A:"<<a[pos_1[i]]<<" "<<a[pos_2[i]]<<" B:"<<b[index]<<endl;
}
isFind=true;
}
pos_1.clear();
pos_2.clear();
}
if (!isFind) cout<<"not find!"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> A,B;
A.push_back(1);
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(3);
A.push_back(3);
A.push_back(4);
A.push_back(4);
A.push_back(5);
A.push_back(5);
B.push_back(1);
B.push_back(2);
B.push_back(2);
B.push_back(3);
B.push_back(4);
B.push_back(4);
FindSum(A,B,6);
return 0;
}