【codeforces 723F】stSpanning Tree

【题目链接】:http://codeforces.com/contest/723/problem/F

【题意】

给你一张图;
让你选择n-1条边;
使得这张图成为一颗树(生成树);
同时s的度数不超过ds且t的度数不超过dt

【题解】

先把s和t隔离开;
考虑其他点形成的若干个联通块;
因为一开始的图是联通的;
所以,那些不同的联通块,肯定是通过s或通过t而联通的;
这样就只要考虑每个联通块和s、t的联通性了;
对于只能和s或t之中的一个相连的块;
直接连一条边到s或t就好,然后ds-=1或是dt-=1(取决与它在原图上只和哪一点相连);
最后处理能和s以及t同时相连的块;
这时s和t还是未联通的!
则一开始先找到一个块;
让s和t变成联通的
即s->连通块sp->t
然后ds-=1,dt-=1
之后,
根据ds和dt;
哪一个不为0就把那个联通块连到哪一个点;
(这种先把要讨论的点隔开的方式值得借鉴)

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int, int> pii;
typedef pair<LL, LL> pll;

const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
const double pi = acos(-1.0);
const int N = 2e5+100;

int n, m,s,t,ds,dt,cnt,vis[N],com;
vector <int> G[N],S[N],T[N];
vector <pii> ans;

void dfs(int x)
{
    vis[x] = 1;
    for (int y : G[x])
    {
        if (y == s)
            S[cnt].push_back(x);
        else
            if (y == t)
                T[cnt].push_back(x);
            else
                if (!vis[y])
                {
                    dfs(y);
                    ans.push_back(mp(x, y));
                }
    }
}

int main()
{
    //freopen("F:\\rush.txt", "r", stdin);
    ios::sync_with_stdio(false), cin.tie(0);//scanf,puts,printf not use
    cin >> n >> m;
    rep1(i, 1, m)
    {
        int x, y;
        cin >> x >> y;
        G[x].pb(y), G[y].pb(x);
    }
    cin >> s >> t >> ds >> dt;
    rep1(i, 1, n)
        if (!vis[i] && i != s && i != t)
        {
            cnt++;
            dfs(i);
        }
    rep1(i, 1, cnt)
        if (S[i].empty())
            ans.push_back(mp(T[i][0], t)), dt--;
        else
            if (T[i].empty())
                ans.push_back(mp(S[i][0], s)), ds--;
            else
                com++;
    if (ds <= 0 || dt <= 0 || ds + dt < com + 1)
        return cout << "No" << endl, 0;
    if (!com)
        ans.push_back(mp(s, t));
    else
    {
        int lj = 0;
        rep1(i,1,cnt)
            if (!S[i].empty() && !T[i].empty())
            {
                if (!lj)
                {
                    ds--, dt--;
                    lj = 1;
                    ans.push_back(mp(S[i][0], s));
                    ans.push_back(mp(T[i][0], t));
                }
                else
                {
                    if (ds)
                        ans.push_back(mp(S[i][0], s)),ds--;
                    else
                        ans.push_back(mp(T[i][0], t)),dt--;
                }
            }
    }
    cout << "Yes" << endl;
    rep1(i, 0, n - 2)
        cout << ans[i].first << ' ' << ans[i].second << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626336.html