欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HDUOJ 1160 FatMouse‘s Speed

程序员文章站 2024-02-24 17:38:37
...

HDUOJ 1160 FatMouse’s Speed

题目链接

Problem Description

FatMouse believes that the fatter a mouse is, the faster it runs. To disprove this, you want to take the data on a collection of mice and put as large a subset of this data as possible into a sequence so that the weights are increasing, but the speeds are decreasing.

Input

Input contains data for a bunch of mice, one mouse per line, terminated by end of file.

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.

Output

Your program should output a sequence of lines of data; the first line should contain a number n; the remaining n lines should each contain a single positive integer (each one representing a mouse). If these n integers are m[1], m[2],…, m[n] then it must be the case that

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.

Sample Input

6008 1300
6000 2100
500 2000
1000 4000
1100 3000
6000 2000
8000 1400
6000 1200
2000 1900

Sample Output

4
4
5
9
7

典型的 DAG 最长路,我们将每个老鼠离散成一个个点,如果满足上述关系就连边,最后在建好的图中求最长路即可,在此基础上加了一个输出路径,直接 DFS 输出即可,AC代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node{
    int w,s;
}mice[1005];
int a,b,cnt=0,ans=0,pos,dp[1005]={0};
vector<int>g[1005];

int dfs(int u){
    if(dp[u]) return dp[u];
    dp[u]=1;
    for(auto v:g[u]){
        dp[u]=max(dp[u],dfs(v)+1);
    }
    return dp[u];
}

void build(){
    for(int i=0;i<cnt;i++){
        for(int j=0;j<cnt;j++){
            if(mice[i].w>mice[j].w&&mice[i].s<mice[j].s) g[i].push_back(j);
        }
    }
}

void print(int v){
    for(auto u:g[v]){
        if(dp[v]==dp[u]+1){
            print(u);
            break;
        }
    }
    printf("%d\n",v+1);
}

int main(){
    while(~scanf("%d%d",&a,&b)){
        mice[cnt].w=a,mice[cnt++].s=b;
    }
    build();
    for(int i=0;i<cnt;i++){
        if(!dp[i]) dfs(i);
        if(dp[i]>ans) ans=dp[i],pos=i;
        if(dp[i]==ans) pos=min(pos,i);
    }
    printf("%d\n",ans);
    print(pos);
}
相关标签: DAG最长路 HDUOJ