UVA, 356 Square Pegs And Round Holes

本文介绍了一种算法,用于计算一个2n*2n网格中,半径为n的圆内部及其边界上的格点数量。该算法通过遍历四分之一区域内的每个格子并利用对称性来简化计算过程。

题目: 给一个n。构建一个2n*2n的方格。里面放一个半径为n的圆。求落在边上的和完全在内部的格子个数

注意:输出的时候。几组数之间有空行。最后一组后面没有

只需要算1/4的。由于对称性

#include <cstdio>
#include <string.h>
#include <cstdlib>
#include <cmath>
#include <ctgmath>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;
//(0,0)到(m,n)距离的平方
int func(int m,int n){
    return m*m+n*n;
}

int main()
{
    //只需要考虑四分之一的区域
    int n;
    int count = 0;//计数,方便回车输出
    while (cin>>n) {
        int i,j;
        double r = (n - 0.5) * (n - 0.5);//半径的平方
 //       cout<<r<<endl;
        int neibu = 0;//内部
        int bianjie = 0;//边上
        //遍历所有格子的左下角
        for(i=0; i<=n-1; i++){
            for(j=0; j<=n-1; j++){
                //左下和右上都在r内部
                if( (func(i, j) < r) && (func(i+1, j+1) < r) ) neibu++;
                else if( (func(i, j) < r) && (func(i+1, j+1) > r)) bianjie++;
            }
        }
 //       cout<<neibu<<endl<<bianjie;
        if(count++) cout<<endl;
        printf("In the case n = %d, %d cells contain segments of the circle.\n",n,bianjie*4);
        printf("There are %d cells completely contained in the circle.\n",neibu*4);
    }
    return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值