百練2792:集合加法

2792:集合加法

總時間限制: 
3000ms 
內存限制: 
65536kB
描述
給出2個正整數集合A = {pi | 1 <= i <= a},B = {qj | 1 <= j <= b}和一個正整數s。問題是:使得pi + qj= s的不同的(i, j)對有多少個。
輸入
第1行是測試數據的組數n,後面跟着n組測試數據。

每組測試數據佔5行,第1行是和s (1 <= s <= 10000),第2行是一個正整數a (1 <= a <= 10000),表示A中元素的數目。第3行是a個正整數,每個正整數不超過10000,表示A中的元素。第4行是一個正整數b (1 <= b <= 10000),表示B中元素的數目。第5行是b個正整數,每個正整數不超過10000,表示B中的元素。

注意:這裏的集合和數學書上定義的集合有一點點區別——集合內可能包含相等的正整數。
輸出
n行,每行輸出對應一個輸入。輸出應是一個非負整數。
樣例輸入
2
99
2
49 49
2
50 50
11
9
1 2 3 4 5 6 7 8 9
10
10 9 8 7 6 5 4 3 2 1
樣例輸出
4
9

  • 查看 
  • 提交 
  • 統計 
  • 提示 
  • 提問
    • 代碼1:快排+二分法
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    const int maxn = 10002;
    int A[maxn],B[maxn];
    int main(){
    	int n,a,b,s;
    	scanf("%d",&n);
    	while(n--){
    		memset(A,0,sizeof(A));
    		memset(B,0,sizeof(B));
    		scanf("%d%d",&s,&a);
    		for(int i = 0;i<a;++i)
    			scanf("%d",&A[i]);
    		scanf("%d",&b);
    		for(int i=0;i<b;i++)
    			scanf("%d",&B[i]);
    		int ans = 0,len = b,pos;
    		sort(A,A+a);
    		sort(B,B+b);
    		for(int i = 0;i<a;i++){
    			if(A[i]>=s) break;
    			pos = lower_bound(B,B+len,s-A[i]) - B;
    			if(pos < len && B[pos] == s-A[i]){
    					while(B[pos++] == s-A[i]) ans++;
    			}
    			len = pos;
    		}
    		printf("%d\n",ans);
    	}
    	return 0;
    }
    代碼2:哈希,桶排序
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 10002;
int A[maxn],B[maxn],C[maxn];
int main(){
	int n,a,b,s,tmp,k,ans;
	scanf("%d",&n);
	while(n--){
		memset(A,0,sizeof(A));
		memset(B,0,sizeof(B));
		scanf("%d%d",&s,&a);
		k = ans = 0;
		for(int i = 0;i<a;++i){
			scanf("%d",&tmp);
			if(A[tmp] == 0){
				C[k++]=tmp;
				A[tmp]++;
			}else
				A[tmp]++;
		}
		scanf("%d",&b);
		for(int i =0;i<b;i++){
			scanf("%d",&tmp);
			B[tmp]++;
		}
		for(int i =0;i<k;i++){
			if(s-C[i]>0){
				ans += A[C[i]]*B[s-C[i]];
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}



發佈了81 篇原創文章 · 獲贊 14 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章