我正在尋找一個提示來嚴格找出非單調的條件。
數字字串以值 0 結尾,其中 0 不是高度的一部分(僅標記字串的結尾)。
指定高度范圍是升序、降序還是非單調。
Input Output
---------------------------
1 2 5 5 10 11 0 ascending
16 7 3 0 descending
1 2 2 1 0 non-monotonous
盡量用while、if和int解決。
限制和說明:
- 0 不是高度字串的一部分,只標記字串的結尾
- 高度是 0 到 10,000 之間的數字
- 為簡單起見,如果所有數字都相等或在 0 之前沒有值,則該字串被認為是非單調的
我如何嘗試解決它:
int main(){
int b , a , ascending = 0 , counter = 0 , descending = 0 ;
cin >> a;
while( a != 0 ){
cin >> b;
counter;
if( a && b != 0 ){
if( a < b ){
ascending;
}
else if(a > b ){
descending;
}
}
a = b;
}
--counter;
if(ascending == counter ){
cout << "\n ascending";
}
else if ( descending > 2 ){
cout << " non-monotonous ";
}
if(descending == counter){
cout << "\n descending ";
}
else if ( ascending > 2 ){
cout << " non-monotonous ";
}
}
uj5u.com熱心網友回復:
我建議您創建兩個 bool 變數并將其命名ascending并descending為它們分配 true。并且始終保留current您擁有的last號碼和號碼。
然后你可以執行while回圈你怎么做
如果您遇到這種情況:
last_number>current_number
然后您只需為升序變數分配 false
如果你有 last_number<current_number
然后反過來
回圈結束后,答案將在此變數中。
uj5u.com熱心網友回復:
這是我將如何解決它,但別擔心,我將解釋我在撰寫代碼時是如何推理的。此解決方案僅被認為對學校有用,因為使用 C 標準實用程式,您可以使用近兩行長檢查來檢查序列(其他用戶已使用比這更快、更干凈和更明智的方法進行回應)
int main()
{
bool descending = true;
bool ascending = true;
bool equals = true;
int num = -1;
int last_num = -1;
std::cin >> num;
last_num = num;
while( num != 0 ){
if(ascending)
ascending = last_num <= num;
if(descending)
descending = last_num >= num;
if(equals)
equals = last_num == num;
last_num = num;
std::cin >> num;
}
if(equals)
std::cout << "non-monotonous";
else if(descending)
std::cout << "descending";
else if(ascending)
std::cout << "ascending";
else
std::cout << "non-monotonous";
return 0;
}
在這種情況下,您無法存盤整個序列并在最后對其進行檢查。因此,您必須檢查遵守什么條件(升序、降序、非單調)的獨特方法是存盤哪些條件對以前的整數仍然有效,并用新整數檢查它們。
為此,我將 (is) descending(is)ascending和 (is) 存盤equals在三個(最初為真)布林值中。每次我得到一個新輸入時,我都會檢查它們中哪些仍然為真,一旦驗證了哪些條件仍然為真,我就可以一一檢查它們(僅那些仍然為真)并驗證新輸入是否破壞了其中一個。
當 while 完成時(并且我得到最后一個被丟棄的 0 數字),最后一個階段是檢查哪些條件仍然為真,優先考慮 (is),equals因為它可以為真而不會使其他兩個條件無效。
descending并且ascending是自我排除的,所以只有一個是真的,所以無論這兩個是什么,我都會在第一個 ( equals)之后檢查。
如果我得到三個錯誤條件,則序列肯定是非單調的。
編輯(感謝@Pete Becker的提示)
我們可以通過另外兩件事來改進代碼,使其更短、更清晰。
-第一點是關于descending和的條件檢查ascending。為簡潔起見,我們可以這樣做:
ascending &= last_num <= num;
descending &= last_num >= num;
按位運算子&=對ascending和descending變數的位應用 AND 運算。這些變數保持true值的獨特方法是僅將正確的值傳遞給 &= 運算子。簡而言之,如果只有一次正確的值為 false,則該變數的 bool 值在回圈的其余部分將為 false。
- 第二點是關于equals變數。這不是絕對必要的,因為我們可以通過檢查descending和ascending是否為真來知道所有值是否相等。
uj5u.com熱心網友回復:
如果你有一個整數范圍*,你可以用std::is_sorted下面的函式來寫
std::string monotonous(std::vector<int> const & v)
{
if (v.empty() or
std::equal(std::begin(v), std::end(v) - 1, std::begin(v) 1))
return "non-monotonous";
if (std::ranges::is_sorted(v))
return "ascending";
else
if (std::ranges::is_sorted(v, std::greater{}))
return "descending";
else
return "non-monotonous";
}
這是一個演示。
如果您沒有 C 20,則std::ranges::is_sorted可以替換為std::is_sorted,并且必須明確指定范圍內的迭代器,例如std::is_sorted(std::begin(v), std::end(v), std::greater{}).
*如果這些值是從標準輸入讀入的,則將它們添加到 a vector<int>(最后一個除外0),然后呼叫該函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351334.html
