码迷,mamicode.com
首页 > 其他好文 > 详细

PAT T1021 Safe Fruit

时间:2020-02-13 13:09:45      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:scan   pac   amp   bit   搜索   sort   safe   rect   turn   

暴力搜索加剪枝~

#include<bits/stdc++.h>
using namespace std;
const int maxn=1014;
const int inf=1e9;
int g[maxn][maxn];
int c[maxn];
int N,M;
int mincost=1e9;
int cost=0;
int flag;
int tle=0;
int ans=0;
bool visit[maxn];
vector<int> path,tmp;
void dfs (int v,int direction) {
    tle++;
    if (tle>1e5) return;
    if (tmp.size()>path.size()) {
        path=tmp;
        mincost=cost;
    }
    else if (tmp.size()==path.size()&&cost<mincost) {
        path=tmp;
        mincost=cost;
    }
    if (direction==1) {
        v++;
        while (v<=1000) {
            flag=0;
            if (c[v]==0) {
                v++;
                continue;
            }
                for (int j=0;j<tmp.size();j++) 
                if (g[v][tmp[j]]==1) {
                    flag++;
                    break;
                }
            if (flag==0) {
                tmp.push_back(v);
                visit[v]=true;
                cost+=c[v];
                dfs (v,1);
                tmp.pop_back();
                visit[v]=false;
                cost-=c[v];
            }
            v++;
        }
    }
    else {
        v--;
        while (v>=0) {
            flag=0;
            if (c[v]==0) {
                v--;
                continue;
            }
            for (int j=0;j<tmp.size();j++) 
            if (g[v][tmp[j]]==1) {
                flag++;
                break;
            }
            if (flag==0) {
                tmp.push_back(v);
                visit[v]=true;
                cost+=c[v];
                dfs (v,0);
                tmp.pop_back();
                visit[v]=false;
                cost-=c[v];
            }
            v--;
        }
    }
}
int main () {
    scanf ("%d %d",&M,&N);
    int u,v;
    for (int i=0;i<M;i++) 
    scanf ("%d %d",&u,&v),g[u][v]=g[v][u]=1;
    for (int i=1;i<=N;i++) {
        scanf ("%d %d",&u,&v);
        c[u]=v;
        if (v>999) ans++;
    }
    if (ans!=0) dfs (0,1);
    else dfs (1000,0);
    printf ("%d\n",path.size());
    sort (path.begin(),path.end());
    for (int i=0;i<path.size();i++) {
        if (i!=0) printf (" ");
        printf ("%03d",path[i]);
    }
    printf ("\n%d",mincost);
    return 0;
}

 

PAT T1021 Safe Fruit

标签:scan   pac   amp   bit   搜索   sort   safe   rect   turn   

原文地址:https://www.cnblogs.com/zhanglichen/p/12303022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!