这是一个不加回溯就无法ac的代码

P2731 [USACO3.3] 骑马修栅栏 Riding the Fences

zhaoyifan @ 2017-10-28 10:37:55

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iomanip>
using namespace std;
int m,du[1001],d[1001][1001],minn=10000,maxx=-1,lu[10001],rt=1e9,re=0;
void write()
{
    for(int i=0;i<=m;++i)
    {
        if(lu[i]>=26) printf("%c",'a'+lu[i]-26);
        else printf("%c",'A'+lu[i]);
    }
    exit(0);
}
void dfs(int x,int num)
{
    if(num==m) 
    {
        write();
    }
    for(int i=minn;i<=maxx;++i)
    {
        if(d[x][i]<=0) continue;
        d[x][i]--;d[i][x]--;lu[num+1]=i;
        dfs(i,num+1);
        d[x][i]++;d[i][x]++;
    }
}
int main()
{
    cin>>m;
    for(int i=1;i<=m;++i)
    {
        string s;cin>>s;int x,y;
        if(s[0]>='a') x=s[0]-'a'+26;
        else x=s[0]-'A';
        if(s[1]>='a') y=s[1]-'a'+26;
        else y=s[1]-'A';
        du[x]++;du[y]++;d[x][y]++;d[y][x]++;
        maxx=max(maxx,max(x,y));minn=min(minn,min(x,y));
    }
    for(int i=minn;i<=maxx;++i)
    if(du[i]%2!=0)
    {
        rt=min(rt,i);re++;
    }
    if(re!=0&&re!=2) 
    {
        cout<<"No Solution";return 0;
    }
    if(re==0) rt=minn;lu[0]=rt;
    dfs(rt,0);
    return 0;
}

by zhaoyifan @ 2017-10-28 10:40:42

哦,明白了,那个地方只要有字符串相同就全部满足

就是那个d[x][i]--;d[i][x]--;直接变为0即可


by chlchl @ 2022-07-26 21:45:37

咱说的是一个题不?这个题输出的不是数字么……


|