关闭

1034. Head of a Gang (30)

116人阅读 评论(0) 收藏 举报
分类:

顺序查找一次的话测试点4出错,Gang中有新加入的成员就要再搜索一遍。

代码如下。还可以用并查集的思想,代码就不写了。

#define  _CRT_SECURE_NO_WARNINGS 

#include<string>
#include<string.h>
#include<vector>
#include<map>
#include<stack>
#include<iostream> 
#include<algorithm>
#include<stdio.h> 
using namespace std;
/*
8 70
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10
*/
struct InPut
{
char name1[4], name2[4];
int Time;
};
struct OutPut
{
char name[4];
int num;
};
struct Member
{
char name[4];
int weight;
};
bool CheckName(vector < Member > &Gang, char *name1, char *name2, int iTime)
{
bool bFind1 = false, bFind2 = false;
vector<Member>::iterator it1 = Gang.begin();
vector<Member>::iterator it2 = Gang.begin();
for (; it1 != Gang.end(); it1++)
{
if (strcmp(name1, it1->name) == 0)
{
bFind1 = true;
break;
}
}
for (; it2 != Gang.end(); it2++)
{
if (strcmp(name2, it2->name) == 0)
{
bFind2 = true;
break;
}
}
if (bFind1&&bFind2)
{
it1->weight += iTime;
it2->weight += iTime;
return true;
}
else if (!bFind1&&bFind2)
{
it2->weight += iTime;
Member mTmp;
strcpy(mTmp.name, name1);
mTmp.weight = iTime;
Gang.push_back(mTmp);
return true;
}
else if (bFind1&&!bFind2)
{
it1->weight += iTime;
Member mTmp;
strcpy(mTmp.name, name2);
mTmp.weight = iTime;
Gang.push_back(mTmp);
return true;
}
return false;
}
bool cmp_mem(Member a,Member c)
{
return a.weight > c.weight;
}
bool cmp_out(OutPut a, OutPut c)
{
return strcmp(a.name, c.name) < 0;
}
bool cmp_name(InPut a, InPut c)
{
return strcmp(a.name1, c.name1) < 0;
}
int main()
{
vector<OutPut> out; 
int out_num = 0;
int N, K;
cin >> N >> K;
vector <InPut> input;
for (int i = 0; i < N; i++)
{
InPut tmp;
scanf("%s %s %d",tmp.name1,tmp.name2,&tmp.Time);
input.push_back(tmp);

sort(input.begin(), input.end(), cmp_name);
while (input.size()>0)
{
int tmp_k = 0;
vector < Member > Gang;
vector<InPut>::iterator it = input.begin();  
tmp_k += it->Time;
Member a, b;
strcpy(a.name, it->name1); strcpy(b.name, it->name2);
a.weight = it->Time; b.weight = it->Time;
Gang.push_back(a); Gang.push_back(b);


it=input.erase(it);
bool chk = false;
do
{
chk = false;
while (it != input.end())
{
//it中的name在Gang中是否出现过
if (CheckName(Gang, it->name1, it->name2, it->Time))
{
chk = true;
tmp_k += it->Time;
//删除这个relation
it = input.erase(it);
}
else
{
it++;
}
}
it = input.begin();
} while (chk);

if (Gang.size() <= 2 || tmp_k<=K)
continue;
sort(Gang.begin(),Gang.end(),cmp_mem);
OutPut out_tmp;
strcpy(out_tmp.name, Gang.begin()->name);
out_tmp.num = Gang.size();
out.push_back(out_tmp);
}
sort(out.begin(),out.end(),cmp_out);
cout << out.size() << endl;
for (int i = 0; i < out.size(); i++)
cout << out[i].name << " " << out[i].num<<endl;
return 0;
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13437次
    • 积分:881
    • 等级:
    • 排名:千里之外
    • 原创:78篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类