标签:stdin hit 选中 its script 标记 break str with
3 2 30 20 10 0 6 2 6 0 3 2 3 0 2 2 1 1 0 2 2 0 0 0
1 3 1 2
最后从1到n扫描ans数组就可以保证答案是升序。
參考代码:
#include<stack>
#include<queue>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma commment(linker,"/STACK: 102400000 102400000")
using namespace std;
const double eps=1e-6;
const int INF=0x3f3f3f3f;
const int MAXN=20;
int n,m,mincost[MAXN],node[MAXN],edge[MAXN][MAXN];
bool vis[MAXN],used[MAXN],ans[MAXN];
double temp;
double prim()
{
memset(mincost,0,sizeof(mincost));
memset(used,false,sizeof(used));
int s;
for(int i=1; i<=n; i++)
if(vis[i])
{
s=i;
break;
}
for(int i=1; i<=n; i++)
{
mincost[i]=edge[s][i];
used[i]=false;
}
used[s]=true;
int res=0;
int nodevalue=node[s];
for(int j=1; j<n; j++)
{
int v=-1;
for(int i=1; i<=n; i++)
if(vis[i]&&!used[i]&&(v==-1||mincost[v]>mincost[i]))//vis[i]表示第i个点有没有被选中
v=i;
res+=mincost[v];
nodevalue+=node[v];
used[v]=true;
for(int i=1; i<=n; i++)
if(vis[i]&&!used[i]&&mincost[i]>edge[v][i])
mincost[i]=edge[v][i];
}
return (res+0.0)/nodevalue;
}
void dfs(int pos,int num)
{
if(num>m)
return ;
if(pos==n+1)
{
if(num!=m)
return ;
double tans=prim();
if(tans<temp)
{
temp=tans;
memcpy(ans,vis,sizeof(ans));
}
return ;
}
vis[pos]=true;//选择当前点
dfs(pos+1,num+1);
vis[pos]=false;//不选择当前点,消除标记
dfs(pos+1,num);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif // ONLINE_JUDGE
while(scanf("%d%d",&n,&m))
{
if(n==0&&m==0)
break;
for(int i=1; i<=n; i++)
scanf("%d",&node[i]);
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
scanf("%d",&edge[i][j]);
temp=INF;
dfs(1,0);
bool flag=false;
for(int i=1; i<=n; i++)
{
if(ans[i])
{
if(flag)
printf(" ");
else
flag=true;
printf("%d",i);
}
}
printf("\n");
}
return 0;
}HDU 2489 Minimal Ratio Tree(prim+DFS)
标签:stdin hit 选中 its script 标记 break str with
原文地址:http://www.cnblogs.com/zhchoutai/p/7084603.html