What Is a Bigger Smarter? (Longest DAG path)

Source: Internet
Author: User

The attributes of n elephants, including weight w and IQ s, are given. Now we need to find a continuous sequence, requiring each elephant to have a higher weight than the previous one, the IQ is small, and the maximum value and solution are output. If the solution is not unique, either of them is output. Solution: The longest path of DAG without a fixed point, memory-based search, and record the precursor of the most current solution.

#include <stdio.h>  #include <string.h>  const int N = 10005;    struct State {      int w;      int s;  }tmp[N];  int n, dp[N], vis[N];    int find(int cur) {      if (dp[cur])    return dp[cur];      int a;      vis[cur] = cur;      State& now = tmp[cur];      for (int i = 0; i < n; i++) {      if (tmp[i].w < now.w && tmp[i].s > now.s) {          a = find(i);          if (dp[cur] <= a) {          dp[cur] = a;          vis[cur] = i;          }      }      }      return ++dp[cur];  }    void solve() {      int Max = 0, id = 0, ans[N], cnt = 0;      for (int i = 0; i < n; i++) {      if (!dp[i]) find(i);      if (Max < dp[i]) {          Max = dp[i];          id = i;      }      }        printf("%d\n", Max);      while (id != vis[id]) {      ans[cnt++] = id + 1;      id = vis[id];      }      ans[cnt++] = id + 1;        for (int i = cnt - 1; i >= 0; i--)      printf("%d\n", ans[i]);    }    int main() {      // Init;      n = 0;      memset(tmp, 0, sizeof(tmp));      memset(vis, 0, sizeof(vis));      memset(dp, 0, sizeof(dp));        // Read;      while(scanf("%d%d", &tmp[n].w, &tmp[n].s) == 2)      n++;        solve();        return 0;  }  

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.