1 角谷步數你聽說過角谷猜想嗎?任意的正整數,比如 5, 我們從它開始,如下規則計算:如果是偶數,則除以2,如果是奇數,則乘以3再加1.如此循環,最終必會得到“1” !比如 5 的處理過程是:5168421一個正整數經過多少步才能變成1, 稱爲角谷步數。對於5而言,步數也是5對於1,步數爲0本題的要求是,從標準輸入給定一個整數n(1<n<300)表示角谷步數求滿足這個角谷步數的最小的正整數例如:輸入:3則輸出:8輸入:4則輸出:16輸入:7則輸出:3
int ComputStep(unsigned int n) { int count=0; if(n==1) return 0; int nStep=0; while(n>1){ if(n%2==0) n=n/2; else n=n*3+1; nStep++; if(nStep>300) break; } return nStep; } int aStep[65005]={0}; unsigned int GetFromStep(int nStep) { unsigned int i=0; for(i=0;i<65005;i++){ if(aStep[i]==nStep) break; } return i; } main() { unsigned int i=2; for(i=2;i<=65000;i++){ aStep[i] = ComputStep(i); printf("%d: %d\n",i,aStep[i]); } printf("%u\n",GetFromStep(10)); printf("%u\n",GetFromStep(20)); printf("%u\n",GetFromStep(100)); printf("%u\n",GetFromStep(290)); printf("%u\n",GetFromStep(298)); }
2 不用排序算法分離數組中的負數,0和正數
#include <stdlib.h>
#include <stdio.h>
#define N 10
int main(void)
{
int p=0,q=N-1,a[N]={2,-5,-89,75,0,-89,0,93,48,0};
int i,temp;
while(p<=q){
if (a[p]<0) {p++;continue;}
if (a[q]>0) {q--;continue;}
if (a[p]>0&&a[q]<0){
temp=a[p]; a[p]=a[q]; a[q]=temp;
p++; q--; continue;
}
if (a[p]==0){
// from p+1 to q, find a nege num
for(i=p+1;i<=q;i++)
if(a[i]<0){
temp=a[p]; a[p]=a[i]; a[i]=temp;
break;
}
p++;
continue;
}
if (a[q]==0){
for(i=q-1;i>=p;i--)
if(a[i]>0){
temp=a[q]; a[q]=a[i]; a[i]=temp;
break;
}
q--;
continue;
}
}
for(i=0;i<N;i++)
printf("%4d",a[i]);
system("pause");
}
3 藍橋杯模擬試題答案及簡要說明
4 最小方差生成樹
輸入格式
輸入多組測試數據。第一行爲N,M,依次是點數和邊數。接下來M行,每行三個整數U,V,W,代表連接U,V的邊,和權值W。保證圖連通。n=m=0標誌着測試文件的結束。
輸出格式
對於每組數據,輸出最小方差,四捨五入到0.01。輸出格式按照樣例。
樣例輸入
4 5
1 2 1
2 3 2
3 4 2
4 1 1
2 4 3
4 6
1 2 1
2 3 2
3 4 3
4 1 1
2 4 3
1 3 3
0 0
樣例輸出
Case 1: 0.22
Case 2: 0.00
數據規模與約定
1<=U,V<=N<=50,N-1<=M<=1000,0<=W<=50。數據不超過5組。
做法:枚舉最小生成樹可能的邊權平均值,將邊權設置爲原邊權減去平均值的平方,然後求最小生成樹。
for 每一個n-1條邊的組合 in 所有的邊 (n爲節點的數量)
if ( n-1條邊包含了n個節點 ) // 有效組合
{
計算邊平均值 m
for (每個邊) new_w = (w-m)^2; // 原圖不改變
計算new_w的圖對應的最小生成樹,並計算代價
比較歷史代價,保留最小的
}