#110-【我也不知道這是什麼鬼演算法】Ska Piggy Banks
阿新 • • 發佈:2018-11-09
Description
Byteazar 有 N 個小豬存錢罐. 每個存錢罐只能用鑰匙開啟或者砸開. Byteazar 已經把每個存錢罐的鑰匙放到了某些存錢罐裡. Byteazar 現在想買一臺汽車於是要把所有的錢都取出來. 他想盡量少的打破存錢罐取出所有的錢,問最少要打破多少個存錢罐.
Input
第一行一個整數 N (1 <= N <= 1.000.000) – 表示存錢罐的總數. 接下來每行一個整數,第 i+1行的整數代表第i個存錢罐的鑰匙放置的存錢罐編號.
Output
一個整數表示最少打破多少個存錢罐.
Sample Input
4
2
1
2
4
Sample Output
2
如果找到這一次才找到的點,停止,結果rp++,
如果找到之前找到的點,停止,結果rp不加不減。
據說有人用並查集?
#include <iostream> #define SIZE 1000010 using namespace std; int pre[SIZE], count = 0; bool visited[SIZE], visited2[SIZE]; void dfs(int u) { if (visited[u]) { if (!visited2[u]) { ++count; // 找到這次找過的點,結果++ visited2[u] = true; } return; // 如果是之前找過的就不管 } visited[u] = true; dfs(pre[u]); visited2[u] = true; return; } int main(void) { int n, i; scanf("%d", &n); for (i = 1; i <= n; ++i) { scanf("%d", &pre[i]); } for (i = 1; i <= n; ++i) { if (!visited[i]) { dfs(i); } } printf("%d", count); return 0; }