ZOJ 3574 Under Attack II 归并排序求逆序对

来源:互联网 发布:linux计数统计命令 编辑:程序博客网 时间:2024/05/19 02:19

题目链接


 Because of the sucessfully calculation in Under Attack I, Doctor is awarded with Courage Cross and promoted to lieutenant. But the war seems to end in never, now Doctor has a new order to help anti-aircraft troops calculate the proper number of supply sites needed for SAMs in battle regions.According to intel, enemy bombers go straight across battle region and the bombing runs are continous. So their routes divides the region into several parts. The missles SAM needed are provided by supply sites. Because it's dangerous to cross fireline, Ufo suggests that every part of battle regions divided by firelines should have a supply site so that the SAMs can safely get enough ammo.Now that the task is clear, Doctor is asked to calculate how many supply sites are at least needed. The bombers' routes are lines y=kx+b given in format as k,b, of course k b are same to their ordinary meanings. Assume the battle region is a rectangle with infinity height, the left x-cooridinate and right x-cooridinate are given so that the width of rectangle is fixed.

Input

The input consists of multiple cases.The first line are the left x-cooridinate a and right x-cooridinate b of battle region. a b are both in the range of [0,1000]. Of course a will not exceed b.Next lines will describe enemy bombing routes number n.n can be up to 30000.Following n lines are k and b of each bombing route.k b are in range of [-100000,100000].It's guaranteed that no three lines (including the two battle region bound lines) will go through one point.

Output

Output the least number of supply sites needed.

Sample Input

1 211 5

Sample Output

2

Hint

In sample, line y=x+5 divides the region between x=1 and x=2 into two parts, so the outcome is 2.

题意:

算直线能把题目给的区域分成几块.

思路:

分析一下题目, 我们发现ans = 交点个数 + 直线个数 + 1;
于是归并排序求逆序对即可.

代码:

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<cmath>using namespace std;const int maxn = 30000+10;int a[maxn];int tmp[maxn];int ans;struct ss{    int x, y;}b[maxn];bool cmp(ss &q, ss &p){    return q.x < p.x;}void Merge_sort(int l, int r){    if(r - l <= 1) return ;    int m = (l + r) >> 1;    Merge_sort(l, m);    Merge_sort(m, r);    int x = l, y = m, i = l;    while(x < m ||y < r){        if(y >= r ||(x < m && a[x] <= a[y]))            tmp[i++] = a[x++];        else {            tmp[i++] = a[y++];            ans += m - x ;        }    }for(i  = l ; i< r; ++i)        a[i] = tmp[i];}int main(){    int x1, x2;    ios::sync_with_stdio(false);    while(cin >> x1 >> x2){        int n;        cin >> n;        for(int i = 1; i <= n; ++i){            int k, t;            cin >> k >> t;            b[i].x = x1 * k + t;            b[i].y = x2 * k + t;        }sort(b + 1, b + 1 + n, cmp);        for(int  i = 1; i <= n; ++i)            a[i-1] = b[i].y;        ans = 0;        Merge_sort(0,n);        cout<< ans + n + 1<<endl;    }return 0;}
原创粉丝点击