?? 鄭凌-6分.txt
字號:
//圓排列的最小長度算法 040000003 鄭凌
#include <fstream.h>
#include <iostream.h>
#include <math.h>
#include <time.h>
//==================隨機數類===========================
const unsigned long maxshort=65536L;
const unsigned long multiplier=1194211693L;
const unsigned long adder=12345L;
class RandomNumber{
public:
RandomNumber(unsigned long s=0); //構造函數,缺省值0表示由系統自動產生種子
unsigned short Random(unsigned long n); //產生0:n-1之間的隨機整數
double fRandom(void); //產生(0,1)之間的隨機實數
private:
unsigned long randSeed;
};
RandomNumber::RandomNumber(unsigned long s)
{
if(s==0)
randSeed=time(0);
else
randSeed=s;
}
unsigned short RandomNumber::Random(unsigned long n)
{
randSeed=multiplier*randSeed+adder;
return(unsigned short)((randSeed>>16)%n);
}
double RandomNumber::fRandom(void)
{
return Random(maxshort)/double(maxshort);
}
//===================圓排列函數===========================
void swap(float&,float&);
void shuffle(float *,int); //隨機洗牌算法
void center(float *,float *,int); //計算當前所有的圓在當前圓排列中圓心的橫坐標
float compute(float *,float *,int); //計算當前圓排列的長度
float circle_search(float *,float *,int); //求一次隨機排列的最小值
void swap(float& x,float& y)
{
float temp;
temp=x;
x=y;
y=temp;
}
void shuffle(float *r,int n) //產生r的一個隨機排列
{
static RandomNumber rnd;
for(int i=n;i>1;i--)
swap(r[i],r[rnd.Random(i)+1]);
}
void center(float *r,float *x,int n)
{
for(int i=1;i<=n;i++){
float temp=0;
for(int j=1;j<i;j++){
float valuex=x[j]+(float)(2.0*sqrt(r[i]*r[j]));
if(valuex>temp) temp=valuex;
}
x[i]=temp;
}
}
float compute(float *r,float *x,int n)
{
float low=0;
float high=0;
for(int i=1;i<=n;i++){
if(x[i]-r[i]<low) low=x[i]-r[i];
if(x[i]+r[i]>high) high=x[i]+r[i];
}
return (high-low);
}
float circle_search(float *r,float *x,int n)
{
float min=9999999, result;
shuffle(r,n);
bool found=true;
while(found)
{
found=false;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
swap(r[i],r[j]);
center(r,x,n);
result=compute(r,x,n);
if(result<min)
{
min=result;
found=true;
}
else swap(r[i],r[j]);
}
}
return min;
}
void main()
{
int n;
float *r,*x,result=9999999,min;
ifstream inf("input.txt"); //打開輸入文件input.txt
if (inf.fail())
{
cerr << "讀入input.txt文件時出錯!";
return;
}
inf>>n;
r=new float[n+1];
for(int i=1;i<=n;i++) inf>>r[i];
x=new float[n+1];
for(i=1;i<=30;i++)
{
min=circle_search(r,x,n);
if(min<result) result=min;
}
ofstream outf("output.txt"); //創建輸出文件output.txt
if (outf.fail())
{
cerr << "創建output.txt文件時出錯!";
return;
}
outf<<result;
inf.close();
outf.close();
delete[] x;
delete[] r;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -