HDU6380 degree

tarjan缩点

正解似乎是并查集,但是这题可以用tarjan乱搞来着。。

缩完点之后,不再同一个强连通分量的点可以直接连边,连到度数最多的点所在的联通块,然后只要把与这个点不相邻的k条边删了,再直接连到这个度数最多的点上就好了。

这里要判断一下加起来是否大于最大度数n-1,因为当所有点都和已经和度数最大的点相连后,已经没有电可以删了,而我们多加了k度,所以这个时候直接输出n-1,反之只要有一个点的不直接和该店相连,那度数就不会超过n-1。

我们这样加起来以后,如果有k个点不相邻,那答案必然小于等于n-1,但是如果不足k个点,答案就一定是n-1

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
#define FAST_IO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int ret = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) ret = (ret << 3) + (ret << 1) + (ch ^ 48), ch = getchar();
    return w ? -ret : ret;
}
inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template <typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template <typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template <typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}
const int N = 300005;
int _, n, m, k, cnt, head[N], dfn[N], low[N], tot, x, d[N], ind;
bool ins[N];
stack<int> st;
struct Edge { int v, next; } edge[N<<1];
void addEdge(int a, int b){
    edge[cnt].v = b, edge[cnt].next = head[a], head[a] = cnt ++;
}

void build(){
    cnt = x = ind = tot = 0;
    full(head, -1), full(dfn, 0), full(low, 0);
    full(d, 0), full(ins, false);
}

void tarjan(int s){
    dfn[s] = low[s] = ++x;
    ins[s] = true, st.push(s);
    for(int i = head[s]; i != -1; i = edge[i].next){
        int u = edge[i].v;
        if(!dfn[u]){
            tarjan(u);
            low[s] = min(low[s], low[u]);
        }
        else if(ins[u]) low[s] = min(low[s], dfn[u]);
    }
    if(dfn[s] == low[s]){
        ++tot;
        int cur;
        do{
            cur = st.top(); st.pop();
            ins[cur] = false;
        }while(cur != s);
    }
}

int main(){

    for(_ = read(); _; _ --){
        build();
        n = read(), m = read(), k = read();
        for(int i = 0; i < m; i ++){
            int u = read(), v = read();
            d[u] ++, d[v] ++;
            addEdge(u, v), addEdge(v, u);
        }
        for(int i = 0; i < n; i ++){
            if(!dfn[i]) tarjan(i);
            ind = max(ind, d[i]);
        }
        int ans = ind + tot - 1 + k;
        printf("%d
", ans > n - 1 ? n - 1 : ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/onionQAQ/p/11196996.html