小小的激动一下,自己做出来的。。
然后有个警醒,如果不是顺其自然简化的条件判断表达式(例如!flag,是flag==0的同义),不要生搬硬套简化,很容易出错!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include<iostream> #include<cstring> #include<algorithm> #define ll long long #define pii pair<int,int> #define PINF 0x7fffffff #define NINF 0x80000000 using namespace std; int n; int To[200005]; int inDegree[200005]; int getRing(int node) { if (!inDegree[node])return 0; inDegree[node] = 0; return 1 + getRing(To[node]); } int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1; i <= n; i++) { cin >> To[i]; inDegree[To[i]]++; } int flag = 0; do { flag = 0; for (int i = 1; i <= n; i++) { if (inDegree[i]==0) { inDegree[i]--; inDegree[To[i]]--; flag++; } } } while (flag!=0); int mmin = 0x7fffffff; for (int i = 1; i <= n; i++) { if (inDegree[i] > 0)mmin = min(mmin, getRing(i)); } cout << mmin; } |