Free Figurines UVALive

来源:互联网 发布:压缩包加密软件 编辑:程序博客网 时间:2024/05/14 13:10

题目传送门

题意:给你一些的套娃的嵌套方式,给你两种操作
1. 打开一个套娃然后放一个比他小的套娃进去。
2. 打开一个套娃拿出其中的套娃。

思路:这个题看到直接就写成暴力了,然后就一场组队赛一直在做这个题直到结束也没有做出来,其实这个题就是一个技巧题。先把初始状态下的所有套娃都分开成单个然后在再组装成目标状态下的所需操作,然后再减去其中不必要的操作就是所需要最小操作数。

#include <algorithm>#include <cmath>#include <cstdio>#include <cstring>#include <fstream>#include <iostream>#include <list>#include <map>#include <queue>#include <set>#include <sstream>#include <stack>#include <string>#include <vector>#define MAXN 100010#define MAXE 210#define INF 100000000#define MOD 1000000007#define LL long long#define pi acos(-1.0)using namespace std;int pre1[MAXN];int pre2[MAXN];int link[MAXN];bool vis[MAXN];int dfs1(int x ,int cnt) {    if (pre1[x] == 0)        return cnt;    if (vis[x]) {        return 0;    }    vis[x] = true;    return dfs1(pre1[x], cnt + 1);}int dfs2(int x ,int cnt) {    if (pre2[x] == 0)        return cnt;    if (vis[x]) {        return 0;    }    vis[x] = true;    return dfs2(pre2[x], cnt + 1);}int main() {    std::ios::sync_with_stdio(false);    int n;    while (cin >> n) {        memset(pre1, 0, sizeof(pre1));        memset(pre2, 0, sizeof(pre2));        for (int i = 1; i <= n; ++i) {            cin >> pre1[i];        }        int sum = 0;        memset(vis, false, sizeof(vis));        for (int i = 1; i <= n; ++i) {            sum += dfs1(i, 0);        }        for (int i = 1; i <= n; ++i) {            cin >> pre2[i];        }        memset(vis, false, sizeof(vis));        for (int i = 1; i <= n; ++i) {            sum += dfs2(i, 0);        }        memset(vis, false, sizeof(vis));        for (int i = 1; i <= n; ++i) {            if (pre1[i]) {                vis[pre1[i]] = true;            }            if (pre2[i]) {                vis[pre2[i]] = true;            }        }        for (int i = 1; i <= n; ++i) {            if (!vis[i]) {                int pos = i;                while (pre1[pos] && pre2[pos] && pre1[pos] == pre2[pos]) {                    sum -= 2;                    pos = pre1[pos];                }            }        }        cout << sum << endl;    }    return 0;}/*73 5 4 0 7 0 03 5 0 6 7 0 062 5 4 0 0 02 6 4 5 0 073 5 4 0 7 0 03 6 4 0 7 5 0 */
原创粉丝点击