A brief talk on "algorithm micro-interpretation" 01 Fractional planning

Source: Internet
Author: User

Tags: ini john img up and down solution People PAC XPL Arm

Elementary Introduction to 01 fractional planning

The so-called 01 score plan, see this name, may think of 01 backpack, actually grow similar.
This algorithm is required to "cost-effective" the highest solution. Sum (v)/sum (W) the highest solution.

Defined

We give two arrays, A[i] indicates the benefit of selecting I, B[i] indicates the cost of selecting I. If I is selected, define x[i]=1 otherwise x[i]=0. There are only two options for each item, and one option is to make R=sigma (A[i]x[i)/sigma (B[i]x[i), which means the total gain/total cost of the selected item is maximum or minimum.

01 The problem of fractional planning mainly includes the following questions:

    • General 01 Score Planning
    • Optimal ratio spanning tree
    • Optimal ratio ring
About the key to 01 score planning

F (L) =sigma (A[i]x[i])-LSigma (B[i]x[i])
F (L) =sigma (A[i]
x[i]-lb[i]a[i])
F (L) =sigma ((a[i]-lb[i])X[i])

We define A[I]-L*B[I] as d[i], so that our formula becomes the following formula.

F (L) =sigma (D[i]*x[i])

So we turn this tedious calculation into a very graceful formula.
The 01 fractional plan is an F (l) that enumerates the maximum or minimum values of L.
In the process of implementing the program, we use a very familiar old friend, asking for maximum or minimum, so?? We're going to use two points .

about why 01 score planning can't be greedy?

(personal view)
If hard to greedy, then it is only possible to calculate the price of each item, in order to find the largest or least cost-effective, in addition to calculate the answer.

One, 01 fractional planning algorithm

First set the value array A[i] and the cost array b[i], our answer is R.
\[r= \frac{\sum_{i=1}^{n}{a[i]*x[i]}}{\sum_{i=1}^{n}{b[i]*x[i]}}\]
In short, \[R=\frac{\sum{valuei}}{\sum{weighti}} \]
We can see that the size of R is related to the total value of the upper and lower.

Second, greedy algorithm

We look at the greedy algorithm, first calculate the price/performance of each item
\[Xi=\frac {valuei}{weighti}\]
Then the greedy answer is
\[R=\sum{xi}\]

Comparison

We can easily find that the 01 score plan and the greedy get the answer have obvious difference, one is total value/total cost, and greed heart is only a single value/single cost accumulation, not just the ratio of the size, and depends on the denominator and the size of the molecule, so these two things are not equal

Examples First, poj-2976dropping testsdescription

In a certain course, you take n tests. If you get the AI out of the bi questions correct on test I, your cumulative average are defined to be

\[100*\frac{\sum_{i=1}^{n}{ai}}{\sum_{i=1}^{n}{ai}}\]

Given your test scores and a positive integer k, determine how high can make your cumulative average if you are Allowe D to drop any k of your test scores.

Suppose 3 tests with scores of 5/5, 0/1, and 2/6. Without dropping any tests, your cumulative average are. However, if you drop the third test, your cumulative average becomes.
Input

    • The input test file would contain multiple test cases, each containing exactly three lines. The first line contains integers, 1≤n≤1000 and 0≤k < n. The second line contains n integers indicating ai for all I. The third line contains n positive integers indicating bi for all I. It is guaranteed that 0≤ai≤bi≤1, 000, 000, 000. The End-of-file is marked by a test case with n = k = 0 and should isn't be processed.
      Output
    • For each test case, write a single line with the highest cumulative average possible after dropping K of the given test SC Ores. The average should is rounded to the nearest integer.
      Sample Input

3 1
5 0 2
5 1 6
5 S
1 2 7 9
5 6 7 9
0 0
Sample Output

    • 83
      100
      Analysis

    • 01 Score Planning The entry question, we will carefully explain.
      First we need to understand the meaning of the title, the effect is: give you a value a[i] and the price b[i], then we elect n-k items, so that the total value/Total cost.
      After understanding the topic, we are going to use the 01 score plan for today's study.
      \[R=\frac{\sum{ai*xi}}{\sum{bi*xi}}\]
      Let's take a variant of this equation:
      \[f (l) =\sum{ai*xi}-l*\sum{bi*xi}\]
      The following analysis has been done on how to move an item:
      \[f (L) =\sum{(AI-L*BI) *xi}\]
      According to this equation, because A[i] and b[i] are known, so we put $ ai-lbi\ (this equation is defined as \) di $
      So the original long and smelly formula can become $f (l) =\sum di
      XI $
      So only \ (l\) is unknown in our calculation, we only need to use two points to enumerate \ (l\) in the calculation of \ (F (l) \) on it.
Code
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include < queue> #include <cctype> #include <cmath> #include <time.h> #include <map> #include <set > #include <vector>using namespace std; #define MS (b) memset (A,b,sizeof (a)) typedef long Long Ll;const double    Eps=1e-7;int n,k;double a[1010],b[1010],d[1010];inline int read () {int x=0,w=0; char ch=0;    while (!isdigit (ch)) {w|=ch== '-'; Ch=getchar ();}    while (IsDigit (CH)) x= (x<<3) + (x<<1) + (ch^48), Ch=getchar (); return w?-x:x;}        int main () {while (1) {N=read (), K=read ();        if (n==0 && k==0) break;        for (int i=1;i<=n;i++) scanf ("%lf", &a[i]);        for (int i=1;i<=n;i++) scanf ("%lf", &b[i]);        Double L=0.0,r=1.0,mid;            while (r-l>eps) {mid= (l+r)/2;            for (int i=1;i<=n;i++) d[i]=a[i]-mid*b[i];            Sort (d+1,d+1+n);            Double sum=0.0; For (int i=k+1;i<=n;i++) sum+=d[i];            if (sum>0) L=mid;        else R=mid;    } printf ("%.0f\n", mid*100); } return 0;}
Second, 51nod knapsack problem v3description

The volume of n items is w1,w2 ... Wn (WI is an integer), corresponding to the value of P1,P2 ... Pn (pi is an integer) from which K-items (k <= N) are selected, making the unit volume value the most.
Input

    • Line 1th: Includes 2 numbers n, K (1 <= k <= N <= 50000)
      Section 2-n + 1 lines: 2 numbers per line WI, Pi (1 <= wi, pi <= 50000)
      Output
    • The value of the output unit volume (expressed as a fraction of the numerator).
      Sample Input

3 2
2 2
5 3
2 1
Sample Output

    • 3/4
      Analysis

    • The entry question, after we figure out the answer, a gcd is good.
      Code
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include < queue> #include <cctype> #include <cmath> #include <time.h> #include <map> #include <set  > #include <vector>using namespace std; #define MS (A, b) memset (A,b,sizeof (a)) typedef long LONG ll;const int MAXN = 50005;const double eps = 1e-9;ll gcd (ll X,ll y) {return y?gcd (y,x%y): x;}    struct node{int w,p;    Double Val;    BOOL operator < (const node& T) const{return val>t.val;    }}B[MAXN];d ouble mid;ll anss,ansx,tmps,tmpx;int n,k;bool Check () {int tot=0;    for (int i=0;i<n;i++) b[i].val = 1.0*b[i].p-b[i].w*mid;    Sort (b,b+n);    Double sum=0;    tmps=0,tmpx=0;     for (int i=0;i<k;i++) SUM+=B[I].VAL,TMPS+=B[I].P,TMPX+=B[I].W;    if (sum-0>=eps) return true; return false;}    int main () {scanf ("%d%d", &n,&k);    for (int i=0;i<n;i++) scanf ("%d%d", &AMP;B[I].W,&AMP;B[I].P);    Double l=0,r=500000; for (int i=0;i<100;i++) {mid= (l+r)/2;        if (check ()) l=mid,anss=tmps,ansx=tmpx;    else R=mid;    } ll TMP=GCD (ANSS,ANSX);    anss/=tmp,ansx/=tmp;    printf ("%lld/%lld\n", ANSS,ANSX); return 0;}
Third, Poj-2728desert kingdescription

David The great has just become the king of a desert country. To win the respect of his people, he decided to build channels all over his country to bring water to every village. Villages which is connected to he capital village would be watered. As the dominate ruler and the symbol of wisdom in the country, he needs to build the channels in a most elegant the.

After days of study, he-finally figured his plan out. He wanted the average cost of each mile of the channels to be minimized. In other words, the ratio of the overall cost of the channels to the total length must be minimized. He just needs to build the necessary channels to bring water to all the villages, which means there would be is only one T O Connect each village to the capital.

His engineers surveyed the country and recorded the position and altitude of each village. All the channels must go straight between, villages and be built horizontally. Since Every, villages is at different altitudes, they concluded, each channel between, villages needed a vertic Al Water lifter, which can lift water up or let water flow down. The length of the channel is the horizontal distance between the villages. The cost of the channel is the height of the lifter. You should notice the village is at a different altitude, and different channels can ' t share a lifter. Channels can intersect safely and no three villages is on the same line.

As King David's prime scientist and programmer, you're asked to find out the best solution to build the channels.
Input

    • There is several test cases. Each test case starts with a line containing a number N (2 <= N <=), which is the number of villages. Each of the following N lines contains three integers, x, y and z (0 <= x, y < 10000, 0 <= Z < 10000000). (x, y) is the position of the village and Z are the altitude. The first village is the capital. A test Case with N = 0 ends the input, and should not being processed.
      Output
    • For each test case, output one line containing a decimal number, which are the minimum ratio of overall cost of the channel s to the total length. This number should is rounded three digits after the decimal point.
      Sample Input

4
0 0 0
0 1 1
1 1 2
1 0 3
0
Sample Output

    • 1.000
      Analysis

    • The main idea: given a picture, each edge has a profit value and a cost value, to find a spanning tree, require the least cost/benefit, output this value
      Analysis: Now the limitations are a little more complicated, requiring the solution to be a spanning tree. and the cost/benefit of this topic is minimal, of course, you want to gain/spend the most and the reverse is also possible, pay attention to processing costs of 0 of the situation. If the least, the processing method is also similar to the first D, and then do a minimum spanning tree, it is obvious that the function value.
      Code
Iv. poj-3621sightseeing cowsdescription

Farmer John had decided to reward he cows for their hard work by taking them on a tour of the big city! The cows must decide how best to spend their free time.

Fortunately, they has a detailed city map showing the L (2≤l≤1000) Major landmarks (conveniently numbered 1.. L) and the P (2≤p≤5000) unidirectional cow paths that join them. Farmer John would drive the cows to a starting landmark of their choice, from which they would walk along the cow paths to a Series of other landmarks, ending back at their starting landmark where Farmer John would pick them up and take them back to the farm. Because space in the city was at a premium, the cow paths was very narrow and so travel along each cow path was only allowed In one fixed direction.

While the cows is spend as much time as they like in the city, they does tend to get bored easily. Visiting each new landmark are fun, but walking between them takes time. The cows know the exact fun values Fi (1≤fi≤1000) for each landmark I.

The cows also know about the cowpaths. Cowpath I connects landmark l1i to L2i (in the direction l1i-l2i) and requires time Ti (1≤ti≤1000) to traverse.

In order to has the best possible day off, the cows want to maximize the average fun value per unit time of their trips. Of course, the landmarks is only fun the first time they is visited; The cows may pass through the landmark more than once, but they does not perceive its fun value again. Furthermore, Farmer John is making the cows visit at least-landmarks, so-they get some exercise during their day Off.

Help the cows find the maximum fun value per unit time that they can achieve.
Input

    • Line 1:two space-separated integers:l and P
    • Lines 2..l+1:line i+1 contains a single one Integer:fi
    • Lines l+2..l+p+1:line l+i+1 describes cow path I with three space-separated integers:l1i, L2i, and Ti
      Output
    • Line 1: A single number given to both decimal places (do not perform explicit rounding), the maximum possible average fun p Er unit time, or 0 if the cows cannot plan any of the accordance with the above rules.
      Sample Input

5 7
30
10
10
5
10
1 2 3
2 3 2
3 4 5
3 5 2
4 5 5
5 1 3
5 2 2
Sample Output

    • 6.00
      Analysis

    • The main idea: given a picture, the edge of the cost, point on the revenue, points can be repeated, but the benefits do not stack, the side can also be repeated, but the cost overlay. Find a loop that makes the yield and/or cost and maximum, output this ratio.
      Analysis: More disgusting than the above. The question of not saying the ring first, is that the cost and income are not in one place also make the egg ache. There are several transformations and conclusions that need to be used.
      One of the first conclusions is that there is no problem with the ring ring, that the optimal scheme must be a separate ring, rather than a large ring with a small ring form. This proof is actually very simple, we can think about it (hint, the big ring on the proceeds and recorded as X1, the cost of Y1, small ring on the x2,y2. The cost of the overlapping portion is s. Expressed as a category discussion). With this conclusion, we will be able to transfer the costs and benefits to the side, because the answer must eventually be a ring, so we set the income of each side as the return of its end, so that all the costs and benefits of a ring can be correctly counted.
      After solving the problem of egg pain, is 01 fractional planning part, we only need to calculate the D array to find whether there is a positive weight ring can, but this is not very good, not familiar with the problem, the D array is all reversed, the problem is converted to find there is no negative weight ring, with SPFA or Bellman_ Ford can.
Code
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <    Cmath> #define N 100010using namespace std;const double eps=1e-5;struct edge{int v,nxt,w; Double C;} E[n<<1];int Head[n],f[n];bool Vis[n];d ouble dis[n];int n,m,mct,u,v,w;inline int read () {int X=0,f=1;char C=getcha    R (); while (c> ' 9 ' | |    c< ' 0 ') {if (c== '-') F=-1;c=getchar ();}    while (c>= ' 0 ' &&c<= ' 9 ') {x=x*10+c-' 0 '; C=getchar ();} return x*f;} void Add (int u,int v,int W) {e[++mct].v=v;e[mct].nxt=head[u];e[mct].w=w;head[u]=mct;}    BOOL SPFA (int u) {vis[u]=1;        for (int i=head[u]; i; i=e[i].nxt) {int v=e[i].v;            if (dis[v]>dis[u]+e[i].c) {dis[v]=dis[u]+e[i].c;                if (Vis[v] | | SPFA (v)) {vis[v]=0;            return 1; }}}vis[u]=0;return 0;}    void judge (Double R) {for (int i=1; i<=mct; i++) e[i].c= (double) e[i].w*r-f[e[i].v]; return;} BOOL Check ({for (int i=1; i<=n; i++) if (SPFA (i)) return 1; return 0;}    int main () {n=read (); M=read ();    for (int i=1; i<=n; i++) F[i]=read ();        for (int i=1; i<=m; i++) {u=read (); V=read (); W=read ();    Add (U,V,W);    } double L=0,r=100000,ans;        while (r-l>eps) {double mid= (l+r)/2;        Judge (mid);        if (check ()) {ans=mid;l=mid;    } else R=mid;    } printf ("%.2f\n", ans); return 0;}

"Algorithm micro-interpretation" on 01 fractional planning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: