NOIP2002提高组

2002提高
A.均分纸牌(贪心)
B.字串变换(字符串哈希+bfs+剪枝)

A

#include 
using namespace std;
#define ll long long
#define N 110
#define inf 0x3f3f3f3f
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,a[N],sum=0,ans=0;
int main(){
//  freopen("a.in","r",stdin);
    n=read();for(int i=1;i<=n;++i) a[i]=read(),sum+=a[i];sum/=n;
    for(int i=1;i<=n;++i){
        a[i]-=sum;if(!a[i]) continue;
        a[i+1]+=a[i];ans++;
    }printf("%d\n",ans);
    return 0;
}

B

#include 
using namespace std;
#define ll long long
#define N 500
#define pa pair
#define inf 0x3f3f3f3f
int const mod=1e9+7;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n=0,ans=0,base[25],ed=0;
char a[7][N],b[7][N],t[N];
map<int,int>mp;
struct str{
    char s[N];str(){memset(s,0,sizeof(s));};
}s;
inline int hash(char *x){
    int len=strlen(x),res=0;
    for(int i=0;i'0')*base[i])%mod;
    return res;
}
inline bool same(char *x,char *y,int l){
    for(int i=0;iif(x[i]!=y[i]) return 0;return 1;
}
inline bool contain(char *x,char *y){
    int l1=strlen(x+1),l2=strlen(y+1);
    for(int i=1;i+l2-1<=l1;++i)
        if(same(x+i,y+1,l2)) return 1;return 0;
}
bool bfs(){
    queueq;q.push(make_pair(s,0));mp[hash(s.s+1)]=1;
    while(!q.empty()){
        str x=q.front().first;int cnt=q.front().second;q.pop();
        if(cnt>10) return 0;
        for(int i=1;i<=n;++i){
            int l1=strlen(x.s+1),l2=strlen(a[i]+1);
            for(int st=1;st+l2-1<=l1;++st)
                if(same(x.s+st,a[i]+1,l2)){
                    str y;int len=0,l3=strlen(b[i]+1);
                    for(int j=1;jfor(int j=1;j<=l3;++j) y.s[++len]=b[i][j];
                    for(int j=st+l2;j<=l1;++j) y.s[++len]=x.s[j];
                    int xx=hash(y.s+1);
                    if(mp[xx]) continue;mp[xx]=1;if(xx==ed) return ans=cnt+1;
                    q.push(make_pair(y,cnt+1));
                }
        }
    }
}
int main(){
//  freopen("testdata.in","r",stdin);
    base[0]=1;for(int i=1;i<=20;++i) base[i]=(ll)base[i-1]*131%mod;
    scanf("%s%s",s.s+1,t+1);ed=hash(t+1);
    while(~scanf("%s%s",a[n]+1,b[++n]+1));--n;
    if(!bfs()) puts("NO ANSWER!");
    else printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(其他oj,贪心,比赛,Hash)