NC24391. Message Relay
描述
输入描述
* Line 1: The number of cows, N.
* Lines 2..1+N: Line i+1 contains the value of F(i).
输出描述
* Line 1: The total number of non-loopy cows.
示例1
输入:
5 0 4 1 5 4
输出:
2
说明:
INPUT DETAILS:Java(javac 1.8) 解法, 执行用时: 200ms, 内存消耗: 15036K, 提交时间: 2020-05-30 10:45:22
import java.util.Scanner; public class Main { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int N[] = new int[sc.nextInt()], count = 0; for (int i = 0; i < N.length; i++) { N[i] = sc.nextInt(); } for (int i = 0; i < N.length; i++) { boolean[] visited = new boolean[N.length]; int j = N[i]; while (true) { if (j == 0) { count++; break; } else if (visited[j - 1]) { break; } visited[j - 1] = true; j = N[j - 1]; } } System.out.println(count); } } }
C++11(clang++ 3.9) 解法, 执行用时: 4ms, 内存消耗: 608K, 提交时间: 2020-06-12 11:54:34
#include <iostream> #include <vector> #include <cstdio> using namespace std; const int N = 1005; vector<int> g[N]; int n; bool vis[N]; int cnt; void dfs(int x) { //printf("x = %d\n", x); for (int i = 0; i < g[x].size(); i++) { int y = g[x][i]; if (vis[y] == false) { cnt++; vis[y] = true; dfs(y); } } } int main() { //freopen("Message Relay.txt", "r", stdin); scanf("%d", &n); int t; for (int i = 1; i <= n; i++) { scanf("%d", &t); g[t].push_back(i); } dfs(0); printf("%d\n", cnt); return 0; }
C(clang 3.9) 解法, 执行用时: 3ms, 内存消耗: 380K, 提交时间: 2020-05-30 09:48:11
#include <stdio.h> #define maxn 2010 int opt[maxn],tf[maxn],a[maxn],n,ans = 0; int f(int p){ if (opt[p] > 0) return opt[p]; if (a[p] == 0){ tf[p] = 1; return opt[p] = 1; } if (tf[p] == 1){ return opt[p] = 2; } tf[p] = 1; return opt[p] = f(a[p]); } int main(){ scanf("%d",&n); for (int i = 1; i <= n; ++i) scanf("%d",&a[i]); for (int i = 1; i <= n; ++i) if (f(i) == 1){ ans++; } printf("%d\n", ans); return 0; }
C++14(g++5.4) 解法, 执行用时: 7ms, 内存消耗: 604K, 提交时间: 2020-06-04 13:28:55
#include<iostream> #include<cstdio> using namespace std; int f[1005],mk[1005],vis[1005],v[1005]; int main(){ int i,j,k,m,n,ans=0; scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&f[i]); } for(i=1;i<=n;i++){ v[i]=1;m=i; while(v[f[m]]==0&&f[m]!=0){ v[m]=1; m=f[m]; } if(f[m]!=0){ for(j=1;j<=n;j++) if(v[j]) mk[j]=1; } for(j=1;j<=n;j++) v[j]=0; } for(i=1;i<=n;i++) if(mk[i]==0) ans++; printf("%d",ans); return 0; }