输入这个数据(代码在下面):
20
9 14 10 8 9 14 12 5 1 9 9 11 13 13 10 5 10 5 6
10 12 5 6 10 12 14 6 8 10 5 9 5 7 12 11 5 1
13 5 10 13 5 13 5 5 9 11 5 9 13 13 6 7 7
13 12 11 11 6 11 13 12 3 9 8 2 10 13 9 9
6 11 10 6 7 14 12 11 14 10 3 14 1 7 12
11 9 6 13 4 6 7 8 10 10 9 12 9 14
9 2 14 11 9 11 14 1 13 1 7 5 7
8 10 10 14 6 11 10 1 13 11 13 6
9 8 10 10 11 7 4 5 9 14 13
10 4 14 12 13 5 13 10 11 9
5 13 12 10 3 11 14 9 5
8 14 6 4 14 9 14 7
14 7 14 14 14 2 8
8 5 14 13 14 11
14 8 12 14 8
12 9 13 11
12 5 8
11 6
9
同一个代码,有时它是正常输出22,但有时炸了,求解!
代码:
#include<bits/stdc++.h>
#define N 105
#define M 1e9
using namespace std;
int ans,n,w,g = 1,to,u,minn,c,fa,k;
vector <int> e[N];
struct Node
{
int a,v,f;
};
vector <Node> f;
struct No
{
int to,v;
};
vector <No> t[N];
bool vis[N];
void dfs(int x,int r,int fa)
{
if(r > ans)
{
ans = r;
u = x;
}
for(int i = 0;i < t[x].size();i ++)
{
if(fa == t[x][i].to) continue;
dfs(t[x][i].to,t[x][i].v + r,x);
}
return;
}
int main()
{
freopen("475718_2.in","r",stdin);
// freopen("475718_2.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> n;
for(int i = 1;i <= n;i ++)
{
e[i].push_back(0);
for(int j = i + 1;j <= n;j ++)
{
cin >> w;
e[i].push_back(w);
e[j].push_back(w);
}
}
for(int i = 1;i < e[1].size();i ++)
{
w = e[1][i],to = i + 1;
f.push_back((Node){to,w,1});
}
vis[1] = 1;
while(g < n)
{
minn = M,c = 0,fa = 0,k = 0;
int fs = f.size();
for(int i = 0;i < fs;i ++)
{
if(vis[f[i].a])
{
f.erase(f.begin() + i);
i --;
}
if(minn > f[i].v)
{
c = f[i].a;
minn = f[i].v;
fa = f[i].f;
k = i;
}
}
t[fa].push_back((No){c,minn});
t[c].push_back((No){fa,minn});
g ++;
for(int i = 0;i < e[c].size();i ++)
{
w = e[c][i],to = i + 1;
if(to == c) continue;
f.push_back((Node){to,w,c});
}
vis[c] = 1;
}
dfs(1,0,0);
dfs(u,0,0);
cout << ans << endl;
return 0;
}