标签:string amp scan eof vector while names com ack
图论的思维题,太秀了,网上答案也不多,我就也来bb吧
总之47个样例姑且是过了,不知道还有没有反例;
会求树的重心和中心了,挺好
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<vector> #include<queue> using namespace std; #define maxn 100110 vector<int>G[maxn]; vector<int>an; void insert(int be, int en) { G[be].push_back(en); G[en].push_back(be); } int root; int n; int in[maxn]; int de[maxn]; queue<int>que; int find_root() { while (!que.empty()) { int x = que.front(); que.pop(); for (int i = 0; i < G[x].size(); i++){ int p = G[x][i]; in[p]--; if (in[p] == 1) { que.push(p); root = p; } } } return 0; } int cnt[maxn]; int flag = 0; int jude(int x, int fa, int dep) {//这个点搜下去,是否符合条件 if (cnt[dep] == 0) { cnt[dep] = de[x]; } else { if (cnt[dep] != de[x]) { flag = 1; return 0; } } for (int i = 0; i < G[x].size(); i++) { int p = G[x][i]; if (p == fa) continue; jude(p, x, dep + 1); } return 0; } int find_point(int x,int fa,int dep) { if (cnt[dep] == 0 && de[x] == 1) { cnt[dep] = 1; an.push_back(x); } for (int i = 0; i < G[x].size(); i++) { int p = G[x][i]; if (p == fa) continue; if (de[p] == 2 || de[p] == 1) { find_point(p, x, dep + 1); } } return 0; } int main() { int be, en; scanf("%d", &n); for (int i = 1; i < n; i++) { scanf("%d %d", &be, &en); insert(be, en); de[be]++; de[en]++; in[be]++; in[en]++; } if (n == 1 || n == 2) { printf("1\n"); return 0; } for (int i = 1; i <= n; i++) { if (in[i] == 1) { in[i] = 0; que.push(i); } } /*if (n == 1 || n == 2) { printf("1\n"); return 0; }*/ find_root(); memset(cnt, 0, sizeof(cnt)); find_point(root, root, 1); memset(cnt, 0, sizeof(cnt)); flag = 0; jude(root, root, 1); if (!flag) { printf("%d\n", root); return 0; } for (int i = 0; i < an.size(); i++) { memset(cnt, 0, sizeof(cnt)); flag = 0; jude(an[i], an[i], 1); if (!flag) { printf("%d\n", an[i]); return 0; } } printf("-1\n"); return 0; }
标签:string amp scan eof vector while names com ack
原文地址:https://www.cnblogs.com/lesning/p/11524685.html