HDU 1160 FatMouse's Speed DP題解,hdufatmouse
本題就先排序老鼠的重量,然後尋找老鼠的速度的最長遞增子序列,不過因為需要按原來的標號輸出,故此需要使用struct把三個資訊打包起來。
尋找最長遞增子序列使用動態規劃法,基本的一維動態規劃法了。
記錄路徑:只需要記錄後繼標號,就可以逐個輸出了。
#include <stdio.h>#include <algorithm>using namespace std;const int MAX_N = 1005;struct MouseSpeed{int id, w, s;bool operator<(const MouseSpeed &ms) const{return w < ms.w;}};int N;MouseSpeed msd[MAX_N];int post[MAX_N], tbl[MAX_N];int main(){N = 0;while (~scanf("%d %d", &msd[N].w, &msd[N].s)){msd[N].id = N+1;++N;}sort(msd, msd+N);//fullfill condition 1: weight increasefill(tbl, tbl+N, 1);//initialize dynamic tablepost[N-1] = N-1;for (int i = N-2; i >= 0; i--){post[i] = i;//as the print out terminate termfor (int j = i+1; j < N; j++){if (msd[i].s>msd[j].s && msd[i].w!=msd[j].w && tbl[i]<tbl[j]+1){//strictly increase, so don't forget msd[i].w must < msd[j].wtbl[i] = tbl[j]+1;//update longest subsequencepost[i] = j;//record the post}}}int id = 0, maxSeq = 0;for (int i = 0; i < N; i++)//find the max sequence starting point{if (maxSeq < tbl[i]){id = i;maxSeq = tbl[i];}}printf("%d\n", maxSeq);printf("%d\n", msd[id].id);while (id != post[id]){id = post[id];printf("%d\n", msd[id].id);//print out the original indices}return 0;}
hdu 1160 FatMouse's Speed幫忙看看哪錯了,為啥WA
程式中for迴圈裡面有i重複聲明了,第一個for迴圈已經聲明i為int類型了,之後的for迴圈不能夠再次聲明了,它相當於main函數中的全域變數。
for(int i=pos-2;i>=0;i--)、for(int i=0;i<pos;i++)這裡不可以聲明i。
另外,main函數應該有個傳回值:return 0;