题目链接:http://poj.org/problem?id=3249
题目大意:给出n个点,m条边,每个点都提供了相对的点权值,然后给出相连着的边,问从起点走到终点最大利润值。起点是入度为0的点,终点是出度为0的点。
思路1:SPFA求最长路,正向建边TLE,反向建边4400msAC。。。。
2:记忆化搜索,每次都保存当前点到终点获得的最大利润。
AC代码,搜索 ....1844ms:
#include<set>
#include<stack>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100100;
const int inf = 0x3f3f3f3f3f;
int head[maxn];
int v[maxn];
int son[maxn];
struct node{
int v,next;
node() {}
node(int v,int next):v(v),next(next) {}
}edge[maxn*10];
int maxx = -inf;
int depth[maxn];
int dfs(int st){
if(head[st] == -1) return depth[st] = v[st];
if(depth[st]) return depth[st];
int ans = -inf;
for(int i = head[st];i != -1;i = edge[i].next)
ans = max(ans,dfs(edge[i].v) + v[st]);
return depth[st] = ans;
}
int main() {
int n,m;
while(~scanf("%d%d",&n,&m)){
memset(head,-1,sizeof(head));
memset(son,0,sizeof(son));
memset(depth,0,sizeof(depth));
maxx = -inf;
int a,b; int cnt = 0;
for(int i = 1;i <= n;i ++)
scanf("%d",&v[i]);
for(int i = 0;i < m;i ++){
scanf("%d%d",&a,&b);
son[b] = 1;
edge[cnt] = node(b,head[a]);
head[a] = cnt ++;
}
for(int i = 1;i <= n;i ++)
if(son[i] == 0) dfs(i);
for(int i = 1;i <= n;i ++)
if(son[i] == 0 && depth[i] > maxx)
maxx = depth[i];
printf("%d\n",maxx);
}
return 0;
}
SPFA 最长路...4400ms:
#include<set>
#include<stack>
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100100;
const int inf = 0x3f3f3f3f;
int head[maxn];
int v[maxn];
int dis[maxn];
int son[maxn];
int vis[maxn];
struct node{
int v,next;
int w;
node() {}
node(int v,int next,int w):v(v),next(next),w(w) {}
}edge[maxn*10];
int maxx = -inf;
int main() {
int n,m;
while(~scanf("%d%d",&n,&m)){
for(int i = 0;i < maxn;i ++){
head[i] = -1;
son[i] = vis[i] = 0;
dis[i] = -inf;
}
maxx = -inf;
int a,b; int cnt = 0;
for(int i = 1;i <= n;i ++)
scanf("%d",&v[i]);
for(int i = 0;i < m;i ++){
scanf("%d%d",&a,&b);
son[a] = 1;
edge[cnt] = node(a,head[b],v[a]);
head[b] = cnt ++;
}
queue<int>Q;
for(int i = 1;i <= n;i ++)
if(son[i] == 0){
printf("%d\n",i);
dis[i] = v[i];
vis[i] = 1;
Q.push(i);
}
while(!Q.empty()){
int now = Q.front();
Q.pop(); vis[now] = 0;
for(int i = head[now];i != -1;i = edge[i].next){
int v = edge[i].v;
if(dis[v] < dis[now] + edge[i].w){
dis[v] = dis[now] + edge[i].w;
if(!vis[v]){
vis[v] = 1;
Q.push(v);
}
}
}
}
for(int i = 1;i <= n;i ++)
if(head[i] == -1 && dis[i] > maxx)
maxx = dis[i];
printf("%d\n",maxx);
}
return 0;
}