Wow! Such Conquering!Time Limit: 15000/8000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2683 Accepted Submission(s): 815 Problem Description There are n Doge Planets in the Doge Space. The conqueror of Doge Space is Super Doge, who is going to inspect his Doge Army on all Doge Planets. The inspection starts from Doge Planet 1 where DOS (Doge Olympic Statue) was built. It takes Super Doge exactly Txy time to travel from Doge Planet x to Doge Planet y.
Input There are multiple test cases. Please process till EOF.
Output If some Deadlines can not be fulfilled, please output “-1” (which means the Super Doge will say “WOW! So Slow! Such delay! Much Anger! . . . ” , but you do not need to output it), else output the minimum sum of all arrival time to each Doge Planet.
Sample Input 4 0 3 8 6 4 0 7 4 7 5 0 2 6 9 3 0 30 8 30 4 0 2 3 3 2 0 3 3 2 3 0 3 2 3 3 0 2 3 3
Sample Output 36 -1 Hint Explanation: In case #1: The Super Doge travels to Doge Planet 2 at the time of 8 and to Doge Planet 3 at the time of 12, then to Doge Planet 4 at the time of 16. The minimum sum of all arrival time is 36.
Source
Recommend liuyiding |
借鉴:https://blog.csdn.net/tobewhatyouwanttobe/article/details/37575983
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
int n,m,ans,tot,len;
int dist[35][35],time[35],R[35],L[35];
void floyd()
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
}
}
}
}
void dfs(int u,int cost,int sum,int num) //深搜就是暴力枚举,毕竟只有30个点,所以暴力下也是可以。
{ //额,毕竟是暴力枚举,就不分什么最优,不最优了,直接枚举所有就行了
for(int i=R[0];i!=0;i=R[i]) //R,L是全局变量。深搜下来的话,有些是被删除了的
{
if(cost+dist[u][i]>time[i])
return; //额,直接全部判是否超期限,有一个不行,就不用这种方法,这样的确可以省许多时间
} //这算是普通的条件剪枝吧。
if(sum>=ans) //A*剪枝。
//对结果的估值
return;
R[L[u]]=R[u];L[R[u]]=L[u]; //删除u,
if(R[0]==0) //当所有点都试过
{
ans=min(ans,sum);
R[L[u]]=L[R[u]]=u;
return ;
}
for(int i=R[0];i!=0;i=R[i])
{
dfs(i,cost+dist[u][i],sum+dist[u][i]*num,num-1); //深搜呈现了一种递进性。
} //sum+dist[u][i]*num是预测出来的最优解。
R[L[u]]=L[R[u]]=u; //枚举回溯吧
return;
}
int main()
{
int i,j;
while(~scanf("%d",&n))
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&dist[i][j]);
}
}
for(i=2;i<=n;i++)
{
scanf("%d",&time[i]);
}
floyd();
for(i=0;i<=n;i++) //双向链表的建立
{
R[i]=i+1; L[i]=i-1;
}
R[n]=0; L[0]=n;
ans=INF;
dfs(1,0,0,n-1); //num一开始从n-1开始的,好吧
if(ans==INF)
ans=-1;
printf("%d\n",ans);
}
}