[最长路][二分图]Codeforces 542 E. Playing on Graph

12 篇文章 0 订阅
8 篇文章 0 订阅

Solution

如果图中存在奇环,那么这个奇环缩了以后还是会产生一个奇环,最后一定会缩到一个三元环,显然无解。
所以说合法的图一定是一个二分图。
对于从某一点开始的链,把距离它距离相同的点可以缩起来,因为这些点肯定在二分图的某一部,是没有边相邻的。所以答案就是每个联通块的直径长度的和。
跑最长路就好了

#include <bits/stdc++.h>
using namespace std;

const int N = 1010;
const int M = 101010;

inline char get(void) {
    static char buf[100000], *S = buf, *T = buf;
    if (S == T) {
        T = (S = buf) + fread(buf, 1, 100000, stdin);
        if (S == T) return EOF;
    }
    return *S++;
}
template<typename T>
inline void read(T &x) {
    static char c; x = 0; int sgn = 0;
    for (c = get(); c < '0' || c > '9'; c = get()) if (c == '-') sgn = 1;
    for (; c >= '0' && c <= '9'; c = get()) x = x * 10 + c - '0';
    if (sgn) x = -x;
}

int n, m, Gcnt, clc, ans, x, y, cnt;
struct edge {
    int to, next;
    edge(int t = 0, int n = 0):to(t), next(n) {}
};
edge G[M << 1];
int head[N], vis[N], pre[N], dep[N], col[N], dis[N];
queue<int> Q;

inline void AddEdge(int from, int to) {
    G[++Gcnt] = edge(to, head[from]); head[from] = Gcnt;
    G[++Gcnt] = edge(from, head[to]); head[to] = Gcnt;
}
inline void dfs(int u, int d) {
    col[u] = cnt; pre[u] = ++clc; dep[u] = d;
    for (int i = head[u]; i; i = G[i].next) {
        if (!pre[G[i].to]) dfs(G[i].to, d ^ 1);
        else if (pre[G[i].to] < pre[u] && (dep[u] ^ dep[G[i].to] ^ 1)) ans = -1;
    }
}
inline int dia(int u) {
    Q.push(u); vis[u] = ++clc; pre[u] = 0;
    while (!Q.empty()) {
        u = Q.front(); Q.pop();
        for (int i = head[u]; i; i = G[i].next)
            if (vis[G[i].to] != clc) {
                pre[G[i].to] = pre[u] + 1;
                vis[G[i].to] = clc; Q.push(G[i].to);
            }
    }
    return pre[u];
}

int main(void) {
    freopen("1.in", "r", stdin);
    freopen("1.out", "w", stdout);
    read(n); read(m);
    for (int i = 1; i <= m; i++) {
        read(x); read(y);
        AddEdge(x, y);
    }
    for (int i = 1; i <= n; i++)
        if (!pre[i]) ++cnt, dfs(i, 0);
    clc = 0;
    if (~ans)
        for (int i = 1; i <= n; i++)
            dis[col[i]] = max(dia(i), dis[col[i]]);
    for (int i = 1; i <= cnt; i++) ans += dis[i];
    printf("%d\n", ans);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值