uva 10817 Headmaster's Headache

状态压缩 384ms ac

#include <iostream>

#include<cstdio>

#include<cstring>

#include<cctype>

#define INF 0x3f3f3f3f

#define N (1<<16)+5

using namespace std;

bool vis[N][105];

int dp[N][105];

int s,m,n,st,T;

int v[105],lesson[105][20];

int DP(int st,int i)

{

    if(vis[st][i])

    return dp[st][i];

    vis[st][i]=true;



    if(st==T)

    return dp[st][i]=0;

    if(i==n)

    return INF;

    int next=st,&top=lesson[i][0];

    for(int j=1;j<top;j++)

    {

        int y=lesson[i][j];

        if((1<<(s+y))&next)

        continue;

        if((1<<y)&next)

        next=next-(1<<y)+(1<<(s+y));

        else

        next=next+(1<<y);

    }

    if(next!=st)

    dp[st][i]=min(dp[st][i],DP(next,i+1)+v[i]);

    dp[st][i]=min(dp[st][i],DP(st,i+1));

    return dp[st][i];

}

int main()

{

    while(scanf("%d%d%d",&s,&m,&n),s+m+n)

    {

        int ans=0;

        st=0;

        char t[100];

        memset(vis,false,sizeof(vis));

        memset(dp,INF,sizeof(dp));

        for(int i=0;i<m;i++)

        {

            int x,y;

            scanf("%d",&x);

            ans+=x;

            gets(t);

            int k=strlen(t);

            for(int j=0;j<k;j++)

            {

                sscanf(t+j,"%d",&y);

                y--;

                for(;isdigit(t[j]);++j);

                ++j;

                if(1<<(s+y)&st)

                continue;

                if(1<<y&st)

                st=st-(1<<y)+(1<<(s+y));

                else

                st=st+(1<<y);

            }

        }

        for(int i=0;i<n;i++)

        {

            int x,y;

            scanf("%d",&v[i]);

            int &top=lesson[i][0]=1;

            gets(t);

            int k=strlen(t);

            for(int j=0;j<k;j++)

            {

                sscanf(t+j,"%d",&lesson[i][top++]);

                lesson[i][top-1]--;

                for(;isdigit(t[j]);++j);

                ++j;

            }

        }

        T=0;

        for(int i=s;i<2*s;i++)

        T+=(1<<i);

        printf("%d\n",ans+DP(st,0));

    }

    return 0;

}

  

你可能感兴趣的:(master)