学生选择问题(回溯)-算法设计与分析

//
//  main.cpp
//  yybhjbl
//
//  Created by liuzhe on 17/10/21.
//  Copyright © 2017年 liuzhe. All rights reserved.
//

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <string.h>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <list>
#include <bitset>
#include <stack>
#include <stdlib.h>
#define lowbit(x) (x&-x)
#define e exp(1.0)
#define eps 1e-8
//ios::sync_with_stdio(false);
//    auto start = clock();
//    cout << (clock()-start)/(double)CLOCKS_PER_SEC<<endl;
typedef long long ll;
typedef long long LL;
using namespace std;
typedef unsigned long long ull;

const int maxn=100;
const int inf=1000000;
int n,m,t1,t2;
struct node
{
    int grade,sex;
}data[maxn];
double ans,now,ave;
vector<int>vec,best;
double get_ans()
{
    double sum=0;
    for(int i=0;i<vec.size();i++) sum+=data[vec[i]].grade;
    ave=sum/m;
    double a=0;
    for(int i=0;i<m;i++)
        a+=(data[vec[i]].grade-ave)*(data[vec[i]].grade-ave);
    return a/m;
}
void backtrack(int i)
{
    if(i>n) return ;
    if(vec.size()==m)
    {
        if(t1==t2)
        {
            double a=get_ans();
            if(ave>80)
            {
                if(ans>a)
                {
                    ans=a;
                    best.clear();
                    for(int i=0;i<m;i++)best.push_back(vec[i]);
                }
            }
        }
    }
    if(vec.size()<m)
    {
        vec.push_back(i);
        if(data[i].sex) t2++;
        else t1++;
        backtrack(i+1);
        if(data[i].sex) t2--;
        else t1--;
        vec.pop_back();
    }
    backtrack(i+1);
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>data[i].grade>>data[i].sex;
    ans=inf;
    vec.clear();
    backtrack(1);
    cout<<ans<<endl;
    for(int i=0;i<best.size();i++)cout<<best[i]<<' ';
    cout<<endl;
    return 0;
}
/*
Input:
5 4
86 0
79 1
82 0
81 1
74 1
Output:
6.25
1 2 4 5
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值