【杭电oj】1789 - Doing Homework again(贪心,并查集)

Doing Homework again

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10545    Accepted Submission(s): 6179


Problem Description
Ignatius has just come back school from the 30th ACM/ICPC. Now he has a lot of homework to do. Every teacher gives him a deadline of handing in the homework. If Ignatius hands in the homework after the deadline, the teacher will reduce his score of the final test. And now we assume that doing everyone homework always takes one day. So Ignatius wants you to help him to arrange the order of doing homework to minimize the reduced score.
 

Input
The input contains several test cases. The first line of the input is a single integer T that is the number of test cases. T test cases follow.
Each test case start with a positive integer N(1<=N<=1000) which indicate the number of homework.. Then 2 lines follow. The first line contains N integers that indicate the deadlines of the subjects, and the next line contains N integers that indicate the reduced scores.
 

Output
For each test case, you should output the smallest total reduced score, one line per test case.
 

Sample Input
   
   
   
   
3 3 3 3 3 10 5 1 3 1 3 1 6 2 3 7 1 4 6 4 2 4 3 3 2 1 7 6 5 4
 

Sample Output
   
   
   
   
0 3 5
 

Author
lcy
 

Source
2007省赛集训队练习赛(10)_以此感谢DOOMIII


思路同 http://blog.csdn.net/wyg1997/article/details/50612126 的思路,其分数就是其价值,应该优先考虑高价值的,并查集在这里表示其最近能安排的天数(感觉这个find函数很好,只是时间长容易忘)。

代码如下:

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
struct node
{
	int day,g;
}data[1011];

bool cmp(node a,node b)
{
	return a.g > b.g;
}

int f[1011];		//根表示最近空闲的天

int find (int x)
{
	if (f[x] == -1)		//若当前时间没标记,则当前空闲
		return x;
	else
	{
		f[x] = find (f[x]);		//路径压缩 
		return f[x];
	}
}
int main()
{
	int u;
	int n;
	int ans,sum;
	scanf ("%d",&u);
	while (u--)
	{
		scanf ("%d",&n);
		ans = sum = 0;
		memset (f,-1,sizeof (f));
		for (int i = 1 ; i <= n ; i++)
			scanf ("%d",&data[i].day);
		for (int i = 1 ; i <= n ; i++)
		{
			scanf ("%d",&data[i].g);
			sum += data[i].g;
		}
		sort (data + 1,data + 1 + n,cmp);
		for (int i = 1 ; i <= n ; i++)
		{
			int t = find (data[i].day);
			if (t > 0)		//表示之前还有时间安排
			{
				ans += data[i].g;
				f[t] = t - 1;		//时间往前推移一天 
			}
		}
		ans = sum - ans;
		printf ("%d\n",ans);
	}
	return 0;
}


你可能感兴趣的:(【杭电oj】1789 - Doing Homework again(贪心,并查集))