#37924: 為什麼while裡不擺cin>>n就不會過?


oliverho0214@gmail.com (123)

學校 : 不指定學校
編號 : 210608
來源 : [36.228.245.204]
最後登入時間 :
2022-10-09 23:19:41
b967. 4. 血緣關係 -- 2016年3月apcs | From: [61.228.75.33] | 發表日期 : 2023-10-18 20:36

我這題這樣寫TLE

#include <bits/stdc++.h>

using namespace std;

int ans=0;

int Count(int target,vector<vector<int>>& tree,vector<int>& high){
    if(high[target]){
        return high[target];
    }
    if(tree[target].empty()){
        return 1;
    }

    int max_1=0;
    int max_2=0;

    for(int i:tree[target]){

        if(Count(i,tree,high)>max_2){

            max_2=Count(i,tree,high);

            if(max_2>max_1){
                swap(max_2,max_1);
            }

        }
    }
    high[target] = max_1+1;

    ans = max(max_1+max_2,ans);

    return high[target];

}


main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    while(1){
    int n;

    cin>>n;



    vector<vector<int>> tree(n);
    vector<int> high(n);

    int a,b;
    for(int i=0;i<n-1;i++){
        cin>>a>>b;
        tree[a].push_back(b);
    }


    for(int i=0;i<n;i++){
        if(!high[i]){
            Count(i,tree,high);
        }
    }




    cout<<ans<<"\n";
    ans=0;
    }



    return 0;
}

但我把cin擺到while裡就過了,如下

#include <bits/stdc++.h>

using namespace std;

int ans=0;

int Count(int target,vector<vector<int>>& tree,vector<int>& high){
    if(high[target]){
        return high[target];
    }
    if(tree[target].empty()){
        return 1;
    }

    int max_1=0;
    int max_2=0;

    for(int i:tree[target]){

        if(Count(i,tree,high)>max_2){

            max_2=Count(i,tree,high);

            if(max_2>max_1){
                swap(max_2,max_1);
            }

        }
    }
    high[target] = max_1+1;

    ans = max(max_1+max_2,ans);

    return high[target];

}


main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n;
    while(cin>>n){
     




    vector<vector<int>> tree(n);
    vector<int> high(n);

    int a,b;
    for(int i=0;i<n-1;i++){
        cin>>a>>b;
        tree[a].push_back(b);
    }


    for(int i=0;i<n;i++){
        if(!high[i]){
            Count(i,tree,high);
        }
    }




    cout<<ans<<"\n";
    ans=0;
    }



    return 0;
}
 
#38032: Re: 為什麼while裡不擺cin>>n就不會過?


cges30901 (cges30901)

學校 : 不指定學校
編號 : 30877
來源 : [101.136.203.77]
最後登入時間 :
2024-04-07 15:34:14
b967. 4. 血緣關係 -- 2016年3月apcs | From: [27.53.241.140] | 發表日期 : 2023-10-22 22:48

    while(1){


這樣不就變成無限迴圈了?除非加一個break:

if(!(cin>>n)) break;
 
ZeroJudge Forum