CSU 1409: 集合的并(数学啊 )

来源:互联网 发布:程序员一年能赚多少钱 编辑:程序博客网 时间:2024/06/11 21:05

题目链接:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1409


Description

给出两个由整数组成的集合AB,计算A  B中包含多少个整数。

Input

输入的第一行包含一个整数T (T > 0),表示一共有T组测试数据。
对于每组测试数据,第一行包含一个整数n (1  n  105)。第二行包含2n个整数a1b1a2b2, ..., anbn (0 < a1  b1 < a2  b2 < ... < an  bn < 109),表示A = [a1b1 [a2b2 ...  [anbn]。第三行包含一个整数m (1  m  105)。第四行包含2m个整数c1d1c2d2, ..., cmdm (0 < c1  d1 < c2  d2 < ... < cm  dm < 109),表示B = [c1d1 [c2d2 ...  [cmdm]。
这里[xy]表示由xy之间(包含xy)所有整数组成的集合。

Output

对于每组测试数据,输出A  B中包含多少个整数

Sample Input

317 713 321 2 3 412 321 2 4 631 3 6 7 9 10

Sample Output

249

HINT

对样例1的解释:A = {7},B = {3},A  B = {3, 7}。

对样例2的解释:A = {1, 2, 3, 4},B = {2, 3},A  B = {1, 2, 3, 4}。

对样例3的解释:A = {1, 2, 4, 5, 6},B = {1, 2, 3, 6, 7, 9, 10},A  B = {1, 2, 3, 4, 5, 6, 7, 9, 10}。

Source

中南大学第八届大学生程序设计竞赛



代码如下:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct pos{    int x, y;} a[500017];bool cmp(pos a, pos b){    if(a.x == b.x)        return a.y > b.y;    return a.x < b.x;}int main(){    int t;    int n, m;    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        for(int i = 0; i < n; i++)        {            scanf("%d%d",&a[i].x,&a[i].y);        }        scanf("%d",&m);        for(int i = n; i < m+n; i++)        {            scanf("%d%d",&a[i].x,&a[i].y);        }        sort(a,a+n+m,cmp);        int ans = 0;        int pre = 0;        for(int i = 0; i < n+m; i++)        {            if(a[i].x > pre)            {                pre = a[i].x;            }            if(pre <= a[i].y)            {                ans+=a[i].y-pre+1;                pre = a[i].y+1;            }        }        printf("%d\n",ans);    }    return 0;}


2 0
原创粉丝点击