CSU-1409 集合的并(水~结构体排序)

来源:互联网 发布:javascript 光标 编辑:程序博客网 时间:2024/05/23 23:13

CSU-1409 集合的并(水~qsort排序)

题目链接
Time Limit: 3 Sec Memory Limit: 128 MB Submit: 687 Solved: 173
Description
给出两个由整数组成的集合A, B,计算A ∪ B中包含多少个整数。
Input
输入的第一行包含一个整数T (T > 0),表示一共有T组测试数据。
对于每组测试数据,第一行包含一个整数n (1 ≤ n ≤ 105)。第二行包含2n个整数a1, b1, a2, b2, …, an, bn (0 < a1 ≤ b1 < a2 ≤ b2 < … < an ≤ bn < 109),表示A = [a1, b1] ∪ [a2, b2] ∪ … ∪ [an, bn]。第三行包含一个整数m (1 ≤ m ≤ 105)。第四行包含2m个整数c1, d1, c2, d2, …, cm, dm (0 < c1 ≤ d1 < c2 ≤ d2 < … < cm ≤ dm < 109),表示B = [c1, d1] ∪ [c2, d2] ∪ … ∪ [cm, dm]。
这里[x, y]表示由x, y之间(包含x, y)所有整数组成的集合。
Output
对于每组测试数据,输出A ∪ B中包含多少个整数。
Sample Input
3
1
7 7
1
3 3
2
1 2 3 4
1
2 3
2
1 2 4 6
3
1 3 6 7 9 10
Sample Output
2
4
9
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}。

题意: 集合的并,排序来覆盖重复,注意!sta按小排,end按大排。

#include<cstdio>#include<cstdlib>using namespace std; struct node{    int sta;    int end;}mu[400050];// 覆盖重复: sta按小排,end按大排。int cmp(const void *a,const void *b){     struct node *aa=(node *)a;     struct node *bb=(node *)b;    if(aa->sta==bb->sta)        return (aa->end)<(bb->end)?1:-1;    else  return (aa->sta)>(bb->sta)?1:-1;}int main(){    int n,m,count,temp1,i,t;    scanf("%d",&t);    while(t--){        scanf("%d",&n);        for(i=0; i<n; i++){            scanf("%d %d",&mu[i].sta,&mu[i].end);        }        scanf("%d",&m);        for(i=n; i<n+m; i++){            scanf("%d %d",&mu[i].sta,&mu[i].end);        }        qsort(mu,m+n,sizeof(mu[0]),cmp);        count = 0;        temp1 = 0;          for(i=0; i<m+n; i++){            if(mu[i].sta > temp1) //不断的更新取sta                temp1 = mu[i].sta;            if(mu[i].end >= temp1)//寻找>=sta的end            {                count += mu[i].end-temp1+1;                temp1 = mu[i].end+1;            }        }        printf("%d\n",count);       }    return 0;}

sort排序

#include<stdio.h>#include<stdlib.h>#include<algorithm>using namespace std; struct node{    int sta;    int end;}mu[400050];// 覆盖重复: sta按小排,end按大排。int cmp(node x, node y){//要定义成bool/int要有返回值    if(x.sta !=y.sta)               return x.sta < y.sta; //升序    return x.end > y.end; //降序}int main(){    int n,m,count,temp,i,t;    scanf("%d",&t);    while(t--){        scanf("%d",&n);        for(i=0; i<n; i++){            scanf("%d %d",&mu[i].sta,&mu[i].end);        }        scanf("%d",&m);        for(i=n; i<n+m; i++){            scanf("%d %d",&mu[i].sta,&mu[i].end);        }        sort(mu,mu+m+n,cmp);        count = 0;        temp = 0;         for(i=0; i<m+n; i++){            if(mu[i].sta > temp)                 temp = mu[i].sta;            if(mu[i].end >= temp)            {                count += mu[i].end - temp + 1;                temp = mu[i].end + 1;            }        }        printf("%d\n",count);       }    return 0;}
0 0
原创粉丝点击