zoukankan      html  css  js  c++  java
  • b_lg_连续攻击游戏(反向思维+记忆化搜索)

    一开始的时候,lxhgww只能使用某个属性值为1的装备攻击boss,然后只能使用某个属性值为2的装备攻击boss,
    然后只能使用某个属性值为3的装备攻击boss……以此类推。现在lxhgww想知道他最多能连续攻击boss多少次?

    思路
    这本是一道二分图的题,但我很生气我没学过,所以一气之下写了个50/100的正向暴搜

    #include<bits/stdc++.h>
    using namespace std;
    const int N=1e7+5;
    int n, a[N][2], st[N], ans;
    void dfs(int attr) {
        if (attr>ans) ans=attr;
        for (int j=1; j<=n; j++) if (!st[j] && (attr+1==a[j][0] || attr+1==a[j][1])) {
            st[j]=1;
            dfs(attr+1);
            st[j]=0;        
        }
    }
    int main() {
        std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
        cin>>n; for (int i=1; i<=n; i++) cin>>a[i][0]>>a[i][1];
        for (int i=1; i<=n; i++) if (a[i][0]==1 || a[i][1]==1) {
            st[i]=1;
            dfs(1);
            st[i]=0;
        }
        cout<<ans;
        return 0;
    }
    

    想着加入记忆化加速,但上面的代码即使加入记忆化也无法摆脱main函数中的for循环
    反向思维优化:将每个武器的属性和属性id换过来存储,即 a[x].push_back(id), a[y].push_back(id)

    #include<bits/stdc++.h>
    using namespace std;
    const int N=1e6+5;
    int st[N], f[N], ans;
    vector<int> a[N];
    int dfs(int attr) {
        if (f[attr]) return f[attr];
        int t=0;
        for (int& id : a[attr]) if (!st[id]) { //该attr对应的武器编号
            st[id]=1;
            t=max(t,dfs(attr+1)+1);
            st[id]=0;
        }
        return f[attr]=t;
    }
    int main() {
        std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
        int n; cin>>n;
        for (int i=1; i<=n; i++) {
            int x,y; cin>>x>>y;
            a[x].push_back(i), a[y].push_back(i);
        }
        cout<<dfs(1);
        return 0;
    }
    
  • 相关阅读:
    .Net需要掌握的知识
    图片轮播
    vector
    2016ACM青岛区域赛题解
    总是有一个程序的bug没找到
    poj1001_Exponentiation_java高精度
    poj2236_并查集_Wireless Network
    poj1703_Find them, Catch them_并查集
    poj2492_A Bug's Life_并查集
    poj1182食物链_并查集_挑战程序设计竞赛例题
  • 原文地址:https://www.cnblogs.com/wdt1/p/13809441.html
Copyright © 2011-2022 走看看