演算法小練 字首和

2021-10-21 20:05:33 字數 3969 閱讀 7692

混了半學期開始好好補題

好好做人ing

題目來自洛谷,題解聽從裡面大佬的指點,所以

慢慢爬吧。。。

a.地毯

乙個簡單的字首和

由於資料比較小可以直接暴力過,但是資料大的話怎麼辦呢

直接tle?

#include

using

namespace std;

int ar_1[

2000][

2000];

intmain()

}}for(

int i =

1; i <= n;

++i)

cout << endl;

}return0;

}

對於此類問題我們可以採用字首和的策略求解,大致思路,如果給出在一定範圍內對陣列做相同加減操作,我們可以記錄首位位置與數值大小,並對首位和(末尾+1)的兩個數做操作,並在最後對陣列依次遞推的方式求值,從而使原來o(n3)的時間複雜度降低到o(n2)從而極大的優化演算法,**如下

#include

using

namespace std;

int ar_1[

1024][

1024];

intmain()

}for

(int i =

1; i <= n;i++

) cout << endl;

}return0;

}

就一題?

b.最大加權矩形

題目簡介,在n*n的正方形中找到加權最重的矩形

題目分析,直接暴力求解?

/*

* referce:

* @author:follyfish

* @date:3.11

* @time:19.52

*/#include

#include

#include

#include

#include

using

namespace std;

typedef

long

long ll;

const

int n =

128;

int n;

int arr[n]

[n],temp_arr[n]

;ll ans, cnt;

intjs

(int x,

int y,

int z)

return temp_1;

}int

main()

}//壓縮遍歷

for(

int i =

0; i < n;

++i)

cnt =0;

for(

int k =

0; k < n;

++k)}}

if(ans>0)

cout << ans;

else cout <<0;

return0;

}

天啊四個for真的能行嗎?

我們可不可以對他用字首和的方式對他優化呢?

要怎麼優化呢?

如果我們讀數時使其每乙個都加上一行或者是上一列的權重會有什麼結果?

不難發現我們用加上權重的值去將去前面某個位置的值可以直接得到這兩個值之間的權重和(左開右閉區間)從而簡便了演算法

**如下

/*

* referce:字首和加動態規劃

* @author:follyfish

* @date:3.11

* @time:20.24

*/#include

#include

#include

#include

#include

using

namespace std;

typedef

long

long ll;

const

int n =

128;

int ar_1[n]

[n];

int ans;

intmain()

}for

(int i =

1; i <= n;

++i)

//和第乙個**思路一致}}

cout << ans;

return0;

}

這樣我們就少了乙個for得到乙個o(n3)的演算法

-----------------------手寫的分割線-------------------------

在來兩題?

可。

c.領地選擇

思路與b題一致練練手吧

/*

* referce:

* @author:follyfish

* @date:3.11

* @time: 21.17

*/#include

#include

#include

#include

#include

using

namespace std;

typedef

long

long ll;

const

int n =

1024

;int mp[n]

[n];

int n, m, c,ans=

-2147483647

;//int所能去的最小值

int x, y;

intmain()

}for

(int i = c; i <= n;

++i)

if(anscout <" "

}

想不到吧還有一題,在練練吧

d.海底高鐵

相信你已經很熟練了吧

/*

* referce:

* @author:follyfish

* @date:3.11

* @time:22.00

*/#include

#include

#include

#include

#include

using

namespace std;

typedef

long

long ll;

const

int n =

1e6+8;

int n,m;

ll ar[n]

;struct o money[n]

;ll ans;

ll js

(int x)

intmain()

for(

int i =

1; i <= n-1;

++i)

for(

int i =

1; i <= n;

++i)

ar[i +1]

+= ar[i]

;for

(int i =

1; i <= n;

++i)

cout << ans;

return0;

}

手寫的文末~~>…<

演算法小練 A B 問題

title 演算法小練 a b 問題 categories 給出兩個整數 aa 和 bb 求他們的和。你不需要從輸入流讀入資料,只需要根據aplusb的兩個引數a和b,計算他們的和並返回就行。您在真實的面試中是否遇到過這個題?是 題目糾錯 a和b都是32位整數麼?我可以使用位運算子麼?樣例 1 輸入...

演算法小練 移除元素

title 演算法小練 移除元素 date 2019 11 07 18 53 04 algorithms tags 給定乙個陣列 nums 和乙個值 val,你需要原地移除所有數值等於 val 的元素,返回移除後陣列的新長度。不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 o 1 額外空間...

演算法小練 加一

title 演算法小練 加一 date 2019 11 09 19 43 59 categories 給定乙個由整數組成的非空陣列所表示的非負整數,在該數的基礎上加一。最高位數字存放在陣列的首位,陣列中每個元素只儲存單個數字。你可以假設除了整數 0 之外,這個整數不會以零開頭。示例 1 輸入 1,2...