HOUSE MAN

来源:互联网 发布:亚马逊a9算法 2017 编辑:程序博客网 时间:2024/06/18 04:35
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

const int MAXN=1100;
const int MAXM=MAXN*MAXN;
const int INF=0x7fffffff;

int head[MAXN],dist[MAXN],vis[MAXN],o[MAXN],id;

struct e
{
    int to;
    int w;
    int next;
}e[MAXM];

struct House
{
    int high;
    int no;
}arr[MAXN];

bool cmp(struct House a,struct House b)
{
    return a.high<b.high;
}

void add(int u,int v,int w)
{
    e[id].to=v;
    e[id].w=w;
    e[id].next=head[u];
    head[u]=id++;
}

int spfa(int s,int t,int n)
{
    memset(vis,0,sizeof(vis));
    memset(o,0,sizeof(o));
    for (int i=0;i<=n;i++) dist[i]=INF;
    dist[s]=0;
    vis[s]=1;
    queue<int>q;
    q.push(s);
    while (!q.empty())
    {
        int u=q.front();
        q.pop();
        vis[u]=0;
        o[u]++;
        if (o[u]>n) return -1;
        for (int i=head[u];i!=-1;i=e[i].next)
        {
            int temp=dist[u]+e[i].w;
            if (temp< dist[e[i].to])
            {
                dist[e[i].to]=temp;
                if (!vis[e[i].to])
                {
                    vis[e[i].to]=1;
                    q.push(e[i].to);
                }
            }
        }
    }
    return dist[t];
}

int main()
{
    int t,n,d,kase=0;
    scanf("%d",&t);
    while (t--)
    {
    memset(head,-1,sizeof(head));
    scanf("%d%d",&n,&d);
    id=0;
    for (int i=1;i<=n;i++)
    {
        scanf("%d",&arr[i].high);
        arr[i].no=i;
        if (i!=n) add(i+1,i,-1);
    }
    
    sort(arr+1,arr+n+1,cmp);
    for (int i=1;i<n;i++)
    {
        int u=arr[i].no;
        int v=arr[i+1].no;
        if (u>v) swap(u,v);
        add(u,v,d);
    }
    int u=arr[1].no;
    int v=arr[n].no;
    if (u>v) swap(u,v);
    printf("Case %d: %d\n",++kase,spfa(u,v,n));
    }
    return 0;
}
0 0