1 条题解
-
0hwt1216 LV 7 @ 2024-10-10 22:43:17
#include <bits/stdc++.h> using namespace std;
const int N = 1010; int n,m,tot,belong[N]; int ans,gcc[N],d[N],mx[N]; bool ood; vector<int> g[N];
void dfs(int u,int bel,int t){ if(ood)return ; gcc[u] = t,belong[u] = bel; for(int v:g[u]){ if(ood)return ; if(!belong[v]){ dfs(v,-bel,t); if(ood)return ; } else if(belong[u] + belong[v]){ ood = 1; return ; } } } int bfs(int s){ memset(d,127,sizeof(d)); d[s] = 0; queue<int> q; bitset<N> vis; int maxdis = 0; q.push(s); while(!q.empty()){ int u = q.front(); q.pop(); vis[u] = 1; for(int v:g[u]){ if(d[u] + 1 < d[v]){ d[v] = d[u] + 1; maxdis = max(maxdis,d[v]); if(!vis[v])q.push(v); } } }return maxdis; } int main(){ cin>>n>>m; for(int i = 1;i <= m;i++){ int u,v; cin>>u>>v; g[u].push_back(v); g[v].push_back(u); } for(int u = 1;u <= n;u++){ if(!belong[u]){ dfs(u,1,++tot); if(ood)return printf("-1"),0; } } for(int u = 1;u <= n;u++) mx[gcc[u]] = max(mx[gcc[u]],bfs(u)); for(int i = 1;i <= tot;i++) ans += mx[i]; cout<<ans; return 0; }
- 1
信息
- ID
- 2674
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 54
- 已通过
- 6
- 上传者