Codeforces 755D:PolandBall and Polygon 贪心 + 树状数组

传送门

题目描述

给出一个n边形,和距离k。 第一次连接1和 k+1,第二次连接k+1和(k+1+k)%n,依次进行n次,每次结束后输出n边形被分割成了几个区域。

分析

画画图可以观察出结论,每次答案都在前一个答案上加1再加上交点个数
所以我们怎么去维护交点个数呢
我们可以计算出两个点之间有多少个点有直线即可,用树状数组进行维护
需要注意的是,我们需要维护小的那一边,否则有的边会被重复计算

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 10;
ll tr[N];
int n,m;

int lowbit(int x){
    
    
    return x & -x;
}

void add(int x,int c){
    
    
    for(int i = x;i <= n;i += lowbit(i)) tr[i] += c;
}

ll sum(int x){
    
    
    ll res = 0;
    for(int i = x;i;i -= lowbit(i)) res += tr[i];
    return res;
}

int main(){
    
    
    scanf("%d%d",&n,&m);
    int s = 1,e;
    m = min(m,n - m);
    ll ans = 1;
    for(int i = 1;i <= n;i++){
    
    
		e = (s + m - 1) % n + 1;
		if(s > e){
    
    
		    ans += (1ll + sum(n) - sum(s) + sum(e - 1) - sum(0));
		}
		else{
    
    
		    ans += (1ll + sum(e - 1) - sum(s));
		}
		add(s,1);
		add(e,1);
		s = e;
		printf("%lld ",ans);
	}
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/

猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/112725388