結果

問題 No.399 動的な領主
ユーザー rapurasurapurasu
提出日時 2016-07-19 18:02:36
言語 C++11
(gcc 11.4.0)
結果
TLE  
実行時間 -
コード長 1,808 bytes
コンパイル時間 1,343 ms
コンパイル使用メモリ 161,016 KB
実行使用メモリ 14,060 KB
最終ジャッジ日時 2024-04-23 16:50:32
合計ジャッジ時間 6,852 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
14,060 KB
testcase_01 AC 3 ms
7,168 KB
testcase_02 AC 3 ms
7,104 KB
testcase_03 AC 4 ms
6,948 KB
testcase_04 AC 4 ms
6,956 KB
testcase_05 AC 19 ms
7,500 KB
testcase_06 AC 451 ms
10,368 KB
testcase_07 AC 459 ms
10,436 KB
testcase_08 AC 319 ms
10,368 KB
testcase_09 AC 295 ms
10,368 KB
testcase_10 AC 5 ms
7,136 KB
testcase_11 AC 14 ms
7,492 KB
testcase_12 AC 130 ms
10,544 KB
testcase_13 AC 124 ms
10,796 KB
testcase_14 TLE -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

 #include<bits/stdc++.h>
 using namespace std;
#define INF 1000000000
#define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++)

typedef long long int LL;
int parent[100002];
int rnk[100002];
vector<int> v[100002];
int cost[100002];
bool check[100002];
bool check2[100002];

//親の作成
void dfs(int n,int x){
   REP(i,v[n].size()){
       int a=v[n][i];
       if(check[a]==false){
          check[a]=true;
          parent[a]=n;
          rnk[a]=x;
          dfs(a,x+1);
       }
   }
}
//imos法
LL imos(int n){
   LL ans=0;
   REP(i,v[n].size()){
       int a=v[n][i];
       if(check2[a]==false){
          check2[a]=true;
          ans+=imos(a);
          cost[n]+=cost[a];
       }
   }
   LL mm=cost[n];
   ans+=(mm+1)*mm/2;
//cout<<n<<*m<<endl;
   return ans;
}

//最小の親を求める
LL lca(int n,int m){
     if(rnk[n]<rnk[m]){
        int temp=m;
        m=n;
        n=temp;
     }
//cout<<rnk[n]<<rnk[m]<<endl;

     int s=rnk[n]-rnk[m];
//cout<<n<<m<<0<<s<<endl;
     REP(i,s){
         n=parent[n];
     }
//cout<<n<<m<<endl;
     while(1){
         if(n==m)break;
         n=parent[n];
         m=parent[m];
     }
     return n;
}


int main(){
    REP(i,100002){
        parent[i]=0;
        rnk[i]=-1;
        cost[i]=0;
        check[i]=false;
        check2[i]=false;
    }

    int N,Q;
    cin>>N;
    REP(i,N-1){
        int a,b;
        cin>>a>>b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    check[1]=true;
    rnk[1]=0;
    dfs(1,1);
    cin>>Q;
    REP(i,Q){
        int a,b;
        cin>>a>>b;
        cost[a]++;
        cost[b]++;
        if(lca(a,b)!=-1){
           cost[lca(a,b)]--;
           if(parent[lca(a,b)]!=-1){
              cost[parent[lca(a,b)]]--;
           }
        }
    }


    check2[1]=true;
    LL ans=imos(1);
    cout<<ans<<endl;

}
0