Skip to content

Instantly share code, notes, and snippets.

@luccasiau
Created June 8, 2015 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luccasiau/2465e35bb63ba427bebb to your computer and use it in GitHub Desktop.
Save luccasiau/2465e35bb63ba427bebb to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <vector>
#include <cassert>
#define MAXN 100100
using namespace std;
typedef long long ll;
int n;
bool visited[MAXN];
vector<int> graph[MAXN];
int last; //quantidade de componentes conexas
ll qtt[MAXN];
void dfs(int x){
qtt[last]++;
visited[x] = true;
for(int i = 0;i < graph[x].size();i++){
if(!visited[ graph[x][i] ])
dfs(graph[x][i]);
}
}
int main(){
scanf("%d", &n);
for(int i = 1;i < n;i++){
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
if(c) continue;
graph[a].push_back(b);
graph[b].push_back(a);
}
for(int i = 1;i <= n;i++) visited[i] = 0;
for(int i = 1;i <= n;i++){
if(!visited[i]){
last++;
dfs(i);
}
}
ll answer = 0LL;
for(int i = 1;i <= last;i++) answer += qtt[i];
answer *= answer;
for(int i = 1;i <= last;i++) answer -= qtt[i]*qtt[i];
answer /= 2;
printf("%lld\n", answer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment