小奇画画

题目描述

红莲清泪两行欲吐半点却无
如初是你杳然若绯雾还在水榭畔画楼处
是谁衣白衫如初谁红裳如故
——《忆红莲》

小奇想画几朵红莲,可惜它刚开始学画画,只能从画圆开始。小奇画了n个圆,它们的圆心都在x轴上,且两两不相交(可以相切)。现在小奇想知道,它画的圆把画纸分割成了多少块?(假设画纸无限大)

输入

第一行包括1个整数n。
接下来n行,每行两个整数x,r,表示小奇画了圆心在(x,0),半径为r的一个圆。

输出

输出一个整数表示答案。

样例输入

4 
7 5 
-9 11 11 9 
0 20

样例输出

6

提示

对于 100%数据,1<=n<=300000,-10^9<=x<=10^9,1<=r<=10^9。

这道题可以搜索,也可以线段树,总而言之,注意的点就那些,思路也挺好找,关键是实现,我们在这运用了stl容器来记录。

#include <iostream>

#include<cstdio>

#include<vector>

#include<stack>

#include<queue>

#include<cmath>

#include<string>

#include<cstring>

#include<algorithm>

using namespace std;

typedef long long ll;

struct node//定义结构体存储左右端点和圆心半径

{

    ll x,r,left,right;

}ap[300050];

int sum[300050];

vector<int>v[300050];

bool cmp(node x,node y)//按左端点由小到大,右端点从大到小排序

{

    if(x.left==y.left)

    {

        return x.right>y.right;

    }

    return x.left<y.left;

}

int bfs(int n)

{

    queue<int>q;

    int ans=0;

    for(int i=0;i<n;i++)

    {

        if(!sum[i])

        {

            q.push(i);

        }

    }

    while(!q.empty())

    {

        int u=q.front();

        q.pop();

        ll temp=0;

        for(int i=0;i<v[u].size();i++)

        {

            int e=v[u][i];

            temp+=ap[e].r;

            q.push(e);

        }

        if(temp==ap[u].r)

        {

            ans++;

        }

    }

    return ans;

}

int main()

{

    int n;

    scanf("%d",&n);

    for(int i=0;i<n;i++)

    {

        scanf("%lld %lld",&ap[i].x,&ap[i].r);

        ap[i].left=ap[i].x-ap[i].r;

        ap[i].right=ap[i].x+ap[i].r;

    }

    sort(ap,ap+n,cmp);//排序

    stack<int>s;

    for(int i=0;i<n;i++)

    {

        while(!s.empty())

        {

            int t=s.top();

            if(ap[i].right<=ap[t].right)

            {

                v[t].push_back(i);

                sum[i]++;

                break;

            }

            s.pop();

        }

        s.push(i);

    }

    int ans=bfs(n)+1+n;

    printf("%d\n",ans);

    return 0;

}

如有不懂可参考https://blog.csdn.net/sxh759151483/article/details/81257936

猜你喜欢

转载自blog.csdn.net/weixin_41370251/article/details/81325713