[Programming thinking and practice Week4 job four columns B]

Subject description:

ZJM has four columns A, B, C, D, each column has the number of digits n. ZJM a number taken from each respective column number, he would like to know how many kinds of programs such that the number of 4 and 0.
When a number of columns has the same plurality of numbers, to treat them as a different number.

Input formats:

The first line: n (number representative of the number of columns) (1≤n≤4000)
the next n-th row, the i-th row of four numbers, each number denotes the i-th column of A, B, C, D of digit (digit 2 to the power of not more than 28)

Sample Input:

6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45

Output formats:

The number of different output combinations.

Sample Output:

5

Ideas:

If the data and to dwell on, n will reach 4 after complexity, significant time out, so we use two arrays prior to first use to enumerate, record them, and then two arrays and enumeration while two arrays before they see the opposite of how many, and included in the answer. Such complexity can be reduced to n- 2 . In calculating the inverse of how many, have been used map notation, but still no response, so we choose to sort the array and the array of the first two, then half, looking to find a number of first and last position, thereby obtaining the target data (the two arrays and the inverse number) number.

Code:

#include <iostream>
#include<map>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
const int size=4000+10;
int d[4][size];
int sum[size*size];
int begin(int x,int left,int right)
{
	int ans=-1;
	while(left<=right)
	{
		int mid=(left+right)>>1;
		if(sum[mid]==x)
		{
			ans=mid;
			right=mid-1;
		}
		else if(sum[mid]<x)
			left=mid+1;
		else
			right=mid-1;
	}
	return ans;
}
int end(int x,int left,int right)
{
	int ans=-1;
	while(left<=right)
	{
		int mid=(left+right)>>1;
		if(sum[mid]==x)
		{
			ans=mid;
			left=mid+1;
		}
		else if(sum[mid]<x)
			left=mid+1;
		else
			right=mid-1;
	}
	return ans;
}
int main(int argc, char** argv) {
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		scanf("%d%d%d%d",&d[0][i],&d[1][i],&d[2][i],&d[3][i]);
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			sum[i*n+j]=d[0][i]+d[1][j];
		}
	}
	sort(sum,sum+n*n);
	int count=0;
	int l,r;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			int temp=d[2][i]+d[3][j];
			temp=0-temp;
			l=begin(temp,0,n*n-1);
			if(l==-1)
				continue;
			r=end(temp,0,n*n-1);
			count+=(r-l+1);
		}
	}
	cout<<count<<endl;
	return 0;
}
Published 25 original articles · won praise 8 · views 532

Guess you like

Origin blog.csdn.net/weixin_44034698/article/details/104874715