Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5954 Accepted Submission(s): 2705
7 1 1 1 1 1 1 1 1 3 2 3 6 4 7 4 4 5 3 5 0 0
5
#include<stdio.h> #include<string.h> #include<vector> #define MAX 6000+10 using namespace std; int max(int x,int y) { return x>y?x:y; } int dp[MAX][2],vis[MAX]; vector<int>tree[MAX];//存储子节点 void dfs(int node) { vis[node]=1; int i,j; int son;//子节点 for(i=0;i<tree[node].size();i++) { son=tree[node][i]; if(!vis[son]) { dfs(son); dp[node][1]+=dp[son][0];//上司去 下属不去 dp[node][0]+=max(dp[son][1],dp[son][0]); // 上司不去 下属去或不去 } } } int main() { int n,i; int root;//根节点 int x,y; while(scanf("%d",&n)!=EOF) { for(i=1;i<=n;i++) { scanf("%d",&dp[i][1]); dp[i][0]=0; vis[i]=1; tree[i].clear();//清空 } while(scanf("%d%d",&x,&y)&&(x!=0||y!=0)) { vis[x]=0;//x为下属 标记一下 tree[y].push_back(x);//建立关系 } root=0; for(i=1;i<=n;i++)//查询根节点 { if(vis[i]) { root=i;//记录根节点 break; } } memset(vis,0,sizeof(vis)); dfs(root); printf("%d\n",max(dp[root][0],dp[root][1])); } return 0; }
#include <cstdio> #include <cstring> #include <vector> #include <algorithm> #define MAXN 6000+10 using namespace std; vector<int> G[MAXN]; int dp[MAXN][2]; int pre[MAXN]; int N; int find(int p) { int t; int child = p; while(child != p) p = pre[p]; while(child != p) { t = pre[child]; pre[child] = p; child = t; } return p; } void merge(int x, int y) { int fx = find(x); int fy = find(y); if(fx != fy) pre[fx] = fy; } void DFS(int u) { for(int i = 0; i < G[u].size(); i++) { int v = G[u][i]; DFS(v); dp[u][1] += dp[v][0]; dp[u][0] += max(dp[v][1], dp[v][0]); } } int main() { while(scanf("%d", &N) != EOF) { int a, b, root; for(int i = 1; i <= N; i++) { scanf("%d", &a); dp[i][1] = a;//i去 dp[i][0] = 0;//i不去 pre[i] = i; G[i].clear(); } while(scanf("%d%d", &a, &b), a||b) G[b].push_back(a), pre[a] = b; for(int i = 1; i <= N; i++) { if(pre[i] == i) root = i; } DFS(root); printf("%d\n", max(dp[root][0], dp[root][1])); } return 0; }