POJ 3107 Godfather 树状DP

来源:互联网 发布:tensorflow mnist例子 编辑:程序博客网 时间:2024/05/17 04:45

这题其实就是一个简单的树状DP,但是最扯的是它居然要卡STL,超时超到哭啊,只能用链表了。

#include <cstdio>#include <cstring>#include <string>#include <iostream>#include <queue>#include <algorithm>#include <map>#include <vector>#include <cmath>#include <stack>using namespace std;#define ll long long#define int64 __int64#define M 100005#define N 1005#define inf 1000010#define mod 1000000007struct node{int sum_son;int max_son;int pos;}tp[M];struct Node{int ev , next;}tree[M];int n , head[M] , tot;void Addedge(int s , int e){tree[tot].ev = e;tree[tot].next = head[s];head[s] = tot++;}void Dfs(int s , int fa){tp[s].max_son = 0;tp[s].sum_son = 1;tp[s].pos = s;int i;for (i = head[s] ; i != -1 ; i = tree[i].next){int v = tree[i].ev;if (v == fa)continue;Dfs(v,s);tp[s].max_son = max(tp[s].max_son , tp[v].sum_son);tp[s].sum_son += tp[v].sum_son;}tp[s].max_son = max(tp[s].max_son , n-tp[s].sum_son);}bool cmp(node a , node b){if (a.max_son < b.max_son)return true;if (a.max_son > b.max_son)return false;if (a.pos < b.pos)return true;return false;}int main(){while (~scanf("%d",&n)){int i;tot = 0;memset(head , -1 , sizeof head);for (i = 1 ; i < n ; i++){int s , e;scanf("%d%d",&s,&e);Addedge(s,e);Addedge(e,s);}Dfs(1,0);sort(tp+1 , tp+n+1 , cmp);printf("%d",tp[1].pos);i = 2;while (i <= n && tp[i].max_son == tp[1].max_son)printf(" %d",tp[i++].pos);printf("\n");}return 0;}