Codeforces Round #286 (Div. 1) C、D,

來源:互聯網
上載者:User

Codeforces Round #286 (Div. 1) C、D,

C:題目中步數看似很多,其實最多就增長250步左右,因為移動的步數為1 + 2 + 3 + .. n,所以大概只會有sqrt(n)步,所以dp[i][j]表示在i位置,增長為j步的值,然後轉移即可

D:這題其實對於一個聯通塊,最多隻需要n條邊,最少要n - 1條,那麼判斷的條件,就是這個聯通塊是否有環,利用拓撲排序去判即可

代碼:

C:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 30005;int n, d, cnt[N], dp[N][500];int dfs(int u, int cha) {    if (u > 30000) return 0;    if (dp[u][cha] != -1) return dp[u][cha];    int tmp = d + cha - 250;    dp[u][cha] = cnt[u];    int ans = 0;    if (tmp > 1)ans = max(ans, dfs(u + tmp - 1, cha - 1));    ans = max(ans, dfs(u + tmp, cha));    ans = max(ans, dfs(u + tmp + 1, cha + 1));    dp[u][cha] += ans;    return dp[u][cha];}int main() {    scanf("%d%d", &n, &d);    int tmp;    for (int i = 0; i < n; i++) {scanf("%d", &tmp);cnt[tmp]++;    }    memset(dp, -1, sizeof(dp));    printf("%d\n", dfs(d, 250));    return 0;}

D:

#include <cstdio>#include <cstring>#include <vector>#include <queue>using namespace std;const int N = 100005;int n, m, du[N], vis[N], have[N], hn;vector<int> g[N], g2[N];void dfs(int u) {    have[hn++] = u;    vis[u] = 1;    for (int i = 0; i < g[u].size(); i++) {        int v = g[u][i];        if (vis[v]) continue;        dfs(v);     }}bool find() {    queue<int> Q;    for (int i = 0; i < hn; i++)        if (!du[have[i]]) Q.push(have[i]);    while (!Q.empty()) {        int u = Q.front();        Q.pop();        int sz = g2[u].size();        for (int i = 0; i < sz; i++) {            int v = g2[u][i];            du[v]--;            if (!du[v]) Q.push(v);        }    }    for (int i = 0; i < hn; i++)        if (du[have[i]]) return true;    return false;}int main() {    scanf("%d%d", &n, &m);    int u, v;    while (m--) {        scanf("%d%d", &u, &v);        du[v]++;        g[u].push_back(v);        g[v].push_back(u);        g2[u].push_back(v);    }    int ans = n;    for (int i = 1; i <= n; i++) {        if (!vis[i]) {            hn = 0;            dfs(i);            if (!find()) ans--;        }    }    printf("%d\n", ans);    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.