• jzoj 6838. 2020.10.31【NOIP提高A组】T4 小j 的组合


    考虑将操作转变为每个点可经过次数(+1),设每个点可经过次数为(e[i]),那答案即为(sum (e[i]-1))
    当每个点的可经过次数等于该点度数的时候,才应当是最优解。
    我们可以通过求直径,然后从直径一端开始跑,先跑非直径边后直接走直径,这样最优。
    由于每条非直径的边走完以后还要返回到父亲节点,所以答案(g)即为(n-直径节点个数)

    #include <cstdio>
    #define N 210
    #define db double
    #define ll long long
    #define mem(x, a) memset(x, a, sizeof x)
    #define mpy(x, y) memcpy(x, y, sizeof y)
    #define fo(x, a, b) for (int x = (a); x <= (b); x++)
    #define fd(x, a, b) for (int x = (a); x >= (b); x--)
    #define go(x) for (int p = tail[x], v; p; p = e[p].fr)
    using namespace std;
    struct node{int v, fr;}e[N << 1];
    int n, tail[N], cnt = 0, fd = 0, rt, mln = 0;
    int p_[N << 2], tot = 0, num, u[N], cz = 0, fa[N];
    
    inline int read() {
    	int x = 0, f = 0; char c = getchar();
    	while (c < '0' || c > '9') f = (c == '-') ? 1 : f, c = getchar();
    	while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    	return f ? -x : x;
    }
    
    inline void add(int u, int v) {e[++cnt] = (node){v, tail[u]}; tail[u] = cnt;}
    
    void dfs(int x, int len, int fat) {
    	if (len > mln) mln = len, fd = x;
    	go(x) {
    		if ((v = e[p].v) == fat) continue;
    		fa[v] = x, dfs(v, len + 1, x);
    	}
    }
    
    void solve(int x, int fro) {
    	p_[++tot] = x;
    	go(x) {
    		if ((v = e[p].v) == fro || v == fa[x]) continue;
    		solve(v, x), p_[++tot] = ++num, u[++cz] = x;
    	}
    	if (fa[x] && fa[x] != fro) solve(fa[x], x);
    }
    
    int main()
    {
    	freopen("combo.in", "r", stdin);
    	freopen("combo.out", "w", stdout);
    	n = read();
    	fo(i, 2, n) {
    		int u = read(), v = read();
    		add(u, v), add(v, u);
    	}
    	dfs(1, 1, 0), rt = fd;
    	mln = fd = 0, fa[rt] = 0;
    	dfs(rt, 1, 0);
    	printf("%d
    ", n - mln);
    	num = n, solve(fd, 0);
    	fo(i, 1, cz) printf("%d ", u[i]);
    	printf("
    ");
    	fo(i, 1, tot) printf("%d ", p_[i]);
    	return 0;
    }
    
  • 相关阅读:
    【LeetCode】006 ZigZag Conversion
    【LeetCode】009 Palindrome Number
    【LeetCode】008 String to Integer (atoi)
    【LeetCode】012 013 Roman Integer
    react-native 入门资源合集
    Thread和ExecutorService(一)
    DrawerLayout、CoordinatorLayout、CollapsingToolbarLayout的使用--AndroidSupportDesign练手
    Valid Number
    When Is Cheryl's Birthday
    【笔试】——常用运算符
  • 原文地址:https://www.cnblogs.com/jz929/p/13908540.html
Copyright © 2020-2023  润新知