我的这份代码
#include <bits/stdc++.h>
using namespace std;
#define N 1000006
#define int long long
int n, siz[N], ans;
vector<pair<int, int> > e[N];
void dfs(int x, int fa)
{
for(auto i : e[x])
{
if(fa != i.first)
{
dfs(i.first, x);
ans += abs(siz[i.first] - (n - siz[i.first])) * i.second;
siz[x] += siz[i.first];
}
}
}
signed main()
{
scanf("%lld", &n);
int x, y, z;
for(int i = 1; i <= n; i++) siz[i] = 1;
for(int i = 1; i < n; i++)
{
scanf("%lld%lld%lld", &x, &y, &z);
e[x].push_back(make_pair(y, z));
e[y].push_back(make_pair(x, z));
}
dfs(1, 1);
printf("%lld", ans);
return 0;
}
对比我以前的代码
#include <bits/stdc++.h>
using namespace std;
#define N 1000006
#define int long long
int n, siz[N], ans;
vector<pair<int, int> > e[N];
void dfs(int x, int fa)
{
for(auto _ : e[x])
{
if(fa != _.first)
{
dfs(_.first, x);
ans += abs(siz[_.first] - (n - siz[_.first])) * _.second;
siz[x] += siz[_.first];
}
}
}
signed main()
{
scanf("%lld", &n);
int x, y, z;
for(int i = 1; i <= n; i++) siz[i] = 1;
for(int i = 1; i < n; i++)
{
scanf("%lld%lld%lld", &x, &y, &z);
e[x].push_back(make_pair(y, z));
e[y].push_back(make_pair(x, z));
}
dfs(1, 1);
printf("%lld", ans);
return 0;
}
只把 DFS 里的变量名 _ 改成了 i
但是却从0分变到了AC , 为什么啊?(我的0分代码甚至是TLE + WA)