zoukankan      html  css  js  c++  java
  • 随机算法

      随机算法听起来就很不靠谱...但是有的时候还是很有用的,而且也有正解就是随机化的题目。

      要说定义好像也没什么好讲的,要不先看道题吧。

      

      偷上网:https://www.luogu.org/problemnew/show/P4703

      luogu某次月赛题,当时刚开始看这个题网站就崩溃了,于是也没有怎么想,今天再想还是没有什么思路。

      一开始想到在边上找,又觉得在中间的可能性也很大,所以似乎并没有什么规律。看了题解发现这道题可以用随机化...随机生成一些点,check一下是否满足条件,这样多找几次总能找到答案。写完之后突然想起来还有无解的情况,用数学方法推了一下无果,(于是又去看了题解)。随机10000次如果还没有解就认为是无解,这也太暴力了吧...

      通过这道题还学到了一个技巧,(double)rand()/RAND_MAX*(想要的范围),就可以构造出在0-想要的范围之间的数了.

      
    # include <cstdio>
    # include <iostream>
    # include <cmath>
    # include <ctime>
    # include <cstdlib>
    
    using namespace std;
    
    int n,l;
    double nx,ny,x[11],y[11],dis;
    const int maxn=10000;
    
    bool check(double a,double b)
    {
        for (int i=1;i<=n;i++)
            if( (x[i]-a)*(x[i]-a)+(y[i]-b)*(y[i]-b)< dis*dis)
                return false;
            return true;
    }
    
    int main()
    {
        srand(time(0));
        scanf("%d%d",&n,&l);
        for (int i=1;i<=n;++i)
            scanf("%lf%lf",&x[i],&y[i]);
        dis=(double)l/n;
        for (int i=1;i<=maxn;++i)    
        {
            nx=(double)rand()/RAND_MAX*l;
            ny=(double)rand()/RAND_MAX*l;
            if(check(nx,ny))
            {
                cout<<nx<<" "<<ny;
                return 0;
            }
        }
        printf("GG");
        return 0;
    }
    偷上网

      

      随机化的题也就见过这么一道,以后见到再写。

  • 相关阅读:
    LeetCode 3-Longest Substring Without Repeating Characters
    LeetCode 2-Add Two Numbers
    LeeCode 1-Two Sum
    Python中Lambda, filter, reduce and map 的区别
    解决Eclipse10配置Pydev不成功的问题
    Pythonxy下载链接
    546C. Soldier and Cards
    欧拉工程第58题:Spiral primes
    欧拉工程第57题:Square root convergents
    Linux编辑器vim键盘详解
  • 原文地址:https://www.cnblogs.com/shzr/p/9200699.html
Copyright © 2011-2022 走看看