1. 程式人生 > >[洛谷P1631] 序列合並

[洛谷P1631] 序列合並

每次 scanf 代碼實現 pan str urn ret body 判重

題目描述

有兩個長度都是N的序列A和B,在A和B中各取一個數相加可以得到N^2個和,求這N^2個和中最小的N個。

輸入輸出格式

輸入格式:

第一行一個正整數N;

第二行N個整數Ai,滿足Ai<=Ai+1且Ai<=10^9;

第三行N個整數Bi, 滿足Bi<=Bi+1且Bi<=10^9.

【數據規模】

對於50%的數據中,滿足1<=N<=1000;

對於100%的數據中,滿足1<=N<=100000。

輸出格式:

輸出僅一行,包含N個整數,從小到大輸出這N個最小的和,相鄰數字之間用空格隔開。

輸入輸出樣例

輸入樣例#1: 復制
3
2 6 6
1 4 8
輸出樣例#1: 復制
3 6 7

思路

a[x]+b[y]<a[x+1]+b[y];

a[x]+b[y]<a[x]+b[y+1];

並且具有緊密性;

所以最開始在優先隊列中加入a[1]+b[1](必然是最小的);

每次取出最小元素a[x]+b[y]輸出,並再加入a[x+1]+b[y], a[x]+b[y+1];

!註意判重;

代碼實現

 1 #include<map>
 2 #include<queue>
 3 #include<cstdio>
 4 const int maxn=1e5+10;
5 int n,a[maxn],b[maxn]; 6 std::map<long long,bool>v; 7 struct nate{ 8 int x,y,z; 9 nate(int a=0,int b=0,int c=0):x(a),y(b),z(c){} 10 }; 11 struct comp{bool operator()(nate a,nate b){return a.z>b.z;}}; 12 int main(){ 13 scanf("%d",&n); 14 for(int i=1;i<=n;i++) scanf("
%d",&a[i]); 15 for(int i=1;i<=n;i++) scanf("%d",&b[i]); 16 std::priority_queue<nate,std::vector<nate>,comp>q; 17 q.push(nate(1,1,a[1]+b[1])); 18 int x,y,z; 19 for(int i=1;i<=n;i++){ 20 x=q.top().x,y=q.top().y; 21 printf("%d ",q.top().z),q.pop(); 22 if(!v[(x+1)*maxn+y]&&x+1<=n) 23 q.push(nate(x+1,y,a[x+1]+b[y])),v[(x+1)*maxn+y]=1; 24 if(!v[x*maxn+(y+1)]&&y+1<=n) 25 q.push(nate(x,y+1,a[x]+b[y+1])),v[x*maxn+(y+1)]=1; 26 } 27 return 0; 28 }

[洛谷P1631] 序列合並