1. 程式人生 > >UVALive 7752 Free Figurines (瞎搞)

UVALive 7752 Free Figurines (瞎搞)

unit long long ++ namespace 結點 name ble cpp put

題意:給定 n 個盒子,然後告訴你每個盒子在哪個盒子裏,數值越大,盒子越大,給定你初態,和末態,問你最少要幾步能完成,只有兩種操作,一種是把一個盒子連同裏面的小盒子放到一個空盒子裏,另一種是把一個堆盒子裏的最外面的那個盒子拿出來。

析:首先,先遍歷一次,如果初態和不一樣,那麽初態後面的要全部拿出來,然後再遍歷一次,然後如果發現不一樣,然後要看把末態的父結點是不是孤立的,如果不是,也要全部拿出。

代碼如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#include <list>
#include <assert.h>
#include <bitset>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a, b, sizeof a)
//#define sz size()
#define pu push_up
#define pd push_down
#define cl clear()
#define all 1,n,1
#define FOR(x,n)  for(int i = (x); i < (n); ++i)
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e15;
const double inf = 1e20;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e5 + 100;
const int mod = 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c) {
  return r >= 0 && r < n && c >= 0 && c < m;
}

int fa[maxn];
int pa[maxn];
int ans;

void dfs(int x){
  if(pa[x] == 0)  return ;
  dfs(pa[x]);  pa[x] = 0;
  ++ans;
}

int main(){
  while(scanf("%d", &n) == 1){
    for(int i = 1; i <= n; ++i) scanf("%d", pa+i);
    for(int i = 1; i <= n; ++i) scanf("%d", fa+i);
    ans = 0;
    for(int i = 1; i <= n; ++i)  // remove
      if(pa[i] != fa[i])  dfs(i);
    for(int i = 1; i <= n; ++i){  // unit
      if(pa[i] == fa[i])  continue;
      ++ans;  dfs(fa[i]);
    }
    printf("%d\n", ans);
  }
  return 0;
}

  

UVALive 7752 Free Figurines (瞎搞)