题目连接:http://acm.pku.edu.cn/JudgeOnline/problem?id=2762
这是到水题,1A就过了。。。简单拓扑+dp就过了。。。。。和pku 3249及其相似,只是3249要注意数值的初始化,因为其可以为负数,。。
pku 2762代码:
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int MAX1=10005; struct Graph { int id; int next; }; Graph G[MAX1*100]; int in[MAX1]; int out[MAX1]; int tp[MAX1]; int value[MAX1]; int record[MAX1]; int n,G_end,cnt; void init() { memset(G,0,sizeof(G)); memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); memset(record,0,sizeof(record)); } void Bulid(int s,int e) { int p=s; while(G[p].next) p=G[p].next; G[G_end].id=e; G[p].next=G_end; G_end++; } void Topsort() { for(int i=1;i<=n;i++) if(in[i]==0) record[i]=value[i]; for(int i=1;i<=n;i++) if(in[i]==0) { tp[cnt++]=i; in[i]=-1; } int fist=0; for(int k=1;k<=n;k++) { int p,q; p=G[tp[fist++]].next; while(p) { q=G[p].id; in[q]--; if(in[q]==0) { tp[cnt++]=q; in[q]=-1; } p=G[p].next; } } } void dp() { for(int i=0;i<cnt;i++) { int p,q; p=G[tp[i]].next; while(p) { q=G[p].id; if(record[q]<value[q]+record[tp[i]]) record[q]=value[q]+record[tp[i]]; p=G[p].next; } } } int main() { while(scanf("%d",&n)!=EOF) { G_end=n+2; int num,y; init(); for(int i=1;i<=n;i++) { scanf("%d %d",&value[i],&num); for(int j=0;j<num;j++) { scanf("%d",&y); Bulid(y,i); in[i]++; out[y]++; } } Topsort(); dp(); int ans=0; for(int i=1;i<=n;i++) if(out[i]==0&&ans<record[i])ans=record[i]; printf("%d/n",ans); } return 0; }
pku 3249
代码:
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int MAX1=100004; const int MAX2=1000008; const int inf=2000000001; struct Gragh { int id; int next; }; Gragh GA[MAX1+MAX2]; int cnt[MAX1]; int out[MAX1]; int value[MAX1]; int record[MAX1]; int Tsot[MAX1]; int n,m,G_end,k,Max; void init() { k=1,Max=-inf; memset(cnt,0,sizeof(cnt)); memset(out,0,sizeof(out)); memset(GA,0,sizeof(GA)); } void Bulid(int s,int e) { int p=s; while(GA[p].next) p=GA[p].next; GA[G_end].id=e; GA[p].next=G_end; G_end++; } bool Topsort() { int top=-1; for(int i=1;i<=n;i++) if(cnt[i]==0) { record[i]=value[i]; cnt[i]=top; top=i; } for(int i=1;i<=n;i++) { if(top==-1) return false; int j=top; top=cnt[top]; Tsot[k++]=j; int p,q; p=GA[j].next; while(p) { q=GA[p].id; if(--cnt[q]==0) { cnt[q]=top; top=q; } p=GA[p].next; } } } void dp() { for(int i=1;i<=n;i++) { int temp=Tsot[i]; int p,q; p=GA[temp].next; while(p) { q=GA[p].id; if(record[temp]+value[q]>record[q]) record[q]=record[temp]+value[q]; p=GA[p].next; } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { G_end=n+1; init(); for(int i=1;i<=n;i++) { scanf("%d",&value[i]); record[i]=-inf; } int s,e; for(int i=0;i<m;i++) { scanf("%d%d",&s,&e); Bulid(s,e); cnt[e]++; out[s]++; } Topsort(); dp(); for(int i=1;i<=n;i++) if(out[i]==0) Max=max(Max,record[i]); printf("%d/n",Max); } return 0; }