FatMouse's Speed
Total Submission(s): 9174 Accepted Submission(s): 4061
Special Judge
The data for a particular mouse will consist of a pair of integers: the first representing its size in grams and the second representing its speed in centimeters per second. Both integers are between 1 and 10000. The data in each test case will contain information for at most 1000 mice.
Two mice may have the same weight, the same speed, or even the same weight and speed.
W[m[1]] < W[m[2]] < ... < W[m[n]]
and
S[m[1]] > S[m[2]] > ... > S[m[n]]
In order for the answer to be correct, n should be as large as possible.
All inequalities are strict: weights must be strictly increasing, and speeds must be strictly decreasing. There may be many correct outputs for a given input, your program only needs to find one.
先將重量從小到大排,再找速度的最長遞減子序列。
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> using namespace std; #define M 2050 struct node { int w,s,index; //w:重量,s:速度,index:第幾個數。 }map[M]; bool cmp(node x,node y){ //如果重量相等,速度大的排前面。 if(x.w==y.w) return x.s>y.s; return x.w<y.w; //如果重量不相等,重量小的排前面。 } int res[M],dp[M],pre[M]; int main() { int i=1,j,k,n,m,maxlen; while(cin>>n>>m) { map[i].w=n;map[i].s=m;map[i].index=i; dp[i]=1;pre[i]=0; i++; //這道題輸入有點問題,要強制結束纔有輸出。 } sort(map+1,map+i,cmp); //對數據進行排序。 n=i-1;maxlen=0; //n表示元素的個數。maxlen表示當前的最長的長度。 int maxi; //maxi記錄最長遞減子序列的末元素。 dp[1]=1; for(i=1;i<=n;i++) //模板。 for(j=1;j<i;j++) if(map[i].w>map[j].w && map[i].s<map[j].s && dp[j]+1>dp[i]) //發現以i結束的有更長的就更新。 { dp[i]=dp[j]+1; pre[i]=j; //pre[]記錄的就是i元素的前一個元素是j。 if(dp[i]>maxlen) //判斷是否比最長個還長。 { maxi=i; maxlen=dp[i]; } } int t=maxi; i=0; while(t!=0) //通過回溯將元素反序輸入res[],同時i找到了元素的個數。 { res[i++]=t; t=pre[t]; } printf("%d\n",i); while(i>0) { i--; //正序輸出。 printf("%d\n",map[res[i]].index); } return 0; }