2020.01.19【NOIP提高组】模拟B 组——总结——钻石交易

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

Sample Input

4 5 2 7 1
0 0
10 0
0 8
100 10
1 2 5
1 3 10
1 4 8
2 3 4
2 4 6

Sample Output

16
【样例说明】
最优方案为:先从城市1到城市2,在城市2卖掉第一颗钻石,然后到城市4,卖掉第二颗钻石并结束旅行。

Data Constraint

在这里插入图片描述

思路

状压dp+spfa,但是会炸,所以考虑优化:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int t,n,m,k,s,x,y,z,ans,cnt;
int a[1507][1507],head[4007],next[4007],last[4007],cost[4007],f[1507][1507],d[1507];
bool vis[1507];
queue<int>q;
void add(int x,int y,int z){
    last[++cnt]=y;
	cost[cnt]=z;
	next[cnt]=head[x];
	head[x]=cnt;
}
void spfa(int state){
    int x;
    vis[s]=1;
	for(int i=1;i<=n;i++)
		d[i]=f[i][state],q.push(i);
    while(!q.empty()){
        x=q.front();
        for(int i=head[x];i;i=next[i]){
            if(d[x]-cost[i]>=d[last[i]]){
                d[last[i]]=d[x]-cost[i];
                if(!vis[last[i]]){
                    vis[last[i]]=1;
                   	q.push(last[i]);
                }
            }
        }
        q.pop();
        vis[x]=0;
    }
    for(int i=1;i<=m;i++){
        if(state&(1<<(i-1)))continue;
        for(int j=1;j<=n;j++)
			if(d[j]>=0)f[j][state|(1<<(i-1))]=max(f[j][state|(1<<(i-1))],d[j]+a[j][i]);
    }
}
int main(){
    scanf("%d%d%d%d%d",&n,&t,&m,&k,&s);
    for(int i=1;i<=n;i++)
	for(int j=1;j<=m;j++)
		scanf("%d",&a[i][j]);
    for(int i=1;i<=t;i++)
		scanf("%d%d%d",&x,&y,&z),add(x,y,z);
    memset(f,128,sizeof(f));
    f[s][0]=k;
    for(int j=0;j<=(1<<m)-1;j++)
		spfa(j);
    for(int i=1;i<=n;i++)
	for(int j=0;j<=(1<<m)-1;j++)
		ans=max(ans,f[i][j]);
    printf("%d\n",ans);
}
发布了16 篇原创文章 · 获赞 2 · 访问量 1520

猜你喜欢

转载自blog.csdn.net/jay_zai/article/details/104042584
今日推荐