POJ 3067 Japan (树状数组)
来源:互联网 发布:数控机床与编程教程pdf 编辑:程序博客网 时间:2024/06/05 16:11
链接:
Description
【问题描述】
日本为了迎接ACM ICPC世界总决赛的到来,计划修建许多道路。日本是一个岛国,其东海岸有N座城市,西海岸有M座城市(M <= 1000, N <= 1000)。K条高速公路将要修建。每个海岸上的城市都被编号为1,2,…从北向南编号。每条高速公路连接东海岸的一座城市和西海岸的一座城市。修建道路的资金由ACM提供保障。有些高速公路会产生交叉。同一个地点最多只会有两条高速公路交汇于此。请你写一个程序,计算高速公路之间的交叉点的数目。
Input
输入文件首先包含数字T,表示测试数据的组数。每组测试数据以三个整数N, M, K 开头,接下来K行每行两个整数,表示高速公路两头的城市编号(第一个数是东海岸的城市编号,第二个数是西海岸的城市编号)。
Output
对于每组测试数据,按如下格式输出一行:
Test case (测试数据编号): (交叉点数目)
Sample Input
1
3 4 4
1 4
2 3
3 2
3 1
Sample Output
Test case 1: 5
思路:先设定左右两侧的两点分别任x1, y1, x2, y2 (x1 < x2 && y1 < y2) 一定是x1 与 y2 间和 x2 与y1之间修公路,就一定会出现交点,按照正常的依次的对两条线段进行判定的话,时间复杂度为O(n^2),此题的数据量为1000*1000,用这种方法肯定会超时;
正确的思路应为:先对要修建的公路按x 和 y进行从小到大排序,求出已经插入数组中的点与当前的这个点有多少个交点,累加起来就可以求出所有的交点数 === 对每个点先求出交点书后将其插入到数组当中去;
代码如下:
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#define MAXN 1005#define RST(N)memset(N, 0, sizeof(N))using namespace std;typedef unsigned long long ULL;typedef struct Node_{ int x, y;}Node;Node N[1000005];int value[MAXN], Max; //value存储交点数;ULL tot; //统计总数;void Init() //初始化;{ RST(value); tot = 0, Max = 0;}int lowbit(int x) { return x & (-x); } //位运算;void update(int pos, int maxn) //更新;{ while(pos <= maxn) { value[pos] += 1; pos += lowbit(pos); }}ULL Getsum(int pos) //求和;{ ULL sum = 0; while(pos > 0) { sum += value[pos]; pos -= lowbit(pos); } /* for(; pos>0; pos-=lowbit(pos)) { //这样写也可以,按个人喜好; sum += value[pos]; } */ return sum;}int cmp(const void *a, const void *b) //按x,y从小到大排序;{ Node *p1 = (Node *)a; Node *p2 = (Node *)b; if(p1->x != p2->x) return p1->x - p2->x; else return p1->y - p2->y;}int main(){ int n, m, k, cas, T = 0; scanf("%d", &cas); while(cas--) { Init(); scanf("%d %d %d", &n, &m, &k); for(int i=0; i<k; i++) { scanf("%d %d", &N[i].x, &N[i].y); if(N[i].y > Max) Max = N[i].y; } qsort(N, k, sizeof(Node), cmp); update(N[0].y, Max); for(int i=1; i<k; i++) { tot += Getsum(Max) - Getsum(N[i].y); update(N[i].y, Max); } printf("Test case %d: %lld\n", ++T, tot); } return 0;}
0 0
- poj - 3067 - Japan(树状数组)
- POJ 3067 Japan (树状数组)
- POJ 3067 Japan (树状数组)
- POJ 3067 Japan (树状数组)
- POJ 3067 Japan(树状数组 )
- POJ 3067 Japan(树状数组)
- poj-3067-Japan(树状数组)
- POJ 3067 Japan (树状数组)
- POJ 3067 Japan(树状数组)
- POJ 3067 Japan(经典树状数组)
- (POJ 3067)Japan 树状数组
- poj 3067 Japan(树状数组)
- POJ-3067 Japan (树状数组)
- POJ 3067 Japan【树状数组】
- poj 3067 japan 树状数组
- poj 3067 树状数组 Japan
- POJ 3067 Japan 树状数组
- POJ 3067 Japan 树状数组
- 三大备份方式(完全备份、增量备份、差异备份)浅析
- 第四周作业---图的表示
- awk手册
- C#总结
- Log4J.xml的模板
- POJ 3067 Japan (树状数组)
- 查找算法大集合
- zoj 3611 Ice Valley 状压BFS
- [LeetCode] Single Number
- 项目二。
- node-qunit的测试结果如何显示到浏览器中(1)
- C++基础
- POJ1002 487-3279
- linux中TFTP配置